repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
khoadaxne15/LastProject
|
src/views/checkout/step2/ShippingTotal.tsx
|
import { useFormikContext } from "formik";
import React from "react";
import { displayMoney } from "../../../helpers";
export const ShippingTotal: React.FC<ShippingTotalProps> = ({ subtotal }) => {
const { values } = useFormikContext();
return (
<div className="checkout-total d-flex-end padding-right-m">
<table>
<tbody>
<tr>
<td>
<span className="d-block margin-0 padding-right-s text-right">International Shipping: </span>
</td>
<td>
<h4 className="basket-total-amount text-subtle text-right margin-0 ">
{/*@ts-ignore*/}
{values.isInternational ? "$50.00" : "$0.00"}
</h4>
</td>
</tr>
<tr>
<td>
<span className="d-block margin-0 padding-right-s text-right">Subtotal: </span>
</td>
<td>
<h4 className="basket-total-amount text-subtle text-right margin-0">{displayMoney(subtotal)}</h4>
</td>
</tr>
<tr>
<td>
<span className="d-block margin-0 padding-right-s text-right">Total: </span>
</td>
<td>
<h2 className="basket-total-amount text-right">
{/* @ts-ignore */}
{displayMoney(Number(subtotal) + (values.isInternational ? 50 : 0))}
</h2>
</td>
</tr>
</tbody>
</table>
</div>
);
};
type ShippingTotalProps = {
subtotal: number;
};
|
khoadaxne15/LastProject
|
src/components/common/AdminSidePanel.tsx
|
import React from "react";
import { NavLink } from "react-router-dom";
import { ADMIN_PRODUCTS, EDIT_PRODUCT, } from "../../constants";
export const AdminSideBar = () => (
<aside className="sidenavigation">
<div className="sidenavigation-wrapper">
<div className="sidenavigation-item">
<NavLink activeClassName="sidenavigation-menu-active" className="sidenavigation-menu" to={ADMIN_PRODUCTS}>
Products
</NavLink>
</div>
<div className="sidenavigation-item">
<NavLink activeClassName="sidenavigation-menu-active" className="sidenavigation-menu" to={EDIT_PRODUCT}>
Users
</NavLink>
</div>
</div>
</aside>
);
|
khoadaxne15/LastProject
|
src/redux/store/store.ts
|
<gh_stars>0
import { applyMiddleware, compose, createStore } from "redux";
import { persistCombineReducers, persistStore } from "redux-persist";
import storage from "redux-persist/lib/storage";
import createSagaMiddleware from "redux-saga";
import { rootReducer } from "../reducers";
import { rootSaga } from "../sagas";
const sagaMiddleware = createSagaMiddleware();
// @ts-ignore
const composeEnhancer = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const authPersistConfig = {
key: "root",
storage,
whitelist: ["auth", "profile", "basket", "checkout"],
};
export const createAppStore = () => {
const store = createStore(
persistCombineReducers(authPersistConfig, rootReducer),
composeEnhancer(applyMiddleware(sagaMiddleware))
);
const persistor = persistStore(store);
sagaMiddleware.run(rootSaga);
return { store, persistor };
};
|
stankaholic/fight-bot
|
src/deploy-commands.ts
|
<reponame>stankaholic/fight-bot<filename>src/deploy-commands.ts
import { SlashCommandBuilder } from '@discordjs/builders';
import { REST } from '@discordjs/rest';
import { Routes } from 'discord-api-types/v9';
import 'dotenv/config';
import Environment from './util/Environment';
const env = new Environment(process.env);
const commands = [
new SlashCommandBuilder()
.setName('fight')
.setDescription('Replies with upcoming fight card'),
new SlashCommandBuilder()
.setName('fights')
.setDescription('Replies with links to upcoming fights'),
].map((command) => command.toJSON());
const rest = new REST({ version: '9' }).setToken(env.DISCORD_TOKEN);
(async () => {
try {
const appCmds = Routes.applicationCommands(env.CLIENT_ID);
await rest.put(appCmds, {
body: commands,
});
const appGuildCmds = Routes.applicationGuildCommands(env.CLIENT_ID, env.GUILD_ID);
await rest.put(appGuildCmds, {
body: commands,
});
console.log('Successfully registered application commands.');
} catch (error) {
console.error(error);
}
})();
|
stankaholic/fight-bot
|
src/app.ts
|
import * as Discord from 'discord.js';
import 'dotenv/config';
import InteractionHandler from './discord/InteractionHandler';
import LoggerFactor from './services/Logging/LoggerFactory';
import UfcService from './services/UfcService';
import Environment from './util/Environment';
const env = new Environment(process.env);
const logger = LoggerFactor.createLogger(env);
const dataService = new UfcService(logger);
const interactionHandler = new InteractionHandler(logger, dataService);
const intents = [Discord.Intents.FLAGS.GUILDS];
const client = new Discord.Client({ intents });
client.once('ready', () => {
logger.info('Ready to accept commands');
});
client.on('interactionCreate', interactionHandler.handleInteraction);
client.login(env.DISCORD_TOKEN);
|
stankaholic/fight-bot
|
src/discord/InteractionHandler.ts
|
import { CommandInteraction, Interaction, MessageEmbed } from 'discord.js';
import { Event, parseEvent, parseEvents } from '../services/FightParser';
import Logger from '../services/Logging/Logger';
import UfcService from '../services/UfcService';
export default class InteractionHandler {
private readonly prefix: string;
private readonly logger: Logger;
private readonly dataService: UfcService;
public constructor(logger: Logger, dataService: UfcService) {
this.logger = logger;
this.dataService = dataService;
this.buildFightEmbed = this.buildFightEmbed.bind(this);
this.handleCommand = this.handleCommand.bind(this);
this.getFightLinks = this.getFightLinks.bind(this);
this.handleFight = this.handleFight.bind(this);
this.handleFights = this.handleFights.bind(this);
this.handleInteraction = this.handleInteraction.bind(this);
}
private buildFightEmbed(event: Event, url: string): MessageEmbed {
const embed = new MessageEmbed();
embed.setTitle(event.title);
embed.setURL(url);
embed.setDescription(`${event.subtitle}\n${event.date}`);
embed.setThumbnail(event.imgUrl);
event.fights.forEach((fight) => {
embed.addField(
fight.weightClass || 'Unknown',
`${fight.redCorner.rank} ${fight.redCorner.name}\nvs.\n${fight.blueCorner.rank} ${fight.blueCorner.name}`,
true
);
});
return embed;
}
private async handleCommand(
interaction: CommandInteraction,
command: string
): Promise<void> {
this.logger.info(`Processing command - ${command}`);
switch (command) {
case 'fight':
this.handleFight(interaction);
break;
case 'fights':
this.handleFights(interaction);
break;
default:
this.logger.info(`Command not supported - ${command}`);
break;
}
}
private async getFightLinks(): Promise<string[]> {
try {
const eventHtml = await this.dataService.fetchEvents();
const links = parseEvents(eventHtml);
return links;
} catch (error) {
this.logger.error(
`Failed retrieving events from UFC website - ${error.message}`
);
return [];
}
}
private async handleFights(interaction: CommandInteraction): Promise<void> {
const links = await this.getFightLinks();
interaction.reply(links.join('\n'));
}
private async handleFight(interaction: CommandInteraction): Promise<void> {
const links = await this.getFightLinks();
if (links.length === 0) {
interaction.channel.send('Failed retriving event information from UFC');
return;
}
const [link] = links;
const eventHtml = await this.dataService.fetchData<string>(link);
const event: Event = parseEvent(eventHtml);
await interaction.reply({ embeds: [this.buildFightEmbed(event, link)] });
}
public handleInteraction(interaction: Interaction): void {
if (!interaction.isCommand()) {
return;
}
const { commandName } = interaction;
this.handleCommand(interaction, commandName);
}
}
|
stankaholic/fight-bot
|
src/util/Environment.ts
|
export default class Environment {
public readonly DISCORD_TOKEN: string;
public readonly PAPERTRAIL_API_TOKEN: string;
public readonly NODE_ENV: string;
public readonly LOGGING_LEVEL: string;
public readonly CLIENT_ID: string;
public readonly GUILD_ID: string;
public constructor(env: NodeJS.ProcessEnv) {
this.DISCORD_TOKEN = env.DISCORD_TOKEN || '';
this.PAPERTRAIL_API_TOKEN = env.PAPERTRAIL_API_TOKEN || '';
this.NODE_ENV = env.NODE_ENV || 'development';
this.LOGGING_LEVEL = env.LOGGING_LEVEL || 'info';
this.CLIENT_ID = env.CLIENT_ID || '';
this.GUILD_ID = env.GUILD_ID || '';
}
}
|
stankaholic/fight-bot
|
src/services/Logging/Logger.ts
|
import * as Winston from 'winston';
export default class Logger {
private readonly logger: Winston.Logger;
public constructor(logger: Winston.Logger) {
this.logger = logger;
this.info = this.info.bind(this);
this.warn = this.warn.bind(this);
this.error = this.error.bind(this);
this.debug = this.debug.bind(this);
this.http = this.http.bind(this);
this.verbose = this.verbose.bind(this);
this.silly = this.silly.bind(this);
}
public info(message: string): void {
this.logger.info(message);
}
public warn(message: string): void {
this.logger.warn(message);
}
public error(message: string): void {
this.logger.error(message);
}
public debug(message: string): void {
this.logger.debug(message);
}
public http(message: string): void {
this.logger.http(message);
}
public verbose(message: string): void {
this.logger.verbose(message);
}
public silly(message: string): void {
this.logger.silly(message);
}
}
|
stankaholic/fight-bot
|
src/services/UfcService.ts
|
import axios from 'axios';
import Logger from './Logging/Logger';
export default class UfcService {
private readonly logger: Logger;
private static readonly EVENTS_URL = 'https://www.ufc.com/events';
public constructor(logger: Logger) {
this.logger = logger;
this.fetchData = this.fetchData.bind(this);
this.fetchEvents = this.fetchEvents.bind(this);
}
public async fetchData<T>(url: string): Promise<T> {
try {
const res = await axios.get(url);
const data: T = res.data;
return data;
} catch (error) {
this.logger.error(error.message);
return undefined;
}
}
public async fetchEvents(): Promise<string> {
return this.fetchData<string>(UfcService.EVENTS_URL);
}
}
|
stankaholic/fight-bot
|
src/services/FightParser.ts
|
<reponame>stankaholic/fight-bot
import * as Cheerio from 'cheerio';
const baseUrl = 'https://www.ufc.com';
const titleClass = '.c-hero__headline-prefix';
const subtitleClass = '.c-hero__headline.is-large-text';
const dateClass = '.c-hero__headline-suffix';
const weightClass = '.c-listing-fight__class';
const fighterClass = '.c-listing-fight__corner-name';
const rankClass = '.c-listing-fight__corner-rank';
const imgClass = '.c-hero__image';
export interface FightCorner {
name: string;
rank: string;
}
export interface Fight {
redCorner: FightCorner;
blueCorner: FightCorner;
weightClass: string;
}
export interface Event {
title: string;
subtitle: string;
date: string;
imgUrl: string;
fights: Fight[];
}
export const parseEvents = (html: string): string[] => {
const $ = Cheerio.load(html);
const links: string[] = [];
$('.c-card-event--result__headline').map((_index, $el) => {
const child: Cheerio.Element = $el.firstChild as Cheerio.Element;
const link = `${baseUrl}${child.attribs['href']}`;
links.push(link);
});
return links;
};
const parseImage = ($: Cheerio.CheerioAPI): string => {
const style = $(imgClass).parent().attr('style');
const urlStart = style.indexOf('url(');
if (urlStart === -1) {
return '';
}
const imgUrl = style.substring(urlStart + 4);
const rightParen = imgUrl.indexOf(')');
if (rightParen === -1) {
return '';
}
return imgUrl.substring(0, rightParen);
};
export const parseEvent = (html: string): Event => {
const $ = Cheerio.load(html);
const fighters: string[] = $(fighterClass)
.map((_, el) => $(el).text().trim().replace(/\n/g, ''))
.get();
const ranks: string[] = $(rankClass)
.map((_, el) => $(el).text().trim().replace(/\n/g, ''))
.get();
const weightClasses: string[] = $(weightClass)
.map((_, el) => $(el).text().trim().replace(/\n/g, ''))
.get();
let i = 0;
const fights: Fight[] = weightClasses.map((weightClass) => {
const fight: Fight = {
weightClass,
redCorner: {
name: fighters[i],
rank: ranks[i],
},
blueCorner: {
name: fighters[i + 1],
rank: ranks[i + 1],
},
};
i += 2;
return fight;
});
const title = $(titleClass).text().trim().replace(/\n/g, '');
const subtitle = $(subtitleClass).text().trim().replace(/\n/g, '');
const date = $(dateClass).text().trim();
const imgUrl = parseImage($);
return {
title,
subtitle,
date,
fights,
imgUrl,
};
};
|
stankaholic/fight-bot
|
src/services/Logging/LoggerFactory.ts
|
<filename>src/services/Logging/LoggerFactory.ts
import * as Winston from 'winston';
import Environment from '../../util/Environment';
import Logger from './Logger';
export default class LoggerFactor {
public static createLogger(env: Environment): Logger {
const logger = Winston.createLogger({
level: env.LOGGING_LEVEL,
exitOnError: false,
transports: [
new Winston.transports.Console({
format: Winston.format.simple(),
}),
],
});
return new Logger(logger);
}
}
|
piglovesyou/react-apollo-loader-example
|
src/data/graphql/Scalar/Timestamp/index.ts
|
<filename>src/data/graphql/Scalar/Timestamp/index.ts
import { GraphQLScalarType } from 'graphql';
import { Kind } from 'graphql/language';
export const schema = [
`
# GraphQL cannot handle long - normal timestamp will go failed.
# In that case, use Timestamp.
scalar Timestamp
`,
];
export const resolvers = {
Timestamp: new GraphQLScalarType({
name: 'Timestamp',
description: 'Timestamp custom scalar type',
parseValue(value) {
return value;
},
serialize(value) {
return value;
},
parseLiteral(ast) {
if (ast.kind === Kind.INT) {
return ast.value;
}
return null;
},
}),
};
|
piglovesyou/react-apollo-loader-example
|
src/data/graphql/Database/schema.ts
|
import merge from 'lodash.merge';
/** * Queries ** */
import {
schema as GetAllUsers,
queries as GetAllUsersQueries,
resolvers as GetAllUsersResolver,
} from './users/GetAllUsers';
import {
queries as GetLoggedInUserQueries,
resolvers as GetLoggedInUserResolver,
} from './users/GetLoggedInUser';
/** * Mutations ** */
import {
schema as CreateUserInput,
mutation as CreateUser,
resolvers as CreateUserResolver,
} from './users/CreateUser';
export const schema = [...GetAllUsers, ...CreateUserInput];
export const queries = [...GetAllUsersQueries, ...GetLoggedInUserQueries];
export const mutations = [...CreateUser];
export const resolvers = merge(
GetAllUsersResolver,
GetLoggedInUserResolver,
CreateUserResolver,
);
|
piglovesyou/react-apollo-loader-example
|
src/data/models/User.ts
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import DataType, { Model } from 'sequelize';
import sequelize from '../sequelize';
class User extends Model {
public id!: string;
public email!: string;
public emailConfirmed!: boolean;
public readonly createdAt!: Date;
public readonly updatedAt!: Date;
}
User.init(
{
id: {
type: DataType.UUID,
defaultValue: DataType.UUIDV1,
primaryKey: true,
},
email: {
type: DataType.STRING(255),
validate: { isEmail: true },
},
emailConfirmed: {
type: DataType.BOOLEAN,
defaultValue: false,
},
},
{
sequelize,
indexes: [{ fields: ['email'] }],
},
);
export default User;
|
piglovesyou/react-apollo-loader-example
|
src/components/Layout/Layout.test.tsx
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/* eslint-env jest */
/* eslint-disable padded-blocks, no-unused-expressions */
import React from 'react';
import renderer from 'react-test-renderer';
import createApolloClient from '../../core/createApolloClient/createApolloClient.server';
import App from '../App';
import Layout from './Layout';
describe('Layout', () => {
test('renders children correctly', () => {
const client = createApolloClient({} as any, {} as any);
const wrapper = renderer
.create(
<App
context={{
pathname: '',
query: {},
}}
insertCss={() => {}}
client={client}
>
<Layout>
<div className="child" />
</Layout>
</App>,
)
.toJSON();
expect(wrapper).toMatchSnapshot();
});
});
|
piglovesyou/react-apollo-loader-example
|
src/data/models/index.ts
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import sequelize from '../sequelize';
import User from './User';
import UserLogin from './UserLogin';
import UserClaim from './UserClaim';
import UserProfile from './UserProfile';
User.hasMany(UserLogin, {
foreignKey: 'userId',
as: 'logins',
onUpdate: 'cascade',
onDelete: 'cascade',
});
User.hasMany(UserClaim, {
foreignKey: 'userId',
as: 'claims',
onUpdate: 'cascade',
onDelete: 'cascade',
});
User.hasOne(UserProfile, {
foreignKey: 'userId',
as: 'profile',
onUpdate: 'cascade',
onDelete: 'cascade',
});
function sync(...args: any) {
return sequelize.sync(...args);
}
export default { sync };
export { User, UserLogin, UserClaim, UserProfile };
|
piglovesyou/react-apollo-loader-example
|
src/history.ts
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import { createBrowserHistory, History } from 'history';
const history = process.env.BROWSER && createBrowserHistory();
// Navigation manager, e.g. history.push('/home')
// https://github.com/mjackson/history
export default history as NonNullable<History>;
|
piglovesyou/react-apollo-loader-example
|
src/data/graphql/Database/users/CreateUser.ts
|
import { User, UserProfile } from '../../../models';
export const schema = [
`
# User profile data for creating a new local database user account
input UserProfile {
# A display name for the logged-in user
displayName: String!
# A profile picture URL
picture: String
# The user's gender
gender: String
# The user's location
location: String
# A website URL
website: String
}
`,
];
export const mutation = [
`
# Creates a new user and profile in the local database
databaseCreateUser(
# The email of the new user, this email must be unique in the database
email: String!
# User profile information for creating a new local database user account
profile: UserProfile!
): DatabaseUser
`,
];
export const resolvers = {
Mutation: {
async databaseCreateUser(parent: any, args: any) {
// If user already exists, throw error
const lookupUser = await User.findOne({ where: { email: args.email } });
if (lookupUser) {
// eslint-disable-next-line no-throw-literal
throw 'User already exists!';
}
// Create new user with profile in database
const user = await User.create(
{
email: args.email,
profile: {
...args.profile,
},
},
{
include: [{ model: UserProfile, as: 'profile' }],
},
);
return user;
},
},
};
|
piglovesyou/react-apollo-loader-example
|
src/components/Footer/Footer.tsx
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { FunctionComponent } from 'react';
import useStyles from 'isomorphic-style-loader/useStyles';
import s from './Footer.css';
import Link from '../Link';
const Footer: FunctionComponent = () => {
useStyles(s);
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Your Company</span>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/">
Home
</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/admin">
Admin
</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/privacy">
Privacy
</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/not-found">
Not Found
</Link>
</div>
</div>
);
};
export default Footer;
|
piglovesyou/react-apollo-loader-example
|
src/routes/register/Register.tsx
|
<gh_stars>0
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import useStyles from 'isomorphic-style-loader/useStyles';
import s from './Register.css';
type PropTypes = {
title: string;
};
const Register = (props: PropTypes) => {
useStyles(s);
return (
<div className={s.root}>
<div className={s.container}>
<h1>{props.title}</h1>
<p>...</p>
</div>
</div>
);
};
export default Register;
|
piglovesyou/react-apollo-loader-example
|
src/routes/error/ErrorPage.tsx
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/withStyles';
import s from './ErrorPage.css';
type PropTypes = {
error?: {
name: string;
message: string;
stack: string;
};
};
const ErrorPage = ({ error }: PropTypes) => {
if (__DEV__ && error) {
return (
<div>
<h1>{error.name}</h1>
<pre>{error.stack}</pre>
</div>
);
}
return (
<div>
<h1>Error</h1>
<p>Sorry, a critical error occurred on this page.</p>
</div>
);
};
export { ErrorPage as ErrorPageWithoutStyle };
export default withStyles(s)(ErrorPage);
|
piglovesyou/react-apollo-loader-example
|
src/data/graphql/OnMemoryState/networkStatus.ts
|
export const defaults = {
networkStatus: {
__typename: 'NetworkStatus',
isConnected: true,
},
};
export const resolvers = {
Mutation: {
updateNetworkStatus: (_: any, { isConnected }: any, { cache }: any) => {
const data = {
networkStatus: {
__typename: 'NetworkStatus',
isConnected,
},
};
cache.writeData({ data });
return null;
},
},
};
export const schema = [
`
type NetworkStatus {
isConnected: Boolean!
}
`,
];
export const queries = [
`
networkStatus: NetworkStatus!
`,
];
export const mutations = [
`
updateNetworkStatus(isConnected: Boolean): NetworkStatus!
`,
];
|
piglovesyou/react-apollo-loader-example
|
src/data/graphql/OnMemoryState/schema.ts
|
import merge from 'lodash.merge';
import {
resolvers as networkStatusResolvers,
defaults as networkStatusDefaults,
schema as networkStatusSchema,
queries as networkStatusQuery,
mutations as networkStatusMutation,
} from './networkStatus';
import { schema as userSchema, queries as userQueries } from './user';
// Used by both GraphQL Server and Apollo Client
export const schema = [...userSchema, ...networkStatusSchema];
// Below are only used by Apollo Client
export const defaults = merge(networkStatusDefaults);
export const resolvers = merge(networkStatusResolvers);
// Below are used by GraphQL Server for Introspection
// that generates Flow types by apollo:codegen.
export const queries = [...networkStatusQuery, ...userQueries];
export const mutations = [...networkStatusMutation];
|
piglovesyou/react-apollo-loader-example
|
src/routes/home/Home.tsx
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import useStyles from 'isomorphic-style-loader/useStyles';
import s from './Home.css';
import { useHomeNewsQuery } from './news.graphql';
type Props = {};
const Home = (_: Props) => {
const { data, loading } = useHomeNewsQuery();
useStyles(s);
return (
<div className={s.root}>
<div className={s.container}>
<p className={s.networkStatusMessage}>
{data && data.networkStatus.isConnected ? 'Online' : 'Offline'}
</p>
<h1>React.js News</h1>
{loading || !data || !data.reactjsGetAllNews
? 'Loading...'
: data.reactjsGetAllNews.map(item => (
<article key={item.link} className={s.newsItem}>
<h1 className={s.newsTitle}>
<a href={item.link}>{item.title}</a>
</h1>
<div
className={s.newsDesc}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: item.content }}
/>
</article>
))}
</div>
</div>
);
};
export default Home;
|
piglovesyou/react-apollo-loader-example
|
src/data/graphql/News/schema.ts
|
import merge from 'lodash.merge';
/** * Queries ** */
import {
schema as GetAllReactJSNews,
queries as GetAllReactJSNewsQueries,
resolvers as GetAllReactJSNewsResolver,
} from './reactjsnews.com/GetAllReactJSNews';
export const schema = [...GetAllReactJSNews];
export const queries = [...GetAllReactJSNewsQueries];
export const resolvers = merge(GetAllReactJSNewsResolver);
|
piglovesyou/react-apollo-loader-example
|
src/data/models/UserProfile.ts
|
<filename>src/data/models/UserProfile.ts
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import DataType, { Model } from 'sequelize';
import sequelize from '../sequelize';
class UserProfile extends Model {
public userId!: string;
public displayName!: string;
public picture!: string;
public gender!: string;
public location!: string;
public website!: string;
}
UserProfile.init(
{
userId: {
type: DataType.UUID,
primaryKey: true,
},
displayName: {
type: DataType.STRING(100),
},
picture: {
type: DataType.STRING(255),
},
gender: {
type: DataType.STRING(50),
},
location: {
type: DataType.STRING(100),
},
website: {
type: DataType.STRING(255),
},
},
{ sequelize },
);
export default UserProfile;
|
piglovesyou/react-apollo-loader-example
|
src/data/graphql/Scalar/schema.ts
|
import merge from 'lodash.merge';
import {
schema as TimestampSchema,
resolvers as TimestampResolvers,
} from './Timestamp';
export const schema = [...TimestampSchema];
export const resolvers = merge(TimestampResolvers);
|
piglovesyou/react-apollo-loader-example
|
src/data/sequelize.ts
|
<filename>src/data/sequelize.ts
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import { Sequelize } from 'sequelize';
import config from '../config';
const sequelize = new Sequelize(config.databaseUrl, {
define: {
freezeTableName: true,
},
});
export default sequelize;
|
piglovesyou/react-apollo-loader-example
|
src/data/graphql/Database/users/GetLoggedInUser.ts
|
<gh_stars>0
import { User, UserClaim, UserLogin, UserProfile } from '../../../models';
export const queries = [
`
# Retrieves information about the currently logged-in user
databaseGetLoggedInUser: DatabaseUser
`,
];
export const resolvers = {
RootQuery: {
async databaseGetLoggedInUser(parent: any, args: any, { req }: any) {
// Throw error if user is not authenticated
if (!req.user) {
return null;
}
// Find logged in user from database
const dbUser = await User.findOne({
where: { email: req.user.email },
include: [
{ model: UserLogin, as: 'logins' },
{ model: UserClaim, as: 'claims' },
{ model: UserProfile, as: 'profile' },
],
});
return dbUser;
},
},
};
|
piglovesyou/react-apollo-loader-example
|
tools/lib/test-fns.ts
|
<filename>tools/lib/test-fns.ts
import { ExecaChildProcess } from 'execa';
import terminate from 'terminate';
import i from 'log-symbols';
import waitOn from 'wait-on';
import puppeteer, { Browser, Page } from 'puppeteer';
export function success(...args: string[]) {
return console.info(i.success, ...args);
}
export function info(...args: string[]) {
return console.info(i.info, ...args);
}
export function getUrl(port: number) {
return `http://localhost:${port}`;
}
export async function waitApp(port: number) {
const url = getUrl(port);
await waitOn({
resources: [url],
timeout: 60 * 1000,
});
}
export async function killApp(app: ExecaChildProcess) {
info(`Terminating app ${app.pid}...`);
await new Promise((resolve, reject) => {
terminate(app.pid, (err: any) => {
if (err) return reject(err);
return resolve();
});
});
success(`App ${app.pid} was terminated`);
}
export function timeout(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
export async function openBrowser(port: number): Promise<[Browser, Page]> {
const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('pageerror', err => {
throw new Error(`The page got an error: ${err}`);
});
const url = getUrl(port);
await page.goto(url);
return [browser, page];
}
|
piglovesyou/react-apollo-loader-example
|
src/components/Page/Page.tsx
|
<filename>src/components/Page/Page.tsx
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import useStyles from 'isomorphic-style-loader/useStyles';
import s from './Page.css';
interface PropTypes {
title: string;
html: string;
}
const Page = ({ title, html }: PropTypes) => {
useStyles(s);
return (
<div className={s.root}>
<div className={s.container}>
<h1>{title}</h1>
<div
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
</div>
);
};
export default Page;
|
piglovesyou/react-apollo-loader-example
|
tools/lib/cp.ts
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import cp, { ExecOptions } from 'child_process';
import execa, { Options } from 'execa';
export const spawn = (command: string, args: string[], options: Options) =>
execa(command, args, {
stdio: ['ignore', 'inherit', 'inherit'],
...options,
});
export const exec = (command: string, options: ExecOptions) =>
new Promise((resolve, reject) => {
cp.exec(command, options, (err, stdout, stderr) => {
if (err) {
reject(err);
return;
}
resolve({ stdout, stderr });
});
});
export default { spawn, exec };
|
piglovesyou/react-apollo-loader-example
|
src/data/models/UserClaim.ts
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import DataType, { Model } from 'sequelize';
import sequelize from '../sequelize';
class UserClaim extends Model {
public type!: string;
public value!: string;
}
UserClaim.init(
{
type: {
type: DataType.STRING,
},
value: {
type: DataType.STRING,
},
},
{
sequelize,
},
);
export default UserClaim;
|
piglovesyou/react-apollo-loader-example
|
src/data/schema.ts
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import { DocumentNode } from 'graphql';
import merge from 'lodash.merge';
import {
schema as NewsSchema,
resolvers as NewsResolvers,
queries as NewsQueries,
} from './graphql/News/schema';
import {
schema as DatabaseSchema,
resolvers as DatabaseResolvers,
mutations as DatabaseMutations,
queries as DatabaseQueries,
} from './graphql/Database/schema';
import {
schema as TimestampSchema,
resolvers as TimestampResolvers,
} from './graphql/Scalar/Timestamp';
import {
schema as OnMemoryStateSchema,
queries as OnMemoryStateQueries,
mutations as OnMemoryStateMutations,
} from './graphql/OnMemoryState/schema';
const RootQuery = [
`
# # React-Starter-Kit Querying API
# ### This GraphQL schema was built with [Apollo GraphQL-Tools](https://github.com/apollographql/graphql-tools)
# _Build, mock, and stitch a GraphQL schema using the schema language_
#
# **[Schema Language Cheet Sheet](https://raw.githubusercontent.com/sogko/graphql-shorthand-notation-cheat-sheet/master/graphql-shorthand-notation-cheat-sheet.png)**
#
# 1. Use the GraphQL schema language to [generate a schema](https://www.apollographql.com/docs/graphql-tools/generate-schema.html) with full support for resolvers, interfaces, unions, and custom scalars. The schema produced is completely compatible with [GraphQL.js](https://github.com/graphql/graphql-js).
# 2. [Mock your GraphQL API](https://www.apollographql.com/docs/graphql-tools/mocking.html) with fine-grained per-type mocking
# 3. Automatically [stitch multiple schemas together](https://www.apollographql.com/docs/graphql-tools/schema-stitching.html) into one larger API
type RootQuery {
${NewsQueries}
${DatabaseQueries}
${OnMemoryStateQueries}
}
`,
];
const Mutation = [
`
# # React-Starter-Kit Mutating API
# ### This GraphQL schema was built with [Apollo GraphQL-Tools](https://github.com/apollographql/graphql-tools)
# _Build, mock, and stitch a GraphQL schema using the schema language_
#
# **[Schema Language Cheet Sheet](https://raw.githubusercontent.com/sogko/graphql-shorthand-notation-cheat-sheet/master/graphql-shorthand-notation-cheat-sheet.png)**
#
# 1. Use the GraphQL schema language to [generate a schema](https://www.apollographql.com/docs/graphql-tools/generate-schema.html) with full support for resolvers, interfaces, unions, and custom scalars. The schema produced is completely compatible with [GraphQL.js](https://github.com/graphql/graphql-js).
# 2. [Mock your GraphQL API](https://www.apollographql.com/docs/graphql-tools/mocking.html) with fine-grained per-type mocking
# 3. Automatically [stitch multiple schemas together](https://www.apollographql.com/docs/graphql-tools/schema-stitching.html) into one larger API
type Mutation {
${DatabaseMutations}
${OnMemoryStateMutations}
}
`,
];
const SchemaDefinition = [
`
schema {
query: RootQuery
mutation: Mutation
}
`,
];
// Merge all of the resolver objects together
// Put schema together into one array of schema strings
const resolvers = merge(NewsResolvers, DatabaseResolvers, TimestampResolvers);
const schema = [
...SchemaDefinition,
...TimestampSchema,
...RootQuery,
...Mutation,
...NewsSchema,
...DatabaseSchema,
...OnMemoryStateSchema,
];
export default {
typeDefs: (schema as any) as DocumentNode[],
resolvers,
// ...(__DEV__ ? { log: e => console.error(e.stack) } : {}),
};
|
piglovesyou/react-apollo-loader-example
|
tools/lib/overrideRules.ts
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
function overrideRules(rules: any, patch: any) {
return rules.map((ruleToPatch: any) => {
let rule = patch(ruleToPatch);
if (rule.rules) {
rule = { ...rule, rules: overrideRules(rule.rules, patch) };
}
if (rule.oneOf) {
rule = { ...rule, oneOf: overrideRules(rule.oneOf, patch) };
}
return rule;
});
}
export default overrideRules;
|
piglovesyou/react-apollo-loader-example
|
src/components/Layout/Layout.tsx
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { FunctionComponent } from 'react';
import useStyles from 'isomorphic-style-loader/useStyles';
// external-global styles must be imported in your JS.
import normalizeCss from 'normalize.css';
import s from './Layout.css';
import Header from '../Header';
import Feedback from '../Feedback';
import Footer from '../Footer';
interface PropTypes {}
const Layout: FunctionComponent<PropTypes> = ({ children }) => {
useStyles(normalizeCss, s);
return (
<div>
<Header />
{children}
<Feedback />
<Footer />
</div>
);
};
export default Layout;
|
piglovesyou/react-apollo-loader-example
|
src/data/graphql/News/reactjsnews.com/GetAllReactJSNews.ts
|
import fetch from 'node-fetch';
import { ReactJsNewsItem } from '../../../../__generated__/dataBinders';
export const schema = [
`
# A single news article from [https://reactjsnews.com/](https://reactjsnews.com/)
type ReactJSNewsItem {
# The news item's title
title: String!
# A direct link URL to this news item on reactjsnews.com
link: String!
# The name of the news item's author
author: String!
# The date this news item was published
pubDate: String!
# News article in HTML format
content: String!
}
`,
];
export const queries = [
`
# Retrieves the latest ReactJS News
reactjsGetAllNews: [ReactJSNewsItem!]!
`,
];
// React.js News Feed (RSS)
const url =
'https://api.rss2json.com/v1/api.json' +
'?rss_url=https%3A%2F%2Freactjsnews.com%2Ffeed.xml';
let items: ReactJsNewsItem[] = [];
let lastFetchTask: Promise<ReactJsNewsItem[]> | null;
let lastFetchTime = Number(new Date(1970, 0, 1));
export const resolvers = {
RootQuery: {
reactjsGetAllNews() {
if (lastFetchTask) {
return lastFetchTask;
}
if (Date.now() - lastFetchTime > 1000 * 60 * 10 /* 10 mins */) {
lastFetchTime = Date.now();
lastFetchTask = fetch(url)
.then(response => response.json())
.then(data => {
if (data.status === 'ok') {
items = data.items;
}
lastFetchTask = null;
return items;
})
.catch(err => {
lastFetchTask = null;
throw err;
});
if (items.length) {
return items;
}
return lastFetchTask;
}
return items;
},
},
};
|
piglovesyou/react-apollo-loader-example
|
src/routes/index.tsx
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
/* eslint-disable global-require */
// The top-level (parent) route
import { Route } from 'universal-router';
const routes: Route = {
path: '',
// Keep in mind, routes are evaluated in order
children: [
{
path: '',
load: () => import(/* webpackChunkName: 'home' */ './home'),
},
{
path: '/contact',
load: () => import(/* webpackChunkName: 'contact' */ './contact'),
},
{
path: '/login',
load: () => import(/* webpackChunkName: 'login' */ './login'),
},
{
path: '/register',
load: () => import(/* webpackChunkName: 'register' */ './register'),
},
{
path: '/about',
load: () => import(/* webpackChunkName: 'about' */ './about'),
},
{
path: '/privacy',
load: () => import(/* webpackChunkName: 'privacy' */ './privacy'),
},
{
path: '/admin',
load: () => import(/* webpackChunkName: 'admin' */ './admin'),
},
// Wildcard routes, e.g. { path: '(.*)', ... } (must go last)
{
path: '(.*)',
load: () => import(/* webpackChunkName: 'not-found' */ './not-found'),
},
],
async action({ next }: any) {
// Execute each child route until one of them return the result
const route = await next();
// Provide default values for title, description etc.
route.title = `${route.title || 'Untitled Page'} - www.reactstarterkit.com`;
route.description = route.description || '';
return route;
},
};
// The error page is available by permanent url for development mode
if (__DEV__) {
routes.children!.unshift({
path: '/error',
action: require('./error').default,
});
}
export default routes;
|
piglovesyou/react-apollo-loader-example
|
src/data/graphql/OnMemoryState/user.ts
|
<filename>src/data/graphql/OnMemoryState/user.ts
export const schema = [
`
type User {
id: String!
}
`,
];
export const queries = [
`
user: User
`,
];
|
piglovesyou/react-apollo-loader-example
|
src/routes/login/Login.tsx
|
<reponame>piglovesyou/react-apollo-loader-example
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import useStyles from 'isomorphic-style-loader/useStyles';
import s from './Login.css';
type PropTypes = {
title: string;
};
const Login = (props: PropTypes) => {
useStyles(s);
return (
<div className={s.root}>
<div className={s.container}>
<h1>{props.title}</h1>
<p className={s.lead}>
Log in with your username or company email address.
</p>
<div className={s.formGroup}>
<a className={s.facebook} href="/login/facebook">
<svg
className={s.icon}
width="30"
height="30"
viewBox="0 0 30 30"
xmlns="http://www.w3.org/2000/svg"
>
<path d="M22 16l1-5h-5V7c0-1.544.784-2 3-2h2V0h-4c-4.072 0-7 2.435-7 7v4H7v5h5v14h6V16h4z" />
</svg>
<span>Log in with Facebook</span>
</a>
</div>
<div className={s.formGroup}>
<a className={s.google} href="/login/google">
<svg
className={s.icon}
width="30"
height="30"
viewBox="0 0 30 30"
xmlns="http://www.w3.org/2000/svg"
>
<path
d={
'M30 13h-4V9h-2v4h-4v2h4v4h2v-4h4m-15 2s-2-1.15-2-2c0 0-.5-1.828 1-3 ' +
'1.537-1.2 3-3.035 3-5 0-2.336-1.046-5-3-6h3l2.387-1H10C5.835 0 2 3.345 2 7c0 ' +
'3.735 2.85 6.56 7.086 6.56.295 0 .58-.006.86-.025-.273.526-.47 1.12-.47 1.735 ' +
'0 1.037.817 2.042 1.523 2.73H9c-5.16 0-9 2.593-9 6 0 3.355 4.87 6 10.03 6 5.882 ' +
'0 9.97-3 9.97-7 0-2.69-2.545-4.264-5-6zm-4-4c-2.395 0-5.587-2.857-6-6C4.587 ' +
'3.856 6.607.93 9 1c2.394.07 4.603 2.908 5.017 6.052C14.43 10.195 13 13 11 ' +
'13zm-1 15c-3.566 0-7-1.29-7-4 0-2.658 3.434-5.038 7-5 .832.01 2 0 2 0 1 0 ' +
'2.88.88 4 2 1 1 1 2.674 1 3 0 3-1.986 4-7 4z'
}
/>
</svg>
<span>Log in with Google</span>
</a>
</div>
<div className={s.formGroup}>
<a className={s.twitter} href="/login/twitter">
<svg
className={s.icon}
width="30"
height="30"
viewBox="0 0 30 30"
xmlns="http://www.w3.org/2000/svg"
>
<path
d={
'M30 6.708c-1.105.49-2.756 1.143-4 1.292 1.273-.762 2.54-2.56 ' +
'3-4-.97.577-2.087 1.355-3.227 1.773L25 5c-1.12-1.197-2.23-2-4-2-3.398 0-6 ' +
'2.602-6 6 0 .4.047.7.11.956L15 10C9 10 5.034 8.724 2 5c-.53.908-1 1.872-1 ' +
'3 0 2.136 1.348 3.894 3 5-1.01-.033-2.17-.542-3-1 0 2.98 4.186 6.432 7 7-1 ' +
'1-4.623.074-5 0 .784 2.447 3.31 3.95 6 4-2.105 1.648-4.647 2.51-7.53 2.51-.5 ' +
'0-.988-.03-1.47-.084C2.723 27.17 6.523 28 10 28c11.322 0 17-8.867 17-17 ' +
'0-.268.008-.736 0-1 1.2-.868 2.172-2.058 3-3.292z'
}
/>
</svg>
<span>Log in with Twitter</span>
</a>
</div>
<strong className={s.lineThrough}>OR</strong>
<form method="post">
<div className={s.formGroup}>
<label className={s.label} htmlFor="usernameOrEmail">
Username or email address:
<input
className={s.input}
id="usernameOrEmail"
type="text"
name="usernameOrEmail"
autoFocus // eslint-disable-line jsx-a11y/no-autofocus
/>
</label>
</div>
<div className={s.formGroup}>
<label className={s.label} htmlFor="password">
Password:
<input
className={s.input}
id="password"
type="password"
name="password"
/>
</label>
</div>
<div className={s.formGroup}>
<button className={s.button} type="submit">
Log in
</button>
</div>
</form>
</div>
</div>
);
};
export default Login;
|
piglovesyou/react-apollo-loader-example
|
src/router.ts
|
<reponame>piglovesyou/react-apollo-loader-example
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import UniversalRouter from 'universal-router';
import routes from './routes';
export default new UniversalRouter(routes, {
resolveRoute(context, params) {
if (typeof context.route.load === 'function') {
return context.route
.load()
.then((action: any) => action.default(context, params))
.then((route: any) => ({ ...route, params }));
}
if (typeof context.route.action === 'function') {
return context.route.action(context, params);
}
return undefined;
},
});
|
piglovesyou/react-apollo-loader-example
|
src/components/Html.tsx
|
<reponame>piglovesyou/react-apollo-loader-example
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import serialize from 'serialize-javascript';
import config from '../config';
/* eslint-disable react/no-danger */
interface PropTypes {
title: string;
description: string;
styles?: Array<{
id: string;
cssText: string;
}>;
scripts?: string[];
app: any;
children: string;
}
const Html = ({
title,
description,
styles = [],
scripts = [],
app,
children,
}: PropTypes) => (
<html className="no-js" lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<title>{title}</title>
<meta name="description" content={description} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
{scripts.map(script => (
<link key={script} rel="preload" href={script} as="script" />
))}
<link rel="manifest" href="/site.webmanifest" />
<link rel="apple-touch-icon" href="/icon.png" />
{styles.map(style => (
<style
key={style.id}
id={style.id}
dangerouslySetInnerHTML={{ __html: style.cssText }}
/>
))}
</head>
<body>
<div id="app" dangerouslySetInnerHTML={{ __html: children }} />
<script
dangerouslySetInnerHTML={{ __html: `window.App=${serialize(app)}` }}
/>
{scripts.map(script => (
<script key={script} src={script} />
))}
{config.analytics.googleTrackingId && (
<script
dangerouslySetInnerHTML={{
__html:
'window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;' +
`ga('create','${config.analytics.googleTrackingId}','auto');ga('send','pageview')`,
}}
/>
)}
{config.analytics.googleTrackingId && (
<script
src="https://www.google-analytics.com/analytics.js"
async
defer
/>
)}
</body>
</html>
);
export default Html;
|
piglovesyou/react-apollo-loader-example
|
src/components/Link/Link.tsx
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { ReactNode } from 'react';
import history from '../../history';
function isLeftClickEvent(event: MouseEvent) {
return event.button === 0;
}
function isModifiedEvent(event: MouseEvent) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
type PropTypes = {
to: string;
onClick?: Function;
children?: ReactNode;
className?: string;
};
const Link = ({ to, children, onClick, ...restProps }: PropTypes) => (
<a
href={to}
{...restProps}
onClick={(event: any) => {
if (onClick) {
onClick(event);
}
if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}
if (event.defaultPrevented === true) {
return;
}
event.preventDefault();
history.push(to);
}}
>
{children}
</a>
);
export default Link;
|
piglovesyou/react-apollo-loader-example
|
typings/express.d.ts
|
import 'express-serve-static-core';
declare module 'express-serve-static-core' {
import { Express } from 'express';
interface Application {
// RSK uses an internal function "handle" in start.ts.
handle(req: Request, res: Response): Express;
}
}
declare global {
namespace Express {
// For use of passport
interface User {
id: string;
}
}
}
|
piglovesyou/react-apollo-loader-example
|
tools/lib/markdown-loader.ts
|
<gh_stars>1-10
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import webpack from 'webpack';
import path from 'path';
import fm from 'front-matter';
import MarkdownIt from 'markdown-it';
module.exports = function markdownLoader(
this: webpack.loader.LoaderContext,
source: string,
) {
const md = new MarkdownIt({
html: true,
linkify: true,
});
const frontmatter = fm<{ key: string; html: string }>(source);
frontmatter.attributes.key = path.basename(this.resourcePath, '.md');
frontmatter.attributes.html = md.render(frontmatter.body);
return `module.exports = ${JSON.stringify(frontmatter.attributes)};`;
};
|
piglovesyou/react-apollo-loader-example
|
src/routes/home/index.tsx
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Home from './Home';
import Layout from '../../components/Layout';
async function action() {
return {
title: 'React Starter Kit',
chunks: ['home'],
component: (
<Layout>
<Home />
</Layout>
),
};
}
export default action;
|
piglovesyou/react-apollo-loader-example
|
tools/__tests__/start.ts
|
import assert from 'assert';
import path from 'path';
import { Browser, Page } from 'puppeteer';
import { readFile, writeFile } from '../lib/fs';
import {
killApp,
waitApp,
timeout,
openBrowser,
getUrl,
} from '../lib/test-fns';
import { spawn } from '../lib/cp';
const startApp = (cwd: string, port: number) =>
spawn('yarn', ['start', '--silent'], {
cwd,
env: { PORT: String(port) },
});
describe('yarn start', () => {
const port = 3033;
const cwd = path.resolve(__dirname, '../..');
const app = startApp(cwd, port);
let browser: Browser;
let page: Page;
beforeAll(async () => {
await waitApp(port);
[browser, page] = await openBrowser(port);
}, 60 * 1000);
afterAll(async () => {
await browser.close();
await killApp(app);
});
it('launches the App', async () => {
const expect = 'React.js News';
const actual = await page.$$eval('h1', es => es[1].textContent);
assert.deepStrictEqual(actual, expect);
});
it(
'does Hot Module Reload',
async () => {
const sourcePath = 'src/routes/home/Home.tsx';
const sourceAbsPath = path.join(cwd, sourcePath);
const expect = 'HMR!!!';
const defaultH1 = '<h1>React.js News</h1>';
const modifiedH1 = `<h1>${expect}</h1>`;
const modifySource = async () => {
const content = await readFile(sourceAbsPath);
if (!content.includes(defaultH1))
throw new Error('This test cannot run. Check "defaultH1".');
await writeFile(sourceAbsPath, content.replace(defaultH1, modifiedH1));
};
const resetSource = async () => {
const content = await readFile(sourceAbsPath);
await writeFile(sourceAbsPath, content.replace(modifiedH1, defaultH1));
};
await modifySource();
await timeout(3 * 1000);
const actual = await page.$$eval('h1', es => es[1].textContent);
assert.deepStrictEqual(actual, expect);
await resetSource();
},
30 * 1000,
);
it('starts GraphiQL', async () => {
await page.goto(`${getUrl(port)}/graphql`);
const textContent = await page.$eval('#root', e => e.textContent!);
assert(textContent.includes('Query Variables'));
assert(textContent.includes('HTTP Headers'));
});
});
|
piglovesyou/react-apollo-loader-example
|
src/core/createApolloClient/createApolloClient.server.ts
|
import { ApolloClient } from 'apollo-client';
import { from } from 'apollo-link';
import { onError } from 'apollo-link-error';
import { SchemaLink } from 'apollo-link-schema';
import merge from 'lodash.merge';
import gql from 'graphql-tag';
import createCache from './createCache';
import {
resolvers as clientResolvers,
schema as clientSchema,
defaults as cacheDefaults,
} from '../../data/graphql/OnMemoryState/schema';
export default function createApolloClient(
schema: SchemaLink.Options,
partialCacheDefaults: Object,
) {
const cache = createCache();
cache.writeData({
data: merge(cacheDefaults, partialCacheDefaults),
});
const link = from([
onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors)
graphQLErrors.map(({ message, locations, path }) =>
console.warn(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
),
);
if (networkError) console.warn(`[Network error]: ${networkError}`);
}),
new SchemaLink({ ...schema }),
]);
return new ApolloClient({
// @ts-ignore
link,
cache,
typeDefs: gql(clientSchema),
resolvers: clientResolvers,
ssrMode: true,
queryDeduplication: true,
});
}
|
piglovesyou/react-apollo-loader-example
|
src/components/Navigation/Navigation.tsx
|
<reponame>piglovesyou/react-apollo-loader-example
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { ComponentType } from 'react';
import cx from 'classnames';
import useStyles from 'isomorphic-style-loader/useStyles';
import s from './Navigation.css';
import Link from '../Link';
const Navigation: ComponentType<{}> = () => {
useStyles(s);
return (
<div className={s.root} role="navigation">
<Link className={s.link} to="/about">
About
</Link>
<Link className={s.link} to="/contact">
Contact
</Link>
<span className={s.spacer}> | </span>
<Link className={s.link} to="/login">
Log in
</Link>
<span className={s.spacer}>or</span>
<Link className={cx(s.link, s.highlight)} to="/register">
Sign up
</Link>
</div>
);
};
export default Navigation;
|
piglovesyou/react-apollo-loader-example
|
src/components/Feedback/Feedback.tsx
|
<filename>src/components/Feedback/Feedback.tsx
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import useStyles from 'isomorphic-style-loader/useStyles';
import s from './Feedback.css';
const Feedback = () => {
useStyles(s);
return (
<div className={s.root}>
<div className={s.container}>
<a
className={s.link}
href="https://gitter.im/kriasoft/react-starter-kit"
>
Ask a question
</a>
<span className={s.spacer}>|</span>
<a
className={s.link}
href="https://github.com/kriasoft/react-starter-kit/issues/new"
>
Report an issue
</a>
</div>
</div>
);
};
export default Feedback;
|
piglovesyou/react-apollo-loader-example
|
tools/bundle.ts
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import webpackConfig from './webpack.config';
import runWebpack from './lib/runWebpack';
/**
* Creates application bundles from the source files.
*/
export default function bundle() {
return runWebpack(webpackConfig, webpackConfig[0].stats);
}
|
PhilipCorr/airbyte
|
airbyte-webapp/src/packages/cloud/views/workspaces/WorkspacePopout/WorkspacePopout.tsx
|
<filename>airbyte-webapp/src/packages/cloud/views/workspaces/WorkspacePopout/WorkspacePopout.tsx
import React, { useMemo } from "react";
import styled from "styled-components";
import { components } from "react-select";
import { FormattedMessage, useIntl } from "react-intl";
import { MenuListComponentProps } from "react-select/src/components/Menu";
import { Popout } from "components";
import { IDataItem } from "components/base/DropDown/components/Option";
import {
useWorkspaceService,
useListCloudWorkspacesAsync,
} from "packages/cloud/services/workspaces/WorkspacesService";
import { useCurrentWorkspace } from "services/workspaces/WorkspacesService";
import ExitIcon from "./components/ExitIcon";
const BottomElement = styled.div`
background: ${(props) => props.theme.greyColro0};
padding: 12px 16px 12px;
width: 100%;
min-height: 34px;
border-top: 1px solid ${(props) => props.theme.greyColor20};
color: ${(props) => props.theme.primaryColor};
`;
const Block = styled.div`
cursor: pointer;
color: ${({ theme }) => theme.primaryColor};
font-size: 11px;
line-height: 13px;
vertical-align: center;
&:hover {
opacity: 0.7;
}
`;
const TextBlock = styled.div`
margin-left: 10px;
vertical-align: text-top;
display: inline-block;
`;
const TopElement = styled.div<{ single: boolean }>`
font-weight: 500;
font-size: 14px;
line-height: 17px;
display: flex;
align-items: center;
padding: 12px 16px 12px;
& > span {
display: block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
${({ single, theme }) =>
!single && `border-bottom: 1px solid ${theme.greyColor20};`}
`;
const List = styled.div`
& .react-select__option {
& div {
font-weight: 400;
font-size: 11px;
color: #1a194d;
}
}
`;
type MenuWithRequestButtonProps = MenuListComponentProps<IDataItem, false> & {
selectedWorkspace: string;
};
const WorkspacesList: React.FC<MenuWithRequestButtonProps> = ({
children,
selectedWorkspace,
...props
}) => {
const { exitWorkspace } = useWorkspaceService();
return (
<List>
<TopElement single={props.options.length === 0}>
<span>{selectedWorkspace}</span>
</TopElement>
<components.MenuList {...props}>{children}</components.MenuList>
<BottomElement>
<Block onClick={exitWorkspace}>
<ExitIcon />
<TextBlock data-testid="workspaces.viewAllWorkspaces">
<FormattedMessage id="workspaces.viewAllWorkspaces" />
</TextBlock>
</Block>
</BottomElement>
</List>
);
};
const WorkspacePopout: React.FC<{
children: (props: { onOpen: () => void; value: any }) => React.ReactNode;
}> = ({ children }) => {
const { formatMessage } = useIntl();
const { data: workspaceList, isLoading } = useListCloudWorkspacesAsync();
const { selectWorkspace } = useWorkspaceService();
const workspace = useCurrentWorkspace();
const options = useMemo(
() =>
workspaceList
?.filter((w) => w.workspaceId !== workspace.workspaceId)
.map((workspace) => ({
value: workspace.workspaceId,
label: workspace.name,
})),
[workspaceList, workspace]
);
return (
<Popout
targetComponent={(targetProps) =>
children({ onOpen: targetProps.onOpen, value: workspace.name })
}
components={{
MenuList: (props) => (
<WorkspacesList {...props} selectedWorkspace={workspace.name} />
),
}}
isSearchable={false}
options={options}
isLoading={isLoading}
loadingMessage={() =>
formatMessage({
id: "workspaces.loading",
})
}
value={workspace.slug}
onChange={({ value }) => selectWorkspace(value)}
/>
);
};
export { WorkspacePopout };
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/helpers/locales.ts
|
import { LocaleName } from '../types';
export const ALL_LOCALES: LocaleName[] = [
'ch',
'cz',
'en',
'es-mx',
'es',
'fr',
'ge',
'hu',
'it',
'jp',
'kr',
'pl',
'po',
'ru',
'sk',
'tu',
];
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/helpers/queststring_validation.ts
|
import { LocaleName, QuestString } from '../types';
import { ALL_LOCALES } from './locales';
export const isValidLocale = (str: string): str is LocaleName => {
return (ALL_LOCALES as string[]).includes(str);
};
const checkForQuestStringErrors = (questString: any): string | null => {
if (typeof questString === 'string') {
return null;
}
if (questString) {
let localesAreOk = true;
Object.keys(questString).forEach(localeName => {
if (!isValidLocale(localeName)) {
localesAreOk = false;
}
});
if (!localesAreOk) {
return 'Unknown locale names found';
}
}
return null;
};
export const assertValidQuestString = (
questString: any,
fieldName: string,
): asserts questString is QuestString => {
const result = checkForQuestStringErrors(questString);
if (result !== null) {
throw new Error(`${result} for '${fieldName}'`);
}
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/helpers/all_quests_images.ts
|
export const ALL_QUESTS_IMAGES = [
'5a27c50f86f7740b3d65e16a',
'5a27c44386f7744237421af0',
'5a27cafa86f77424e20615d6',
'5a29221d86f77457303da9fa',
'5a29222486f77456f50d09e7',
'5ac4d8f186f774422237860d',
'5ac4d9aa86f7744784484abf',
'5ac4da0486f7744cc7701bdc',
'5ac4db0986f77442000164dd',
'5ac4dbb086f7743e7c61ca09',
'5ac4dc0486f77442000164e5',
'5ac4e02986f774617a185ef2',
'5ac4e06086f774623122ae42',
'5ac4e08086f774623122ae44',
'5ae4a7d286f7744748710d74',
'5ae4a7d986f7743fee0a75b2',
'5ae4a7dd86f77448464ed2b2',
'5ae4a74386f7744748710d72',
'5ae4a76086f774455f7d62d2',
'5ae325c586f77444fa45d0de',
'5ae326a086f77444fd36f5d8',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'5b478eda86f77470315db899',
'5b4785f586f77470315db7ed',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'5c1e358f86f77408017f539f',
'5c7eb06188a4504aae56deb7',
'5d6e860186f774460f1f0602',
'5d6faf8f86f7743598553dd4',
'5d67b2a086f774131e206c05',
'5d67b3ed86f7744a2e70f15c',
'5d67b5ca86f7744dcc5e2f88',
'5d67b7ba86f774131e206c0c',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'5d67c1e486f774131e206c3a',
'5d77a10586f7745041358b41',
'5d694a6b86f77452a94debdf',
'<KEY>',
'<KEY>',
'5d763d4886f774454e50d06d',
'<KEY>',
'<KEY>',
'5d6948e186f774238a38d8a7',
'5d69468a86f77452aa51d79d',
'5d66701986f7744a2e70f025',
'5d69470786f774238a38d844',
'5d69474486f77414077d1cc8',
'5d69483686f77414077d1cca',
'5e4d3a5186f77464185227f3',
'5e4d3a5886f77438b1632d82',
'5e383a6386f77465910ce1f3',
'5eda19f0edce541157209cee',
'5ee234c386f77447ee650e32',
'<KEY>',
'5f0f202de269d61a4b5cf6ec',
'5fd9fad9c1ce6b1a3b486d00',
'57e4f1852459772a15635633',
'59bfebe686f7745ba3403da3',
'<KEY>',
'<KEY>',
'<KEY>',
'59c273da86f77459b8017e7b',
'59c274ae86f77475060a9341',
'<KEY>',
'<KEY>',
'<KEY>',
'59ca2e4186f77445e4732b22',
'<KEY>',
'60c373e753bc0f18316351fe',
'60c375a0c2d86b57700e316b',
'60c3752d78280c17952e1e69',
'60c37450de6b0b44cc320e9a',
'60c37481c2d86b57700e3169',
'60c37416898b57521260e12a',
'<KEY>',
'<KEY>',
'61ab4f090330382cea7bad57',
'61ab40a7edd0787ea26a69a6',
'61ab48bc5c890e40ca1a30f8',
'<KEY>',
'<KEY>',
'<KEY>',
'61ab421079c3a477d0121e46',
'<KEY>',
'<KEY>',
'594d241f86f7740d8246218d',
'<KEY>',
'594d247486f77426ad2fd20b',
'594d248186f7740e670685db',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'597a0fad86f77426d464f995',
'<KEY>',
'616d993bc8c5ad2ab30ff6ba',
'<KEY>',
'<KEY>',
'5969f96786f7741dde183a4f',
'5979d3da86f774719f309082',
'5979d3ea86f7746d0b3e3fdc',
'5979d3f986f7746d08051ce0',
'5979d36d86f7746d093ddd7a',
'5979d37886f7746d0b3e3fdb',
'<KEY>',
'<KEY>',
'5979ef2a86f77431185415c3',
'<KEY>',
'5981c96e86f77477920d1a04',
'<KEY>',
'<KEY>',
'<KEY>',
'59689f8f86f7740d121082d7',
'<KEY>',
'<KEY>',
'<KEY>',
'<KEY>',
'5967505886f774590730dadc',
'5967611386f7741dfe4f46fb',
'<KEY>',
'<KEY>',
];
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/QuestGenericDropdown/index.tsx
|
import {
Component,
createEffect,
createMemo,
createSignal,
For,
Match,
Show,
Switch,
} from 'solid-js';
type Props = {
paddingValue?: number;
formIndex: number;
allValues: string[];
value: string;
setValue?: (v: string) => void;
uniqId: string;
fieldName?: string;
onSelectValue?: (v: string) => void;
editable?: boolean;
};
type SelectEvent = Event & { target: Element; currentTarget: HTMLSelectElement };
export const QuestGenericDropdown: Component<Props> = props => {
const [adding, setAdding] = createSignal(false);
createEffect(prev => {
if (prev !== props.uniqId) {
setAdding(false);
}
return props.uniqId;
});
const values = createMemo(() => {
const result = [...props.allValues];
if (!result.includes(props.value)) {
result.push(props.value);
}
return result;
});
const onSelectChange = (e: SelectEvent) => {
const value = e.currentTarget.value;
props.setValue?.(value);
props.onSelectValue?.(value);
};
const idInputText = createMemo(() => {
return `form_generic_dropdown_id_${props.fieldName}_${props.formIndex}`;
});
const selectValue = () => {
const el = document.getElementById(idInputText());
if (el) {
props.onSelectValue?.((el as HTMLInputElement).value);
}
setAdding(false);
};
return (
<div style={{ padding: '15px' }}>
<Show when={Boolean(props.fieldName)}>
<label
style={{
display: 'inline-block',
float: 'left',
clear: 'left',
width: '180px',
'text-align': 'left',
'margin-right': '10px',
}}
for={idInputText()}
>
{`${props.fieldName}: `}
</label>
</Show>
<Switch>
<Match when={adding()}>
<input
autofocus={true}
style={{ display: 'inline-block', float: 'left', width: '180px' }}
onInput={e => {
const value = e.currentTarget.value;
if (value) {
props.setValue?.(value);
}
}}
type="text"
onKeyPress={e => {
if (e.key === 'Enter') {
selectValue();
}
}}
id={idInputText()}
tabIndex={props.formIndex}
/>
<input
style={{ display: 'inline-block', float: 'left' }}
type="button"
tabIndex={props.formIndex + 1}
value="Ok"
onClick={() => {
selectValue();
}}
/>
</Match>
<Match when={!adding()}>
<select
onChange={onSelectChange}
style={{ display: 'inline-block', float: 'left', width: '180px' }}
tabIndex={props.formIndex}
>
<For each={values()}>
{v => (
<option selected={v === props.value} value={v}>
{v}
</option>
)}
</For>
</select>
<Show when={props.editable}>
<input
tabIndex={props.formIndex + 1}
type="button"
value="Edit manually..."
style={{ display: 'inline-block', float: 'left' }}
onClick={() => {
setAdding(true);
const el = document.getElementById(idInputText());
if (el) {
el.focus();
}
}}
/>
</Show>
</Match>
</Switch>
{props.children}
</div>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/MissionNeedSurviveInput/index.tsx
|
import { Component, createMemo, Show } from 'solid-js';
import { DeepReadonly } from 'solid-js/store';
import {
MissionPlaceBeacon,
MissionPlaceItem,
MissionPlaceSignalJammer,
MissionVisitPlace,
} from '../../../types';
import { MissionUpdator } from '../QuestMissionsForm/types';
import { QuestStringInput } from '../QuestStringInput';
type CompatibleMission =
| MissionPlaceItem
| MissionPlaceBeacon
| MissionPlaceSignalJammer
| MissionVisitPlace;
type Props = {
uniqId: string;
mission: DeepReadonly<CompatibleMission>;
updateMission: MissionUpdator<CompatibleMission>;
};
export const MissionNeedSurviveInput: Component<Props> = props => {
const needSurviveEnabled = createMemo(() => {
if (props.mission.need_survive !== undefined && props.mission.need_survive !== 'null') {
return true;
}
return false;
});
return (
<>
<label
style={{
display: 'inline-block',
float: 'left',
clear: 'left',
width: '180px',
'text-align': 'right',
'margin-right': '10px',
}}
for={`form_disabled`}
>
{'need_survive: '}
</label>
<input
id={`form_place_item_need_survive_${props.uniqId}`}
onChange={e => {
props.updateMission(q => {
if (e.currentTarget.checked) {
return { ...q, need_survive: '' };
}
return { ...q, need_survive: undefined };
});
}}
type="checkbox"
checked={needSurviveEnabled()}
/>
<Show when={needSurviveEnabled()}>
<QuestStringInput
fieldName="survive message"
formIndex={-1}
uniqId={props.uniqId}
questString={props.mission.need_survive}
updateQuestString={fn =>
props.updateMission(m => ({ ...m, need_survive: fn(m.need_survive) }))
}
/>
</Show>
</>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/QuestMissionsForm/ChooseMissionType.tsx
|
<gh_stars>0
import { Component, For } from 'solid-js';
import { MissionType, VALID_MISSION_TYPES } from '../../../helpers/mission_validation';
type MissionProps = {
onClickType: (missionType: MissionType) => void;
};
export const ChooseMissionType: Component<MissionProps> = props => {
return (
<div
style={{
'margin-bottom': '5px',
'margin-top': '15px',
padding: '15px',
'background-color': '#333333',
color: 'white',
}}
>
<span
style={{
display: 'inline-block',
'margin-right': '10px',
'margin-bottom': '10px',
}}
>
Choose a type of mission:
</span>
<div>
<For each={VALID_MISSION_TYPES}>
{missionType => {
return (
<input
onClick={() => props.onClickType(missionType)}
style={{ 'margin-right': '13px' }}
type="button"
value={missionType}
/>
);
}}
</For>
</div>
</div>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/types.ts
|
import { DeepReadonly } from 'solid-js/store';
const ALL_DESCRIPTIVE_LOCATION_OBJ = {
any: true,
customs: true,
factory: true,
laboratory: true,
interchange: true,
lighthouse: true,
reserve: true,
shoreline: true,
woods: true,
};
const ALL_LOCATIONS_OBJ = {
any: true,
customs: true,
factory: true, // night and day
factory4_day: true, // day only
factory4_night: true, // night only
laboratory: true,
interchange: true,
lighthouse: true,
reserve: true,
shoreline: true,
woods: true,
};
export const ALL_LOCATIONS = Object.keys(ALL_LOCATIONS_OBJ);
export type PossibleLocation = keyof typeof ALL_LOCATIONS_OBJ;
export const ALL_DESCRIPTIVE_LOCATION = Object.keys(ALL_DESCRIPTIVE_LOCATION_OBJ);
export type DescriptiveLocation = keyof typeof ALL_DESCRIPTIVE_LOCATION_OBJ;
export type LocalizedString = {
ch?: string;
cz?: string;
en?: string;
'es-mx'?: string;
es?: string;
fr?: string;
ge?: string;
hu?: string;
it?: string;
jp?: string;
kr?: string;
pl?: string;
po?: string;
ru?: string;
sk?: string;
tu?: string;
};
export type LocaleName = keyof LocalizedString;
export type QuestType = 'Completion' | 'PickUp' | 'Elimination' | 'Loyalty' | 'Discover';
export type QuestString = string | LocalizedString;
export type KillTarget = 'Savage' | 'AnyPmc' | 'Usec' | 'Bear';
export type MissionKill = {
type: 'Kill';
target?: KillTarget;
locations?: PossibleLocation[];
count?: number;
message?: QuestString;
};
export type MissionGiveItem = {
type: 'GiveItem';
accepted_items: string[];
count?: number;
found_in_raid_only?: boolean;
message?: QuestString;
};
type CommonPlaceX = {
zone_id: string; // TODO list all zone ids;
plant_time?: number;
need_survive?: QuestString;
message?: QuestString;
};
export type MissionPlaceItem = {
type: 'PlaceItem';
accepted_items: string[];
} & CommonPlaceX;
export type MissionPlaceBeacon = {
type: 'PlaceBeacon';
} & CommonPlaceX;
export type MissionPlaceSignalJammer = {
type: 'PlaceSignalJammer';
} & CommonPlaceX;
export type MissionVisitPlace = {
type: 'VisitPlace';
place_id: string; // TODO: list all place ids
need_survive?: QuestString;
message?: QuestString;
};
export type QuestMission =
| MissionKill
| MissionGiveItem
| MissionPlaceItem
| MissionPlaceBeacon
| MissionPlaceSignalJammer
| MissionVisitPlace;
export type QuestRewards = {
xp?: number;
items?: {
[itemId: string]: number;
};
};
export type QuestData = {
id: string;
trader_id: string;
disabled?: boolean;
descriptive_location?: DescriptiveLocation;
type?: QuestType;
image?: string;
name?: QuestString;
description?: QuestString;
success_message?: QuestString;
level_needed?: number;
locked_by_quests?: string[];
unlock_on_quest_start?: string[];
missions?: QuestMission[];
rewards?: QuestRewards;
};
export type LoadedJsonFile = {
name: string;
data: QuestData[];
};
type QuestUpdateFn = (q: DeepReadonly<QuestData>) => DeepReadonly<QuestData>;
type QuestStringUpdateFn = (q: DeepReadonly<QuestString | undefined>) => DeepReadonly<QuestString>;
type Updator<T> = (fn: T) => void;
export type QuestUpdator = Updator<QuestUpdateFn>;
export type QuestStringUpdator = Updator<QuestStringUpdateFn>;
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/helpers/validation.ts
|
import { QuestData, QuestType, QuestRewards, ALL_DESCRIPTIVE_LOCATION } from '../types';
import { assertValidMission } from './mission_validation';
import { assertValidQuestString } from './queststring_validation';
export const ALL_QUEST_TYPES = ['Completion', 'PickUp', 'Elimination', 'Loyalty', 'Discover'];
const DESCRIPTIVE_LOCATION_ALIASES: Record<string, string> = {
rezervbase: 'reserve',
bigmap: 'customs',
labs: 'laboratory',
'56f40101d2720b2a4d8b45d6': 'customs',
'55f2d3fd4bdc2d5f408b4567': 'factory',
'5714dbc024597771384a510d': 'interchange',
'5b0fc42d86f7744a585f9105': 'laboratory',
'5704e4dad2720bb55b8b4567': 'lighthouse',
'5704e5fad2720bc05b8b4567': 'reserve',
'5704e554d2720bac5b8b456e': 'shoreline',
'5704e3c2d2720bac5b8b4567': 'woods',
};
const LOCATION_ALIASES: Record<string, string> = {
'': 'any',
bigmap: 'customs',
rezervbase: 'reserve',
labs: 'laboratory',
};
const error = (msg: string) => new Error(msg);
const isValidQuestType = (str: string): str is QuestType => {
return ALL_QUEST_TYPES.includes(str);
};
const assertValidRewards = (rewards: any): asserts rewards is QuestRewards => {
if (!rewards) {
return;
}
if (rewards.xp !== undefined && typeof rewards.xp !== 'number') {
throw error(`'rewards.xp' should be a number`);
}
if (rewards.items !== undefined && typeof rewards.items !== 'object') {
throw error(`'rewards.items' should be an object`);
}
Object.keys(rewards.items).forEach(k => {
if (typeof k !== 'string') {
throw error(`invalid key found in 'rewards.items'`);
}
});
Object.values(rewards.items).forEach(v => {
if (typeof v !== 'number') {
throw error(`invalid value found in 'rewards.items', it should be a number`);
}
});
};
const assertValidQuest = (questData: any): asserts questData is QuestData => {
const q = questData;
if (!q.id || typeof q.id !== 'string') {
throw error(`no valid 'id' found`);
}
if (!q.trader_id || typeof q.trader_id !== 'string') {
throw error(`no valid 'trader_id' found`);
}
if (q.disabled !== undefined && q.disabled !== true && q.disabled !== false) {
throw error(`'disabled' should be a boolean`);
}
if (q.descriptive_location !== undefined && typeof q.descriptive_location !== 'string') {
throw error(`'descriptive_location' should be a string`);
}
if (
q.descriptive_location !== undefined &&
!ALL_DESCRIPTIVE_LOCATION.includes(q.descriptive_location)
) {
throw error(`unknown 'descriptive_location' : ${q.descriptive_location}`);
}
if (q.type && !isValidQuestType(q.type)) {
throw error(`invalid quest 'type' provided`);
}
if (q.image !== undefined && typeof q.image !== 'string') {
throw error(`'image' should be a string`);
}
if (q.name !== undefined) {
void assertValidQuestString(q.name, 'name');
}
if (q.description !== undefined) {
void assertValidQuestString(q.description, 'description');
}
if (q.success_message !== undefined) {
void assertValidQuestString(q.success_message, 'success_message');
}
if (q.level_needed !== undefined && typeof q.level_needed !== 'number') {
throw error(`'level_needed' should be a number`);
}
if (q.locked_by_quests && !Array.isArray(q.locked_by_quests)) {
throw error(`'locked_by_quests' should be an array`);
}
if (q.locked_by_quests) {
q.locked_by_quests.forEach((questId: any) => {
if (typeof questId !== 'string') {
throw new Error(`invalid 'locked_by_quests' quest ids`);
}
});
}
if (q.unlock_on_quest_start && !Array.isArray(q.unlock_on_quest_start)) {
throw error(`'unlock_on_quest_start' should be an array`);
}
if (q.unlock_on_quest_start) {
q.unlock_on_quest_start.forEach((questId: any) => {
if (typeof questId !== 'string') {
throw new Error(`invalid 'unlock_on_quest_start' quest ids`);
}
});
}
if (q.rewards !== undefined) {
void assertValidRewards(q.rewards);
}
if (q.missions !== undefined && !Array.isArray(q.missions)) {
throw error(`'missions' should be an array`);
}
q.missions?.forEach((mission: any) => {
void assertValidMission(mission);
});
};
export const checkQuestJsonData = (givenData: any): QuestData[] => {
const data: any[] = Array.isArray(givenData) ? givenData : [givenData];
const newData = data.map(questData => {
const descriptive_location: string | undefined = questData.descriptive_location;
const missions = questData.missions ?? [];
return {
...questData,
missions: missions.map((m: any) => {
// set locations aliases on missions
if (m.locations && m.locations.length) {
return {
...m,
locations: m.locations.map((locationName: string) => {
if (LOCATION_ALIASES[locationName]) {
return LOCATION_ALIASES[locationName];
}
return locationName;
}),
};
}
return m;
}),
// set descriptive_location aliases
descriptive_location:
DESCRIPTIVE_LOCATION_ALIASES[descriptive_location ?? ''] ?? descriptive_location,
};
});
newData.forEach(questData => {
void assertValidQuest(questData);
});
return newData;
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/index.tsx
|
import { render } from 'solid-js/web';
import './index.css';
import App from './App';
const rootElement = document.getElementById('root');
if (!rootElement) {
throw new Error('Fatal: no div #root found in the DOM');
}
render(() => <App />, rootElement);
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/helpers/allZonesByMap.ts
|
<gh_stars>1-10
export const allZonesByMap: Record<string, string[]> = {
bigmap: [
'gazel',
'place_peacemaker_007_N1',
'place_peacemaker_002_N1',
'place_peacemaker_002_N2',
'place_peacemaker_002_N3',
'extraction_zone_zibbo',
'fuel1',
'fuel2',
'fuel3',
'fuel4',
'place_skier_12_2',
'place_skier_11_3',
'Q019_3',
],
woods: [
'place_peacemaker_007_2_N2',
'place_peacemaker_007_2_N2_1',
'place_THX_15',
'bar_fuel3_1',
'bar_fuel3_2',
'bar_fuel3_3',
'place_skier_12_3',
'place_skier_11_2',
'huntsman_005_1',
'huntsman_005_2',
],
shoreline: [
'place_peacemaker_007_2_N3',
'place_peacemaker_008_2_N1',
'place_peacemaker_008_2_N2',
'place_peacemaker_003_N1',
'place_peacemaker_003_N2',
'place_peacemaker_003_N3',
'place_peacemaker_005_N1',
'place_peacemaker_005_N2',
'place_peacemaker_010_2',
'place_SIGNAL_03_1',
'place_SIGNAL_03_2',
'place_SIGNAL_03_3',
'place_peacemaker_001',
'ter_013_area_1',
'ter_013_area_2',
'ter_013_area_3',
'skier_022_area_1',
'skier_022_area_2',
'skier_022_area_3',
'prapor_022_area_1',
'prapor_022_area_2',
'prapor_022_area_3',
],
interchange: [
'place_WARBLOOD_04_1',
'place_WARBLOOD_04_2',
'place_WARBLOOD_04_3',
'place_skier_12_1',
'place_skier_11_1',
'place_merch_21_1',
'place_merch_21_2',
'place_merch_21_3',
'place_merch_020_1',
'place_merch_020_2',
],
factory: ['place_SADOVOD_01_1', 'place_SADOVOD_01_2', 'case_extraction', 'ter_017_area_1'],
lighthouse: [
'qlight_pr1_heli1_mark',
'qlight_mark_vech1',
'qlight_mark_vech2',
'qlight_mark_vech3',
'qlight_mark_vech4',
'qlight_fuel_blood',
'qlight_fuel_blood_bezovoz1',
'qlight_fuel_blood_bezovoz2',
'qlight_fuel_blood_bezovoz3',
'qlight16_peace_terra',
],
rezervbase: [
'tadeush_bmp2_area_mark_2',
'tadeush_bmp2_area_mark_11',
'tadeush_bmp2_area_mark_12',
'tadeush_bmp2_area_mark_13',
'tadeush_stryker_area_mark_3',
'baraholshik_fuel_area_2',
'baraholshik_fuel_area_3',
],
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/QuestMissionsForm/MissionVisitPlaceForm.tsx
|
import { Component } from 'solid-js';
import { DeepReadonly } from 'solid-js/store';
import { MissionVisitPlace } from '../../../types';
import { MissionNeedSurviveInput } from '../MissionNeedSurviveInput';
import { MissionPlaceIdInput } from '../MissionPlaceIdInput';
import { QuestStringInput } from '../QuestStringInput';
import { MissionUpdator } from './types';
type Props = {
questId: string;
index: number;
mission: DeepReadonly<MissionVisitPlace>;
updateMission: MissionUpdator<MissionVisitPlace>;
};
export const MissionVisitPlaceForm: Component<Props> = props => {
void props;
return (
<>
{props.children}
<QuestStringInput
formIndex={-1}
updateQuestString={fn => props.updateMission(m => ({ ...m, message: fn(m.message) }))}
uniqId={props.questId}
questString={props.mission.message}
fieldName="message"
/>
<MissionPlaceIdInput mission={props.mission} updateMission={props.updateMission} />
<br />
<MissionNeedSurviveInput
uniqId={props.questId}
mission={props.mission}
updateMission={fn =>
props.updateMission(m => {
return fn(m) as MissionVisitPlace;
})
}
/>
</>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/QuestMissionsForm/MissionKillForm.tsx
|
import { Component, createMemo } from 'solid-js';
import { DeepReadonly } from 'solid-js/store';
import { VALID_KILL_TARGETS } from '../../../helpers/mission_validation';
import { ALL_LOCATIONS, KillTarget, MissionKill, PossibleLocation } from '../../../types';
import { IdsForm } from '../IdsForm';
import { QuestNumberInput } from '../QuestNumberInput';
import { QuestSimpleDropdown } from '../QuestSimpleDropdown';
import { QuestStringInput } from '../QuestStringInput';
import { MissionUpdator } from './types';
type Props = {
questId: string;
index: number;
mission: DeepReadonly<MissionKill>;
updateMission: MissionUpdator<MissionKill>;
};
export const MissionKillForm: Component<Props> = props => {
const selectedValue = createMemo(() => {
return props.mission.target ?? 'Savage';
});
const missionCount = createMemo(() => {
return props.mission.count ?? 1;
});
const uniqId = createMemo(() => {
return `${props.questId}_mission_kill_${props.index}`;
});
const locations = createMemo(() => {
return props.mission.locations ?? [];
});
return (
<>
{props.children}
<QuestStringInput
formIndex={-1}
updateQuestString={fn => props.updateMission(m => ({ ...m, message: fn(m.message) }))}
uniqId={uniqId()}
questString={props.mission.message}
fieldName="message"
/>
<QuestSimpleDropdown
fieldName="target"
formIndex={18}
values={VALID_KILL_TARGETS}
selectedValue={selectedValue()}
onValueChanged={v => props.updateMission(m => ({ ...m, target: v as KillTarget }))}
/>
<QuestNumberInput
min={1}
fieldName="count"
value={missionCount()}
setValue={c => props.updateMission(m => ({ ...m, count: c }))}
/>
<IdsForm
wordingButton="locations"
possibleValues={ALL_LOCATIONS}
values={locations()}
updateValues={fn => {
props.updateMission(m => {
return {
...m,
locations: fn(locations()) as PossibleLocation[],
};
});
}}
uniqId={uniqId()}
fieldName="locations"
/>
</>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/QuestMissionsForm/MissionPlaceItemForm.tsx
|
<gh_stars>1-10
import { Component, createMemo, Show } from 'solid-js';
import { DeepReadonly } from 'solid-js/store';
import { MissionPlaceBeacon, MissionPlaceItem, MissionPlaceSignalJammer } from '../../../types';
import { MissionAcceptedItemsInput } from '../MissionAcceptedItemsInput';
import { MissionNeedSurviveInput } from '../MissionNeedSurviveInput';
import { MissionZoneIdInput } from '../MissionZoneIdInput';
import { QuestNumberInput } from '../QuestNumberInput';
import { QuestStringInput } from '../QuestStringInput';
import { MissionUpdator } from './types';
export type CompatiblePlaceItemMission =
| MissionPlaceItem
| MissionPlaceBeacon
| MissionPlaceSignalJammer;
type Props = {
questId: string;
index: number;
mission: DeepReadonly<CompatiblePlaceItemMission>;
updateMission: MissionUpdator<CompatiblePlaceItemMission>;
};
export const MissionPlaceItemForm: Component<Props> = props => {
const uniqId = createMemo(() => {
return `${props.questId}_place_item_${props.index}`;
});
const missionPlantTime = createMemo(() => {
return props.mission.plant_time ?? 30;
});
return (
<>
{props.children}
<QuestStringInput
formIndex={-1}
updateQuestString={fn => props.updateMission(m => ({ ...m, message: fn(m.message) }))}
uniqId={uniqId()}
questString={props.mission.message}
fieldName="message"
/>
<MissionZoneIdInput mission={props.mission} updateMission={props.updateMission} />
<QuestNumberInput
fieldName="plant_time"
value={missionPlantTime()}
setValue={c => props.updateMission(m => ({ ...m, plant_time: c }))}
/>
<MissionNeedSurviveInput
uniqId={uniqId()}
mission={props.mission}
updateMission={fn =>
props.updateMission(m => {
return fn(m) as CompatiblePlaceItemMission;
})
}
/>
<Show when={props.mission.type === 'PlaceItem'}>
<MissionAcceptedItemsInput
updateItems={fn => {
props.updateMission(m => ({
...m,
accepted_items: fn((m as MissionPlaceItem).accepted_items),
}));
}}
items={(props.mission as MissionPlaceItem).accepted_items}
uniqId={uniqId()}
/>
</Show>
</>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/MissionPlaceIdInput/index.tsx
|
<reponame>Procedural-Fox/aki_CustomQuestsEditor
import { Component, createEffect, createMemo, createSignal } from 'solid-js';
import { DeepReadonly } from 'solid-js/store';
import { allPlacesByMap } from '../../../helpers/allPlacesByMap';
import { MissionVisitPlace } from '../../../types';
import { MissionUpdator } from '../QuestMissionsForm/types';
import { QuestSimpleDropdown } from '../QuestSimpleDropdown';
const ALL_CONCERNED_MAP = Object.keys(allPlacesByMap);
const findMapForPlaceId = (placeId: string): string | undefined => {
return ALL_CONCERNED_MAP.find(mapId => allPlacesByMap[mapId].includes(placeId));
};
type CompatibleMission = MissionVisitPlace;
type Props = {
mission: DeepReadonly<CompatibleMission>;
updateMission: MissionUpdator<CompatibleMission>;
};
export const MissionPlaceIdInput: Component<Props> = props => {
const [selectedMap, setSelectedMap] = createSignal('bigmap');
const [mapChangedByUser, setMapChangedByUser] = createSignal(0);
const availablePlaces = createMemo(() => {
return allPlacesByMap[selectedMap()];
});
createEffect(prev => {
if (prev !== undefined && prev !== mapChangedByUser()) {
props.updateMission(m => ({ ...m, place_id: allPlacesByMap[selectedMap()][0] }));
}
return mapChangedByUser();
});
createEffect(prev => {
if (prev !== props.mission.place_id) {
const map = findMapForPlaceId(props.mission.place_id);
if (map) {
setSelectedMap(map);
}
}
return props.mission.place_id;
});
return (
<>
<QuestSimpleDropdown
fieldName="map"
formIndex={-1}
values={ALL_CONCERNED_MAP}
selectedValue={selectedMap()}
onValueChanged={v => {
setSelectedMap(v);
setMapChangedByUser(x => x + 1);
}}
/>
<QuestSimpleDropdown
fieldName="place_id"
fieldLink="https://github.com/guillaumearm/aki_CustomQuests/blob/master/docs/ALL_PLACES.md"
formIndex={-1}
values={availablePlaces()}
selectedValue={props.mission.place_id}
onValueChanged={v => {
props.updateMission(m => ({ ...m, place_id: v }));
}}
/>
</>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/QuestForm/index.tsx
|
<gh_stars>0
import { Component, createMemo } from 'solid-js';
import { DeepReadonly } from 'solid-js/store';
import { ALL_DESCRIPTIVE_LOCATION, DescriptiveLocation, QuestData, QuestType, QuestUpdator, } from '../../types';
import { QuestDisabledInput } from '../forms/QuestDisabledInput';
import { QuestSimpleInput } from '../forms/QuestSimpleInput';
import { QuestStringInput } from '../forms/QuestStringInput';
import { QuestGenericDropdown } from '../forms/QuestGenericDropdown';
import { IdsForm } from '../forms/IdsForm';
import { ALL_QUEST_TYPES } from '../../helpers/validation';
import { QuestSimpleDropdown } from '../forms/QuestSimpleDropdown';
import { ALL_QUESTS_IMAGES } from '../../helpers/all_quests_images';
import { QuestItemRewardsList } from '../forms/QuestItemRewardsList';
import { QuestNumberInput } from '../forms/QuestNumberInput';
import { QuestMissionsForm } from '../forms/QuestMissionsForm';
export const ALL_TRADERS = [
'prapor',
'therapist',
'fence',
'skier',
'peacekeeper',
'mechanic',
'ragman',
'jaeger',
];
type Props = {
nbQuests: number;
allQuestIds: string[];
questIndex: number | null;
quest: DeepReadonly<QuestData>;
updateQuest: QuestUpdator;
onMoveUp?: () => void;
onMoveDown?: () => void;
onRemove?: () => void;
onDupliacteQuest?: () => void;
};
export const QuestForm: Component<Props> = props => {
const uniqQuestId = createMemo(() => {
return `${props.quest.id}_${props.questIndex}`;
});
const rewardsItems = createMemo(() => {
return props.quest.rewards?.items ?? {};
});
const lockedByQuests = createMemo(() => {
return props.quest.locked_by_quests ?? [];
});
const unlockOnQuestStart = createMemo(() => {
return props.quest.unlock_on_quest_start ?? [];
});
return (
<div
id="quest_form"
style={{
'margin': '30px',
width: '100%',
'overflow-y': 'scroll',
'background-color': '#282828',
float: 'left',
}}
>
<div style={{ padding: '10px', color: 'white', 'background-color': '#121212' }}>
<h4 style={{ 'text-align': 'center' }}>Quest configuration</h4>
<div style={{
display: 'flex', 'flex-wrap': 'wrap',
}}>
<input
disabled={props.questIndex === 0}
onClick={props.onMoveUp}
style={{ margin: '0 10px 0 0' }}
type="button"
value="UP"
/>
<input
disabled={props.questIndex === props.nbQuests - 1}
onClick={props.onMoveDown}
style={{ margin: '0 10px 0 0' }}
type="button"
value="DOWN"
/>
<input
onClick={props.onDupliacteQuest}
style={{ margin: '0px' }}
type="button"
value="Duplicate quest"
/>
<input
onClick={props.onRemove}
style={{ float: 'right', 'margin-left': 'auto' }}
type="button"
className={'delete-button'}
value="Remove quest"
/>
</div>
</div>
<form
style={{color: 'white'}}
onSubmit={() => {}}>
<QuestDisabledInput formIndex={2} {...props} />
<QuestSimpleInput formIndex={4} {...props} fieldName="id"/>
<QuestGenericDropdown
formIndex={6}
fieldName="trader_id"
uniqId={uniqQuestId()}
allValues={ALL_TRADERS}
value={props.quest.trader_id}
setValue={v => props.updateQuest(q => ({ ...q, trader_id: v }))}
/>
<QuestStringInput
formIndex={8}
updateQuestString={fn => props.updateQuest(q => ({ ...q, name: fn(q.name) }))}
uniqId={uniqQuestId()}
questString={props.quest.name}
fieldName="name"
/>
<QuestStringInput
formIndex={10}
updateQuestString={fn =>
props.updateQuest(q => ({ ...q, description: fn(q.description) }))
}
uniqId={uniqQuestId()}
questString={props.quest.description}
fieldName="description"
/>
<QuestStringInput
formIndex={12}
updateQuestString={fn =>
props.updateQuest(q => ({ ...q, success_message: fn(q.success_message) }))
}
uniqId={uniqQuestId()}
questString={props.quest.success_message}
fieldName="success_message"
/>
<QuestSimpleDropdown
fieldName="type"
formIndex={14}
values={ALL_QUEST_TYPES}
selectedValue={props.quest.type ?? ALL_QUEST_TYPES[0]}
onValueChanged={v => props.updateQuest(q => ({ ...q, type: v as QuestType }))}
/>
<QuestSimpleDropdown
fieldName="descriptive_location"
formIndex={16}
values={ALL_DESCRIPTIVE_LOCATION}
selectedValue={props.quest.descriptive_location ?? ALL_DESCRIPTIVE_LOCATION[0]}
onValueChanged={v =>
props.updateQuest(q => ({ ...q, descriptive_location: v as DescriptiveLocation }))
}
/>
<QuestSimpleDropdown
fieldName="image"
formIndex={18}
values={ALL_QUESTS_IMAGES}
selectedValue={props.quest.image ?? ALL_QUESTS_IMAGES[0]}
onValueChanged={v => props.updateQuest(q => ({ ...q, image: v as string }))}
/>
<QuestNumberInput
min={1}
fieldName="level_needed"
value={props.quest.level_needed ?? 1}
setValue={level_needed => props.updateQuest(q => ({ ...q, level_needed }))}
/>
<IdsForm
editable
wordingButton="quest"
possibleValues={props.allQuestIds}
values={lockedByQuests()}
updateValues={fn =>
props.updateQuest(q => ({ ...q, locked_by_quests: fn(lockedByQuests()) }))
}
uniqId={uniqQuestId()}
fieldName="locked_by_quests"
/>
<IdsForm
editable
wordingButton="quest"
possibleValues={props.allQuestIds}
values={unlockOnQuestStart()}
updateValues={fn =>
props.updateQuest(q => ({ ...q, unlock_on_quest_start: fn(unlockOnQuestStart()) }))
}
uniqId={uniqQuestId()}
fieldName="unlock_on_quest_start"
/>
<QuestNumberInput
fieldName="rewards.xp"
value={props.quest.rewards?.xp ?? 0}
setValue={xp => props.updateQuest(q => ({ ...q, rewards: { ...q.rewards, xp } }))}
/>
<QuestItemRewardsList
updateRewards={fn =>
props.updateQuest(q => ({
...q,
rewards: { ...q.rewards, items: { ...fn(q.rewards?.items ?? {}) } },
}))
}
uniqQuestId={uniqQuestId()}
rewards={rewardsItems()}
/>
<h2>Missions</h2>
<QuestMissionsForm quest={props.quest} updateQuest={props.updateQuest}/>
</form>
</div>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/AppTitle/index.tsx
|
import { Component } from 'solid-js';
type AppTitleProps = { children: string; customQuestsVersion: string };
export const AppTitle: Component<AppTitleProps> = props => {
return (
<>
<div style={{
position: 'relative',
'background-color': '#121212',
padding: '15px 30px 15px 30px',
color: 'white'
}}>
<h2
style={{
'text-align': 'left',
}}
>
{props.children}
</h2>
<h4
className={'responsive-nav'}
style={{
position: 'absolute',
margin: 0,
right: '10px',
top: '50%',
transform: 'translateY(-50%)'
}}
>
For{' '}
<a
target="_blank"
style={{ color: '#00b2e8' }}
href="https://hub.sp-tarkov.com/files/file/517-custom-quests/"
>
Custom Quests
</a>{' '}
v{props.customQuestsVersion}
</h4>
</div>
</>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/QuestsFiles/index.tsx
|
import { dropLast } from 'ramda';
import { Accessor, Component, For } from 'solid-js';
import { DeepReadonly } from 'solid-js/store';
import { LoadedJsonFile } from '../../types';
import { MainMenu, MainMenuItem } from '../MainMenu';
const removeJsonExt = (fileName: string): string => {
const splitted = fileName.split('.json');
if (splitted.length >= 2) {
return dropLast(1, splitted).join('.json');
}
return fileName;
};
type Props = {
isDragging: Accessor<boolean>;
loadedJsonFiles: DeepReadonly<LoadedJsonFile[]>;
selectedFile: null | number;
onClickFile: (index: number) => void;
onCreateNewFile: () => void;
onEditFilename: (newFilename: string, index: number) => void;
};
const QuestsFiles: Component<Props> = props => {
return (
<MainMenu isDragging={props.isDragging()} title="Quest files">
<For each={props.loadedJsonFiles}>
{(loadedJsonFile, index) => (
<MainMenuItem
index={index()}
enableEdition={true}
selected={index() === props.selectedFile}
onClick={() => props.onClickFile(index())}
onEditEnter={props.onEditFilename}
text={removeJsonExt(loadedJsonFile.name)}
/>
)}
</For>
<div style={{ margin: '10px 0 10px 0' }}>
<input onClick={() => props.onCreateNewFile()} type="button" value="Create new file..." />
</div>
{props.children}
</MainMenu>
);
};
export default QuestsFiles;
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/MissionZoneIdInput/index.tsx
|
<reponame>Procedural-Fox/aki_CustomQuestsEditor
import { Component, createEffect, createMemo, createSignal } from 'solid-js';
import { DeepReadonly } from 'solid-js/store';
import { allZonesByMap } from '../../../helpers/allZonesByMap';
import { MissionPlaceBeacon, MissionPlaceItem, MissionPlaceSignalJammer } from '../../../types';
import { MissionUpdator } from '../QuestMissionsForm/types';
import { QuestSimpleDropdown } from '../QuestSimpleDropdown';
const ALL_CONCERNED_MAP = Object.keys(allZonesByMap);
const findMapForZoneId = (zoneId: string): string | undefined => {
return ALL_CONCERNED_MAP.find(mapId => allZonesByMap[mapId].includes(zoneId));
};
type CompatibleMission = MissionPlaceItem | MissionPlaceBeacon | MissionPlaceSignalJammer;
type Props = {
mission: DeepReadonly<CompatibleMission>;
updateMission: MissionUpdator<CompatibleMission>;
};
export const MissionZoneIdInput: Component<Props> = props => {
const [selectedMap, setSelectedMap] = createSignal('bigmap');
const [mapChangedByUser, setMapChangedByUser] = createSignal(0);
const availableZones = createMemo(() => {
return allZonesByMap[selectedMap()];
});
createEffect(prev => {
if (prev !== undefined && prev !== mapChangedByUser()) {
props.updateMission(m => ({ ...m, zone_id: allZonesByMap[selectedMap()][0] }));
}
return mapChangedByUser();
});
createEffect(prev => {
if (prev !== props.mission.zone_id) {
const map = findMapForZoneId(props.mission.zone_id);
if (map) {
setSelectedMap(map);
}
}
return props.mission.zone_id;
});
return (
<>
<QuestSimpleDropdown
fieldName="map"
formIndex={-1}
values={ALL_CONCERNED_MAP}
selectedValue={selectedMap()}
onValueChanged={v => {
setSelectedMap(v);
setMapChangedByUser(x => x + 1);
}}
/>
<QuestSimpleDropdown
fieldName="zone_id"
fieldLink="https://github.com/guillaumearm/aki_CustomQuests/blob/master/docs/ALL_ZONES.md"
formIndex={-1}
values={availableZones()}
selectedValue={props.mission.zone_id}
onValueChanged={v => {
props.updateMission(m => ({ ...m, zone_id: v }));
}}
/>
</>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/helpers/allPlacesByMap.ts
|
export const allPlacesByMap: Record<string, string[]> = {
bigmap: [
'gazel',
'dead_posylni',
'vremyan_case',
'room206_water',
'vaz_feld',
'room114',
'room214',
'bomj_place',
'place_SADOVOD_03',
],
woods: ['bunker2', 'ter_015_area_1', 'huntsman_001', 'pr_scout_col', 'pr_scout_base'],
shoreline: [
'place_peacemaker_007_1_N1',
'place_peacemaker_010_3',
'place_peacemaker_004_N1',
'place_peacemaker_004_N2',
'place_peacemaker_009_2',
'place_peacemaker_009_3_N1',
'place_peacemaker_005_N1',
'place_peacemaker_005_N2',
'place_peacemaker_010_2',
'huntsman_026',
'place_peacemaker_008_4_N1',
'place_peacemaker_008_4_N2',
'place_peacemaker_001',
'place_SIGNAL_01_1',
'place_SIGNAL_01_2',
'place_meh_sanitar_room',
'huntsman_024_1',
'huntsman_024_2',
'huntsman_024_3',
'ter_023_area_1_1',
'ter_023_area_3_1',
'ter_023_area_2_1',
],
interchange: [
'place_SALE_03_AVOKADO',
'place_SALE_03_KOSTIN',
'place_SALE_03_TREND',
'place_SALE_03_DINO',
'place_SALE_03_TOPBRAND',
],
factory: [
'pumproom',
'place_pacemaker_SCOUT_01',
'place_pacemaker_SCOUT_02',
'place_pacemaker_SCOUT_03',
'ter_017_area_1',
'locked_office',
],
lighthouse: [
'qlight_pr1_heli1_find',
'qlight_hunt_fr_find',
'qlight_find_light_merchant',
'qlight_find_crushed_heli',
'qlight_find_scav_group1',
],
rezervbase: [
'huntsman_029',
'prapor_024_area_2',
'prapor_024_area_1',
'tadeush_bmp2_area_check_2',
'tadeush_bmp2_area_check_11',
'tadeush_bmp2_area_check_12',
'tadeush_bmp2_area_check_13',
'tadeush_stryker_area_check_3',
'tadeush_stryker_area_check_4',
'tadeush_t90_area_check_1',
'mechanik_exit_area_1',
'prapor_025_area_1',
'prapor_025_area_2',
'prapor_025_area_3',
'prapor_025_area_4',
'prapor_025_area_5',
'baraholshik_arsenal_area_1',
'baraholshik_dejurniy_area_2',
'baraholshik_arsenal_area_3',
'baraholshik_arsenal_area_4',
'baraholshik_arsenal_area_5',
],
laboratory: ['peace_027_area'],
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/QuestMissionsForm/types.ts
|
<gh_stars>1-10
import { DeepReadonly } from 'solid-js/store';
import { QuestMission } from '../../../types';
type Updator<T> = (fn: (x: T) => T) => void;
export type MissionUpdator<T = QuestMission> = Updator<DeepReadonly<T>>;
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/QuestStringInput/index.tsx
|
import { Component, createEffect, createMemo, createSignal, For, Match, Switch } from 'solid-js';
import { ALL_LOCALES } from '../../../helpers/locales';
import { isValidLocale } from '../../../helpers/queststring_validation';
import { QuestString, LocaleName, QuestStringUpdator } from '../../../types';
type Props = {
formIndex: number;
updateQuestString: QuestStringUpdator;
questString?: QuestString;
fieldName: string;
uniqId: string; // questId concatened to the file index
};
type SelectEvent = Event & { target: Element; currentTarget: HTMLSelectElement };
export const QuestStringInput: Component<Props> = props => {
const [currentLocale, setCurrentLocale] = createSignal<LocaleName | null>(null);
createEffect(questId => {
if (questId !== props.uniqId && typeof props.questString === 'object') {
const localeName = (Object.keys(props.questString)[0] as LocaleName) ?? null;
if (localeName) {
setCurrentLocale(localeName);
}
}
return props.uniqId;
});
const onChangeWhenString = (questString: QuestString | undefined) => (e: SelectEvent) => {
const selectedValue = e.currentTarget.value;
if (isValidLocale(selectedValue)) {
setCurrentLocale(selectedValue);
props.updateQuestString(() => ({ [selectedValue]: questString }));
}
};
const onChangeWhenObject = (e: SelectEvent) => {
const selectedValue = e.currentTarget.value;
if (isValidLocale(selectedValue)) {
setCurrentLocale(selectedValue);
}
};
const inputValue = createMemo(() => {
if (typeof props.questString === 'string') {
return props.questString;
}
const locale = currentLocale();
if (locale && typeof props.questString === 'object') {
return props.questString[locale] ?? '';
}
return '';
});
const onInputChange = (e: InputEvent & { currentTarget: HTMLInputElement; target: Element }) => {
const value = e.currentTarget.value;
if (typeof props.questString === 'string' || props.questString === undefined) {
props.updateQuestString(() => value);
return;
}
const locale = currentLocale();
if (locale && typeof props.questString === 'object') {
props.updateQuestString(questString => {
if (!questString || typeof questString === 'string') {
return { [locale]: value };
}
return { ...questString, [locale]: value };
});
}
};
const renderLocaleValue = (localeName: LocaleName) => {
if (typeof props.questString === 'object') {
const locale = props.questString[localeName];
return locale ? ` : ${props.questString[localeName]}` : '';
}
return '';
};
return (
<div style={{ 'padding-left': '15px', 'padding-top': '15px' }}>
<label
style={{
display: 'inline-block',
float: 'left',
clear: 'left',
width: '180px',
'text-align': 'left',
'margin-right': '10px',
}}
for={`form_${props.fieldName}`}
>
{props.fieldName}:{' '}
</label>
<input
tabIndex={props.formIndex}
style={{ display: 'inline-block', float: 'left', width: '180px' }}
onInput={onInputChange}
value={inputValue()}
type="text"
id={`form_${props.fieldName}`}
/>
<Switch>
<Match when={typeof props.questString === 'string' || props.questString === undefined}>
<select
tabIndex={props.formIndex + 1}
onChange={onChangeWhenString(props.questString)}
style={{}}
>
<option value="set_locale">Set locale...</option>
<For each={ALL_LOCALES}>
{localeName => <option value={localeName}>{localeName}</option>}
</For>
</select>
</Match>
<Match when={typeof props.questString === 'object'}>
<select
tabIndex={props.formIndex + 1}
onChange={onChangeWhenObject}
style={{ 'max-width': '180px' }}
>
<For each={ALL_LOCALES}>
{localeName => (
<option selected={currentLocale() === localeName} value={localeName}>
{localeName}
{renderLocaleValue(localeName)}
</option>
)}
</For>
</select>
</Match>
</Switch>
</div>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/QuestItemInput/index.tsx
|
<gh_stars>0
import { take } from 'ramda';
import { Component, createEffect, createMemo, createSignal, For, Show } from 'solid-js';
let ALL_TEMPLATES: (readonly [string, { Name: string }])[] = [];
let LOCALES_TEMPLATES: Record<string, { Name: string } | undefined> = {};
import('../../../assets/db/locales/global/en.json').then(enLocales => {
const localesTemplates = enLocales.default.templates;
LOCALES_TEMPLATES = localesTemplates;
ALL_TEMPLATES = Object.keys(localesTemplates).map(
k => [k, localesTemplates[k as keyof typeof localesTemplates]] as const,
);
});
type Props = {
index?: number;
uniqQuestId: string;
fieldName: string;
onChange: (v: string) => void;
value: string;
count?: number;
onCounterChanged?: (c: number) => void;
onRemove?: () => void;
};
export const QuestItemInput: Component<Props> = props => {
const [searchEnabled, setSearchEnabled] = createSignal(false);
const [searchResults, setSearchResults] = createSignal<(readonly [string, string])[]>([]);
const uniqId = createMemo(() => `${props.uniqQuestId}_${props.fieldName}_${String(props.index)}`);
createEffect(() => {
setSearchEnabled(false);
setSearchResults([]);
return uniqId();
});
const nameItem = createMemo(() => {
return LOCALES_TEMPLATES[props.value]?.Name ?? undefined;
});
return (
<>
<div style={{ 'margin': '15px 0 0 0', padding: '15px', display: 'flex', 'flex-wrap': 'wrap', 'background-color': '#333333' }}>
<label
style={{
display: 'inline-block',
float: 'left',
clear: 'left',
}}
>
{props.fieldName ? `${props.fieldName} ` : ''}
</label>
<input
title={nameItem()}
placeholder="Type item id..."
style={{ width: '320px' }}
disabled={searchEnabled()}
type="text"
value={props.value}
onChange={e => props.onChange(e.currentTarget.value)}
/>
<Show when={props.onCounterChanged !== undefined}>
<input
onInput={e => props.onCounterChanged?.(Number(e.currentTarget.value))}
style={{ width: '100px' }}
value={props.count}
type="number"
min="0"
/>
</Show>
<input
type="button"
value={searchEnabled() ? 'Ok' : 'Search...'}
onClick={() => {
const enabled = searchEnabled();
if (enabled) {
setSearchResults([]);
}
setSearchEnabled(!enabled);
}}
/>
<Show when={props.onRemove}>
<input
type="button"
value={'Remove'}
className={'delete-button'}
onClick={() => {
setSearchResults([]);
setSearchEnabled(false);
props.onRemove?.();
}}
/>
</Show>
</div>
<Show when={searchEnabled()}>
<div
style={{
'margin': '15px 0 0 0', padding: '15px', display: 'flex', 'flex-direction': 'column', 'background-color': '#333333'
}}
>
<input
onInput={e => {
const value = e.currentTarget.value;
const searchResult = ALL_TEMPLATES.filter(([, template]) => {
if (typeof template !== 'object') {
return false;
}
return template.Name.toLowerCase().includes(value.trim().toLowerCase());
}).map(([id, template]) => [id, template.Name] as const);
setSearchResults(take(50)(searchResult));
}}
type="text"
placeholder="Search for item..."
/>
<div style={{ padding: '10px', color: 'black' }}>
<For each={searchResults()}>
{([id, name]) => {
return (
<div
onClick={() => props.onChange(id)}
style={{
cursor: 'pointer',
margin: '1px',
color: id === props.value ? 'white' : 'inherit',
'background-color': id === props.value ? 'green' : 'white',
}}
>
{name}
</div>
);
}}
</For>
</div>
</div>
</Show>
</>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/MissionAcceptedItemsInput/index.tsx
|
import { remove, update } from 'ramda';
import { Component, For } from 'solid-js';
import { QuestItemInput } from '../QuestItemInput';
type ItemIds = readonly string[];
type Props = {
items: ItemIds;
updateItems: (fn: (r: ItemIds) => ItemIds) => void;
uniqId: string;
};
export const MissionAcceptedItemsInput: Component<Props> = props => {
return (
<div style={{ padding: '15px' }}>
<label
style={{
display: 'inline-block',
// float: 'left',
clear: 'left',
width: '180px',
'text-align': 'right',
'margin-right': '10px',
'margin-bottom': '10px',
}}
>
{`accepted_items: `}
</label>
<input
onClick={() => {
props.updateItems(items => [...items, '']);
}}
type="button"
value="Add item"
/>
<For each={props.items}>
{(itemId, i) => (
<QuestItemInput
index={i()}
fieldName=""
uniqQuestId={`${props.uniqId}_${i()}`}
value={itemId}
onChange={newId => {
props.updateItems(items => {
return update(i(), newId, items);
});
}}
onRemove={() => {
props.updateItems(items => {
return remove(i(), 1, items);
});
}}
/>
)}
</For>
</div>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/DownloadButton/index.tsx
|
import { pipe } from 'ramda';
import { Component, createMemo } from 'solid-js';
import { DeepReadonly } from 'solid-js/store';
import { LoadedJsonFile, QuestData } from '../../types';
type DownloadButtonProps = {
tabIndex?: number;
loadedJsonFiles: DeepReadonly<LoadedJsonFile[]>;
selectedQuestFile: null | number;
};
const ignoreQuestsWithEmptyId = (data: DeepReadonly<QuestData[]>): DeepReadonly<QuestData[]> => {
return data.filter(q => {
return q.id !== '';
});
};
const ignoreRewardsItemWithEmptyId = (
data: DeepReadonly<QuestData[]>,
): DeepReadonly<QuestData[]> => {
return data.map(quest => {
if (quest.rewards && quest.rewards.items) {
const newItems: Record<string, number> = {};
const items = quest.rewards.items;
Object.keys(items).forEach(itemId => {
if (itemId !== '') {
newItems[itemId] = items[itemId];
}
});
return { ...quest, rewards: { ...quest.rewards, items: newItems } };
}
return quest;
});
};
const ignoreAcceptedItemsWithEmptyId = (
data: DeepReadonly<QuestData[]>,
): DeepReadonly<QuestData[]> => {
return data.map(quest => {
if (quest.missions) {
const filteredMissions = quest.missions.map(m => {
if ('accepted_items' in m) {
return { ...m, accepted_items: m.accepted_items.filter(itemId => Boolean(itemId)) };
}
return m;
});
return { ...quest, missions: filteredMissions };
}
return quest;
});
};
const filterData = (data: DeepReadonly<QuestData[]>): DeepReadonly<QuestData[]> => {
return pipe(
ignoreRewardsItemWithEmptyId,
ignoreQuestsWithEmptyId,
ignoreAcceptedItemsWithEmptyId,
)(data);
};
const convertObjectToDataString = (data: DeepReadonly<QuestData[]>) => {
const filteredData = filterData(data);
return (
'data:text/json;charset=utf-8,' + encodeURIComponent(JSON.stringify(filteredData, undefined, 4))
);
};
export const DownloadButton: Component<DownloadButtonProps> = props => {
const file = createMemo(() => props.loadedJsonFiles[props.selectedQuestFile ?? -1]);
const fileName = createMemo(() => file()?.name ?? '');
const fileData = createMemo(() => convertObjectToDataString(file()?.data ?? []));
return (
<a style={{}} download={fileName()} href={fileData()}>
<button tabIndex={props.tabIndex} className={'download-button'} type="button">{`Download ${fileName()}`}</button>
</a>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/forms/QuestMissionsForm/MissionGiveItemForm.tsx
|
import { Component, createMemo } from 'solid-js';
import { DeepReadonly } from 'solid-js/store';
import { MissionGiveItem } from '../../../types';
import { MissionAcceptedItemsInput } from '../MissionAcceptedItemsInput';
import { QuestFoundInRaidOnly } from '../QuestFoundInRaidOnly';
import { QuestNumberInput } from '../QuestNumberInput';
import { QuestStringInput } from '../QuestStringInput';
import { MissionUpdator } from './types';
type Props = {
questId: string;
index: number;
mission: DeepReadonly<MissionGiveItem>;
updateMission: MissionUpdator<MissionGiveItem>;
};
export const MissionGiveItemForm: Component<Props> = props => {
const uniqId = createMemo(() => {
return `${props.questId}_give_item_${props.index}`;
});
const missionCount = createMemo(() => {
return props.mission.count ?? 0;
});
return (
<>
{props.children}
<QuestStringInput
formIndex={-1}
updateQuestString={fn => props.updateMission(m => ({ ...m, message: fn(m.message) }))}
uniqId={uniqId()}
questString={props.mission.message}
fieldName="message"
/>
<QuestNumberInput
fieldName="count"
value={missionCount()}
setValue={c => props.updateMission(m => ({ ...m, count: c }))}
/>
<QuestFoundInRaidOnly mission={props.mission} updateMission={props.updateMission} />
<MissionAcceptedItemsInput
updateItems={fn => {
props.updateMission(m => ({ ...m, accepted_items: fn(m.accepted_items) }));
}}
items={props.mission.accepted_items}
uniqId={uniqId()}
/>
</>
);
};
|
Procedural-Fox/aki_CustomQuestsEditor
|
src/components/DndJsonHandler/index.tsx
|
import { Component, onCleanup, Signal } from 'solid-js';
import { noop } from '../../utils/noop';
type Props = {
isDraggingSignal: Signal<boolean>;
onDropJson?: (fileName: string, jsonObject: object) => void;
onDropInvalidJson?: (err: unknown) => void;
};
const DndJsonHandler: Component<Props> = props => {
const onDropJson = props.onDropJson ?? noop;
const onDropInvalidJson = props.onDropInvalidJson ?? noop;
const [, setIsDragging] = props.isDraggingSignal;
setIsDragging(false);
const element = document.getElementById('root');
if (!element) {
console.error('no root element found');
return null;
}
const dragEnter = (event: DragEvent) => {
setIsDragging(true);
event.preventDefault();
};
const dragLeave = (event: DragEvent) => {
setIsDragging(false);
event.preventDefault();
};
const dragOver = (event: DragEvent) => {
setIsDragging(true);
event.preventDefault();
};
const dragDrop = (event: DragEvent) => {
setIsDragging(false);
if (event.dataTransfer) {
const file = event.dataTransfer.files[0];
const reader = new FileReader();
reader.onloadend = function () {
if (typeof this.result === 'string') {
try {
const data = JSON.parse(this.result);
onDropJson(file.name, data);
} catch (err) {
onDropInvalidJson(err);
}
}
};
reader.readAsText(event.dataTransfer.files[0]);
}
event.preventDefault();
};
element.addEventListener('dragenter', dragEnter);
element.addEventListener('dragleave', dragLeave);
element.addEventListener('dragover', dragOver);
element.addEventListener('drop', dragDrop);
onCleanup(() => {
element.removeEventListener('dragenter', dragEnter);
element.removeEventListener('dragleave', dragLeave);
element.removeEventListener('dragover', dragOver);
element.removeEventListener('drop', dragDrop);
});
return null;
};
export default DndJsonHandler;
|
fabianschwarzfritz/colorful-oled-js
|
playground.ts
|
import { Board } from "johnny-five"
const board = new Board()
import { ColorfulOled, DefaultColors } from "./index"
const oled = new ColorfulOled(board, 0, {
width: 128,
height: 128,
})
oled.drawPixel(5, 5, DefaultColors.BLUE)
|
fabianschwarzfritz/colorful-oled-js
|
index.ts
|
import { Board, Pin } from "johnny-five"
enum TransferType {
Command = 0x00,
Data = 0x40
}
enum Command {
SET_COLUMN_START_ADDRESS = 0x15,
SET_COLUMN_END_ADDRESS = 0x15,
SET_ROW_START_ADDRESS = 0x75 ,
SET_ROW_END_ADDRESS = 0x75,
SET_CONTRAST_COLOR_A = 0x81,
SET_CONTRAST_COLOR_B = 0x82,
SET_CONTRAST_COLOR_C = 0x83,
MASTER_CURRENT_CONTROL = 0x87,
SET_SECOND_PRE_CHARGE_SPEED_A = 0x8A,
SET_SECOND_PRE_CHARGE_SPEED_B = 0x8B,
SET_SECOND_PRE_CHARGE_SPEED_C = 0x8C,
REMAP_AND_COLOR_DEPTH = 0xA0,
SET_DISPLAY_START_LINE = 0xA1,
SET_DISPLAY_OFFSET = 0xA2,
SET_DISPLAY_MODE_NORMAL = 0xA4,
SET_DISPLAY_MODE_ENTIRE_ON = 0xA5,
SET_DISPLAY_MODE_ENTIRE_OFF = 0xA6,
SET_DISPLAY_MODE_INVERSE = 0xA7,
SET_MULTIPLEX_RATIO = 0xA8,
DIM_MODE = 0xAB,
SET_MASTER_CONFIGURATION = 0xAD,
SET_DISPLAY_ON_DIM_MODE = 0xAC,
SET_DISPLAY_OFF = 0xAE,
SET_DISPLAY_ON_NORMAL_MODE = 0xAF,
POWER_SAVE_MODE = 0xB0,
PHASE_PERIOD_ADJUSTMENT = 0xB1,
DISPLAY_CLOCK_DIVIDER = 0xB3,
SET_GRAYSCALE_TABLE = 0xB8,
ENABLE_LINEAR_GRAYSCALE_TABLE = 0xB9,
SET_PRECHARGE_LEVEL = 0xBB,
NO_OPERATION_1 = 0xBC,
NO_OPERATION_2 = 0xBD,
SET_VOLTAGE = 0xBE,
NO_OPERATION_3 = 0xE3,
SET_COMMAND_LOCK = 0xFD,
DRAW_LINE = 0x21,
DRAW_RECTANGLE = 0x22,
COPY = 0x23,
DIM_WINDOW = 0x24,
CLEAR_WINDOW = 0x25,
FILL_ENABLE_DISABLE = 0x26,
CONTINUOUS_SCROLLING = 0x27,
DEACTIVATE_SCROLLING = 0x2E,
ACTIVATE_SCROLLING = 0x2F,
}
export enum DefaultColors {
RED = 0xF00,
GREEN = 0x0F0,
BLUE = 0x00F,
}
interface Options {
width?: number;
height?: number;
}
export class ColorfulOled {
private readonly board: Board
private readonly ADDRESS: number
private readonly WIDTH: number
private readonly HEIGHT: number
public constructor(board: Board, address: number, options: Options) {
this.board = board
this.ADDRESS = address
this.WIDTH = options.width || 128
this.HEIGHT = options.height || 128
this._initialize()
}
private _initialize() {
// TODO check initalization routine when hardware has arrived.
// Routine template: https://github.com/Seeed-Studio/RGB_OLED_SSD1331/blob/master/SSD1331.cpp
this._transferCommand(Command.SET_DISPLAY_OFF)
this._transferCommand(Command.SET_CONTRAST_COLOR_A, 0x91)
this._transferCommand(Command.SET_CONTRAST_COLOR_B, 0x50)
this._transferCommand(Command.SET_CONTRAST_COLOR_C, 0x7D)
this._transferCommand(Command.MASTER_CURRENT_CONTROL, 0x06)
this._transferCommand(Command.SET_SECOND_PRE_CHARGE_SPEED_A, 0x64)
this._transferCommand(Command.SET_SECOND_PRE_CHARGE_SPEED_B, 0x78)
this._transferCommand(Command.SET_SECOND_PRE_CHARGE_SPEED_C, 0x64)
this._transferCommand(Command.REMAP_AND_COLOR_DEPTH, 0x72)
this._transferCommand(Command.SET_DISPLAY_START_LINE, 0x0)
this._transferCommand(Command.SET_DISPLAY_OFFSET, 0x0)
this._transferCommand(Command.SET_DISPLAY_MODE_NORMAL)
this._transferCommand(Command.SET_MULTIPLEX_RATIO, 0x3F)
this._transferCommand(Command.SET_MASTER_CONFIGURATION, 0x8E)
this._transferCommand(Command.POWER_SAVE_MODE, 0x00)
this._transferCommand(Command.PHASE_PERIOD_ADJUSTMENT, 0x31)
this._transferCommand(Command.DISPLAY_CLOCK_DIVIDER, 0xF0)
this._transferCommand(Command.SET_PRECHARGE_LEVEL, 0x3A)
this._transferCommand(Command.SET_VOLTAGE, 0x3E)
this._transferCommand(Command.DEACTIVATE_SCROLLING)
this._transferCommand(Command.SET_DISPLAY_ON_NORMAL_MODE)
}
private _transferCommand(command: number, value?: number) {
this._transfer(TransferType.Command, command);
if(value) {
this._transfer(TransferType.Command, value);
}
}
private _transferData(value: number) {
this._transfer(TransferType.Data, value);
}
private _transfer(type: TransferType, transferValue: number): void {
this.board.io.i2cWrite(this.ADDRESS, [type, transferValue])
}
private _read(fn: (data: number) => void): void {
this.board.io.i2cReadOnce(this.ADDRESS, 1, (data: number) => {
fn(data)
})
}
public drawPixel(x: number, y: number, color: DefaultColors): void {
if (x < 0 || this.WIDTH <= x || y < 0 || this.HEIGHT <= y) {
throw new Error("Invalid x or y position")
}
this._transferCommand(Command.SET_COLUMN_START_ADDRESS, x);
this._transferCommand(Command.SET_ROW_START_ADDRESS, y);
this._transferData(color);
}
public drawLine(x0: number, y0: number, x1: number, y1: number, color: DefaultColors): void {
if (x0 < 0 || this.WIDTH <= x0) {
throw new Error("Invalid x0 position")
}
if (y0 < 0 || this.HEIGHT <= y0) {
throw new Error("Invalid y0 position")
}
if (x1 < 0 || this.WIDTH <= x1) {
throw new Error("Invalid x1 position")
}
if (y1 < 0 || this.HEIGHT <= y1) {
throw new Error("Invalid y1 position")
}
this._transferCommand(Command.DRAW_LINE);
this._transferData(x0);
this._transferData(y0);
this._transferData(x1);
this._transferData(y1);
this._transferData(color);
}
public turnOffDisplay(): void {
this._transferCommand(Command.SET_DISPLAY_OFF)
}
public turnOnDisplay(): void {
this._transferCommand(Command.SET_DISPLAY_ON_NORMAL_MODE)
}
}
|
fabianschwarzfritz/colorful-oled-js
|
test/test.ts
|
import { Board } from "johnny-five"
import { ColorfulOled } from "./../index"
var sinon = require('sinon');
describe('Colorful Oled', function() {
it('#constructor initializes display', function() {
const board = sinon.mock(Board);
board.io = sinon.mock();
board.io.i2cWrite = sinon.spy();
const oled = new ColorfulOled(board, 10, {});
sinon.assert.calledWith(board.io.i2cWrite, 10, [0x00, 0xAE]);
});
});
|
Paul-Long/virtual-dom-simple
|
src/vite-env.d.ts
|
<reponame>Paul-Long/virtual-dom-simple
/// <reference types="vite/client" />
interface ElementNode {
tag: string;
props: object;
key?: string;
text?: string;
children?: ElementNode[] | string[]
}
|
Paul-Long/virtual-dom-simple
|
src/App.tsx
|
<gh_stars>0
import React, {CSSProperties} from 'react'
interface AppProps {
title: string;
style?: CSSProperties
}
function App(props: AppProps) {
return (
<div className="App" style={props.style}>
<div id="realDom">
<div id="real-container">
<p>{props.title}</p>
<div>cannot update</div>
<ul>
<li className="item">Item 1</li>
<li className="item">Item 2</li>
<li className="item">Item 3</li>
</ul>
</div>
</div>
<div id="virtualDom" />
</div>
)
}
export default App
|
Paul-Long/virtual-dom-simple
|
src/virtual-dom/patch.ts
|
<filename>src/virtual-dom/patch.ts
export function patch() {
}
|
Paul-Long/virtual-dom-simple
|
src/virtual-dom/diff.ts
|
function diffProps() {
}
function diffChildren() {
}
export function diff(oldNode: ElementNode, newNode: ElementNode) {
if (oldNode === newNode) {
return;
}
if (oldNode.tag === newNode.tag && oldNode.key === newNode.key) {
// change
diffProps();
diffChildren()
}
if (oldNode.tag !== newNode.tag) {
// replace
}
}
|
Paul-Long/virtual-dom-simple
|
src/Main.tsx
|
<reponame>Paul-Long/virtual-dom-simple
import React from 'react'
import ReactDOM from 'react-dom'
import {el} from './virtual-dom/element'
import './index.css'
import App from './App'
const app = <App title='Virtual DOM' style={{width: '100%'}} />;
console.log(app)
ReactDOM.render(
<React.StrictMode>
{app}
</React.StrictMode>,
document.getElementById('root')
)
function renderVirtualDom() {
const tree = el('div', { id: 'virtual-container' }, 'key', [
el('p', {},'key-1', ['Virtual DOM']),
el('div', {},'key-2', ['before update']),
el('ul', {}, 'key-3', [
el('li', { class: 'item' },'key-3-1', ['Item 1']),
el('li', { class: 'item' },'key-3-2', ['Item 2']),
el('li', { class: 'item' },'key-3-3', ['Item 3']),
])
]);
const root = tree.render();
document.getElementById('virtualDom')?.appendChild(root);
}
renderVirtualDom();
|
Paul-Long/virtual-dom-simple
|
src/virtual-dom/element.ts
|
<reponame>Paul-Long/virtual-dom-simple<gh_stars>0
export function el(tag: string, props: Record<string, any>, key: string, children: ElementNode[] | string[]) {
return new Element({tag, props, key, children})
}
class Element implements ElementNode {
children: ElementNode[] | string[] = [];
props: object = {};
key?: string = '';
tag: string = '';
text?: string;
constructor(props: ElementNode) {
this.key = props.key;
this.tag = props.tag;
this.props = props.props;
this.text = props.text;
this.children = props.children || []
}
render() {
const el = document.createElement(this.tag) as HTMLElement
const props: Record<string, any> = this.props;
for (const key in props) {
setAttr(el, key, props[key]);
}
if (this.children.length > 0) {
this.children.forEach((child) => {
if (child instanceof Element) {
el.appendChild(child.render())
}
if (typeof child === 'string') {
el.appendChild(document.createTextNode(child));
}
})
}
return el;
}
}
function setAttr(node: HTMLElement & {value?: any}, key: string, value: any) {
switch (key) {
case 'style':
node.style.cssText = value;
break;
case 'value': {
const tagName = node.tagName.toLowerCase() || '';
if (tagName === 'input' || tagName === 'textarea') {
node.value = value;
} else {
node.setAttribute(key, value);
}
break;
}
default:
node.setAttribute(key, value);
break;
}
}
|
CadeXu/xiaomi-mall-mobile
|
web/shims.d.ts
|
<filename>web/shims.d.ts<gh_stars>0
declare module 'swiper/swiper-bundle';
declare module 'nprogress';
declare module 'dompurify'
|
webilix/regex-library
|
dist/lib/password.d.ts
|
<reponame>webilix/regex-library<filename>dist/lib/password.d.ts
export declare const PASSWORD: {
get: (length?: number, forceLowerCase?: boolean, forceUpperCase?: boolean, forceNumber?: boolean, fullLine?: boolean, flags?: string | undefined) => RegExp;
verify: (text: string, length?: number, forceLowerCase?: boolean, forceUpperCase?: boolean, forceNumber?: boolean) => boolean;
};
//# sourceMappingURL=password.d.ts.map
|
webilix/regex-library
|
dist/test/ip4.test.d.ts
|
export {};
//# sourceMappingURL=ip4.test.d.ts.map
|
webilix/regex-library
|
dist/test/mobile.test.d.ts
|
export {};
//# sourceMappingURL=mobile.test.d.ts.map
|
webilix/regex-library
|
src/test/email.test.ts
|
import { rxEmail } from '../regex';
import { testFind, testReplace, testVerify } from './_';
const valid: string[] = ['<EMAIL>', '<EMAIL>', '<EMAIL>', '<EMAIL>'];
const invalid: string[] = ['email@', <EMAIL>', 'email.domain.com'];
testVerify('EMAIL', rxEmail, valid, invalid);
testFind('EMAIL', rxEmail, valid, invalid);
testReplace('EMAIL', rxEmail, valid, invalid);
|
webilix/regex-library
|
src/lib/username.ts
|
<reponame>webilix/regex-library
import { get, verify } from '../method';
import { rxUsername } from '../regex';
export const USERNAME = {
get: (
length: number = 3,
useDash: boolean = true,
useDot: boolean = true,
fullLine: boolean = true,
flags?: string,
): RegExp => get(rxUsername(length, useDash, useDot), fullLine, flags),
verify: (text: string, length: number = 3, useDash: boolean = true, useDot: boolean = true): boolean =>
verify(rxUsername(length, useDash, useDot), text),
};
|
webilix/regex-library
|
src/lib/ip4.ts
|
<reponame>webilix/regex-library
import { find, get, replace, verify } from '../method';
import { rxIP4 } from '../regex';
export const IP4 = {
get: (fullLine: boolean = true, flags?: string): RegExp => get(rxIP4, fullLine, flags),
verify: (text: string): boolean => verify(rxIP4, text),
find: (text: string): string[] => find(rxIP4, text),
replace: (text: string, replaceWith: string = ''): string => replace(rxIP4, text, replaceWith),
};
|
webilix/regex-library
|
dist/test/date.test.d.ts
|
<reponame>webilix/regex-library
export {};
//# sourceMappingURL=date.test.d.ts.map
|
webilix/regex-library
|
dist/lib/url.d.ts
|
<filename>dist/lib/url.d.ts
export declare const URL: {
get: (full?: boolean, fullLine?: boolean, flags?: string | undefined) => RegExp;
verify: (text: string, full?: boolean) => boolean;
find: (text: string, full?: boolean) => string[];
replace: (text: string, replaceWith?: string, full?: boolean) => string;
};
//# sourceMappingURL=url.d.ts.map
|
webilix/regex-library
|
src/lib/password.ts
|
<reponame>webilix/regex-library<filename>src/lib/password.ts
import { get, verify } from '../method';
import { rxPassword } from '../regex';
export const PASSWORD = {
get: (
length: number = 8,
forceLowerCase: boolean = true,
forceUpperCase: boolean = true,
forceNumber: boolean = true,
fullLine: boolean = true,
flags?: string,
): RegExp => get(rxPassword(length, forceLowerCase, forceUpperCase, forceNumber), fullLine, flags),
verify: (
text: string,
length: number = 8,
forceLowerCase: boolean = true,
forceUpperCase: boolean = true,
forceNumber: boolean = true,
): boolean => verify(rxPassword(length, forceLowerCase, forceUpperCase, forceNumber), text),
};
|
webilix/regex-library
|
src/test/_.ts
|
<gh_stars>0
import { find, replace, verify } from '../method';
export const testVerify = (title: string, pattern: string, valid: string[], invalid: string[]) => {
test(`${title}: verify`, () => {
valid.forEach((value: string) => {
const test: boolean = verify(pattern, value);
expect(test).toBe(true);
});
invalid.forEach((value: string) => {
const test: boolean = verify(pattern, value);
expect(test).toBe(false);
});
});
};
export const testFind = (title: string, pattern: string, valid: string[], invalid: string[]) => {
test(`${title}: find`, () => {
const test1: string[] = find(pattern, valid.join(' '));
expect(test1.length).toBe(valid.length);
const test2: string[] = find(pattern, valid.join('\n'));
expect(test2.length).toBe(valid.length);
const test3: string[] = find(pattern, invalid.join(' '));
expect(test3.length).toBe(0);
const test4: string[] = find(pattern, invalid.join('\n'));
expect(test4.length).toBe(0);
});
};
export const testReplace = (title: string, pattern: string, valid: string[], invalid: string[]) => {
test(`${title}: replace`, () => {
const test1: string = replace(pattern, valid.join(' '));
expect(test1.length).toBe(valid.length - 1);
const test2: string = replace(pattern, valid.join('\n'));
expect(test2.length).toBe(valid.length - 1);
const test3: string = replace(pattern, invalid.join(' '));
expect(test3).toBe(invalid.join(' '));
const test4: string = replace(pattern, invalid.join('\n'));
expect(test4).toBe(invalid.join('\n'));
});
};
|
webilix/regex-library
|
src/lib/url.ts
|
import { find, get, replace, verify } from '../method';
import { rxUrl } from '../regex';
export const URL = {
get: (full: boolean = false, fullLine: boolean = true, flags?: string): RegExp => get(rxUrl(full), fullLine, flags),
verify: (text: string, full: boolean = false): boolean => verify(rxUrl(full), text),
find: (text: string, full: boolean = false): string[] => find(rxUrl(full), text),
replace: (text: string, replaceWith: string = '', full: boolean = false): string =>
replace(rxUrl(full), text, replaceWith),
};
|
webilix/regex-library
|
src/lib/time.ts
|
<filename>src/lib/time.ts
import { find, get, replace, verify } from '../method';
import { rxTime } from '../regex';
export const TIME = {
get: (fullLine: boolean = true, flags?: string): RegExp => get(rxTime, fullLine, flags),
verify: (text: string): boolean => verify(rxTime, text),
find: (text: string): string[] => find(rxTime, text),
replace: (text: string, replaceWith: string = ''): string => replace(rxTime, text, replaceWith),
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.