repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
luxor37/cookbook-vercel
|
src/pages/index.tsx
|
<filename>src/pages/index.tsx
import RecipeList from "@/components/modules/reicpe-list";
import LinkButton from "@/components/shared/link-button";
import Page from "@/components/shared/page";
import RecipeCard from "@/components/shared/recipe-card";
import Row from "@/components/shared/row";
import TextInput from "@/components/shared/text-input";
import { getFilteredRecipe } from "lib/api";
import { useTranslation } from "next-i18next";
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import React, { useEffect, useState } from "react";
export default function Homepage({ locale }) {
const [search, setSearch] = useState("")
const [recipes, setRecipes] = useState([])
const { t } = useTranslation('common');
useEffect(() => {
console.log(locale)
if (search && search.length >= 0 && (search.replace(' ', '')).length != 0) {
const fetchData = async () => {
const response = await getFilteredRecipe(search, locale)
setRecipes(response)
};
fetchData()
}
else if(search.length == 0){
setRecipes([])
}
}, [search, setSearch])
return (
<Page>
<div className="rounded-lg shadow-md md:m-5 m-2 p-3">
<Row>
<TextInput
className=" w-full"
value={search}
onChange={setSearch}
name="search"
placeholder={t('Search') + "..."}
/>
</Row>
<div >
<Row>
<h5>
{t('Quick access')} :
</h5>
<div className="sm:block hidden">
<LinkButton className="ml-5 mr-5" href="/appetizers" text={t('Appetizers')} />
<LinkButton className="mr-5" href="/maindishes" text={t('Main Dishes')} />
<LinkButton className="mr-5" href="/desserts" text={t('Desserts')} />
<LinkButton className="mr-5" href="/drinks" text={t('Drinks')} />
<LinkButton className="mr-5" href="/others" text={t('Others')} />
</div>
</Row>
<Row className="sm:hidden block">
<ol>
<li><LinkButton className=" my-2" href="/appetizers" text={t('Appetizers')} /></li>
<li><LinkButton className=" my-2" href="/maindishes" text={t('Main Dishes')} /></li>
<li><LinkButton className=" my-2" href="/desserts" text={t('Desserts')} /></li>
<li><LinkButton className=" my-2" href="/drinks" text={t('Drinks')} /></li>
<li><LinkButton className=" my-2" href="/others" text={t('Others')} /></li>
</ol>
</Row>
</div>
</div>
{!recipes || recipes.length == 0? (<h1 className="text-center">{t("No results")}</h1>) :
(<RecipeList recipes={recipes} />)}
</Page>
)
}
export async function getStaticProps({ locale }) {
return {
props: {
locale,
...await serverSideTranslations(locale, ['common']),
},
revalidate: 5
}
}
|
luxor37/cookbook-vercel
|
src/pages/others/index.tsx
|
<reponame>luxor37/cookbook-vercel
import Page from "@/components/shared/page";
import { serverSideTranslations } from 'next-i18next/serverSideTranslations';
import React from "react";
import { getCardByCategory } from 'lib/api'
import RecipeList from "@/components/modules/reicpe-list";
export default function Others(props) {
return (
<Page>
<RecipeList recipes={props.recipes} />
</Page>
)
}
export async function getStaticProps({ locale }) {
return {
props: {
recipes: await getCardByCategory("other", locale),
locale,
...await serverSideTranslations(locale, ['common']),
},
revalidate: 5,
}
}
|
luxor37/cookbook-vercel
|
src/@components/modules/preparation/index.tsx
|
<reponame>luxor37/cookbook-vercel<gh_stars>0
import client from "lib/sanity";
import { useTranslation } from "next-i18next";
import { translate } from "../../shared/lang";
import Nullable from "../../shared/undefinable"
import BlockContent from '@sanity/block-content-to-react'
export default function Preparation({ instructions }) {
const { t } = useTranslation('common');
const list = (props) => {
return <ol className="list-decimal">{props.children}</ol>
}
return (
<>
<h3 className="pb-3">
{t('Preparation')} :
</h3>
<div className="flex flex-row ">
<Nullable obj={instructions}>
<BlockContent
blocks={translate(instructions)}
serializers={{ list: list }}
renderContainerOnSingleChild={true}
{...client.config()}
/>
</Nullable>
</div>
</>
)
}
|
luxor37/cookbook-vercel
|
src/@components/shared/sanityImage/index.tsx
|
import imageUrlBuilder from '@sanity/image-url'
import client from 'lib/sanity'
export default function SanityImage({ picture, className="" }) {
function urlFor(source) {
return imageUrlBuilder(client).image(source)
}
return (
<>
<img className={className} src={urlFor(picture) + ""} />
</>
)
}
|
luxor37/cookbook-vercel
|
src/@components/shared/row/index.tsx
|
<reponame>luxor37/cookbook-vercel
export default function Row({ noDefaultMargins = false, children, className = "" }) {
var margins = noDefaultMargins ? `` : `my-2`;
return (
<div className={`flex flex-row flex-wrap w-full ${margins} ${className}`}>
{children}
</div>
)
}
|
luxor37/cookbook-vercel
|
src/@components/shared/nav/index.tsx
|
import NavButton from "./nav-button";
import NavButtonMobile from "./nav-button-mobile";
import NavButtonLang from "./nav-button-lang";
import { useTranslation } from 'next-i18next';
export const Navbar = () => {
const { t } = useTranslation('common');
return (
<nav className='md:text-center md:flex-col md:w-full top-0 left-0 right-0 flex z-10 bg-primary flex-wrap items-center content-between py-4 px-4'>
<span className="flex mx-auto mt-auto mb-0 md:hidden">
<span className='text-xl text-white font-bold uppercase tracking-wide'>
<NavButton href="/" text="cookbook" />
</span>
</span>
<NavButtonMobile />
<div className="nav-items md:mb-auto md:items-start md:flex-grow-0 md:max-h-full md:flex max-h-0 box-border w-full items-center flex-grow my-auto">
<div className="md:w-full md:flex md:justify-between">
<ul className='flex flex-col md:flex-row pl-0 mb-0 list-none'>
<li className="md:mx-5 ml-auto mr-auto">
<NavButton href="/" text={t('home')} />
</li>
<li className="md:mx-5 ml-auto mr-auto">
<NavButton href="/appetizers" text={t('appetizers')} />
</li>
<li className="md:mx-5 ml-auto mr-auto">
<NavButton href="/maindishes" text={t('main dishes')} />
</li>
<li className="md:mx-5 ml-auto mr-auto">
<NavButton href="/desserts" text={t('desserts')} />
</li>
<li className="md:mx-5 ml-auto mr-auto">
<NavButton href="/drinks" text={t('drinks')} />
</li>
<li className="md:mx-5 ml-auto mr-auto">
<NavButton href="/others" text={t('others')} />
</li>
</ul>
<div className=" text-center">
<NavButtonLang />
</div>
</div>
</div>
</nav>
)
}
|
luxor37/cookbook-vercel
|
src/@components/shared/page/index.tsx
|
<gh_stars>0
import Head from "next/head";
import { Navbar } from '@/components/shared/nav'
export default function Page({ children, className = "" }) {
return (
<div className={` ${className}`}>
<Head>
<title>MyCookbook</title>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
</Head>
<Navbar />
<div className=" mt-10 xl:mx-80 ">
{children}
</div>
<footer>
</footer>
</div>
)
}
|
luxor37/cookbook-vercel
|
src/@components/modules/ingredients/index.tsx
|
<filename>src/@components/modules/ingredients/index.tsx
import { useTranslation } from "next-i18next";
import Lang from "../../shared/lang";
export default function Ingredients({ ingredients }) {
const { t } = useTranslation('common');
if (!ingredients) {
return <></>
}
else {
return (
<>
<h3 className="pb-3">
{t('Ingredients')} :
</h3><div className="flex flex-row ">
<table>
<tbody>
{ingredients.map(
({ name, quantity, unit }) => {
const bullet = quantity == " " || !quantity ? " " : " :"
return (
<tr key={name.en} className="pb-3">
<td className=" text-right pr-3">
<Lang>{name}</Lang>{bullet}
</td>
<td>
{quantity} <Lang>{unit.name}</Lang>
</td>
</tr>
)
})
}
</tbody>
</table>
</div>
</>
)
}
}
|
luxor37/cookbook-vercel
|
src/pages/_app.tsx
|
<filename>src/pages/_app.tsx<gh_stars>0
import type { AppProps } from 'next/app'
import 'tailwindcss/tailwind.css'
import '@/styles/tailwind.css';
import '@/styles/main.scss';
import "@fortawesome/fontawesome-svg-core/styles.css";
import { config } from "@fortawesome/fontawesome-svg-core";
config.autoAddCss = false;
import { appWithTranslation } from 'next-i18next';
function MyApp({ Component, pageProps }: AppProps) {
return (
<Component {...pageProps} />
)
}
export default appWithTranslation(MyApp);
|
luxor37/cookbook-vercel
|
src/@components/shared/link-button/index.tsx
|
<filename>src/@components/shared/link-button/index.tsx<gh_stars>0
import Link from 'next/link';
export default function LinkButton({ className="", href, text }) {
return (
<Link href={href}>
<a className={`${className} opacity-75 font-extrabold uppercase hover:opacity-100 focus:opacity-100`}>
{text}
</a>
</Link>
)
}
|
luxor37/cookbook-vercel
|
src/@components/modules/reicpe-list/index.tsx
|
import RecipeCard from "@/components/shared/recipe-card";
import Row from "@/components/shared/row";
import { useTranslation } from "next-i18next";
export default function RecipeList({ recipes }) {
if (!recipes || recipes.length == 0) {
const { t } = useTranslation('common');
return <h1 className="text-center">{t('No recipes yet')}</h1>
}
else {
return (
<Row>
{recipes.map(
({ _id, title, servings, time, tags, picture, source }) => {
return (
<RecipeCard _id={_id} title={title} time={time} servings={servings}
image={picture} tags={tags} key={_id} />
)
}
)}
</Row>
)
}
}
|
luxor37/cookbook-vercel
|
src/@components/shared/lang/index.tsx
|
import { useTranslation } from 'react-i18next'
export default function Lang({ children }) {
const { i18n } = useTranslation('common');
var text = i18n.language == 'en' ? 'Translation error' : 'Erreur de traduction';
if (i18n.language == 'en' && children && children.en) {
text = children.en
}
else if (i18n.language == 'fr' && children && children.fr) {
text = children.fr
}
return (
<>
{text}
</>
)
}
export function translate(text) {
const { i18n } = useTranslation('common');
var textOutput = i18n.language == 'en' ? 'Translation error' : 'Erreur de traduction';
if (i18n.language == 'en' && text && text.en) {
textOutput = text.en
}
else if (i18n.language == 'fr' && text && text.fr) {
textOutput = text.fr
}
return textOutput;
}
|
luxor37/cookbook-vercel
|
src/@components/shared/nav/nav-button/index.tsx
|
import Link from 'next/link';
export default function NavButton({ href, text }) {
return (
<Link href={href}>
<a className="text-white opacity-75 block font-extrabold uppercase hover:opacity-100 focus:opacity-100 hover:text-white focus:text-white my-3">
{text}
</a>
</Link>
)
}
|
benkaiser/vscode-extension-auto-import
|
src/import-scanner.ts
|
import { NodeUpload } from './node-upload';
import * as FS from 'fs';
import * as vscode from 'vscode';
import * as _ from 'lodash';
import { ImportDb } from './import-db';
import { AutoImport } from './auto-import';
export class ImportScanner {
private scanStarted: Date;
private scanEnded: Date;
private showOutput: boolean;
private filesToScan: string;
private showNotifications: boolean;
private higherOrderComponents: string;
constructor(private config: vscode.WorkspaceConfiguration) {
this.filesToScan = this.config.get<string>('filesToScan');
this.showNotifications = this.config.get<boolean>('showNotifications');
this.higherOrderComponents = this.config.get<string>('higherOrderComponents');
}
public scan(request: any): Thenable<any> {
this.showOutput = request.showOutput ? request.showOutput : false;
if (this.showOutput) {
this.scanStarted = new Date();
}
return vscode.workspace
.findFiles(this.filesToScan, '**/node_modules/**', 99999)
.then((files) => this.processWorkspaceFiles(files))
.then(() =>
vscode.commands
.executeCommand('extension.scanNodeModules')
);
}
public edit(request: any): Thenable<any> {
ImportDb.delete(request);
this.loadFile(request.file, true);
return new NodeUpload(vscode.workspace.getConfiguration('autoimport')).scanNodeModules();
}
public delete(request: any): Thenable<void> {
ImportDb.delete(request);
AutoImport.setStatusBar();
return Promise.resolve();
}
private processWorkspaceFiles(files: vscode.Uri[]): Promise<void> {
let pruned = files.filter((f) => {
return f.fsPath.indexOf('typings') === -1 &&
f.fsPath.indexOf('node_modules') === -1 &&
f.fsPath.indexOf('.history') === -1 &&
f.fsPath.indexOf('jspm_packages') === -1;
});
let readPromise: Promise<any> = Promise.resolve();
pruned.forEach((f, i) => {
readPromise = readPromise.then(() => this.loadFile(f, i === (pruned.length - 1)));
});
return readPromise;
}
private loadFile(file: vscode.Uri, last: boolean): Promise<any> {
return new Promise((resolve) => {
FS.readFile(file.fsPath, 'utf8', (err, data) => {
if (err) {
resolve();
return console.log(err);
}
this.processFile(data, file);
if (last) {
AutoImport.setStatusBar();
}
if (last && this.showOutput && this.showNotifications) {
this.scanEnded = new Date();
let str = `[AutoImport] cache creation complete - (${Math.abs(<any>this.scanStarted - <any>this.scanEnded)}ms)`;
vscode.window
.showInformationMessage(str);
}
resolve();
});
});
}
private processFile(data: any, file: vscode.Uri): void {
//added code to support any other middleware that the component can be nested in.
const regExp = new RegExp(`(export\\s?(default)?\\s?(class|interface|let|var|const|function)?) ((${this.higherOrderComponents}).+[, (])?(\\w+)`, "g");
var matches = data.match(regExp);
if (matches != null) {
matches.forEach(m => {
//this allows us to reliably gets the last string (not splitting on spaces)
const mArr = regExp.exec(m);
if(mArr === null){
//this is a weird situation that shouldn't ever happen. but does?
return;
}
const workingFile: string = mArr[mArr.length - 1];
const isDefault = m.indexOf('default') !== -1;
ImportDb.saveImport(workingFile, data, file, isDefault, null);
})
}
}
}
|
fbi-templates/fbi-project-fullpack
|
src/scripts/ts.ts
|
<gh_stars>1-10
import '../styles/_base.css'
function greeter (person: string) {
return 'Hello, ' + person
}
const user = 'new User'
document.querySelector('#text').innerHTML = greeter(user)
|
rick-schultz/rick-virtual-identity-coding-challenge-built
|
types/Users/Rick Schultz/Desktop/rick-virtual-identity-coding-challenge/.stencil/testing/index.d.ts
|
export * from './component-specs';
export * from './screenshot-stories';
|
rick-schultz/rick-virtual-identity-coding-challenge-built
|
types/global.d.ts
|
<gh_stars>0
// Add your global typings here
declare module '*.md';
|
rick-schultz/rick-virtual-identity-coding-challenge-built
|
types/Users/Rick Schultz/Desktop/rick-virtual-identity-coding-challenge/.stencil/testing/screenshot-stories.d.ts
|
export declare const screenshotStories: (stories: any) => void;
|
rick-schultz/rick-virtual-identity-coding-challenge-built
|
types/Users/Rick Schultz/Desktop/rick-virtual-identity-coding-challenge/.stencil/testing/component-specs.d.ts
|
<filename>types/Users/Rick Schultz/Desktop/rick-virtual-identity-coding-challenge/.stencil/testing/component-specs.d.ts
import { ComponentInterface } from '../../../../../../stencil-public-runtime';
export declare const createSpecComponent: <T>(componentTag: string, component: ComponentInterface | ComponentInterface[], props?: Record<string, any>) => Promise<T>;
export declare const getChild: (component: HTMLElement) => HTMLElement;
export declare const getAttributes: (component: HTMLElement) => Record<string, string>;
|
rick-schultz/rick-virtual-identity-coding-challenge-built
|
types/components/example-component/example-component.stories.d.ts
|
declare const _default: {
title: string;
parameters: {
docs: {
description: {
component: any;
};
};
jest: string[];
};
};
export default _default;
export declare const empty: (content: HTMLElement) => string;
|
rick-schultz/rick-virtual-identity-coding-challenge-built
|
types/components/example-component/example-component.d.ts
|
/// <reference types="react" />
export declare class ExampleComponent {
headline: string;
contactUS: string;
private menuToggleOn;
private menuToggleOff;
render(): JSX.Element;
}
|
costaivo/chapter
|
pages/dashboard/venues/index.tsx
|
import React, { useEffect } from 'react';
import { Grid } from '@material-ui/core';
import { useSelector } from 'react-redux';
import Link from 'next/link';
import { venueActions } from 'client/store/actions';
import { AppStoreState } from 'client/store/reducers';
import VenueItem from 'client/components/Dashboard/Venues/VenueItem';
import { IVenueModal } from 'client/store/types/venues';
import useThunkDispatch from 'client/hooks/useThunkDispatch';
const Venues: React.FC = () => {
const { error, loading, venues } = useSelector((state: AppStoreState) => ({
error: state.venues.error,
loading: state.venues.loading,
venues: state.venues.venues,
}));
const dispatch = useThunkDispatch();
useEffect(() => {
dispatch(venueActions.fetchVenues());
}, []);
return (
<Grid container spacing={2}>
<Grid item xs={12}>
<Link href="/dashboard">
<a>Dashboard</a>
</Link>
<br />
<Link href="/dashboard/venues/new">
<a>Add new</a>
</Link>
{error ? (
<h1>😢Error</h1>
) : (
venues.map((venue: IVenueModal) => (
<VenueItem
venue={venue}
loading={loading}
key={`venue-${venue.id}`}
/>
))
)}
</Grid>
</Grid>
);
};
export default Venues;
|
costaivo/chapter
|
client/store/types/actions/events.ts
|
<reponame>costaivo/chapter
export const FETCH_START = 'fcc/chapter/EVENTS_START';
export const FETCH_SUCCESS = 'fcc/chapter/EVENTS_SUCCESS';
export const FETCH_SINGLE_SUCCESS = 'fcc/chapter/EVENTS_SINGLE_SUCCESS';
export const FETCH_FAIL = 'fcc/chapter/EVENTS_FAIL';
export const CREATE_START = 'fcc/chapter/EVENT_CREATE_START';
export const CREATE_SUCCESS = 'fcc/chapter/EVENT_CREATE_SUCCESS';
export const CREATE_FAIL = 'fcc/chapter/EVENT_CREATE_FAIL';
export const REMOVE_SUCCESS = 'fcc/chapter/EVENT_REMOVE_SUCCESS';
export const REMOVE_FAIL = 'fcc/chapter/EVENT_REMOVE_FAIL';
|
costaivo/chapter
|
pages/dashboard/venues/[id]/edit.tsx
|
<reponame>costaivo/chapter
import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { makeStyles } from '@material-ui/core';
import { useRouter } from 'next/router';
import { venueActions, locationActions } from 'client/store/actions';
import { AppStoreState } from 'client/store/reducers';
import { VenueForm, Skeleton } from 'client/components/Dashboard/Venues';
import sanitizeFormData from 'client/helpers/sanitizeFormData';
import useThunkDispatch from 'client/hooks/useThunkDispatch';
const useStyles = makeStyles(() => ({
responseDiv: {
margin: '15px 0',
},
}));
const EditVenue: React.FC = () => {
const router = useRouter();
const { id } = router.query;
const styles = useStyles();
const { error, loading, venue, locations, locationsLoading } = useSelector(
(state: AppStoreState) => ({
error: state.venues.error,
loading: state.venues.loading,
venue: state.venues.venues.find(
venue => venue.id === parseInt(Array.isArray(id) ? id[0] : id),
),
locations: state.locations.locations,
locationsLoading: state.locations.loading,
}),
);
const dispatch = useThunkDispatch();
useEffect(() => {
if (id !== undefined) {
dispatch(venueActions.fetchOneVenue(id));
dispatch(locationActions.fetchLocations());
}
}, [id]);
const onSubmit = async data => {
const success = await dispatch(
venueActions.updateVenue(
parseInt(Array.isArray(id) ? id[0] : id),
sanitizeFormData(data),
),
);
if (success) {
router.replace('/dashboard/venues');
}
};
if (loading || error || !venue) {
return (
<Skeleton>
<h1>{loading ? 'Loading...' : 'Error...'}</h1>
{error && <div className={styles.responseDiv}>{error}</div>}
</Skeleton>
);
}
return (
<Skeleton>
<VenueForm
loading={loading}
onSubmit={onSubmit}
locations={locations}
locationsLoading={locationsLoading}
data={venue}
submitText={'Update venue'}
/>
</Skeleton>
);
};
export default EditVenue;
|
costaivo/chapter
|
pages/dashboard/index.tsx
|
import React from 'react';
import Link from 'next/link';
import links from 'client/constants/DashboardLinks';
import { makeStyles } from '@material-ui/core';
const useStyles = makeStyles(() => ({
link: {
fontSize: '1rem',
marginRight: '1rem',
},
}));
const Dashboard: React.FC = () => {
const styles = useStyles();
return (
<div>
{links.map(item => (
<>
<Link href={item.link} key={item.text}>
<a className={styles.link}>{item.text}</a>
</Link>
</>
))}
</div>
);
};
export default Dashboard;
|
costaivo/chapter
|
client/components/Dashboard/Events/EventForm.tsx
|
<gh_stars>0
import React from 'react';
import { useForm, Controller } from 'react-hook-form';
import {
FormControl,
TextField,
Button,
makeStyles,
InputLabel,
Select,
MenuItem,
} from '@material-ui/core';
import { IVenueModal } from 'client/store/types/venues';
interface IField {
key: string;
label: string;
placeholder?: string;
type: string;
defaultValue?: string;
}
const fields: IField[] = [
{
key: 'name',
type: 'text',
label: 'Event title',
placeholder: 'Foo and the Bars',
},
{
key: 'description',
type: 'text',
label: 'Description',
placeholder: '',
},
{
key: 'capacity',
type: 'number',
label: 'Capacity',
placeholder: '50',
},
{
key: 'tags',
type: 'text',
label: 'Tags (separated by a comma)',
placeholder: 'Foo, bar',
},
{
key: 'start_at',
type: 'datetime-local',
label: 'Start at',
defaultValue: new Date().toISOString().slice(0, 16),
},
{
key: 'ends_at',
type: 'datetime-local',
label: 'End at',
defaultValue: new Date(Date.now() + 1000 * 60 * 60)
.toISOString()
.slice(0, 16),
},
];
const useStyles = makeStyles(() => ({
form: {
display: 'flex',
flexDirection: 'column',
maxWidth: '25%',
},
item: {
marginTop: '20px',
},
}));
export interface IEventFormData {
name: string;
description: string;
capacity: number;
tags: string;
venue: number;
}
interface IEventFormProps {
onSubmit: (data: IEventFormData) => void;
loading: boolean;
venues: IVenueModal[];
venuesLoading: boolean;
}
const EventForm: React.FC<IEventFormProps> = ({
onSubmit,
loading,
venues,
venuesLoading,
}) => {
const { control, handleSubmit } = useForm();
const styles = useStyles();
return (
<form onSubmit={handleSubmit(onSubmit)} className={styles.form}>
{fields.map(field => (
<FormControl className={styles.item} key={field.key}>
<Controller
control={control}
as={
<TextField
label={field.label}
type={field.type}
placeholder={field.placeholder}
/>
}
name={field.key}
defaultValue={field.defaultValue}
options={{ required: true }}
/>
</FormControl>
))}
{venuesLoading ? (
<h1>Loading venues...</h1>
) : (
<FormControl className={styles.item}>
<InputLabel id="venue-label">Venue</InputLabel>
<Controller
control={control}
as={
<Select labelId="venue-label">
{venues.map(venue => (
<MenuItem value={venue.id} key={venue.id}>
{venue.name}
</MenuItem>
))}
</Select>
}
name="venue"
options={{ required: true }}
defaultValue={0}
/>
</FormControl>
)}
<Button
className={styles.item}
variant="contained"
color="primary"
type="submit"
disabled={loading}
>
Add Event
</Button>
</form>
);
};
export default EventForm;
|
costaivo/chapter
|
pages/dashboard/events/[id]/edit.tsx
|
import React from 'react';
import { Skeleton } from 'client/components/Dashboard/Events';
const EditEvent: React.FC = () => {
return (
<Skeleton>
<h1>Edit event</h1>
</Skeleton>
);
};
export default EditEvent;
|
costaivo/chapter
|
pages/dashboard/locations/new.tsx
|
import React from 'react';
import { useSelector } from 'react-redux';
import { makeStyles } from '@material-ui/core';
import { useRouter } from 'next/router';
import { locationActions } from 'client/store/actions';
import { AppStoreState } from 'client/store/reducers';
import sanitizeFormData from 'client/helpers/sanitizeFormData';
import useThunkDispatch from 'client/hooks/useThunkDispatch';
import { LocationForm, Skeleton } from 'client/components/Dashboard/Locations';
const useStyles = makeStyles(() => ({
responseDiv: {
margin: '15px 0',
},
}));
const NewLocation: React.FC = () => {
const router = useRouter();
const styles = useStyles();
const { error, state } = useSelector((state: AppStoreState) => ({
error: state.locations.create.error,
state: state.locations.create.state,
}));
const dispatch = useThunkDispatch();
const onSubmit = async data => {
const success = await dispatch(
locationActions.create(sanitizeFormData(data)),
);
if (success) {
router.replace('/dashboard/locations');
}
};
return (
<Skeleton>
{error && <div className={styles.responseDiv}>{error}</div>}
<LocationForm
loading={state === 'loading'}
onSubmit={onSubmit}
submitText={'Add location'}
/>
</Skeleton>
);
};
export default NewLocation;
|
costaivo/chapter
|
pages/dashboard/venues/[id]/index.tsx
|
<gh_stars>0
import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { Card, Typography } from '@material-ui/core';
import { useRouter } from 'next/router';
import { venueActions } from 'client/store/actions';
import { AppStoreState } from 'client/store/reducers';
import { ProgressCardContent } from 'client/components';
import useThunkDispatch from 'client/hooks/useThunkDispatch';
import Skeleton from 'client/components/Dashboard/Venues/Skeleton';
const ShowVenue: React.FC = () => {
const router = useRouter();
const { id } = router.query;
const { error, loading, venue } = useSelector((state: AppStoreState) => ({
error: state.venues.error,
loading: state.venues.loading,
venue: state.venues.venues.find(
venue => venue.id === parseInt(Array.isArray(id) ? id[0] : id),
),
}));
const dispatch = useThunkDispatch();
useEffect(() => {
if (id !== undefined) {
dispatch(venueActions.fetchOneVenue(id));
}
}, [id]);
if (loading || error || !venue) {
return (
<Skeleton>
<h1>{loading ? 'Loading...' : 'Error...'}</h1>
</Skeleton>
);
}
return (
<Skeleton>
<Card style={{ marginTop: '12px' }} key={`event-${venue.id}`}>
<ProgressCardContent loading={loading}>
<Typography gutterBottom variant="h5" component="h2">
{venue.name}
</Typography>
{venue.location && (
<Typography variant="body2" color="textSecondary" component="p">
{`${venue.location.region}, ${venue.location.country_code}, ${venue.location.postal_code}`}
</Typography>
)}
</ProgressCardContent>
</Card>
<h3>Placeholder for venues...</h3>
</Skeleton>
);
};
export default ShowVenue;
|
costaivo/chapter
|
server/controllers/userChapterController.ts
|
<reponame>costaivo/chapter
import { Request, Response } from 'express';
import { Chapter, User } from 'server/models';
import { UserChapter } from 'server/models/UserChapter';
// The whole model is a json response, fix that if there's some sensitive data here
export default {
async join(req: Request, res: Response) {
const { chapter_id, user_id } = req.body;
const chapter = await Chapter.findOne({ id: chapter_id });
const user = await User.findOne({ id: user_id });
if (chapter && user) {
const userChapter = new UserChapter({
user,
chapter,
});
try {
await userChapter.save();
res.status(201).json(userChapter);
} catch (e) {
res.status(500).json({ error: e });
}
} else {
res.status(404).json({ error: "Can't find user or chapter. Or both." });
}
},
async ban(req: Request, res: Response) {
const { id, user_id } = req.params;
const userChapter = await UserChapter.findOne({
where: { user_id: parseInt(user_id), chapter_id: parseInt(id) },
});
if (userChapter) {
try {
await userChapter.remove();
res.status(201).json({ id, user_id });
} catch (e) {
res.json(500).json({ error: e });
}
} else {
res.status(404).json({ error: "Can't find user record for chapter" });
}
},
};
|
costaivo/chapter
|
client/store/types/events.ts
|
import { ThunkAction } from 'redux-thunk';
import { AppStoreState } from '../reducers';
import * as ACTIONS from './actions/events';
export * from './actions/events';
export interface IEventModal {
id?: number;
chapterId?: string;
name: string;
description: string;
start_at: Date;
ends_at: Date;
canceled: boolean;
capacity: number;
created_at?: string;
updated_at?: string;
}
export interface IEventStoreState {
chapterId: string;
events: IEventModal[];
loading: boolean;
error: string; // Should reflect a generic Error Type here
create: {
state: 'idle' | 'error' | 'loading';
error: string;
};
}
interface IEventFetchStartAction {
type: typeof ACTIONS.FETCH_START;
}
interface IEventFetchSuccessAction {
type: typeof ACTIONS.FETCH_SUCCESS;
payload: {
events: IEventModal[];
chapterId: string;
};
}
interface IEventFetchSingleSuccessAction {
type: typeof ACTIONS.FETCH_SINGLE_SUCCESS;
payload: {
event: IEventModal;
chapterId: string;
};
}
interface IEventFetchFailureAction {
type: typeof ACTIONS.FETCH_FAIL;
payload: string;
}
interface IEventCreateStartAction {
type: typeof ACTIONS.CREATE_START;
}
interface IEventCreateSuccessAction {
type: typeof ACTIONS.CREATE_SUCCESS;
payload: {
event: IEventModal;
};
}
interface IEventCreateFailureAction {
type: typeof ACTIONS.CREATE_FAIL;
payload: string;
}
interface IEventRemoveSuccessAction {
type: typeof ACTIONS.REMOVE_SUCCESS;
payload: {
id: number;
chapterId: number;
};
}
interface IEventRemoveFailuerAction {
type: typeof ACTIONS.REMOVE_FAIL;
payload: string;
}
export type IEventActionTypes =
| IEventFetchStartAction
| IEventFetchSuccessAction
| IEventFetchFailureAction
| IEventFetchSingleSuccessAction
| IEventCreateSuccessAction
| IEventCreateStartAction
| IEventCreateFailureAction
| IEventRemoveSuccessAction
| IEventRemoveFailuerAction;
export type ThunkResult<R> = ThunkAction<
R,
AppStoreState,
null,
IEventActionTypes
>;
|
costaivo/chapter
|
client/components/Dashboard/Events/EventItem.tsx
|
import React from 'react';
import { Card, Typography, Button } from '@material-ui/core';
import { useDispatch } from 'react-redux';
import Link from 'next/link';
import { IEventModal } from 'client/store/types/events';
import { eventActions } from 'client/store/actions';
import useConfirm from 'client/hooks/useConfirm';
import { ProgressCardContent } from 'client/components';
interface IEventItemProps {
event: IEventModal;
loading: boolean;
}
const EventItem: React.FC<IEventItemProps> = ({ event, loading }) => {
const dispatch = useDispatch();
const [confirmCancel, clickCancel] = useConfirm(() =>
dispatch(eventActions.cancelEvent(1, event.id)),
);
const [confirmRemove, clickRemove] = useConfirm(() =>
dispatch(eventActions.removeEvent(1, event.id)),
);
return (
<Card style={{ marginTop: '12px' }}>
<ProgressCardContent loading={loading}>
<Link
href="/dashboard/events/[id]"
as={`/dashboard/events/${event.id}`}
>
<a>
<Typography gutterBottom variant="h5" component="h2">
{event.name}
</Typography>
</a>
</Link>
{event.canceled && (
<Typography variant="h5" color="error">
Canceled
</Typography>
)}
<Typography variant="body2" color="textSecondary" component="p">
{event.description}
</Typography>
<Typography variant="body2" color="textSecondary" component="p">
{event.capacity}
</Typography>
{!event.canceled && (
<Button onClick={clickCancel}>
{confirmCancel ? 'Are you sure?' : 'Cancel'}
</Button>
)}
<Button onClick={clickRemove}>
{confirmRemove ? 'Are you sure?' : 'delete'}
</Button>
<Link
href={`/dashboard/events/[id]/edit`}
as={`/dashboard/events/${event.id}/edit`}
>
<a style={{ marginLeft: '10px' }}>Edit</a>
</Link>
</ProgressCardContent>
</Card>
);
};
export default EventItem;
|
costaivo/chapter
|
server/controllers/eventsController.ts
|
<gh_stars>0
import { Request, Response } from 'express';
import { Event } from 'server/models/Event';
import { PostgresErrorCodes } from 'server/util/PostgresErrorConstants';
import { Tag } from 'server/models/Tag';
import sanitizeTags from 'server/util/sanitizeTags';
// The whole model is a json response, fix that if there's some sensitive data here
export default {
async index(req: Request, res: Response) {
const { chapterId } = req.params;
const events = await Event.find({
where: { chapter: chapterId },
relations: ['tags'],
});
res.json(events);
},
async show(req: Request, res: Response) {
const { id, chapterId } = req.params;
const event = await Event.findOne({
where: {
id: parseInt(id),
chapter: chapterId,
},
});
if (event) {
res.json(event);
} else {
res.status(404).json({ error: "Can't find event" });
}
},
async create(req: Request, res: Response) {
const {
name,
chapter,
description,
capacity,
venue,
start_at,
ends_at,
tags,
} = req.body;
const event = new Event({
name,
chapter,
description,
capacity,
venue,
start_at,
ends_at,
});
try {
await event.save();
const sanitizedTags = sanitizeTags(tags);
const outTags = await Promise.all(
sanitizedTags.map(item => {
const tag = new Tag({ name: item, event });
return tag.save();
}),
);
return res.status(201).json({
event,
tags: outTags.map((tag: Tag) => ({ id: tag.id, name: tag.name })),
});
} catch (e) {
if (e.code === PostgresErrorCodes.FOREIGN_KEY_VIOLATION) {
if (e.detail.includes('venue')) {
return res
.status(400)
.json({ error: { message: 'venue not found' } });
}
if (e.detail.includes('chapter')) {
return res
.status(400)
.json({ error: { message: 'chapter not found' } });
}
}
res.status(500).json({ error: e });
}
},
async update(req: Request, res: Response) {
const { id, chapterId } = req.params;
const {
name,
description,
capacity,
venue,
canceled,
start_at,
ends_at,
} = req.body;
const event = await Event.findOne({
where: { id: parseInt(id), chapter: chapterId },
});
if (event) {
event.name = name ?? event.name;
event.description = description ?? event.description;
event.capacity = capacity ?? event.capacity;
event.venue = venue ?? event.venue;
event.canceled = canceled ?? event.canceled;
event.start_at = start_at ?? event.start_at;
event.ends_at = ends_at ?? event.ends_at;
try {
await event.save();
res.json(event);
} catch (e) {
if (e.code === PostgresErrorCodes.FOREIGN_KEY_VIOLATION) {
if (e.detail.includes('venue')) {
return res.status(400).json({ message: 'venue not found' });
}
if (e.detail.includes('chapter')) {
return res.status(400).json({ message: 'chapter not found' });
}
}
res.status(500).json({ error: e });
}
} else {
res.status(404).json({ error: "Can't find event" });
}
},
async remove(req: Request, res: Response) {
const { id, chapterId } = req.params;
const event = await Event.findOne({
where: { id: parseInt(id), chapter: chapterId },
});
if (event) {
try {
await event.remove();
res.json({ id: parseInt(id) });
} catch (e) {
res.status(500).json({ error: e });
}
} else {
res.status(404).json({ error: "Can't find event" });
}
},
async cancel(req: Request, res: Response) {
const { id, chapterId } = req.params;
const event = await Event.findOne({
where: { id: parseInt(id), chapter: chapterId },
});
if (event) {
event.canceled = true;
try {
await event.save();
res.json(event);
} catch (e) {
res.status(500).json({ error: e });
}
} else {
res.status(404).json({ error: "Can't find event" });
}
},
};
|
costaivo/chapter
|
pages/dashboard/events/index.tsx
|
<reponame>costaivo/chapter
import React, { useEffect } from 'react';
import { Grid } from '@material-ui/core';
import { useSelector } from 'react-redux';
import Link from 'next/link';
import { AppStoreState } from 'client/store/reducers';
import { eventActions } from 'client/store/actions';
import { IEventModal } from 'client/store/types/events';
import useThunkDispatch from 'client/hooks/useThunkDispatch';
import EventItem from 'client/components/Dashboard/Events/EventItem';
const Events: React.FC = () => {
const { error, loading, events } = useSelector((state: AppStoreState) => ({
error: state.events.error,
loading: state.events.loading,
events: state.events.events,
}));
const dispatch = useThunkDispatch();
useEffect(() => {
dispatch(eventActions.fetchEvents('1'));
}, []);
return (
<Grid container spacing={2}>
<Grid item xs={12}>
<Link href="/dashboard">
<a>Dashboard</a>
</Link>
<br />
<Link href="/dashboard/events/new">
<a>Add new</a>
</Link>
{error ? (
<h1>😢Error</h1>
) : (
events.map((event: IEventModal) => (
<EventItem
event={event}
loading={loading}
key={`events-${event.id}`}
/>
))
)}
</Grid>
</Grid>
);
};
export default Events;
|
costaivo/chapter
|
client/store/reducers/events.ts
|
<filename>client/store/reducers/events.ts
import produce from 'immer';
import { eventsTypes } from '../types';
const initialState: eventsTypes.IEventStoreState = {
loading: true,
events: [],
chapterId: '',
error: '',
create: {
state: 'idle',
error: '',
},
};
const reducer = (state = initialState, action: eventsTypes.IEventActionTypes) =>
produce(state, draft => {
switch (action.type) {
case eventsTypes.FETCH_START:
draft.error = '';
draft.loading = true;
break;
case eventsTypes.FETCH_SUCCESS:
draft.chapterId = action.payload.chapterId;
draft.events = action.payload.events;
draft.error = '';
draft.loading = false;
break;
case eventsTypes.FETCH_SINGLE_SUCCESS:
draft.chapterId = action.payload.chapterId;
if (draft.events.find(event => event.id === action.payload.event.id)) {
draft.events = draft.events.map(event =>
event.id === action.payload.event.id ? action.payload.event : event,
);
} else {
draft.events = [...draft.events, action.payload.event];
}
draft.error = '';
draft.loading = false;
break;
case eventsTypes.FETCH_FAIL:
draft.error = action.payload;
draft.loading = false;
break;
case eventsTypes.CREATE_START:
draft.create.state = 'loading';
draft.create.error = '';
break;
case eventsTypes.CREATE_SUCCESS:
draft.create.state = 'idle';
draft.create.error = '';
draft.events = [...draft.events, action.payload.event];
break;
case eventsTypes.CREATE_FAIL:
draft.create.state = 'error';
draft.create.error = action.payload;
break;
case eventsTypes.REMOVE_SUCCESS:
draft.events = draft.events.filter(
item => item.id !== action.payload.id,
);
break;
case eventsTypes.REMOVE_FAIL:
console.error('Remove failed');
break;
default:
return state;
}
});
export default reducer;
|
costaivo/chapter
|
client/store/actions/events/index.ts
|
import { ActionCreator } from 'redux';
import { HttpService } from 'client/services/http-service';
import { eventsTypes } from '../../types';
import {
fetchStart,
fetchSuccess,
fetchFail,
fetchSingleSuccess,
createStart,
createFail,
createSuccess,
removeFail,
removeSuccess,
} from './actions';
export const fetchEvents: ActionCreator<eventsTypes.ThunkResult<
Promise<void>
>> = (chapterId: string) => async dispatch => {
dispatch(fetchStart());
const http = new HttpService<eventsTypes.IEventModal[]>();
try {
const { resData } = await http.get(`/chapters/${chapterId}/events`, {}, {});
dispatch(fetchSuccess(resData, chapterId));
} catch (err) {
dispatch(fetchFail(err));
}
};
export const fetchEvent: ActionCreator<eventsTypes.ThunkResult<
Promise<void>
>> = (chapterId: string, eventId: string) => async dispatch => {
dispatch(fetchStart());
const http = new HttpService<eventsTypes.IEventModal>();
try {
const { resData } = await http.get(
`/chapters/${chapterId}/events/${eventId}`,
{},
{},
);
dispatch(fetchSingleSuccess(resData, chapterId));
} catch (err) {
dispatch(fetchFail(err));
}
};
export const createEvent: ActionCreator<eventsTypes.ThunkResult<
Promise<boolean>
>> = (data: any) => async dispatch => {
dispatch(createStart());
// TODO: Add new HTTP service when #342 is merged
try {
const res = await fetch(`/api/v1/chapters/1/events`, {
body: JSON.stringify(data),
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
});
const resData = await res.json();
if (res.status !== 201) {
throw new Error(resData.error.message);
}
dispatch(createSuccess(resData));
return true;
} catch (err) {
dispatch(createFail(err.message));
}
return false;
};
export const cancelEvent: ActionCreator<eventsTypes.ThunkResult<
Promise<void>
>> = (chapterId: string, eventId: string) => async dispatch => {
const http = new HttpService<eventsTypes.IEventModal>();
try {
const { resData } = await http.delete(
`/chapters/${chapterId}/events/${eventId}/cancel`,
{},
{},
);
dispatch(fetchSingleSuccess(resData, chapterId));
} catch (err) {
dispatch(fetchFail(err));
}
};
export const removeEvent: ActionCreator<eventsTypes.ThunkResult<
Promise<void>
>> = (chapterId: string, eventId: string) => async dispatch => {
const http = new HttpService<{ id: number }>();
try {
const { resData } = await http.delete(
`/chapters/${chapterId}/events/${eventId}`,
{},
{},
);
dispatch(removeSuccess(resData.id, parseInt(chapterId)));
} catch (err) {
dispatch(removeFail(err));
}
};
|
costaivo/chapter
|
pages/dashboard/locations/[id]/index.tsx
|
import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { Card, Typography } from '@material-ui/core';
import { useRouter } from 'next/router';
import { locationActions } from 'client/store/actions';
import { AppStoreState } from 'client/store/reducers';
import { ProgressCardContent } from 'client/components';
import useThunkDispatch from 'client/hooks/useThunkDispatch';
import Skeleton from 'client/components/Dashboard/Locations/Skeleton';
const ShowLocation: React.FC = () => {
const router = useRouter();
const { id } = router.query;
const { error, loading, location } = useSelector((state: AppStoreState) => ({
error: state.locations.error,
loading: state.locations.loading,
location: state.locations.locations.find(
location => location.id === parseInt(Array.isArray(id) ? id[0] : id),
),
}));
const dispatch = useThunkDispatch();
useEffect(() => {
if (id !== undefined) {
dispatch(locationActions.fetchOneLocation(id));
}
}, [id]);
if (loading || error || !location) {
return (
<Skeleton>
<h1>{loading ? 'Loading...' : 'Error...'}</h1>
</Skeleton>
);
}
return (
<Skeleton>
<Card style={{ marginTop: '12px' }} key={`event-${location.id}`}>
<ProgressCardContent loading={loading}>
<Typography gutterBottom variant="h5" component="h2">
{location.address}
</Typography>
<Typography variant="body2" color="textSecondary" component="p">
{`${location.region}, ${location.country_code}, ${location.postal_code}`}
</Typography>
<Typography variant="body2" color="textSecondary" component="p">
{location.address}
</Typography>
</ProgressCardContent>
</Card>
<h3>Placeholder for venues...</h3>
</Skeleton>
);
};
export default ShowLocation;
|
costaivo/chapter
|
pages/dashboard/events/[id]/index.tsx
|
import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { Card, Typography } from '@material-ui/core';
import { useRouter } from 'next/router';
import { eventActions } from 'client/store/actions';
import { AppStoreState } from 'client/store/reducers';
import { ProgressCardContent } from 'client/components';
import useThunkDispatch from 'client/hooks/useThunkDispatch';
import Skeleton from 'client/components/Dashboard/Events/Skeleton';
const ShowEvent: React.FC = () => {
const router = useRouter();
const { id } = router.query;
const { error, loading, event } = useSelector((state: AppStoreState) => ({
error: state.events.error,
loading: state.events.loading,
event: state.events.events.find(
event => event.id === parseInt(Array.isArray(id) ? id[0] : id),
),
}));
const dispatch = useThunkDispatch();
console.log(parseInt(Array.isArray(id) ? id[0] : id));
useEffect(() => {
if (id !== undefined) {
dispatch(eventActions.fetchEvent('1', id));
}
}, [id]);
if (loading || error || !event) {
return (
<Skeleton>
<h1>{loading ? 'Loading...' : 'Error...'}</h1>
</Skeleton>
);
}
return (
<Skeleton>
<Card style={{ marginTop: '12px' }}>
<ProgressCardContent loading={loading}>
<Typography gutterBottom variant="h5" component="h2">
{event.name}
</Typography>
</ProgressCardContent>
</Card>
</Skeleton>
);
};
export default ShowEvent;
|
costaivo/chapter
|
client/components/Dashboard/Venues/VenueForm.tsx
|
<reponame>costaivo/chapter
import React from 'react';
import { useForm, Controller } from 'react-hook-form';
import {
Button,
TextField,
makeStyles,
FormControl,
Select,
InputLabel,
MenuItem,
} from '@material-ui/core';
import { ILocationModal } from 'client/store/types/locations';
import getLocationString from 'client/helpers/getLocationString';
import { IVenueModal } from 'client/store/types/venues';
interface IData {
name: string;
location: number;
}
interface IVenueFormProps {
loading: boolean;
onSubmit: (data: IData) => Promise<void>;
data?: IVenueModal;
locations: ILocationModal[];
locationsLoading: boolean;
submitText: string;
}
const useStyles = makeStyles(() => ({
form: {
display: 'flex',
flexDirection: 'column',
maxWidth: '25%',
},
item: {
marginTop: '20px',
},
}));
const VenueForm: React.FC<IVenueFormProps> = props => {
const {
loading,
onSubmit,
data,
locations,
locationsLoading,
submitText,
} = props;
const styles = useStyles();
const { control, handleSubmit } = useForm();
console.log(data && data.location && data.location.id);
console.log(locations[0] && locations[0].id);
// useEffect(() => {
// if (!locationsLoading && locations && data && data.location) {
// console.log(data.location.id);
// setValue('location', data.location.id);
// }
// }, [locationsLoading, locations, data]);
return (
<form onSubmit={handleSubmit(onSubmit)} className={styles.form}>
<FormControl className={styles.item}>
<Controller
control={control}
as={<TextField name="name" type="text" label="Name" placeholder="" />}
name={'name'}
options={{ required: true }}
defaultValue={(data && data.name) || ''}
/>
</FormControl>
{locationsLoading ? (
<h1>Loading locations...</h1>
) : (
<FormControl className={styles.item}>
<InputLabel id="location-label">Location</InputLabel>
<Controller
control={control}
as={
<Select labelId="location-label">
{locations.map(location => (
<MenuItem value={location.id} key={location.id}>
{getLocationString(location, true)}
</MenuItem>
))}
</Select>
}
name="location"
options={{ required: true }}
defaultValue={
(data && data.location && data.location.id) ||
(locations[0] && locations[0].id) ||
0
}
/>
</FormControl>
)}
<Button
className={styles.item}
variant="contained"
color="primary"
type="submit"
disabled={loading}
>
{submitText}
</Button>
</form>
);
};
export default VenueForm;
|
costaivo/chapter
|
client/store/actions/events/actions.ts
|
import { eventsTypes } from 'client/store/types';
export const fetchStart = (): eventsTypes.IEventActionTypes => {
return {
type: eventsTypes.FETCH_START,
};
};
export const fetchSuccess = (
events: eventsTypes.IEventModal[],
chapterId: string,
): eventsTypes.IEventActionTypes => {
return {
type: eventsTypes.FETCH_SUCCESS,
payload: { events, chapterId },
};
};
export const fetchSingleSuccess = (
event: eventsTypes.IEventModal,
chapterId: string,
): eventsTypes.IEventActionTypes => {
return {
type: eventsTypes.FETCH_SINGLE_SUCCESS,
payload: { event, chapterId },
};
};
export const fetchFail = (error: string): eventsTypes.IEventActionTypes => {
return {
type: eventsTypes.FETCH_FAIL,
payload: error,
};
};
export const createStart = (): eventsTypes.IEventActionTypes => {
return {
type: eventsTypes.CREATE_START,
};
};
export const createSuccess = (
event: eventsTypes.IEventModal,
): eventsTypes.IEventActionTypes => {
return {
type: eventsTypes.CREATE_SUCCESS,
payload: { event },
};
};
export const createFail = (error: string): eventsTypes.IEventActionTypes => {
return {
type: eventsTypes.CREATE_FAIL,
payload: error,
};
};
export const removeSuccess = (
id: number,
chapterId: number,
): eventsTypes.IEventActionTypes => {
return {
type: eventsTypes.REMOVE_SUCCESS,
payload: { id, chapterId },
};
};
export const removeFail = (error: string): eventsTypes.IEventActionTypes => {
return {
type: eventsTypes.REMOVE_FAIL,
payload: error,
};
};
|
costaivo/chapter
|
pages/dashboard/venues/new.tsx
|
import React, { useEffect } from 'react';
import { useSelector } from 'react-redux';
import { makeStyles } from '@material-ui/core';
import { useRouter } from 'next/router';
import { locationActions, venueActions } from 'client/store/actions';
import { AppStoreState } from 'client/store/reducers';
import sanitizeFormData from 'client/helpers/sanitizeFormData';
import useThunkDispatch from 'client/hooks/useThunkDispatch';
import { VenueForm, Skeleton } from 'client/components/Dashboard/Venues/';
const useStyles = makeStyles(() => ({
responseDiv: {
margin: '15px 0',
},
}));
const NewVenue: React.FC = () => {
const router = useRouter();
const styles = useStyles();
const { error, state, locations, locationsLoading } = useSelector(
(state: AppStoreState) => ({
error: state.venues.create.error,
state: state.venues.create.state,
locations: state.locations.locations,
locationsLoading: state.locations.loading,
}),
);
const dispatch = useThunkDispatch();
useEffect(() => {
dispatch(locationActions.fetchLocations());
}, []);
const onSubmit = async data => {
const success = await dispatch(venueActions.create(sanitizeFormData(data)));
if (success) {
router.replace('/dashboard/venues');
}
};
return (
<Skeleton>
{error && <div className={styles.responseDiv}>{error}</div>}
<VenueForm
loading={state === 'loading'}
locations={locations}
locationsLoading={locationsLoading}
onSubmit={onSubmit}
submitText={'Add venue'}
/>
</Skeleton>
);
};
export default NewVenue;
|
Mukkesh20/Trackcov
|
src/app/app.module.ts
|
<filename>src/app/app.module.ts<gh_stars>0
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { ChartsModule, ThemeService } from 'ng2-charts';
import { AppComponent } from './app.component';
import { NavbarComponent } from './navbar/navbar.component';
import { SidebarComponent } from './sidebar/sidebar.component';
import { FooterComponent } from './footer/footer.component';
import { DashboardComponent } from './dashboard/dashboard.component';
import { FormsComponent } from './forms/forms.component';
import { ButtonsComponent } from './buttons/buttons.component';
import { TablesComponent } from './tables/tables.component';
import { TypographyComponent } from './typography/typography.component';
import { IconsComponent } from './icons/icons.component';
import { AlertsComponent } from './alerts/alerts.component';
import { AccordionsComponent } from './accordions/accordions.component';
import { BadgesComponent } from './badges/badges.component';
import { ProgressbarComponent } from './progressbar/progressbar.component';
import { BreadcrumbsComponent } from './breadcrumbs/breadcrumbs.component';
import { PaginationComponent } from './pagination/pagination.component';
import { DropdownComponent } from './dropdown/dropdown.component';
import { TooltipsComponent } from './tooltips/tooltips.component';
import { CarouselComponent } from './carousel/carousel.component';
import { TabsComponent } from './tabs/tabs.component';
import { HttpClientModule } from '@angular/common/http';
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
SidebarComponent,
FooterComponent,
DashboardComponent,
FormsComponent,
ButtonsComponent,
TablesComponent,
TypographyComponent,
IconsComponent,
AlertsComponent,
AccordionsComponent,
BadgesComponent,
ProgressbarComponent,
BreadcrumbsComponent,
PaginationComponent,
DropdownComponent,
TooltipsComponent,
CarouselComponent,
TabsComponent
],
imports: [
BrowserModule,
ReactiveFormsModule,
RouterModule,
HttpClientModule,
AppRoutingModule,
FormsModule,
NgbModule,
ChartsModule
],
providers: [ThemeService],
bootstrap: [AppComponent]
})
export class AppModule { }
|
Mukkesh20/Trackcov
|
src/app/charts/chartjs/charts.component.ts
|
<filename>src/app/charts/chartjs/charts.component.ts
import { Component, OnInit } from '@angular/core';
import { ThemeService } from 'ng2-charts';
@Component({
selector: 'app-chart',
templateUrl: './charts.component.html',
styleUrls: ['./charts.component.scss'],
//providers:[]
})
export class ChartsComponent implements OnInit {
lineChartData = [{
label: '# of Votes',
data: [10, 19, 3, 5, 2, 3],
borderWidth: 1,
fill: false
}];
lineChartLabels = ["2013", "2014", "2014", "2015", "2016", "2017"];
lineChartOptions = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
display: false
},
elements: {
point: {
radius: 0
}
}
};
lineChartColors = [
{
borderColor: 'rgba(255,99,132,1)'
}
];
barChartData = [{
label: '# of Votes',
data: [10, 19, 3, 5, 2, 3],
borderWidth: 1,
fill: false
}];
barChartLabels = ["2013", "2014", "2014", "2015", "2016", "2017"];
barChartOptions = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
display: false
},
elements: {
point: {
radius: 0
}
}
};
barChartColors = [
{
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)',
'rgba(75, 192, 192, 0.2)',
'rgba(153, 102, 255, 0.2)',
'rgba(255, 159, 64, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)',
'rgba(75, 192, 192, 1)',
'rgba(153, 102, 255, 1)',
'rgba(255, 159, 64, 1)'
]
}
];
areaChartData = [{
label: '# of Votes',
data: [10, 19, 3, 5, 2, 3],
borderWidth: 1,
fill: true
}];
areaChartLabels = ["2013", "2014", "2014", "2015", "2016", "2017"];
areaChartOptions = {};
areaChartColors = [
{
borderColor: 'rgba(255,99,132,1)',
backgroundColor: 'rgba(255,99,132,.2)'
}
];
doughnutPieChartData = [
{
data: [30, 40, 30],
}
];
doughnutPieChartLabels = ["Pink", "Blue", "Yellow"];
doughnutPieChartOptions = {
responsive: true,
animation: {
animateScale: true,
animateRotate: true
}
};
doughnutPieChartColors = [
{
backgroundColor: [
'rgba(255, 99, 132, 0.2)',
'rgba(54, 162, 235, 0.2)',
'rgba(255, 206, 86, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)',
'rgba(54, 162, 235, 1)',
'rgba(255, 206, 86, 1)'
]
}
];
scatterChartData = [
{
label: 'First Dataset',
data: [{
x: -10,
y: 0
},
{
x: 0,
y: 3
},
{
x: -25,
y: 5
},
{
x: 40,
y: 5
}
],
borderWidth: 1
},
{
label: 'Second Dataset',
data: [{
x: 10,
y: 5
},
{
x: 20,
y: -30
},
{
x: -25,
y: 15
},
{
x: -10,
y: 5
}
],
borderWidth: 1
}
];
scatterChartOptions = {
scales: {
xAxes: [{
type: 'linear',
position: 'bottom'
}]
}
};
scatterChartColors = [
{
backgroundColor: [
'rgba(255, 99, 132, 0.2)'
],
borderColor: [
'rgba(255,99,132,1)' ]
},
{
backgroundColor: [
'rgba(54, 162, 235, 0.2)'
],
borderColor: [
'rgba(54, 162, 235, 1)'
]
}
];
constructor() { }
ngOnInit() {
}
}
|
Mukkesh20/Trackcov
|
src/app/sidebar/sidebar.component.ts
|
<gh_stars>0
import { Component, OnInit } from '@angular/core';
import { DashBoardService } from '../dashboard/dashboard.service';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.scss']
})
export class SidebarComponent implements OnInit {
countryList = [];
constructor(private dashBoardService : DashBoardService) { }
ngOnInit() {
this.countryList = this.dashBoardService.getAllCountryList();
}
}
|
Mukkesh20/Trackcov
|
src/app/dashboard/dashboard.component.ts
|
<filename>src/app/dashboard/dashboard.component.ts
import { Component, OnInit } from '@angular/core';
import { ViewEncapsulation } from '@angular/core';
import { Subscription } from 'rxjs';
import { DashBoardService } from './dashboard.service';
import { Router, ActivatedRoute } from '@angular/router';
import { FormGroup, FormControl } from '@angular/forms';
import {AfterViewInit, ViewChild} from '@angular/core';
import {MatSort} from '@angular/material/sort';
import {MatTableDataSource} from '@angular/material/table';
@Component({
selector: 'app-dashboard',
templateUrl: './dashboard.component.html',
styleUrls: ['../app.component.scss','./dashboard.component.scss'],
encapsulation: ViewEncapsulation.None
})
export class DashboardComponent implements OnInit,AfterViewInit {
checked ;
isLoading = false;
panelOpenState= false
isTimelineClicked = false;
lastUpdatedMinutes: any;
lastUpdatedSeconds: any;
lastUpdatedDateTime: any
lastUpdatedDate: any;
lastUpdatedTime: any;
totalCases : any
totalActive: any
totalDeaths : any
totalRecovered : any
totalTested: any;
casesPerMil: any;
deathsPerMil: any;
testsPerMil: any;
lastUpdatedDateTimeTimeline: Date;
totalCasesTimeline : any
totalActiveTimeline: any
totalDeathsTimeline : any
totalRecoveredTimeline : any
totalTestedTimeline: any;
casesPerMilTimeline: any;
deathsPerMilTimeline: any;
testsPerMilTimeline: any;
totalCasesIncreasedTimeline : any
totalActiveIncreasedTimeline : any
totalDeathsIncreasedTimeline : any
totalRecoveredIncreasedTimeline : any
totalCasesIncreased : any
totalActiveIncreased : any
totalDeathsIncreased : any
totalRecoveredIncreased : any
totalCasesAllCountries : { country: string, number: any }[] = []
sortedTotalCasesAllCountries : { country: string, number: any }[] = []
timelineCountryClicked = false;
country;
countryList = [];
pastData = [];
pastDataDate = [];
pastDataDate1 = [];
pastDataActive = [];
pastDataRecovered = [];
pastDataDeaths=[];
pastDataDailyCases=[];
pastDataDailyDeaths=[];
pastDataDailyRecovered=[];
totalActiveIndia;
totalRecoveredIndia;
totalDeathsIndia;
totalCasesIndia;
barChartData : {total: string, recovered:string, deaths: string }[] = []
dataSub : Subscription;
sortSub : Subscription;
timelineDataSub: Subscription;
statesList : {active: string, recovered:string, deaths: string , active_rate: string, recovered_rate:string, death_rate: string, states:string, confirmed:string}[] = []
displayedColumns: string[] = ['position', 'name', 'weight', 'symbol'];
dataSource = new MatTableDataSource(this.statesList);
constructor(private dashBoardService : DashBoardService,
private router: Router,
private route: ActivatedRoute) {this.getPastCountryTimeline(); }
ngOnInit() {
this.countryList = this.dashBoardService.getAllCountryList();
if(localStorage.getItem('country') === null){
this.getStatsByCountry('India')
}else{
this.getStatsByCountry(localStorage.getItem('country'));
}
this.sortByanyOfCases();
this.getStateData()
//this.getPastCountryTimeline();
//console.log(this.sortedTotalCasesAllCountries)
}
onRefresh(){
if(localStorage.getItem('country') === null){
this.getStatsByCountry('India')
}else{
this.getStatsByCountry(localStorage.getItem('country'));
}
//this.sortedTotalCasesAllCountries = [];
this.sortByanyOfCases();
this.getPastCountryTimeline();
}
timelineExpand(){
this.isTimelineClicked = !this.isTimelineClicked;
}
sortByanyOfCases(){
this.sortedTotalCasesAllCountries = [];
// this.worldSub = this.dashBoardService.getWorldData().subscribe((data) => {
// let myData1 = JSON.parse(JSON.stringify(data));
// this.sortedTotalCasesAllCountries.push({'country' : 'World', 'number': myData1.total_cases})
// })
this.sortSub = this.dashBoardService.getAllCountryData().subscribe((data) => {
let myData = JSON.parse(JSON.stringify(data.countries_stat));
for(let country of myData){
this.sortedTotalCasesAllCountries.push({'country' : country.country_name, 'number': country.cases})
}
})
}
getStatsByCountry(country: string){
this.isLoading = true;
localStorage.setItem('country', country);
this.country=localStorage.getItem('country');
//this.router.navigate(['/',country], {relativeTo: this.route})
this.dataSub = this.dashBoardService.getLatestStatsByCountry(country).subscribe((data) => {
let myData = JSON.parse(JSON.stringify(data.latest_stat_by_country));
var year = myData[0].record_date.substr(0,4);
var month = myData[0].record_date.substr(5,2);
var day = myData[0].record_date.substr(8,2);
var hours = myData[0].record_date.substr(11,2);
var min = myData[0].record_date.substr(14,2);
var sec = myData[0].record_date.substr(17,2);
let date: Date = new Date(year, month-1, day, hours, min, sec, null);
var currentDate = Date.parse(new Date().toUTCString());
var currDateOffset = new Date().getTimezoneOffset();
var millisec = (date.getTime() - currDateOffset*1000*60);
this.lastUpdatedDateTime = new Date(millisec).toString().substr(15,9);
var minutes = (currentDate - Date.parse(date.toString()))/60000 + date.getTimezoneOffset();
var seconds = minutes.toString().split('.')[1].substr(0,2);
//console.log(parseInt(seconds) * 0.6);
this.lastUpdatedMinutes = minutes.toString().split('.')[0];
this.lastUpdatedSeconds = Math.round(parseInt(seconds) * 0.6)
this.totalTested = myData[0].total_tests;
this.totalCases = myData[0].total_cases;
this.totalActive = myData[0].active_cases;
this.totalRecovered = myData[0].total_recovered;
this.totalDeaths = myData[0].total_deaths;
this.totalCasesIncreased = myData[0].new_cases;
this.totalDeathsIncreased = myData[0].new_deaths;
this.casesPerMil = myData[0].total_cases_per1m;
this.deathsPerMil = myData[0].deaths_per1m;
this.testsPerMil = myData[0].total_tests_per1m;
this.isLoading = false;
})
}
getStatsByCountryTimeline(country: string){
//this.timelineCountryClicked=!this.timelineCountryClicked;
this.totalTestedTimeline ='NA';
this.totalCasesTimeline = 'NA';
this.totalActiveTimeline = 'NA';
this.totalRecoveredTimeline = 'NA';
this.totalDeathsTimeline = '';
this.totalCasesIncreasedTimeline = 'NA';
this.totalDeathsIncreasedTimeline ='NA';
this.casesPerMilTimeline = 'NA';
this.deathsPerMilTimeline = 'NA';
this.testsPerMilTimeline = 'NA';
this.timelineDataSub = this.dashBoardService.getLatestStatsByCountry(country).subscribe((data) => {
let myData = JSON.parse(JSON.stringify(data.latest_stat_by_country));
this.totalTestedTimeline = myData[0].total_tests;
this.totalCasesTimeline = myData[0].total_cases;
this.totalActiveTimeline = myData[0].active_cases;
this.totalRecoveredTimeline = myData[0].total_recovered;
this.totalDeathsTimeline = myData[0].total_deaths;
this.totalCasesIncreasedTimeline = myData[0].new_cases;
this.totalDeathsIncreasedTimeline = myData[0].new_deaths;
this.casesPerMilTimeline = myData[0].total_cases_per1m;
this.deathsPerMilTimeline = myData[0].deaths_per1m;
this.testsPerMilTimeline = myData[0].total_tests_per1m;
})
}
getPastCountryTimeline(){
//this.timelineCountryClicked=!this.timelineCountryClicked;
this.timelineDataSub = this.dashBoardService.getPastData().subscribe((data) => {
let myData = JSON.parse(JSON.stringify(data));
// this.totalActiveIndia = myData[myData.length-1].totalconfirmed - (+myData[myData.length-1].totalrecovered + +myData[myData.length-1].totaldeceased)
// this.totalRecoveredIndia = myData[myData.length-1].totalrecovered
// this.totalDeathsIndia = myData[myData.length-1].totaldeceased
// this.totalCasesIndia = myData[myData.length-1].totalconfirmed
for(var i= myData.length-100 ; i<myData.length; i++){
this.pastData.push(myData[i].totalconfirmed)
this.pastDataDate.push(myData[i].date)
i++;
}
for(var j= myData.length-7 ; j<myData.length; j++){
this.pastDataDate1.push(myData[j].date)
this.pastDataDailyCases.push(myData[j].dailyconfirmed)
this.pastDataDailyRecovered.push(myData[j].dailyrecovered)
this.pastDataDailyDeaths.push(myData[j].dailydeceased)
i++;
}
console.log()
})
}
downloadApp(){
}
getStateData(){
//this.timelineCountryClicked=!this.timelineCountryClicked;
this.timelineDataSub = this.dashBoardService.getAllStateData().subscribe((data) => {
let myData = JSON.parse(JSON.stringify(data));
// this.totalActiveIndia = myData[myData.length-1].totalconfirmed - (+myData[myData.length-1].totalrecovered + +myData[myData.length-1].totaldeceased)
// this.totalRecoveredIndia = myData[myData.length-1].totalrecovered
// this.totalDeathsIndia = myData[myData.length-1].totaldeceased
// this.totalCasesIndia = myData[myData.length-1].totalconfirmed
for(var i=0; i< myData.state_data.length;i++){
this.statesList.push({
'active': myData.state_data[i].active,
'recovered':myData.state_data[i].recovered,
'deaths': myData.state_data[i].deaths ,
'active_rate': myData.state_data[i].active_rate,
'recovered_rate':myData.state_data[i].recovered_rate,
'death_rate': myData.state_data[i].death_rate,
'states': myData.state_data[i].state,
'confirmed': myData.state_data[i].confirmed
})
}
console.log(myData.state_data.length)
console.log(this.statesList)
})
}
@ViewChild(MatSort, {static: false} ) sort: MatSort;
ngAfterViewInit() {
this.dataSource.sort = this.sort;
}
ngOnDestroy(){
this.sortSub.unsubscribe();
this.dataSub.unsubscribe();
//this.timelineDataSub.unsubscribe();
}
//----------------------------Chart-------------------------------------
lineChartData = [{
label: '# of People',
data: this.pastData,
borderWidth: 3,
fill: false
}];
lineChartLabels = this.pastDataDate;
lineChartOptions = {
scales: {
yAxes: [{
ticks: {
beginAtZero: false
}
}]
},
legend: {
display: false
},
elements: {
point: {
radius: 0
}
}
};
lineChartColors = [
{
borderColor: 'rgba(255,99,132,1)'
}
];
barChartData1 = [{
label: 'Confirmed',
data: this.pastDataDailyCases,
borderWidth: 1,
fill: false,
},
{
label: 'Recovered',
data: this.pastDataDailyRecovered,
borderWidth: 1,
fill: false,
}];
barChartLabels = this.pastDataDate1;
barChartOptions = {
scales: {
yAxes: [{
ticks: {
beginAtZero: true
}
}]
},
legend: {
display: false
},
elements: {
point: {
radius: 0
}
}
};
}
|
cowai/gccgce
|
src/main.ts
|
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function updateEventColor(): void {
const timeMinDate = new Date()
timeMinDate.setHours(timeMinDate.getHours() - 2)
const optionalArgs = {
timeMin: timeMinDate.toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 10,
orderBy: 'startTime',
}
const calendarId = 'primary'
const events = Calendar.Events?.list(calendarId, optionalArgs)
events?.items?.forEach((event: GoogleAppsScript.Calendar.Schema.Event) => {
if (!event.colorId && event.id) {
event.colorId = colorBySummary(event.summary)
Calendar.Events?.update(event, calendarId, event.id)
}
})
}
function colorBySummary(summary?: string): string | undefined {
// https://developers.google.com/apps-script/reference/calendar/event-color
if (!summary || /無駄/.test(summary)) {
return CalendarApp.EventColor.RED.toString()
}
if (/睡眠/.test(summary)) {
return CalendarApp.EventColor.PALE_BLUE.toString()
}
if (/映画|漫画|ゲーム|テレビ|アニメ/.test(summary)) {
return CalendarApp.EventColor.PALE_GREEN.toString()
}
if (/仕事/.test(summary)) {
return CalendarApp.EventColor.MAUVE.toString()
}
if (/家族/.test(summary)) {
return CalendarApp.EventColor.PALE_RED.toString()
}
if (/創作|作曲/.test(summary)) {
return CalendarApp.EventColor.YELLOW.toString()
}
if (/英|Anki|ELSA|読書|開発|勉強|プログラミング/.test(summary)) {
return CalendarApp.EventColor.ORANGE.toString()
}
if (/運動|筋トレ|ジョギング|散歩|瞑想|ストレッチ/.test(summary)) {
return CalendarApp.EventColor.CYAN.toString()
}
if (
/(育児|おむつ|ミルク|あやし|寝かしつけ|ごみ|ゴミ|浣腸|沐浴|炊事|洗濯|洗い物|荷解き|片付け|買い物)/.test(
summary
)
) {
return CalendarApp.EventColor.GRAY.toString()
}
// if (/word/.test(summary)) {
// return CalendarApp.EventColor.BLUE.toString();
// }
if (/ふりかえり|振り返り/.test(summary)) {
return CalendarApp.EventColor.GREEN.toString()
}
}
|
dejapong/grafana
|
public/app/features/library-panels/state/api.ts
|
<gh_stars>1-10
import { getBackendSrv } from '@grafana/runtime';
import { LibraryPanelDTO, PanelModelWithLibraryPanel } from '../types';
export async function getLibraryPanels(): Promise<LibraryPanelDTO[]> {
const { result } = await getBackendSrv().get(`/api/library-panels`);
return result;
}
export async function addLibraryPanel(
panelSaveModel: PanelModelWithLibraryPanel,
folderId: number
): Promise<LibraryPanelDTO> {
const { result } = await getBackendSrv().post(`/api/library-panels`, {
folderId,
name: panelSaveModel.title,
model: panelSaveModel,
});
return result;
}
export async function updateLibraryPanel(
panelSaveModel: PanelModelWithLibraryPanel,
folderId: number
): Promise<LibraryPanelDTO> {
const { result } = await getBackendSrv().patch(`/api/library-panels/${panelSaveModel.libraryPanel.uid}`, {
folderId,
name: panelSaveModel.title,
model: panelSaveModel,
version: panelSaveModel.libraryPanel.version,
});
return result;
}
export function deleteLibraryPanel(uid: string): Promise<{ message: string }> {
return getBackendSrv().delete(`/api/library-panels/${uid}`);
}
export async function getLibraryPanelConnectedDashboards(libraryPanelUid: string): Promise<number[]> {
const { result } = await getBackendSrv().get(`/api/library-panels/${libraryPanelUid}/dashboards`);
return result;
}
|
multum/react-updates
|
types/index.d.ts
|
<gh_stars>1-10
import { ComponentType, FunctionComponent } from 'react';
interface DebuggerSettings {
disabled?: boolean;
}
/**
* @example
* import { setDebuggerSettings } from 'react-updates';
* setDebuggerSettings({
* disabled: process.env.NODE_ENV === 'production'
* });
*/
export function setDebuggerSettings(
settings: DebuggerSettings
): DebuggerSettings;
/**
* @example
* import { useDebugger } from 'react-updates';
* const ViewComponent = (props) => {
* useDebugger('View', props);
* return '...'
* };
*/
export function useDebugger<P = {}>(
component: FunctionComponent<P> | string,
props: object
): void;
/**
* @example
* import { debugComponentUpdate } from 'react-updates';
* class View extends Component {
* componentDidUpdate(prevProps) {
* debugComponentUpdate('View', prevProps, this.props);
* }
* render() {
* return '...'
* }
* };
*/
export function debugComponentUpdate<P = {}>(
component: ComponentType<P> | string,
prevProps: object,
props: object
): void;
|
FeatureToggleStudy/open-kilda
|
services/src/openkilda-gui/ui/src/app/modules/isl/isl-detail/isl-detail.component.ts
|
<gh_stars>0
import { Component, OnInit, EventEmitter, Output, AfterViewInit, OnDestroy } from '@angular/core';
import { HttpClient } from "@angular/common/http";
import { IslDetailModel } from '../../../common/data-models/isl-detail-model';
import { Observable } from "rxjs";
import { ActivatedRoute, Router } from '@angular/router';
import { IslModel } from "../../../common/data-models/isl-model";
import { SwitchidmaskPipe } from "../../../common/pipes/switchidmask.pipe";
import { IslListService } from '../../../common/services/isl-list.service';
import { DygraphService } from '../../../common/services/dygraph.service';
import { ToastrService } from 'ngx-toastr';
import { IslDataService } from '../../../common/services/isl-data.service';
import { IslDetailService } from '../../../common/services/isl-detail.service';
import { FormBuilder, FormGroup, Validators, NgForm } from '@angular/forms';
import { NgxSpinnerService } from "ngx-spinner";
import { ClipboardService } from "ngx-clipboard";
import * as _moment from 'moment';
import { LoaderService } from "../../../common/services/loader.service";
import { Title } from '@angular/platform-browser';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';
import { ModalconfirmationComponent } from '../../../common/components/modalconfirmation/modalconfirmation.component';
import { IslmaintenancemodalComponent } from '../../../common/components/islmaintenancemodal/islmaintenancemodal.component';
import { CommonService } from '../../../common/services/common.service';
import { ModalComponent } from 'src/app/common/components/modal/modal.component';
import { OtpComponent } from 'src/app/common/components/otp/otp.component';
declare var moment: any;
@Component({
selector: 'app-isl-detail',
templateUrl: './isl-detail.component.html',
styleUrls: ['./isl-detail.component.css']
})
export class IslDetailComponent implements OnInit, AfterViewInit,OnDestroy {
openedTab = "graph";
detailUrl: string = '';
src_switch:string = '';
src_port:string = '';
dst_switch:string = '';
dst_port:string = '';
speed:string = '';
latency:string = '';
state:string = '';
evacuate:boolean=false;
under_maintenance:boolean=false;
loadingData = true;
dataSet:any;
available_bandwidth:string = '';
default_max_bandwidth='';
max_bandwidth :any = '';
detailDataObservable : any;
src_switch_name: string;
dst_switch_name: string;
graphDataForwardUrl: string;
graphDataBackwardUrl: string;
responseGraph = [];
src_switch_kilda: string;
dst_switch_kilda:string;
callGraphAPIFlag: boolean = false;
currentGraphData = {
data:[],
startDate:moment(new Date()).format("YYYY/MM/DD HH:mm:ss"),
endDate: moment(new Date()).format("YYYY/MM/DD HH:mm:ss"),
timezone: "LOCAL"
};
graphObj: any;
message:{};
getautoReloadValues = this.commonService.getAutoreloadValues();
filterForm: FormGroup;
graphMetrics = [];
autoReloadTimerId = null;
islForm: FormGroup;
showCostEditing: boolean = false;
showBandwidthEditing : boolean = false;
currentGraphName : string = "Round Trip Latency Graph (In Seconds)";
dateMessage:string;
clipBoardItems = {
sourceSwitchName:"",
sourceSwitch:"",
targetSwitchName:"",
targetSwitch:""
}
@Output() hideToValue: EventEmitter<any> = new EventEmitter();
newMessageDetail(){
this.islDataService.changeMessage(this.currentGraphData)
}
constructor(private httpClient:HttpClient,
private route: ActivatedRoute,
private maskPipe: SwitchidmaskPipe,
private router:Router,
private islListService:IslListService,
private toastr: ToastrService,
private dygraphService:DygraphService,
private islDataService: IslDataService,
private formBuiler: FormBuilder,
private loaderService: LoaderService,
private clipboardService: ClipboardService,
private islFormBuiler: FormBuilder,
private titleService: Title,
private modalService: NgbModal,
private commonService: CommonService,
private islDetailService : IslDetailService,
) {
}
ngOnInit() {
this.titleService.setTitle('OPEN KILDA - View ISL');
var date = new Date();
var yesterday = new Date(date.getTime());
yesterday.setDate(date.getDate() - 1);
var fromStartDate = moment(yesterday).format("YYYY/MM/DD HH:mm:ss");
var toEndDate = moment(date).format("YYYY/MM/DD HH:mm:ss");
let dateRange = this.getDateRange();
this.route.params.subscribe(params => {
this.src_switch = params['src_switch'];
this.src_port = params['src_port'];
this.dst_switch = params['dst_switch'];
this.dst_port = params['dst_port'];
this.src_switch_kilda = this.maskPipe.transform(this.src_switch,'legacy');
this.dst_switch_kilda = this.maskPipe.transform(this.dst_switch,'legacy');
this.getIslDetailData(this.src_switch,this.src_port,this.dst_switch,this.dst_port);
});
this.filterForm = this.formBuiler.group({
timezone: ["LOCAL"],
fromDate: [dateRange.from],
toDate: [dateRange.to],
download_sample: ["30s"],
graph: ["rtt"],
metric: ["bits"],
auto_reload: [""],
auto_reload_time: ["", Validators.compose([Validators.pattern("[0-9]*")])]
});
this.graphMetrics = this.dygraphService.getPortMetricData();
}
getIslDetailData(src_switch,src_port,dst_switch,dst_port){
this.loaderService.show("Loading ISL detail");
this.islListService.getISLDetailData(src_switch, src_port, dst_switch, dst_port).subscribe((linkData:any) =>{
if(linkData && linkData.length){
this.loaderService.hide();
var retrievedObject = linkData[linkData.length-1];
this.src_switch =retrievedObject.source_switch;
this.src_switch_name =retrievedObject.source_switch_name;
this.src_port =retrievedObject.src_port;
this.dst_switch =retrievedObject.target_switch;
this.dst_switch_name =retrievedObject.target_switch_name;
this.dst_port =retrievedObject.dst_port;
this.speed = retrievedObject.speed;
this.max_bandwidth = retrievedObject.max_bandwidth;
this.default_max_bandwidth = retrievedObject.default_max_bandwidth;
this.latency = retrievedObject.latency;
this.state = retrievedObject.state;
this.available_bandwidth = retrievedObject.available_bandwidth;
this.under_maintenance = retrievedObject.under_maintenance;
this.evacuate = retrievedObject.evacuate;
this.clipBoardItems = Object.assign(this.clipBoardItems,{
sourceSwitchName: retrievedObject.source_switch_name,
sourceSwitch: retrievedObject.source_switch,
targetSwitchName: retrievedObject.target_switch_name,
targetSwitch: retrievedObject.target_switch
});
this.islListService.getIslDetail(this.src_switch, this.src_port, this.dst_switch, this.dst_port).subscribe((data : any) =>{
if(data!= null){
this.detailDataObservable = data;
this.islForm = this.islFormBuiler.group({
cost: [this.detailDataObservable.cost, Validators.min(0)],
max_bandwidth:[this.max_bandwidth,Validators.min(0)]
});
}
else{
this.detailDataObservable = {
"props": {
"cost": "-"
}
};
this.islForm = this.islFormBuiler.group({
cost: [this.detailDataObservable.cost, Validators.min(0)],
max_bandwidth:[this.max_bandwidth,Validators.min(0)]
});
}
},error=>{
this.toastr.error("API did not return Cost data.",'Error');
});
}else{
this.loaderService.hide();
this.toastr.error("No ISL Found",'Error');
this.router.navigate([
"/isl"
]);
}
// this.setForwardLatency();
this.loadGraphData();
},error =>{
this.loaderService.hide();
this.toastr.error("No ISL Found",'Error');
this.router.navigate([
"/isl"
]);
})
}
refreshIslFlows(){
this.getIslFlowList();
}
getIslFlowList(){
this.loadingData = true;
let query = {src_switch:this.src_switch,src_port:this.src_port,dst_switch:this.dst_switch,dst_port:this.dst_port};
this.loaderService.show("Loading ISL Flows");
this.islDetailService.getISLFlowsList(query).subscribe((data : Array<object>) =>{
this.dataSet = data || [];
if(this.dataSet.length == 0){
this.toastr.info("No ISL Flows Available",'Information');
}else{
localStorage.setItem('flows',JSON.stringify(data));
}
this.loadingData = false;
},error=>{
this.toastr.info("No ISL Flows Available",'Information');
this.loaderService.hide();
this.loadingData = false;
this.dataSet = [];
});
}
maskSwitchId(switchType, e){
if(switchType === 'source'){
if(e.target.checked){
this.src_switch = this.maskPipe.transform(this.src_switch,'legacy');
}else{
this.src_switch = this.maskPipe.transform(this.src_switch,'kilda');
}
}
if(switchType === 'destination'){
if(e.target.checked){
this.dst_switch= this.maskPipe.transform(this.dst_switch,'legacy');
}else{
this.dst_switch = this.maskPipe.transform(this.dst_switch,'kilda');
}
}
if(switchType == 'source'){
this.clipBoardItems.sourceSwitch = this.src_switch;
}else{
this.clipBoardItems.targetSwitch = this.dst_switch;
}
}
openTab(tab) {
this.openedTab = tab;
if(tab == 'graph'){
this.loadGraphData();
}else if(tab == 'flow'){
this.getIslFlowList();
}
}
showMenu(e){
e.preventDefault();
$('.clip-board-button').hide();
$('.clip-board-button').css({
top: e.pageY+'px',
left: (e.pageX-220)+'px',
"z-index":2,
}).toggle();
}
islMaintenance(e){
const modalRef = this.modalService.open(IslmaintenancemodalComponent);
modalRef.componentInstance.title = "Confirmation";
modalRef.componentInstance.isMaintenance = !this.under_maintenance;
modalRef.componentInstance.content = 'Are you sure ?';
this.under_maintenance = e.target.checked;
modalRef.result.then((response) =>{
if(!response){
this.under_maintenance = false;
}
},error => {
this.under_maintenance = false;
})
modalRef.componentInstance.emitService.subscribe(
evacuate => {
var data = {src_switch:this.src_switch,src_port:this.src_port,dst_switch:this.dst_switch,dst_port:this.dst_port,under_maintenance:e.target.checked,evacuate:evacuate};
this.islListService.islUnderMaintenance(data).subscribe(response=>{
this.toastr.success('Maintenance mode changed successful','Success');
this.under_maintenance = e.target.checked;
if(evacuate){
location.reload();
}
},error => {
this.toastr.error('Error in changing maintenance mode! ','Error');
})
},
error => {
}
);
}
evacuateIsl(e){
const modalRef = this.modalService.open(ModalconfirmationComponent);
modalRef.componentInstance.title = "Confirmation";
this.evacuate = e.target.checked;
if(this.evacuate){
modalRef.componentInstance.content = 'Are you sure you want to evacuate all flows?';
}else{
modalRef.componentInstance.content = 'Are you sure ?';
}
modalRef.result.then((response)=>{
if(response && response == true){
var data = {src_switch:this.src_switch,src_port:this.src_port,dst_switch:this.dst_switch,dst_port:this.dst_port,under_maintenance:this.under_maintenance,evacuate:e.target.checked};
this.islListService.islUnderMaintenance(data).subscribe(response=>{
this.toastr.success('All flows are evacuated successfully!','Success');
location.reload();
},error => {
this.toastr.error('Error in evacuating flows! ','Error');
})
}else{
this.evacuate = false;
}
},error => {
this.evacuate = false;
})
}
copyToClip(event, copyItem) {
this.clipboardService.copyFromContent(this.clipBoardItems[copyItem]);
}
changeDate(input, event) {
this.filterForm.controls[input].setValue(event.target.value);
setTimeout(() => {
this.loadGraphData();
}, 0);
}
ngAfterViewInit() {
this.loadGraphData();
this.filterForm.get("auto_reload").valueChanges.subscribe(value => {
if (value) {
this.filterForm
.get("auto_reload_time")
.setValidators([Validators.required, Validators.pattern("^[0-9]*")]);
} else {
this.filterForm
.get("auto_reload_time")
.setValidators([Validators.pattern("^[0-9]*")]);
if (this.autoReloadTimerId) {
clearInterval(this.autoReloadTimerId);
}
}
this.filterForm.get("auto_reload_time").setValue("");
this.filterForm.get("auto_reload_time").updateValueAndValidity();
});
this.filterForm.get("auto_reload_time").valueChanges.subscribe(value => {});
}
startAutoReload() {
let autoReloadTime = Number(
this.filterForm.controls["auto_reload_time"].value
);
if (this.filterForm.controls["auto_reload"]) {
if (this.autoReloadTimerId) {
clearInterval(this.autoReloadTimerId);
}
if(autoReloadTime){
this.autoReloadTimerId = setInterval(() => {
this.loadGraphData();
}, 1000 * autoReloadTime);
}
} else {
if (this.autoReloadTimerId) {
clearInterval(this.autoReloadTimerId);
}
}
}
get f() {
return this.filterForm.controls;
}
graphChanged(){
if(this.filterForm.controls.graph.value == "isllossforward"){
this.currentGraphName = "ISL Loss Packets Forward Graph";
this.filterForm.controls.metric.setValue("packets");
}
if(this.filterForm.controls.graph.value == "isllossreverse"){
this.currentGraphName = "ISL Loss Packets Resverse Graph";
this.filterForm.controls.metric.setValue("packets");
}
if(this.filterForm.controls.graph.value == "target"){
this.currentGraphName = "Destination Graph";
this.filterForm.controls.metric.setValue("bits");
}
if(this.filterForm.controls.graph.value == "source"){
this.currentGraphName = "Source Graph";
this.filterForm.controls.metric.setValue("bits");
}
if(this.filterForm.controls.graph.value == "latency"){
this.currentGraphName = "ISL Latency Graph";
}
if(this.filterForm.controls.graph.value == "rtt"){
this.currentGraphName = "Round Trip Latency Graph (In Seconds)";
}
this.loadGraphData();
}
getDateRange() : any {
var date = new Date();
var yesterday = new Date(date.getTime());
yesterday.setDate(date.getDate() - 1);
var fromStartDate = moment(yesterday).format("YYYY/MM/DD HH:mm:ss");
var toEndDate = moment(date).format("YYYY/MM/DD HH:mm:ss");
var utcStartDate = moment(yesterday).utc().format("YYYY/MM/DD HH:mm:ss")
var utcToEndDate = moment(date).utc().format("YYYY/MM/DD HH:mm:ss");
return { from : fromStartDate, to : toEndDate ,utcStartDate : utcStartDate, utcToEndDate : utcToEndDate };
}
changeTimezone(){
let formdata = this.filterForm.value;
let timezone = formdata.timezone;
let dateaRange = this.getDateRange();
if(timezone == "UTC"){
this.filterForm.controls['fromDate'].setValue(dateaRange.utcStartDate);
this.filterForm.controls['toDate'].setValue(dateaRange.utcToEndDate);
}else{
this.filterForm.controls['fromDate'].setValue(dateaRange.from);
this.filterForm.controls['toDate'].setValue(dateaRange.to);
}
this.loadGraphData();
}
loadGraphData(){
if(this.filterForm.value.graph === 'latency' || this.filterForm.value.graph === 'rtt'){
this.callGraphAPI();
}
else{
this.callSourceGraphAPI();
}
}
callGraphAPI(){
let formdata = this.filterForm.value;
let downsampling = formdata.download_sample;
let autoReloadTime = Number(
this.filterForm.controls["auto_reload_time"].value
);
let metric = formdata.metric;
let timezone = formdata.timezone;
let graph = formdata.graph;
if (this.filterForm.controls["auto_reload"]) {
formdata.toDate = new Date(new Date(formdata.toDate).getTime() + (autoReloadTime * 1000));
}
let convertedStartDate = moment(new Date(formdata.fromDate)).add(-60, 'seconds').utc().format("YYYY-MM-DD-HH:mm:ss");
let convertedEndDate = moment(new Date(formdata.toDate)).add(60, 'seconds').utc().format("YYYY-MM-DD-HH:mm:ss");
let startDate = moment(new Date(formdata.fromDate));
let endDate = moment(new Date(formdata.toDate));
if (
moment(new Date(formdata.fromDate)).isAfter(new Date(formdata.toDate))
) {
this.toastr.error("Start date can not be after End date", "Error");
return;
}
if (
moment(new Date(formdata.toDate)).isBefore(new Date(formdata.fromDate))
) {
this.toastr.error("To date should not be less than from date.", "Error");
return;
}
if (formdata.timezone == "UTC") {
convertedStartDate = moment(new Date(formdata.fromDate)).add(-60, 'seconds').format("YYYY-MM-DD-HH:mm:ss");
convertedEndDate = moment(new Date(formdata.toDate)).add(60, 'seconds').format("YYYY-MM-DD-HH:mm:ss");
}
this.dygraphService.getForwardGraphData(this.src_switch_kilda,
this.src_port,
this.dst_switch_kilda,
this.dst_port,
downsampling,
graph,
metric,
convertedStartDate,
convertedEndDate).subscribe((dataForward : any) =>{
this.responseGraph = [];
if(dataForward[0] !== undefined){
dataForward[0].tags.direction = "F";
if(graph == 'rtt'){
var responseData = this.commonService.convertDpsToSecond(dataForward[0]);
this.responseGraph.push(responseData);
}else{
this.responseGraph.push(dataForward[0]) ;
}
}
this.dygraphService.getBackwardGraphData(this.src_switch_kilda,
this.src_port,
this.dst_switch_kilda,
this.dst_port,
downsampling,
graph,
convertedStartDate,
convertedEndDate).subscribe((dataBackward : any) =>{
if(dataBackward[0] !== undefined){
dataBackward[0].tags.direction = "R";
if(graph == 'rtt'){
var responseData = this.commonService.convertDpsToSecond(dataBackward[0]);
this.responseGraph.push(responseData);
}else{
this.responseGraph.push(dataBackward[0]) ;
}
}
this.currentGraphData.data = this.responseGraph;
this.currentGraphData.timezone = timezone;
this.currentGraphData.startDate = moment(new Date(formdata.fromDate));
this.currentGraphData.endDate = moment(new Date(formdata.toDate));
this.newMessageDetail()
this.islDataService.currentMessage.subscribe(message => this.message = message)
this.loaderService.hide();
},error=>{
this.loaderService.hide();
this.toastr.error("Backward Graph API did not return data.",'Error');
});
},error=>{
this.loaderService.hide();
this.toastr.error("Forward Graph API did not return data.",'Error');
});
}
// setForwardLatency(){
// let formdata = this.filterForm.value;
// let downsampling = formdata.download_sample;
// let metric = 'latency';
// let graph = formdata.graph;
// let convertedStartDate = moment(new Date()).add(-300, 'seconds').utc().format("YYYY-MM-DD-HH:mm:ss");
// let convertedEndDate = moment(new Date()).add(60, 'seconds').utc().format("YYYY-MM-DD-HH:mm:ss");
// let startDate = moment(new Date()).add(-300,'seconds');
// let endDate = moment(new Date());
// if (formdata.timezone == "UTC") {
// convertedStartDate = moment(new Date()).add(-300, 'seconds').format("YYYY-MM-DD-HH:mm:ss");
// convertedEndDate = moment(new Date()).add(60, 'seconds').format("YYYY-MM-DD-HH:mm:ss");
// }
// this.islDetailService.getIslLatencyfromGraph(this.src_switch_kilda,
// this.src_port,
// this.dst_switch_kilda,
// this.dst_port,
// convertedStartDate,
// convertedEndDate,downsampling).subscribe((dataLatency : any) =>{
// this.responseGraph = [];
// if(dataLatency[0] !== undefined){
// var data =dataLatency[0].dps;
// var latencyTotal = 0;
// var dpslength = 1;
// var startDateTime = new Date(startDate).getTime() ;
// var endDateTime = new Date(endDate).getTime();
// if(dpslength)
// Object.keys(data).map(function(d,i){
// var dpsTime = new Date(Number(parseInt(d) * 1000)).getTime();
// if( dpsTime > startDateTime && dpsTime < endDateTime){
// dpslength = dpslength + 1;
// latencyTotal = latencyTotal + parseInt(data[d]);
// }
// });
// var avgLatency = latencyTotal / dpslength;
// this.latency = avgLatency.toFixed(0).toString();
// }
// },error=>{
// console.log('Error in getting latency');
// });
// }
callSourceGraphAPI(){
let formdata = this.filterForm.value;
let downsampling = formdata.download_sample;
let metric = formdata.metric;
let timezone = formdata.timezone;
let graph = formdata.graph;
let convertedStartDate = moment(new Date(formdata.fromDate)).add(-60, 'seconds').utc().format("YYYY-MM-DD-HH:mm:ss");
let convertedEndDate = moment(new Date(formdata.toDate)).add(60, 'seconds').utc().format("YYYY-MM-DD-HH:mm:ss");
let startDate = moment(new Date(formdata.fromDate));
let endDate = moment(new Date(formdata.toDate));
if (
moment(new Date(formdata.fromDate)).isAfter(new Date(formdata.toDate))
) {
this.toastr.error("Start date can not be after End date", "Error");
return;
}
if (
moment(new Date(formdata.toDate)).isBefore(new Date(formdata.fromDate))
) {
this.toastr.error("To date should not be less than from date.", "Error");
return;
}
if (formdata.timezone == "UTC") {
convertedStartDate = moment(new Date(formdata.fromDate)).add(-60, 'seconds').format("YYYY-MM-DD-HH:mm:ss");
convertedEndDate = moment(new Date(formdata.toDate)).add(60, 'seconds').format("YYYY-MM-DD-HH:mm:ss");
}
this.dygraphService.getForwardGraphData(this.src_switch_kilda,
this.src_port,
this.dst_switch_kilda,
this.dst_port,
downsampling,
graph,
metric,
convertedStartDate,
convertedEndDate).subscribe((dataForward : any) =>{
this.responseGraph = [];
if(dataForward[0] !== undefined){
dataForward[0].tags.direction = "F";
this.responseGraph.push(dataForward[0]) ;
}
if(dataForward[1] !== undefined){
dataForward[1].tags.direction = "R";
this.responseGraph.push(dataForward[1]) ;
}
this.currentGraphData.data = this.responseGraph;
this.currentGraphData.timezone = timezone;
this.currentGraphData.startDate = moment(new Date(formdata.fromDate));
this.currentGraphData.endDate = moment(new Date(formdata.toDate));
this.loaderService.hide();
this.newMessageDetail()
this.islDataService.currentMessage.subscribe(message => this.message = message)
},error=>{
this.loaderService.hide();
this.toastr.error("Backward Graph API did not return data.",'Error');
});
}
editCost(){
this.showCostEditing = true;
if(this.detailDataObservable.props.cost == "-"){
this.detailDataObservable.props.cost = "";
}
this.islForm.controls["cost"].setValue(
this.detailDataObservable.props.cost
);
}
editMaxbandwidth(){
this.showBandwidthEditing = true;
this.islForm.controls["max_bandwidth"].setValue(this.convertInMB(this.max_bandwidth));
}
saveEditedBandwidth(){
if (this.islForm.invalid) {
this.toastr.error("Please enter valid value for Max. Bandwidth.");
return;
}
const modalRef = this.modalService.open(ModalconfirmationComponent);
modalRef.componentInstance.title = "Confirmation";
modalRef.componentInstance.content = 'Are you sure you want to change the Max Bandwidth?';
modalRef.result.then((response) => {
if(response && response == true){
this.loaderService.show("Updating ISL max bandwidth");
let costValue = this.convertToByteFromMB(this.islForm.value.max_bandwidth);
var data = {max_bandwidth:costValue};
this.islListService.updateIslBandWidth(data,this.src_switch, this.src_port, this.dst_switch, this.dst_port).subscribe((response: any) => {
this.loaderService.hide();
this.toastr.success("ISL Bandwidth updated successfully!",'Success');
this.showBandwidthEditing = false;
this.max_bandwidth = costValue;
this.islForm.controls["max_bandwidth"].setValue(costValue);
},error => {
this.showBandwidthEditing = false;
if(error.status == '500'){
this.toastr.error(error.error['error-message'],'Error! ');
}else{
this.toastr.error("Error in updating ISL Bandwidth!",'Error');
}
})
}
});
}
cancelEditedBandwidth(){
this.showBandwidthEditing = false;
}
saveEditedCost(){
if (this.islForm.invalid) {
this.toastr.error("Please enter valid value for ISL cost.");
return;
}
const modalRef = this.modalService.open(ModalconfirmationComponent);
modalRef.componentInstance.title = "Confirmation";
modalRef.componentInstance.content = 'Are you sure you want to change the cost?';
modalRef.result.then((response) => {
if(response && response == true){
this.loaderService.show("Updating ISL cost");
let costValue = this.islForm.value.cost;
this.islListService.updateCost(this.src_switch, this.src_port, this.dst_switch, this.dst_port, costValue).subscribe((status: any) => {
this.loaderService.hide();
if(typeof(status.successes)!=='undefined' && status.successes > 0){
this.toastr.success("ISL cost updated successfully!",'Success');
this.showCostEditing = false;
this.detailDataObservable.props.cost = costValue;
this.islForm.controls["cost"].setValue(costValue);
}else if(typeof(status.failures)!=='undefined' && status.failures > 0){
this.toastr.error("Error in updating ISL cost!",'Error');
this.showCostEditing = false;
}
if(this.detailDataObservable.props.cost == ""){
this.detailDataObservable.props.cost = "-";
}
},error => {
this.showCostEditing = false;
if(error.status == '500'){
this.toastr.error(error.error['error-message'],'Error! ');
}else{
this.toastr.error("Error in updating ISL cost!",'Error');
}
})
}
});
}
deleteISL(){
let is2FaEnabled = localStorage.getItem('is2FaEnabled')
var self = this;
const modalReff = this.modalService.open(ModalconfirmationComponent);
modalReff.componentInstance.title = "Delete ISL";
modalReff.componentInstance.content = 'Are you sure you want to perform delete action ?';
modalReff.result.then((response) => {
if(response && response == true){
if(is2FaEnabled == 'true'){
const modalRef = this.modalService.open(OtpComponent);
modalRef.componentInstance.emitService.subscribe(
otp => {
if (otp) {
this.loaderService.show("Deleting ISL");
var data = {
src_switch:this.src_switch,
src_port:this.src_port,
dst_switch:this.dst_switch,
dst_port:this.dst_port,
code:otp
}
this.modalService.dismissAll();
this.islListService.deleteIsl(data,response => {
this.toastr.success("ISL deleted successfully!", "Success!");
this.loaderService.hide();
localStorage.removeItem('ISL_LIST');
setTimeout(function(){
self.router.navigate(["/isl"]);
},100);
}, error => {
this.loaderService.hide();
var message = (error && error['error-auxiliary-message']) ? error['error-auxiliary-message'] :'Error in Isl Deletion!';
this.toastr.error(message, "Error!");
})
} else {
this.toastr.error("Unable to detect OTP", "Error!");
}
},
error => {
}
);
}else{
const modalRef2 = this.modalService.open(ModalComponent);
modalRef2.componentInstance.title = "Warning";
modalRef2.componentInstance.content = 'You are not authorised to delete the ISL.';
}
}
});
}
cancelEditedCost(){
this.showCostEditing = false;
if(this.detailDataObservable.props.cost == ""){
this.detailDataObservable.props.cost = "-";
}
}
zoomHandler=(event, x,y,z)=>{
let formdata = this.filterForm.value;
if(formdata.timezone == 'UTC'){
var startDate = moment(new Date(event.minX)).utc().format("YYYY/MM/DD HH:mm:ss");
var endDate = moment( new Date(event.maxX)).utc().format("YYYY/MM/DD HH:mm:ss");
this.filterForm.controls['fromDate'].setValue(startDate);
this.filterForm.controls['toDate'].setValue(endDate);
}else{
var startDate = moment(new Date(event.minX)).format("YYYY/MM/DD HH:mm:ss");
var endDate = moment( new Date(event.maxX)).format("YYYY/MM/DD HH:mm:ss");
this.filterForm.controls['fromDate'].setValue(startDate);
this.filterForm.controls['toDate'].setValue(endDate);
}
}
convertInMB(value) {
value = parseInt(value);
if (value === "" || value == undefined) {
return "-";
} else {
return (value / 1000);
}
}
convertToByteFromMB(value){
value = parseInt(value);
return (value * 1000);
}
ngOnDestroy(){
if (this.autoReloadTimerId) {
clearInterval(this.autoReloadTimerId);
}
}
}
|
FeatureToggleStudy/open-kilda
|
services/src/openkilda-gui/ui/src/app/common/services/flowpath.service.ts
|
import { Injectable } from '@angular/core';
import { CommonService } from './common.service';
import * as d3 from "d3";
import { environment } from "src/environments/environment";
import { Subject } from 'rxjs';
import { Router } from '@angular/router';
@Injectable({
providedIn: 'root'
})
export class FlowpathService {
forwardPathLoaded :boolean = false;
reversepathLoaded : boolean = false;
forwardpathLoadedChange: Subject<boolean> = new Subject<boolean>();
reversepathLoadedChange: Subject<boolean> = new Subject<boolean>();
diverseGroupCommonSwitch:any = [];
diverseGroupCommonSwitchReverse:any = [];
graphOptions = {
radius: 35,
text_center: false,
nominal_text_size: 10,
nominal_base_node_size: 40,
nominal_stroke: 1.5,
max_stroke: 4.5,
max_base_node_size: 36,
max_text_size: 24
};
min_zoom = 0.15;
max_zoom = 3;
zoomStep = 0.15;
simulationArr = {};
zoomArr = {};
zoomLevelArr = {};
constructor(private commonService:CommonService,
private router:Router
) { }
setCommonSwitch (type,data){
if(type=='forward'){
this.diverseGroupCommonSwitch= data;
}else{
this.diverseGroupCommonSwitchReverse= data;
}
}
getcommonSwitches(type){
if(type=='forward'){
return this.diverseGroupCommonSwitch;
}else{
return this.diverseGroupCommonSwitchReverse;
}
}
loadIslDetail(src_switch,src_port,dst_switch,dst_port){
this.router.navigate(["/isl/switch/isl/"+src_switch+"/"+src_port+"/"+dst_switch+"/"+dst_port]);
}
loadSwitchDetail(switchId){
this.router.navigate(["/switches/details/" + switchId]);
}
forwardLoaderChange(){
this.forwardPathLoaded = false;
this.forwardpathLoadedChange.next(this.forwardPathLoaded);
}
reverseLoaderChange(){
this.reversepathLoaded = false;
this.reversepathLoadedChange.next(this.reversepathLoaded);
}
horizontallyBound = (parentDiv, childDiv) => {
let parentRect: any = parentDiv.getBoundingClientRect();
let childRect: any = childDiv.getBoundingClientRect();
return (
parentRect.left <= childRect.left && parentRect.right >= childRect.right
);
};
initSimulation(nodes,links,svgElement,graphWrapper,type,positions,hoverTextID,showValueID,hideValueID){
var linksSourceArr = [];
var self = this;
if (links.length > 0) {
try {
var result = this.commonService.groupBy(links, function(item) {
return [item.source, item.target];
});
for (var i = 0, len = result.length; i < len; i++) {
var row = result[i];
if (row.length >= 1) {
for (var j = 0, len1 = row.length; j < len1; j++) {
var key = row[j].source.switch_id+ "_" + row[j].target.switch_id;
var key1 = row[j].target.switch_id + "_" + row[j].source.switch_id;
var prcessKey = ( linksSourceArr && typeof linksSourceArr[key] !== "undefined") ? key:key1;
if (typeof linksSourceArr[prcessKey] !== "undefined") {
linksSourceArr[prcessKey].push(row[j]);
} else {
linksSourceArr[key] = [];
linksSourceArr[key].push(row[j]);
}
}
}
}
} catch (e) {}
}
var processedlinks = this.processLinks(nodes,links);
var zoomLevel = 0.45;
svgElement.html("");
var width = $("#"+graphWrapper)[0].clientWidth || window.innerWidth;
var height = svgElement.attr('height');
svgElement.style('cursor','move');
svgElement.attr("width",width);
svgElement.attr("height",height);
var g = svgElement.append("g");
var graphLinkGroup = g.append("g").attr("id", `links`).attr("class", "links");
var graphNodeGroup = g.append('g').attr("class",".nodes").attr("id","nodes");
var size = d3
.scalePow()
.exponent(1)
.domain(d3.range(1));
var zoom = this.zoomArr[type] = d3
.zoom()
.scaleExtent([this.min_zoom, this.max_zoom])
.extent([[0, 0], [width - 200, height-50]])
.on("zoom", () => {
zoomLevel = Math.round(d3.event.transform.k*100)/100;
self.zoomLevelArr[type] = zoomLevel;
g.attr(
"transform",
"translate(" +
d3.event.transform.x +
"," +
d3.event.transform.y +
") scale(" +
d3.event.transform.k +
")"
);
});
var mLinkNum = this.setLinkIndexAndNum(processedlinks);
var forceSimulation = d3
.forceSimulation()
.velocityDecay(0.2)
.force('collision', d3.forceCollide().radius(function(d) {
return 20;
}))
.force("charge_force",d3.forceManyBody().strength(-1000))
.force("xPos", d3.forceX(width /2))
.force("yPos", d3.forceY(height / 2));
forceSimulation.nodes(nodes);
forceSimulation.force("link", d3.forceLink().links(processedlinks).distance((d:any)=>{
let distance = 20;
if(d.type=='isl'){
distance = 150;
}
return distance;
}).strength(0.1));
var graphNode = this.insertNodes(graphNodeGroup,nodes,type,size,hoverTextID,showValueID);
var graphLink = this.insertLinks(graphWrapper,graphLinkGroup,processedlinks,type,hoverTextID,showValueID,hideValueID);
forceSimulation.on("tick", () => {
this.repositionNodes(graphNode,positions);
this.tick(graphLink,graphNode,linksSourceArr,mLinkNum);
});
svgElement.call(zoom);
svgElement.on("dblclick.zoom", null);
forceSimulation.restart();
forceSimulation.on("end",()=>{
this.zoomFit(g,svgElement,zoomLevel,zoom,nodes,type);
});
this.simulationArr[type] = forceSimulation;
}
repositionNodes = (graphNode,positions) => {
graphNode.attr("transform", function(d: any) {
try {
d.x = positions[d.switch_id][0];
d.y = positions[d.switch_id][1];
} catch (e) {}
if (typeof(d.x) != 'undefined' && typeof(d.y)!='undefined'){
return "translate(" + d.x + "," + d.y + ")";
}
});
};
zoomFit = (g,svgElement,zoomLevel,zoom,nodes,type) => {
var bounds = g.node().getBBox();
var parent = g.node().parentElement;
var fullWidth = parent.clientWidth || parent.parentNode.clientWidth || $(parent).width(),
fullHeight = parent.clientHeight || parent.parentNode.clientHeight || $(parent).height();
var width = bounds.width,
height = bounds.height;
var midX = (bounds.x + width) / 2,
midY = (bounds.y + height) / 2;
if (width == 0 || height == 0) return;
var scale = zoomLevel / Math.max(width / fullWidth, height / fullHeight);
if(nodes.length >= 70){
var translate = [(fullWidth/2 - scale * midX)/scale, (fullHeight/2 - scale * midY)/scale];
}else{
var translate = [(fullWidth / 2 - scale * midX) , (fullHeight/2 - scale * midY) ];
}
let newtranformation = d3.zoomIdentity
.scale(scale)
.translate(translate[0], translate[1]);
svgElement.transition().duration(300).call(zoom.transform, newtranformation);
if(type=='forwardDiverse' || type=='forward'){
this.forwardLoaderChange();
}else{
this.reverseLoaderChange();
}
}
zoomFn(direction,svgElement,type){
var simulation = this.simulationArr[type];
var zoom = this.zoomArr[type];
var zoomLevel = this.zoomLevelArr[type];
if (direction == 1) {
simulation.stop();
if (zoomLevel + this.zoomStep <= this.max_zoom) {
svgElement
.transition()
.duration(350)
.call(zoom.scaleTo, zoomLevel + this.zoomStep);
}
} else if (direction == -1) {
simulation.stop();
if (zoomLevel - this.zoomStep >= this.min_zoom) {
svgElement
.transition()
.duration(350)
.call(zoom.scaleTo, zoomLevel - this.zoomStep);
}
}
};
processLinks(nodes,links){
var nodelength = nodes.length;
var linklength = links.length;
for (var i = 0; i < nodelength; i++) {
for (var j = 0; j < linklength; j++) {
if (
nodes[i].switch_id == links[j]["source"]["switch_id"] &&
nodes[i].switch_id == links[j]["target"]["switch_id"]
) {
links[j].source = i;
links[j].target = i;
} else {
if (nodes[i].switch_id == links[j]["source"]["switch_id"]) {
links[j].source = i;
} else if (
nodes[i].switch_id == links[j]["target"]["switch_id"]
) {
links[j].target = i;
}
}
}
}
return links;
}
generatePositionForNodes(element,nodes){
var positions = [];
var yValue = element[0].clientTop;
var xValue = element[0].clientLeft;
if(yValue == 0){
yValue = 100;
}
if(xValue == 0){
xValue = 150;
}
var maxLimit = element[0].clientWidth;
var reverseXvalue = element[0].clientWidth;
var reverseYvalue = element[0].clientTop + 200;
for(var i = 0; i < nodes.length; i++){
positions[nodes[i].switch_id] = [];
var arr = nodes[i].switch_id.split("_");
var arr1 = [];
if(i > 0){
arr1 = nodes[i-1].switch_id.split("_");
}
var isSwitch = false;
if(typeof(arr[1]) == 'undefined'){
isSwitch = true;
}
var isIslPort = false;
if(typeof(arr[1])!='undefined' && typeof(arr1[1])!='undefined'){
isIslPort = true;
}
if(xValue < maxLimit){
positions[nodes[i].switch_id][0] = xValue ;
positions[nodes[i].switch_id][1] = yValue;
if(isSwitch){
positions[nodes[i].switch_id][1] = positions[nodes[i].switch_id][1] - 50;
}
if(isIslPort){
xValue = xValue + 150;
positions[nodes[i].switch_id][0] = xValue;
}
xValue = xValue + 80;
}else if(xValue >= maxLimit && reverseXvalue > 100){
positions[nodes[i].switch_id][0] = reverseXvalue;
positions[nodes[i].switch_id][1] = reverseYvalue;
if(isSwitch){
positions[nodes[i].switch_id][1] = positions[nodes[i].switch_id][1] - 50;
}
if(isIslPort){
reverseXvalue = reverseXvalue - 150;
positions[nodes[i].switch_id][0] = reverseXvalue;
}
reverseXvalue = reverseXvalue - 80;
}else{
yValue = reverseYvalue + 100;
xValue = element[0].clientLeft;
maxLimit = element[0].clientWidth;
reverseXvalue = element[0].clientWidth;
reverseYvalue = yValue + 200;
positions[nodes[i].switch_id][0] = xValue ;
positions[nodes[i].switch_id][1] = yValue;
if(isSwitch){
positions[nodes[i].switch_id][1] = positions[nodes[i].switch_id][1] - 50;
}
if(isIslPort){
xValue = xValue + 150;
positions[nodes[i].switch_id][0] = xValue;
}
}
}
return positions;
}
insertLinks(graphWrapper,graphLinkGroup,links,type,hoverTextID,showValueID,hideValueID){
var ref = this;
let graphLinksData = graphLinkGroup.selectAll("path.link").data(links);
let graphNewLink = graphLinksData
.enter()
.append("path")
.attr("class", function(d, index) {
return "link physical "+type+"_link_"+d.flow;
})
.attr("id", (d, index) => {
return type+"_link" + index;
}).attr('stroke-width', (d) =>{ return 4.5; }).attr("stroke", function(d, index) {
return d.colourCode;
}).attr("cursor","pointer")
.on('mouseover',function(d,index){
if(type == 'forwardDiverse' || type =='reverseDiverse' ){
var element = document.getElementById(type+"_link" + index);
var classes = element.getAttribute("class");
classes = classes + " overlay";
element.setAttribute('class',classes);
var rec: any = element.getBoundingClientRect();
$('#'+hideValueID).css('display','none');
$("#"+hoverTextID).css("display", "block");
$('#'+showValueID).html(d.flow);
$('#'+showValueID).css('display','block');
$(element).on("mousemove", function(e) {
$("#"+hoverTextID).css("top", (e.pageY-50) + "px");
$("#"+hoverTextID).css("left", (e.pageX-60) + "px");
var bound = ref.horizontallyBound(
document.getElementById(graphWrapper),
document.getElementById(hoverTextID)
);
if (bound) {
$("#"+hoverTextID).removeClass("left");
} else {
var left = e.pageX; // subtract width of tooltip box + circle radius
$("#"+hoverTextID).css("left", left + "px");
$("#"+hoverTextID).addClass("left");
}
});
}
}).on('mouseout',function(d,index){
var element = document.getElementById("link" + index);
$('#'+type+'_link' + index).removeClass('overlay');
$("#"+hoverTextID).css("display", "none");
}).on('click',function(d){
if(d.type == 'isl'){
var src_switch = d.source_detail.id,
src_port = d.source_detail.out_port,
dst_switch = d.target_detail.id,
dst_port = d.target_detail.in_port;
ref.loadIslDetail(src_switch,src_port,dst_switch,dst_port);
}
});
graphLinksData.exit().remove();
return graphNewLink.merge(graphLinksData);
}
insertNodes(graphNodeGroup,nodes,type,size,hoverTextID,showValueID){
let ref = this;
let graphNodesData = graphNodeGroup.selectAll("g.node").data(nodes,d=>d.switch_id);
let graphNodeElement = graphNodesData.enter().append("g")
.attr("class", "node");
graphNodesData.exit().remove();
graphNodeElement.append("circle").attr("r",function(d){
var portNumber = d.switch_id.split("_")[2];
if(typeof(portNumber)!='undefined'){
return 20;
}else{
return ref.graphOptions.radius
}
})
.attr("class", function(d, index) {
var classes = "circle blue";
return classes;
})
.attr("id", function(d, index) {
var valuesArr = d.switch_id.split("_");
var switch_id = (typeof(valuesArr[1]) == 'undefined') ? d.switch_id:d.index;
return type+"_circle_" + switch_id;
}).style("cursor", "pointer");
let text = graphNodeElement
.append("text")
.attr("dy",function(d){
var portNumber = d.switch_id.split("_")[2];
if(typeof(portNumber)!='undefined'){
return '.10em';
}
return ".35em";
})
.style("font-size",(d) =>{
var portNumber = d.switch_id.split("_")[2];
if(typeof(portNumber)!='undefined'){
return 20;
}
return this.graphOptions.nominal_text_size + "px";
})
.attr("class", "switchname");
if (this.graphOptions.text_center) {
text
.text(function(d) {
var portNumber = d.switch_id.split("_")[2];
if(typeof(portNumber)!='undefined'){
return portNumber;
}
return d.switch_id;
})
.style("text-anchor", "middle");
} else {
text
.attr("dx", function(d) {
var portNumber = d.switch_id.split("_")[2];
if(typeof(portNumber)!='undefined'){
return -10;
}
return size(d.size) || ref.graphOptions.nominal_base_node_size;
})
.text(function(d) {
var portNumber = d.switch_id.split("_")[2];
if(typeof(portNumber)!='undefined'){
return portNumber;
}
return d.switch_id;
});
}
let images = graphNodeElement.append("svg:image")
.attr("xlink:href", function(d) {
var portNumber = d.switch_id.split("_")[2];
if(typeof(portNumber)!='undefined'){
return '';
}
return environment.assetsPath + "/images/switch.png";
})
.attr("x", function(d) {
return -29;
})
.attr("y", function(d) {
return -29;
})
.attr("height", 58)
.attr("width", 58)
.attr("id", function(d, index) {
return type+"_image_" + index;
}).on('mouseover',function(d){
var valuesArr = d.switch_id.split("_");
var switch_id = (typeof(valuesArr[1]) == 'undefined') ? d.switch_id:d.index;
var element = document.getElementById( type+"_circle_"+ switch_id);
var classes = 'circle blue hover';
element.setAttribute('class',classes);
var portNumber = d.switch_id.split("_")[2];
var switch_id = d.switch_id.split("_")[1];
if(typeof(portNumber)!='undefined'){
var rec: any = element.getBoundingClientRect();
$("#"+hoverTextID).css("top", (rec.y - 40) + "px");
$("#"+hoverTextID).css("left", (rec.x - 60) + "px");
$("#"+hoverTextID).css("display", "block");
$('#'+showValueID).html(switch_id);
$('#'+showValueID).css('display','block');
}
}).on('mouseout',function(d){
var valuesArr = d.switch_id.split("_");
var switch_id = (typeof(valuesArr[1]) == 'undefined') ? d.switch_id:d.index;
var element = document.getElementById( type+"_circle_"+ switch_id);
var classes = 'circle blue';
element.setAttribute('class',classes);
var portNumber = d.switch_id.split("_")[2];
if(typeof(portNumber)!='undefined'){
$("#"+hoverTextID).css("display", "none");
}
}).on('click',function(d){
var portNumber = d.switch_id.split("_")[2];
var switch_id = d.switch_id.split("_")[1];
if(typeof(portNumber)=='undefined'){
ref.loadSwitchDetail(switch_id);
}
});;
return graphNodeElement.merge(graphNodesData);
}
isObjEquivalent(a, b) {
// Create arrays of property names
var aProps = Object.getOwnPropertyNames(a);
var bProps = Object.getOwnPropertyNames(b);
if (aProps.length != bProps.length) {
return false;
}
for (var i = 0; i < aProps.length; i++) {
var propName = aProps[i];
if (a[propName] !== b[propName]) {
return false;
}
}
return true;
}
setLinkIndexAndNum(links) {
var mLinkNum = [];
for (var i = 0; i < links.length; i++) {
if (
i != 0 &&
links[i].source == links[i - 1].source.switch_id &&
links[i].target == links[i - 1].target.switch_id
) {
links[i].linkindex = links[i - 1].linkindex + 1;
} else {
links[i].linkindex = 1;
}
// save the total number of links between two nodes
if (
mLinkNum[links[i].target.switch_id + "," + links[i].source.switch_id] !==
undefined
) {
mLinkNum[
links[i].target.switch_id + "," + links[i].source.switch_id
] = links[i].linkindex;
} else {
mLinkNum[
links[i].source.switch_id + "," + links[i].target.switch_id
] = links[i].linkindex;
}
}
return mLinkNum;
}
tick(graphLink,graphNode,linksSourceArr,mLinkNum){
var ref = this;
graphLink.attr("d", d => {
var islCount = 0;
var matchedIndex = 1;
var key = d.source.switch_id + "_" + d.target.switch_id;
var key1 = d.target.switch_id + "_" + d.source.switch_id;
var processKey = ( linksSourceArr && typeof linksSourceArr[key] !== "undefined") ? key:key1;
if (
linksSourceArr &&
typeof linksSourceArr[processKey] !== "undefined"
) {
islCount = linksSourceArr[processKey].length;
}
if (islCount > 1) {
linksSourceArr[processKey].map(function(o, i) {
if (ref.isObjEquivalent(o, d)) {
matchedIndex = i + 1;
return;
}
});
}
var x1 = d.source.x,
y1 = d.source.y,
x2 = d.target.x,
y2 = d.target.y,
dx = x2 - x1,
dy = y2 - y1,
dr = Math.sqrt(dx * dx + dy * dy);
var lTotalLinkNum =
mLinkNum[d.source.index + "," + d.target.index] ||
mLinkNum[d.target.index + "," + d.source.index];
if (lTotalLinkNum > 1) {
dr = dr / (1 + (1 / lTotalLinkNum) * (d.linkindex - 1));
}
if (islCount == 1) {
return (
"M" +
d.source.x +
"," +
d.source.y +
"L" +
d.target.x +
"," +
d.target.y
);
} else {
if (islCount % 2 != 0 && matchedIndex == 1) {
return (
"M" +
d.source.x +
"," +
d.source.y +
"L" +
d.target.x +
"," +
d.target.y
);
} else if (matchedIndex % 2 == 0) {
return (
"M" +
d.source.x +
"," +
d.source.y +
"A" +
dr +
"," +
dr +
" 0 0 1," +
d.target.x +
"," +
d.target.y +
"A" +
dr +
"," +
dr +
" 0 0 0," +
d.source.x +
"," +
d.source.y
);
} else {
return (
"M" +
d.source.x +
"," +
d.source.y +
"A" +
dr +
"," +
dr +
" 0 0 1," +
d.target.x +
"," +
d.target.y +
"A" +
dr +
"," +
dr +
" 0 0 0," +
d.source.x +
"," +
d.source.y
);
}
}
});
graphNode.attr("transform", function(d) {
if (typeof(d.x) !='undefined' && typeof(d.y)!='undefined') {
return "translate(" + d.x + "," + d.y + ")";
}
});
}
}
|
FeatureToggleStudy/open-kilda
|
services/src/openkilda-gui/ui/src/app/common/components/sidebar/sidebar.component.ts
|
import { Component, OnInit } from '@angular/core';
import { Router, NavigationEnd } from '@angular/router';
import { CommonService } from '../../services/common.service';
@Component({
selector: 'app-sidebar',
templateUrl: './sidebar.component.html',
styleUrls: ['./sidebar.component.css']
})
export class SidebarComponent implements OnInit {
currentUrl :any = '';
constructor(private router: Router, public commonService: CommonService) {
this.router.events.subscribe((_:NavigationEnd) => {
this.currentUrl = router.url
if(!this.currentUrl.includes('/flows')){
localStorage.removeItem('flows');
localStorage.removeItem('haslinkStoreSetting');
localStorage.removeItem('linkStoreSetting');
localStorage.removeItem('linkStoreStatusList');
localStorage.removeItem('activeFlowStatusFilter');
localStorage.removeItem('filterFlag');
localStorage.removeItem('flowsinventory');
}
if(!this.currentUrl.includes('/isl')) {
localStorage.removeItem('linkData');
localStorage.removeItem('ISL_LIST');
}
if(!this.currentUrl.includes('/switches')) {
localStorage.removeItem('SWITCHES_LIST');
localStorage.removeItem('SWITCHES_LIST_ALL');
localStorage.removeItem('switchPortDetail');
}
if(!this.currentUrl.includes('/port')) {
localStorage.removeItem('portFlows');
localStorage.removeItem('portFlowInventory');
}
this.commonService.setCurrentUrl(router.url);
});
}
ngOnInit() {}
urlmatch(url){
return this.currentUrl.includes(url);
}
closeSidebar() {
jQuery('body').removeClass('mini-sidebar');
localStorage.removeItem('sidebarToggled');
}
openSidebar() {
jQuery('body').addClass('mini-sidebar');
localStorage.setItem('sidebarToggled','1');
}
}
|
FeatureToggleStudy/open-kilda
|
services/src/openkilda-gui/ui/src/app/modules/flows/flow-path/flow-path.component.ts
|
<reponame>FeatureToggleStudy/open-kilda
import { Component, OnInit, Input, OnDestroy } from "@angular/core";
import { FlowsService } from "../../../common/services/flows.service";
import { NgxSpinnerService } from "ngx-spinner";
import { LoaderService } from "../../../common/services/loader.service";
import { Router } from "@angular/router";
@Component({
selector: "app-flow-path",
templateUrl: "./flow-path.component.html",
styleUrls: ["./flow-path.component.css"]
})
export class FlowPathComponent implements OnInit, OnDestroy {
@Input() flowId;
flowPathData: any;
forwardPathGraph: Boolean = false;
reversePathGraph: Boolean = false;
reversePathData = [];
forwardPathData = [];
constructor(
private flowService: FlowsService,
private loaderService: LoaderService,
private router:Router
) {}
ngOnInit() {
if (this.flowId) {
this.getFlowPath(this.flowId);
} else {
console.error("Flow Id required");
}
}
getFlowPath(flowId) {
this.loaderService.show("Loading Flow Path...");
this.flowService.getFlowPath(flowId).subscribe(
data => {
this.flowPathData = data;
this.forwardPathData = data.flowpath_forward;
this.reversePathData = data.flowpath_reverse;
this.loaderService.hide();
},
error => {
this.loaderService.hide();
}
);
}
loadIslDetail(type){
if(type=='forward'){
var src_switch = (this.forwardPathData && this.forwardPathData.length && this.forwardPathData[0]['switch_id'] ) ? this.forwardPathData[0]['switch_id']:null;
var src_port = (this.forwardPathData && this.forwardPathData.length && this.forwardPathData[0]['output_port'] ) ? this.forwardPathData[0]['output_port'] : null;
var dst_switch = (this.forwardPathData && this.forwardPathData.length && this.forwardPathData[1]['switch_id'] ) ? this.forwardPathData[1]['switch_id'] : null;
var dst_port = (this.forwardPathData && this.forwardPathData.length && this.forwardPathData[1]['output_port'] ) ? this.forwardPathData[1]['input_port'] : null;
}else if(type=='reverse'){
var src_switch = (this.reversePathData && this.reversePathData.length && this.reversePathData[0]['switch_id'] ) ? this.reversePathData[0]['switch_id']:null;
var src_port = (this.reversePathData && this.reversePathData.length && this.reversePathData[0]['output_port'] ) ? this.reversePathData[0]['output_port'] : null;
var dst_switch = (this.reversePathData && this.reversePathData.length && this.reversePathData[1]['switch_id'] ) ? this.reversePathData[1]['switch_id'] : null;
var dst_port = (this.reversePathData && this.reversePathData.length && this.reversePathData[1]['output_port'] ) ? this.reversePathData[1]['input_port'] : null;
}
this.router.navigate(["/isl/switch/isl/"+src_switch+"/"+src_port+"/"+dst_switch+"/"+dst_port]);
}
loadSwitchDetail(switchId){
this.router.navigate(["/switches/details/" + switchId]);
}
viewPathGraph(type) {
if (type == "forward") {
this.reversePathGraph = false;
this.forwardPathGraph = this.forwardPathGraph ? false : true;
} else {
this.forwardPathGraph = false;
this.reversePathGraph = this.reversePathGraph ? false : true;
}
}
ngOnDestroy(){
this.reversePathGraph = false;
this.forwardPathGraph = false;
}
}
|
opstalent/ot-ng2-oauth
|
src/oauth.module.ts
|
<gh_stars>0
import {
NgModule,
ModuleWithProviders
} from '@angular/core';
import { CommonModule } from '@angular/common';
import { OAuthService } from './services/oauth.service';
import { HttpService } from './services/http.service';
@NgModule({
imports: [
CommonModule,
]
})
export class OAuthModule {
static forRoot(): ModuleWithProviders {
return {
ngModule: OAuthModule,
providers: [
OAuthService,
HttpService,
]
};
}
}
|
opstalent/ot-ng2-oauth
|
src/services/oauth.service.ts
|
<reponame>opstalent/ot-ng2-oauth<filename>src/services/oauth.service.ts
import {
Injectable,
Inject
} from '@angular/core';
import {
Http,
Headers,
RequestOptions,
Response
} from '@angular/http';
import { Observable } from 'rxjs/Rx';
import {
IAuthConfig,
AUTH_CONFIG
} from '../models/opAuthConfig';
import { OAuthToken } from './token.service';
import { forOwn } from 'lodash';
/**
*
*
* @export
* @class OAuthService
*/
@Injectable()
export class OAuthService {
/**
*
*
* @protected
* @type {string}
* @memberOf OAuthService
*/
protected clientId: string;
/**
*
*
* @protected
* @type {string}
* @memberOf OAuthService
*/
protected clientSecret: string;
/**
*
*
* @protected
* @type {string}
* @memberOf OAuthService
*/
protected baseUrl: string;
/**
*
*
* @protected
* @type {string}
* @memberOf OAuthService
*/
protected grantPath: string;
/**
*
*
* @protected
* @type {string}
* @memberOf OAuthService
*/
protected revokePath: string;
/**
* Creates an instance of OAuthService.
*
* @param {Http} http
* @param {IAuthConfig} authConfig
*
* @memberOf OAuthService
*/
constructor(protected http: Http, @Inject(AUTH_CONFIG)private authConfig: IAuthConfig) {
this.clientId = authConfig.clientId;
this.clientSecret = authConfig.clientSecret;
this.baseUrl = authConfig.baseUrl;
this.grantPath = authConfig.grantPath;
this.revokePath = authConfig.revokePath;
}
/**
*
*
* @returns
*
* @memberOf OAuthService
*/
isAuthenticated() {
let date = Math.floor(Date.now() / 1000);
if (OAuthToken.getToken().refresh_token === undefined && OAuthToken.getToken().date < date) {
this.getClientToken().subscribe();
return false;
}
return !!OAuthToken.getToken();
}
/**
*
*
* @param {*} [data]
* @param {*} [options]
* @returns {Observable<Response>}
*
* @memberOf OAuthService
*/
getClientToken(data?: any, options?: any): Observable<Response> {
let search = {
client_id: this.clientId,
grant_type: 'client_credentials'
};
let request = this.getRequest(search, data, options);
return this.http.post(`${this.baseUrl}${this.grantPath}`, request.body, request.options)
.map(res => {
let token = res.json();
token.date = Math.floor((Date.now() / 1000) + 3500);
OAuthToken.setToken(token);
return token;
});
}
/**
*
*
* @param {string} username
* @param {string} password
* @param {*} [data]
* @param {*} [options]
* @returns {Observable<Response>}
*
* @memberOf OAuthService
*/
getAccessToken(username: string, password: string, data?: any, options?: any): Observable<Response> {
let search = {
client_id: this.clientId,
grant_type: 'password',
username: username,
password: password
};
let request = this.getRequest(search, data, options);
return this.http.post(`${this.baseUrl}${this.grantPath}`, request.body, request.options)
.map(res => {
let token = res.json();
OAuthToken.setToken(token);
return token;
});
}
/**
*
*
* @param {*} [data]
* @param {*} [options]
* @returns {Observable<Response>}
*
* @memberOf OAuthService
*/
getRefreshToken(data?: any, options?: any): Observable<Response> {
let search = {
client_id: this.clientId,
grant_type: 'refresh_token',
refresh_token: OAuthToken.getRefreshToken()
};
let request = this.getRequest(search, data, options);
return this.http.post(`${this.baseUrl}${this.grantPath}`, request.body, request.options)
.map(res => {
let token = res.json();
OAuthToken.setToken(token);
return token;
});
}
/**
*
*
* @param {*} [data]
* @param {*} [options]
* @returns {Observable<Response>}
*
* @memberOf OAuthService
*/
revokeToken(data?: any, options?: any): Observable<Response> {
let refreshToken = OAuthToken.getRefreshToken();
let search = {
client_id: this.clientId,
token: refreshToken ? refreshToken : OAuthToken.getAccessToken(),
token_type_hint: refreshToken ? 'refresh_token' : 'access_token'
};
let request = this.getRequest(search, data, options);
return this.http.post(`${this.baseUrl}${this.revokePath}`,
request.body, request.options)
.map(res => {
let token = res.json();
OAuthToken.removeToken();
return token;
});
}
/**
*
*
* @protected
* @param {*} body
* @param {*} [data]
* @param {*} [optionsData={}]
* @returns
*
* @memberOf OAuthService
*/
protected getRequest(body: any, data?: any, optionsData: any = {}) {
if (this.clientSecret) {
body.client_secret = this.clientSecret;
}
forOwn(data, (value, key) => { body.set(key, value); });
if (!optionsData.headers) {
optionsData.headers = new Headers({'Content-Type': 'application/json'});
}
return {
body: JSON.stringify(body),
options: new RequestOptions(optionsData)
};
}
}
|
opstalent/ot-ng2-oauth
|
src/services/oauth.service.spec.ts
|
<gh_stars>0
import {
async,
inject,
TestBed
} from '@angular/core/testing';
import {
MockBackend
} from '@angular/http/testing';
import {
XHRBackend,
Response,
HttpModule
} from '@angular/http';
import { OAuthService } from './oauth.service';
import { AUTH_CONFIG } from '../models/opAuthConfig';
import 'rxjs/add/observable/of';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/do';
import 'rxjs/add/operator/toPromise';
const AuthConfigMock = {
clientId: '1',
clientSecret: '2',
baseUrl: 'games.com',
frontUrl: 'google.com',
grantPath: '/oauth/v2/token',
revokePath: '/oauth/v2/revoke',
googleMapsApiKey: 'A3'
};
describe('OAuthService', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
OAuthService,
{ provide: XHRBackend, useClass: MockBackend },
{ provide: AUTH_CONFIG, useValue: AuthConfigMock }
]
});
}));
it('can instantiate service when inject service', () => {
inject([OAuthService], (service: OAuthService) => {
expect(service instanceof OAuthService).toBe(true);
});
});
it('can instantiate service with "new"', () => {
inject([OAuthService], (service: OAuthService) => {
expect(service instanceof OAuthService).toBe(true, 'new service should be ok');
});
});
it('can provide the mockBackend as XHRBackend',
inject([XHRBackend], (backend: MockBackend) => {
expect(backend).not.toBeNull('backend should be provided');
})
);
describe('OAuthService', () => {
let service: OAuthService;
beforeEach(inject([OAuthService], (ser: OAuthService) => {
service = ser;
}));
it('should have expected access token', async(inject([], () => {
service.getClientToken().subscribe(
(data: Response) => expect(data).toBeTruthy()
);
})));
it('should have expected client token', async(inject([], () => {
let username = '<EMAIL>';
let password = '<PASSWORD>!';
service.getAccessToken(username, password).subscribe(
(data: Response) => expect(data).toBeTruthy()
);
})));
it('should not have expected client token', async(inject([], () => {
let username = '<EMAIL>';
let password = '<PASSWORD>!';
service.getAccessToken(username, password).subscribe(
data => {},
error => {
expect(error.status).toEqual(400);
}
);
})));
it('should have refresh token', async(inject([], () => {
service.getRefreshToken().subscribe(
(data: Response) => {
expect(data).toBeTruthy();
}
);
})));
});
});
|
opstalent/ot-ng2-oauth
|
src/services/http.service.spec.ts
|
<filename>src/services/http.service.spec.ts<gh_stars>0
import {
Http,
XHRBackend,
HttpModule,
Response,
ResponseOptions
} from '@angular/http';
import {
fakeAsync,
tick,
async,
inject,
TestBed
} from '@angular/core/testing';
import {
MockBackend,
MockConnection
} from '@angular/http/testing';
import { OAuthService } from './oauth.service';
import { HttpService } from './http.service';
class OAuthServiceMock {}
describe('HttpService', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [HttpModule],
providers: [
HttpService,
{ provide: XHRBackend, useClass: MockBackend },
{ provide: OAuthService, useClass: OAuthServiceMock }
]
});
}));
it('can instantiate service when inject service',
inject([HttpService], (service: HttpService) => {
expect(service instanceof HttpService).toBe(true);
}));
it('can instantiate service with "new"', inject([Http, OAuthService], (http: Http, oAuthService: OAuthService) => {
expect(http).not.toBeNull('http should be provided');
let service = new HttpService(oAuthService, http);
expect(service instanceof HttpService).toBe(true, 'new service should be ok');
}));
it('can provide the mockBackend as XHRBackend',
inject([XHRBackend], (backend: MockBackend) => {
expect(backend).not.toBeNull('backend should be provided');
}));
describe('HttpService methods', () => {
let service: HttpService;
let http: Http;
beforeEach(inject([HttpService, Http], (
ser: HttpService, httpService: Http) => {
service = ser;
http = httpService;
}));
it('should return correct value when a request is sent', inject([XHRBackend], fakeAsync((backend: MockBackend) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toBe('https://google.com');
c.mockRespond(new Response(new ResponseOptions({body: 'Whos there?'})));
});
service.request('https://google.com').subscribe(data => expect(data.text()).toEqual('Whos there?'));
tick();
})));
it('should return correct error when response is with error', inject([XHRBackend], fakeAsync((backend: MockBackend) => {
backend.connections.subscribe((c: MockConnection) => {
expect(c.request.url).toBe('https://google.com');
c.mockRespond(new Response(new ResponseOptions({status: 401, body: { error: 'invalid_grant'} })));
});
service.request('https://google.com').subscribe(data => expect(data.json()).toEqual({ error: 'invalid_grant'}));
tick();
})));
});
});
|
opstalent/ot-ng2-oauth
|
src/models/opAuthConfig.ts
|
<filename>src/models/opAuthConfig.ts<gh_stars>0
export interface IAuthConfig {
clientId: string;
clientSecret: string;
baseUrl: string;
grantPath: string;
revokePath: string;
}
export const AUTH_CONFIG = 'authConfig';
|
opstalent/ot-ng2-oauth
|
index.ts
|
export * from './src/oauth.module';
export * from './src/services/oauth.service';
export * from './src/services/http.service';
|
opstalent/ot-ng2-oauth
|
src/services/user.service.ts
|
import { Injectable } from '@angular/core';
@Injectable()
export class OAuthUser {
storageKey: string = 'oauth_user';
/**
* Retrieve user from local storage
*/
getUser(): any {
if (typeof(Storage) !== 'undefined') {
let data = localStorage.getItem(this.storageKey);
return (data) ? JSON.parse(data) : false;
}
return false;
}
/**
* Save user to local storage
*/
setUser(data: any): boolean {
if (typeof(Storage) !== 'undefined') {
localStorage.setItem(this.storageKey, JSON.stringify(data));
return true;
}
return false;
}
/**
* Remove user to local storage
*/
removeUser(): any {
if (typeof(Storage) !== 'undefined') {
localStorage.removeItem(this.storageKey);
return true;
}
return false;
}
}
|
opstalent/ot-ng2-oauth
|
src/services/http.service.ts
|
import { Injectable } from '@angular/core';
import {
Headers,
Http,
Request,
RequestOptions,
RequestOptionsArgs,
Response
} from '@angular/http';
import { OAuthService } from './oauth.service';
import { OAuthToken } from './token.service';
import {
Observable,
Observer,
Subject
} from 'rxjs/Rx';
@Injectable()
export class HttpService {
constructor(private oauth: OAuthService, private http: Http) {}
request(url: string | Request, options?: RequestOptionsArgs): Observable<Response> {
return this.intercept(url, options);
}
/**
* @param {string} url
* @param {RequestOptionsArgs} [options]
* @returns {Observable<Response>}
*
* @memberOf HttpService
*/
get(url: string, options: RequestOptionsArgs = new RequestOptions()): Observable<Response> {
options.method = 'GET';
return this.intercept(url, options);
}
/**
* @param {string} url
* @param {string} body
* @param {RequestOptionsArgs} [options]
* @returns {Observable<Response>}
*
* @memberOf HttpService
*/
post(url: string,
body: string,
options: RequestOptionsArgs = new RequestOptions()): Observable<Response> {
options.method = 'POST';
options.body = body;
options = this.setAuthorizationHeader(this.getRequestOptionArgs(options));
return this.intercept(url, options);
}
/**
* @param {string} url
* @param {string} body
* @param {RequestOptionsArgs} [options]
* @returns {Observable<Response>}
*
* @memberOf HttpService
*/
put(url: string, body: string, options: RequestOptionsArgs = new RequestOptions()): Observable<Response> {
options.method = 'PUT';
options.body = body;
options = this.setAuthorizationHeader(this.getRequestOptionArgs(options));
return this.intercept(url, options);
}
/**
*
* @param {string} url
* @param {string} body
* @param {RequestOptionsArgs} [options]
* @returns {Observable<Response>}
*
* @memberOf HttpService
*/
patch(url: string, body: string, options: RequestOptionsArgs = new RequestOptions()): Observable<Response> {
options.method = 'PATCH';
options.body = body;
return this.intercept(url, options);
}
/**
* @param {string} url
* @param {RequestOptionsArgs} [options]
* @returns {Observable<Response>}
*
* @memberOf HttpService
*/
delete(url: string, options: RequestOptionsArgs = new RequestOptions()): Observable<Response> {
options.method = 'DELETE';
return this.intercept(url, options);
}
protected setAuthorizationHeader(options: RequestOptionsArgs = new RequestOptions): RequestOptionsArgs {
if (options.headers == null) {
options.headers = new Headers();
}
if (!options.headers.has('Authorization')) {
let authHeader = OAuthToken.getAuthorizationHeader();
if (authHeader) {
options.headers.append('Authorization', OAuthToken.getAuthorizationHeader());
}
}
return options;
}
protected getRequestOptionArgs(options: RequestOptionsArgs = new RequestOptions): RequestOptionsArgs {
if (options.headers == null) {
options.headers = new Headers();
}
options.headers.append('Content-Type', 'application/json');
return options;
}
protected intercept(url: string | Request, options: RequestOptionsArgs = new RequestOptions): Observable<Response> {
return Observable.create((observer: Observer<any>) => {
if (options.headers && options.headers.has('Authorization')) {
options.headers.delete('Authorization');
}
options = this.setAuthorizationHeader(options);
this.http.request(url, options).subscribe(
(result: any) => observer.next(result),
(error: any) => observer.error(error));
}).retryWhen((errors: any) => this.errorHandler(errors, options));
}
protected errorHandler(errors: any, options?: RequestOptionsArgs): any {
return errors.switchMap((err: any) => {
if (err.status !== 401 && err.status !== 400) {
return Observable.throw(err.json());
}
let data = err.json();
if (400 === err.status && ['invalid_request', 'invalid_grant'].indexOf(data.error) !== -1) {
OAuthToken.removeToken();
return Observable.throw(err.json());
}
let hasBearerToken = err.headers.has('www-authenticate') && 0 === err.headers.get('www-authenticate').indexOf('Bearer');
if (401 === err.status && ['invalid_token', 'invalid_grant'].indexOf(data.error) !== -1 || hasBearerToken) {
let closedSubject = new Subject();
this.oauth.getRefreshToken().subscribe(
(res: Response) => closedSubject.next(res),
(error: any) => Observable.throw(error.json())
);
return <any>closedSubject;
}
return Observable.throw(err.json());
});
}
}
|
opstalent/ot-ng2-oauth
|
src/services/token.service.ts
|
import { capitalize } from 'lodash';
export class OAuthToken {
static storageKey: string = 'oauth';
/**
* Retrieve token from local storage
*/
static getToken(): any {
if (typeof(Storage) === 'undefined') {
return false;
}
let data = localStorage.getItem(this.storageKey);
return (data) ? JSON.parse(data) : false;
}
/**
* Save token to local storage
*/
static setToken(data: any): boolean {
if (typeof(Storage) !== 'undefined' && data !== undefined) {
localStorage.setItem(this.storageKey, JSON.stringify(data));
return true;
}
return false;
}
/**
* Remove token to local storage
*/
static removeToken(): any {
if (typeof(Storage) !== 'undefined') {
localStorage.removeItem(this.storageKey);
return true;
}
return false;
}
/**
* Retrieve access token from local storage
*/
static getAccessToken(): string {
return this.getToken() ? this.getToken().access_token : undefined;
}
/**
* Retrieve refresh token from local storage
*/
static getRefreshToken(): string {
return this.getToken() ? this.getToken().refresh_token : undefined;
}
/**
* Retrieve token type from local storage
*/
static getTokenType(): string {
return this.getToken() ? this.getToken().token_type : undefined;
}
/**
* Returns authorization header based on token from local storage
*/
static getAuthorizationHeader(): string {
if (!(this.getTokenType() && this.getAccessToken())) {
return;
}
return `${capitalize(this.getTokenType())} ${this.getAccessToken()}`;
}
}
|
thiessenp/chatapp-web
|
client/src/util/poll.ts
|
<gh_stars>0
/**
* e.g. use:
* useEffect(() => {
const callback:any = () => { return dispatch(getChatAction({chatId})); }
const poll = new Poll({callback});
return () => { poll.stop(); }
}, [chatId])
*/
export class Poll {
isPolling:boolean = false;
delay:number = 2000;
callback:Function;
constructor({callback, delay=2000, isAutoStart=true}) {
if (!callback) {
throw Error('Poll requires a callback');
}
this.callback = callback;
if (delay) { this.delay = delay; }
if (isAutoStart) { this.start(); }
}
start() {
this.isPolling = true;
this.doPoll();
}
stop() {
this.isPolling = false;
}
doPoll() {
if (!this.isPolling) { return; }
setTimeout(() => {
if (!this.isPolling) { return; }
this.callback();
this.doPoll();
}, this.delay);
}
}
|
thiessenp/chatapp-web
|
client/src/pages/ChatsPage/Chat.tsx
|
<reponame>thiessenp/chatapp-web
import React, {useEffect, useState} from 'react';
import {useParams} from 'react-router-dom';
import {useDispatch, useSelector} from 'react-redux';
import {Poll} from '../../util/poll';
import {requestPostMessage, requestPostMessageFiles, getChatAction, addUserTochat} from '../../store/chats';
import {Transcript} from '../../components/Transcript';
import {Roster} from '../../components/Roster';
import {Composer} from '../../components/Composer';
// NOTE: props receives an account - to join the chat
// NOTE: chatId from PATH
// NOTE: receives chats but can ALSO use a reducer
export function Chat(props) {
let {chatId} = useParams();
const dispatch = useDispatch();
const account = useSelector(state => state.account);
// TODO: could also try - useSelector(state => state.chats.find(chat=> chat.id === chatId));
const chat = useSelector(state => {
const chat = state.chats.chats.filter(chat => chat.id === chatId);
if (!chat || !chat[0]) { return state; }
return chat[0];
});
// Update Chat details on new Chat (when navigate to another chat)
useEffect(() => {
// Join The Chat (if haven't already)
if (!chat.chatUserId) {
dispatch(addUserTochat({chatId, accountId:account.id}));
}
// Get The Chat (polling)
const callback:any = () => { return dispatch(getChatAction({chatId})); }
const poll = new Poll({callback});
// Stop polling on leaving the chat
return () => { poll.stop(); }
}, [chatId])
async function sendMessage({content, files}) {
const message = {
chatId: chat.id,
fromChatUserId: chat.chatUserId, //chatUser.id,
toChatUserId: chat.chatUserId, //chatUser.id,
content,
files: null
};
if (files && files.length > 0) {
message.files = files;
requestPostMessageFiles({
account,
...message
});
} else {
requestPostMessage({
account,
...message
});
}
}
return (
<section className="chat-container">
<h3 className="sr-only">Chat: {chat && chat.name}</h3>
{ chat && chat.transcript && chat.roster &&
<>
<Roster roster={chat.roster} chatId={chatId} />
<div className="transcriptContainer">
<Transcript transcript={chat.transcript} chatId={chatId} />
{/* Function Components cannot be given refs */}
{/* <Composer sendMessage={sendMessage} ref={composerRef} /> */}
<Composer sendMessage={sendMessage} chatId={chatId} />
</div>
</>
}
</section>
)
}
|
thiessenp/chatapp-web
|
client/src/store/app.ts
|
/**
* Stores shared Client Only Chats Data
*/
export const ACTIVE_CHAT = 'ACTIVE_CHAT';
export function activeChat({chatId}) {
return async (dispatch) => {
dispatch({type: ACTIVE_CHAT, payload: { activeChatId: chatId }});
}
}
const INITIAL_STATE = {
activeChatId: null
};
export function appReducer(state=INITIAL_STATE, action) {
switch(action.type) {
case ACTIVE_CHAT:
const activeChatId = action.payload.activeChatId;
return {...state, activeChatId};
default:
return state;
}
}
|
thiessenp/chatapp-web
|
client/src/store/store.ts
|
import {combineReducers, createStore, applyMiddleware} from 'redux';
import thunkMiddleware from 'redux-thunk';
import {composeWithDevTools} from 'redux-devtools-extension';
import {healthReducer} from './health';
import {accountReducer} from './account';
import {chatsReducer} from './chats';
import {appReducer} from './app';
const rootReducer = combineReducers({
app: appReducer,
health: healthReducer,
account: accountReducer,
chats: chatsReducer,
});
// not needed since devtools?
// import { createLogger } from 'redux-logger';
// const loggerMiddleware = createLogger();
export const store = createStore(
rootReducer,
/* preloadedState, */
// Access debug console (load in new tab if not show first try)
// Download also from chrome: "Redux DevTools for Chrome"
composeWithDevTools(
applyMiddleware(
// for fetching stuff async
thunkMiddleware,
// not needed since devtools?
// ,loggerMiddleware
)
),
);
|
thiessenp/chatapp-web
|
client/src/pages/ChatsPage/ChatsPage.tsx
|
<gh_stars>0
import {useEffect} from 'react';
import {useRouteMatch, Route, Switch} from 'react-router-dom';
import {useDispatch, useSelector} from 'react-redux';
import {getChatsAction} from '../../store/chats';
import {healthAction} from '../../store/health';
import {Poll} from '../../util/poll';
import {ChatsList} from '../../components/ChatsList';
import {Chat} from './Chat';
import {ErrorMessage} from '../../components/ErrorMessage';
import './ChatsPage.scss';
function ChatsPage() {
const dispatch = useDispatch();
let {path} = useRouteMatch();
// const health = useSelector(state => state.health);
const chats = useSelector(state => state.chats.chats);
const account = useSelector(state => state.account);
const getErrorMessage = useSelector(state => state.chats.error || null);
// Server health up/down status
useEffect(() => {
dispatch(healthAction());
}, [dispatch]);
// Bootstrap with Account Data, then get initial Chats data
useEffect(() => {
let poll;
(async () => {
// Get initial all Chat data
dispatch(getChatsAction({isAllData:true}));
// Poll Chat List - just list updates (let each Chat handle their full updates)
const callback:any = () => { return dispatch(getChatsAction({isAllData:false})); }
// Delay 4s, rare event of new Chat
poll = new Poll({callback, delay: 4000});
})();
return () => { poll.stop(); }
}, [dispatch]);
return (
<section className="chats-page-container">
<ErrorMessage message={getErrorMessage}/>
{/* Interesting - if a link in a hidden text, it is focussable - WARNING */}
{/* <h2 className="sr-only">ChatsPage TODO (<Link to={`/home`}>home</Link>)</h2> */}
<h2 className="sr-only">ChatsPage</h2>
{/* <div>Connection to API: {process.env.REACT_APP_API_URL} is {health.status} with account {account.username}</div> */}
<div className="chats-page">
<ChatsList chats={chats} />
<Switch>
<Route path={`${path}/:chatId`}>
{account.id &&
<Chat account={account} chats={chats} />
}
</Route>
</Switch>
</div>
</section>
)
}
export default ChatsPage;
|
thiessenp/chatapp-web
|
client/src/store/chats.ts
|
<reponame>thiessenp/chatapp-web
import {getAuthHeader} from '../store/account';
import { formatFlux } from '../util/format';
export interface IChat {
id: string, //uuid
// Set on joining a chat - possibly independently
chatUserId?: string, //uuid
name: string,
roster: [],
transcript: []
}
export async function requestGetChats({account, isAllData=false}) {
const url = process.env.REACT_APP_API_URL + '/chats' + (isAllData ? '?isAllData=true' : '');
const response = await fetch(url, {
headers: { ...getAuthHeader({idToken: account.idToken}) }
});
let result = await response.json();
return result;
}
export async function requestGetChat({account, chatId}) {
const response = await fetch(`${process.env.REACT_APP_API_URL}/chats/${chatId}`, {
headers: {
...getAuthHeader({idToken: account.idToken}),
}
});
try {
let result = await response.json();
let chat = result.payload.chat;
return chat;
} catch(e) {
throw new Error('ERROR: requestGetChat serious failure, like JSON or CORS. ' + e.message);
}
}
export async function requestAddUserTochat({account, chatId, accountId}) {
const response = await fetch(`${process.env.REACT_APP_API_URL}/chats/${chatId}/users`, {
method: 'POST',
headers: {
...getAuthHeader({idToken: account.idToken}),
'Content-Type': 'application/json'
},
body: JSON.stringify({chatId, accountId})
});
try {
let result = await response.json();
if (result.status === 'error') {
throw new Error(result.message);
}
let user = result.payload.user;
return user;
} catch(e) {
// TODO: error handling service?
throw new Error(e.message);
}
}
// Payload Default: in Body as simple x-www-form-urlencoded key=value pairs
export async function requestPostMessage({account, chatId, fromChatUserId, toChatUserId, content}) {
const response = await fetch(`${process.env.REACT_APP_API_URL}/chats/${chatId}/messages`, {
method: 'POST',
headers: {
...getAuthHeader({idToken: account.idToken}),
'Content-Type': 'application/json'
},
// Standard non-file body
body: JSON.stringify({chatId, fromChatUserId, toChatUserId, content})
});
return response;
}
// Payload Files: more complex multipart/form-data
export async function requestPostMessageFiles({account, chatId, fromChatUserId, toChatUserId, content, files}) {
console.log('requestPostMessageFiles Files: ', files);
// Gather and format form data
// Note: Sends same as a Form's submit() - ?default to form-urlencoded?
const formData:FormData = new FormData();
formData.append('chatId', chatId);
formData.append('fromChatUserId', fromChatUserId);
formData.append('toChatUserId', toChatUserId);
formData.append('content', content);
files.forEach(file => { formData.append('file', file); });
const response = await fetch(`${process.env.REACT_APP_API_URL}/chats/${chatId}/uploads`, {
method: 'POST',
/**
* Content type is specifying that the keys and values submitted in a form will be encoded in a specific format.
* - Content-Type application/x-www-form-urlencoded - Default Form submit() and uses URL encoding, so key=value&key..
* - Content-Type multipart/form-data - Use for non-ASCII data, and binary data (file transfers), more efficient for lots of data
*/
headers: {
...getAuthHeader({idToken: account.idToken}),
// Note: DO NOT SET - browser will set this automatically
// 'Content-Type': 'multipart/form-data',
},
body: formData
});
return response;
}
export const GET_CHATS_REQUEST = 'GET_CHATS_REQUEST';
export const GET_CHATS_SUCCESS = 'GET_CHATS_SUCCESS';
export const GET_CHATS_ERROR = 'GET_CHATS_ERROR';
export function getChatsAction({isAllData}) {
// Note: assuming arrow func is to closure this scope for, hmm something
return async (dispatch, getState) => {
const account = getState().account;
dispatch(formatFlux({type: GET_CHATS_REQUEST, payload: {}}));
try {
const result = await requestGetChats({account, isAllData});
if (result.error) { throw new Error(result.payload.message); }
dispatch(formatFlux({
type: GET_CHATS_SUCCESS,
payload: result.payload.chats
}));
} catch(err) {
dispatch(formatFlux({type: GET_CHATS_ERROR, payload: err}))
}
};
}
export const GET_CHAT_REQUEST = 'GET_CHAT_REQUEST';
export const GET_CHAT_SUCCESS = 'GET_CHAT_SUCCESS';
export const GET_CHAT_ERROR = 'GET_CHAT_ERROR';
export function getChatAction({chatId}) {
return async (dispatch, getState) => {
const account = getState().account;
dispatch(formatFlux({type: GET_CHAT_REQUEST, payload: {}}));
try {
const chat = await requestGetChat({account, chatId});
dispatch(formatFlux({type: GET_CHAT_SUCCESS, payload: chat}));
} catch(err) {
dispatch(formatFlux({type: GET_CHAT_ERROR, payload: err}));
}
};
}
export const ADD_USER_TO_CHAT_REQUEST = 'ADD_USER_TO_CHAT_REQUEST';
export const ADD_USER_TO_CHAT_SUCCESS = 'ADD_USER_TO_CHAT_SUCCESS';
export const ADD_USER_TO_CHAT_ERROR = 'ADD_USER_TO_CHAT_ERROR';
export function addUserTochat({chatId, accountId}) {
return async (dispatch, getState) => {
const account = getState().account;
dispatch(formatFlux({type: ADD_USER_TO_CHAT_REQUEST, payload: {}}));
try {
const chatUser = await requestAddUserTochat({account, chatId, accountId});
dispatch(formatFlux({
type: ADD_USER_TO_CHAT_SUCCESS,
payload: {chatId, chatUserId: chatUser.id}
}));
} catch(err) {
dispatch(formatFlux({type: ADD_USER_TO_CHAT_ERROR, payload: err}));
}
};
}
const INITIAL_STATE = { chats: [] };
export function chatsReducer(state=INITIAL_STATE, action) {
switch(action.type) {
// CHATS
case GET_CHATS_REQUEST:
return {
...state,
//...action.payload, -- No don't think so, dangerous?
isLoading: true,
};
case GET_CHATS_SUCCESS:
return {
...state, // -- Yes, Ok overriding below? (No, not this since replace old state below.)
chats: updateChats({oldChats: state.chats, newChats: action.payload}),
isLoading: false,
};
case GET_CHATS_ERROR:
return {
...state,
isLoading: false,
error: action.payload.message || true,
};
// TODO: split into separate reducer for separation of concerns
// CHAT
case GET_CHAT_REQUEST:
return {
...state,
isLoading: true,
};
case GET_CHAT_SUCCESS: {
const newChat:IChat = action.payload;
let isChatUpdated = false;
const newChatsState = state.chats.map((chat:IChat) => {
if (chat.id !== newChat.id) { return chat; }
if (!isChatDiff({oldChat:chat, newChat})) { return chat; }
// TODO: kind of messy capturing state here, better way?
isChatUpdated = true;
// Override old chat but keep anything extra added (like chatUserId)
return {...chat, ...newChat};
});
let newChatState;
if (!isChatUpdated) {
newChatState = {
...state,
isLoading: false
};
} else {
newChatState = {
...state,
chats: newChatsState,
isLoading: false,
};
}
return newChatState;
}
case GET_CHAT_ERROR:
return {
...state,
isLoading: false,
error: action.payload.message || true,
};
// TODO: split into separate reducer for separation of concerns
// USER - join chat
case ADD_USER_TO_CHAT_REQUEST:
return {
...state,
isLoading: true,
};
case ADD_USER_TO_CHAT_SUCCESS: {
const chatId = action.payload.chatId;
const chatUserId = action.payload.chatUserId;
const newChatsState = state.chats.map((chat:IChat) => {
if (chat.id !== chatId) { return chat; }
return {...chat, chatUserId};
});
const newState = {
...state,
chats: newChatsState,
isLoading: false,
};
return newState;
}
case ADD_USER_TO_CHAT_ERROR:
return {
...state,
isLoading: false,
error: action.payload.message || true,
};
default:
return state;
}
}
/**
* Updates chats by over writing all chats if there is a different number of
* chats. (chats have been added/removed so update)
*
* TODO: could compare transcript/roster for changes per chat for update diff.
*/
function updateChats({oldChats, newChats}) {
// New session? add any new chats
if (oldChats.length === 0) { return newChats; }
// No new chats
if (oldChats.length === newChats.length) { return oldChats; }
// Add any new Chats
// NOTE: array.filter wasn't working for me so went with foreach (try later?)
let newChatsDiff: Array<any> = [];
newChats.forEach(newChat => {
let notFound = true;
oldChats.forEach(oldChat => {
if (newChat.id === oldChat.id) { notFound = false; }
});
if (notFound) { newChatsDiff.push(newChat); }
});
// TODO:
// Remove any removed Chats (server API as well)
return [...oldChats, ...newChatsDiff];
}
function isChatDiff({oldChat, newChat}) {
if (!oldChat || !newChat) { return false; }
// Diff the Chat
if (
(oldChat.transcript.length !== newChat.transcript.length) ||
(oldChat.roster.length !== newChat.roster.length)
) {
return true;
}
// No diff in chat
return false;
}
|
thiessenp/chatapp-web
|
client/src/components/Transcript.tsx
|
<reponame>thiessenp/chatapp-web
import {useState, useRef, useEffect} from 'react';
import {debounce} from 'debounce';
// import {useSelector} from 'react-redux';
import {ListNav} from 'keynav-web';
import './Transcript.scss';
export function Transcript(props) {
// const getActiveChatId = useSelector(state => state.app.activeChatId);
// const [initialized, setInitialized] = useState<boolean>(false);
const [listNav, setListNav] = useState<any>(null);
const [transcriptHeight, setTranscriptHeight] = useState<number>(500);
const transcriptRef = useRef<HTMLOListElement>(null);
const debouncedUpdateTranscriptHeight = debounce(updateTranscriptHeight, 150);
// Add Keynav when component created (remove it when destroyed)
useEffect(() => {
if (transcriptRef.current) {
setListNav(new ListNav({
listEl: transcriptRef.current,
listItemsSelector: 'li'
}));
}
return () => {
if (listNav) {
listNav.removeBehavior();
setListNav(null);
}
}
// chatId needed so will update when Route changes (on diff chat shown)
}, [props.chatId]);
// Resize Transcript height to available size and on any browser size change
useEffect(() => {
updateTranscriptHeight();
window.addEventListener('resize', debouncedUpdateTranscriptHeight);
return () => {
window.removeEventListener('resize', debouncedUpdateTranscriptHeight);
}
}, [debouncedUpdateTranscriptHeight]);
// Sadly still require manual calculation of DOM els to set Transcript (done here)
function updateTranscriptHeight() {
function calculateTranscriptHeight() {
// Gather related DOM heights - TODO: probably a better way to get HTML refs
const navbarEl:any = document.querySelector('.main-header-container');
const chatComposerEl:any = document.querySelector('.composer');
const documentEl:any = document.documentElement;
// Do some existence checks
if (!navbarEl || !chatComposerEl || !documentEl) {
return;
}
// Calculate transcript height based on gathered
// WARNING: using getBoundingClientRect().height to get computed actual
// height regardless of box model
const height = documentEl.clientHeight - navbarEl.offsetHeight - chatComposerEl.offsetHeight;
// TODO check for NaN or not care?
return height;
}
// Get Height
const newTranscriptHeight:any = calculateTranscriptHeight();
// Diff: Only set the trasncript height if the calculated one is different
if (newTranscriptHeight !== transcriptHeight) {
setTranscriptHeight(newTranscriptHeight);
}
}
// Keep latest chat message shown at the bottom of the Transcript
useEffect(() => {
if (transcriptRef.current) {
scrollElView(transcriptRef.current.lastElementChild);
}
}, [props.transcript]);
function scrollElView(el) {
if (!el) { return; }
el.scrollIntoView({behavior: 'smooth', block: 'start', inline: 'nearest'});
}
function isImage(path:string):boolean {
if (path.split('.').pop()?.match(/^(png|jpg|jpeg|gif|jiff)$/)) {
return true;
}
return false;
}
return (
<section className="transcript">
<h3 className="sr-only">Transcript</h3>
{props.transcript.length === 0 &&
<div>No messages yet. Why not send one?</div>
}
{(props.transcript.length > 0 &&
<ol className="list" ref={transcriptRef} role="log" style={{height: transcriptHeight}}>
{(
props.transcript.map(message => {
return (
<li className="item" key={message.id}>
<section className="message">
<span className="username">{message.from_chat_user_username}</span>
<span className="content">{message.content}</span>
{(message.attachments && message.attachments.length > 0 &&
<ul className="attachments">
{
message.attachments.map(attachment => {
const path = `http://localhost:3000/${attachment.path}`;
return (
<li key={path} className="item">
{(isImage(path) ?
<a href={path} target="_blank"><img className="image" src={path} /></a>
:
<span className="icon">📁</span>
)}
</li>
)
})
}
</ul>
)}
</section>
</li>
)
})
)}
</ol>
)}
</section>
)
}
|
thiessenp/chatapp-web
|
client/src/components/ChatsList.tsx
|
<reponame>thiessenp/chatapp-web
import {useEffect, useRef, useState} from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {activeChat} from '../store/app';
import {useHistory,useRouteMatch} from 'react-router-dom';
import {ChatsListItem} from './ChatsListItem';
import './ChatsList.scss';
// NOTE: keynav not added since chats anchors and focusable.
export function ChatsList(props) {
const listRef = useRef<HTMLOListElement>(null);
// Used to ensure a chat is activated only once, not on any change
const [shownAChat, setShownAChat] = useState(false);
const getActiveChatId = useSelector(state => state.app.activeChatId);
let history = useHistory();
let {url} = useRouteMatch();
const dispatch = useDispatch();
useEffect(() => {
// Automatically show a chat in the UI to improve UX (1-less click)
if (!shownAChat && props.chats && props.chats.length > 0) {
let activeChatId = getActiveChatId;
// Case of new Chat, so no active chats - set one
if (!activeChatId) {
activeChatId = props.chats[0].id;
console.log('activating chat...', activeChatId);
dispatch(activeChat({chatId: activeChatId}));
}
// TODO: can below be abstracted?
// Navigate (show) to the active chat
let {from} = {from: {pathname: `${url}/${activeChatId}`}};
history.replace(from);
// Should only be done once?
setShownAChat(true);
}
}, [props, history, dispatch, getActiveChatId, shownAChat, url]);
// NOTE:
// Could also use click method below but above event method is cleaner
//
// useEffect(() => {
// // All this crap for typescript, is this really better?...
// const listEl:any = listRef?.current;
// const listItemsEl = listEl?.children;
// if (!activatedChat && listItemsEl && listItemsEl.length > 0) {
// let listItemEl:HTMLElement = listItemsEl[0];
// let anchor = listItemEl.querySelector('a');
// anchor?.click();
// setActivatedChat(true);
// }
// }, [props]);
return (
<section className="chats-list">
<h2 className="sr-only">ChatsList</h2>
<ol className="list" ref={listRef}>
{props.chats && props.chats.map(chat => (
<ChatsListItem
key={chat.id}
id={chat.id}
name={chat.name} />
))}
</ol>
</section>
)
}
|
thiessenp/chatapp-web
|
client/src/components/MainHeader.tsx
|
// import {useRef} from 'react';
import {Link} from 'react-router-dom';
// export const MainHeader = React.forwardRef((props, ref) => {
export function MainHeader() {
// const mainRef = useRef<HTMLDivElement>(null);
return (
// <header ref={mainRef} className="sticky-top app-header">
<header className="sticky-top main-header-container">
<nav className="navbar navbar-dark sticky-top bg-dark flex-md-nowrap p-0 shadow">
<Link className="navbar-brand px-2 px-md-3" to={`/home`}>ChatsApp</Link>
<ul className="navbar-nav px-2 px-md-3">
<li className="nav-item text-nowrap">
{/* TODO: Use below hack instead to simulate a logout (out of react context) but fix later. */}
{/* <Link className="nav-link" to={`/home`}>Sign out (todo)</Link> */}
<a className="nav-link" href="/">Sign out (todo)</a>
</li>
</ul>
</nav>
</header>
);
// });
}
|
thiessenp/chatapp-web
|
client/src/pages/LoginPage/LoginPage.tsx
|
import React, {useEffect} from 'react';
import {useHistory /*,useLocation*/} from 'react-router-dom';
import {useDispatch, useSelector} from 'react-redux';
// import {isAuth} from '../../services/accountService';
// import {requestGetHealth} from '../../services/healthService';
import {healthAction} from '../../store/health';
import {loginAction, isAuth} from '../../store/account';
import {ErrorMessage} from '../../components/ErrorMessage';
import './LoginPage.scss';
// NOTE: Hooks must be used in react components
function LoginPage(/*props*/) {
const dispatch = useDispatch();
const getHealth = useSelector(state => state.health);
const getAccount = useSelector(state => state.account);
const getErrorMessage = useSelector(state => state.account.error || null);
let history = useHistory();
// TODO:
//let location = useLocation();
const usernameRef = React.useRef<HTMLInputElement>(null);
const passwordRef = React.useRef<HTMLInputElement>(null);
// Server health up/down status
useEffect(() => {
dispatch(healthAction());
}, [dispatch]);
useEffect(() => {
if (!isAuth(getAccount)) { return; }
// TODO:
// -- then remove above when other stuff works
// let { from } = location.state || { from: { pathname: "/" } };
// TEMP:
// -- This works but is not generic
console.log('forwarding to /chats...');
let {from} = {from: {pathname: '/chats'}};
history.replace(from);
}, [getAccount, history]);
async function handleSubmit(e) {
e.preventDefault();
const username = usernameRef.current;
const password = passwordRef.current;
if (!username || !password) {
alert('TODO: username and password required');
return;
}
// Do the Login - on success the below should forward the user to the Chats
dispatch(loginAction({
username: username.value,
password: password.value
}));
}
return (
<section className="text-center">
<h1 className="sr-only">ChatsApp Login</h1>
{/* TODO: separate Login form into a component? */}
<section className="text-center login">
<form onSubmit={handleSubmit}>
<h2 className="h3 mb-3 font-weight-normal">Sign in to ChatsApp</h2>
<ErrorMessage message={getErrorMessage}/>
<label htmlFor="login--username" className="sr-only">Email address</label>
<input ref={usernameRef} id="login--username" className="form-control login--top-style" placeholder="Username" required autoFocus />
<label htmlFor="login--password" className="sr-only">Password</label>
<input ref={passwordRef} type="password" id="login--password" className="form-control login--bottom-style" placeholder="Password" required />
<button type="submit" className="btn btn-lg btn-primary btn-block mt-4">Sign in</button>
</form>
</section>
<p className="mt-5 mb-3 text-muted">Connection to API: {process.env.REACT_APP_API_URL} is {getHealth.status}</p>
</section>
)
}
export default LoginPage;
|
thiessenp/chatapp-web
|
client/src/store/account.ts
|
import { formatFlux } from '../util/format';
export interface IAccount {
id: string,
username: string,
idToken: string,
//TODO source of bug? on check auth need to check expiresIn also?
//Actually get a 401 so better with a account action that triggers a redirect to login and resets all state
expiresIn: string,
// TODO: good way to do it? (function with expiresCheck, not sure)
isAuthenticated: boolean
}
export async function postLogin({username, password}) {
// Login - holds idToken and expiresIn
const response = await fetch(process.env.REACT_APP_API_URL + '/accounts/login', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({username, password})
});
return await response.json();
}
export function getAuthHeader({idToken}) {
return {'Authorization': `Bearer ${idToken}`};
}
export function isAuth(account:IAccount) {
// TODO: add check for isExpired? maybe other stuff?
return Boolean(account.isAuthenticated);
}
// Note: could group into an object also
export const LOGIN_REQUEST = 'LOGIN_REQUEST';
export const LOGIN_SUCCESS = 'LOGIN_SUCCESS';
export const LOGIN_ERROR = 'LOGIN_ERROR';
export function loginAction({username, password}) {
// Note: assuming arrow func is to closure this scope for, hmm something
return async (dispatch) => {
if (!username || !password) {
dispatch(formatFlux({
type: LOGIN_ERROR,
payload: new Error('Login missing username or password')
}));
}
dispatch({
type: LOGIN_REQUEST,
payload: {}
});
try {
const result = await postLogin({
username: username.trim(),
password: password.<PASSWORD>()
});
if (result.error) {
throw new Error(result.payload.message);
}
dispatch(formatFlux({
type: LOGIN_SUCCESS,
payload: result.payload
}));
} catch(err) {
dispatch(formatFlux({
type: LOGIN_ERROR,
payload: err
}));
}
};
}
const INITIAL_STATE:IAccount = {
id: '',
username: '',
idToken: '',
expiresIn: '',
isAuthenticated: false
};
export function accountReducer(state=INITIAL_STATE, action) {
switch(action.type) {
case LOGIN_REQUEST:
return {
...state,
...action.payload,
isLoading: true
};
case LOGIN_SUCCESS:
return {
...state,
...action.payload,
isAuthenticated: Boolean(action.payload.idToken),
isLoading: false
};
case LOGIN_ERROR:
return {
...state,
error: action.payload.message,
isAuthenticated: false,
isLoading: false,
};
default:
return state;
}
}
// TODO
//
/**
* Account Service uses Session Storage. Mainly just used for Login APIs to do
* an initial check for any sessions - then Redux is used from then on.
*
* So sessionStorage:
* - data in sessionStorage is cleared when the page session ends
* - page session continues: page reload
* - page session ends: open a new tab (same URL - each gets sessionStore)
* - page session ends: closing tab
*
* BIG BONUS?
* - No cleanup, all session data cleared on tab/browser close.
*/
export function getAccountSession() {
return {
id: window.sessionStorage.getItem('id') || '',
username: window.sessionStorage.getItem('username') || '',
idToken: window.sessionStorage.getItem('idToken') || '',
expiresIn: window.sessionStorage.getItem('expiresIn') || '',
isAuthenticated: window.sessionStorage.getItem('idToken') ? true : false
};
}
export function setAccountSession({id,username,idToken, expiresIn}) {
window.sessionStorage.setItem('id', id);
window.sessionStorage.setItem('username', username);
window.sessionStorage.setItem('idToken', idToken);
window.sessionStorage.setItem('expiresIn', expiresIn);
}
|
thiessenp/chatapp-web
|
client/src/components/DragAndDrop.tsx
|
import React from 'react';
type MyProps = {handleDropCallback: any};
type MyState = {drag: boolean};
export class DragAndDrop extends React.Component<MyProps, MyState> {
dropRef: any;
constructor(props) {
super(props);
this.state = { drag: false };
this.dropRef = React.createRef();
this.handleDragEnter = this.handleDragEnter.bind(this);
this.handleDragExit = this.handleDragExit.bind(this);
this.handleDragOver = this.handleDragOver.bind(this);
this.handleDrop = this.handleDrop.bind(this);
}
componentDidMount():void {
this.dropRef.current.addEventListener('dragenter', this.handleDragEnter);
this.dropRef.current.addEventListener('dragexit', this.handleDragExit);
this.dropRef.current.addEventListener('dragover', this.handleDragOver);
this.dropRef.current.addEventListener('drop', this.handleDrop);
}
componentWillUnmount():void {
this.dropRef.current.removeEventListener('dragenter', this.handleDragEnter);
this.dropRef.current.removeEventListener('dragexit', this.handleDragExit);
this.dropRef.current.removeEventListener('dragover', this.handleDragOver);
this.dropRef.current.removeEventListener('drop', this.handleDrop);
}
handleDragEnter(e):void {
if (e.dataTransfer.items && e.dataTransfer.items.length > 0) this.setState({drag: true});
}
handleDragExit(e):void { this.setState({drag: false});}
handleDragOver(e):void {
e.preventDefault(); // Note: Need this also to Prevent default behavior (Prevent file from being opened)
e.dataTransfer.dropEffect = 'move';
}
handleDrop(e):void {
e.preventDefault(); // Note: Prevent default behavior (Prevent file from being opened)
if (e.dataTransfer.files && e.dataTransfer.files.length > 0) {
this.props.handleDropCallback(e.dataTransfer.files);
e.dataTransfer.clearData();
}
}
render():any {
return (
<div ref={this.dropRef} className={this.state.drag ? 'bg-success' : ''}>
{/*
//Not necessary since this is probably handled in component using this.
{this.state.drag &&
<div>
Drop here
</div>
} */}
{this.props.children}
</div>
);
}
}
|
thiessenp/chatapp-web
|
client/src/components/ChatsListItem.tsx
|
import {Link, useRouteMatch} from 'react-router-dom';
import {useDispatch, useSelector} from 'react-redux';
import {activeChat} from '../store/app';
import './ChatsListItem.scss';
export function ChatsListItem(props) {
let {url} = useRouteMatch();
const dispatch = useDispatch();
const activeChatId = useSelector(state => state.app.activeChatId);
function setActiveChat(e) {
dispatch(activeChat({chatId: props.id}));
}
return (
<li className={props.id===activeChatId ?
'chats-list-item active' : 'chats-list-item'
}>
<Link to={`${url}/${props.id}`} onClick={setActiveChat}>
{/* id: {props.chatId}, */}
{props.name}
</Link>
</li>
)
}
|
thiessenp/chatapp-web
|
client/src/components/FileUploadModal.tsx
|
<filename>client/src/components/FileUploadModal.tsx<gh_stars>0
import React, {FormEvent, useState /*, useEffect*/} from 'react';
import Button from 'react-bootstrap/Button';
import Modal from 'react-bootstrap/Modal';
import {DragAndDrop} from './DragAndDrop';
// TODO use my accessible modal later
export function FileUploadModal(props: any) {
// captain - HOOKS!
// Set a local state object here to use in UI for UX
const [files, setFiles] = useState([] as any);
// useEffect(() => {
// put any side effects to a state update here - remember async so must go here to see
// })
function handleFilesUpdate(fileList: FileList):void {
const newFiles = Array.prototype.slice.call(fileList);
/**
* HOOKS! and setState
* Will lose state if the callback syntax isn't used. Old state will be overwritten otherwise
*/
setFiles(oldFiles => [...oldFiles, ...newFiles]);
}
function handleClose():void {
setFiles([]);
props.onHide();
}
function getInputFiles(e: FormEvent) {
// Use passed files, probably the input
const inputEl:any = e.target;
const fileList:FileList = inputEl.files;
props.callback(fileList);
// Show files in modal also
handleFilesUpdate(fileList);
}
function getDragAndDropFiles(fileList: FileList):void {
// Use files from drag and drop
props.callback(fileList);
// Show files in modal also
handleFilesUpdate(fileList);
}
return (
// <Modal {...props}> WARNING this would include all props, including ones NOT VALID for Modal
<Modal className="chatapp-web-modal" show={props.show} onHide={props.onHide}>
<Modal.Header closeButton>
Upload Files <h1>TODO use my accessible modal later</h1>
</Modal.Header>
<Modal.Body>
<div className="text-center" style={{border: '4px dashed #ccc'}}>
<DragAndDrop handleDropCallback={getDragAndDropFiles}>
<div className="pt-5 pb-5">
<div style={{fontSize: '5rem'}}>⇩</div>
<h2>Drag and drop<br/>files here</h2>
</div>
</DragAndDrop>
</div>
<div className="mt-3 text-center text-muted" style={{fontSize: '1.1rem'}}>-or-</div>
<div className="mt-3 mb-3 text-center">
<label className="btn btn-info">
Upload an image <input hidden onChange={getInputFiles} type="file" multiple name="chatinput-file" />
</label>
</div>
{files.length > 0 &&
<div>
<h3 className="h5">Attached Files:</h3>
<ul>
{files.map(file => <li key={file.name}>{file.name}</li>)}
</ul>
</div>
}
</Modal.Body>
<Modal.Footer>
<Button onClick={handleClose}>Close and Attach Files</Button>
</Modal.Footer>
</Modal>
);
}
|
thiessenp/chatapp-web
|
client/src/components/ErrorMessage.tsx
|
<gh_stars>0
/**
* Displays a generic and consistent error message in the UI
* @param props Error data
*/
export function ErrorMessage(props) {
if (!props || !props.message) {
return null;
}
// TODO: could add logic here from more props
return (
<div className="mt-4 alert alert-danger" role="alert">{props.message}</div>
);
}
|
thiessenp/chatapp-web
|
client/src/components/AuthGuard.tsx
|
<gh_stars>0
import {Route, Redirect} from 'react-router-dom';
import {useSelector} from 'react-redux';
import {isAuth} from '../store/account';
function RouteGuard({component: Component, /*auth,*/ ...rest}) {
const account = useSelector(state => state.account);
return(
<Route
{...rest}
render={(props) => (
isAuth(account) ? <Component {...props} /> : <Redirect to='/login' />
)}
/>
);
}
export default RouteGuard;
////////////////////////////////////////////////////////////////////////////////
// DEPRECATED below
////////////////////////////////////////////////////////////////////////////////
// import React, { useContext, createContext, useState } from "react";
// import {
// BrowserRouter as Router,
// Route,
// Switch,
// Link,
// Redirect,
// useHistory,
// useLocation
// } from 'react-router-dom';
// const fakeAuth = {
// isAuthenticated: false,
// signin(cb) {
// fakeAuth.isAuthenticated = true;
// setTimeout(cb, 100); // fake async
// },
// signout(cb) {
// fakeAuth.isAuthenticated = false;
// setTimeout(cb, 100);
// }
// };
// /** For more details on
// * `authContext`, `ProvideAuth`, `useAuth` and `useProvideAuth`
// * refer to: https://usehooks.com/useAuth/
// */
// const authContext = createContext({
// user: null
// });
// // Provider component that wraps your app and makes auth object ...
// // ... available to any child component that calls useAuth().
// export function ProvideAuth({ children }) {
// const auth = useProvideAuth();
// return (
// <authContext.Provider value={auth}>
// {children}
// </authContext.Provider>
// );
// }
// function useProvideAuth() {
// const [user, setUser] = useState(null);
// const signin = cb => {
// return fakeAuth.signin(() => {
// setUser("user");
// cb();
// });
// };
// const signout = cb => {
// return fakeAuth.signout(() => {
// setUser(null);
// cb();
// });
// };
// return {
// user,
// signin,
// signout
// };
// }
// // A wrapper for <Route> that redirects to the login
// // screen if you're not yet authenticated.
// export function PrivateRoute({ children, ...rest }) {
// let auth = useAuth();
// return (
// <Route
// {...rest}
// render={({ location }) =>
// auth.user ? (children) : (
// <Redirect
// to={{
// pathname: '/login',
// state: { from: location }
// }}
// />
// )
// }
// />
// );
// }
// function useAuth() {
// return useContext(authContext);
// }
|
thiessenp/chatapp-web
|
client/src/store/error.ts
|
<gh_stars>0
// DEPRECATED?
//
// Using the flux formatter, is simpler and clearer I think?
// (plus keeps more state logic in the Reducer (BP))
import {IAction} from '../util/format';
/**
* Used to format and create a standard error for all components.
* Follows the Flux pattern
* see: https://github.com/redux-utilities/flux-standard-action
*
* @param errorType code for error
* @param error payload for error
* @deprecated
*/
export function errorActionCreator({type, payload}) {
const createdError:IAction = {
type,
payload,
error: true,
};
return createdError;
}
/**
* Used to add consistent Error state to existing Reducers
* see: https://alexandrempsantos.com/sane-error-handling-react-redux/
*
* @deprecated
*/
export function errorReducer (state, action) {
if (!action.error) {
return {
...state,
//TODO: maybe false better?
error: null,
}
}
return {
...state,
error: {
// Should be formatted using errorActionCreator (flux standard)
...action
}
}
}
|
thiessenp/chatapp-web
|
client/src/util/format.ts
|
<reponame>thiessenp/chatapp-web
/**
* Actions FLUX standard for Error object properties.
* More info https://github.com/redux-utilities/flux-standard-action
*/
export interface IAction {
// identifies to the consumer the nature of the action that has occurred
type: string,
// Any information about the action that is not the type or status
// By convention, if error is true, the payload SHOULD be an error object
payload?: any,
// set to true if the action represents an error, e.g. rejected Promise
// only === true is an error, anything falsey is not
error?: boolean,
// intended for any extra information that is not part of the payload.
meta?: any,
}
// TODO: utility function isFSA(action)
// TODO: utility function isError(action)
/**
* Formats the data for a router response
* @param {Object} o - params
* @param {String} [o.type] - code or type of data, should be UPPERCASE snakecase
* @param {Object} [o.payload] - response data here, or Error data if an error
* @param {Boolean} [o.error] - (optional) set to True for an error
* @param {String} [o.meta] - (optional) any extra info like a code number
* @return {Object} formatted response object
*/
export function formatFlux({type, payload, error=null, meta=null}) {
return {
type,
payload,
error: Boolean(error) || null,
meta,
};
}
|
thiessenp/chatapp-web
|
client/src/store/health.ts
|
import {formatFlux, IAction} from '../util/format';
export interface IHealth {
status: string
}
export enum HEALTH {
UNKNOWN = 'UNKNOWN',
DOWN = 'DOWN',
UP = 'UP'
}
export const HEALTH_REQUEST = 'HEALTH_REQUEST';
export const HEALTH_SUCCESS = 'HEALTH_SUCCESS';
export const HEALTH_ERROR = 'HEALTH_ERROR';
export async function getHealthRequest() {
const response = await fetch(process.env.REACT_APP_API_URL + '/health');
try {
let result: IAction = await response.json();
if (result.error) {
throw new Error(result.payload.message);
}
return result;
} catch(e) {
// Mocked as Backend response, since the error probably is no response
return formatFlux({
type: HEALTH_ERROR,
payload: {}
});
}
}
export function healthAction() {
return async (dispatch) => {
dispatch(formatFlux({
type: HEALTH_REQUEST,
payload: {}
}));
try {
const healthData = await getHealthRequest();
dispatch(healthData);
} catch(err) {
dispatch({
type: HEALTH_ERROR,
payload: err,
});
}
};
}
const INITIAL_STATE:IHealth = {
status: HEALTH.UNKNOWN
};
export function healthReducer(state=INITIAL_STATE, action) {
switch(action.type) {
case HEALTH_REQUEST:
return {
...state,
...action.payload,
isLoading: true
};
case HEALTH_SUCCESS:
return {
...state,
...action.payload,
isLoading: false
};
case HEALTH_ERROR:
return {
...state,
...action.payload,
isLoading: false,
status: HEALTH.DOWN,
// TODO: consider using a formatter for error consistency?
// (probably no, see error.ts comments about this)
error: true,
};
default:
return state;
}
}
|
thiessenp/chatapp-web
|
client/src/pages/HomePage/HomePage.tsx
|
import {useEffect,} from 'react';
import {Link} from 'react-router-dom';
import {useDispatch, useSelector} from 'react-redux';
// NOTE: Important to do Component specific imports.
// This would import entire lib: import { Button } from 'react-bootstrap';
// import Button from 'react-bootstrap/Button';
// import NavLink from 'react-bootstrap/NavLink';
import {healthAction} from '../../store/health';
/**
Could do styles like this
const styles = {
count: css`
font-size: 12px;
`,
lastUpdated: css`
color: #666;
font-size: 10px;
`,
todos: css`
padding-left: 0;
`,
};
*/
export default function HomePage() {
const dispatch = useDispatch();
const getHealth = useSelector(state => state.health);
// Server health up/down status
useEffect(() => {
dispatch(healthAction());
}, []);
return (
<section>
<h1 className="h1">ChatApp (WIP)</h1>
<p><small>Connection to API: {process.env.REACT_APP_API_URL} is {getHealth.status}</small></p>
<div className="text-center">
<Link to={`/chats`} className="btn btn-primary btn-lg">Go to the Chats</Link>
</div>
<p className="my-4"><em>Tip: Remember set width to MOBILE for initial design</em></p>
</section>
)
}
|
thiessenp/chatapp-web
|
client/src/index.tsx
|
<gh_stars>0
import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter, Route, Switch, Redirect} from 'react-router-dom';
import {Provider} from 'react-redux';
import {store} from './store/store';
// import App from './App';
import reportWebVitals from './reportWebVitals';
import RouteGuard from './components/AuthGuard';
import HomePage from './pages/HomePage/HomePage';
import LoginPage from './pages/LoginPage/LoginPage';
import ChatsPage from './pages/ChatsPage/ChatsPage';
import {MainHeader} from './components/MainHeader';
import './style/main.scss';
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<BrowserRouter>
{/* <App /> */}
<MainHeader />
<div className="container-fluid">
<div className="row">
{/* Gaaah... do I have to put container-fluid on ever full width box...?! */}
<main className="container-fluid main-container">
{/* <BrowserRouter> */}
<Switch>
{/*
Switch chooses the first match, so order Matters
BUT a "/" will be included in addition regardless - exact stops this
*/}
<Route exact path="/" component={HomePage} />
{/* <Route path="/">
<div className="App">
<header className="App-header">
<h1>ChatApp (WIP)</h1>
<Link to={`/chats`}>Go to the Chats id</Link>
</header>
</div>
</Route> */}
{/* Another less efficient way is: <Route path="/home"><Redirect to={"/"} /></Route> */}
<Redirect strict from="/home" to="/" />
<Route path="/login" component={LoginPage} />
<RouteGuard path="/chats" component={ChatsPage} />
{/*-vs- <RouteGuard path="/chats">
<ChatsPage></ChatsPage>
</RouteGuard> */}
</Switch>
{/* </BrowserRouter> */}
</main>
</div>
</div>
</BrowserRouter>
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint. Learn more: https://bit.ly/CRA-vitals
reportWebVitals();
|
thiessenp/chatapp-web
|
client/src/components/Composer.tsx
|
import {useState, useEffect, useRef} from 'react';
import {useSelector} from 'react-redux';
import {FileUploadModal} from './FileUploadModal';
import './Composer.scss';
export function Composer(props) {
const [files, setFiles] = useState([]);
const [showFileModal, setShowFileModal] = useState(false);
const getActiveChatId = useSelector(state => state.app.activeChatId);
const composerRef = useRef<HTMLDivElement>(null);
const messageRef = useRef<HTMLInputElement>(null);
useEffect(() => {
// UX: focus composer when transcript is visible, 1-less user click to send a message
if (props.chatId === getActiveChatId && messageRef.current) {
messageRef.current.focus();
}
}, [getActiveChatId, props.chatId]);
function createMessage(e) {
e.preventDefault();
// Check the message
if (!messageRef.current || !messageRef.current.value) {
alert('Composer createMessage expects message content');
return;
}
// Send the message
let content = messageRef.current.value;
props.sendMessage({content, files});
// Reset the composer for the next message
messageRef.current.value = '';
setFiles([]);
}
// TODO: Only makes sense on multi-line input - so build multi-line input
//
// NOTE: React Synthetic events have their own thing (KeyboardEvent won't work in TS)
function handleInputKeys(/*e: React.KeyboardEvent<HTMLDivElement>*/):void {
// const key:string = e.key.toLowerCase();
// const isCtrlKey:boolean = e.ctrlKey;
// const isShiftKey:boolean = e.shiftKey;
// if ((key === 'enter' && isCtrlKey) || (key === 'enter' && isShiftKey)) {
// console.log('SHIFT or CTRL+ENTER! do something')
// e.preventDefault();
// }
}
function toggleShowFileModal(e){
showFileModal ? setShowFileModal(false) : setShowFileModal(true);
}
function addFilesForUpload(fileList: FileList):void {
if (fileList.length <= 0) return;
// Files from Drop - add them to state to prepare for upload
const newFiles = Array.prototype.slice.call(fileList);
// this.setState({files: this.state.files.concat(files)});
const combinedFiles = files.concat(newFiles as any);
setFiles(combinedFiles);
console.log('Added files for message:', files);
}
return (
<section ref={composerRef} className="composer">
<h3 id="composer-title" className="sr-only">Compose a Message</h3>
<form className="composer-form" onSubmit={createMessage} autoComplete="off" aria-labelledby="composer-title">
<input type="hidden" value={props.username} />
<div className="input-area">
<input ref={messageRef} onKeyDown={handleInputKeys} name="message" className="message" placeholder="Type a message" spellCheck="false" autoComplete="off" required />
<button className="btn btn-primary send" type="submit">Send</button>
</div>
</form>
{/* TODO: hide for desktop, show for Mobile? */}
<button className="btn btn-secondary attachment" onClick={toggleShowFileModal}>
💾
{(files.length && files.length > 0) ?
<span className="badge badge-info badge">{files.length}</span>
: null
}
</button>
<FileUploadModal
show={showFileModal}
onHide={toggleShowFileModal}
callback={addFilesForUpload}
/>
</section>
);
}
|
thiessenp/chatapp-web
|
client/src/components/Roster.tsx
|
<filename>client/src/components/Roster.tsx
import {useState, useRef, useEffect} from 'react';
import {ListNav} from 'keynav-web';
import './Roster.scss';
export function Roster(props) {
const [listNav, setListNav] = useState<any>(null);
const rosterRef = useRef<HTMLOListElement>(null);
// Add Keynav when component created (remove it when destroyed)
useEffect(() => {
if (rosterRef.current) {
setListNav(new ListNav({
listEl: rosterRef.current,
listItemsSelector: 'li'
}));
}
return () => {
if (listNav) {
listNav.removeBehavior();
setListNav(null);
}
}
// chatId needed so will update when Route changes (on diff chat shown)
}, [props.chatId]);
return (
<section className="roster">
<h3 className="sr-only">Roster</h3>
{props.roster.length === 0 &&
<div>No Users yet?</div>
}
{props.roster.length > 0 &&
<ol className="list" ref={rosterRef}>
{props.roster && props.roster.map(user => {
return (
<li className="item" key={user.id}>{user.username}</li>
)
})}
</ol>
}
</section>
)
}
|
QuietWind/find-imports
|
test/index.test.ts
|
<gh_stars>0
import * as assert from "assert";
import * as path from "path";
import f, { findImports } from "./../src/index";
describe("findImports", () => {
describe("#findImports fixture", () => {
const strs = f.findImportsByName(
path.resolve(__dirname, "./files/fixture.js")
);
it("find all require files", () => {
assert.deepEqual(strs, [
"foo",
"vue/dist/vue",
"wow",
"baby",
"./async-module"
]);
});
});
describe("#findImports fixture-export", () => {
const strs = f.findImportsByName(
path.resolve(__dirname, "./files/fixture-export.js")
);
it("find all require files", () => {
assert.deepEqual(strs, ["./util", "./temporary", "./persistent", "all"]);
});
});
describe("#findImports App.tsx", () => {
const strs = f.findImportsByName(
path.resolve(__dirname, "./files/App.tsx")
);
it("find all require files", () => {
assert.deepEqual(strs, [
"react",
"react-router-dom",
"./Todo",
"./NormalTodo",
"./Home",
"./App.css",
"./logo.svg"
]);
});
});
describe("#findImports App.tsx and child", () => {
const strs = findImports(path.resolve(__dirname, "./files/App.tsx"), {
findChild: true,
log: false,
baseUrl: [process.cwd(), process.cwd() + "node_modules"]
});
it("find all require files", () => {
assert.deepEqual(strs, [
"react",
"react-router-dom",
"test/files/Todo.tsx",
"test/files/NormalTodo.tsx",
"test/files/Home.tsx",
"react-addons-perf",
"test/files/TodoItem.tsx",
"immutable",
"test/files/data.ts"
]);
});
});
});
|
QuietWind/find-imports
|
test/files/NormalTodo.tsx
|
import * as React from "react";
import { Link } from "react-router-dom";
import { TodoItem, TTodoItem } from "./TodoItem";
import { Map } from "immutable";
import * as Perf from "react-addons-perf";
import testData from "./data";
import "./Todo.css";
window.Perf = Perf;
interface TodoProps {}
interface TodoState {
normalTodos: TTodoItem[];
}
function normalAddItem(data: TTodoItem[], item: TTodoItem) {
const newData = [...data];
newData.unshift(item);
return newData;
}
export class Todo extends React.Component<TodoProps, TodoState> {
private input: HTMLInputElement | null;
constructor(props: TodoProps) {
super(props);
this.state = {
normalTodos: testData
};
this.normalAdd = this.normalAdd.bind(this);
}
getVal() {
if (!this.input || !this.input.value) {
return "";
}
const value = this.input.value;
return value;
}
normalAdd() {
const value = this.getVal();
if (!value) {
return;
}
const newTodos = normalAddItem(this.state.normalTodos, {
title: value,
check: false
});
this.setState({
normalTodos: newTodos
});
}
changeStatus = (todo: TTodoItem, index: number) => {
const { normalTodos } = this.state;
const newTodos = [
...normalTodos.slice(0, index),
{
title: todo.title,
check: !todo.check
},
...normalTodos.slice(index + 1)
];
this.setState({
normalTodos: newTodos
});
};
public render(): JSX.Element {
return (
<div>
<p>
<Link to="/todo">Todo</Link>
vs
<Link to="/normaltodo">Normal Todo</Link>
</p>
<div className="add">
<input
ref={node => {
this.input = node;
}}
onKeyDown={eve => {
if (eve.keyCode === 13) {
this.normalAdd();
}
}}
type="text"
/>
<button onClick={this.normalAdd}>Normal add</button>
</div>
<br />
<br />
<div>
<ul className="todos">
{this.state.normalTodos.map((todo, index) => {
if (!todo) {
return null;
}
return (
<TodoItem
key={index}
todo={Map(todo)}
index={index}
onChange={this.changeStatus}
/>
);
})}
</ul>
</div>
</div>
);
}
}
export default Todo;
|
QuietWind/find-imports
|
src/index.ts
|
import { extname, relative, isAbsolute } from "path";
import * as fs from "fs";
import * as store from "data-store";
import { digest, findModulePath, extensions } from "./file";
import { findImportsByName, findImportsByNameAsync } from "./find.by.name";
export interface TFindImportsOptions {
findChild: boolean;
log: boolean; // log result imports
baseUrl: string[];
}
function logStrings(strs: string[]) {
console.log(strs.join("\n"));
}
function filenamekey(filename: string) {
return digest(filename);
}
const findStore = store("FINDIMPORTS");
findStore.clear(); // clear memory data
const uniqueArray = function(arrArg: string[]) {
return arrArg.filter(function(elem, pos, arr) {
return arr.indexOf(elem) === pos;
});
};
function findAllImports(
filename: string,
options: TFindImportsOptions
): string[] {
if (!filename || !fs.existsSync(filename)) {
console.log(`${filename} not find.`);
return [];
}
const { findChild, log, baseUrl } = options;
const key = filenamekey(filename);
const storeItems = findStore.get(key);
const dataImports: string[] = storeItems || findImportsByName(filename);
if (log) {
logStrings(dataImports);
}
const abPaths = (items: string[]): string[] => {
const strs: string[] = [];
items.forEach(p => {
const r = findModulePath(filename, p, {
baseUrl
});
if (r) {
strs.push(r);
} else if (!extname(p)) {
// filter not in extensions
strs.push(p);
}
});
findStore.set(key, [...strs]);
return strs;
};
if (findChild) {
const items = abPaths(dataImports).reduce((prev, next) => {
const s = findStore.get(filenamekey(next));
if (s) return [...prev];
if (
!fs.existsSync(next) ||
extensions.findIndex(e => e === extname(next)) < 0
) {
return [...prev];
}
return [...prev, ...findImports(next, options)];
}, dataImports);
return uniqueArray(abPaths(items));
} else {
return uniqueArray(abPaths(dataImports));
}
}
export function findImports(filename: string, options: TFindImportsOptions) {
const paths = findAllImports(filename, options);
return paths.map(ele => {
if (isAbsolute(ele)) {
return relative(options.baseUrl[0], ele);
}
return ele;
});
}
export default {
findImports,
findImportsByName,
findImportsByNameAsync
};
|
QuietWind/find-imports
|
test/files/prueRender.tsx
|
import * as React from "react";
import { is } from "immutable";
// function diffValue(a: any, b: any) {
// if (typeof a === "function" || typeof b === "function") {
// return true;
// } else if (!is(Map(a), Map(b))) {
// return false;
// }
// return true;
// }
// function diffEqual(a: Object, b: Object) {
// // is 只是针对 immutable collection 对象
// for (const key in a) {
// if (!diffValue(a[key], b[key])) {
// return false;
// }
// }
// return true;
// }
export function PrueRender<P>(ComposedComponent: React.ComponentClass<P>) {
class PrueRenderHoc extends React.Component<any, any> {
static displayName = "PrueRenderHOC";
shouldComponentUpdate(nextProps: any = {}, nextState: any = {}) {
const thisProps = this.props || {};
const thisState = this.state || {};
nextProps = nextProps || {};
nextState = nextState || {};
if (
Object.keys(thisProps).length !== Object.keys(nextProps).length ||
Object.keys(thisState).length !== Object.keys(nextState).length
) {
return true;
}
for (const key in nextProps) {
if (!is(thisProps[key], nextProps[key])) {
return true;
}
}
for (const key in nextState) {
if (
thisState[key] !== nextState[key] ||
!is(thisState[key], nextState[key])
) {
return true;
}
}
return false;
}
render() {
return <ComposedComponent {...this.props} />;
}
}
return PrueRenderHoc;
}
export default PrueRender;
|
QuietWind/find-imports
|
types/index.d.ts
|
<reponame>QuietWind/find-imports
declare module "babel-traverse";
declare module "data-store";
|
QuietWind/find-imports
|
lib/find.by.name.d.ts
|
<reponame>QuietWind/find-imports<filename>lib/find.by.name.d.ts
export declare function findImportsByName(filename: string): string[];
export declare function findImportsByNameAsync(filename: string): Promise<string[]>;
|
QuietWind/find-imports
|
src/util.ts
|
<gh_stars>0
import * as colors from "colors";
export function msgError(text: string) {
console.log(colors.red(text));
}
export function msgSuccess(text: string) {
console.log(colors.green(text));
}
|
QuietWind/find-imports
|
src/find.by.name.ts
|
<gh_stars>0
import * as fs from "fs";
import * as path from "path";
import { findImportsByStr } from "./find.by.str";
const r = (str: string, filename: string): string[] => {
const ext = path.extname(filename);
const options = {
isTS: /\.tsx?$/i.test(ext),
filename
};
return findImportsByStr(str, options);
};
export function findImportsByName(filename: string): string[] {
const data_str = fs.readFileSync(filename, "utf8");
return r(data_str, filename);
}
export function findImportsByNameAsync(filename: string): Promise<string[]> {
return new Promise((resolve, reject) => {
fs.readFile(filename, "utf8", (err, data_str) => {
if (err) {
console.log(err);
reject([]);
return;
}
resolve(r(data_str, filename));
});
});
}
|
QuietWind/find-imports
|
lib/find.by.str.d.ts
|
export interface TFindImportsByStrOptions {
isTS: boolean;
filename: string;
}
export declare function findImportsByStr(str: string, options: TFindImportsByStrOptions): string[];
|
QuietWind/find-imports
|
test/files/TodoItem.tsx
|
<reponame>QuietWind/find-imports<filename>test/files/TodoItem.tsx
import * as React from "react";
import { Map, is } from "immutable";
export interface TTodoItem {
title: string;
check?: boolean;
}
interface TodoItemProps {
index: number;
onChange: any;
todo: Map<string, any>;
}
interface TodoItemState {}
export class TodoItem extends React.Component<TodoItemProps, TodoItemState> {
shouldComponentUpdate(nextProps: TodoItemProps) {
// if (
// nextProps.todo.title !== this.props.todo.title ||
// nextProps.todo.check !== this.props.todo.check
// ) {
// return true;
// } else {
// return false;
// }
/**
* immutable-js
*/
if (!is(nextProps.todo, this.props.todo)) {
return true;
} else {
return false;
}
}
public render(): JSX.Element {
const { todo, index, onChange } = this.props;
const title = todo.get("title");
const check = todo.get("check");
return (
<li className="todoitem">
<span className="title">{title}</span>
<span className="status">
<input
type="checkbox"
onChange={() => {
onChange(todo, index);
}}
checked={check ? true : false}
/>
</span>
</li>
);
}
}
export default TodoItem;
|
QuietWind/find-imports
|
test/files/Todo.tsx
|
<gh_stars>0
import * as React from "react";
import { Link } from "react-router-dom";
import * as Perf from "react-addons-perf";
import { TodoItem } from "./TodoItem";
import { List, Map, fromJS, is } from "immutable";
import testData from "./data";
import "./Todo.css";
window.Perf = Perf;
interface TodoProps {}
interface TodoState {
todos: List<Map<string, any>>;
}
// const c1 = Map({ title: "周六欢迎致辞", check: undefined });
// const c2 = Map({ title: "周六欢迎致辞", check: undefined });
console.log(
is(
{ title: "周六欢迎致辞", check: undefined },
{ title: "周六欢迎致辞", check: undefined }
)
);
export class Todo extends React.Component<TodoProps, TodoState> {
private input: HTMLInputElement | null;
constructor(props: TodoProps) {
super(props);
this.state = {
todos: fromJS(testData)
};
this.addItem = this.addItem.bind(this);
}
getVal() {
if (!this.input || !this.input.value) {
return "";
}
const value = this.input.value;
return value;
}
addItem() {
const value = this.getVal();
if (!value) {
return;
}
const { todos } = this.state;
const item = Map({
title: value,
check: false
});
const newTodos = todos.unshift(item);
this.setState(
{
todos: newTodos
},
() => {
if (this.input) {
this.input.value = "";
}
}
);
}
changeStatus = (todo: Map<string, any>, index: number) => {
const newTodos = this.state.todos.setIn(
[index, "check"],
!todo.get("check")
);
this.setState({
todos: newTodos
});
}
public render(): JSX.Element {
const { todos } = this.state;
return (
<div>
<p>
<Link to="/todo">Todo</Link>
vs
<Link to="/normaltodo">Normal Todo</Link>
</p>
<div className="add">
<input
ref={node => {
this.input = node;
}}
onKeyDown={eve => {
if (eve.keyCode === 13) {
this.addItem();
}
}}
type="text"
/>
<button onClick={this.addItem}>Immutablejs Add</button>
</div>
<br />
<br />
<div>
<ul className="todos">
{todos.map((todo, index) => {
if (!todo || index === undefined) {
return null;
}
return (
<TodoItem
key={index}
todo={todo}
index={index}
onChange={this.changeStatus}
/>
);
})}
</ul>
</div>
</div>
);
}
}
export default Todo;
|
QuietWind/find-imports
|
test/files/Enhance.tsx
|
<gh_stars>0
import * as React from "react";
export function IntervalEnhance<P>(ComposedComponent: React.ComponentClass<P>) {
return class extends React.Component<any, any> {
static displayName = "ComponentEnhancedWithIntervalHOC";
interval: number;
constructor(props: any) {
super(props);
this.state = {
seconds: 0
};
}
componentDidMount() {
this.interval = setInterval(this.tick.bind(this), 1000);
}
componentWillUnmount() {
clearInterval(this.interval);
}
tick() {
this.setState({
seconds: this.state.seconds + 2
});
}
render() {
return <ComposedComponent {...this.props} {...this.state} />;
}
};
}
|
QuietWind/find-imports
|
test/files/Home.tsx
|
<gh_stars>0
import * as React from "react";
interface HomeProps {}
interface HomeState {}
export class Home extends React.Component<HomeProps, HomeState> {
public render(): JSX.Element {
return <span>Home</span>;
}
}
export default Home;
|
QuietWind/find-imports
|
lib/file.d.ts
|
<filename>lib/file.d.ts<gh_stars>0
export declare const extensions: string[];
export interface PathOption {
baseUrl: string[];
}
export declare function digest(str: string): string;
export declare function genPath(root: string, filename: string): string | null;
/**
* node_modules do not thinks
* @param filename_rootfile
* @param filename
* @param options
*/
export declare function findModulePath(filename_rootfile: string, filename: string, options?: PathOption): string | null;
|
QuietWind/find-imports
|
test/files/App.tsx
|
import * as React from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import Todo from "./Todo";
import NormalTodo from "./NormalTodo";
import { Home } from "./Home";
import "./App.css";
const logo = require("./logo.svg");
class App extends React.Component {
render() {
return (
<Router>
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<Route path="/" component={Home} />
<Route path="/todo" component={Todo} />
<Route path="/normaltodo" component={NormalTodo} />
<p className="App-intro">
To get started, edit <code>src/App.tsx</code> and save to reload.
</p>
</div>
</Router>
);
}
}
export default App;
|
QuietWind/find-imports
|
lib/util.d.ts
|
<filename>lib/util.d.ts
export declare function msgError(text: string): void;
export declare function msgSuccess(text: string): void;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.