First working version

This commit is contained in:
Sebastian Seedorf
2022-08-08 23:12:11 +02:00
parent 78dcee42ca
commit 940149cec8
22 changed files with 12436 additions and 1586 deletions

View File

@@ -0,0 +1,6 @@
<component name="InspectionProjectProfileManager">
<profile version="1.0">
<option name="myName" value="Project Default" />
<inspection_tool class="Eslint" enabled="true" level="WARNING" enabled_by_default="true" />
</profile>
</component>

6
.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

View File

@@ -0,0 +1,33 @@
import {FC, useEffect, useState} from "react";
import Select from "react-select";
import {isNonNullable} from "../src/utils";
import details from "../res/details.json";
interface Props {
factories: string[]
onSetFactories: (factories: string[]) => void
}
const options = details.map(detail => ({
label: detail.name,
value: detail.href
}))
export const FactorySelect: FC<Props> = ({factories, onSetFactories}) => {
const [state, setState] = useState<typeof options>([])
useEffect(() => {
setState(factories
.map(factory => options.find(option => option.value === factory))
.filter(isNonNullable))
}, [factories])
return <Select
value={state}
isMulti
options={options as never}
onChange={e => {
setState(e as typeof options)
onSetFactories(e.map(s => s?.value))
}}
/>
}

View File

@@ -0,0 +1,4 @@
.grid {
display: grid;
grid-template-columns: 1fr 1fr;
}

125
components/Group.tsx Normal file
View File

@@ -0,0 +1,125 @@
import {FC, useMemo} from "react";
import {FactorySelect} from "./FactorySelect";
import {useDetails} from "../src/hooks/useDetails";
import {Entity} from "../src/types";
import styles from "./Group.module.css"
interface Props {
onRemove: () => void
onSetOutputFactories: (uids: string[]) => void
outputFactories: string[]
onSetIntermediateFactories: (uids: string[]) => void
intermediateFactories: string[]
onSetInputFactories: (uids: string[]) => void
inputFactories: string[]
onRename: (name: string) => void
onDoIgnore: (name: string) => void
name: string
doNotSuggest: string[]
}
export const Group: FC<Props> = ({
onRemove,
onRename,
onSetOutputFactories,
outputFactories,
onSetIntermediateFactories,
intermediateFactories,
onSetInputFactories,
inputFactories,
name,
doNotSuggest,
onDoIgnore
}) => {
const details = useDetails()
const inputs = useMemo<string[]>(() => {
const newData: string[] = details
.filter(detail => intermediateFactories.includes(detail.href) || outputFactories.includes(detail.href))
.flatMap(detail => Object.keys(detail.recipe?.prerequisites ?? {}))
const uniqueInputs = Array.from(new Set(newData))
return uniqueInputs
.filter(input => !intermediateFactories.includes(input) && !outputFactories.includes(input))
}, [details, intermediateFactories, outputFactories])
const suggestions = useMemo<Entity[]>(() => {
const availableIngredients = Array.from(new Set([...intermediateFactories, ...outputFactories, ...inputs, ...inputFactories]))
const selectedValues = Array.from(new Set([...intermediateFactories, ...outputFactories, ...inputFactories]))
return details
.filter(detail => {
if (!detail.recipe) return false
if (selectedValues.includes(detail.href)) return false
if (doNotSuggest.includes(detail.href)) return false
const prerequisites = Object.keys(detail.recipe?.prerequisites ?? {})
/*if (intermediateFactories.length) {
const usesInter = prerequisites.some(pre => outputFactories.includes(pre) || intermediateFactories.includes(pre))
if (!usesInter) return false
} else {
const usesEveryInput = inputs.every(inp => prerequisites.includes(inp))
if (!usesEveryInput) return false
}*/
return prerequisites.every(pre => availableIngredients.includes(pre))
})
}, [inputFactories, doNotSuggest, details, inputs, intermediateFactories, outputFactories])
const addIntermediateFactory = (uid: string) => {
onSetIntermediateFactories([...intermediateFactories, uid])
}
const addOutputFactory = (uid: string) => {
onSetOutputFactories([...outputFactories, uid])
}
return <div style={{border: "2px solid black", padding: "0.5em", margin: "1em"}}>
<div>
<h3 contentEditable={true} onBlur={event => {
event.currentTarget.innerText = event.currentTarget.innerText.trim()
onRename(event.currentTarget.innerText);
}}>
{name}
</h3>
<button onClick={onRemove} style={{display: 'block'}}>X</button>
<label>Additional Inputs</label>
<FactorySelect
factories={inputFactories}
onSetFactories={onSetInputFactories}
/>
<label>Intermediate Factories</label>
<FactorySelect
factories={intermediateFactories}
onSetFactories={onSetIntermediateFactories}
/>
<label>Output Factories</label>
<FactorySelect
factories={outputFactories}
onSetFactories={onSetOutputFactories}
/>
<div className={styles.grid}>
<div>
<h4>Inputs</h4>
<ul>
{inputs.map(input => <li key={input}><a href={'javascript:void(0)'} onClick={() => addIntermediateFactory(input)}>{input}</a></li>)}
</ul>
</div>
<div>
<h4>Suggestions</h4>
<ul>
{suggestions.map(suggestion => <li key={suggestion.href}>
<a
href={'javascript:void(0)'}
onClick={() => addOutputFactory(suggestion.href)}
onContextMenu={event => {
event.preventDefault()
onDoIgnore(suggestion.href)
}}
>
{suggestion.name}
</a>
</li>)}
</ul>
</div>
</div>
</div>
</div>
}

