repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
ymatzki/eslint-plugin
lib/rules/prefer-parameter-instance.ts
<reponame>ymatzki/eslint-plugin // ------------------------------------------------------------------------------ // Imports // ------------------------------------------------------------------------------ import { createRule, TSKeywordMap } from "../util"; import { TSESTree, AST_NODE_TYPES, } from "@typescript-eslint/experimental-utils"; // ------------------------------------------------------------------------------ // Helpers // ------------------------------------------------------------------------------ const isKeywordType = (type: string) => Object.keys(TSKeywordMap).includes(type); // ------------------------------------------------------------------------------ // Settings of createRule // ------------------------------------------------------------------------------ type Options = { onlyReference: boolean; allowKeywords?: boolean; }; const defaultOptions: [Options] = [ { onlyReference: false, allowKeywords: false, }, ]; type MessageIds = "onlyReference"; // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ export = createRule<[Options], MessageIds>({ name: "prefer-parameter-instance", meta: { docs: { description: "Check generics paramater instance whether expected", category: "Best Practices", recommended: false, }, type: "suggestion", messages: { onlyReference: "Prefer use type reference like `type`, `interface` etc...", }, schema: [ { type: "object", properties: { onlyReference: { type: "boolean", }, allowKeywords: { type: "boolean", }, }, required: ["onlyReference"], }, ], }, defaultOptions, create(context, optionsWithDefault) { const onlyReference = context.options[0]?.onlyReference ?? optionsWithDefault[0]?.onlyReference; const allowKeywords = context.options[0]?.allowKeywords ?? optionsWithDefault[0]?.allowKeywords; return { "TSTypeParameterInstantiation[params.length>0]"( node: TSESTree.TSTypeParameterInstantiation ) { for (const param of node.params) { if (param.type === AST_NODE_TYPES.TSTypeReference) continue; if (allowKeywords && isKeywordType(param.type)) continue; if (onlyReference) { context.report({ node: param, loc: param.loc, messageId: "onlyReference", }); } } }, }; }, });
ymatzki/eslint-plugin
lib/rules/use-name-space-import.ts
<reponame>ymatzki/eslint-plugin<filename>lib/rules/use-name-space-import.ts<gh_stars>1-10 // ------------------------------------------------------------------------------ // Imports // ------------------------------------------------------------------------------ import { createRule } from "../util"; import { TSESTree, AST_NODE_TYPES, } from "@typescript-eslint/experimental-utils"; import minimatch from "minimatch"; // ------------------------------------------------------------------------------ // Helpers // ------------------------------------------------------------------------------ /** * whether module doesn't need to be `nameSpaceImport` */ const isAllowNotNameSpaceImportModule = ( node: TSESTree.ImportDeclaration, allowNotNameSpaceImportModules: Options["allowNotNameSpaceImportModules"] ) => { if (typeof node.source.value !== "string") return false; if ( !allowNotNameSpaceImportModules || allowNotNameSpaceImportModules.length === 0 ) return false; return allowNotNameSpaceImportModules.some((allowModuleName) => { if (typeof node.source.value !== "string") return false; return minimatch(node.source.value, allowModuleName); }); }; const hasImportDefaultSpecifier = (node: TSESTree.ImportDeclaration) => { if (typeof node.source.value !== "string") return false; return node.specifiers.some( (specifier) => specifier.type === AST_NODE_TYPES.ImportDefaultSpecifier ); }; // ------------------------------------------------------------------------------ // Settings of createRule // ------------------------------------------------------------------------------ type Options = { allowNotNameSpaceImportModules?: string[]; allowDefaultImport?: boolean; }; const defaultOptions: [Options] = [ { allowDefaultImport: false, }, ]; type MessageIds = "useNameSpaceImport"; // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ export = createRule<[Options], MessageIds>({ name: "use-name-space-import", meta: { docs: { description: "Use name space import", category: "Best Practices", recommended: false, }, type: "suggestion", messages: { useNameSpaceImport: "Should use name space import if import module from {{ moduleName }}.", }, schema: [ { type: "object", properties: { allowNotNameSpaceImportModules: { type: "array", items: { type: "string", }, }, allowDefaultImport: { type: "boolean", }, }, }, ], }, defaultOptions, create(context, optionsWithDefault) { const allowNotNameSpaceImportModules = context.options[0]?.allowNotNameSpaceImportModules ?? optionsWithDefault[0]?.allowNotNameSpaceImportModules; const allowDefaultImport = context.options[0]?.allowDefaultImport ?? optionsWithDefault[0]?.allowDefaultImport; return { 'ImportDeclaration[parent.type="Program"]'( node: TSESTree.ImportDeclaration ) { // Exclude name space import if ( node.specifiers.length === 0 || node.specifiers[0].type === AST_NODE_TYPES.ImportNamespaceSpecifier ) return; if ( isAllowNotNameSpaceImportModule(node, allowNotNameSpaceImportModules) ) return; if ( node.specifiers.length === 1 && allowDefaultImport && hasImportDefaultSpecifier(node) ) return; context.report({ node, loc: node.loc, messageId: "useNameSpaceImport", data: { moduleName: node.source.value, }, }); }, }; }, });
ymatzki/eslint-plugin
tests/lib/rules/no-multiple-named-imports.spec.ts
<reponame>ymatzki/eslint-plugin<filename>tests/lib/rules/no-multiple-named-imports.spec.ts import { RuleTester } from "../../util"; import rule from "../../../lib/rules/no-multiple-named-imports"; const tester = new RuleTester({ parser: "@typescript-eslint/parser", parserOptions: { sourceType: "module", ecmaFeatures: { jsx: true, }, }, }); tester.run("no-multiple-named-imports", rule, { valid: [ { code: ` import { FC } from 'react'; `, }, { code: ` import defaultExportMember, {member1} from 'module'; `, }, ], invalid: [ { code: ` import { FC, FunctionComponent } from 'react'; `, errors: [{ messageId: "noMultipleNamedImports" }], }, { code: ` import defaultExportMember, {member1, module2} from 'module'; `, errors: [{ messageId: "noMultipleNamedImports" }], }, ], });
ymatzki/eslint-plugin
lib/util/keywords.ts
import { AST_NODE_TYPES } from "@typescript-eslint/experimental-utils"; // @see https://github.com/typescript-eslint/typescript-eslint/blob/1765a178e456b152bd48192eb5db7e8541e2adf2/packages/eslint-plugin/src/rules/no-inferrable-types.ts#L95 const keywordMap = { [AST_NODE_TYPES.TSBigIntKeyword]: "bigint", [AST_NODE_TYPES.TSBooleanKeyword]: "boolean", [AST_NODE_TYPES.TSNumberKeyword]: "number", [AST_NODE_TYPES.TSNullKeyword]: "null", [AST_NODE_TYPES.TSStringKeyword]: "string", [AST_NODE_TYPES.TSSymbolKeyword]: "symbol", [AST_NODE_TYPES.TSUndefinedKeyword]: "undefined", }; export const TSKeywordMap = { ...keywordMap, [AST_NODE_TYPES.TSAnyKeyword]: "any", [AST_NODE_TYPES.TSUnknownKeyword]: "unknown", [AST_NODE_TYPES.TSVoidKeyword]: "void", };
ymatzki/eslint-plugin
lib/rules.ts
<reponame>ymatzki/eslint-plugin // This file has been automatically generated, in order to update it's content execute "npm run update" import noMultipleNamedImports from "./rules/no-multiple-named-imports"; import noUseFunctionComponentTypeWithoutChildren from "./rules/no-use-function-component-type-without-children"; import preferParameterInstance from "./rules/prefer-parameter-instance"; import useNameSpaceImport from "./rules/use-name-space-import"; export const rules = { "no-multiple-named-imports": noMultipleNamedImports, "no-use-function-component-type-without-children": noUseFunctionComponentTypeWithoutChildren, "prefer-parameter-instance": preferParameterInstance, "use-name-space-import": useNameSpaceImport, };
ymatzki/eslint-plugin
lib/util/isFunctionComponentType.ts
<gh_stars>1-10 const FunctionComponentTypes = ["FunctionComponent", "FC"]; export const isFunctionComponentType = (name: string) => FunctionComponentTypes.some((type) => new RegExp(String.raw`^.*${type}$`, "u").test(name) );
ymatzki/eslint-plugin
tests/lib/rules/no-use-function-component-type-without-children.spec.ts
import { RuleTester } from "../../util"; import rule from "../../../lib/rules/no-use-function-component-type-without-children"; const tester = new RuleTester({ parser: "@typescript-eslint/parser", parserOptions: { sourceType: "module", ecmaFeatures: { jsx: true, }, }, }); tester.run("no-use-function-component-type-without-children", rule, { valid: [ { code: ` import * as React from "react"; type Props = { name: string; }; export const Component = (props: Props) => <div>{props.name}</div>; `, }, { code: ` import * as React from "react"; type Props = { name: string; }; export const Component: React.FC<Props> = (props) => <div>{props.name} <p>{props.children}</p></div>; `, }, { code: ` import * as React from "react"; type Props = { name: string; }; export const Component: React.FC<Props> = (props) => { const foobarchildren = props.children return ( <div>{props.name} <p>{foobarchildren}</p></div> ) }; `, }, { code: ` import * as React from "react"; type Props = { name: string; }; export const Component: React.FC<Props> = (props) => { const foobarchildren = props['children'] return ( <div>{props.name} <p>{foobarchildren}</p></div> ) }; `, }, { code: ` import * as React from "react"; type Props = { name: string; }; export const Component: React.FC<Props> = (props) => { const { children } = props return ( <div>{props.name} <p>{children}</p></div> ) }; `, }, { code: ` import * as React from "react"; type Props = { name: string; }; export const Component = (props): React.ReactElement => <div>{props.name}</div> `, }, ], invalid: [ { code: ` import * as React from 'react'; type Props = { name: string; }; export const Component: React.FunctionComponent<Props> = (props: Props) => <div>{props.name}</div>; `, errors: [{ messageId: "noUseFunctionComponentTypeWithoutChildren" }], }, { code: ` import { FunctionComponent } from 'react'; type Props = { name: string; }; export const Component: FunctionComponent<Props> = (props: Props) => <div>{props.name}</div>; `, errors: [{ messageId: "noUseFunctionComponentTypeWithoutChildren" }], }, { code: ` import * as React from 'react'; type Props = { name: string; }; export const Component: React.FC<Props> = (props: Props) => <div>{props.name}</div>; `, errors: [{ messageId: "noUseFunctionComponentTypeWithoutChildren" }], }, { code: ` import { FC } from 'react'; type Props = { name: string; }; export const Component: FC<Props> = (props: Props) => <div>{props.name}</div>; `, errors: [{ messageId: "noUseFunctionComponentTypeWithoutChildren" }], }, ], });
ymatzki/eslint-plugin
lib/util/createRule.ts
<gh_stars>1-10 import { ESLintUtils } from "@typescript-eslint/experimental-utils"; // eslint-disable-next-line new-cap export const createRule = ESLintUtils.RuleCreator( (name) => `https://github.com/hrbrain/eslint-plugin/blob/master/docs/rules/${name}.md` );
ymatzki/eslint-plugin
tests/lib/rules/use-name-space-import.spec.ts
import { RuleTester } from "../../util"; import rule from "../../../lib/rules/use-name-space-import"; const tester = new RuleTester({ parser: "@typescript-eslint/parser", parserOptions: { sourceType: "module", ecmaFeatures: { jsx: true, }, }, }); tester.run("use-name-space-import", rule, { valid: [ { code: "import * as React from 'react';", }, { code: "import 'minireset.css';", }, { code: "import React from 'react';", options: [{ allowNotNameSpaceImportModules: ["react"] }], }, { code: ` import Module1 from 'module/1'; import Module2 from 'module/2'; import React from 'react'; `, options: [{ allowNotNameSpaceImportModules: ["module/**/*", "react"] }], }, { code: "import React from 'react';", options: [{ allowDefaultImport: true }], }, ], invalid: [ { code: ` import React from 'react'; `, errors: [{ messageId: "useNameSpaceImport" }], }, { code: ` import { createSlice, configureStore, PayloadAction } from '@reduxjs/toolkit'; `, errors: [{ messageId: "useNameSpaceImport" }], }, { code: "import React, { useState } from 'react';", options: [{ allowDefaultImport: true }], errors: [{ messageId: "useNameSpaceImport" }], }, ], });
ymatzki/eslint-plugin
lib/util/index.ts
export * from "./createRule"; export * from "./createLibIndex"; export * from "./isFunctionComponentType"; export * from "./keywords";
ymatzki/eslint-plugin
lib/rules/no-multiple-named-imports.ts
// ------------------------------------------------------------------------------ // Imports // ------------------------------------------------------------------------------ import { createRule } from "../util"; import { TSESTree, AST_NODE_TYPES, } from "@typescript-eslint/experimental-utils"; // ------------------------------------------------------------------------------ // Helpers // ------------------------------------------------------------------------------ const countImportSpecifier = (node: TSESTree.ImportDeclaration) => node.specifiers.filter( (specifier) => specifier.type === AST_NODE_TYPES.ImportSpecifier ).length; // ------------------------------------------------------------------------------ // Settings of createRule // ------------------------------------------------------------------------------ const defaultOptions: [] = []; type MessageIds = "noMultipleNamedImports"; // ------------------------------------------------------------------------------ // Rule Definition // ------------------------------------------------------------------------------ export = createRule<[], MessageIds>({ name: "no-multiple-named-imports", meta: { docs: { description: "Don't imports as named import from a module", category: "Best Practices", recommended: false, }, type: "suggestion", messages: { noMultipleNamedImports: "Should not multiple imports from '{{ moduleName }}' module", }, schema: [], }, defaultOptions, create(context) { return { "ImportDeclaration[specifiers.length>1]"( node: TSESTree.ImportDeclaration ) { if (countImportSpecifier(node) >= 2) { context.report({ node, loc: node.loc, messageId: "noMultipleNamedImports", data: { moduleName: node.source.value, }, }); } }, }; }, });
jmfirth/netlify-test-microsite
src/pages/contact/thanks.tsx
<reponame>jmfirth/netlify-test-microsite import React from "react"; import Layout from '../../components/Layout' export default (() => ( <Layout> <section className="section"> <div className="container"> <div className="content"> <h1>Thank you!</h1> <p>This is a custom thank you page for form submissions</p> </div> </div> </section> </Layout> )) as React.SFC;
jmfirth/netlify-test-microsite
src/cms/preview-templates/common.ts
import { Iterable } from 'immutable'; export interface PreviewProps { entry: Iterable<any, any>; widgetFor: (name: string) => string; getAsset: <R>(name: string) => R; }
jmfirth/netlify-test-microsite
src/cms/preview-templates/BlogPostPreview.tsx
<filename>src/cms/preview-templates/BlogPostPreview.tsx import React from 'react'; import { BlogPostTemplate } from '../../templates/blog-post'; import { PreviewProps } from './common'; export interface BlogPostPreviewProps extends PreviewProps {} const BlogPostPreview: React.SFC<BlogPostPreviewProps> = ({ entry, widgetFor }) => ( <BlogPostTemplate content={widgetFor('body')} description={entry.getIn(['data', 'description'])} tags={entry.getIn(['data', 'tags'])} title={entry.getIn(['data', 'title'])} /> ); export default BlogPostPreview;
jmfirth/netlify-test-microsite
src/components/Navbar.tsx
import React from 'react'; import { Link } from 'gatsby'; import github from '../img/github-icon.svg'; import logo from '../img/logo.svg'; const Navbar: React.SFC = () => ( <nav className="navbar is-transparent"> <div className="container"> <div className="navbar-brand"> <Link to="/" className="navbar-item"> <figure className="image"> <img src={logo} alt="Kaldi" style={{ width: '88px' }} /> </figure> </Link> </div> <div className="navbar-start"> <Link className="navbar-item" to="/about"> About </Link> <Link className="navbar-item" to="/products"> Products </Link> <Link className="navbar-item" to="/contact"> Contact </Link> <Link className="navbar-item" to="/contact/examples"> Form Examples </Link> </div> <div className="navbar-end"> <a className="navbar-item" href="https://github.com/AustinGreen/gatsby-netlify-cms-boilerplate" target="_blank" rel="noopener noreferrer" > <span className="icon"> <img src={github} alt="Github" /> </span> </a> </div> </div> </nav> ); export default Navbar;
jmfirth/netlify-test-microsite
src/declarations/external.d.ts
<filename>src/declarations/external.d.ts declare module '*.svg' { export default string; } // declare module 'netlify-cms' { // interface NetlifyCMS { // registerPreviewTemplate: (name: string, component: React.ComponentType<any>) => any; // } // const CMS: NetlifyCMS; // export default CMS; // }
jmfirth/netlify-test-microsite
src/cms/preview-templates/AboutPagePreview.tsx
<reponame>jmfirth/netlify-test-microsite<gh_stars>0 import React from 'react'; import { AboutPageTemplate } from '../../templates/about-page'; import { PreviewProps } from './common'; export interface AboutPagePreviewProps extends PreviewProps {} const AboutPagePreview: React.SFC<AboutPagePreviewProps> = ({ entry, widgetFor }) => ( <AboutPageTemplate title={entry.getIn(['data', 'title'])} content={widgetFor('body')} /> ); export default AboutPagePreview;
jmfirth/netlify-test-microsite
src/components/PreviewCompatibleImage.tsx
import React from 'react'; import Img from 'gatsby-image'; export interface ChildImageSharp { fluid: { src: string; }; } export type ChildImageSharpVariants = ChildImageSharp | undefined; export type Image = ImageInfo | string; export interface ImageInfo<CIS = ChildImageSharpVariants> { alt?: string; childImageSharp: CIS; image: Image; style?: React.CSSProperties; } export function isImageInfo<HCIS extends boolean>( o: any, hasChildImageSharp: HCIS ): o is ImageInfo<HCIS extends true ? ChildImageSharp : undefined> { return o && (hasChildImageSharp ? o.childImageSharp : true); } export interface PreviewCompatibleImageProps { imageInfo: ImageInfo | string; } const PreviewCompatibleImage: React.SFC<PreviewCompatibleImageProps> = ({ imageInfo }) => { const imageStyle = { borderRadius: '5px' }; const { alt = '', childImageSharp, image } = (imageInfo as ImageInfo); if (isImageInfo(image, true)) { return ( <Img style={imageStyle} fluid={image.childImageSharp.fluid} alt={alt} /> ); } if (!!childImageSharp) { return <Img style={imageStyle} fluid={childImageSharp.fluid} alt={alt} />; } if (!!image && typeof image === 'string') return <img style={imageStyle} src={image} alt={alt} />; return null; }; export default PreviewCompatibleImage;
jmfirth/netlify-test-microsite
src/pages/contact/examples.tsx
<reponame>jmfirth/netlify-test-microsite import React from 'react'; import Link from 'gatsby-link'; import Layout from '../../components/Layout' export default class Index extends React.Component { render() { return ( <Layout> <section className="section"> <div className="container"> <div className="content"> <h1>Hi people</h1> <p> This is an example site integrating Netlify’s form handling with Gatsby </p> <ul> <li><Link to="/contact">Basic contact form</Link></li> <li><Link to="/contact/file-upload/">Form with file upload</Link></li> </ul> <h2>Troubleshooting</h2> <h3>Forms stop working after upgrading to Gatsby v2</h3> <p>This can be caused by the offline-plugin. <a href="https://github.com/gatsbyjs/gatsby/issues/7997#issuecomment-419749232">Workaround</a> is to use <code>?no-cache=1</code> in the POST url to prevent the service worker from handling form submissions</p> </div> </div> </section> </Layout> ); } }
jmfirth/netlify-test-microsite
src/templates/about-page.tsx
import React from 'react'; import { graphql } from 'gatsby'; import Layout from '../components/Layout'; import Content, { HTMLContent, BaseContentProps } from '../components/Content'; export interface AboutPageTemplateProps { title?: React.ReactText; content: string; contentComponent?: React.ComponentType<BaseContentProps<any>>; } export const AboutPageTemplate: React.SFC<AboutPageTemplateProps> = ({ title, content, contentComponent }) => { const PageContent = contentComponent || Content return ( <section className="section section--gradient"> <div className="container"> <div className="columns"> <div className="column is-10 is-offset-1"> <div className="section"> <h2 className="title is-size-3 has-text-weight-bold is-bold-light"> {title} </h2> <PageContent className="content" content={content} /> </div> </div> </div> </div> </section> ) } export interface AboutPageProps { data: any; } const AboutPage: React.SFC<AboutPageProps> = ({ data }) => { const { markdownRemark: post } = data return ( <Layout> <AboutPageTemplate contentComponent={HTMLContent} title={post.frontmatter.title} content={post.html} /> </Layout> ) }; export default AboutPage; export const aboutPageQuery = graphql` query AboutPage($id: String!) { markdownRemark(id: { eq: $id }) { html frontmatter { title } } } `;
jmfirth/netlify-test-microsite
src/components/Content.tsx
import React from 'react'; export interface BaseContentProps<C> { content: C; className?: string; } export interface HTMLContentProps extends BaseContentProps<string> {} export interface ContentProps extends BaseContentProps<React.ReactText> {} export const HTMLContent: React.SFC<HTMLContentProps> = ({ content, className }) => ( <div className={className} dangerouslySetInnerHTML={{ __html: content }} /> ) const Content: React.SFC<ContentProps> = ({ content, className }) => ( <div className={className}>{content}</div> ) export default Content
ansballard/Frontend
src/store/index.ts
import createStore from "unistore"; import devtools from "unistore/devtools"; ///DEV_ONLY import jwtDecode from "jwt-decode"; import { clearLocalState, setLocalState, getLocalState } from "./local"; import { insertScriptIntoDom } from "./dom"; import { GlobalState } from "../types"; const user = getLocalState(); export const rawState = { notifications: [], user: user.username ? user : undefined, adsense: { loaded: false, failed: false } }; let _store = createStore(rawState); _store = devtools(_store); ///DEV_ONLY export const store = _store; let notificationCounter = 0; export const actions = store => ({ login(state: GlobalState, token) { const { sub, scopes } = jwtDecode(token); const user = { token, authenticated: true, username: sub, scopes }; setLocalState(user); return { ...state, user }; }, logout(state: GlobalState) { clearLocalState(); return { ...state, user: undefined }; }, async loadAdsenseAds(state: GlobalState) { if (state.adsense.loaded || state.adsense.failed) { return state; } try { await insertScriptIntoDom( "https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js" ); return { ...state, adsense: { loaded: true, failed: false } }; } catch (e) { store.setState( actions(store).addNotification(store.getState(), "Ads Blocked") ); return { ...state, adsense: { loaded: false, failed: true } }; } }, addNotification( state: GlobalState, message: string, { type = "info", delay = 3000, removalDelay = 300 }: { type?: string; delay?: number; removalDelay?: number; } = {} ) { const _id = `${notificationCounter++}`; return { ...state, notifications: state.notifications.concat({ message, removalDelay, delay, _id, type, softDelete: false }) }; }, /* ok then */ removeNotification(state: GlobalState, _id: string) { const onlyActiveIndex = state.notifications .map(({ softDelete }) => softDelete) .indexOf(false); if (onlyActiveIndex === 0 && state.notifications[0]._id === _id) { notificationCounter = 0; return { notifications: [] }; } const index = state.notifications.map(({ _id }) => _id).indexOf(_id); if (index !== -1) { return { ...state, notifications: state.notifications .slice(0, index) .concat({ ...state.notifications[index], softDelete: true }) .concat(state.notifications.slice(index + 1)) }; } } });
ansballard/Frontend
src/components/modwatch-file.tsx
import { h, Component } from "preact"; import "./modwatch-file.css"; import { Line } from "../types"; export default class ModwatchFile extends Component<{ lines: string[]; complexLines: boolean; showDescriptor: boolean; filetype?: string; filter: string; showInactiveMods: boolean; }> { render() { const { lines = [], complexLines = false, showDescriptor = false, filetype, filter = "", showInactiveMods = false } = this.props; return ( <div> <ul> {(!complexLines ? lines.map((line, index) => stringToSimpleLine( line, index, filetype, filter.toLowerCase(), showInactiveMods ) ) : lines.map((line, index) => stringToComplexLine(line, index, filter.toLowerCase()) ) ).map( line => !line.hide && ( <li class={`modlist-item ${ line.descriptor ? line.descriptor : "" } ${line.type ? line.type : ""}`} > <span class="modlist-item-index unselectable"> {line.index}. </span> <span class="modlist-item-content"> {line.content.map(chunk => ( <span class={chunk.class}>{chunk.display}</span> ))} </span> <span class="modlist-item-descriptor"> {showDescriptor && line.descriptor !== "comment" ? line.descriptor : ""} </span> </li> ) )} </ul> </div> ); } } const typeMap = { b: "type-boolean", s: "type-string", i: "type-integer", u: "type-unsigned", f: "type-float", r: "type-color" }; const modlistMap = { "*": "unmanaged", "+": "enabled", "-": "disabled" }; function stringToSimpleLine( originalLine: string, index: number, filetype: string, filter: string, showInactiveMods: boolean ): Line { const hide = (filter === "" ? false : !originalLine.toLowerCase().includes(filter)) || (filetype === "modlist" && !showInactiveMods && originalLine[0] === "-"); return hide ? { hide: true, index: index + 1 } : { descriptor: filetype === "plugins" ? originalLine.slice(-3) : modlistMap[originalLine[0]], index: index + 1, content: [ { class: "", display: originalLine } ] }; } function stringToComplexLine( originalLine: string, index: number, filter: string ): Line { const hide = filter === "" ? false : !originalLine.toLowerCase().includes(filter.toLowerCase()); if (hide) { return { hide: true, index: index + 1 }; } const descriptor = originalLine[0] !== ";" ? originalLine[0] !== "[" ? "setting" : "section" : "comment"; const commentIndex = originalLine.indexOf(";"); if ( (descriptor === "setting" && commentIndex === -1) || commentIndex > originalLine.indexOf("=") ) { const [key, value, comment] = originalLine.split(/[=;]/g, 3); return { descriptor, type: typeMap[originalLine[0]], index: index + 1, content: [ { class: "key", display: key }, { class: "assign", display: "=" }, { class: "value", display: value } ].concat( comment ? { class: "comment", display: comment } : [] ) }; } else { return { descriptor, index: index + 1, content: [ { class: "", display: originalLine } ] }; } }
ansballard/Frontend
tests/store/index.ts
const test = require("tape"); const proxyquire = require("proxyquire"); const { encode } = require("jwt-simple"); const jwtDecode = require("jwt-decode"); const { rawState, store, actions } = proxyquire("../../src/store/index", { "unistore/devtools": store => store, "./local": { clearLocalState: () => ({}), setLocalState: state => state, getLocalState: () => ({}) } }); test('login should decode the given token and update state.user with the contents', t => { const token = { sub: "Peanut", scopes: ["user"] }; const encodedToken = encode(token, "SECRET"); t.deepEqual(actions(store).login(rawState, encodedToken), { ...rawState, user: { token: encodedToken, authenticated: true, username: token.sub, scopes: token.scopes } }); t.end(); }); test('logout should reset state.user to undefined', t => { t.deepEqual(actions(store).logout(rawState), { ...rawState, user: undefined }); t.end(); }); test('loadAdsenseAds should short circuit if adsense has loaded or failed', async t => { t.deepEqual(await actions(store).loadAdsenseAds({ ...rawState, adsense: { loaded: true } }), { ...rawState, adsense: { loaded: true } }); t.deepEqual(await actions(store).loadAdsenseAds({ ...rawState, adsense: { failed: true } }), { ...rawState, adsense: { failed: true } }); t.end(); });
ansballard/Frontend
src/router/notFound.tsx
<reponame>ansballard/Frontend<filename>src/router/notFound.tsx import { h } from "preact"; export default (props: any) => ( <section> <h1>404 Not Found</h1> <p>Good try, but this page doesn't exist</p> </section> );
ansballard/Frontend
src/components/modwatch-modlists.tsx
<gh_stars>0 import { h, Component } from "preact"; import { Link } from "preact-router"; import { searchModlists, getModlists } from "../store/pure"; import { PartialModlist } from "../types"; const styles = { th: { borderBottom: "1px solid", padding: "3px" }, td: { padding: "3px" }, modlistTable: { width: "100%", textAlign: "left" } }; export default class ModwatchModlists extends Component< {}, { modlists: PartialModlist[]; gameMap: { [key: string]: string; }; debounceFilter?: number; filter: string; } > { state = { modlists: [], gameMap: { skyrim: "Skyrim Classic", skyrimse: "Skryim SE", fallout4: "Fallout 4" }, debounceFilter: undefined, filter: "" }; componentDidMount = async () => { const modlists = await getModlists(); this.setState(() => ({ modlists: prettifyModlists(modlists) })); }; search = (value = "", debounce = 150) => { clearTimeout(this.state.debounceFilter); this.setState(() => ({ filter: value, debounceFilter: window.setTimeout(async () => { if (value === "") { const modlists = await getModlists(); this.setState(() => ({ modlists: prettifyModlists(modlists) })); return; } const modlists = await searchModlists({ filter: value }); this.setState(() => ({ modlists: prettifyModlists(modlists) })); }, debounce) })); }; clear = () => { this.setState(() => ({ filter: "" })); this.search(undefined, 0); }; render() { return ( <div> <form> <label for="modlists-search" class="sr-only"> Search </label> <input type="text" placeholder="Search" id="modlists-search" value={this.state.filter} onInput={e => this.search((e.target as HTMLInputElement).value)} /> <button type="button" onClick={this.clear}> Clear </button> </form> <table style={styles.modlistTable}> <thead> <tr> <th style={styles.th}>Username</th> <th style={styles.th}>Game</th> <th style={styles.th} class="responsive-hide"> Timestamp </th> </tr> </thead> {this.state.modlists.map( ({ username, encodedUsername, game, displayTimestamp, timestampTitle }) => ( <tr> <td style={styles.td}> <Link href={`/u/${encodedUsername}`}>{username}</Link> </td> <td style={styles.td}>{this.state.gameMap[game]}</td> <td style={styles.td} class="responsive-hide"> {displayTimestamp} </td> </tr> ) )} </table> </div> ); } } function prettifyModlists(modlists: PartialModlist[]): PartialModlist[] { let t; return modlists.map( m => ( (t = new Date(m.timestamp)), { ...m, game: m.game || "skyrim", encodedUsername: encodeURIComponent(m.username), displayTimestamp: t.toLocaleString() } ) ); }
ansballard/Frontend
src/__helpers__/mocks.ts
import { Modlist, ModFile, FileName, Game } from "@modwatch/types"; export const profile: Partial<Modlist> = { timestamp: new Date("1995-12-17T03:24:00"), tag: "Tag", game: "skyrim", enb: "Shiny ENB" }; export const plugins: ModFile = [ "*UHDAP - en0.esp", "*UHDAP - en1.esp", "*UHDAP - en2.esp", "*UHDAP - en3.esp", "*UHDAP - en4.esp", "*UHDAP - MusicHQ.esp", "*RSkyrimChildren.esm", "*Unofficial Skyrim Special Edition Patch.esp", "*Lanterns Of Skyrim - All In One - Main.esm", "*Skyrim Project Optimization - No Homes - Full Version.esm", "*FISS.esp", "*LegacyoftheDragonborn.esm", "*Dave'sMajesticMountains_Landscape.esm", "*DwemerGatesNoRelock.esl", "*BBLuxurySuite.esm", "*DynDOLOD.esm", "*hdtHighHeel.esm", "*ApachiiHair.esm" ]; export const modlist: ModFile = [ "-Recently Installed_separator", "+FNIS [Output]", "+BodySlide Output", "+DynDOLOD_Output", "+Know Your Enemy [Output]", "+ENB Light [Output]", "+Racemenu Presets", "-33 PATCHER OUTPUT_separator", "+GAMEPLAY – Conflict Resolution Patch", "+VISUALS – Conflict Resolution Patch", "+CORE – Conflict Resolution Patch", "-32 CONFLICT RESOLUTION_separator", "+Charrmers - The Eyes Of Beauty Compability", "+OMEGA AIO" ]; export const ini: ModFile = [ "[Actor]", "bUseNavMeshForMovement=0", "[Animation]", "fMaxFrameCounterDifferenceToConsiderVisible=0.06666667", "[Archive]", "bLoadArchiveInMemory=1", "sArchiveToLoadInMemoryList=Skyrim - Animations.bsa", "sResourceArchiveList=Skyrim - Misc.bsa, Skyrim - Shaders.bsa, Skyrim - Interface.bsa, Skyrim - Animations.bsa, Skyrim - Meshes0.bsa, Skyrim - Meshes1.bsa, Skyrim - Sounds.bsa", "sResourceArchiveList2=Skyrim - Voices_en0.bsa, Skyrim - Textures0.bsa, Skyrim - Textures1.bsa, Skyrim - Textures2.bsa, Skyrim - Textures3.bsa, Skyrim - Textures4.bsa, Skyrim - Textures5.bsa, Skyrim - Textures6.bsa, Skyrim - Textures7.bsa, Skyrim - Textures8.bsa, Skyrim - Patch.bsa", "[Audio]", "fMenuModeFadeInTime=1.0", "fMenuModeFadeOutTime=3.0", "fMusicDuckingSeconds=6.0", "fMusicUnDuckingSeconds=8.0", "[Bethesda.net]", "bEnablePlatform=0" ]; export const prefsini: ModFile = [ "[AudioMenu]", "fAudioMasterVolume=0.6000", "fVal0=0.1500", "fVal1=0.3500", "fVal2=1.0000", "fVal3=0.3000", "fVal4=0.1500", "fVal5=1.0000", "fVal6=0.5000", "fVal7=1.0000", "uID0=94881", "uID1=1007612", "uID2=554685", "uID3=466532", "uID4=522251", "uID5=410705", "uID6=106685", "uID7=573393613", "[Bethesda.net]", "uPersistentUuidData0=3251767419", "uPersistentUuidData1=880756506", "uPersistentUuidData2=2788829086", "uPersistentUuidData3=1390707462" ]; export const game: Game = "skyrim"; export const files: { [key: string]: number } = { plugins: plugins.length, modlist: modlist.length, ini: ini.length, prefsini: prefsini.length }; export const all: Partial<Modlist> = { ...profile, plugins, files }; export const users: Partial<Modlist>[] = [ { username: "Peanut", timestamp: new Date("1995-12-17T03:24:00") }, { username: "Sunconure11", timestamp: new Date("1995-12-17T03:23:54") }, { username: "eeekief", timestamp: new Date("1995-12-17T03:23:20") }, { username: "alcyonemods", timestamp: new Date("1995-12-17T03:22:49") }, { username: "aaronth07", timestamp: new Date("1995-12-17T03:22:47") }, { username: "MickSonger", timestamp: new Date("1995-12-17T03:22:27") }, { username: "Arthandis", timestamp: new Date("1995-12-17T03:22:00") }, { username: "FollowTheLaser", timestamp: new Date("1995-12-17T03:20:34") }, { username: "OsirisNGaming", timestamp: new Date("1995-12-17T03:20:15") }, { username: "krrptd", timestamp: new Date("1995-12-17T03:20:13") }, { timestamp: new Date("1995-12-17T03:20:03"), username: "Flintlocksagerider" } ]; const iat = new Date("1995-12-17T03:24:00").getTime(); export const token = { iss: "http://localhost:3000/", aud: "http://localhost:3001/", sub: "Peanut", iat, exp: iat + 3600 * 1000, scopes: ["user"] };
ansballard/Frontend
src/components/asyncRoute.tsx
<filename>src/components/asyncRoute.tsx import { h, Component } from "preact"; function noop() {} export default class AsyncRoute extends Component< { getComponent(url: string, cb: () => any, props: any); url: string; matches: any; }, { componentData?: any; } > { constructor() { super(); this.state = { componentData: null }; } loadComponent = async () => { const componentData = await this.props.getComponent( this.props.url, noop, Object.assign({}, this.props, this.props.matches) ); this.setState({ componentData }); }; componentWillReceiveProps(nextProps) { if (this.props.path && this.props.path !== nextProps.path) { this.setState( { componentData: null }, () => { this.loadComponent(); } ); } } componentWillMount() { this.loadComponent(); } render() { if (this.state.componentData) { // return this.state.componentData; // preactX return this.state.componentData.props ? this.state.componentData : h(this.state.componentData, this.props); } return null; } }
ansballard/Frontend
src/store/pure.ts
import { Modlist } from "@modwatch/types"; import { PartialModlist, User } from "../types"; const getJson = res => res.json(); const _e = encodeURIComponent; export async function getModlists({ limit = 10 }: { limit?: number; } = {}): Promise<PartialModlist[]> { return await fetch(`${process.env.API_URL}/api/users/list/${limit}`).then( getJson ); } export async function searchModlists({ filter, limit = 10 }: { filter: string; limit?: number; }): Promise<PartialModlist[]> { return await fetch( `${process.env.API_URL}/api/search/users/${_e(filter)}/${limit}` ).then(getJson); } export async function getModlist({ username }: { username: string; }): Promise<Modlist> { return await fetch( `${process.env.API_URL}/api/user/${_e(username)}/all` ).then(getJson); } export async function getModlistFileType({ username, filetype }: { username: string; filetype: string; }): Promise<Modlist> { return await fetch( `${process.env.API_URL}/api/user/${_e(username)}/file/${_e(filetype)}` ).then(getJson); } export async function deleteModlist({ user, username }: { user: User; username: string; }): Promise<boolean> { if (user.scopes.indexOf("admin") === -1 && username !== user.username) { throw `${user.scopes.join( "," )} does not include admin, and ${username} does not equal ${user.username}`; } try { return ( (await fetch(`${process.env.API_URL}/oauth/user/${_e(username)}/delete`, { method: "DELETE", headers: { "Content-Type": "application/json", Authorization: `Bearer ${user.token}` } })).status === 200 ); } catch (e) { return false; } } export async function verify(token: string): Promise<boolean> { return ( (await fetch(`${process.env.API_URL}/oauth/verify?t=${Date.now()}`, { headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}` } })).status === 200 ); }
ansballard/Frontend
src/components/modwatch-notifications.tsx
import { h, Component } from "preact"; import Notification from "./modwatch-notification"; import * as types from "../types"; const color = "#E3A853"; const styles = { notificationsWrapper: { fontFamily: "monospace", fontSize: "16px", listStyle: "none", margin: 0, position: "fixed", top: "20px", left: "15px", width: "200px", borderColor: color, color } }; export default class Notifications extends Component<types.StoreProps, {}> { render() { const { notifications, removeNotification } = this.props; return ( <div style={styles.notificationsWrapper}> {notifications.map(notification => ( <Notification notification={notification} onRemove={_id => removeNotification(_id)} /> ))} </div> ); } }
ansballard/Frontend
micro.ts
<reponame>ansballard/Frontend<filename>micro.ts<gh_stars>0 import { ServerRequest, ServerResponse } from "microrouter"; const { router, get, post, del } = require("microrouter"); const { send } = require("micro"); const Cors = require("micro-cors"); const compress = require("micro-compress"); const { encode } = require("jwt-simple"); const mocks = require("./src/__helpers__/mocks"); const cors = Cors(); async function throttledSend(res: ServerResponse, status: number, response?: any) { return new Promise(resolve => { setTimeout(() => resolve(send(res, status, response)), Math.random() * 50 + 175); }); } export default cors(compress(router( /* User */ get("/api/user/:username/file/:filetype", async (req: ServerRequest, res: ServerResponse) => { await throttledSend(res, 200, mocks[req.params.filetype]); }), get("/api/user/:username/profile", async (req: ServerRequest, res: ServerResponse) => { await throttledSend(res, 200, mocks.profile); }), get("/api/user/:username/files", async (req: ServerRequest, res: ServerResponse) => { await throttledSend(res, 200, mocks.files); }), get("/api/user/:username/all", async (req: ServerRequest, res: ServerResponse) => { await throttledSend(res, 200, mocks.all); }), post("/api/user/:username/delete", async (req: ServerRequest, res: ServerResponse) => { await throttledSend(res, 200); }), post("/api/user/:username/changepass", async (req: ServerRequest, res: ServerResponse) => { await throttledSend(res, 200); }), /* Users */ get("/api/users/count", async (req: ServerRequest, res: ServerResponse) => { await throttledSend(res, 200, mocks.users.length); }), get("/api/users/list(/:limit)", async (req: ServerRequest, res: ServerResponse) => { await throttledSend(res, 200, mocks.users); }), get("/api/search/users/:query/:limit", async (req: ServerRequest, res: ServerResponse) => { const query = req.params.query.toLowerCase(); await throttledSend(res, 200, mocks.users.filter(user => user.username.toLowerCase().includes(query))); }), /* OAuth */ get("/oauth/authorize", (req: ServerRequest, res: ServerResponse) => { res.statusCode = 301; res.setHeader( "Location", `${decodeURIComponent( req.query.redirect_uri )}oauth/access_token/${encodeURIComponent( encode(mocks.token, "FAKE_JWT_SECRET") )}/token_type/Bearer/expires_in/3600` ); res.end(); }), get("/oauth/verify", async (req: ServerRequest, res: ServerResponse) => { await throttledSend(res, 200); }), del("/oauth/user/:username/delete", async (req: ServerRequest, res: ServerResponse) => { await throttledSend(res, 200); }) )));
ansballard/Frontend
src/router/home.tsx
<filename>src/router/home.tsx import { h, Component } from "preact"; import ModwatchModlists from "../components/modwatch-modlists"; import ModwatchPostList from "../components/modwatch-postlist"; import { PostMetadata } from "../types"; export default class Home extends Component< { path?: string; }, { posts: PostMetadata[]; } > { render() { return ( <div> <section> <h2>What is Modwatch?</h2> <p> This is a modlist-hosting site for Skyrim, Skyrim SE, and Fallout 4. If you've ever had your game crash and asked for help on the internet, you've probably had someone ask you for what mods you're using. So you could go find those file and copy them into a comment, or into pastebin, or a google doc, etc. Or you could{" "} <a href="http://www.nexusmods.com/skyrim/mods/56640"> download Modwatch </a> , choose a username, upload your files here, and have an easy link ( <i>modwat.ch/u/your_username_here</i>) to give out. This site is also used by streamers, youtubers, or anyone else that might want to show people what mods they're using. </p> </section> <section> <a href="http://www.nexusmods.com/skyrim/mods/56640" target="_blank"> <h2 style={{ paddingBottom: 0, marginBottom: 0, borderBottom: 0 }} > Download Here </h2> </a> </section> {/* <ModwatchPostList /> */} <section> <h2>Latest Modlists</h2> <ModwatchModlists /> </section> </div> ); } }
ansballard/Frontend
src/components/modwatch-nav.tsx
import { h, Component } from "preact"; import { route } from "preact-router"; import { Link } from "preact-router"; import "./modwatch-nav.css"; import { StoreProps } from "../types"; export default class ModwatchNav extends Component< StoreProps, { show: boolean; loginLink: string; redirect_uri: string; } > { state = { show: false, loginLink: `${process.env.API_URL}/oauth/authorize`, redirect_uri: encodeURIComponent( `${window.location.protocol}//${window.location.host}/` ) }; toggleShow = () => { this.setState(({ show }) => ({ show: !show })); }; login = () => { window.location.replace( `${this.state.loginLink}?client_id=modwatch&redirect_uri=${this.state.redirect_uri}&response_type=code` ); }; logout = () => { this.props.logout(); this.props.addNotification("Logged Out"); }; gotoProfile = () => { if (this.props.user) { route(`/u/${this.props.user.username}`); this.props.addNotification("Viewing Your Profile"); } }; gotoHome = () => { route("/"); }; render() { const authenticated = this.props.user ? this.props.user.authenticated : false; return ( <div class="menu-wrapper"> <div class="menu-toggle" onClick={this.toggleShow} /> <nav class={this.state.show ? "menu-main menu-active" : "menu-main"} onClick={this.toggleShow} > <a onClick={this.gotoHome} class="nav-block"> Home </a> {!authenticated ? ( <a onClick={this.login} class="nav-block"> Login </a> ) : ( <a onClick={this.logout} class="nav-block"> Logout </a> )} {authenticated && ( <a onClick={this.gotoProfile} class="nav-block"> Profile </a> )} <span class="nav-block">Close</span> </nav> </div> ); } }
ansballard/Frontend
src/components/modwatch-notification.tsx
import { h, Component } from "preact"; import * as types from "../types"; const notificationsWrapperPseudo = { content: "", width: "10px", position: "absolute", top: 0, height: "100%", borderTop: `3px solid`, borderBottom: `3px solid`, boxSizing: "border-box", opacity: "inherit" }; const styles = { notificationsWrapperBefore: { ...notificationsWrapperPseudo, left: 0, borderLeft: `3px solid` }, notificationsWrapperAfter: { ...notificationsWrapperPseudo, right: 0, borderRight: `3px solid` }, error: { borderColor: "#e45649", color: "#e45649" }, notification: { position: "relative", padding: "7px 10px", margin: "5px 0", opacity: 1, transition: "opacity 0.3s ease", backgroundColor: "rgba(0, 0, 0, 0.2)", cursor: "pointer" }, removing: { opacity: 0.01 }, softDelete: { display: "none", zIndex: -1 } }; export default class Notification extends Component< { notification: types.Notification; onRemove(_id: string) }, { removingTimeout?: number; removeTimeout?: number; removing: boolean; } > { state = { removingTimeout: undefined, removeTimeout: undefined, removing: false }; componentDidMount() { if (this.props.notification.delay !== -1) { const { onRemove } = this.props; const { delay, removalDelay, _id } = this.props.notification; const removingTimeout = window.setTimeout(() => { this.setState({ removing: true }); }, delay); const removeTimeout = window.setTimeout(() => { onRemove(_id); }, removalDelay + delay); this.setState({ removeTimeout, removingTimeout }); } } removeOnClick = () => { const { onRemove, notification } = this.props; const { removingTimeout, removeTimeout, removing } = this.state; if (!removing) { clearTimeout(removingTimeout); clearTimeout(this.state.removeTimeout); this.setState({ removing: true }); const removeTimeout = window.setTimeout(() => { onRemove(notification._id); }, notification.removalDelay); this.setState({ removeTimeout, removingTimeout: undefined }); } else { clearTimeout(removeTimeout); onRemove(notification._id); } }; componentWillUnmount() { clearTimeout(this.state.removingTimeout); clearTimeout(this.state.removeTimeout); } render() { const { notification, key } = this.props; const { removing } = this.state; return ( <div key={notification._id} style={ !notification.softDelete ? { ...styles.notification, transition: `opacity ${notification.removalDelay}ms ease`, ...styles[notification.type], ...(!removing ? {} : styles.removing) } : styles.softDelete } onClick={this.removeOnClick} > <div style={styles.notificationsWrapperBefore} /> <div key={`notification-${key}`}>{notification.message}</div> <div style={styles.notificationsWrapperAfter} /> </div> ); } }
ansballard/Frontend
src/router/modlist.tsx
<gh_stars>0 import { h, Component } from "preact"; import { Link, route } from "preact-router"; import "./modlist.css"; import { getModlist, getModlistFileType } from "../store/pure"; import { RouteProps } from "../types"; import { Modlist } from "@modwatch/types"; import ModwatchFile from "../components/modwatch-file"; type ComponentProps = RouteProps<{ username: string; filetype: string; path?: string; }>; type ComponentState = { showInactiveMods: boolean; gameDisplay?: string; filter: string; filtering: boolean; filterTimeoutID?: number; modlist: Partial<Modlist>; files: string[]; isAdmin: boolean; filetype: string; }; const gameMap = { skyrim: "Skyrim Classic", skyrimse: "Skyrim SE", fallout4: "Fallout 4" }; const filetypeMap = game => ({ plugins: "plugins", modlist: "modlist", ini: game.indexOf("skyrim") !== -1 ? "skyrim" : game, prefsini: `${game.indexOf("skyrim") !== -1 ? "skyrim" : game}Prefs` }); const initialState: ComponentState = { filter: "", filtering: false, filterTimeoutID: undefined, showInactiveMods: false, modlist: { files: {}, plugins: [], tag: undefined, enb: undefined, game: undefined, timestamp: undefined, score: undefined }, files: [], gameDisplay: undefined, isAdmin: false, filetype: "plugins" }; export default class ModlistWrapper extends Component< ComponentProps, ComponentState > { constructor(props: ComponentProps) { super(props); this.state = { ...initialState, isAdmin: props.user && props.user.scopes.indexOf("admin") !== -1 // filetype: props.matches.filetype || undefined }; } initialize = async ({ clear }: { clear?: boolean } = {}) => { clear && this.setState({ modlist: initialState.modlist, filetype: initialState.filetype }); const [modlist, file] = await Promise.all([ getModlist({ username: this.props.matches.username }), this.state.filetype !== "plugins" ? getModlistFileType(this.props.matches) : undefined ]); const files = Object.keys(modlist.files).filter( key => modlist.files[key] > 0 ); this.setState(() => ({ modlist: { ...modlist, [this.state.filetype]: file || modlist.plugins }, gameDisplay: gameMap[modlist.game || "skyrim"], files })); if (!files.includes(this.props.matches.filetype)) { route(`/u/${this.props.matches.username}/${files[0]}`, true); } }; async componentDidMount() { this.initialize({ clear: true }) .then(() => this.props.loadAdsenseAds()) .then(() => { if (!this.props.adsense.failed) { //@ts-ignore google adsense nonsense (window.adsbygoogle = window.adsbygoogle || []).push({}); } }); } updateFilter = ({ target }) => { if (this.state.filtering) { clearTimeout(this.state.filterTimeoutID); } this.setState(() => ({ filtering: true, filterTimeoutID: window.setTimeout(() => { this.setState(() => ({ filter: target.value, filtering: false })); }, 200) })); }; toggleActiveMods = () => { this.setState(({ showInactiveMods }) => ({ showInactiveMods: !showInactiveMods })); }; shouldComponentUpdate(nextProps, nextState) { // const kPop = Object.keys(this.props).filter(k => typeof this.props[k] !== "function"); // console.log("PROPS", kPop.map(k => ({ [k]: this.props[k] })), kPop.map(k => ({ [k]: nextProps[k] }))); // const kState = Object.keys(this.state).filter(k => typeof this.state[k] !== "function"); // console.log("STATE", kState.map(k => ({ [k]: this.state[k] })), kState.map(k => ({ [k]: nextState[k] }))); const valid = [ [this.state.filetype, nextState.filetype], [this.props.url, nextProps.url] ]; return valid.map(set => set[0] !== set[1]).some(_ => true); } componentDidUpdate = async (prevProps: ComponentProps) => { if (typeof this.props.matches.username === "undefined") { return; } if (this.props.matches.username !== prevProps.matches.username) { this.initialize({ clear: true }); } else if (this.props.matches.filetype !== prevProps.matches.filetype) { this.setState({ filetype: this.props.matches.filetype }); const file = await getModlistFileType(this.props.matches); this.setState(({ modlist }) => ({ modlist: { ...modlist, [this.props.matches.filetype]: file } })); } }; render() { const { matches, user, deleteModlist, adsense } = this.props; const { modlist, files, gameDisplay, isAdmin, filetype, filter, showInactiveMods } = this.state; const showAdminTools = user && (isAdmin || user.username === matches.username); const complexLines = ["prefsini", "ini"].includes(filetype); const _fileTypeMap = modlist.game ? filetypeMap(modlist.game) : {}; return ( <div class="modlist-wrapper"> <section class="modlist-meta"> <p class="modlist-username">{matches.username}</p> {modlist.enb && <p class="modlist-enb">ENB: {modlist.enb}</p>} {modlist.tag && <p class="modlist-tag">Tag: {modlist.tag}</p>} <p class="modlist-gamedisplay">{gameDisplay}</p> {showAdminTools && ( <div class="modlist-actions"> <button type="button" onClick={e => deleteModlist()}> Delete </button> </div> )} </section> <ins class="adsbygoogle" style={{ display: "block", width: "100%", height: !adsense.failed ? "280px" : "0", marginBottom: !adsense.failed ? "25px" : "0" }} data-ad-client={process.env.ADSENSE_CLIENT} data-adtest={process.env.NODE_ENV !== "production" ? "on" : undefined} data-ad-slot="1008233292" data-ad-format="auto" data-full-width-responsive="true" ></ins> <section class="modlist-content"> <nav class="modlist-filetype-nav"> <ul> {files.map(t => ( <li> <Link href={`/u/${encodeURIComponent( matches.username )}/${encodeURIComponent(t)}`} class="no-underline" > <button class={filetype === t ? "active" : ""}> {_fileTypeMap[t]} </button> </Link> </li> ))} </ul> </nav> <form class="modlist-filter"> <span class="form-group"> <label for="modlist-filter" style="visibility: hidden; display: none;" > Filter </label> <input type="text" id="modlist-filter" placeholder="Filter By..." onInput={this.updateFilter} /> </span> {filetype === "modlist" && ( <span class="form-group"> <label for="modlist-enabled-toggle">Inactive Mods</label> <input type="checkbox" id="modlist-enabled-toggle" onChange={this.toggleActiveMods} /> </span> )} </form> {modlist[filetype] && modlist[filetype].length > 0 && ( <ModwatchFile filter={filter} showInactiveMods={showInactiveMods} filetype={filetype} showDescriptor={filetype === "plugins"} complexLines={complexLines} lines={modlist[filetype] as string[]} /> )} </section> </div> ); } }
ansballard/Frontend
src/index.tsx
<filename>src/index.tsx // import "preact/debug"; ///DEV_ONLY import { render, h, Component } from "preact"; import { Link } from "preact-router"; import { Provider, connect } from "unistore/preact"; import "unfetch/polyfill/index"; ///NOMODULE_ONLY import "./global.css"; import Router from "./router"; import { rawState, store, actions } from "./store"; import { verify } from "./store/pure"; import Nav from "./components/modwatch-nav"; import Notifications from "./components/modwatch-notifications"; import { StoreProps } from "./types"; import "./ga"; ///PROD_ONLY console.log(`Modwatch: VERSION:\t${process.env.VERSION} NODE_ENV:\t${process.env.NODE_ENV}`); const pathname = window.location.pathname; const token = (() => { if (pathname.indexOf("/oauth/access_token/") === 0) { history.replaceState(null, null, "/"); try { const [, , , token, , token_type, , expires_in] = pathname.split("/"); return token; } catch (e) { return "401"; } } return undefined; })(); class Root extends Component<StoreProps & { token: string }, {}> { componentDidMount = async () => { if (!this.props.token && this.props.user && this.props.user.authenticated) { setTimeout( () => this.props.addNotification( `Welcome Back, ${this.props.user.username}` ), 1 ); } else if (this.props.token === "<PASSWORD>" || !(await verify(token))) { if (!this.props.user || !this.props.user.authenticated) { return; } this.props.logout(); setTimeout( () => this.props.addNotification("Login Failed", { type: "error" }), 1 ); } else { this.props.login(token); setTimeout(() => this.props.addNotification("Login Successful"), 1); } }; render() { return ( <div> <Notifications {...this.props} /> <header> <h1 class="header"> <Link class="no-underline" href="/"> MODWATCH </Link> </h1> </header> <Nav {...this.props} /> <div class="content-wrapper"> <div class="view-wrapper"> <Router {...this.props} /> </div> </div> </div> ); } } const Connector = connect( Object.keys(rawState), actions )(props => ( //@ts-ignore I don't know how to pass types to connect <Root {...props} token={token} /> )); render( <Provider store={store}> <Connector /> </Provider>, document.getElementById("modwatch-app") );
ansballard/Frontend
src/router/index.tsx
import { h, Component } from "preact"; import Router, { route } from "preact-router"; import AsyncRoute from "../components/asyncRoute"; import NotFound from "./notFound"; import Post from "../components/post"; import { RouteProps, StoreProps } from "../types"; const ROUTE_TRANSITION_TIMEOUT = 150; // needs to match transition duration in src/global.css export default class Routes extends Component< StoreProps, { fading: boolean; timeout: boolean } > { state = { fading: false, timeout: false }; cancelRouteChange = false; wrappedImport = importedComponent => { return importedComponent.then(() => { this.setState(() => ({ fading: false })); return importedComponent; }); }; importPost = async (url, cb, props) => { const DynamicPost = await this.wrappedImport(import(`./${props.title}.js`)); return <Post {...DynamicPost.metadata} content={DynamicPost.default} />; }; routeChange = e => { if (this.cancelRouteChange) { this.cancelRouteChange = false; return; } if (this.state.fading || this.state.timeout) { return; } if ( e.previous && e.previous.indexOf("/u/") === 0 && e.current.key === "modlist" && e.current.props.matches.username === e.previous.slice(3, e.current.props.matches.username.length + 3) ) { return; } e.previous && route(e.previous, true); setTimeout(() => { this.setState( () => ({ timeout: false }), () => { if (e.previous) { this.cancelRouteChange = true; route(e.url, true); } } ); }, ROUTE_TRANSITION_TIMEOUT); this.setState(() => ({ fading: true, timeout: true })); }; render() { return ( <div class={`router-wrapper ${ this.state.fading || this.state.timeout ? "fading" : "" }`} > <Router onChange={this.routeChange}> <AsyncRoute key={"home"} path="/" {...(this.props as RouteProps)} getComponent={() => this.wrappedImport(import("./home").then(c => c.default)) } /> <AsyncRoute key="modlist" path="/u/:username/:filetype?" {...(this.props as RouteProps)} getComponent={() => this.wrappedImport( import("./modlist").then(c => { return c.default; }) ) } /> <AsyncRoute key="posts" path="/posts" {...(this.props as RouteProps)} getComponent={() => this.wrappedImport(import("./posts/index").then(c => c.default)) } /> <AsyncRoute key="post" path="/post/:title" {...(this.props as RouteProps)} getComponent={this.importPost} /> <NotFound key="404" default {...(this.props as RouteProps)} /> </Router> </div> ); } }
ansballard/Frontend
src/router/posts/mdx.d.ts
declare module "*.mdx" { let MDXComponent: (props) => preact.JSX.Element; export default MDXComponent; export const metadata: { title: string; author: string; tags: string[]; timestamp: Date; }; }
jm-seabery/angular-web-qt
src/app/webgl/webgl.component.ts
<gh_stars>0 import { Component, OnInit } from '@angular/core'; import { ViewChild, ElementRef } from '@angular/core'; import * as THREE from 'three'; import { ColladaLoader } from 'three-full'; @Component({ selector: 'webgl', templateUrl: './webgl.component.html', styleUrls: ['./webgl.component.scss'] }) export class WebglComponent implements OnInit { @ViewChild('webGLCanvas') basicCanvas/*: ElementRef*/; private width: number = 400; private height: number = 400; private renderer: THREE.WebGLRenderer; private animationWindow : Window; private canvas: any; private sceneElements = []; private timeElapsed : number = 0.0; private then : number = 0.0; constructor() { } ngOnInit() { this.canvas = document.getElementById( "basic-canvas" ); var modelPaths = [ { name:"model1", file:"./assets/collada/cow/cow.dae", model:null }, { name:"model2", file:"./assets/collada/pig/pig.dae", model:null }, { name:"model3", file:"./assets/collada/horse/horse.dae", model:null }, ] this.then = new Date().getTime(); this.renderer = new THREE.WebGLRenderer({antialias: false, alpha: true, canvas: this.canvas}); this.renderer.setClearColor("#808080", 1); this.renderer.setPixelRatio( window.devicePixelRatio ); for (let entry of modelPaths) { // once the model is loader this manager is called to add to the scene const loadingManager = new THREE.LoadingManager( () => { } ); // load the model and call the manager above const loader = new ColladaLoader( loadingManager ); loader.load( entry.file, ( collada ) => { const {scene, camera} = this.makeScene(); var element = document.getElementById( entry.name ); scene.userData.element = element; scene.userData.camera = camera; entry.model = collada.scene; entry.model.scale.set(0.5, 0.5, 0.5); scene.add(collada.scene); this.addScene(element, this.getRandColor(5), (time, rect) => { camera.aspect = rect.width / rect.height; camera.updateProjectionMatrix(); entry.model.rotation.z += THREE.Math.degToRad(90.0*time); this.renderer.render(scene, camera); }); } ); } window.addEventListener('resize', () => { this.onResize(); }); this.animationWindow = window; window.requestAnimationFrame(() => { this.update(); }); } onResize(): void { var width = this.canvas.clientWidth; var height = this.canvas.clientHeight; if ( this.canvas.width !== width || this.canvas.height !== height ) { this.renderer.setSize( width, height, false ); } } update(): void { this.onResize(); var now = new Date().getTime(); this.timeElapsed = (now - this.then) * 0.001; // compute time since last frame this.then = now; // remember time for next frame const fps = 1 / this.timeElapsed; // compute frames per second this.renderer.setClearColor(0x000000, 0); this.renderer.setScissorTest(false); this.renderer.clear(); this.renderer.setScissorTest(true); for (const {elem, bgCol, fn} of this.sceneElements) { this.renderer.setClearColor( bgCol, 0.5 ); // get the viewport relative position opf this element // get its position relative to the page's viewport var rect = elem.getBoundingClientRect(); // check if it's offscreen. If so skip it if ( rect.bottom < 0 || rect.top > this.renderer.domElement.clientHeight || rect.right < 0 || rect.left > this.renderer.domElement.clientWidth ) { continue; // it's off screen } // set the viewport var width = rect.right - rect.left; var height = rect.bottom - rect.top; var left = rect.left; var bottom = this.renderer.domElement.clientHeight - rect.bottom; this.renderer.setViewport( left, bottom, width, height ); this.renderer.setScissor( left, bottom, width, height ); fn(this.timeElapsed, rect); } // request next update this.animationWindow.requestAnimationFrame(() => { this.update(); }); } addScene(elem, bgCol, fn) { this.sceneElements.push({elem, bgCol, fn}); } makeScene() { const scene = new THREE.Scene(); const fov = 75; const aspect = 2; // the canvas default const near = 0.1; const far = 1000; const camera = new THREE.PerspectiveCamera(fov, aspect, near, far); camera.position.set(0, 0, 4); camera.lookAt(0, 0, 0); { const color = 0xFFFFFF; const intensity = .5; const light = new THREE.DirectionalLight(color, intensity); light.position.set(-1, 2, 4); scene.add(light); } { var ambientLight = new THREE.AmbientLight( 0xcccccc, 0.8 ); scene.add( ambientLight ); } return {scene, camera}; } getRandColor(brightness){ // Six levels of brightness from 0 to 5, 0 being the darkest /*var rgb = [Math.random() * 256, Math.random() * 256, Math.random() * 256]; var mix = [brightness*51, brightness*51, brightness*51]; //51 => 255/5 var mixedrgb = [rgb[0] + mix[0], rgb[1] + mix[1], rgb[2] + mix[2]].map(function(x){ return Math.round(x/2.0)}) return "rgb(" + mixedrgb.join(",") + ")";*/ var val = '0x'+Math.floor(Math.random()*16777215).toString(16); return parseInt(val); } }
phryneas/postgraphile
src/postgraphile/http/subscriptions.ts
<gh_stars>0 import { Server, IncomingMessage, ServerResponse } from 'http'; import { HttpRequestHandler, mixed, Middleware } from '../../interfaces'; import { subscribe as graphqlSubscribe, ExecutionResult, specifiedRules, validate, GraphQLError, parse, DocumentNode, } from 'graphql'; import * as WebSocket from 'ws'; import { SubscriptionServer, ConnectionContext, ExecutionParams } from 'subscriptions-transport-ws'; import parseUrl = require('parseurl'); import { pluginHookFromOptions } from '../pluginHook'; import { isEmpty } from './createPostGraphileHttpRequestHandler'; import liveSubscribe from './liveSubscribe'; interface Deferred<T> extends Promise<T> { resolve: (input?: T | PromiseLike<T> | undefined) => void; reject: (error: Error) => void; } function lowerCaseKeys(obj: object): object { return Object.keys(obj).reduce((memo, key) => { memo[key.toLowerCase()] = obj[key]; return memo; }, {}); } function deferred<T = void>(): Deferred<T> { let resolve: (input?: T | PromiseLike<T> | undefined) => void; let reject: (error: Error) => void; const promise = new Promise<T>((_resolve, _reject) => { resolve = _resolve; reject = _reject; }); // tslint:disable-next-line prefer-object-spread return Object.assign(promise, { // @ts-ignore This isn't used before being defined. resolve, // @ts-ignore This isn't used before being defined. reject, }); } export async function enhanceHttpServerWithSubscriptions( websocketServer: Server, postgraphileMiddleware: HttpRequestHandler, subscriptionServerOptions?: { keepAlive?: number; }, ) { if (websocketServer['__postgraphileSubscriptionsEnabled']) { return; } websocketServer['__postgraphileSubscriptionsEnabled'] = true; const { options, getGraphQLSchema, withPostGraphileContextFromReqRes, handleErrors, } = postgraphileMiddleware; const pluginHook = pluginHookFromOptions(options); const externalUrlBase = options.externalUrlBase || ''; const graphqlRoute = options.graphqlRoute || '/graphql'; const schema = await getGraphQLSchema(); const keepalivePromisesByContextKey: { [contextKey: string]: Deferred<void> | null } = {}; const contextKey = (ws: WebSocket, opId: string) => ws['postgraphileId'] + '|' + opId; const releaseContextForSocketAndOpId = (ws: WebSocket, opId: string) => { const promise = keepalivePromisesByContextKey[contextKey(ws, opId)]; if (promise) { promise.resolve(); keepalivePromisesByContextKey[contextKey(ws, opId)] = null; } }; const addContextForSocketAndOpId = (context: mixed, ws: WebSocket, opId: string) => { releaseContextForSocketAndOpId(ws, opId); const promise = deferred(); promise['context'] = context; keepalivePromisesByContextKey[contextKey(ws, opId)] = promise; return promise; }; const applyMiddleware = async ( middlewares: Array<Middleware> = [], req: IncomingMessage, res: ServerResponse, ) => { for (const middleware of middlewares) { // TODO: add Koa support await new Promise((resolve, reject) => { middleware(req, res, err => (err ? reject(err) : resolve())); }); } }; const reqResFromSocket = async (socket: WebSocket) => { const req = socket['__postgraphileReq']; if (!req) { throw new Error('req could not be extracted'); } let dummyRes = socket['__postgraphileRes']; if (req.res) { throw new Error( "Please get in touch with Benjie; we weren't expecting req.res to be present but we want to reserve it for future usage.", ); } if (!dummyRes) { dummyRes = new ServerResponse(req); dummyRes.writeHead = (statusCode: number, _statusMessage: never, headers: never) => { if (statusCode && statusCode > 200) { // tslint:disable-next-line no-console console.error( `Something used 'writeHead' to write a '${statusCode}' error for websockets - check the middleware you're passing!`, ); socket.close(); } else if (headers) { // tslint:disable-next-line no-console console.error( "Passing headers to 'writeHead' is not supported with websockets currently - check the middleware you're passing", ); socket.close(); } }; await applyMiddleware(options.websocketMiddlewares, req, dummyRes); // reqResFromSocket is only called once per socket, so there's no race condition here // eslint-disable-next-line require-atomic-updates socket['__postgraphileRes'] = dummyRes; } return { req, res: dummyRes }; }; const getContext = (socket: WebSocket, opId: string) => { return new Promise((resolve, reject) => { reqResFromSocket(socket) .then(({ req, res }) => withPostGraphileContextFromReqRes(req, res, { singleStatement: true }, context => { const promise = addContextForSocketAndOpId(context, socket, opId); resolve(promise['context']); return promise; }), ) .then(null, reject); }); }; const wss = new WebSocket.Server({ noServer: true }); let socketId = 0; websocketServer.on('upgrade', (req, socket, head) => { const { pathname = '' } = parseUrl(req) || {}; const isGraphqlRoute = pathname === externalUrlBase + graphqlRoute; if (isGraphqlRoute) { wss.handleUpgrade(req, socket, head, ws => { wss.emit('connection', ws, req); }); } }); const staticValidationRules = pluginHook('postgraphile:validationRules:static', specifiedRules, { options, }); SubscriptionServer.create( { schema, validationRules: staticValidationRules, execute: () => { throw new Error('Only subscriptions are allowed over websocket transport'); }, subscribe: options.live ? liveSubscribe : graphqlSubscribe, onConnect( connectionParams: object, _socket: WebSocket, connectionContext: ConnectionContext, ) { const { socket, request } = connectionContext; socket['postgraphileId'] = ++socketId; if (!request) { throw new Error('No request!'); } const normalizedConnectionParams = lowerCaseKeys(connectionParams); request['connectionParams'] = connectionParams; request['normalizedConnectionParams'] = normalizedConnectionParams; socket['__postgraphileReq'] = request; if (!request.headers.authorization && normalizedConnectionParams['authorization']) { /* * Enable JWT support through connectionParams. * * For other headers you'll need to do this yourself for security * reasons (e.g. we don't want to allow overriding of Origin / * Referer / etc) */ request.headers.authorization = String(normalizedConnectionParams['authorization']); } socket['postgraphileHeaders'] = { ...normalizedConnectionParams, // The original headers must win (for security) ...request.headers, }; }, // tslint:disable-next-line no-any async onOperation(message: any, params: ExecutionParams, socket: WebSocket) { const opId = message.id; const context = await getContext(socket, opId); // Override schema (for --watch) params.schema = await getGraphQLSchema(); Object.assign(params.context, context); const { req, res } = await reqResFromSocket(socket); const meta = {}; const formatResponse = (response: ExecutionResult) => { if (response.errors) { response.errors = handleErrors(response.errors, req, res); } if (!isEmpty(meta)) { response['meta'] = meta; } return response; }; // onOperation is only called once per params object, so there's no race condition here // eslint-disable-next-line require-atomic-updates params.formatResponse = formatResponse; const hookedParams = pluginHook ? pluginHook('postgraphile:ws:onOperation', params, { message, params, socket, options, }) : params; const finalParams: typeof hookedParams & { query: DocumentNode } = { ...hookedParams, query: typeof hookedParams.query !== 'string' ? hookedParams.query : parse(hookedParams.query), }; // You are strongly encouraged to use // `postgraphile:validationRules:static` if possible - you should // only use this one if you need access to variables. const moreValidationRules = pluginHook('postgraphile:validationRules', [], { options, req, res, variables: params.variables, operationName: params.operationName, meta, }); if (moreValidationRules.length) { const validationErrors: ReadonlyArray<GraphQLError> = validate( params.schema, finalParams.query, moreValidationRules, ); if (validationErrors.length) { const error = new Error( 'Query validation failed: \n' + validationErrors.map(e => e.message).join('\n'), ); error['errors'] = validationErrors; return Promise.reject(error); } } return finalParams; }, onOperationComplete(socket: WebSocket, opId: string) { releaseContextForSocketAndOpId(socket, opId); }, /* * Heroku times out after 55s: * https://devcenter.heroku.com/articles/error-codes#h15-idle-connection * * The subscriptions-transport-ws client times out by default 30s after last keepalive: * https://github.com/apollographql/subscriptions-transport-ws/blob/52758bfba6190169a28078ecbafd2e457a2ff7a8/src/defaults.ts#L1 * * GraphQL Playground times out after 20s: * https://github.com/prisma/graphql-playground/blob/fa91e1b6d0488e6b5563d8b472682fe728ee0431/packages/graphql-playground-react/src/state/sessions/fetchingSagas.ts#L81 * * Pick a number under these ceilings. */ keepAlive: 15000, ...subscriptionServerOptions, }, wss, ); }
danwulff/meal-tracker
app/edit-food.component.ts
<gh_stars>0 import {Component, EventEmitter} from 'angular2/core'; import {Food} from './food.model'; @Component({ selector: 'edit-food', inputs: ['food'], template: ` <h3 class="selected">Edit Food Details:</h3> <input [(ngModel)]="food.name" class="input-lg" style="width: 50%"/> <input [(ngModel)]="food.details" class="input-lg" style="width: 50%"/> <input [(ngModel)]="food.calories" class="input-lg" style="width: 50%"/> ` }) export class EditFoodComponent { }
danwulff/meal-tracker
app/food-list.component.ts
<filename>app/food-list.component.ts import { Component, EventEmitter } from 'angular2/core'; import { FoodComponent } from './food.component'; import { Food } from './food.model'; import { HealthyFoodPipe } from './healthy-food.pipe'; import { NewFoodComponent } from './new-food.component'; import { EditFoodComponent } from './edit-food.component'; @Component({ selector: 'food-list', inputs: ['foodList'], pipes: [HealthyFoodPipe], directives: [FoodComponent, NewFoodComponent, EditFoodComponent], template: ` <div class="row"> <select (change)="onChange($event.target.value)"> <option value="all" selected="selected">Show All Foods</option> <option value="healthy">Show healthy foods</option> <option value="unhealthy">Show unhealthy foods</option> </select> </div> <div class="row"> <food-display *ngFor="#currentFood of foodList | health:filterLevel" [food]="currentFood" (click)="foodClicked(currentFood)" [class.selected]="currentFood === selectedFood"> </food-display> </div> <div class="row"> <edit-food *ngIf="selectedFood" [food]="selectedFood"></edit-food> </div> <div class="row"> <new-food (onSubmitNewFood)="createFood($event)"></new-food> </div> ` }) export class FoodListComponent { public foodList: Food[]; public selectedFood: Food; public filterLevel: String = "all"; onChange(filterOption): void { this.filterLevel = filterOption; } createFood(newFood: Food): void { this.foodList.push(newFood); } foodClicked(foodClicked: Food): void { this.selectedFood = foodClicked; } }
danwulff/meal-tracker
app/new-food.component.ts
<filename>app/new-food.component.ts import {Component, EventEmitter} from 'angular2/core'; import {Food} from './food.model'; @Component({ selector: 'new-food', outputs: ['onSubmitNewFood'], template:` <form name="newFoodForm"> <h3>Add Food:</h3> <input placeholder="Name" class="input-lg" style="width: 50%" #newName /><br> <input placeholder="Details" class="input-lg" style="width: 50%" #newDetails /><br> <input placeholder="Calories" class="input-lg" style="width: 50%" #newCalories /><br> <button (click)="addFood(newName, newDetails, newCalories)" class="btn-primary btn-lg">Submit</button> </form> ` }) export class NewFoodComponent { public onSubmitNewFood: EventEmitter<Food>; constructor(){ this.onSubmitNewFood = new EventEmitter(); } addFood(newName: HTMLInputElement, newDetails: HTMLInputElement, newCalories: HTMLInputElement){ //create food object var food = new Food(newName.value, newDetails.value, parseInt(newCalories.value)); //emit food object to list this.onSubmitNewFood.emit(food); //clear forms newName.value= ""; newDetails.value= ""; newCalories.value= ""; } }
divyajyoti21/CarSalesApp
src/components/Header/Header.tsx
<filename>src/components/Header/Header.tsx import React from "react"; import { withRouter, Link, Route } from "react-router-dom"; function Header(props: any) { return ( <React.Fragment> <nav> <ul id="navbar"> <li style={{ float: "left" }}> <a href="/home"> <img className="logo" src="https://auto1-js-task-api--mufasa71.repl.co/images/logo.png" ></img> </a> </li> <li style={{ float: "right" }}> <a href="/favorites">Favorites</a> </li> <li style={{ float: "right" }}> <a href="">Purchase</a> </li> <li style={{ float: "right" }}> <a href="">My Orders</a> </li> <li style={{ float: "right" }}> <a href="">Sell</a> </li> </ul> </nav> </React.Fragment> ); } export default withRouter(Header);
divyajyoti21/CarSalesApp
src/components/MultiFilter/MultiFilter.tsx
import React, { useState } from "react"; import Button from "../Button/Button"; import "./MultiFilter.css"; function MultiFilter(props: any) { const [colorSelected, updateColorSelected] = useState("allcolors"); const [manufacturerSelected, updateManufacturerSelected] = useState("allmanufacturers"); function filterCars() { props.onClick(colorSelected, manufacturerSelected); } function handleColorChange(event: any) { console.log(event.target.value); updateColorSelected(event.target.value); } function handleManufacturerChange(event: any) { console.log(event.target.value); updateManufacturerSelected(event.target.value); } return ( <div className="multi-filter" style={{ padding: "24px", margin: "12px" }}> <label>Color</label> <select id="colors" onChange={handleColorChange}> <option value="allcolors">All colors</option> {props.colors.map((color: any) => ( <option value={color}>{color}</option> ))} </select> <label>Manufacturer</label> <select id="country" onChange={handleManufacturerChange}> <option value="allmanufacturers">All Manufacturers</option> {props.manufacturers.map((manufacturer: any) => ( <option value={manufacturer.name}>{manufacturer.name}</option> ))} </select> <p className="align-button"> <Button name="Filter" id="btn-filter" onClick={filterCars}></Button> </p> </div> ); } export default MultiFilter;
divyajyoti21/CarSalesApp
src/components/LinkButton/LinkButton.test.tsx
<filename>src/components/LinkButton/LinkButton.test.tsx import { render, screen, fireEvent } from '@testing-library/react'; import LinkButton from './LinkButton'; describe("<LinkButton />", () => { test('Linkbutton rendered', () => { render(<LinkButton />); }); });
divyajyoti21/CarSalesApp
src/components/Footer/Footer.test.tsx
import { render, screen, fireEvent, getByText } from "@testing-library/react"; import Footer from "./Footer"; describe("<Footer />", () => { test("footer rendered", () => { render(<Footer />); }); });
divyajyoti21/CarSalesApp
src/components/Button/Button.test.tsx
<reponame>divyajyoti21/CarSalesApp<filename>src/components/Button/Button.test.tsx import { render, screen, fireEvent, getByText } from "@testing-library/react"; import Button from "./Button"; describe("<Button />", () => { test("button rendered", () => { render(<Button />); }); test("button clicked", async () => { function handleClick() { // done(); } render(<Button onClick={handleClick} />); const button = screen.getByRole("button"); fireEvent.click(button); }); });
divyajyoti21/CarSalesApp
src/components/Footer/Footer.tsx
<reponame>divyajyoti21/CarSalesApp<gh_stars>0 import React from "react"; import "./Footer.css"; function Header(props: any) { return ( <React.Fragment> <div className="footer">&copy;AUTO 1 Group 2018</div> </React.Fragment> ); } export default Header;
divyajyoti21/CarSalesApp
src/components/DisplayCard/DisplayCard.test.tsx
import { render, screen, fireEvent, getByText } from "@testing-library/react"; import DisplayCard from "./DisplayCard"; describe("<DisplayCard />", () => { test("displaycard rendered", () => {}); });
divyajyoti21/CarSalesApp
src/components/Loading/Loading.tsx
<filename>src/components/Loading/Loading.tsx import React from "react"; import "./Loading.css"; function Loading(props: any) { return ( <div className="display-card" style={{ padding: "24px", margin: "12px" }}> <div className="card-img-style"></div> <div className="loading-info"> <div></div> <div></div> <div></div> </div> </div> ); } export default Loading;
divyajyoti21/CarSalesApp
src/app/Favorites/Favorites.tsx
import MultiFilter from "../../components/MultiFilter/MultiFilter"; import DisplayCard from "../../components/DisplayCard/DisplayCard"; import { withRouter } from "react-router-dom"; import "./Favorites.css"; import React, { useEffect, useState } from "react"; function Favorites(props: any) { const [favorites, updateFavorites] = useState([]); function handleClick(id: any) { props.onClick(id); } function onViewDetails(id: any) { props.onViewDetails(id); } function removeFavorite(event: any) { console.log(event.target.value); let favorites = localStorage.getItem("favorites"); if (favorites) { let favoritesParsed = JSON.parse(favorites); favoritesParsed.splice(event.target.value, 1); localStorage.setItem("favorites", JSON.stringify(favoritesParsed)); updateFavorites(favoritesParsed); } } useEffect(() => { let favorites = localStorage.getItem("favorites"); if (favorites) { let favoritesParsed = JSON.parse(favorites); updateFavorites(favoritesParsed); } }, []); return ( <div className="home-grid"> <div style={{ width: "60%", margin: "auto" }}> <div className="available-cars" style={{ padding: "12px", margin: "12px" }} > Favorite cars </div> {favorites.map((car: any, index: number) => ( <div className="display-card" style={{ padding: "24px", margin: "12px" }} > <div className="card-img-style"></div> <div className="car-info"> <div className="car-name"> {car.manufacturerName}&nbsp;{car.modelName} </div> <div className="car-details"> Stock&nbsp;#&nbsp;{car.stockNumber}&nbsp;-&nbsp; {car.mileage.number}&nbsp;{car.mileage.unit} &nbsp;-&nbsp; {car.fuelType}&nbsp;-&nbsp;{car.color} </div> <div className="link-details"> <button className="link-button" value={index} onClick={removeFavorite} > Delete </button> </div> </div> </div> ))} </div> </div> ); } export default withRouter(Favorites);
divyajyoti21/CarSalesApp
src/components/DisplayCard/DisplayCard.tsx
import React from "react"; import Button from "../Button/Button"; import "./DisplayCard.css"; import LinkButton from "../LinkButton/LinkButton"; function DisplayCard(props: any) { function handleClick(id: any) { props.onViewDetails(id); } return ( <div className="display-card" style={{ padding: "24px", margin: "12px" }}> <div className="card-img-style"></div> <div className="car-info"> <div className="car-name"> {props.car.manufacturerName}&nbsp;{props.car.modelName} </div> <div className="car-details"> Stock&nbsp;#&nbsp;{props.car.stockNumber}&nbsp;-&nbsp; {props.car.mileage.number}&nbsp;{props.car.mileage.unit}&nbsp;-&nbsp; {props.car.fuelType}&nbsp;-&nbsp;{props.car.color} </div> <div className="link-details"> <LinkButton id="View details" value={props.index} onClick={handleClick} ></LinkButton> </div> </div> </div> ); } export default DisplayCard;
divyajyoti21/CarSalesApp
src/components/Input/Input.test.tsx
<reponame>divyajyoti21/CarSalesApp import { render, screen, fireEvent } from '@testing-library/react'; import Input from './Input'; describe("<Input />", () => { test('input rendered', () => { render(<Input />); }); });
divyajyoti21/CarSalesApp
src/components/MultiFilter/MultiFilter.test.tsx
import { render, screen, fireEvent } from "@testing-library/react"; import MultiFilter from "./MultiFilter"; describe("<MultiFilter />", () => { test("Multifilter rendered", () => { render( <MultiFilter manufacturers={["test1", "test2"]} colors={["test1", "test2"]} /> ); }); });
divyajyoti21/CarSalesApp
src/components/SelectDropdown/SelectDropdown.test.tsx
<gh_stars>0 import { render, screen, fireEvent } from "@testing-library/react"; import SelectDropdown from "./SelectDropdown"; describe("<SelectDropdown />", () => { test("Select dropdown rendered", () => { render(<SelectDropdown params={["test1", "test2"]} />); }); });
divyajyoti21/CarSalesApp
src/app/PageNotFound/PageNotFound.tsx
import { withRouter, Link } from "react-router-dom"; import "./PageNotFound.css"; function PageNotFound() { return ( <div className="page-not-found"> <div> <img style={{ height: "40px" }} src="https://auto1-js-task-api--mufasa71.repl.co/images/logo.png" ></img> </div> <div>404 - Not Found</div> <div>Sorry, the page you are looking for does not exist</div> <div> You can always go back to the{" "} <Link className="redirectHome" to="/home"> homepage </Link> </div> </div> ); } export default withRouter(PageNotFound);
divyajyoti21/CarSalesApp
src/components/Input/Input.tsx
import React from "react"; function Input(props: any) { function handleChange(event: any) { props.onInputChange(event.target.value); } return ( <input data-testid={props.testid} placeholder={props.placeholder} disabled={props.disabled} value={props.value} id="amount" type="number" onChange={handleChange} /> ); } export default Input;
divyajyoti21/CarSalesApp
src/components/LinkButton/LinkButton.tsx
import React from "react"; import "./LinkButton.css"; function LinkButton(props: any) { function handleClick(event: any) { if (props.id == "View details") { props.onClick(event.target.value); } else { props.onClick(event.target.id); } } return ( <React.Fragment> <button id={props.id} value={props.value} className="link-button" onClick={handleClick} > {props.id} </button> </React.Fragment> ); } export default LinkButton;
divyajyoti21/CarSalesApp
src/components/Button/Button.tsx
import React from "react"; import "./Button.css"; function Button(props: any) { function handleClick(event: any) { props.onClick(event); } return ( <React.Fragment> <button className="button" data-testid={props.testid} onClick={handleClick} > {props.name} </button> </React.Fragment> ); } export default Button;
divyajyoti21/CarSalesApp
src/components/Paginate/Paginate.tsx
import React from "react"; import LinkButton from "../LinkButton/LinkButton"; import "./Paginate.css"; function Paginate(props: any) { function handleClick(id: any) { props.onClick(id); } return ( <React.Fragment> <div id="paginate" className="paginate"> <div> <LinkButton id="First" onClick={handleClick}></LinkButton> </div> <div> <LinkButton id="Prev" onClick={handleClick}></LinkButton> </div> <div className="page-count"> Page {props.currentPage} of {props.totalNumberOfPages} </div> <div> <LinkButton id="Next" onClick={handleClick}></LinkButton> </div> <div> <LinkButton id="Last" onClick={handleClick}></LinkButton> </div> </div> </React.Fragment> ); } export default Paginate;
divyajyoti21/CarSalesApp
src/components/Paginate/Paginate.test.tsx
<filename>src/components/Paginate/Paginate.test.tsx import { render, screen, fireEvent } from "@testing-library/react"; import Paginate from "./Paginate"; describe("<Paginate />", () => { test("paginate rendered", () => { render(<Paginate />); }); });
divyajyoti21/CarSalesApp
src/App.test.tsx
// app.test.js import { render, screen } from "@testing-library/react"; import { createMemoryHistory } from "history"; import React from "react"; import { Router } from "react-router-dom"; import "@testing-library/jest-dom/extend-expect"; import App from "./App"; import Details from "./app/Details/Details"; import PageNotFound from "./app/PageNotFound/PageNotFound"; import Favorites from "./app/Favorites/Favorites"; test("full app rendering/navigating", () => { const history = createMemoryHistory(); render( <Router history={history}> <App /> </Router> ); expect(screen.getByText(/Available/i)).toBeInTheDocument(); }); test("landing on details page", () => { const history = createMemoryHistory(); history.push("/details"); render( <Router history={history}> <Details /> </Router> ); expect(screen.getByText(/current/i)).toBeInTheDocument(); }); test("landing on a favorites page", () => { const history = createMemoryHistory(); history.push("/favorites"); render( <Router history={history}> <Favorites /> </Router> ); expect(screen.getByText(/favorite cars/i)).toBeInTheDocument(); }); test("landing on a bad page", () => { const history = createMemoryHistory(); history.push("/detadfsss"); render( <Router history={history}> <PageNotFound /> </Router> ); expect(screen.getByText(/Not Found/i)).toBeInTheDocument(); });
divyajyoti21/CarSalesApp
src/components/SelectDropdown/SelectDropdown.tsx
import React from "react"; function SelectDropdown(props: any) { function handleChange(event: any) { props.onSelectChange(event); } return ( <select data-testid={props.testid} id={props.id} onChange={handleChange}> {props.params.map((elem: any) => ( <option value={elem}>{elem}</option> ))} </select> ); } export default SelectDropdown;
divyajyoti21/CarSalesApp
src/App.tsx
import React, { useEffect, useState } from "react"; import { Router, Switch, Route, withRouter } from "react-router-dom"; import Header from "./components/Header/Header"; import Footer from "./components/Footer/Footer"; import Home from "./app/Home/Home"; import Details from "./app/Details/Details"; import { createBrowserHistory } from "history"; import PageNotFound from "./app/PageNotFound/PageNotFound"; import Favorites from "./app/Favorites/Favorites"; function App() { const [carList, updateCarList] = useState([]); const [loading, updateLoading] = useState(true); const [colors, updateColors] = useState([]); const [manufacturers, updateManufacturers] = useState([]); const [totalPages, updateTotalPages] = useState(0); const [carsPerPage, updateCarsPerPage] = useState(0); const [currentPageNumber, updateCurrentPageNumber] = useState(1); const [filterColor, updateFilterColor] = useState(undefined); const [filterManufacturer, updateFilterManufacturer] = useState(undefined); const [totalCarCount, updateTotalCarCount] = useState(0); const history: any = createBrowserHistory({ forceRefresh: true }); const getCarList = (page: any, color: any, manufacturer: any) => { let url = "https://auto1-mock-server.herokuapp.com/api/cars?page=" + page; if (color && manufacturer) { url = "https://auto1-mock-server.herokuapp.com/api/cars?manufacturer=" + manufacturer + "&color=" + color + "&sort=asc&page=" + page; } fetch(url) .then((res) => res.json()) .then( (response) => { console.log(response); updateCarList(response.cars); updateTotalPages(response.totalPageCount); updateCarsPerPage(response.cars.length); updateTotalCarCount(response.totalCarsCount); updateLoading(false); }, (error) => { console.log(error); } ); }; const getColors = () => { let url = "https://auto1-mock-server.herokuapp.com/api/colors"; fetch(url) .then((res) => res.json()) .then( (response) => { localStorage.setItem("colors", JSON.stringify(response.colors)); updateColors(response.colors); }, (error) => { console.log(error); } ); }; const getManufacturers = () => { let url = "https://auto1-mock-server.herokuapp.com/api/manufacturers"; fetch(url) .then((res) => res.json()) .then( (response) => { localStorage.setItem( "manufacturers", JSON.stringify(response.manufacturers) ); updateManufacturers(response.manufacturers); }, (error) => { console.log(error); } ); }; useEffect(() => { getCarList(1, filterColor, filterManufacturer); getColors(); getManufacturers(); }, []); function handleClick(id: any) { if (id == "Next") { if (currentPageNumber < totalPages) { updateCurrentPageNumber(currentPageNumber + 1); getCarList(currentPageNumber, filterColor, filterManufacturer); } } else if (id == "Prev") { if (currentPageNumber !== 1) { updateCurrentPageNumber(currentPageNumber - 1); getCarList(currentPageNumber - 1, filterColor, filterManufacturer); } } else if (id == "First") { updateCurrentPageNumber(1); getCarList(1, filterColor, filterManufacturer); } else if (id == "Last") { updateCurrentPageNumber(totalPages); getCarList(totalPages, filterColor, filterManufacturer); } else { } } const onViewDetails = (id: any) => { history.push({ pathname: "/details", state: { carList: carList, id: id }, }); }; const handleFilter = (color: any, manufacturer: any) => { updateFilterColor(color); updateFilterManufacturer(manufacturer); if (color == "allcolors") { color = undefined; } if (manufacturer == "allmanufacturers") { manufacturer = undefined; } getCarList(1, color, manufacturer); }; return ( <div className="wrapper"> <header> <Header /> </header> <Router history={history}> <div> <Switch> <Route exact path="/" render={() => ( <Home colors={colors} loading={loading} totalCarCount={totalCarCount} manufacturers={manufacturers} cars={carList} carCountPerPage={carsPerPage} totalPages={totalPages} currentPageNumber={currentPageNumber} onClick={handleClick} onViewDetails={onViewDetails} onHandleFilter={handleFilter} /> )} ></Route> <Route exact path="/home" render={() => ( <Home colors={colors} loading={loading} totalCarCount={totalCarCount} manufacturers={manufacturers} cars={carList} carCountPerPage={carsPerPage} totalPages={totalPages} currentPageNumber={currentPageNumber} onClick={handleClick} onViewDetails={onViewDetails} onHandleFilter={handleFilter} /> )} ></Route> <Route exact path="/favorites" render={() => <Favorites onViewDetails={onViewDetails} />} ></Route> <Route exact path="/details" component={Details}></Route> <Route component={PageNotFound}></Route> </Switch> </div> </Router> <footer> <Footer /> </footer> </div> ); } export default withRouter(App);
divyajyoti21/CarSalesApp
src/app/Details/Details.tsx
<reponame>divyajyoti21/CarSalesApp<gh_stars>0 import { withRouter } from "react-router-dom"; import { useEffect, useState } from "react"; import "./Details.css"; import React from "react"; import Button from "../../components/Button/Button"; function Details(props: any) { useEffect(() => { if (props.location.state) { updateCarDetails( props.location.state.carList[parseInt(props.location.state.id)] ); getCarDetails(); } }, []); const [carDetails, updateCarDetails] = useState({ manufacturerName: "", modelName: "", mileage: { number: "", unit: "" }, stockNumber: "", fuelType: "", color: "", }); function saveDetails() { let favorites: any = localStorage.getItem("favorites"); if (favorites) { let parsedFav = JSON.parse(favorites); console.log(typeof parsedFav); let count = 0; for (let i = 0; i < parsedFav.length; i++) { if ( parsedFav[i].stockNumber == carDetails.stockNumber && parsedFav[i].modelName == carDetails.modelName ) { count++; } } if (count == 0) parsedFav.push(carDetails); localStorage.setItem("favorites", JSON.stringify(parsedFav)); } else { localStorage.setItem("favorites", JSON.stringify([carDetails])); } } function getCarDetails() { if (props.location.state) { localStorage.setItem( "carList", JSON.stringify(props.location.state.carList) ); localStorage.setItem("state", JSON.stringify(props.location.state)); let stat: any = localStorage.getItem("state"); let carList: any = localStorage.getItem("carList"); let parsedStat = JSON.parse(stat); let parsedCarList = JSON.parse(carList); if (parsedCarList) { updateCarDetails(parsedCarList[parseInt(parsedStat.id)]); } } } return ( <div> <div className="car-details-img"></div> <div className="car-details-content"> {carDetails && ( <div id="carDetailsInfo" style={{ width: "30%" }}> <div> {carDetails.manufacturerName}&nbsp;{carDetails.modelName} </div> <div> Stock&nbsp;#&nbsp;{carDetails.stockNumber}&nbsp;-&nbsp; {carDetails.mileage.number}&nbsp;{carDetails.mileage.unit} &nbsp;-&nbsp;{carDetails.fuelType}&nbsp;-&nbsp;{carDetails.color} </div> <div> The car is currently available and can be delivered as soon as tomorrow morning. Please be aware that delivery times shown in this page are not definitive and may change due to bad weather conditions </div> </div> )} <div id="saveCarDetails"> <div> If you like this car, click the button <br /> and save it in your collection of favourite items. </div> <div className="save-details-button"> <Button name="Save" onClick={saveDetails}></Button> </div> </div> </div> </div> ); } export default React.memo(withRouter(Details));
divyajyoti21/CarSalesApp
src/app/Home/Home.tsx
import MultiFilter from "../../components/MultiFilter/MultiFilter"; import DisplayCard from "../../components/DisplayCard/DisplayCard"; import Paginate from "../../components/Paginate/Paginate"; import { withRouter } from "react-router-dom"; import "./Home.css"; import Loading from "../../components/Loading/Loading"; import React from "react"; function Home(props: any) { function handleClick(id: any) { props.onClick(id); } function onViewDetails(id: any) { props.onViewDetails(id); } function handleFilterClick(color: string, manufacturer: string) { props.onHandleFilter(color, manufacturer); } return ( <div className="home-grid"> <div style={{ width: "30%", float: "left" }}> <MultiFilter colors={props.colors} manufacturers={props.manufacturers} onClick={handleFilterClick} ></MultiFilter> </div> <div style={{ width: "70%", float: "right" }}> <div className="available-cars">Available cars</div> <div className="car-count-display"> Showing {props.carCountPerPage} of {props.totalCarCount} results </div> {props.loading ? ( <React.Fragment> {[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((index: number) => ( <Loading key={index} /> ))} </React.Fragment> ) : ( props.cars.map((car: any, index: number) => ( <DisplayCard key={index} car={car} onViewDetails={onViewDetails} index={index} ></DisplayCard> )) )} <Paginate onClick={handleClick} currentPage={props.currentPageNumber} totalNumberOfPages={props.totalPages} /> </div> </div> ); } export default withRouter(Home);
fedecech/starter-snake-node-ts
src/routes/end.ts
import { Router, Request, Response } from 'express'; import { GameData } from '../interfaces/gameData'; const router = Router(); router.post('/end', (req: Request, res: Response) => { const gameData = req.body as GameData; console.log('/end', gameData); res.status(200).send('ok'); }); export { router as endRouter };
fedecech/starter-snake-node-ts
src/routes/start.ts
import { Router, Request, Response } from 'express'; import { GameData } from '../interfaces/gameData'; const router = Router(); router.post('/start', (req: Request, res: Response) => { const gameData = req.body as GameData; console.log('/start', gameData); res.status(200).send('ok'); }); export { router as startRouter };
fedecech/starter-snake-node-ts
src/core/Converter.ts
<reponame>fedecech/starter-snake-node-ts<filename>src/core/Converter.ts import { Coordinates, GameData } from '../interfaces/gameData'; export class Converter { private gameData: GameData; constructor(gameData: GameData) { this.gameData = gameData; } public getFood() { const { height, food } = this.gameData.board; let convertedFood: Coordinates[] = []; food.forEach((f) => { convertedFood.push(this.toTopBottomIndexed(f, height)); }); return convertedFood; } public getMatrix() { return this.gameDataToMatrix(this.gameData); } public getMySnakeHead() { const { head } = this.gameData.you; const { height } = this.gameData.board; return this.toTopBottomIndexed(head, height); } private gameDataToMatrix(gd: GameData) { const { width, height } = gd.board; const walls = this.getWalls(); let matrix: number[][] = []; for (let row = 0; row < height; row++) { matrix[row] = []; for (let col = 0; col < width; col++) { const cord = { x: col, y: row }; if (!walls.some((w) => w.x === cord.x && w.y === cord.y)) { //walkable matrix[row][col] = 0; } else { //not walkable matrix[row][col] = 1; } } } return matrix; } public getWalls() { const { snakes, height } = this.gameData.board; const { id } = this.gameData.you; let walls: Coordinates[] = []; snakes.forEach((s) => { const { head } = s; let body = s.body; // filter head from body if its my snake if (s.id === id) { body = body.filter((s) => s.x != head.x || s.y != head.y); } walls = walls.concat(body); }); for (let i = 0; i < walls.length; i++) { walls[i] = this.toTopBottomIndexed(walls[i], height); } return walls; } // method that converts points from gameData to matrix indexed points // gameData idexing: // 0 1 2 3 // 3 // 2 // 1 // 0 // matrix idexing: // 0 1 2 3 // 0 // 1 // 2 // 3 public toTopBottomIndexed(p: Coordinates, rows: number) { return { x: p.x, y: rows - p.y - 1 }; } }
fedecech/starter-snake-node-ts
src/interfaces/battlesnakeInfo.ts
export interface BattleSnakeInfo { apiversion: string; author: string; color: string, head: string, tail: string, }
fedecech/starter-snake-node-ts
src/core/util.ts
<gh_stars>0 import { AStarFinder } from '../finders/astar-finder'; import { Coordinates } from '../interfaces/gameData'; import { PossibleMoves } from '../routes/move'; import { Node } from './Node'; /** * Backtrace from end node through parents and return the path. * @param node * @param includeStartingNode */ export function backtrace( node: Node, includeStartNode: boolean, includeEndNode: boolean ): number[][] { // Init empty path const path: number[][] = []; let currentNode: Node; if (includeEndNode) { // Attach the end node to be the current node currentNode = node; } else { currentNode = node.getParent(); } // Loop as long the current node has a parent while (currentNode.getParent()) { path.push([currentNode.position.x, currentNode.position.y]); currentNode = currentNode.getParent(); } // If true we will also include the starting node if (includeStartNode) { path.push([currentNode.position.x, currentNode.position.y]); } return path.reverse(); } /** * Find shortest path from point A to point B using A* algorithm. * @param s [starting cordinates] * @param e [ending coordinates] * @param matrix [2D array fo board] */ export const next_path = ( s: Coordinates, e: Coordinates, matrix: number[][] ) => { return new AStarFinder({ grid: { matrix, }, diagonalAllowed: false, includeStartNode: false, includeEndNode: true, }).findPath(s, e); }; /** * Finds next possible step where there is no obstacle. * @param head [starting coordinates] * @param walls [obstacles coordinates] * @param width [width of board] * @param height [height of board] */ const next_clear_step = ( head: Coordinates, walls: Coordinates[], width: number, height: number ) => { const up = { x: head.x, y: head.y - 1, direction: PossibleMoves.UP }; const dw = { x: head.x, y: head.y + 1, direction: PossibleMoves.DOWN }; const lt = { x: head.x - 1, y: head.y, direction: PossibleMoves.LEFT }; const rt = { x: head.x + 1, y: head.y, direction: PossibleMoves.RIGHT }; let dirs = [up, dw, lt, rt]; // remove directions were there are external walls dirs = dirs.filter( (d) => (d.x < width || d.x >= 0) && (d.y < height || d.y >= 0) ); console.log('DIRS: ', dirs); console.log('WALLS: ', walls); walls.forEach((w) => { if (w.x === up.x && w.y === up.y) { dirs.splice(dirs.indexOf(up)); } else if (w.x === dw.x && w.y === dw.y) { dirs.splice(dirs.indexOf(dw)); } else if (w.x === lt.x && w.y === lt.y) { dirs.splice(dirs.indexOf(lt)); } else if (w.x === rt.x && w.y === rt.y) { dirs.splice(dirs.indexOf(rt)); } }); console.log('DIRS AFTER SPLICE: ', dirs); return dirs.length > 0 ? dirs[0].direction : PossibleMoves.LEFT; // all 4 ways (up, left, right, down) have walls }; export const next_move = ( path: number[][], head: Coordinates, walls: Coordinates[], width: number, height: number ) => { if (path.length < 1) { return next_clear_step(head, walls, width, height); } const step = path[0]; const x = step[0]; const y = step[1]; if (x < head.x) { return PossibleMoves.LEFT; } else if (x > head.x) { return PossibleMoves.RIGHT; } else if (y > head.y) { return PossibleMoves.DOWN; } else { return PossibleMoves.UP; } };
fedecech/starter-snake-node-ts
src/index.ts
import { app } from './app'; const PORT = process.env.PORT || 3000; app.listen(PORT, () => console.log(`Battlesnake Server listening at http://127.0.0.1:${PORT}`) );
fedecech/starter-snake-node-ts
src/routes/index.ts
import { Router, Request, Response } from 'express'; import { BattleSnakeInfo } from '../interfaces/battlesnakeInfo'; const router = Router(); // route used to get info about the snakes before the game starts router.get('/', (_: Request, res: Response) => { const battlesnakeInfo: BattleSnakeInfo = { apiversion: '1', author: 'fedecech', color: '#ffcc00', head: 'default', tail: 'default', }; res.status(200).json(battlesnakeInfo); }); export { router as baseRouter };
fedecech/starter-snake-node-ts
src/app.ts
<filename>src/app.ts import { json } from 'body-parser'; import express from 'express'; import { baseRouter } from './routes'; import { endRouter } from './routes/end'; import { moveRouter } from './routes/move'; import { startRouter } from './routes/start'; const app = express(); app.use(json()); app.use(baseRouter); app.use(startRouter); app.use(moveRouter); app.use(endRouter); export { app };
fedecech/starter-snake-node-ts
src/interfaces/astar.ts
import { HeuristicFN } from './../core/Heuristic'; import { Coordinates } from './gameData'; export interface INodeConstructor { id: number; position: Coordinates; walkable?: boolean; } export interface IGridConstructor { width?: number; height?: number; matrix: number[][]; } export interface IAStarFinderConstructor { grid: IGridConstructor; diagonalAllowed?: boolean; heuristic?: HeuristicFN; weight?: number; includeStartNode?: boolean; includeEndNode?: boolean; }
fedecech/starter-snake-node-ts
src/core/Node.ts
<reponame>fedecech/starter-snake-node-ts import { Coordinates } from '../interfaces/gameData'; import { INodeConstructor } from '../interfaces/astar'; export class Node { readonly id: number; readonly position: Coordinates; private fValue: number; private gValue: number; private hValue: number; private parentNode: Node; private isOnClosedList: boolean; private isOnOpenList: boolean; private isWalkable: boolean; constructor(params: INodeConstructor) { this.id = params.id; this.position = params.position; // set default values this.hValue = 0; this.gValue = 0; this.fValue = 0; this.parentNode = undefined; this.isOnClosedList = false; this.isOnOpenList = false; this.isWalkable = params.walkable || true; } /** * Calculate or Recalculate the F value * This is a private function */ private calculateFValue(): void { this.fValue = this.gValue + this.hValue; } /** * Set the g value of the node */ public setGValue(gValue: number): void { this.gValue = gValue; // The G value has changed, so recalculate the f value this.calculateFValue(); } /** * Set the h value of the node */ public setHValue(hValue: number): void { this.hValue = hValue; // The H value has changed, so recalculate the f value this.calculateFValue(); } /** * Reset the FGH values to zero */ public setFGHValuesToZero(): void { this.fValue = this.gValue = this.hValue = 0; } /** * Getter functions */ public getFValue(): number { return this.fValue; } public getGValue(): number { return this.gValue; } public getHValue(): number { return this.hValue; } public getParent(): Node { return this.parentNode; } public getIsOnClosedList(): boolean { return this.isOnClosedList; } public getIsOnOpenList(): boolean { return this.isOnOpenList; } public getIsWalkable(): boolean { return this.isWalkable; } /** * Setter functions */ public setParent(parent: Node): void { this.parentNode = parent; } public setIsOnClosedList(isOnClosedList: boolean): void { this.isOnClosedList = isOnClosedList; } public setIsOnOpenList(isOnOpenList: boolean): void { this.isOnOpenList = isOnOpenList; } public setIsWalkable(isWalkable: boolean): void { this.isWalkable = isWalkable; } }
fedecech/starter-snake-node-ts
src/core/Heuristic.ts
<gh_stars>0 import { Coordinates } from './../interfaces/gameData'; export type HeuristicFN = 'Manhatten' | 'Euclidean' | 'Chebyshev' | 'Octile'; export class Heuristic { public static calculateHeuristic( hFN: HeuristicFN, pos0: Coordinates, pos1: Coordinates, weight?: number ) { const dx = Math.abs(pos1.x - pos0.x); const dy = Math.abs(pos1.y - pos0.y); switch (hFN) { case 'Manhatten': return this.manhatten(dx, dy, weight); case 'Euclidean': return this.euclidean(dx, dy, weight); case 'Octile': return this.octile(dx, dy, weight); case 'Chebyshev': return this.chebyshev(dx, dy, weight); } } private static manhatten(dx: number, dy: number, weight?: number) { return weight ? (dx + dy) * weight : dx + dy; } private static euclidean(dx: number, dy: number, weight?: number) { return weight ? Math.sqrt(dx * dx + dy * dy) * weight : Math.sqrt(dx * dx + dy * dy); } private static octile(dx: number, dy: number, weight?: number) { return weight ? (dx + dy - 0.58 * Math.min(dx, dy)) * weight : dx + dy - 0.58 * Math.min(dx, dy); } private static chebyshev(dx: number, dy: number, weight?: number) { return weight ? Math.max(dx, dy) * weight : Math.max(dx, dy); } }
fedecech/starter-snake-node-ts
src/interfaces/gameData.ts
export interface GameData { game: Game; turn: number; board: Board; you: Snake; } export interface Game { id: string; ruleset: RuleSet; timeout: number; } export interface RuleSet { name: string; version: string; } export interface Board { height: number; width: number; snakes: [Snake]; food: Coordinates[]; hazards: []; } export interface Snake { id: string; latency: string; health: number; body: Coordinates[]; head: Coordinates; length: number; shout: string; } export interface Coordinates { x: number; y: number; }
fedecech/starter-snake-node-ts
src/routes/move.ts
<filename>src/routes/move.ts import { Heuristic } from '../core/Heuristic'; import { Coordinates } from '../interfaces/gameData'; import { Router, Request, Response } from 'express'; import { GameData } from '../interfaces/gameData'; import { Converter } from '../core/Converter'; import { next_move, next_path } from '../core/util'; const router = Router(); export enum PossibleMoves { UP = 'up', DOWN = 'down', LEFT = 'left', RIGHT = 'right', } const logs = (gameData: GameData, matrix: number[][], food: Coordinates[]) => { console.log('Game Id: ', gameData.game.id); console.log('Turn ', gameData.turn); console.log('Board: ', matrix); console.log('Food', food); }; router.post('/move', (req: Request, res: Response) => { const gameData = req.body as GameData; const { width, height } = gameData.board; const converter = new Converter(gameData); const matrix = converter.getMatrix(); const food = converter.getFood(); const head = converter.getMySnakeHead(); const walls = converter.getWalls(); // change beacuse is doing usless calcs ? maybe store walls in instace var logs(gameData, matrix, food); let min_distance = 100; // because max is 19x19 grid let next_food = food.length > 0 ? food[0] : null; food.forEach((f) => { const distance = Heuristic.calculateHeuristic('Manhatten', head, f); if (distance < min_distance) { min_distance = distance; next_food = f; } }); const path = next_path(head, next_food, matrix); const move = next_move(path, head, walls, width, height); console.log('Head', head); console.log('Next food ', next_food); console.log('Path to next food', path); console.log('Move to next food', move); res.status(200).send({ move, }); }); export { router as moveRouter };
fedecech/starter-snake-node-ts
src/core/Grid.ts
<reponame>fedecech/starter-snake-node-ts<gh_stars>0 import { Coordinates } from './../interfaces/gameData'; import { IGridConstructor } from './../interfaces/astar'; import { Node } from './Node'; export class Grid { readonly width: number; readonly height: number; readonly numberOfFields: number; private gridNodes: Node[][]; constructor(params: IGridConstructor) { if (params.width && params.height) { this.width = params.width; this.height = params.height; this.numberOfFields = this.width * this.height; } else if (params.matrix) { this.width = params.matrix[0].length; this.height = params.matrix.length; this.numberOfFields = this.width * this.height; } // Create and generate the matrix this.gridNodes = this.buildGridWithNodes( params.matrix || undefined, this.width, this.height ); } private buildGridWithNodes( matrix: number[][], width: number, height: number ) { const newGrid: Node[][] = []; let id: number = 0; for (let y = 0; y < height; y++) { newGrid[y] = []; for (let x = 0; x < width; x++) { newGrid[y][x] = new Node({ id, position: { x, y } }); id++; } } for (let y = 0; y < height; y++) { for (let x = 0; x < width; x++) { if (matrix[y][x]) { newGrid[y][x].setIsWalkable(false); } else { newGrid[y][x].setIsWalkable(true); } } } return newGrid; } /** * Return a specific node. * @param position [position on the grid] */ public getNodeAt(position: Coordinates): Node { return this.gridNodes[position.y][position.x]; } /** * Check if specific node walkable. * @param position [position on the grid] */ public isWalkableAt(position: Coordinates): boolean { return this.gridNodes[position.y][position.x].getIsWalkable(); } /** * Check if specific node is on the grid. * @param position [position on the grid] */ private isOnTheGrid(position: Coordinates): boolean { return ( position.x >= 0 && position.x < this.width && position.y >= 0 && position.y < this.height ); } /** * Get surrounding nodes. * @param currentXPos [x-position on the grid] * @param currentYPos [y-position on the grid] * @param diagnonalMovementAllowed [is diagnonal movement allowed?] */ public getSurroundingNodes( currentPosition: Coordinates, diagnonalMovementAllowed: boolean ): Node[] { const surroundingNodes: Node[] = []; for (var y = currentPosition.y - 1; y <= currentPosition.y + 1; y++) { for (var x = currentPosition.x - 1; x <= currentPosition.x + 1; x++) { if (this.isOnTheGrid({ x, y })) { if (this.isWalkableAt({ x, y })) { if (diagnonalMovementAllowed) { surroundingNodes.push(this.getNodeAt({ x, y })); } else { if (x == currentPosition.x || y == currentPosition.y) { surroundingNodes.push(this.getNodeAt({ x, y })); } } } else { continue; } } else { continue; } } } return surroundingNodes; } public setGrid(newGrid: Node[][]): void { this.gridNodes = newGrid; } /** * Reset the grid */ public resetGrid(): void { for (let y = 0; y < this.gridNodes.length; y++) { for (let x = 0; x < this.gridNodes[y].length; x++) { this.gridNodes[y][x].setIsOnClosedList(false); this.gridNodes[y][x].setIsOnOpenList(false); this.gridNodes[y][x].setParent(undefined); this.gridNodes[y][x].setFGHValuesToZero(); } } } /** * Get all the nodes of the grid. */ public getGridNodes(): Node[][] { return this.gridNodes; } /** * Get a clone of the grid */ public clone(): Node[][] { const cloneGrid: Node[][] = []; let id: number = 0; for (let y = 0; y < this.height; y++) { cloneGrid[y] = []; for (let x = 0; x < this.width; x++) { cloneGrid[y][x] = new Node({ id: id, position: { x: x, y: y }, walkable: this.gridNodes[y][x].getIsWalkable(), }); id++; } } return cloneGrid; } }
egozavr/angular2-switcher
src/extension.ts
<filename>src/extension.ts "use strict"; // The module 'vscode' contains the VS Code extensibility API // Import the module and reference it with the alias vscode in your code below import * as vscode from "vscode"; function fileIs(path: string, ...items: string[]): boolean { if (!items) { return false; } for (let index = 0; index < items.length; index++) { if (path.endsWith(items[index].toLowerCase())) { return true; } } return false; } function fileIsTs(path: string) { if (fileIs(path, ".ts")) { let parts = path.split("."); parts.pop(); if (parts[parts.length - 1] !== "spec") { return true; } } return false; } function fileIsStyle(path: string) { return fileIs(path, ".scss", ".sass", ".less", ".css"); } function fileIsHtml(path: string) { return fileIs(path, ".html"); } function fileIsPug(path: string) { return fileIs(path, ".pug"); } function fileIsSpec(path: string) { return fileIs(path, ".spec.ts"); } function getFileNameWithoutExtension(path: string) { let parts = path.split("."); parts.pop(); if (parts.length > 1) { if (parts[parts.length - 1] === "spec") { parts.pop(); } } return parts.join("."); } let isSplit = vscode.workspace .getConfiguration("ngx-swithcer") .get<boolean>("openSideBySide"); vscode.workspace.onDidChangeConfiguration(() => { isSplit = vscode.workspace .getConfiguration("ngx-swithcer") .get("openSideBySide"); }); let previous = ""; function xOpenTextDocument( path: string, viewColumn?: vscode.ViewColumn ): Promise<vscode.TextDocument> { return new Promise((resolve, reject) => { let opened = false; // vscode.workspace.textDocuments.forEach((doc) => { // }); // try to find opened document. vscode.window.visibleTextEditors.forEach(textEditor => { if (textEditor.document.fileName === path) { opened = true; vscode.window .showTextDocument(textEditor.document, textEditor.viewColumn) .then( () => { resolve(textEditor.document); }, err => { reject(err); } ); } }); if (!opened) { vscode.workspace.openTextDocument(path).then( doc => { vscode.window.showTextDocument(doc, viewColumn).then( () => { resolve(doc); }, err => { reject(err); } ); }, err => { reject(err); } ); } }); } // this method is called when your extension is activated // your extension is activated the very first time the command is executed export function activate(context: vscode.ExtensionContext) { // Use the console to output diagnostic information (console.log) and errors (console.error) // This line of code will only be executed once when your extension is activated console.log( 'Congratulations, your extension "ngx-switcher" is now active!' ); // The command has been defined in the package.json file // Now provide the implementation of the command with registerCommand // The commandId parameter must match the command field in package.json let cmdSwitchTemplate = vscode.commands.registerCommand( "extension.switchTemplate", () => { // The code you place here will be executed every time your command is executed // Display a message box to the user // vscode.window.showInformationMessage('Hello World!'); if (!vscode.workspace) { return; } var editor = vscode.window.activeTextEditor; if (!editor) { return; } var currentFile = editor.document.fileName; let fileNameWithoutExtension = getFileNameWithoutExtension(currentFile); var targetFile = ""; if ( fileIsTs(currentFile) || fileIsStyle(currentFile) || fileIsSpec(currentFile) || fileIsPug(currentFile) ) { targetFile = fileNameWithoutExtension + ".html"; } else if (fileIsHtml(currentFile)) { if (previous && previous !== currentFile) { if (previous.startsWith(fileNameWithoutExtension)) { targetFile = previous; } else { targetFile = fileNameWithoutExtension + ".ts"; } } else { targetFile = fileNameWithoutExtension + ".ts"; } } else { return; } xOpenTextDocument( targetFile, isSplit ? vscode.ViewColumn.Two : editor.viewColumn ).then( () => { previous = currentFile; }, err => { console.log(err); } ); } ); let cmdSwitchPug = vscode.commands.registerCommand( "extension.switchPug", () => { // The code you place here will be executed every time your command is executed // Display a message box to the user // vscode.window.showInformationMessage('Hello World!'); if (!vscode.workspace) { return; } var editor = vscode.window.activeTextEditor; if (!editor) { return; } var currentFile = editor.document.fileName; let fileNameWithoutExtension = getFileNameWithoutExtension(currentFile); var targetFile = ""; if ( fileIsTs(currentFile) || fileIsStyle(currentFile) || fileIsSpec(currentFile) || fileIsHtml(currentFile) ) { targetFile = fileNameWithoutExtension + ".pug"; } else if (fileIsPug(currentFile)) { if (previous && previous !== currentFile) { if (previous.startsWith(fileNameWithoutExtension)) { targetFile = previous; } else { targetFile = fileNameWithoutExtension + ".ts"; } } else { targetFile = fileNameWithoutExtension + ".ts"; } } else { return; } xOpenTextDocument( targetFile, isSplit ? vscode.ViewColumn.Two : editor.viewColumn ).then( () => { previous = currentFile; }, err => { console.log(err); } ); } ); let cmdSwitchTS = vscode.commands.registerCommand( "extension.switchTS", () => { if (!vscode.workspace) { return; } var editor = vscode.window.activeTextEditor; if (!editor) { return; } var currentFile = editor.document.fileName; let fileNameWithoutExtension = getFileNameWithoutExtension(currentFile); var targetFile = ""; if ( fileIsHtml(currentFile) || fileIsStyle(currentFile) || fileIsSpec(currentFile) || fileIsPug(currentFile) ) { targetFile = fileNameWithoutExtension + ".ts"; } else if (fileIsTs(currentFile)) { if (previous && previous !== currentFile) { if (previous.startsWith(fileNameWithoutExtension)) { targetFile = previous; } else { targetFile = fileNameWithoutExtension + ".html"; } } else { targetFile = fileNameWithoutExtension + ".html"; } } else { return; } xOpenTextDocument( targetFile, isSplit ? vscode.ViewColumn.Two : editor.viewColumn ).then( () => { previous = currentFile; }, err => { // console.log(err); } ); } ); let cmdSwitchStyle = vscode.commands.registerCommand( "extension.switchStyle", () => { if (!vscode.workspace) { return; } var editor = vscode.window.activeTextEditor; if (!editor) { return; } var currentFile = editor.document.fileName; let fileNameWithoutExtension = getFileNameWithoutExtension(currentFile); var targetFile: string[] = []; if (fileIsStyle(currentFile)) { if (previous && previous !== currentFile) { if (previous.startsWith(fileNameWithoutExtension)) { targetFile.push(previous); } else { targetFile.push(fileNameWithoutExtension + ".html"); } } else { targetFile.push(fileNameWithoutExtension + ".html"); } } else if ( fileIsTs(currentFile) || fileIsHtml(currentFile) || fileIsSpec(currentFile) || fileIsPug(currentFile) ) { targetFile.push(fileNameWithoutExtension + ".scss"); targetFile.push(fileNameWithoutExtension + ".sass"); targetFile.push(fileNameWithoutExtension + ".less"); targetFile.push(fileNameWithoutExtension + ".css"); } else { return; } var g = gen( targetFile, isSplit ? vscode.ViewColumn.Two : editor.viewColumn ); function next() { var result = g.next(); if (result.done) return; result.value.then( () => { previous = currentFile; return; }, err => { // console.log(err); next(); } ); } next(); } ); // will jump *.spec.ts only current within *.ts let cmdSwitchSpec = vscode.commands.registerCommand( "extension.switchSpec", () => { if (!vscode.workspace) { return; } var editor = vscode.window.activeTextEditor; if (!editor) { return; } var currentFile = editor.document.fileName; let fileNameWithoutExtension = getFileNameWithoutExtension(currentFile); var targetFile = ""; if ( fileIsTs(currentFile) || fileIsStyle(currentFile) || fileIsHtml(currentFile) || fileIsPug(currentFile) ) { targetFile = fileNameWithoutExtension + ".spec.ts"; } else if (fileIsSpec(currentFile)) { if (previous && previous !== currentFile) { if (previous.startsWith(fileNameWithoutExtension)) { targetFile = previous; } else { targetFile = fileNameWithoutExtension + ".ts"; } } else { targetFile = fileNameWithoutExtension + ".ts"; } } else { return; } xOpenTextDocument( targetFile, isSplit ? vscode.ViewColumn.Two : editor.viewColumn ).then( () => { previous = currentFile; }, err => { console.log(err); } ); } ); context.subscriptions.push(cmdSwitchTemplate, cmdSwitchStyle, cmdSwitchTS, cmdSwitchPug); } function* gen(files: string[], viewColumn: vscode.ViewColumn) { for (var index = 0; index < files.length; index++) { yield xOpenTextDocument(files[index], viewColumn); } } // this method is called when your extension is deactivated export function deactivate() { }
parsegraph/spotlightpainter
src/index.ts
<reponame>parsegraph/spotlightpainter<gh_stars>0 import SpotlightPainter from "./SpotlightPainter"; export default SpotlightPainter;
parsegraph/spotlightpainter
src/SpotlightPainter.ts
import { compileProgram } from "parsegraph-compileprogram"; import { generateRectangleVertices, generateRectangleTexcoords, Matrix3x3, } from "parsegraph-matrix"; import PagingBuffer from "parsegraph-pagingbuffer"; import Color from "parsegraph-color"; import spotlightPainterVertexShader from "./SpotlightPainter_VertexShader.glsl"; import spotlightPainterFragmentShader from "./SpotlightPainter_FragmentShader.glsl"; import { GLProvider } from "parsegraph-compileprogram"; export default class SpotlightPainter { _window: GLProvider; _program: any; _spotlightBuffer: PagingBuffer; aPosition: any; aTexCoord: any; aColor: any; uWorld: WebGLUniformLocation; constructor(window: GLProvider) { this._window = window; if (!this._window) { throw new Error("Window must be provided"); } this._program = null; this.contextChanged(this._window.gl().isContextLost()); } drawSpotlight(cx: number, cy: number, radius: number, color: Color) { if (this._spotlightBuffer === null) { return; } // console.log(cx + ", " + cy + ", " + radius + " " + color.toString()); // Append position data. this._spotlightBuffer.appendData( this.aPosition, generateRectangleVertices(cx, cy, radius * 2, radius * 2) ); // Append texture coordinate data. this._spotlightBuffer.appendData( this.aTexCoord, generateRectangleTexcoords() ); // Append color data. for (let k = 0; k < 3 * 2; ++k) { this._spotlightBuffer.appendData( this.aColor, color.r(), color.g(), color.b(), color.a() ); } } drawRectSpotlight( cx: number, cy: number, w: number, h: number, color: Color ) { if (this._spotlightBuffer === null) { return; } // Append position data. this._spotlightBuffer.appendData( this.aPosition, generateRectangleVertices(cx, cy, w, h) ); // Append texture coordinate data. this._spotlightBuffer.appendData( this.aTexCoord, generateRectangleTexcoords() ); // Append color data. for (let k = 0; k < 3 * 2; ++k) { this._spotlightBuffer.appendData( this.aColor, color.r(), color.g(), color.b(), color.a() ); } } clear() { this._spotlightBuffer.clear(); this._spotlightBuffer.addPage(); } contextChanged(isLost: boolean): void { if (isLost) { // console.log(new Error("Losing spotlight painter")); this._program = null; this._spotlightBuffer.clear(); this._spotlightBuffer = null; } else { // console.log(new Error("Restoring spotlight painter")); const gl = this._window.gl(); this._program = compileProgram( this._window, "SpotlightPainter", spotlightPainterVertexShader, spotlightPainterFragmentShader ); // Prepare attribute buffers. this._spotlightBuffer = new PagingBuffer(gl, this._program); this._spotlightBuffer.addPage(); this.aPosition = this._spotlightBuffer.defineAttrib("a_position", 2); this.aTexCoord = this._spotlightBuffer.defineAttrib("a_texCoord", 2); this.aColor = this._spotlightBuffer.defineAttrib("a_color", 4); } } render(world: Matrix3x3): void { const gl = this._window.gl(); if (gl.isContextLost()) { return; } // Cache program locations. this.uWorld = gl.getUniformLocation(this._program, "u_world"); // Render spotlights. gl.useProgram(this._program); gl.uniformMatrix3fv(this.uWorld, false, world); this._spotlightBuffer.renderPages(); } }
yyzclyang/algae-ui
components/form/form.tsx
import React, { useState } from 'react'; import Input, { InputProps } from '../input'; import { scopedClassMaker, classNames, isNonEmptyArray, validator, ValidateFormMessageGroup } from '../utils'; const sc = scopedClassMaker('algae-ui-form'); export type FormMessageType = 'success' | 'warning' | 'error'; export type Rule = ( | { type: 'required'; match: boolean } | { type: 'minLength' | 'maxLength'; match: number } | { type: 'pattern'; match: RegExp } | { type: 'custom'; match: (value: string) => boolean | Promise<boolean>; } ) & { messageType?: FormMessageType; message: string; }; export interface Field { type: string; label: string; input: InputProps; rules?: Rule[]; } export interface FormValue { [key: string]: string; } interface FormProps { value: FormValue; fields: Field[]; buttons: React.ReactNode; onSubmit: React.FormEventHandler<HTMLFormElement>; onChange: (formValue: FormValue) => void; } const Form: React.FunctionComponent<FormProps> = (props: FormProps) => { const { value, fields, buttons, onChange } = props; const [validateMessageGroup, setValidateMessageGroup] = useState< ValidateFormMessageGroup >({}); const onSubmit: React.FormEventHandler<HTMLFormElement> = (e) => { e.preventDefault(); validator(value, fields).then(setValidateMessageGroup); props.onSubmit(e); }; const onFormChange = ( type: string, e: React.ChangeEvent<HTMLInputElement> ) => { onChange({ ...value, [type]: e.currentTarget.value }); }; return ( <form onSubmit={onSubmit} className={classNames(sc())}> <table className={classNames(sc('table'))}> <tbody> {fields.map((field) => ( <tr key={field.type} className={classNames(sc('row'))}> <td> <span className={classNames(sc('row-label'))}> {field.label} </span> </td> <td className={classNames( sc('row-content'), isNonEmptyArray(validateMessageGroup[field.type]) ? sc( 'row-validate-' + validateMessageGroup[field.type][0].type ) : '' )} data-validate={ isNonEmptyArray(validateMessageGroup[field.type]) ? validateMessageGroup[field.type][0].message : '' } > <Input {...field.input} className={classNames(sc('row-input'))} value={value[field.type]} onChange={onFormChange.bind(null, field.type)} /> </td> </tr> ))} <tr className={classNames(sc('row'))}> <td /> <td>{buttons}</td> </tr> </tbody> </table> </form> ); }; Form.displayName = 'Form'; export default Form;
yyzclyang/algae-ui
site/componentExample/RadioExample/radio.codeDemo3.tsx
<filename>site/componentExample/RadioExample/radio.codeDemo3.tsx import React, { useState } from 'react'; import { Radio, RadioGroup } from 'algae-ui'; export default () => { const [value, setValue] = useState<string>('1'); return ( <div className="radio-example-list"> <RadioGroup value={value} onChange={(e) => { setValue(e.currentTarget.value); console.log(e.currentTarget.value); }} > <Radio value="1">Radio</Radio> <Radio value="2">Radio</Radio> <Radio value="3">Radio</Radio> </RadioGroup> </div> ); };
yyzclyang/algae-ui
components/avatar/style/index.ts
<gh_stars>1-10 // style dependencies import '../../icon/style'; import './avatar.scss';
yyzclyang/algae-ui
site/componentExample/MessageExample/message.example.tsx
<filename>site/componentExample/MessageExample/message.example.tsx import React from 'react'; import { CodeDemo, Api } from '../CommonDispalyComponents'; import './message.example.scss'; import CodeDemo1 from './message.codeDemo1'; const code1 = require('!!raw-loader!./message.codeDemo1.tsx'); import CodeDemo2 from './message.codeDemo2'; const code2 = require('!!raw-loader!./message.codeDemo2.tsx'); import CodeDemo3 from './message.codeDemo3'; const code3 = require('!!raw-loader!./message.codeDemo3.tsx'); import CodeDemo4 from './message.codeDemo4'; const code4 = require('!!raw-loader!./message.codeDemo4.tsx'); const MessageExample: React.FunctionComponent = () => { return ( <div className="message-example-page"> <section> <h1>Message 消息</h1> <p>全局展示操作反馈信息</p> </section> <section> <h2>何时使用</h2> <p>可提供成功、警告和错误等反馈信息</p> </section> <section> <h2>代码演示</h2> <div className="code-demonstration"> <div className="code-demo-column"> <CodeDemo title="基础使用" content={<p>信息提示反馈</p>} code={code1.default} > <CodeDemo1 /> </CodeDemo> <CodeDemo title="修改延时" content={ <p> 设置自定义延时<code>10s</code>,默认延时为<code>3s</code> </p> } code={code3.default} > <CodeDemo3 /> </CodeDemo> </div> <div className="code-demo-column"> <CodeDemo title="其他类型的提示" content={ <p> 包括<code>success</code> <code>error</code> <code> warning</code> </p> } code={code2.default} > <CodeDemo2 /> </CodeDemo> <CodeDemo title="加载中" content={<p>进行全局 loading,异步自行移除。</p>} code={code4.default} > <CodeDemo4 /> </CodeDemo> </div> </div> </section> <section> <h2>API</h2> <p>提供了一些方法,使用方式和参数如下:</p> <ul> <li> <code>message.info(message[, duration[, closeCallback]])</code> </li> <li> <code>message.success(message[, duration[, closeCallback]])</code> </li> <li> <code>message.error(message[, duration[, closeCallback]])</code> </li> <li> <code>message.warning(message[, duration[, closeCallback]])</code> </li> <li> <code>message.loading(message[, duration[, closeCallback]])</code> </li> </ul> <Api data={[ ['message', '提示内容', 'string | ReactNode', '-'], [ 'duration', '自动关闭的延时,单位毫秒。设为 0 时不自动关闭。', 'number', '3000' ], ['closeCallback', '关闭时触发的回调', '() => void', '-'] ]} /> </section> </div> ); }; export default MessageExample;
yyzclyang/algae-ui
site/componentExample/ModalExample/modal.codeDemo2.tsx
<filename>site/componentExample/ModalExample/modal.codeDemo2.tsx<gh_stars>1-10 import React from 'react'; import { Modal, confirm, Button } from 'algae-ui'; export default () => { const showModal = () => confirm({ title: 'This is a confirm message', content: ( <div> <p>some messages...some messages...</p> <p>some messages...some messages...</p> </div> ), iconType: 'question-circle', iconStyle: { fill: 'red' }, okButton: { content: 'Ok', onClick: () => { console.log('你点击了 OK'); } }, cancelButton: { content: 'Cancel', onClick: () => { console.log('你点击了 Cancel'); } } }); const alert = () => { Modal.alert({ title: 'This is a Modal.alert message', content: ( <div> <p>some messages...some messages...</p> <p>some messages...some messages...</p> </div> ), iconType: 'question-circle', iconStyle: { fill: 'red' }, okButton: { content: 'Ok', onClick: () => { console.log('你点击了 OK'); } }, cancelButton: { content: 'Cancel', onClick: () => { console.log('你点击了 Cancel'); } } }); }; return ( <div className="modal-example-list"> <Button buttonType="primary" onClick={showModal}> confirm </Button> <Button onClick={alert}>Modal.alert</Button> </div> ); };
yyzclyang/algae-ui
components/affix/style/index.ts
<reponame>yyzclyang/algae-ui import './affix.scss';
yyzclyang/algae-ui
components/layout/content.tsx
import React from 'react'; import { classNames, scopedClassMaker } from '../utils'; const sc = scopedClassMaker('algae-ui-layout'); interface ContentProps extends React.HtmlHTMLAttributes<HTMLElement> {} const Content: React.FunctionComponent<ContentProps> = ( props: ContentProps ) => { const { className, style, children, ...rest } = props; return ( <div className={classNames(sc('content'), className)} style={style} {...rest} > {children} </div> ); }; export default Content;
yyzclyang/algae-ui
site/componentExample/AvatarExample/index.ts
export { default } from './avatar.example';
yyzclyang/algae-ui
components/progress/circleProgress.tsx
import React from 'react'; import Icon from '../icon'; import { classNames, scopedClassMaker, rotateMatrixGenerator, arcGenerator } from '../utils'; const sc = scopedClassMaker('algae-ui-progress'); interface CircleProgressProps { type?: 'circle' | 'dashboard'; radius?: number; strokeWidth?: number; backgroundColor?: string; strokeColor?: string; strokeLinecap?: 'round' | 'square'; percent: number; value?: string; showInfo?: boolean; status?: 'normal' | 'success' | 'fail'; } const CircleProgress: React.FunctionComponent<CircleProgressProps> = ( props: CircleProgressProps ) => { const { type, radius, strokeWidth, backgroundColor, strokeColor, strokeLinecap, percent, value, showInfo, status } = props; const outRadius = radius! + strokeWidth!; return ( <div className={classNames( sc('circle'), type === 'dashboard' ? sc('dashboard') : '' )} > <svg width="120" height="120" viewBox="0 0 200 200"> <circle cx={outRadius} cy={outRadius} r={radius} strokeWidth={strokeWidth} stroke={backgroundColor} strokeLinecap={strokeLinecap} fill="none" {...(type === 'dashboard' ? { strokeDasharray: arcGenerator(radius!, 1, 270), transform: rotateMatrixGenerator( 135, { x: outRadius, y: outRadius }, { x: outRadius, y: outRadius } ) } : {})} /> <circle cx={outRadius} cy={outRadius} r={radius} strokeWidth={strokeWidth} stroke={strokeColor} strokeLinecap={strokeLinecap} fill="none" transform={ type === 'dashboard' ? rotateMatrixGenerator( 135, { x: outRadius, y: outRadius }, { x: outRadius, y: outRadius } ) : rotateMatrixGenerator( -90, { x: outRadius, y: outRadius }, { x: outRadius, y: outRadius } ) } strokeDasharray={arcGenerator( radius!, percent / 100, type === 'dashboard' ? 270 : 360 )} /> </svg> {showInfo && (status === 'normal' ? ( <span className={classNames(sc('text'), sc('content'))}> {value !== undefined ? value : `${Math.floor(percent)}%`} </span> ) : status === 'success' ? ( <span className={classNames(sc('icon'), sc('content'))}> <Icon type="check" style={{ fill: '#52c41a' }} /> </span> ) : ( <span className={classNames(sc('icon'), sc('content'))}> <Icon type="close" style={{ fill: '#f5222d' }} /> </span> ))} </div> ); }; CircleProgress.displayName = 'CircleProgress'; CircleProgress.defaultProps = { type: 'circle', radius: 88, strokeWidth: 12, backgroundColor: '#E5E5E5', strokeColor: '#506DFE' }; export default CircleProgress;
yyzclyang/algae-ui
components/button/index.ts
<reponame>yyzclyang/algae-ui<filename>components/button/index.ts export { default } from './button'; export { default as ButtonGroup } from './buttonGroup';
yyzclyang/algae-ui
components/steps/index.ts
<reponame>yyzclyang/algae-ui export { default } from './steps'; export { default as Step } from './step'; export { StatusTypes } from './step';
yyzclyang/algae-ui
components/modal/style/index.ts
<reponame>yyzclyang/algae-ui // style dependencies import '../../icon/style'; import '../../button/style'; import './confirm.scss'; import './dialog.scss';
yyzclyang/algae-ui
components/button/button.tsx
<reponame>yyzclyang/algae-ui<gh_stars>1-10 import React from 'react'; import Icon from '../icon'; import { classNames, useDiffuseAnimation } from '../utils'; interface ButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> { buttonType?: 'default' | 'primary' | 'success' | 'danger'; icon?: string; iconPosition?: 'left' | 'right'; loading?: boolean; ghost?: boolean; full?: boolean; children?: React.ReactNode; } const Button: React.FunctionComponent<ButtonProps> = (props: ButtonProps) => { const { buttonType, className, onClick, icon, iconPosition, disabled, loading, ghost, full, children, ...restProps } = props; const [diffuseClassName, setDiffuseClassName] = useDiffuseAnimation(); const handleClick: React.MouseEventHandler = ( e: React.MouseEvent<HTMLButtonElement, MouseEvent> ) => { if (!diffuseClassName && !disabled) { setDiffuseClassName(); } !disabled && onClick && onClick(e); }; return ( <button className={classNames( 'algae-ui-button', `algae-ui-button-${buttonType}`, className, ghost ? 'algae-ui-button-ghost' : undefined, full ? 'algae-ui-button-full' : undefined, disabled ? 'algae-ui-button-disabled' : undefined, diffuseClassName )} onClick={handleClick} {...restProps} > {iconPosition === 'right' && children} {loading ? ( <Icon className={'animation-loading'} type="loading" style={{ fill: 'inherit' }} /> ) : icon ? ( <Icon type={icon} className={iconPosition} /> ) : null} {iconPosition === 'left' && children} </button> ); }; Button.displayName = 'Button'; Button.defaultProps = { buttonType: 'default', loading: false, iconPosition: 'left', ghost: false }; export default Button;
yyzclyang/algae-ui
components/layout/style/index.ts
<gh_stars>1-10 import './content.scss'; import './layout.scss';
yyzclyang/algae-ui
site/componentExample/SwitchExample/switch.codeDemo4.tsx
<filename>site/componentExample/SwitchExample/switch.codeDemo4.tsx import React from 'react'; import { Switch } from 'algae-ui'; export default () => { return ( <div className="switch-example-list"> <Switch defaultChecked loading /> <br /> <br /> <Switch loading /> </div> ); };
yyzclyang/algae-ui
components/utils/classNames.ts
const classNames = (...classNames: Array<string | undefined>) => { return classNames.filter(Boolean).join(' '); }; export default classNames;