View File

@@ -0,0 +1,4 @@
.grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(500px, max-content));
}

94
components/Home.tsx Normal file
View File

@@ -0,0 +1,94 @@
import {FC, useCallback, useEffect, useMemo, useState} from "react";
import {useLocalStorage} from "../src/hooks/useLocalStorage";
import {Group} from "./Group";
import {FactorySelect} from "./FactorySelect";
import styles from "./Home.module.css"
import {sortByProperty} from "../src/utils";
interface Group {
name: string
factories: string[]
intermediates: string[]
inputs: string[]
}
export const HomeComponent: FC = () => {
const [newGroupValue, setNewGroupValue] = useState("New group")
const [excludedSuggestions, setExcludedSuggestions] = useLocalStorage<string[]>('excludedSuggestions', [])
const [basicValues, setBasicValues] = useLocalStorage<string[]>('basicValues', [])
const [groups, setGroups] = useLocalStorage<Group[]>('serviceGroups', [])
const [clientGroups, setClientGroups] = useState<typeof groups>([])
const doNotSuggest = useMemo<string[]>(() => {
return groups.flatMap(group => [...group.intermediates, ...group.factories, ...excludedSuggestions])
}, [groups, excludedSuggestions])
useEffect(() => setClientGroups(groups), [groups])
const removeGroup = (idx: number) => setGroups(groups => {
groups.splice(idx, 1)
return groups
})
const appendGroup = useCallback((name: string) => setGroups(groups => {
groups.push({name, factories: [], intermediates: [], inputs: []})
groups.sort(sortByProperty(group => group.name))
return groups
}), [setGroups])
const setFactories = useCallback((idx: number, uids: string[], key: 'intermediates'|'factories'|'inputs') => setGroups(groups => {
groups[idx][key] = uids
return groups
}), [setGroups])
const renameGroup = useCallback((idx: number, name: string) => setGroups(groups => {
groups[idx].name = name
groups.sort(sortByProperty(group => group.name))
return groups
}), [setGroups])
return (
<main>
<h1>Factorio Microservices</h1>
<fieldset>
<legend>Basic Values</legend>
<FactorySelect
factories={basicValues}
onSetFactories={setBasicValues}
/>
</fieldset>
<fieldset>
<legend>Ignored Values</legend>
<FactorySelect
factories={excludedSuggestions}
onSetFactories={setExcludedSuggestions}
/>
</fieldset>
<fieldset>
<legend>Add new groups</legend>
<input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)}/>
<button disabled={!newGroupValue} onClick={() => {
appendGroup(newGroupValue)
setNewGroupValue("New group")
}}>
Add group &quot;{newGroupValue}&quot;
</button>
</fieldset>
<div className={styles.grid}>
{
clientGroups.map((group, idx) => <Group
key={idx}
outputFactories={group.factories}
intermediateFactories={group.intermediates}
inputFactories={group.inputs}
name={group.name}
onRemove={() => removeGroup(idx)}
onRename={(name: string) => renameGroup(idx, name)}
onSetOutputFactories={uids => setFactories(idx, uids, 'factories')}
onSetIntermediateFactories={uids => setFactories(idx, uids, 'intermediates')}
onSetInputFactories={uids => setFactories(idx, uids, 'inputs')}
doNotSuggest={doNotSuggest}
onDoIgnore={uid => setExcludedSuggestions([...excludedSuggestions, uid])}
/>)
}
</div>
</main>
)
}

6991
package-lock.json generated Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -11,7 +11,8 @@
"dependencies": {
"next": "12.2.4",
"react": "18.2.0",
"react-dom": "18.2.0"
"react-dom": "18.2.0",
"react-select": "^5.4.0"
},
"devDependencies": {
"@types/node": "18.6.4",

View File

@@ -1,13 +0,0 @@
// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
name: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
res.status(200).json({ name: 'John Doe' })
}

View File

@@ -1,70 +1,16 @@
import type { NextPage } from 'next'
import Head from 'next/head'
import Image from 'next/image'
import styles from '../styles/Home.module.css'
import {HomeComponent} from "../components/Home";
const Home: NextPage = () => {
return (
<div className={styles.container}>
<div>
<Head>
<title>Create Next App</title>
<meta name="description" content="Generated by create next app" />
<title>Factorio Microservices</title>
<meta name="description" content="Create Factorio microservices" />
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h1 className={styles.title}>
Welcome to <a href="https://nextjs.org">Next.js!</a>
</h1>
<p className={styles.description}>
Get started by editing{' '}
<code className={styles.code}>pages/index.tsx</code>
</p>
<div className={styles.grid}>
<a href="https://nextjs.org/docs" className={styles.card}>
<h2>Documentation &rarr;</h2>
<p>Find in-depth information about Next.js features and API.</p>
</a>
<a href="https://nextjs.org/learn" className={styles.card}>
<h2>Learn &rarr;</h2>
<p>Learn about Next.js in an interactive course with quizzes!</p>
</a>
<a
href="https://github.com/vercel/next.js/tree/canary/examples"
className={styles.card}
>
<h2>Examples &rarr;</h2>
<p>Discover and deploy boilerplate example Next.js projects.</p>
</a>
<a
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
className={styles.card}
>
<h2>Deploy &rarr;</h2>
<p>
Instantly deploy your Next.js site to a public URL with Vercel.
</p>
</a>
</div>
</main>
<footer className={styles.footer}>
<a
href="https://vercel.com?utm_source=create-next-app&utm_medium=default-template&utm_campaign=create-next-app"
target="_blank"
rel="noopener noreferrer"
>
Powered by{' '}
<span className={styles.logo}>
<Image src="/vercel.svg" alt="Vercel Logo" width={72} height={16} />
</span>
</a>
</footer>
<HomeComponent/>
</div>
)
}

View File

@@ -1,4 +0,0 @@
<svg width="283" height="64" viewBox="0 0 283 64" fill="none"
xmlns="http://www.w3.org/2000/svg">
<path d="M141.04 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.46 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM248.72 16c-11.04 0-19 7.2-19 18s8.96 18 20 18c6.67 0 12.55-2.64 16.19-7.09l-7.65-4.42c-2.02 2.21-5.09 3.5-8.54 3.5-4.79 0-8.86-2.5-10.37-6.5h28.02c.22-1.12.35-2.28.35-3.5 0-10.79-7.96-17.99-19-17.99zm-9.45 14.5c1.25-3.99 4.67-6.5 9.45-6.5 4.79 0 8.21 2.51 9.45 6.5h-18.9zM200.24 34c0 6 3.92 10 10 10 4.12 0 7.21-1.87 8.8-4.92l7.68 4.43c-3.18 5.3-9.14 8.49-16.48 8.49-11.05 0-19-7.2-19-18s7.96-18 19-18c7.34 0 13.29 3.19 16.48 8.49l-7.68 4.43c-1.59-3.05-4.68-4.92-8.8-4.92-6.07 0-10 4-10 10zm82.48-29v46h-9V5h9zM36.95 0L73.9 64H0L36.95 0zm92.38 5l-27.71 48L73.91 5H84.3l17.32 30 17.32-30h10.39zm58.91 12v9.69c-1-.29-2.06-.49-3.2-.49-5.81 0-10 4-10 10V51h-9V17h9v9.2c0-5.08 5.91-9.2 13.2-9.2z" fill="#000"/>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

3075
res/details.json Normal file

File diff suppressed because it is too large Load Diff

1
res/entities.json Normal file

File diff suppressed because one or more lines are too long

4
src/hooks/useDetails.ts Normal file
View File

@@ -0,0 +1,4 @@
import {Entity} from "../types";
import details from "../../res/details.json";
export const useDetails = () => details as Entity[]

View File

@@ -0,0 +1,69 @@
import { RefObject, useEffect, useRef } from 'react'
// See: https://usehooks-ts.com/react-hook/use-isomorphic-layout-effect
import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect'
// Window Event based useEventListener interface
export function useEventListener<K extends keyof WindowEventMap>(
eventName: K,
handler: (event: WindowEventMap[K]) => void,
element?: undefined,
options?: boolean | AddEventListenerOptions,
): void
// Element Event based useEventListener interface
export function useEventListener<
K extends keyof HTMLElementEventMap,
T extends HTMLElement = HTMLDivElement,
>(
eventName: K,
handler: (event: HTMLElementEventMap[K]) => void,
element: RefObject<T>,
options?: boolean | AddEventListenerOptions,
): void
// Document Event based useEventListener interface
export function useEventListener<K extends keyof DocumentEventMap>(
eventName: K,
handler: (event: DocumentEventMap[K]) => void,
element: RefObject<Document>,
options?: boolean | AddEventListenerOptions,
): void
export function useEventListener<
KW extends keyof WindowEventMap,
KH extends keyof HTMLElementEventMap,
T extends HTMLElement | void = void,
>(
eventName: KW | KH,
handler: (
event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event,
) => void,
element?: RefObject<T>,
options?: boolean | AddEventListenerOptions,
) {
// Create a ref that stores handler
const savedHandler = useRef(handler)
useIsomorphicLayoutEffect(() => {
savedHandler.current = handler
}, [handler])
useEffect(() => {
// Define the listening target
const targetElement: T | Window = element?.current || window
if (!(targetElement && targetElement.addEventListener)) {
return
}
// Create event listener that calls handler function stored in ref
const eventListener: typeof handler = event => savedHandler.current(event)
targetElement.addEventListener(eventName, eventListener, options)
// Remove event listener on cleanup
return () => {
targetElement.removeEventListener(eventName, eventListener)
}
}, [eventName, element, options])
}

View File

@@ -0,0 +1,4 @@
import { useEffect, useLayoutEffect } from 'react'
export const useIsomorphicLayoutEffect =
typeof window !== 'undefined' ? useLayoutEffect : useEffect

View File

@@ -0,0 +1,102 @@
import {
Dispatch,
SetStateAction,
useCallback,
useEffect,
useState,
} from 'react'
// See: https://usehooks-ts.com/react-hook/use-event-listener
import { useEventListener } from './useEventListener'
declare global {
interface WindowEventMap {
'local-storage': CustomEvent
}
}
type SetValue<T> = Dispatch<SetStateAction<T>>
export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T>] {
// Get from local storage then
// parse stored json or return initialValue
const readValue = useCallback((): T => {
// Prevent build error "window is undefined" but keep keep working
if (typeof window === 'undefined') {
return initialValue
}
try {
const item = window.localStorage.getItem(key)
return item ? (parseJSON(item) as T) : initialValue
} catch (error) {
console.warn(`Error reading localStorage key “${key}”:`, error)
return initialValue
}
}, [initialValue, key])
// State to store our value
// Pass initial state function to useState so logic is only executed once
const [storedValue, setStoredValue] = useState<T>(readValue)
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue: SetValue<T> = useCallback(value => {
// Prevent build error "window is undefined" but keeps working
if (typeof window == 'undefined') {
console.warn(
`Tried setting localStorage key “${key}” even though environment is not a client`,
)
}
try {
// Allow value to be a function so we have the same API as useState
const newValue = value instanceof Function ? value(storedValue) : value
// Save to local storage
window.localStorage.setItem(key, JSON.stringify(newValue))
// Save state
setStoredValue(newValue)
// We dispatch a custom event so every useLocalStorage hook are notified
window.dispatchEvent(new Event('local-storage'))
} catch (error) {
console.warn(`Error setting localStorage key “${key}”:`, error)
}
}, [key, storedValue])
useEffect(() => {
setStoredValue(readValue())
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
const handleStorageChange = useCallback(
(event: StorageEvent | CustomEvent) => {
if ((event as StorageEvent)?.key && (event as StorageEvent).key !== key) {
return
}
setStoredValue(readValue())
},
[key, readValue],
)
// this only works for other documents, not the current one
useEventListener('storage', handleStorageChange)
// this is a custom event, triggered in writeValueToLocalStorage
// See: useLocalStorage()
useEventListener('local-storage', handleStorageChange)
return [storedValue, setValue]
}
// A wrapper for "JSON.parse()"" to support "undefined" value
function parseJSON<T>(value: string | null): T | undefined {
try {
return value === 'undefined' ? undefined : JSON.parse(value ?? '')
} catch {
console.log('parsing error on', { value })
return undefined
}
}

15
src/types.ts Normal file
View File

@@ -0,0 +1,15 @@
export interface Recipe {
prerequisites: Record<string, number>
time: number
output: Record<string, number>
}
export interface UnfetchedEntity {
name: string
image: string
href: string
}
export interface Entity extends UnfetchedEntity {
recipe?: Recipe
}

12
src/utils.ts Normal file
View File

@@ -0,0 +1,12 @@
export function isNonNullable<T>(any: T): any is NonNullable<T> {
return any !== undefined && any !== null
}
export function sortByProperty<T>(transform: (val: T) => number | string): (a: T, b: T) => number {
return (a, b) => {
const a2 = transform(a)
const b2 = transform(b)
if (a2 > b2) return 1
return a2 === b2 ? 0 : -1
}
}

View File

@@ -1,129 +0,0 @@
.container {
padding: 0 2rem;
}
.main {
min-height: 100vh;
padding: 4rem 0;
flex: 1;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
}
.footer {
display: flex;
flex: 1;
padding: 2rem 0;
border-top: 1px solid #eaeaea;
justify-content: center;
align-items: center;
}
.footer a {
display: flex;
justify-content: center;
align-items: center;
flex-grow: 1;
}
.title a {
color: #0070f3;
text-decoration: none;
}
.title a:hover,
.title a:focus,
.title a:active {
text-decoration: underline;
}
.title {
margin: 0;
line-height: 1.15;
font-size: 4rem;
}
.title,
.description {
text-align: center;
}
.description {
margin: 4rem 0;
line-height: 1.5;
font-size: 1.5rem;
}
.code {
background: #fafafa;
border-radius: 5px;
padding: 0.75rem;
font-size: 1.1rem;
font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
Bitstream Vera Sans Mono, Courier New, monospace;
}
.grid {
display: flex;
align-items: center;
justify-content: center;
flex-wrap: wrap;
max-width: 800px;
}
.card {
margin: 1rem;
padding: 1.5rem;
text-align: left;
color: inherit;
text-decoration: none;
border: 1px solid #eaeaea;
border-radius: 10px;
transition: color 0.15s ease, border-color 0.15s ease;
max-width: 300px;
}
.card:hover,
.card:focus,
.card:active {
color: #0070f3;
border-color: #0070f3;
}
.card h2 {
margin: 0 0 1rem 0;
font-size: 1.5rem;
}
.card p {
margin: 0;
font-size: 1.25rem;
line-height: 1.5;
}
.logo {
height: 1em;
margin-left: 0.5rem;
}
@media (max-width: 600px) {
.grid {
width: 100%;
flex-direction: column;
}
}
@media (prefers-color-scheme: dark) {
.card,
.footer {
border-color: #222;
}
.code {
background: #111;
}
.logo img {
filter: invert(1);
}
}

3264
yarn.lock

File diff suppressed because it is too large Load Diff