This commit is contained in:
Sebastian Seedorf
2022-08-18 09:20:00 +02:00
parent 92b762bbd2
commit de95f57b18
60 changed files with 3450 additions and 994 deletions

3
.eslintignore Normal file
View File

@@ -0,0 +1,3 @@
.next
node_modules
*.json

View File

@@ -1,3 +1,62 @@
{ {
"extends": "next/core-web-vitals" "plugins": ["unused-imports", "@typescript-eslint"],
"extends": ["next/core-web-vitals", "plugin:@typescript-eslint/recommended"],
"parserOptions": {
"project": ["./tsconfig.json", "./tsconfig.test.json"],
"extraFileExtensions": [".json"]
},
"rules": {
"@typescript-eslint/no-non-null-assertion": "error",
"no-trailing-spaces": "error",
"no-unused-vars": "off",
"unused-imports/no-unused-imports": "error",
"unused-imports/no-unused-vars": "off",
"@typescript-eslint/no-unused-vars": [
"error",
{ "args": "after-used", "argsIgnorePattern": "^_$" }
],
"@typescript-eslint/no-explicit-any": "error",
"@typescript-eslint/member-delimiter-style": [
"error",
{
"multiline": {
"delimiter": "none",
"requireLast": false
},
"singleline": {
"delimiter": "comma",
"requireLast": false
}
}
],
"@typescript-eslint/semi": ["error", "never"],
"no-shadow": "off",
"@typescript-eslint/no-shadow": ["error"],
"no-useless-constructor": "off",
"no-use-before-define": "off",
"jsx-a11y/label-has-associated-control": "error",
"no-console": ["error", { "allow": ["warn", "error"] }],
"indent": [2, 2],
"new-cap": ["error", { "capIsNewExceptions": ["Router"] }],
"semi": ["error", "never"],
"multiline-ternary": "off",
"quotes": ["error", "single", { "avoidEscape": true }],
"jsx-quotes": ["error", "prefer-single"],
"no-return-await": "error",
"no-process-env": "error",
"react-hooks/exhaustive-deps": [
"warn",
{
"additionalHooks": "(useAsyncEffect)"
}
]
},
"overrides": [
{
"files": "**/*.js",
"rules": {
"@typescript-eslint/no-var-requires": ["off"]
}
}
]
} }

12
.lintstagedrc Normal file
View File

@@ -0,0 +1,12 @@
{
"(!cypress)/**/*.+(ts|tsx)": [
"tsc-files --noEmit"
],
"**/*.{js,jsx,ts,tsx,json}": [
"prettier --write --loglevel warn",
"eslint --fix"
],
"**/*.{css,scss,less}": [
"stylelint --fix"
]
}

17
.stylelintrc.json Normal file
View File

@@ -0,0 +1,17 @@
{
"extends": ["stylelint-config-standard", "stylelint-config-idiomatic-order"],
"rules": {
"selector-pseudo-class-no-unknown": [
true,
{
"ignorePseudoClasses": ["global"]
}
],
"no-descending-specificity": null,
"indentation": 4,
"declaration-block-no-duplicate-properties": true,
"no-duplicate-selectors": true,
"selector-class-pattern": "^.*|([a-z][a-zA-Z0-9]+)$",
"custom-property-pattern": ".*"
}
}

View File

@@ -1,10 +1,14 @@
import {createContext, FC, useCallback, useContext, useEffect, useMemo, useState} from "react"; import { createContext, FC, useCallback, useContext, useMemo, useState } from 'react'
import {Group} from "../../src/types"; import { Group } from '../../src/types'
import {ReactNodeLike} from "prop-types"; import { ReactNodeLike } from 'prop-types'
import pako from "pako"; import pako from 'pako'
import {Dict} from "../../src/types"; import { Dict } from '../../src/types'
import {fixedEncodeURIComponent} from "../../src/utils"; import { fixedEncodeURIComponent } from '../../src/utils'
import {GroupRenameBody, GroupSetFactoryArrayBody, SetFactoryArrayBody} from "../../src/types/ApiSchemasFrontend"; import {
GroupRenameBody,
GroupSetFactoryArrayBody,
SetFactoryArrayBody
} from '../../src/types/ApiSchemasFrontend'
interface Props { interface Props {
children: ReactNodeLike children: ReactNodeLike
@@ -31,8 +35,8 @@ interface GroupContextType {
removeGroup(name: string): void removeGroup(name: string): void
renameGroup(name: string, newName: string): void renameGroup(name: string, newName: string): void
setFactories(name: string, factories: string[], type: 'exports'|'malls'): void setFactories(name: string, factories: string[], type: 'exports' | 'malls'): void
getInputType(uid: string): 'base'|'produced'|'unknown' getInputType(uid: string): 'base' | 'produced' | 'unknown'
store(): Uint8Array store(): Uint8Array
load(str: Uint8Array): void load(str: Uint8Array): void
@@ -43,29 +47,47 @@ const defaultValues: GroupContextType = {
exportedFactories: new Set(), exportedFactories: new Set(),
ignoredFactories: [], ignoredFactories: [],
setIgnoredFactories() {}, setIgnoredFactories() {
return
},
baseFactories: [], baseFactories: [],
setBaseFactories() {}, setBaseFactories() {
return
},
groups: {}, groups: {},
addGroup() {}, addGroup() {
removeGroup() {}, return
renameGroup() {}, },
removeGroup() {
return
},
renameGroup() {
return
},
setFactories() {}, setFactories() {
getInputType() {return 'unknown'}, return
},
getInputType() {
return 'unknown'
},
store() {return new Uint8Array(0)}, store() {
load() {} return new Uint8Array(0)
},
load() {
return
}
} }
const GroupContext = createContext<GroupContextType>(defaultValues); const GroupContext = createContext<GroupContextType>(defaultValues)
export const useGroups = () => useContext(GroupContext) export const useGroups = () => useContext(GroupContext)
interface StoredFile { interface StoredFile {
groups: Dict<Group>, groups: Dict<Group>
basicValues: string[], basicValues: string[]
excludedSuggestions: string[] excludedSuggestions: string[]
} }
@@ -80,143 +102,203 @@ export const postFetchJson = async (url: string, body: Dict<unknown>) => {
return res.json() return res.json()
} }
export const GroupProvider: FC<Props> = ({children, id, initial}) => { export const GroupProvider: FC<Props> = ({ children, id, initial }) => {
const [excludedSuggestions, _setExcludedSuggestions] = useState<string[]>(initial.ignored) const [excludedSuggestions, _setExcludedSuggestions] = useState<string[]>(initial.ignored)
const [basicValues, _setBasicValues] = useState<string[]>(initial.base) const [basicValues, _setBasicValues] = useState<string[]>(initial.base)
const [groups, setGroups] = useState<Dict<Group>>(initial.groups) const [groups, setGroups] = useState<Dict<Group>>(initial.groups)
const doNotSuggest = useMemo<Set<string>>(() => { const doNotSuggest = useMemo<Set<string>>(() => {
return new Set([...Object.values(groups).flatMap(group => [...group.exports, ...group.malls]), ...excludedSuggestions, ...basicValues]) return new Set([
...Object.values(groups).flatMap(group => [...group.exports, ...group.malls]),
...excludedSuggestions,
...basicValues
])
}, [basicValues, groups, excludedSuggestions]) }, [basicValues, groups, excludedSuggestions])
const exportedFactories = useMemo<Set<string>>(() => { const exportedFactories = useMemo<Set<string>>(() => {
return new Set([...Object.values(groups).flatMap(group => [...group.exports])]) return new Set([...Object.values(groups).flatMap(group => [...group.exports])])
}, [groups]) }, [groups])
const setExcludedSuggestions = useCallback<typeof _setExcludedSuggestions>((val) => { const setExcludedSuggestions = useCallback<typeof _setExcludedSuggestions>(
_setExcludedSuggestions(val) val => {
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, { _setExcludedSuggestions(val)
type: 'ignored', postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, {
factories: val type: 'ignored',
} as SetFactoryArrayBody) factories: val
.catch(console.error) } as SetFactoryArrayBody).catch(console.error)
}, [id]) },
[id]
)
const setBasicValues = useCallback<typeof _setBasicValues>((val) => { const setBasicValues = useCallback<typeof _setBasicValues>(
_setBasicValues(val) val => {
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, { _setBasicValues(val)
type: 'base', postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, {
factories: val type: 'base',
} as SetFactoryArrayBody) factories: val
.catch(console.error) } as SetFactoryArrayBody).catch(console.error)
}, [id]) },
[id]
)
const addGroup = useCallback((name: string, exports: string[] = [], malls: string[] = []) => { const addGroup = useCallback(
name = name.replace(/[.$]/g, '') (name: string, exports: string[] = [], malls: string[] = []) => {
if (name in groups) return false name = name.replace(/[.$]/g, '')
setGroups(groups => { if (name in groups) return false
groups[name] = { name, exports, malls } setGroups(g => {
return {...groups} g[name] = { name, exports, malls }
}) return { ...g }
;(async () => { })
await postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/add`, {}) ;(async () => {
if (exports.length) { await postFetchJson(
await postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`, { `/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/add`,
type: 'exports', {}
factories: exports )
} as GroupSetFactoryArrayBody) if (exports.length) {
} await postFetchJson(
if (malls.length) { `/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`,
await postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`, { {
type: 'malls', type: 'exports',
factories: exports factories: exports
} as GroupSetFactoryArrayBody) } as GroupSetFactoryArrayBody
} )
})().catch(console.error) }
return true if (malls.length) {
}, [groups, id]) await postFetchJson(
const removeGroup = useCallback((name: string) => { `/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`,
name = name.replace(/[.$]/g, '') {
setGroups(groups => { type: 'malls',
delete groups[name] factories: exports
console.log(groups[name]) } as GroupSetFactoryArrayBody
return {...groups} )
}) }
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/remove`, {}) })().catch(console.error)
.catch(console.error) return true
}, [id]) },
const renameGroup = useCallback((name: string, newName: string) => { [groups, id]
name = name.replace(/[.$]/g, '') )
newName = newName.replace(/[.$]/g, '') const removeGroup = useCallback(
if (newName in groups) return (name: string) => {
setGroups(groups => { name = name.replace(/[.$]/g, '')
groups[newName] = {...groups[name], name: newName} setGroups(g => {
delete groups[name] delete g[name]
return {...groups} return { ...g }
}) })
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/rename`, { postFetchJson(
newName `/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/remove`,
} as GroupRenameBody) {}
.catch(console.error) ).catch(console.error)
}, [groups, id]) },
[id]
)
const renameGroup = useCallback(
(name: string, newName: string) => {
name = name.replace(/[.$]/g, '')
newName = newName.replace(/[.$]/g, '')
if (newName in groups) return
setGroups(g => {
g[newName] = { ...g[name], name: newName }
delete g[name]
return { ...g }
})
postFetchJson(
`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/rename`,
{
newName
} as GroupRenameBody
).catch(console.error)
},
[groups, id]
)
const setFactories = useCallback((name: string, factories: string[], type: 'exports'|'malls') => { const setFactories = useCallback(
name = name.replace(/[.$]/g, '') (name: string, factories: string[], type: 'exports' | 'malls') => {
setGroups(groups => { name = name.replace(/[.$]/g, '')
groups[name] = {...groups[name], [type]: factories} setGroups(g => {
return {...groups} g[name] = { ...g[name], [type]: factories }
}) return { ...g }
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`, { })
type, postFetchJson(
factories `/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`,
} as GroupSetFactoryArrayBody) {
.catch(console.error) type,
}, [id]) factories
const getInputType = useCallback((uid: string) => { } as GroupSetFactoryArrayBody
if (basicValues.includes(uid)) return 'base' ).catch(console.error)
else if (exportedFactories.has(uid)) return 'produced' },
else return 'unknown' [id]
}, [basicValues, exportedFactories]) )
const getInputType = useCallback(
(uid: string) => {
if (basicValues.includes(uid)) return 'base'
else if (exportedFactories.has(uid)) return 'produced'
else return 'unknown'
},
[basicValues, exportedFactories]
)
const store = useCallback(() => { const store = useCallback(() => {
const btoa = (bin: Uint8Array) => Buffer.from(bin).toString('base64') // const btoa = (bin: Uint8Array) => Buffer.from(bin).toString('base64')
const value: StoredFile = { const value: StoredFile = {
groups, basicValues, excludedSuggestions groups,
basicValues,
excludedSuggestions
} }
const uncompressed = JSON.stringify(value) const uncompressed = JSON.stringify(value)
return pako.deflate(uncompressed) return pako.deflate(uncompressed)
}, [basicValues, excludedSuggestions, groups]) }, [basicValues, excludedSuggestions, groups])
const load = useCallback((compressed: Uint8Array) => { const load = useCallback(
const atob = (str: string) => Buffer.from(str, 'base64') (compressed: Uint8Array) => {
const uncompressed = pako.inflate(compressed, {to: "string"}) // const atob = (str: string) => Buffer.from(str, 'base64')
const value: StoredFile = JSON.parse(uncompressed) const uncompressed = pako.inflate(compressed, { to: 'string' })
if (!value.groups || !value.basicValues || !value.excludedSuggestions) return const value: StoredFile = JSON.parse(uncompressed)
setGroups(value.groups) if (!value.groups || !value.basicValues || !value.excludedSuggestions) return
setBasicValues(value.basicValues) setGroups(value.groups)
setExcludedSuggestions(value.excludedSuggestions) setBasicValues(value.basicValues)
}, []) setExcludedSuggestions(value.excludedSuggestions)
},
[setBasicValues, setExcludedSuggestions]
)
const value: GroupContextType = useMemo(() => ({ const value: GroupContextType = useMemo(
doNotSuggest, () => ({
exportedFactories, doNotSuggest,
exportedFactories,
ignoredFactories: excludedSuggestions, ignoredFactories: excludedSuggestions,
setIgnoredFactories: setExcludedSuggestions, setIgnoredFactories: setExcludedSuggestions,
baseFactories: basicValues, baseFactories: basicValues,
setBaseFactories: setBasicValues, setBaseFactories: setBasicValues,
groups, groups,
addGroup, addGroup,
removeGroup, removeGroup,
renameGroup, renameGroup,
setFactories, setFactories,
getInputType, getInputType,
store, store,
load load
}), [addGroup, basicValues, doNotSuggest, excludedSuggestions, exportedFactories, getInputType, groups, load, removeGroup, renameGroup, setBasicValues, setExcludedSuggestions, setFactories, store]) }),
[
addGroup,
basicValues,
doNotSuggest,
excludedSuggestions,
exportedFactories,
getInputType,
groups,
load,
removeGroup,
renameGroup,
setBasicValues,
setExcludedSuggestions,
setFactories,
store
]
)
return <GroupContext.Provider value={value}>{children}</GroupContext.Provider> return <GroupContext.Provider value={value}>{children}</GroupContext.Provider>
} }

View File

@@ -1,5 +1,5 @@
.span { .span {
background: #DDD; background: #ddd;
font-size: 2em; font-size: 2em;
border: 1px solid white; border: 1px solid white;
display: inline-block; display: inline-block;

View File

@@ -1,18 +1,18 @@
import {FC, HTMLProps, useMemo} from "react" import { FC, HTMLProps, useMemo } from 'react'
import {Entity} from "../../../src/types" import { Entity } from '../../../src/types'
import {useFactories} from "../../../src/hooks/useFactories" import { useFactories } from '../../../src/hooks/useFactories'
import styles from './EntityIcon.module.css' import styles from './EntityIcon.module.css'
import cx from "classnames"; import cx from 'classnames'
interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> { interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> {
value: Entity|string value: Entity | string
amount?: number amount?: number
} }
export const EntityIcon: FC<Props> = ({className, value, amount, ...rest}) => { export const EntityIcon: FC<Props> = ({ className, value, amount, ...rest }) => {
const {findFactory} = useFactories() const { findFactory } = useFactories()
const entity = useMemo<Entity>(() => { const entity = useMemo<Entity>(() => {
return typeof value === "object" return typeof value === 'object'
? value ? value
: value === '/Time' : value === '/Time'
? { ? {
@@ -29,9 +29,15 @@ export const EntityIcon: FC<Props> = ({className, value, amount, ...rest}) => {
} }
}, [findFactory, value]) }, [findFactory, value])
return <span {...rest} className={cx(className, styles.span)} title={entity.name}> return (
{/* eslint-disable-next-line @next/next/no-img-element */} <span {...rest} className={cx(className, styles.span)} title={entity.name}>
<img className={cx(styles.img, amount === undefined ? styles.noAmount : undefined)} src={`https://wiki.factorio.com${entity.image}`} alt={entity.name}/> {/* eslint-disable-next-line @next/next/no-img-element */}
{amount !== undefined && <span className={styles.amount}>{amount}</span>} <img
</span> className={cx(styles.img, amount === undefined ? styles.noAmount : undefined)}
src={`https://wiki.factorio.com${entity.image}`}
alt={entity.name}
/>
{amount !== undefined && <span className={styles.amount}>{amount}</span>}
</span>
)
} }

View File

@@ -1,25 +1,33 @@
import {FC, HTMLProps, memo, useMemo} from "react" import { FC, HTMLProps, memo, useMemo } from 'react'
import {EnrichedEntity, Entity} from "../../../src/types" import { EnrichedEntity } from '../../../src/types'
import {useFactories} from "../../../src/hooks/useFactories" import { useFactories } from '../../../src/hooks/useFactories'
import styles from './EntitySpan.module.css' import styles from './EntitySpan.module.css'
import {RecipeSpan} from "../Recipe/Recipe"; import { RecipeSpan } from '../Recipe/Recipe'
import {LeftClickIcon} from "../LeftClickIcon/LeftClickIcon"; import { LeftClickIcon } from '../LeftClickIcon/LeftClickIcon'
import cx from 'classnames'; import cx from 'classnames'
import {EntityIcon} from "../EntityIcon/EntityIcon"; import { EntityIcon } from '../EntityIcon/EntityIcon'
interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> { interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> {
value: EnrichedEntity|string value: EnrichedEntity | string
state?: 'base'|'produced'|'unknown' state?: 'base' | 'produced' | 'unknown'
leftClickText?: string leftClickText?: string
rightClickText?: string rightClickText?: string
simpleStyle?: boolean simpleStyle?: boolean
className?: string className?: string
} }
const EntitySpanUnmemo: FC<Props> = ({className, value, state, leftClickText, rightClickText, simpleStyle, ...rest}) => { const EntitySpanUnmemo: FC<Props> = ({
const {findFactory} = useFactories() className,
value,
state,
leftClickText,
rightClickText,
simpleStyle,
...rest
}) => {
const { findFactory } = useFactories()
const entity = useMemo<EnrichedEntity>(() => { const entity = useMemo<EnrichedEntity>(() => {
return typeof value === "object" return typeof value === 'object'
? value ? value
: findFactory(value) ?? { : findFactory(value) ?? {
usedBy: [], usedBy: [],
@@ -30,34 +38,52 @@ const EntitySpanUnmemo: FC<Props> = ({className, value, state, leftClickText, ri
} }
}, [findFactory, value]) }, [findFactory, value])
return <span className={cx(className, simpleStyle ? styles.spanSimple : styles.span)} {...rest}> return (
{/* eslint-disable-next-line @next/next/no-img-element */} <span className={cx(className, simpleStyle ? styles.spanSimple : styles.span)} {...rest}>
<img className={styles.img} src={`https://wiki.factorio.com${entity.image}`} alt={entity.name}/> {/* eslint-disable-next-line @next/next/no-img-element */}
<span className={styles[state ?? 'unknown']}>{entity.name}</span> <img
<div className={styles.tooltip}> className={styles.img}
{entity.recipe && ( src={`https://wiki.factorio.com${entity.image}`}
<> alt={entity.name}
<div className={styles.strong}>Recipe</div> />
<RecipeSpan recipe={entity.recipe}/> <span className={styles[state ?? 'unknown']}>{entity.name}</span>
</> <div className={styles.tooltip}>
)} {entity.recipe && (
{entity.usedBy?.length ? ( <>
<> <div className={styles.strong}>Recipe</div>
<div className={styles.strong}>Used By</div> <RecipeSpan recipe={entity.recipe} />
<div className={styles.usedBy}> </>
{entity.usedBy.map(used => <EntityIcon value={used} key={used.name}/>)} )}
</div> {entity.usedBy?.length ? (
</> <>
) : null} <div className={styles.strong}>Used By</div>
{(leftClickText || rightClickText) && ( <div className={styles.usedBy}>
<> {entity.usedBy.map(used => (
<div className={styles.strong}>Actions</div> <EntityIcon value={used} key={used.name} />
{leftClickText && <div><LeftClickIcon className={styles.leftClick} classClick={styles.clickBtn}/> {leftClickText}</div>} ))}
{rightClickText && <div><LeftClickIcon className={styles.rightClick} classClick={styles.clickBtn}/> {rightClickText}</div>} </div>
</> </>
)} ) : null}
</div> {(leftClickText || rightClickText) && (
</span> <>
<div className={styles.strong}>Actions</div>
{leftClickText && (
<div>
<LeftClickIcon className={styles.leftClick} classClick={styles.clickBtn} />{' '}
{leftClickText}
</div>
)}
{rightClickText && (
<div>
<LeftClickIcon className={styles.rightClick} classClick={styles.clickBtn} />{' '}
{rightClickText}
</div>
)}
</>
)}
</div>
</span>
)
} }
export const EntitySpan = memo(EntitySpanUnmemo) export const EntitySpan = memo(EntitySpanUnmemo)

View File

@@ -4,8 +4,7 @@
} }
.select :global(.factory-select__multi-value), .select :global(.factory-select__multi-value),
.select :global(.factory-select__menu) .select :global(.factory-select__menu) {
{
background-color: #444; background-color: #444;
} }
@@ -18,6 +17,6 @@
} }
.select :global(.factory-select__multi-value__label) { .select :global(.factory-select__multi-value__label) {
color: #DDDDDD; color: #dddddd;
} }
} }

View File

@@ -1,9 +1,9 @@
import {FC, memo, useEffect, useMemo, useState} from "react"; import { FC, memo, useMemo } from 'react'
import Select from "react-select"; import Select from 'react-select'
import {isNonNullable} from "../../../src/utils"; import { isNonNullable } from '../../../src/utils'
import details from "../../../res/details.json"; import details from '../../../res/details.json'
import styles from "./FactorySelect.module.css"; import styles from './FactorySelect.module.css'
import {EntitySpan} from "../EntitySpan/EntitySpan"; import { EntitySpan } from '../EntitySpan/EntitySpan'
interface Props { interface Props {
id: string id: string
@@ -16,33 +16,37 @@ const options = details.map(detail => ({
value: detail.href value: detail.href
})) }))
const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => { const FactorySelectBase: FC<Props> = ({ id, factories, onSetFactories }) => {
const state = useMemo<typeof options>(() => { const state = useMemo<typeof options>(() => {
return factories return factories
.map(factory => options.find(option => option.value === factory)) .map(factory => options.find(option => option.value === factory))
.filter(isNonNullable) .filter(isNonNullable)
}, [factories]) }, [factories])
return <Select return (
id={id} <Select
instanceId={id} id={id}
value={state} instanceId={id}
components={{ value={state}
MultiValueLabel: ({data, innerProps}) => ( components={{
<EntitySpan {...innerProps} value={data.value} simpleStyle={true}/> MultiValueLabel: ({ data, innerProps }) => (
), <EntitySpan {...innerProps} value={data.value} simpleStyle={true} />
Option: ({innerProps, data}) => ( ),
<div {...innerProps} className={styles.option}><EntitySpan value={data.value} simpleStyle={true}/></div> Option: ({ innerProps, data }) => (
) <div {...innerProps} className={styles.option}>
}} <EntitySpan value={data.value} simpleStyle={true} />
isMulti </div>
options={options as never} )
onChange={e => { }}
onSetFactories(e.map(s => s?.value)) isMulti
}} options={options as never}
className={styles.select} onChange={e => {
classNamePrefix={"factory-select"} onSetFactories(e.map(s => s?.value))
/> }}
className={styles.select}
classNamePrefix={'factory-select'}
/>
)
} }
export const FactorySelect = memo(FactorySelectBase) export const FactorySelect = memo(FactorySelectBase)

View File

@@ -1,14 +1,14 @@
import {FC, memo, useCallback, useMemo, useState} from "react"; import { FC, memo, useCallback, useMemo, useState } from 'react'
import {FactorySelect} from "../FactorySelect/FactorySelect"; import { FactorySelect } from '../FactorySelect/FactorySelect'
import {useFactories} from "../../../src/hooks/useFactories"; import { useFactories } from '../../../src/hooks/useFactories'
import {EnrichedEntity, Group} from "../../../src/types"; import { EnrichedEntity, Group } from '../../../src/types'
import styles from "./GroupBox.module.css" import styles from './GroupBox.module.css'
import {EntitySpan} from "../EntitySpan/EntitySpan"; import { EntitySpan } from '../EntitySpan/EntitySpan'
import {useGroups} from "../../contexts/GroupProvider"; import { useGroups } from '../../contexts/GroupProvider'
import {calculateInputs} from "../../../src/calculateInputs"; import { calculateInputs } from '../../../src/calculateInputs'
import {fixedEncodeURIComponent, uniquify} from "../../../src/utils"; import { fixedEncodeURIComponent, uniquify } from '../../../src/utils'
import Link from "next/link"; import Link from 'next/link'
import {useRouter} from "next/router"; import { useRouter } from 'next/router'
interface Props { interface Props {
group: Group group: Group
@@ -16,7 +16,7 @@ interface Props {
const GroupBoxBase: FC<Props> = ({ group }) => { const GroupBoxBase: FC<Props> = ({ group }) => {
const router = useRouter() const router = useRouter()
const {factories, findFactory} = useFactories() const { factories, findFactory } = useFactories()
const { const {
doNotSuggest, doNotSuggest,
setFactories, setFactories,
@@ -28,24 +28,14 @@ const GroupBoxBase: FC<Props> = ({ group }) => {
removeGroup, removeGroup,
getInputType getInputType
} = useGroups() } = useGroups()
const { const { name, exports, malls } = group
name,
exports,
malls
} = group
const [isDeleteConfirm, setDeleteConfirm] = useState(false) const [isDeleteConfirm, setDeleteConfirm] = useState(false)
const [inputs, intermediates] = useMemo(() => { const [inputs, intermediates] = useMemo(() => {
const allProducingFactories = [...exports, ...malls] const allProducingFactories = [...exports, ...malls]
return calculateInputs( return calculateInputs(allProducingFactories, baseFactories, exportedFactories, findFactory)
allProducingFactories, }, [exports, malls, baseFactories, findFactory, exportedFactories])
ignoredFactories,
baseFactories,
exportedFactories,
findFactory
)
}, [exports, malls, ignoredFactories, baseFactories, findFactory, exportedFactories])
const [suggestionsExport, suggestionMall] = useMemo<[EnrichedEntity[], EnrichedEntity[]]>(() => { const [suggestionsExport, suggestionMall] = useMemo<[EnrichedEntity[], EnrichedEntity[]]>(() => {
const selectedValues = uniquify([...exports, ...malls]) const selectedValues = uniquify([...exports, ...malls])
@@ -58,110 +48,142 @@ const GroupBoxBase: FC<Props> = ({ group }) => {
const prerequisites = Object.keys(factory.recipe.prerequisites ?? {}) const prerequisites = Object.keys(factory.recipe.prerequisites ?? {})
return prerequisites.every(pre => availableIngredients.includes(pre)) return prerequisites.every(pre => availableIngredients.includes(pre))
}) })
.reduce((acc, factory) => .reduce(
(factory.usedBy?.length ?? 0) >= 3 (acc, factory) =>
? [[...acc[0], factory], acc[1]] (factory.usedBy?.length ?? 0) >= 3
: [acc[0], [...acc[1], factory]], ? [[...acc[0], factory], acc[1]]
: [acc[0], [...acc[1], factory]],
[[], []] as [EnrichedEntity[], EnrichedEntity[]] [[], []] as [EnrichedEntity[], EnrichedEntity[]]
) )
}, [exports, malls, intermediates, inputs, factories, doNotSuggest]) }, [exports, malls, intermediates, inputs, factories, doNotSuggest])
const addFactory = useCallback((uid: string, type: Parameters<typeof setFactories>[2]) => { const addFactory = useCallback(
setFactories(name, [...group[type], uid], type) (uid: string, type: Parameters<typeof setFactories>[2]) => {
}, [group, name, setFactories]) setFactories(name, [...group[type], uid], type)
},
[group, name, setFactories]
)
const setExportFactories = useCallback((factories: string[]) => setFactories(name, factories, 'exports'), [setFactories, name]) const setExportFactories = useCallback(
const setMallFactories = useCallback((factories: string[]) => setFactories(name, factories, 'malls'), [setFactories, name]) (exportFactories: string[]) => setFactories(name, exportFactories, 'exports'),
[setFactories, name]
)
const setMallFactories = useCallback(
(mallFactories: string[]) => setFactories(name, mallFactories, 'malls'),
[setFactories, name]
)
return <div className={styles.root}> return (
<h3 <div className={styles.root}>
contentEditable={true} <h3
suppressContentEditableWarning={true} contentEditable={true}
onBlur={event => { suppressContentEditableWarning={true}
event.currentTarget.innerText = event.currentTarget.innerText.trim() onBlur={event => {
renameGroup(name, event.currentTarget.innerText); event.currentTarget.innerText = event.currentTarget.innerText.trim()
}} renameGroup(name, event.currentTarget.innerText)
> }}
{name} >
</h3> {name}
<Link href={{pathname: `/visualize/${fixedEncodeURIComponent(group.name)}`, query: router.query}}>👁</Link> </h3>
<button <Link
className={styles.quit} href={{
onBlur={() => setDeleteConfirm(false)} pathname: `/visualize/${fixedEncodeURIComponent(group.name)}`,
onClick={() => !isDeleteConfirm ? setDeleteConfirm(true) : removeGroup(name)} style={{display: 'block'}} query: router.query
> }}
{isDeleteConfirm ? 'Delete GroupBox?' : 'X'} >
</button> 👁
<h4>Exported Factories</h4> </Link>
<FactorySelect <button
id={name+"-exports"} className={styles.quit}
factories={exports} onBlur={() => setDeleteConfirm(false)}
onSetFactories={setExportFactories} onClick={() => (!isDeleteConfirm ? setDeleteConfirm(true) : removeGroup(name))}
/> style={{ display: 'block' }}
<h4>Mall Factories</h4> >
<FactorySelect {isDeleteConfirm ? 'Delete GroupBox?' : 'X'}
id={name+"-malls"} </button>
factories={malls} <h4>Exported Factories</h4>
onSetFactories={setMallFactories} <FactorySelect
/> id={name + '-exports'}
{ inputs.length ? <> factories={exports}
<h4>Input Factories ({inputs.length})</h4> onSetFactories={setExportFactories}
<div className={styles.flex}> />
{ inputs.map(input => <EntitySpan <h4>Mall Factories</h4>
key={input} <FactorySelect id={name + '-malls'} factories={malls} onSetFactories={setMallFactories} />
value={input} {inputs.length ? (
state={getInputType(input)} <>
onContextMenu={event => { <h4>Input Factories ({inputs.length})</h4>
event.preventDefault() <div className={styles.flex}>
setIgnoredFactories([...ignoredFactories, input]) {inputs.map(input => (
}} <EntitySpan
rightClickText={"Exclude this recipe from suggestions"} key={input}
/>) } value={input}
</div> state={getInputType(input)}
</> : null } onContextMenu={event => {
{ intermediates.length ? <> event.preventDefault()
<h4>Intermediate Factories ({intermediates.length})</h4> setIgnoredFactories([...ignoredFactories, input])
<div className={styles.flex}> }}
{ intermediates.map(intermediate => <EntitySpan rightClickText={'Exclude this recipe from suggestions'}
key={intermediate} />
value={intermediate} ))}
state={getInputType(intermediate)} </div>
/>) } </>
</div> ) : null}
</> : null } {intermediates.length ? (
{ suggestionsExport.length ? <> <>
<h4>Suggestions (Export)</h4> <h4>Intermediate Factories ({intermediates.length})</h4>
<div className={styles.flex}> <div className={styles.flex}>
{ suggestionsExport.map(suggestion => <EntitySpan {intermediates.map(intermediate => (
key={suggestion.href} <EntitySpan
value={suggestion} key={intermediate}
onClick={() => addFactory(suggestion.href, 'exports')} value={intermediate}
onContextMenu={event => { state={getInputType(intermediate)}
event.preventDefault() />
setIgnoredFactories([...ignoredFactories, suggestion.href]) ))}
}} </div>
leftClickText={"Add to exported factories"} </>
rightClickText={"Exclude this recipe from suggestions"} ) : null}
/>) } {suggestionsExport.length ? (
</div> <>
</> : null } <h4>Suggestions (Export)</h4>
{ suggestionMall.length ? <> <div className={styles.flex}>
<h4>Suggestions (Mall)</h4> {suggestionsExport.map(suggestion => (
<div className={styles.flex}> <EntitySpan
{ suggestionMall.map(suggestion => <EntitySpan key={suggestion.href}
key={suggestion.href} value={suggestion}
value={suggestion} onClick={() => addFactory(suggestion.href, 'exports')}
onClick={() => addFactory(suggestion.href, 'malls')} onContextMenu={event => {
onContextMenu={event => { event.preventDefault()
event.preventDefault() setIgnoredFactories([...ignoredFactories, suggestion.href])
setIgnoredFactories([...ignoredFactories, suggestion.href]) }}
}} leftClickText={'Add to exported factories'}
leftClickText={"Add to mall factories"} rightClickText={'Exclude this recipe from suggestions'}
rightClickText={"Exclude this recipe from suggestions"} />
/>) } ))}
</div> </div>
</> : null } </>
</div> ) : null}
{suggestionMall.length ? (
<>
<h4>Suggestions (Mall)</h4>
<div className={styles.flex}>
{suggestionMall.map(suggestion => (
<EntitySpan
key={suggestion.href}
value={suggestion}
onClick={() => addFactory(suggestion.href, 'malls')}
onContextMenu={event => {
event.preventDefault()
setIgnoredFactories([...ignoredFactories, suggestion.href])
}}
leftClickText={'Add to mall factories'}
rightClickText={'Exclude this recipe from suggestions'}
/>
))}
</div>
</>
) : null}
</div>
)
} }
export const GroupBox = memo(GroupBoxBase) export const GroupBox = memo(GroupBoxBase)

View File

@@ -1,18 +1,18 @@
import {FC, useMemo, useRef, useState} from "react"; import { FC, useMemo, useRef, useState } from 'react'
import {GroupBox} from "./GroupBox/GroupBox"; import { GroupBox } from './GroupBox/GroupBox'
import styles from "./Home.module.css" import styles from './Home.module.css'
import {useFactories} from "../../src/hooks/useFactories"; import { useFactories } from '../../src/hooks/useFactories'
import {EnrichedEntity} from "../../src/types"; import { EnrichedEntity } from '../../src/types'
import {EntitySpan} from "./EntitySpan/EntitySpan"; import { EntitySpan } from './EntitySpan/EntitySpan'
import {useGroups} from "../contexts/GroupProvider"; import { useGroups } from '../contexts/GroupProvider'
import {Preferences} from "./Preferences/Preferences"; import { Preferences } from './Preferences/Preferences'
import {download, streamToArrayBuffer} from "../../src/download"; import { download, streamToArrayBuffer } from '../../src/download'
import Link from "next/link"; import Link from 'next/link'
import {useRouter} from "next/router"; import { useRouter } from 'next/router'
export const Home: FC = () => { export const Home: FC = () => {
const router = useRouter() const router = useRouter()
const {factories} = useFactories() const { factories } = useFactories()
const { const {
groups, groups,
addGroup, addGroup,
@@ -23,13 +23,14 @@ export const Home: FC = () => {
store, store,
load load
} = useGroups() } = useGroups()
const [newGroupValue, setNewGroupValue] = useState("New group") const [newGroupValue, setNewGroupValue] = useState('New group')
const inputRef = useRef<HTMLInputElement>(null) const inputRef = useRef<HTMLInputElement>(null)
const [missingExport, missingMall] = useMemo<[EnrichedEntity[], EnrichedEntity[]]>(() => { const [missingExport, missingMall] = useMemo<[EnrichedEntity[], EnrichedEntity[]]>(() => {
return factories return factories
.filter(factory => !doNotSuggest.has(factory.href) && factory.recipe) .filter(factory => !doNotSuggest.has(factory.href) && factory.recipe)
.reduce((acc, factory) => .reduce(
(acc, factory) =>
(factory.usedBy?.length ?? 0) >= 3 (factory.usedBy?.length ?? 0) >= 3
? [[...acc[0], factory], acc[1]] ? [[...acc[0], factory], acc[1]]
: [acc[0], [...acc[1], factory]], : [acc[0], [...acc[1], factory]],
@@ -40,49 +41,66 @@ export const Home: FC = () => {
return ( return (
<main> <main>
<h1>Factorio Microservices</h1> <h1>Factorio Microservices</h1>
<button onClick={() => { <button
download('factorio-microservices.bin', store()); onClick={() => {
}}>Store</button> download('factorio-microservices.bin', store())
<button onClick={async () => { }}
const res = await fetch( '/api/submit', { >
method: 'POST', Store
headers: { </button>
'Content-Type': 'application/json' <button
}, onClick={async () => {
body: JSON.stringify({groups, ignored: ignoredFactories, base: baseFactories}) const res = await fetch('/api/submit', {
}) method: 'POST',
if (res.ok) { headers: {
const { uuid } = await res.json() 'Content-Type': 'application/json'
if (uuid) await router.push({query: {...router.query, id: uuid}}) },
} body: JSON.stringify({ groups, ignored: ignoredFactories, base: baseFactories })
}}>Upload</button> })
<input type={"file"} multiple={false} ref={inputRef} onChange={async evt => { if (res.ok) {
const stream = evt.currentTarget.files?.[0].stream() as globalThis.ReadableStream<Uint8Array>|undefined const { uuid } = await res.json()
if (stream) { if (uuid) await router.push({ query: { ...router.query, id: uuid } })
const array = await streamToArrayBuffer(stream) }
load(array) }}
if (inputRef.current) inputRef.current.value = null as unknown as string >
} Upload
}}/> </button>
<Link href={{pathname: '/visualize', query: router.query}}>Visualize</Link> <input
type={'file'}
multiple={false}
ref={inputRef}
onChange={async evt => {
const stream = evt.currentTarget.files?.[0].stream() as
| globalThis.ReadableStream<Uint8Array>
| undefined
if (stream) {
const array = await streamToArrayBuffer(stream)
load(array)
if (inputRef.current) inputRef.current.value = null as unknown as string
}
}}
/>
<Link href={{ pathname: '/visualize', query: router.query }}>Visualize</Link>
<Preferences /> <Preferences />
<fieldset> <fieldset>
<legend>Missing export factories</legend> <legend>Missing export factories</legend>
<div className={styles.missingFactories}> <div className={styles.missingFactories}>
{ missingExport.map(missing => ( {missingExport.map(missing => (
<EntitySpan <EntitySpan
key={missing.href} key={missing.href}
value={missing} value={missing}
onClick={() => { onClick={() => {
addGroup(newGroupValue !== "New group" ? newGroupValue : missing.name, [missing.href]) addGroup(newGroupValue !== 'New group' ? newGroupValue : missing.name, [
setNewGroupValue("New group") missing.href
])
setNewGroupValue('New group')
}} }}
onContextMenu={event => { onContextMenu={event => {
event.preventDefault() event.preventDefault()
setIgnoredFactories([...ignoredFactories, missing.href]) setIgnoredFactories([...ignoredFactories, missing.href])
}} }}
leftClickText={"Create a new group with this name and item as exported factory"} leftClickText={'Create a new group with this name and item as exported factory'}
rightClickText={"Exclude this recipe from suggestions"} rightClickText={'Exclude this recipe from suggestions'}
/> />
))} ))}
</div> </div>
@@ -90,31 +108,34 @@ export const Home: FC = () => {
<fieldset> <fieldset>
<legend>Missing mall factories</legend> <legend>Missing mall factories</legend>
<div className={styles.missingFactories}> <div className={styles.missingFactories}>
{ missingMall.map(missing => ( {missingMall.map(missing => (
<EntitySpan <EntitySpan
key={missing.href} key={missing.href}
value={missing} value={missing}
onClick={() => { onClick={() => {
addGroup(newGroupValue !== "New group" ? newGroupValue : missing.name, [], [missing.href]) addGroup(
setNewGroupValue("New group") newGroupValue !== 'New group' ? newGroupValue : missing.name,
[],
[missing.href]
)
setNewGroupValue('New group')
}} }}
onContextMenu={event => { onContextMenu={event => {
event.preventDefault() event.preventDefault()
setIgnoredFactories([...ignoredFactories, missing.href]) setIgnoredFactories([...ignoredFactories, missing.href])
}} }}
leftClickText={"Create a new group with this name and item as mall factory"} leftClickText={'Create a new group with this name and item as mall factory'}
rightClickText={"Exclude this recipe from suggestions"} rightClickText={'Exclude this recipe from suggestions'}
/> />
))} ))}
</div> </div>
</fieldset> </fieldset>
<div className={styles.grid}> <div className={styles.grid}>
{ {Object.values(groups)
Object .sort((a, b) => a.name.localeCompare(b.name))
.values(groups) .map(group => (
.sort((a, b) => a.name.localeCompare(b.name)) <GroupBox key={group.name} group={group} />
.map((group) => <GroupBox key={group.name} group={group} />) ))}
}
</div> </div>
</main> </main>
) )

View File

@@ -1,4 +1,4 @@
import {FC} from "react"; import { FC } from 'react'
interface Props { interface Props {
className?: string className?: string
@@ -6,11 +6,25 @@ interface Props {
classClick?: string classClick?: string
} }
export const LeftClickIcon: FC<Props> = ({className, classBody, classClick}) => { export const LeftClickIcon: FC<Props> = ({ className, classBody, classClick }) => {
return ( return (
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0px" y="0px" viewBox="0 0 100 100" className={className}> <svg
<path className={classBody} d="M51.552,8.117v32.554l-3.095,0.009c-9.203,0.027-17.447,0.297-24.509,0.803l-0.291,0.021 c-0.026,1.733-0.036,3.521-0.036,5.378c0,24.854,1.527,45,26.379,45c24.854,0,26.379-20.146,26.379-45 C76.379,22.563,74.903,8.701,51.552,8.117z" /> xmlns='http://www.w3.org/2000/svg'
<path className={classClick} id="click" d="M48.448,37.577V8.117C27.971,8.629,24.313,19.354,23.727,38.388C29.914,37.945,38.002,37.607,48.448,37.577z" /> version='1.1'
x='0px'
y='0px'
viewBox='0 0 100 100'
className={className}
>
<path
className={classBody}
d='M51.552,8.117v32.554l-3.095,0.009c-9.203,0.027-17.447,0.297-24.509,0.803l-0.291,0.021 c-0.026,1.733-0.036,3.521-0.036,5.378c0,24.854,1.527,45,26.379,45c24.854,0,26.379-20.146,26.379-45 C76.379,22.563,74.903,8.701,51.552,8.117z'
/>
<path
className={classClick}
id='click'
d='M48.448,37.577V8.117C27.971,8.629,24.313,19.354,23.727,38.388C29.914,37.945,38.002,37.607,48.448,37.577z'
/>
</svg> </svg>
) )
} }

View File

@@ -1,42 +1,42 @@
import {FC, useState} from "react"; import { FC, useState } from 'react'
import {FactorySelect} from "../FactorySelect/FactorySelect"; import { FactorySelect } from '../FactorySelect/FactorySelect'
import {useGroups} from "../../contexts/GroupProvider"; import { useGroups } from '../../contexts/GroupProvider'
export const Preferences: FC = () => { export const Preferences: FC = () => {
const { const { addGroup, baseFactories, setBaseFactories, ignoredFactories, setIgnoredFactories } =
addGroup, useGroups()
baseFactories, const [newGroupValue, setNewGroupValue] = useState('New group')
setBaseFactories, return (
ignoredFactories, <>
setIgnoredFactories <fieldset>
} = useGroups() <legend>Basic Values</legend>
const [newGroupValue, setNewGroupValue] = useState("New group") <FactorySelect
return <> id={'baseFactoriesSelect'}
<fieldset> factories={baseFactories}
<legend>Basic Values</legend> onSetFactories={setBaseFactories}
<FactorySelect />
id={'baseFactoriesSelect'} </fieldset>
factories={baseFactories} <fieldset>
onSetFactories={setBaseFactories} <legend>Ignored Values</legend>
/> <FactorySelect
</fieldset> id={'ignoredFactoriesSelect'}
<fieldset> factories={ignoredFactories}
<legend>Ignored Values</legend> onSetFactories={setIgnoredFactories}
<FactorySelect />
id={'ignoredFactoriesSelect'} </fieldset>
factories={ignoredFactories} <fieldset>
onSetFactories={setIgnoredFactories} <legend>Add new groups</legend>
/> <input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)} />
</fieldset> <button
<fieldset> disabled={!newGroupValue}
<legend>Add new groups</legend> onClick={() => {
<input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)}/> addGroup(newGroupValue)
<button disabled={!newGroupValue} onClick={() => { setNewGroupValue('New group')
addGroup(newGroupValue) }}
setNewGroupValue("New group") >
}}> Add group &quot;{newGroupValue}&quot;
Add group &quot;{newGroupValue}&quot; </button>
</button> </fieldset>
</fieldset> </>
</> )
} }

View File

@@ -1,24 +1,29 @@
import {FC} from "react" import { FC } from 'react'
import {Recipe} from "../../../src/types" import { Recipe } from '../../../src/types'
import {EntityIcon} from "../EntityIcon/EntityIcon"; import { EntityIcon } from '../EntityIcon/EntityIcon'
import styles from './Recipe.module.css' import styles from './Recipe.module.css'
interface Props { interface Props {
recipe: Recipe recipe: Recipe
} }
export const RecipeSpan: FC<Props> = ({recipe}) => { export const RecipeSpan: FC<Props> = ({ recipe }) => {
const toEntityIcon = ([key, amount]: [string, number]) => <EntityIcon key={key} value={key} amount={amount} /> const toEntityIcon = ([key, amount]: [string, number]) => (
const joinByPlus = (elems: JSX.Element[]) => elems.reduce((acc, curr) => { <EntityIcon key={key} value={key} amount={amount} />
if (acc.length) { )
return [...acc, '+', curr] const joinByPlus = (elems: JSX.Element[]) =>
} else { elems.reduce((acc, curr) => {
return [curr] if (acc.length) {
} return [...acc, '+', curr]
}, [] as (JSX.Element|string)[]) } else {
const before = Object.entries({...recipe.prerequisites}).map(toEntityIcon) return [curr]
const after = Object.entries({...recipe.output}).map(toEntityIcon) }
return <span className={styles.recipe}> }, [] as (JSX.Element | string)[])
{joinByPlus([toEntityIcon(['/Time', recipe.time]), ...before])} {joinByPlus(after)} const before = Object.entries({ ...recipe.prerequisites }).map(toEntityIcon)
</span> const after = Object.entries({ ...recipe.output }).map(toEntityIcon)
return (
<span className={styles.recipe}>
{joinByPlus([toEntityIcon(['/Time', recipe.time]), ...before])} {joinByPlus(after)}
</span>
)
} }

View File

@@ -17,8 +17,8 @@
.node { .node {
padding: 0.5em; padding: 0.5em;
border-radius: 4px; border-radius: 4px;
border: 1px solid #DDDDDD; border: 1px solid #dddddd;
background-color: #EEE; background-color: #eee;
} }
.hidden { .hidden {

View File

@@ -1,29 +1,44 @@
import {FC, HTMLProps, PropsWithChildren, useEffect, useRef, useState} from "react"; import { FC, HTMLProps, PropsWithChildren, useEffect, useRef, useState } from 'react'
import styles from './ProducingGraph.module.css' import styles from './ProducingGraph.module.css'
import {EntityIcon} from "../../home/EntityIcon/EntityIcon"; import { EntityIcon } from '../../home/EntityIcon/EntityIcon'
import {createPath, drawLine} from "../../../src/svg"; import { createPath, drawLine } from '../../../src/svg'
import {AdditionalNode, GraphNode, GraphNodeWithIds, isAdditionalNode} from "../../../src/graph-untangle/types"; import {
import {graphUntangled} from "../../../src/graph-untangle"; AdditionalNode,
import {Dict} from "../../../src/types"; GraphNode,
GraphNodeWithIds,
isAdditionalNode
} from '../../../src/graph-untangle/types'
import { graphUntangled } from '../../../src/graph-untangle'
import { Dict } from '../../../src/types'
interface Props<T extends {}> { interface Props<T extends Dict<unknown>> {
nodes: GraphNode<T>[] nodes: GraphNode<T>[]
inputs: string[] inputs: string[]
outputs?: string[] outputs?: string[]
childType: FC<HTMLProps<HTMLDivElement> & {node: GraphNode<T>}> childType: FC<HTMLProps<HTMLDivElement> & { node: GraphNode<T> }>
} }
export const ProducingGraph = <T extends Dict<unknown>,>({nodes, inputs, outputs, childType: ChildType}: PropsWithChildren<Props<T>>) => { export const ProducingGraph = <T extends Dict<unknown>>({
nodes,
inputs,
outputs,
childType: ChildType
}: PropsWithChildren<Props<T>>) => {
const planeRef = useRef<HTMLDivElement>(null) const planeRef = useRef<HTMLDivElement>(null)
const [[rows, nodeMap], setGraph] = useState<[string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>]>(graphUntangled(nodes, inputs, outputs ?? [], 3000)) const [[rows, nodeMap]] = useState<[string[][], Dict<GraphNodeWithIds<T | AdditionalNode>>]>(
graphUntangled(nodes, inputs, outputs ?? [], 3000)
)
useEffect(() => { useEffect(() => {
if (!planeRef.current) return if (!planeRef.current) return
const plane = planeRef.current const plane = planeRef.current
function createSvgElement() { function createSvgElement() {
const elem = document.createElementNS("http://www.w3.org/2000/svg", "svg") const elem = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
elem.id = 'arrows' elem.id = 'arrows'
elem.setAttribute('style', 'position: absolute; inset: 0 0 0 0; pointer-events: none; z-index: -10;') elem.setAttribute(
'style',
'position: absolute; inset: 0 0 0 0; pointer-events: none; z-index: -10;'
)
elem.setAttributeNS(null, 'stroke', 'black') elem.setAttributeNS(null, 'stroke', 'black')
elem.setAttributeNS(null, 'fill', 'none') elem.setAttributeNS(null, 'fill', 'none')
plane.appendChild(elem) plane.appendChild(elem)
@@ -37,69 +52,75 @@ export const ProducingGraph = <T extends Dict<unknown>,>({nodes, inputs, outputs
svg.setAttributeNS(null, 'viewBox', `0 0 ${width} ${height}`) svg.setAttributeNS(null, 'viewBox', `0 0 ${width} ${height}`)
svg.replaceChildren() svg.replaceChildren()
let paths: string[] = [] const paths: string[] = []
plane.querySelectorAll('[data-outputs]').forEach(startNode => { plane.querySelectorAll('[data-outputs]').forEach(startNode => {
if (!(startNode instanceof HTMLElement)) return if (!(startNode instanceof HTMLElement)) return
(startNode.dataset.outputs?.split(' ') ?? []).forEach(output => { ;(startNode.dataset.outputs?.split(' ') ?? []).forEach(output => {
const endNode = plane.querySelector(`[data-name="${output}"]`) const endNode = plane.querySelector(`[data-name="${output}"]`)
if (!(endNode instanceof HTMLElement)) return if (!(endNode instanceof HTMLElement)) return
paths.push(createPath(plane.getBoundingClientRect(), startNode.getBoundingClientRect(), endNode.getBoundingClientRect())) paths.push(
createPath(
plane.getBoundingClientRect(),
startNode.getBoundingClientRect(),
endNode.getBoundingClientRect()
)
)
}) })
}) })
plane.querySelectorAll('[data-hidden="true"][data-outputs]').forEach(elem => { plane.querySelectorAll('[data-hidden="true"][data-outputs]').forEach(elem => {
if (!(elem instanceof HTMLElement)) return if (!(elem instanceof HTMLElement)) return
paths.push(drawLine(plane.getBoundingClientRect(), elem.getBoundingClientRect())) paths.push(drawLine(plane.getBoundingClientRect(), elem.getBoundingClientRect()))
}) })
const path = document.createElementNS('http://www.w3.org/2000/svg',"path") const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
path.setAttributeNS(null, 'd', paths.join(' ')) path.setAttributeNS(null, 'd', paths.join(' '))
svg.appendChild(path) svg.appendChild(path)
}) })
return <div className={styles.plane} ref={planeRef}> return (
{rows.map((row, colIdx) => ( <div className={styles.plane} ref={planeRef}>
<div className={styles.row} key={colIdx} data-row={true}> {rows.map((row, colIdx) => (
{ <div className={styles.row} key={colIdx} data-row={true}>
row.map((uid) => { {row.map(uid => {
const node = nodeMap[uid] const node = nodeMap[uid]
return ( return !isAdditionalNode(node) ? (
!isAdditionalNode(node) <span
? <span data-name={node.___uid}
data-name={node.___uid} data-inputs={node.___uidInputs.join(' ')}
data-inputs={node.___uidInputs.join(' ')} data-outputs={node.___uidOutputs.join(' ')}
data-outputs={node.___uidOutputs.join(' ')} key={node.___uid}
key={node.___uid} data-hidden={node.___uidOutputs.length > 0}
data-hidden={node.___uidOutputs.length > 0}> >
<ChildType <ChildType className={styles.node} node={node} />
className={styles.node} </span>
node={node} ) : node.___type === 'h' ? (
/> <span
</span> className={styles.hidden}
: node.___type === 'h' key={node.___uid}
? <span data-name={node.___uid}
className={styles.hidden} data-inputs={node.___uidInputs.join(' ')}
key={node.___uid} data-outputs={node.___uidOutputs.join(' ')}
data-name={node.___uid} data-hidden={true}
data-inputs={node.___uidInputs.join(' ')} ></span>
data-outputs={node.___uidOutputs.join(' ')} ) : node.___type === 'i' ? (
data-hidden={true}></span> <span
: node.___type === 'i' key={node.___uid}
? <span data-name={node.___uid}
key={node.___uid} data-outputs={node.___uidOutputs.join(' ')}
data-name={node.___uid} data-hidden={true}
data-outputs={node.___uidOutputs.join(' ')} >
data-hidden={true}> <EntityIcon value={node.name} />
<EntityIcon value={node.name}/> </span>
</span> ) : (
: <EntityIcon <EntityIcon
key={node.___uid} key={node.___uid}
value={node.name} value={node.name}
data-name={node.___uid} data-name={node.___uid}
data-inputs={node.___uidInputs.join(' ')} data-inputs={node.___uidInputs.join(' ')}
/> />
); )
}) })}
} </div>
</div> ))}
))} </div>
</div> )
} }

View File

@@ -1,25 +1,25 @@
import {FC, PropsWithChildren, useEffect, useRef} from "react"; import { FC, PropsWithChildren, useEffect, useRef } from 'react'
import IndianaDragScoll from "react-indiana-drag-scroll"; import IndianaDragScoll from 'react-indiana-drag-scroll'
import styles from './ScrollContainer.module.css' import styles from './ScrollContainer.module.css'
export const ScrollContainer: FC<PropsWithChildren> = ({children}) => { export const ScrollContainer: FC<PropsWithChildren> = ({ children }) => {
const container = useRef<HTMLDivElement>(null); const container = useRef<HTMLDivElement>(null)
useEffect(() => { useEffect(() => {
if (container.current) { if (container.current) {
container.current.oncontextmenu = e => e.preventDefault() container.current.oncontextmenu = e => e.preventDefault()
} }
}, []); }, [])
return <IndianaDragScoll return (
className={styles.container} <IndianaDragScoll
buttons={[2]} className={styles.container}
innerRef={container} buttons={[2]}
hideScrollbars={false} innerRef={container}
activationDistance={5} hideScrollbars={false}
> activationDistance={5}
<div className={styles.inner}> >
{children} <div className={styles.inner}>{children}</div>
</div> </IndianaDragScoll>
</IndianaDragScoll> )
} }

View File

@@ -1,9 +1,9 @@
import {FC, HTMLProps} from "react"; import { FC, HTMLProps } from 'react'
import {GraphNode} from "../../shared/ProducingGraph/ProducingGraph"; import { Recipe } from '../../../src/types'
import {Recipe} from "../../../src/types"; import cx from 'classnames'
import cx from "classnames"; import styles from './NodeDetails.module.css'
import styles from "./NodeDetails.module.css"; import { RecipeSpan } from '../../home/Recipe/Recipe'
import {RecipeSpan} from "../../home/Recipe/Recipe"; import { GraphNode } from '../../../src/graph-untangle/types'
export type DetailGraphNode = GraphNode<{ export type DetailGraphNode = GraphNode<{
recipes: Recipe[] recipes: Recipe[]
@@ -13,9 +13,13 @@ interface Props extends HTMLProps<HTMLDivElement> {
node: DetailGraphNode node: DetailGraphNode
} }
export const NodeDetails: FC<Props> = ({node, className, ...props}) => { export const NodeDetails: FC<Props> = ({ node, className, ...props }) => {
return <div {...props} className={cx(className, styles.root)}> return (
<h3>{node.name}</h3> <div {...props} className={cx(className, styles.root)}>
{node.recipes.map((recipe, idx) => <RecipeSpan key={idx} recipe={recipe}/>)} <h3>{node.name}</h3>
</div> {node.recipes.map((recipe, idx) => (
<RecipeSpan key={idx} recipe={recipe} />
))}
</div>
)
} }

View File

@@ -4,9 +4,9 @@
} }
.tiny { .tiny {
font-size: 0.5em; font-size: 0.5em;
margin-top: -1.6em; margin-top: -1.6em;
} }
.small { .small {
font-size: 0.8em; font-size: 0.8em;
@@ -15,4 +15,3 @@
.linkOut { .linkOut {
margin-inline-end: 0.5em; margin-inline-end: 0.5em;
} }

View File

@@ -1,14 +1,13 @@
import {FC, HTMLProps} from "react"; import { FC, HTMLProps } from 'react'
import {GraphNode} from "../../shared/ProducingGraph/ProducingGraph"; import { EnrichedEntity } from '../../../src/types'
import {EnrichedEntity, Recipe} from "../../../src/types"; import cx from 'classnames'
import cx from "classnames"; import styles from './NodeOverview.module.css'
import styles from "./NodeOverview.module.css"; import Link from 'next/link'
import {RecipeSpan} from "../../home/Recipe/Recipe"; import { EntityIcon } from '../../home/EntityIcon/EntityIcon'
import Link from "next/link"; import { GraphNode } from '../../../src/graph-untangle/types'
import {EntityIcon} from "../../home/EntityIcon/EntityIcon";
export type OverviewGraphNode = GraphNode<{ export type OverviewGraphNode = GraphNode<{
icons: (EnrichedEntity|string)[] icons: (EnrichedEntity | string)[]
linkOut: string linkOut: string
}> }>
@@ -16,21 +15,38 @@ interface Props extends HTMLProps<HTMLDivElement> {
node: OverviewGraphNode node: OverviewGraphNode
} }
export const NodeOverview: FC<Props> = ({node, className, ...props}) => { export const NodeOverview: FC<Props> = ({ node, className, ...props }) => {
return <div {...props} className={cx(className, styles.root)}> return (
<h3><span className={styles.linkOut}><Link href={node.linkOut}>🔗</Link></span>{node.name}</h3> <div {...props} className={cx(className, styles.root)}>
{ node.icons?.length ? <div className={styles.tiny}> <h3>
{node.icons.map((input) => <EntityIcon key={typeof input === "string" ? input : input.href} value={input} />)} <span className={styles.linkOut}>
</div> : null } <Link href={node.linkOut}>🔗</Link>
<h4>Inputs</h4> </span>
<div className={styles.small}> {node.name}
{node.inputs.map((input) => <EntityIcon key={input} value={input} />)} </h3>
</div> {node.icons?.length ? (
{node.outputs.length ? <> <div className={styles.tiny}>
<h4>Outputs</h4> {node.icons.map(input => (
<EntityIcon key={typeof input === 'string' ? input : input.href} value={input} />
))}
</div>
) : null}
<h4>Inputs</h4>
<div className={styles.small}> <div className={styles.small}>
{node.outputs.map((input) => <EntityIcon key={input} value={input} />)} {node.inputs.map(input => (
<EntityIcon key={input} value={input} />
))}
</div> </div>
</>: null} {node.outputs.length ? (
</div> <>
<h4>Outputs</h4>
<div className={styles.small}>
{node.outputs.map(input => (
<EntityIcon key={input} value={input} />
))}
</div>
</>
) : null}
</div>
)
} }

View File

@@ -1,72 +1,74 @@
import {useRouter} from "next/router"; import { useRouter } from 'next/router'
import {GroupProvider, useGroups} from "../contexts/GroupProvider"; import { useGroups } from '../contexts/GroupProvider'
import {useFactories} from "../../src/hooks/useFactories"; import { useFactories } from '../../src/hooks/useFactories'
import {FC, useEffect, useMemo} from "react"; import { FC, useEffect, useMemo } from 'react'
import {calculateInputs} from "../../src/calculateInputs"; import { calculateInputs } from '../../src/calculateInputs'
import {DetailGraphNode, NodeDetails} from "./NodeDetails/NodeDetails"; import { DetailGraphNode, NodeDetails } from './NodeDetails/NodeDetails'
import {groupBy, isNonNullable, uniquify} from "../../src/utils"; import { groupBy, isNonNullable, uniquify } from '../../src/utils'
import {EnrichedEntity} from "../../src/types"; import { EnrichedEntity } from '../../src/types'
import Head from "next/head"; import Head from 'next/head'
import {ScrollContainer} from "../shared/ScrollContainer/ScrollContainer"; import { ScrollContainer } from '../shared/ScrollContainer/ScrollContainer'
import {ProducingGraph} from "../shared/ProducingGraph/ProducingGraph"; import { ProducingGraph } from '../shared/ProducingGraph/ProducingGraph'
export const PageDetails: FC = () => { export const PageDetails: FC = () => {
const {query: {name}} = useRouter()
const { const {
exportedFactories, query: { name }
baseFactories, } = useRouter()
ignoredFactories, const { exportedFactories, baseFactories, groups } = useGroups()
groups const { findFactory } = useFactories()
} = useGroups()
const {
findFactory
} = useFactories()
useEffect(() => { useEffect(() => {
document.body.classList.add("scroll"); document.body.classList.add('scroll')
return () => document.body.classList.remove("scroll") return () => document.body.classList.remove('scroll')
}, []); }, [])
const group = typeof name === 'string' ? groups[name] : undefined const group = typeof name === 'string' ? groups[name] : undefined
const [inputFactories, intermediateFactories] = useMemo<ReturnType<typeof calculateInputs>>(() => { const [inputFactories, intermediateFactories] = useMemo<
ReturnType<typeof calculateInputs>
>(() => {
if (!group) return [[], []] if (!group) return [[], []]
return calculateInputs( return calculateInputs(
[...group.exports, ...group.malls], [...group.exports, ...group.malls],
ignoredFactories,
baseFactories, baseFactories,
exportedFactories, exportedFactories,
findFactory findFactory
) )
}, [baseFactories, exportedFactories, findFactory, group, ignoredFactories]) }, [baseFactories, exportedFactories, findFactory, group])
const producingNodes: DetailGraphNode[] = useMemo(() => { const producingNodes: DetailGraphNode[] = useMemo(() => {
if (!group) return [] if (!group) return []
const nodes = uniquify([...intermediateFactories, ...group.exports, ...group.malls]) const nodes = uniquify([...intermediateFactories, ...group.exports, ...group.malls])
.map(findFactory) .map(findFactory)
.filter(isNonNullable) .filter(isNonNullable)
.map((factory: EnrichedEntity) => ({ .map(
inputs: Object.keys(factory.recipe?.prerequisites ?? {}).sort((a, b) => a.localeCompare(b)), (factory: EnrichedEntity) =>
outputs: Object.keys(factory.recipe?.output ?? {}).sort((a, b) => a.localeCompare(b)), ({
name: factory.name, inputs: Object.keys(factory.recipe?.prerequisites ?? {}).sort((a, b) =>
recipes: [factory.recipe] a.localeCompare(b)
} as DetailGraphNode)) ),
return Object outputs: Object.keys(factory.recipe?.output ?? {}).sort((a, b) => a.localeCompare(b)),
.values(groupBy(nodes, node => node.inputs.join())) name: factory.name,
.map(nodesOfInput => ({ recipes: [factory.recipe]
inputs: nodesOfInput[0].inputs, } as DetailGraphNode)
outputs: uniquify(nodesOfInput.flatMap(node => node.outputs)), )
name: nodesOfInput.map(node => node.name).join(', '), return Object.values(groupBy(nodes, node => node.inputs.join())).map(
recipes: nodesOfInput.flatMap(node => node.recipes) nodesOfInput =>
} as DetailGraphNode)) ({
inputs: nodesOfInput[0].inputs,
outputs: uniquify(nodesOfInput.flatMap(node => node.outputs)),
name: nodesOfInput.map(node => node.name).join(', '),
recipes: nodesOfInput.flatMap(node => node.recipes)
} as DetailGraphNode)
)
}, [findFactory, group, intermediateFactories]) }, [findFactory, group, intermediateFactories])
return ( return (
<> <>
<Head> <Head>
<title>Factorio Microservices</title> <title>Factorio Microservices</title>
<meta name="description" content="Create Factorio microservices" /> <meta name='description' content='Create Factorio microservices' />
<link rel="icon" href="/public/favicon.ico" /> <link rel='icon' href='/public/favicon.ico' />
</Head> </Head>
<main> <main>
<ScrollContainer> <ScrollContainer>

View File

@@ -6,7 +6,11 @@
"dev": "next dev", "dev": "next dev",
"build": "next build", "build": "next build",
"start": "next start", "start": "next start",
"lint": "next lint" "lint": "next lint",
"lint:fix": "tsc --noEmit && prettier --write --loglevel warn . && eslint --fix . && stylelint --fix **/*.css",
"eslint:fix": "eslint --fix .",
"stylelint:fix": " stylelint --fix **/*.css",
"prepare": "husky install"
}, },
"dependencies": { "dependencies": {
"classnames": "^2.3.1", "classnames": "^2.3.1",
@@ -30,9 +34,18 @@
"@types/react": "18.0.17", "@types/react": "18.0.17",
"@types/react-dom": "18.0.6", "@types/react-dom": "18.0.6",
"@types/seedrandom": "^3.0.2", "@types/seedrandom": "^3.0.2",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"eslint": "8.21.0", "eslint": "8.21.0",
"eslint-config-next": "12.2.4", "eslint-config-next": "12.2.4",
"eslint-plugin-unused-imports": "^2.0.0",
"husky": "^8.0.1",
"json-schema-to-typescript": "^11.0.2", "json-schema-to-typescript": "^11.0.2",
"lint-staged": "^13.0.3",
"prettier": "^2.7.1",
"stylelint": "^14.10.0",
"stylelint-config-idiomatic-order": "^8.1.0",
"stylelint-config-standard": "^27.0.0",
"typescript": "4.7.4" "typescript": "4.7.4"
} }
} }

View File

@@ -1,7 +1,6 @@
import '../styles/globals.css' import '../styles/globals.css'
import type { AppProps } from 'next/app' import type { AppProps } from 'next/app'
import {GroupProvider} from "../components/contexts/GroupProvider"; import { FC } from 'react'
import {FC} from "react";
const MyApp: FC<AppProps> = ({ Component, pageProps }) => { const MyApp: FC<AppProps> = ({ Component, pageProps }) => {
return <Component {...pageProps} /> return <Component {...pageProps} />

View File

@@ -1,18 +1,18 @@
import {Html, Main, NextScript, DocumentProps, Head} from 'next/document'; import { Html, Main, NextScript, DocumentProps, Head } from 'next/document'
import {FC} from "react"; import { FC } from 'react'
import Dict = NodeJS.Dict; import Dict = NodeJS.Dict
const MyDocument: FC<DocumentProps> = ({ __NEXT_DATA__ }) => { const MyDocument: FC<DocumentProps> = ({ __NEXT_DATA__ }) => {
const pageProps: Dict<unknown>|undefined = __NEXT_DATA__?.props?.pageProps; const pageProps: Dict<unknown> | undefined = __NEXT_DATA__?.props?.pageProps
return ( return (
<Html> <Html>
<Head /> <Head />
<body className={pageProps?.bodyClassName as string}> <body className={pageProps?.bodyClassName as string}>
<Main /> <Main />
<NextScript /> <NextScript />
</body> </body>
</Html> </Html>
); )
} }
export default MyDocument export default MyDocument

View File

@@ -1,8 +1,8 @@
import {nextHandler} from "../../../src/utils/errors"; import { nextHandler } from '../../../src/utils/errors'
import {validate} from "../../../src/validation"; import { validate } from '../../../src/validation'
import {IdParam, SetFactoryArrayBody} from "../../../src/types/ApiSchemas"; import { IdParam, SetFactoryArrayBody } from '../../../src/types/ApiSchemas'
import {setFactories} from "../../../src/database/groups"; import { setFactories } from '../../../src/database/groups'
import {waitForInitSchemas} from "../../../src/validation/schemas"; import { waitForInitSchemas } from '../../../src/validation/schemas'
const handler = nextHandler(async (req, res) => { const handler = nextHandler(async (req, res) => {
if (req.method !== 'POST') throw new Error('Invalid method') if (req.method !== 'POST') throw new Error('Invalid method')

View File

@@ -1,8 +1,8 @@
import {nextHandler} from "../../../../../src/utils/errors"; import { nextHandler } from '../../../../../src/utils/errors'
import {validate} from "../../../../../src/validation"; import { validate } from '../../../../../src/validation'
import {GroupIdParam} from "../../../../../src/types/ApiSchemas"; import { GroupIdParam } from '../../../../../src/types/ApiSchemas'
import {addGroup} from "../../../../../src/database/groups"; import { addGroup } from '../../../../../src/database/groups'
import {waitForInitSchemas} from "../../../../../src/validation/schemas"; import { waitForInitSchemas } from '../../../../../src/validation/schemas'
const handler = nextHandler(async (req, res) => { const handler = nextHandler(async (req, res) => {
if (req.method !== 'POST') throw new Error('Invalid method') if (req.method !== 'POST') throw new Error('Invalid method')

View File

@@ -1,14 +1,17 @@
import {nextHandler} from "../../../../../src/utils/errors"; import { nextHandler } from '../../../../../src/utils/errors'
import {validate} from "../../../../../src/validation"; import { validate } from '../../../../../src/validation'
import {GroupIdParam, GroupSetFactoryArrayBody} from "../../../../../src/types/ApiSchemas"; import { GroupIdParam, GroupSetFactoryArrayBody } from '../../../../../src/types/ApiSchemas'
import {setFactoriesOfGroup} from "../../../../../src/database/groups"; import { setFactoriesOfGroup } from '../../../../../src/database/groups'
import {waitForInitSchemas} from "../../../../../src/validation/schemas"; import { waitForInitSchemas } from '../../../../../src/validation/schemas'
const handler = nextHandler(async (req, res) => { const handler = nextHandler(async (req, res) => {
if (req.method !== 'POST') throw new Error('Invalid method') if (req.method !== 'POST') throw new Error('Invalid method')
await waitForInitSchemas.resolve() await waitForInitSchemas.resolve()
const { transformed: params } = validate<GroupIdParam>(req.query, '/GroupIdParam') const { transformed: params } = validate<GroupIdParam>(req.query, '/GroupIdParam')
const { transformed: body } = validate<GroupSetFactoryArrayBody>(req.body, '/GroupSetFactoryArrayBody') const { transformed: body } = validate<GroupSetFactoryArrayBody>(
req.body,
'/GroupSetFactoryArrayBody'
)
const success = await setFactoriesOfGroup(params.id, params.name, body.type, body.factories) const success = await setFactoriesOfGroup(params.id, params.name, body.type, body.factories)
res.json({ success }) res.json({ success })

View File

@@ -1,8 +1,8 @@
import {nextHandler} from "../../../../../src/utils/errors"; import { nextHandler } from '../../../../../src/utils/errors'
import {validate} from "../../../../../src/validation"; import { validate } from '../../../../../src/validation'
import {GroupIdParam} from "../../../../../src/types/ApiSchemas"; import { GroupIdParam } from '../../../../../src/types/ApiSchemas'
import {removeGroup} from "../../../../../src/database/groups"; import { removeGroup } from '../../../../../src/database/groups'
import {waitForInitSchemas} from "../../../../../src/validation/schemas"; import { waitForInitSchemas } from '../../../../../src/validation/schemas'
const handler = nextHandler(async (req, res) => { const handler = nextHandler(async (req, res) => {
if (req.method !== 'POST') throw new Error('Invalid method') if (req.method !== 'POST') throw new Error('Invalid method')

View File

@@ -1,8 +1,8 @@
import {nextHandler} from "../../../../../src/utils/errors"; import { nextHandler } from '../../../../../src/utils/errors'
import {validate} from "../../../../../src/validation"; import { validate } from '../../../../../src/validation'
import {GroupIdParam, GroupRenameBody} from "../../../../../src/types/ApiSchemas"; import { GroupIdParam, GroupRenameBody } from '../../../../../src/types/ApiSchemas'
import {renameGroup} from "../../../../../src/database/groups"; import { renameGroup } from '../../../../../src/database/groups'
import {waitForInitSchemas} from "../../../../../src/validation/schemas"; import { waitForInitSchemas } from '../../../../../src/validation/schemas'
const handler = nextHandler(async (req, res) => { const handler = nextHandler(async (req, res) => {
if (req.method !== 'POST') throw new Error('Invalid method') if (req.method !== 'POST') throw new Error('Invalid method')

View File

@@ -1,9 +1,10 @@
import {GroupData, setGroups} from "../../../src/database/groups"; import { NetworkError, nextHandler } from '../../../src/utils/errors'
import {NetworkError, nextHandler} from "../../../src/utils/errors"; import getConfig from 'next/config'
import getConfig from "next/config"; import { waitForInitSchemas } from '../../../src/validation/schemas'
import {addSchemas, waitForInitSchemas} from "../../../src/validation/schemas";
const {publicRuntimeConfig: {TENANT_TYPE}} = getConfig() const {
publicRuntimeConfig: { TENANT_TYPE }
} = getConfig()
const handler = nextHandler(async (req, res) => { const handler = nextHandler(async (req, res) => {
if (req.method !== 'GET') throw new NetworkError('Invalid method') if (req.method !== 'GET') throw new NetworkError('Invalid method')

View File

@@ -1,6 +1,6 @@
import {GroupData, setGroups} from "../../src/database/groups"; import { GroupData, setGroups } from '../../src/database/groups'
import {nextHandler} from "../../src/utils/errors"; import { nextHandler } from '../../src/utils/errors'
import {waitForInitSchemas} from "../../src/validation/schemas"; import { waitForInitSchemas } from '../../src/validation/schemas'
const handler = nextHandler(async (req, res) => { const handler = nextHandler(async (req, res) => {
if (req.method !== 'POST') throw new Error('Invalid method') if (req.method !== 'POST') throw new Error('Invalid method')

View File

@@ -1,23 +1,18 @@
import type {GetServerSideProps, NextPage} from 'next' import type { NextPage } from 'next'
import Head from 'next/head' import Head from 'next/head'
import {Home} from "../components/home/Home"; import { Home } from '../components/home/Home'
import {useEffect} from "react"; import { GroupProvider } from '../components/contexts/GroupProvider'
import {GroupProvider} from "../components/contexts/GroupProvider"; import { getServerSidePropsGroupProvider, PropsGroupProvider } from '../src/getServerSideProps'
import {getGroup, setGroups} from "../src/database/groups";
import {Dict, Group} from "../src/types";
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../src/getServerSideProps";
const Page: NextPage<PropsGroupProvider> = ({ id, ...initial }) => {
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
return ( return (
<GroupProvider id={id} initial={initial}> <GroupProvider id={id} initial={initial}>
<Head> <Head>
<title>Factorio Microservices</title> <title>Factorio Microservices</title>
<meta name="description" content="Create Factorio microservices" /> <meta name='description' content='Create Factorio microservices' />
<link rel="icon" href="/favicon.ico" /> <link rel='icon' href='/favicon.ico' />
</Head> </Head>
<Home/> <Home />
</GroupProvider> </GroupProvider>
) )
} }

View File

@@ -1,13 +1,12 @@
import type { NextPage } from 'next' import type { NextPage } from 'next'
import {GroupProvider} from "../../components/contexts/GroupProvider"; import { GroupProvider } from '../../components/contexts/GroupProvider'
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../../src/getServerSideProps"; import { getServerSidePropsGroupProvider, PropsGroupProvider } from '../../src/getServerSideProps'
import {PageDetails} from "../../components/visualize/PageDetails"; import { PageDetails } from '../../components/visualize/PageDetails'
const Page: NextPage<PropsGroupProvider> = ({ id, ...initial }) => {
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
return ( return (
<GroupProvider id={id} initial={initial}> <GroupProvider id={id} initial={initial}>
<PageDetails/> <PageDetails />
</GroupProvider> </GroupProvider>
) )
} }

View File

@@ -1,36 +1,31 @@
import type {NextPage} from 'next' import type { NextPage } from 'next'
import Head from 'next/head' import Head from 'next/head'
import {GroupProvider, useGroups} from "../../components/contexts/GroupProvider"; import { GroupProvider, useGroups } from '../../components/contexts/GroupProvider'
import {useFactories} from "../../src/hooks/useFactories"; import { useFactories } from '../../src/hooks/useFactories'
import {ProducingGraph} from "../../components/shared/ProducingGraph/ProducingGraph"; import { ProducingGraph } from '../../components/shared/ProducingGraph/ProducingGraph'
import {useEffect, useMemo} from "react"; import { useEffect, useMemo } from 'react'
import {calculateInputs} from "../../src/calculateInputs"; import { calculateInputs } from '../../src/calculateInputs'
import {NodeOverview, OverviewGraphNode} from "../../components/visualize/NodeOverview/NodeOverview"; import {
import {fixedEncodeURIComponent} from "../../src/utils"; NodeOverview,
import {ScrollContainer} from "../../components/shared/ScrollContainer/ScrollContainer"; OverviewGraphNode
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../../src/getServerSideProps"; } from '../../components/visualize/NodeOverview/NodeOverview'
import { fixedEncodeURIComponent } from '../../src/utils'
import { ScrollContainer } from '../../components/shared/ScrollContainer/ScrollContainer'
import { getServerSidePropsGroupProvider, PropsGroupProvider } from '../../src/getServerSideProps'
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => { const Page: NextPage<PropsGroupProvider> = ({ id, ...initial }) => {
const { const { exportedFactories, baseFactories, groups } = useGroups()
exportedFactories, const { findFactory } = useFactories()
ignoredFactories,
baseFactories,
groups
} = useGroups()
const {
findFactory
} = useFactories()
useEffect(() => { useEffect(() => {
document.body.classList.add("scroll"); document.body.classList.add('scroll')
return () => document.body.classList.remove("scroll") return () => document.body.classList.remove('scroll')
}, []); }, [])
const producingNodes: OverviewGraphNode[] = useMemo(() => { const producingNodes: OverviewGraphNode[] = useMemo(() => {
return Object.values(groups).map(group => ({ return Object.values(groups).map(group => ({
inputs: calculateInputs( inputs: calculateInputs(
[...group.exports, ...group.malls], [...group.exports, ...group.malls],
ignoredFactories,
baseFactories, baseFactories,
exportedFactories, exportedFactories,
findFactory findFactory
@@ -40,19 +35,19 @@ const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
icons: [...group.exports, ...group.malls], icons: [...group.exports, ...group.malls],
linkOut: `./visualize/${fixedEncodeURIComponent(group.name)}` linkOut: `./visualize/${fixedEncodeURIComponent(group.name)}`
})) }))
}, [baseFactories, exportedFactories, findFactory, groups, ignoredFactories]) }, [baseFactories, exportedFactories, findFactory, groups])
return ( return (
<GroupProvider id={id} initial={initial}> <GroupProvider id={id} initial={initial}>
<Head> <Head>
<title>Factorio Microservices</title> <title>Factorio Microservices</title>
<meta name="description" content="Create Factorio microservices" /> <meta name='description' content='Create Factorio microservices' />
<link rel="icon" href="/public/favicon.ico" /> <link rel='icon' href='/public/favicon.ico' />
</Head> </Head>
<main> <main>
<ScrollContainer> <ScrollContainer>
<h1>Factorio Microservices</h1> <h1>Factorio Microservices</h1>
<ProducingGraph nodes={producingNodes} inputs={baseFactories} childType={NodeOverview}/> <ProducingGraph nodes={producingNodes} inputs={baseFactories} childType={NodeOverview} />
</ScrollContainer> </ScrollContainer>
</main> </main>
</GroupProvider> </GroupProvider>

File diff suppressed because one or more lines are too long

View File

@@ -1,20 +1,24 @@
import {EnrichedEntity} from "./types"; import { EnrichedEntity } from './types'
export const calculateInputs = (allProducingFactories: string[], ignoredFactories: string[], baseFactories: string[], exportedFactories: Set<string>, findFactory: (uid: string) => EnrichedEntity|undefined) => { export const calculateInputs = (
const prducingSet = new Set(allProducingFactories) allProducingFactories: string[],
const ignored = new Set(ignoredFactories) baseFactories: string[],
exportedFactories: Set<string>,
findFactory: (uid: string) => EnrichedEntity | undefined
) => {
const producingSet = new Set(allProducingFactories)
const base = new Set(baseFactories) const base = new Set(baseFactories)
const inputs = new Set<string>() const inputs = new Set<string>()
const intermediates = new Set<string>() const intermediates = new Set<string>()
let next: string|undefined let next: string | undefined
while (next = allProducingFactories.pop()) { while ((next = allProducingFactories.pop())) {
const pres = Object.keys(findFactory(next)?.recipe?.prerequisites ?? {}) const pres = Object.keys(findFactory(next)?.recipe?.prerequisites ?? {})
for (const pre of pres) { for (const pre of pres) {
if (exportedFactories.has(pre) || base.has(pre)) { if (exportedFactories.has(pre) || base.has(pre)) {
if (!prducingSet.has(pre)) inputs.add(pre) if (!producingSet.has(pre)) inputs.add(pre)
} else if (!intermediates.has(pre)) { } else if (!intermediates.has(pre)) {
if (!prducingSet.has(pre)) intermediates.add(pre) if (!producingSet.has(pre)) intermediates.add(pre)
allProducingFactories.push(pre) allProducingFactories.push(pre)
} }
} }

View File

@@ -1,22 +1,22 @@
import {database} from "./start"; import { database } from './start'
import {Dict, Group} from "../types"; import { Dict, Group } from '../types'
import {Filter, ObjectId} from "mongodb"; import { Filter, ObjectId } from 'mongodb'
export interface GroupData { export interface GroupData {
groups: Dict<Group>, groups: Dict<Group>
ignored: string[], ignored: string[]
base: string[] base: string[]
} }
export type InsertMeta<T> = T & { export type InsertMeta<T> = T & {
createdOn: Date, createdOn: Date
modifiedOn: Date, modifiedOn: Date
accessedOn: Date accessedOn: Date
} }
type GroupFilter = Filter<InsertMeta<GroupData>> type GroupFilter = Filter<InsertMeta<GroupData>>
export async function setGroups(data: GroupData): Promise<string|undefined> { export async function setGroups(data: GroupData): Promise<string | undefined> {
const collection = (await database.resolve())?.collection('setups') const collection = (await database.resolve())?.collection('setups')
if (!collection) return if (!collection) return
const result = await collection.insertOne({ const result = await collection.insertOne({
@@ -25,7 +25,6 @@ export async function setGroups(data: GroupData): Promise<string|undefined> {
modifiedOn: new Date(), modifiedOn: new Date(),
accessedOn: new Date() accessedOn: new Date()
}) })
console.log(result.insertedId, result.insertedId.toString())
return result.insertedId.toString() return result.insertedId.toString()
} }
@@ -35,38 +34,48 @@ function getUuid(uuid: string): GroupFilter {
} }
} }
export async function setFactories(uuid: string, type: 'ignored'|'base', factories: string[]): Promise<boolean> { export async function setFactories(
uuid: string,
type: 'ignored' | 'base',
factories: string[]
): Promise<boolean> {
const collection = (await database.resolve())?.collection('setups') const collection = (await database.resolve())?.collection('setups')
if (!collection) return false if (!collection) return false
collection.updateOne(getUuid(uuid), {$set: {[type]: factories} as never}) collection.updateOne(getUuid(uuid), { $set: { [type]: factories } as never })
return true return true
} }
export async function getGroup(uuid: string) { export async function getGroup(uuid: string) {
const collection = (await database.resolve())?.collection('setups') const collection = (await database.resolve())?.collection('setups')
if (!collection) return if (!collection) return
const data = (await collection.findOne(getUuid(uuid))) ?? undefined const data = (await collection.findOne(getUuid(uuid))) ?? undefined
if (data) { if (data) {
await collection.updateOne(getUuid(uuid), { $set: {accessedOn: new Date()}}) await collection.updateOne(getUuid(uuid), { $set: { accessedOn: new Date() } })
} }
return data return data
} }
export async function renameGroup(uuid: string, oldName: string, newName: string): Promise<boolean> { export async function renameGroup(
uuid: string,
oldName: string,
newName: string
): Promise<boolean> {
oldName = oldName.replace(/[.$]/g, '') oldName = oldName.replace(/[.$]/g, '')
newName = newName.replace(/[.$]/g, '') newName = newName.replace(/[.$]/g, '')
const data = await getGroup(uuid) const data = await getGroup(uuid)
if (data?.groups && !(newName in data.groups)) { if (data?.groups && !(newName in data.groups)) {
const collection = (await database.resolve())?.collection('setups') const collection = (await database.resolve())?.collection('setups')
console.log("fere", `groups.${oldName}`, `groups.${newName}`)
if (!collection) return false if (!collection) return false
await collection.updateOne(getUuid(uuid), { $set: { await collection.updateOne(getUuid(uuid), {
$set: {
[`groups.${oldName}.name`]: newName [`groups.${oldName}.name`]: newName
} as never}) } as never
await collection.updateOne(getUuid(uuid), { $rename: { })
await collection.updateOne(getUuid(uuid), {
$rename: {
[`groups.${oldName}`]: `groups.${newName}` [`groups.${oldName}`]: `groups.${newName}`
}}) }
})
return true return true
} }
return false return false
@@ -78,7 +87,9 @@ export async function addGroup(uuid: string, name: string): Promise<boolean> {
if (data?.groups && !(name in data.groups)) { if (data?.groups && !(name in data.groups)) {
const collection = (await database.resolve())?.collection('setups') const collection = (await database.resolve())?.collection('setups')
if (!collection) return false if (!collection) return false
await collection.updateOne(getUuid(uuid), {$set: {[`groups.${name}`]: {name, exports: [], malls: []} as never}}) await collection.updateOne(getUuid(uuid), {
$set: { [`groups.${name}`]: { name, exports: [], malls: [] } as never }
})
return true return true
} }
return false return false
@@ -90,20 +101,26 @@ export async function removeGroup(uuid: string, name: string): Promise<boolean>
if (data?.groups && name in data.groups) { if (data?.groups && name in data.groups) {
const collection = (await database.resolve())?.collection('setups') const collection = (await database.resolve())?.collection('setups')
if (!collection) return false if (!collection) return false
console.log(`groups.${name}`) await collection.updateOne(getUuid(uuid), { $unset: { [`groups.${name}`]: '' } })
await collection.updateOne(getUuid(uuid), {$unset: {[`groups.${name}`]: ""}})
return true return true
} }
return false return false
} }
export async function setFactoriesOfGroup(uuid: string, name: string, type: 'exports'|'malls', factories: string[]): Promise<boolean> { export async function setFactoriesOfGroup(
uuid: string,
name: string,
type: 'exports' | 'malls',
factories: string[]
): Promise<boolean> {
name = name.replace(/[.$]/g, '') name = name.replace(/[.$]/g, '')
const data = await getGroup(uuid) const data = await getGroup(uuid)
if (data?.groups && (name in data.groups)) { if (data?.groups && name in data.groups) {
const collection = (await database.resolve())?.collection('setups') const collection = (await database.resolve())?.collection('setups')
if (!collection) return false if (!collection) return false
await collection.updateOne(getUuid(uuid), {$set: {[`groups.${name}.${type}`]: factories} as never}) await collection.updateOne(getUuid(uuid), {
$set: { [`groups.${name}.${type}`]: factories } as never
})
return true return true
} }
return false return false

View File

@@ -1,23 +1,21 @@
import {Collection, Db, MongoClient} from 'mongodb' import { Collection, Db, MongoClient } from 'mongodb'
import getConfig from 'next/config' import getConfig from 'next/config'
import {Resolvable} from "../utils/Resolvable"; import { Resolvable } from '../utils/Resolvable'
import {GroupData, InsertMeta} from "./groups"; import { GroupData, InsertMeta } from './groups'
import { logger } from '../utils/logger'
const { serverRuntimeConfig: { const {
MONGO_URL, serverRuntimeConfig: { MONGO_URL, MONGO_USER, MONGO_PASS, MONGO_DB }
MONGO_USER, } = getConfig()
MONGO_PASS,
MONGO_DB
} } = getConfig()
async function getDatabase() { async function getDatabase() {
const url = `mongodb://${MONGO_USER ? `${MONGO_USER}:${MONGO_PASS ?? ''}@` : ''}${MONGO_URL}`; const url = `mongodb://${MONGO_USER ? `${MONGO_USER}:${MONGO_PASS ?? ''}@` : ''}${MONGO_URL}`
const client = new MongoClient(url); const client = new MongoClient(url)
await client.connect(); await client.connect()
console.log('Connected successfully to server') logger.info('Connected successfully to server')
return client.db(MONGO_DB) as unknown as (Omit<Db, 'collection'> & { return client.db(MONGO_DB) as unknown as Omit<Db, 'collection'> & {
collection : (_: 'setups') => Collection<InsertMeta<GroupData>> collection: (_: 'setups') => Collection<InsertMeta<GroupData>>
}) }
} }
export const database = new Resolvable(getDatabase) export const database = new Resolvable(getDatabase)

View File

@@ -1,29 +1,30 @@
export function download(filename: string, data: Uint8Array) { export function download(filename: string, data: Uint8Array) {
const tag = document.createElement("a"); const tag = document.createElement('a')
tag.style.display = "none"; tag.style.display = 'none'
document.body.appendChild(tag); document.body.appendChild(tag)
const blob = new Blob([data], {type: "octet/stream"}), const blob = new Blob([data], { type: 'octet/stream' }),
url = window.URL.createObjectURL(blob); url = window.URL.createObjectURL(blob)
tag.href = url; tag.href = url
tag.download = filename; tag.download = filename
tag.click(); tag.click()
window.URL.revokeObjectURL(url); window.URL.revokeObjectURL(url)
document.body.removeChild(tag); document.body.removeChild(tag)
} }
export async function streamToArrayBuffer(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> { export async function streamToArrayBuffer(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
let result = new Uint8Array(0); let result = new Uint8Array(0)
const reader = stream.getReader(); const reader = stream.getReader()
while (true) { // eslint-disable-line no-constant-condition while (true) {
const { done, value } = await reader.read(); // eslint-disable-line no-constant-condition
const { done, value } = await reader.read()
if (done) { if (done) {
break; break
} }
const newResult = new Uint8Array(result.length + value.length); const newResult = new Uint8Array(result.length + value.length)
newResult.set(result); newResult.set(result)
newResult.set(value, result.length); newResult.set(value, result.length)
result = newResult result = newResult
} }
return result; return result
} }

View File

@@ -1,6 +1,6 @@
import {GetServerSideProps} from "next"; import { GetServerSideProps } from 'next'
import {getGroup, setGroups} from "./database/groups"; import { getGroup, setGroups } from './database/groups'
import {Dict, Group} from "./types"; import { Dict, Group } from './types'
export interface PropsGroupProvider { export interface PropsGroupProvider {
id: string id: string
@@ -9,9 +9,11 @@ export interface PropsGroupProvider {
base: string[] base: string[]
} }
export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvider> = async ({query}) => { export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvider> = async ({
query
}) => {
const id = Array.isArray(query?.id) ? query.id[0] : query?.id const id = Array.isArray(query?.id) ? query.id[0] : query?.id
const data = id && await getGroup(id) const data = id && (await getGroup(id))
if (data) { if (data) {
return { return {
props: { props: {
@@ -22,15 +24,14 @@ export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvi
} }
} }
} else if (!id) { } else if (!id) {
const newId = await setGroups({groups: {}, base: [], ignored: []}) const newId = await setGroups({ groups: {}, base: [], ignored: [] })
return { return {
redirect: { redirect: {
destination: `?id=${newId}`, destination: `?id=${newId}`,
permanent: false, permanent: false
} }
} }
} else { } else {
console.log(data)
return { return {
notFound: true notFound: true
} }

View File

@@ -1,31 +1,48 @@
import {AdditionalNode, GraphNode, GraphNodeWithIds, isAdditionalNode} from "./types"; import { AdditionalNode, GraphNode, GraphNodeWithIds } from './types'
import {Dict} from "../types"; import { Dict } from '../types'
import deepcopy from "deepcopy"; import deepcopy from 'deepcopy'
import {isNonNullable, shuffleInplace, sortByProperty, uniquify} from "../utils"; import { isNonNullable, shuffleInplace, sortByProperty, uniquify } from '../utils'
import seedrandom from "seedrandom"; import seedrandom from 'seedrandom'
function generateIds<T extends Dict<unknown>>(node: GraphNode<T>, nodeUid: () => string): GraphNodeWithIds<T> { function generateIds<T extends Dict<unknown>>(
node: GraphNode<T>,
nodeUid: () => string
): GraphNodeWithIds<T> {
return { return {
...node, ...node,
___uid: `${node.name.replace(/[^a-z]/gi, '').toLowerCase().substring(0, 3)}_${nodeUid()}`, ___uid: `${node.name
.replace(/[^a-z]/gi, '')
.toLowerCase()
.substring(0, 3)}_${nodeUid()}`,
___uidInputs: [], ___uidInputs: [],
___uidOutputs: [] ___uidOutputs: []
} }
} }
function generateAdditional<T extends Dict<unknown>>(uid: string, type: 'i'|'h'|'o', nodeUid: () => string): GraphNodeWithIds<AdditionalNode> { function generateAdditional(
uid: string,
type: 'i' | 'h' | 'o',
nodeUid: () => string
): GraphNodeWithIds<AdditionalNode> {
return { return {
inputs: type !== 'i' ? [uid] : [], inputs: type !== 'i' ? [uid] : [],
outputs: type !== 'o' ? [uid] : [], outputs: type !== 'o' ? [uid] : [],
name: uid, name: uid,
___type: type, ___type: type,
___uid: `${uid.replace(/[^a-z]/gi, '').toLowerCase().substring(0, 3)}_${nodeUid()}_${type}`, ___uid: `${uid
.replace(/[^a-z]/gi, '')
.toLowerCase()
.substring(0, 3)}_${nodeUid()}_${type}`,
___uidInputs: [], ___uidInputs: [],
___uidOutputs: [] ___uidOutputs: []
} }
} }
function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNode<T>[], nodeUid: () => string): [string[][], Dict<GraphNodeWithIds<T>>] { function splitIntoRows<T extends Dict<unknown>>(
inputs: string[],
nodes: GraphNode<T>[],
nodeUid: () => string
): [string[][], Dict<GraphNodeWithIds<T>>] {
const nodesWithId: Dict<GraphNodeWithIds<T>> = {} const nodesWithId: Dict<GraphNodeWithIds<T>> = {}
const available = new Set(inputs) const available = new Set(inputs)
let queue = [...nodes] let queue = [...nodes]
@@ -35,7 +52,7 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
const availableOfRow: string[] = [] const availableOfRow: string[] = []
rows.push([]) rows.push([])
queue = queue.filter((node) => { queue = queue.filter(node => {
const isPlaceable = node.inputs.every(input => available.has(input)) const isPlaceable = node.inputs.every(input => available.has(input))
if (isPlaceable) { if (isPlaceable) {
const nodeWithId: GraphNodeWithIds<T> = generateIds(node, nodeUid) const nodeWithId: GraphNodeWithIds<T> = generateIds(node, nodeUid)
@@ -48,7 +65,7 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
availableOfRow.map(uid => available.add(uid)) availableOfRow.map(uid => available.add(uid))
if (amount === queue.length) { if (amount === queue.length) {
console.warn("Loop detected! Left over:", queue) console.warn('Loop detected! Left over:', queue)
rows.pop() rows.pop()
break break
} }
@@ -56,78 +73,123 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
return [rows, nodesWithId] return [rows, nodesWithId]
} }
function addAdditionalNodes<T extends Dict<unknown>>(rowsRaw: string[][], nodesRaw: Dict<GraphNodeWithIds<T>>, inputs: string[], outputs: string[], nodeUid: () => string): [string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>] { function addAdditionalNodes<T extends Dict<unknown>>(
rowsRaw: string[][],
nodesRaw: Dict<GraphNodeWithIds<T>>,
inputs: string[],
outputs: string[],
nodeUid: () => string
): [string[][], Dict<GraphNodeWithIds<T | AdditionalNode>>] {
const addedInputs: Dict<number> = {} const addedInputs: Dict<number> = {}
const res: string[][] = deepcopy([[], ...rowsRaw, []]) const res: string[][] = deepcopy([[], ...rowsRaw, []])
const resNodes: Dict<GraphNodeWithIds<T|AdditionalNode>> = deepcopy(nodesRaw) const resNodes: Dict<GraphNodeWithIds<T | AdditionalNode>> = deepcopy(nodesRaw)
for (let i = 0; i < rowsRaw.length; i++) { for (let i = 0; i < rowsRaw.length; i++) {
const rowInputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].inputs)) const rowInputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].inputs))
for (let rowInput of rowInputs) { for (const rowInput of rowInputs) {
if (rowInput in addedInputs) { if (rowInput in addedInputs) {
for (let j = addedInputs[rowInput]+1; j < i+1; j++) { for (let j = addedInputs[rowInput] + 1; j < i + 1; j++) {
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowInput, 'h', nodeUid) const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(
rowInput,
'h',
nodeUid
)
res[j].push(nodeWithId.___uid) res[j].push(nodeWithId.___uid)
resNodes[nodeWithId.___uid] = nodeWithId resNodes[nodeWithId.___uid] = nodeWithId
} }
addedInputs[rowInput] = i addedInputs[rowInput] = i
} else if (inputs.includes(rowInput)) { } else if (inputs.includes(rowInput)) {
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowInput, 'i', nodeUid) const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(
rowInput,
'i',
nodeUid
)
res[i].push(nodeWithId.___uid) res[i].push(nodeWithId.___uid)
resNodes[nodeWithId.___uid] = nodeWithId resNodes[nodeWithId.___uid] = nodeWithId
addedInputs[rowInput] = i addedInputs[rowInput] = i
} }
} }
const rowOutputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].outputs)) const rowOutputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].outputs))
for (let rowOutput of rowOutputs) { for (const rowOutput of rowOutputs) {
if (outputs?.includes(rowOutput)) { if (outputs?.includes(rowOutput)) {
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowOutput, 'o', nodeUid) const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(
res[i+2].push(nodeWithId.___uid) rowOutput,
'o',
nodeUid
)
res[i + 2].push(nodeWithId.___uid)
resNodes[nodeWithId.___uid] = nodeWithId resNodes[nodeWithId.___uid] = nodeWithId
} }
addedInputs[rowOutput] = i+1 addedInputs[rowOutput] = i + 1
} }
} }
if (res[res.length-1].length === 0) res.splice(res.length-1, 1) if (res[res.length - 1].length === 0) res.splice(res.length - 1, 1)
return [res, resNodes] return [res, resNodes]
} }
function linkNodes<T extends Dict<unknown>>(rowsWithInOut: string[][], nodesWithInOut: Dict<GraphNodeWithIds<T|AdditionalNode>>): Dict<GraphNodeWithIds<T|AdditionalNode>> { function linkNodes<T extends Dict<unknown>>(
type Store = {input: Dict<string[]>[], output: Dict<string[]>[]} rowsWithInOut: string[][],
nodesWithInOut: Dict<GraphNodeWithIds<T | AdditionalNode>>
): Dict<GraphNodeWithIds<T | AdditionalNode>> {
type Store = { input: Dict<string[]>[], output: Dict<string[]>[] }
const store: Store = { const store: Store = {
input: Array.from(rowsWithInOut, Object), input: Array.from(rowsWithInOut, Object),
output: Array.from(rowsWithInOut, Object) output: Array.from(rowsWithInOut, Object)
} }
const nodesPremapping = (node: GraphNodeWithIds<T|AdditionalNode>, rowIdx: number) => { const nodesPremapping = (node: GraphNodeWithIds<T | AdditionalNode>, rowIdx: number) => {
node.inputs.forEach(input => store.input[rowIdx][input] = [...(store.input[rowIdx][input] ?? []), node.___uid]) node.inputs.forEach(
node.outputs.forEach(output => store.output[rowIdx][output] = [...(store.output[rowIdx][output] ?? []), node.___uid]) input => (store.input[rowIdx][input] = [...(store.input[rowIdx][input] ?? []), node.___uid])
}; )
const linkInOut = (node: GraphNodeWithIds<T|AdditionalNode>, rowIdx: number) => { node.outputs.forEach(
output =>
(store.output[rowIdx][output] = [...(store.output[rowIdx][output] ?? []), node.___uid])
)
}
const linkInOut = (node: GraphNodeWithIds<T | AdditionalNode>, rowIdx: number) => {
if (rowIdx > 0) if (rowIdx > 0)
node.___uidInputs = uniquify(node.inputs.flatMap(input => store.output[rowIdx - 1][input]).filter(isNonNullable)) node.___uidInputs = uniquify(
if (rowIdx < rowsWithInOut.length-1) node.inputs.flatMap(input => store.output[rowIdx - 1][input]).filter(isNonNullable)
node.___uidOutputs = uniquify(node.outputs.flatMap(output => store.input[rowIdx + 1][output]).filter(isNonNullable)) )
}; if (rowIdx < rowsWithInOut.length - 1)
node.___uidOutputs = uniquify(
node.outputs.flatMap(output => store.input[rowIdx + 1][output]).filter(isNonNullable)
)
}
rowsWithInOut.forEach((row, rowIdx) => row.forEach(uid => nodesPremapping(nodesWithInOut[uid], rowIdx))) rowsWithInOut.forEach((row, rowIdx) =>
row.forEach(uid => nodesPremapping(nodesWithInOut[uid], rowIdx))
)
rowsWithInOut.forEach((row, rowIdx) => row.forEach(uid => linkInOut(nodesWithInOut[uid], rowIdx))) rowsWithInOut.forEach((row, rowIdx) => row.forEach(uid => linkInOut(nodesWithInOut[uid], rowIdx)))
return nodesWithInOut return nodesWithInOut
} }
function crossingsOf<T extends Dict<unknown>>(fixed: string[], flex: string[], nodes: Dict<GraphNodeWithIds<T|AdditionalNode>>, isDown: boolean): [number[][], number] { function crossingsOf<T extends Dict<unknown>>(
fixed: string[],
flex: string[],
nodes: Dict<GraphNodeWithIds<T | AdditionalNode>>,
isDown: boolean
): [number[][], number] {
const result = Array.from(flex, () => Array.from(flex, () => 9999999)) const result = Array.from(flex, () => Array.from(flex, () => 9999999))
let score = 0 let score = 0
for (let i = 0; i < flex.length-1; i++) { for (let i = 0; i < flex.length - 1; i++) {
for (let j = i+1; j < flex.length; j++) { for (let j = i + 1; j < flex.length; j++) {
const inputsI = new Set(nodes[flex[i]][isDown ? '___uidInputs' : '___uidOutputs']) const inputsI = new Set(nodes[flex[i]][isDown ? '___uidInputs' : '___uidOutputs'])
const inputsJ = new Set(nodes[flex[j]][isDown ? '___uidInputs' : '___uidOutputs']) const inputsJ = new Set(nodes[flex[j]][isDown ? '___uidInputs' : '___uidOutputs'])
const diff = fixed.reduce(([size, acc], curr) => { const diff =
inputsI.has(curr) && size-- fixed.reduce(
return [size, acc + (inputsJ.has(curr) ? size : 0)] ([size, acc], curr) => {
}, [inputsI.size, 0])[1] - fixed.reduce(([size, acc], curr) => { inputsI.has(curr) && size--
inputsJ.has(curr) && size-- return [size, acc + (inputsJ.has(curr) ? size : 0)]
return [size, acc + (inputsI.has(curr) ? size : 0)] },
}, [inputsJ.size, 0])[1] [inputsI.size, 0]
)[1] -
fixed.reduce(
([size, acc], curr) => {
inputsJ.has(curr) && size--
return [size, acc + (inputsI.has(curr) ? size : 0)]
},
[inputsJ.size, 0]
)[1]
result[i][j] = diff result[i][j] = diff
result[j][i] = -diff result[j][i] = -diff
score += diff score += diff
@@ -136,82 +198,102 @@ function crossingsOf<T extends Dict<unknown>>(fixed: string[], flex: string[], n
return [result, score] return [result, score]
} }
function optimizeOrder<T extends Dict<unknown>>(rowsWithInOut: string[][], nodesWithInOut: Dict<GraphNodeWithIds<T|AdditionalNode>>): [string[][], number] { function optimizeOrder<T extends Dict<unknown>>(
rowsWithInOut: string[][],
function addCosts(costsUp: [number[][], number], costsDown: [number[][], number]): [number[][], number] { nodesWithInOut: Dict<GraphNodeWithIds<T | AdditionalNode>>
): [string[][], number] {
function addCosts(
costsUp: [number[][], number],
costsDown: [number[][], number]
): [number[][], number] {
return [ return [
costsUp[0].map((row, rowIdx) => row.map((col, colIdx) => col+costsDown[0][rowIdx][colIdx])), costsUp[0].map((row, rowIdx) => row.map((col, colIdx) => col + costsDown[0][rowIdx][colIdx])),
costsUp[1] + costsDown[1] costsUp[1] + costsDown[1]
] ]
} }
function improveRow(top: string[]|undefined, mid: string[], bot: string[]|undefined) { function improveRow(top: string[] | undefined, mid: string[], bot: string[] | undefined) {
const costsUp = top ? crossingsOf(top, mid, nodesWithInOut, true) : undefined const costsUp = top ? crossingsOf(top, mid, nodesWithInOut, true) : undefined
const costsDown = bot ? crossingsOf(bot, mid, nodesWithInOut, false) : undefined const costsDown = bot ? crossingsOf(bot, mid, nodesWithInOut, false) : undefined
const [costs, scoreConst] = costsUp && costsDown ? addCosts(costsUp, costsDown) : costsDown ?? costsUp ?? [undefined, 0] const [costs, scoreConst] =
costsUp && costsDown ? addCosts(costsUp, costsDown) : costsDown ?? costsUp ?? [undefined, 0]
let score = scoreConst let score = scoreConst
if (!costs) return score if (!costs) return score
let improvementInRow = true let improvementInRow = true
while (improvementInRow) { while (improvementInRow) {
improvementInRow = false improvementInRow = false
const colBest = costs const colBest = costs
.map((_, idx) => costs .map(
.slice(0, idx) (_, idx) =>
.map(r => r[idx]) costs
.reverse() .slice(0, idx)
.reduce(([sum, best], curr, i) => { .map(r => r[idx])
return sum + curr > best.sum .reverse()
? [sum + curr, {sum: sum+curr, move: -i-1, idx}] as const .reduce(
: [sum + curr, best] as const ([sum, best], curr, i) => {
}, [0, {sum: -10000, move: 0, idx: 0}] as readonly [number, Reduce])[1] return sum + curr > best.sum
? ([sum + curr, { sum: sum + curr, move: -i - 1, idx }] as const)
: ([sum + curr, best] as const)
},
[0, { sum: -10000, move: 0, idx: 0 }] as readonly [number, Reduce]
)[1]
) )
.filter(isNonNullable) .filter(isNonNullable)
const rowBest = costs const rowBest = costs
.map((_, idx) => costs[idx] .map(
.slice(idx+1) (_, idx) =>
.reduce(([sum, best], curr, i) => { costs[idx].slice(idx + 1).reduce(
return sum + curr > best.sum ([sum, best], curr, i) => {
? [sum + curr, {sum: sum+curr, move: i+1, idx}] as const return sum + curr > best.sum
: [sum + curr, best] as const ? ([sum + curr, { sum: sum + curr, move: i + 1, idx }] as const)
}, [0, {sum: -10000, move: 0, idx: 0}] as readonly [number, Reduce])[1] : ([sum + curr, best] as const)
},
[0, { sum: -10000, move: 0, idx: 0 }] as readonly [number, Reduce]
)[1]
) )
.filter(isNonNullable) .filter(isNonNullable)
const replacement = [...colBest, ...rowBest].sort(sortByProperty(red => -red.sum))[0] const replacement = [...colBest, ...rowBest].sort(sortByProperty(red => -red.sum))[0]
if (replacement.sum > 0) { if (replacement.sum > 0) {
score -= 2*replacement.sum score -= 2 * replacement.sum
improvement = true improvement = true
improvementInRow = true improvementInRow = true
costs.splice(replacement.move+replacement.idx, 0, ...costs.splice(replacement.idx, 1)) costs.splice(replacement.move + replacement.idx, 0, ...costs.splice(replacement.idx, 1))
costs.map(col => col.splice(replacement.move+replacement.idx, 0, ...col.splice(replacement.idx, 1))) costs.map(col =>
mid.splice(replacement.move+replacement.idx, 0, ...mid.splice(replacement.idx, 1)) col.splice(replacement.move + replacement.idx, 0, ...col.splice(replacement.idx, 1))
)
mid.splice(replacement.move + replacement.idx, 0, ...mid.splice(replacement.idx, 1))
} }
} }
return score return score
} }
type Reduce = {sum: number, move: number, idx: number} type Reduce = { sum: number, move: number, idx: number }
let improvement = true let improvement = true
let scores: number[] = [] const scores: number[] = []
while (improvement) { while (improvement) {
improvement = false improvement = false
rowsWithInOut.reduce((top, mid, idx) => { rowsWithInOut.reduce((top, mid, idx) => {
scores[idx] = improveRow(top, mid, rowsWithInOut[idx+1]) scores[idx] = improveRow(top, mid, rowsWithInOut[idx + 1])
return mid return mid
}, undefined as string[]|undefined) }, undefined as string[] | undefined)
rowsWithInOut.reduceRight((bot, mid, idx) => { rowsWithInOut.reduceRight((bot, mid, idx) => {
scores[idx] = improveRow(rowsWithInOut[idx-1], mid, bot) scores[idx] = improveRow(rowsWithInOut[idx - 1], mid, bot)
return mid return mid
}, undefined as string[]|undefined) }, undefined as string[] | undefined)
} }
return [rowsWithInOut, scores.reduce((a, b) => a+b)] return [rowsWithInOut, scores.reduce((a, b) => a + b)]
} }
export function findBest<T extends Dict<unknown>>(rowsWithInOut: string[][], nodesWithInOut: Dict<GraphNodeWithIds<T|AdditionalNode>>, timeLimit: number) { export function findBest<T extends Dict<unknown>>(
rowsWithInOut: string[][],
nodesWithInOut: Dict<GraphNodeWithIds<T | AdditionalNode>>,
timeLimit: number
) {
let bestScore = Infinity let bestScore = Infinity
let bestRows = deepcopy(rowsWithInOut) let bestRows = deepcopy(rowsWithInOut)
let limit = Date.now() + timeLimit const limit = Date.now() + timeLimit
let iterSinceImprovements = 0 let iterSinceImprovements = 0
let rng = seedrandom.alea("We are SEEED, ya!") const rng = seedrandom.alea('We are SEEED, ya!')
while (true) { while (true) {
if (Date.now() > limit) break if (Date.now() > limit) break
if (iterSinceImprovements > 100) break if (iterSinceImprovements > 100) break
@@ -223,21 +305,31 @@ export function findBest<T extends Dict<unknown>>(rowsWithInOut: string[][], nod
} else { } else {
iterSinceImprovements++ iterSinceImprovements++
} }
rowsOptimized.forEach((row, ) => shuffleInplace(row, rng)) rowsOptimized.forEach(row => shuffleInplace(row, rng))
} }
console.log(bestScore)
return bestRows return bestRows
} }
export function graphUntangled<T extends Dict<unknown>>(nodes: GraphNode<T>[], inputs: string[], outputs: string[], timeLimit = 0): [string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>] { export function graphUntangled<T extends Dict<unknown>>(
const nodeSeed = seedrandom.alea("node") nodes: GraphNode<T>[],
inputs: string[],
outputs: string[],
timeLimit = 0
): [string[][], Dict<GraphNodeWithIds<T | AdditionalNode>>] {
const nodeSeed = seedrandom.alea('node')
const nodeUid = () => Math.abs(nodeSeed.int32()).toString(16).substring(0, 3) const nodeUid = () => Math.abs(nodeSeed.int32()).toString(16).substring(0, 3)
//console.log('---------------') //console.log('---------------')
const [rowsRaw, nodesRaw] = splitIntoRows(inputs, nodes, nodeUid) const [rowsRaw, nodesRaw] = splitIntoRows(inputs, nodes, nodeUid)
//console.log("Step 1") //console.log("Step 1")
//console.table(rowsRaw) //console.table(rowsRaw)
//console.table(nodesRaw) //console.table(nodesRaw)
const [rowsWithInOut, nodesWithInOut] = addAdditionalNodes(rowsRaw, nodesRaw, inputs, outputs, nodeUid) const [rowsWithInOut, nodesWithInOut] = addAdditionalNodes(
rowsRaw,
nodesRaw,
inputs,
outputs,
nodeUid
)
//console.log("Step 2") //console.log("Step 2")
//console.table(rowsWithInOut) //console.table(rowsWithInOut)
//console.table(nodesWithInOut) //console.table(nodesWithInOut)

View File

@@ -1,4 +1,4 @@
import {Dict} from "../types"; import { Dict } from '../types'
interface GraphNodeBase { interface GraphNodeBase {
inputs: string[] inputs: string[]
@@ -14,7 +14,8 @@ export type GraphNodeWithIds<T extends Dict<unknown>> = GraphNode<T> & {
} }
export type AdditionalNode = { export type AdditionalNode = {
___type: 'i'|'h'|'o' ___type: 'i' | 'h' | 'o'
} }
export const isAdditionalNode = (node: unknown): node is GraphNodeWithIds<AdditionalNode> => !!(node && typeof node === 'object' && '___type' in node) export const isAdditionalNode = (node: unknown): node is GraphNodeWithIds<AdditionalNode> =>
!!(node && typeof node === 'object' && '___type' in node)

View File

@@ -8,18 +8,18 @@ export function useEventListener<K extends keyof WindowEventMap>(
eventName: K, eventName: K,
handler: (event: WindowEventMap[K]) => void, handler: (event: WindowEventMap[K]) => void,
element?: undefined, element?: undefined,
options?: boolean | AddEventListenerOptions, options?: boolean | AddEventListenerOptions
): void ): void
// Element Event based useEventListener interface // Element Event based useEventListener interface
export function useEventListener< export function useEventListener<
K extends keyof HTMLElementEventMap, K extends keyof HTMLElementEventMap,
T extends HTMLElement = HTMLDivElement, T extends HTMLElement = HTMLDivElement
>( >(
eventName: K, eventName: K,
handler: (event: HTMLElementEventMap[K]) => void, handler: (event: HTMLElementEventMap[K]) => void,
element: RefObject<T>, element: RefObject<T>,
options?: boolean | AddEventListenerOptions, options?: boolean | AddEventListenerOptions
): void ): void
// Document Event based useEventListener interface // Document Event based useEventListener interface
@@ -27,20 +27,18 @@ export function useEventListener<K extends keyof DocumentEventMap>(
eventName: K, eventName: K,
handler: (event: DocumentEventMap[K]) => void, handler: (event: DocumentEventMap[K]) => void,
element: RefObject<Document>, element: RefObject<Document>,
options?: boolean | AddEventListenerOptions, options?: boolean | AddEventListenerOptions
): void ): void
export function useEventListener< export function useEventListener<
KW extends keyof WindowEventMap, KW extends keyof WindowEventMap,
KH extends keyof HTMLElementEventMap, KH extends keyof HTMLElementEventMap,
T extends HTMLElement | void = void, T extends HTMLElement | void = void
>( >(
eventName: KW | KH, eventName: KW | KH,
handler: ( handler: (event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event) => void,
event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event,
) => void,
element?: RefObject<T>, element?: RefObject<T>,
options?: boolean | AddEventListenerOptions, options?: boolean | AddEventListenerOptions
) { ) {
// Create a ref that stores handler // Create a ref that stores handler
const savedHandler = useRef(handler) const savedHandler = useRef(handler)

View File

@@ -1,23 +1,23 @@
import {EnrichedEntity, Entity} from "../types"; import { EnrichedEntity, Entity } from '../types'
import details from "../../res/details.json"; import details from '../../res/details.json'
import manual from "../../res/manual.json"; import manual from '../../res/manual.json'
const joined = [...details, ...manual] as Entity[] const joined = [...details, ...manual] as Entity[]
const factories = joined.map((detail: EnrichedEntity) => { const factories = joined.map((detail: EnrichedEntity) => {
detail.usedBy = joined detail.usedBy = joined.filter(f =>
.filter(f => Object Object.keys(f.recipe?.prerequisites ?? {}).includes(detail.href)
.keys(f.recipe?.prerequisites ?? {}) )
.includes(detail.href) return detail
)
return detail;
}) })
const detailsMap = Object.fromEntries(factories.map((detail: EnrichedEntity) => [detail.href, detail])) const detailsMap = Object.fromEntries(
factories.map((detail: EnrichedEntity) => [detail.href, detail])
)
export const useFactories = () => ({ export const useFactories = () => ({
factories, factories,
findFactory: (uid: string): EnrichedEntity|undefined => { findFactory: (uid: string): EnrichedEntity | undefined => {
return detailsMap[uid] return detailsMap[uid]
} }
}) })

View File

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

View File

@@ -1,10 +1,4 @@
import { import { Dispatch, SetStateAction, useCallback, useEffect, useState } from 'react'
Dispatch,
SetStateAction,
useCallback,
useEffect,
useState,
} from 'react'
// See: https://usehooks-ts.com/react-hook/use-event-listener // See: https://usehooks-ts.com/react-hook/use-event-listener
import { useEventListener } from './useEventListener' import { useEventListener } from './useEventListener'
@@ -41,30 +35,33 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
// Return a wrapped version of useState's setter function that ... // Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage. // ... persists the new value to localStorage.
const setValue: SetValue<T> = useCallback(value => { const setValue: SetValue<T> = useCallback(
// Prevent build error "window is undefined" but keeps working value => {
if (typeof window == 'undefined') { // Prevent build error "window is undefined" but keeps working
console.warn( if (typeof window == 'undefined') {
`Tried setting localStorage key “${key}” even though environment is not a client`, console.warn(
) `Tried setting localStorage key “${key}” even though environment is not a client`
} )
}
try { try {
// Allow value to be a function so we have the same API as useState // Allow value to be a function so we have the same API as useState
const newValue = value instanceof Function ? value(storedValue) : value const newValue = value instanceof Function ? value(storedValue) : value
// Save to local storage // Save to local storage
window.localStorage.setItem(key, JSON.stringify(newValue)) window.localStorage.setItem(key, JSON.stringify(newValue))
// Save state // Save state
setStoredValue(newValue) setStoredValue(newValue)
// We dispatch a custom event so every useLocalStorage hook are notified // We dispatch a custom event so every useLocalStorage hook are notified
window.dispatchEvent(new Event('local-storage')) window.dispatchEvent(new Event('local-storage'))
} catch (error) { } catch (error) {
console.warn(`Error setting localStorage key “${key}”:`, error) console.warn(`Error setting localStorage key “${key}”:`, error)
} }
}, [key, storedValue]) },
[key, storedValue]
)
useEffect(() => { useEffect(() => {
setStoredValue(readValue()) setStoredValue(readValue())
@@ -78,7 +75,7 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
} }
setStoredValue(readValue()) setStoredValue(readValue())
}, },
[key, readValue], [key, readValue]
) )
// this only works for other documents, not the current one // this only works for other documents, not the current one

6
src/next-types.d.ts vendored
View File

@@ -1,7 +1,3 @@
declare module 'next/config' { declare module 'next/config' {
export interface ServerRuntimeConfig { export interface ServerRuntimeConfig {
MONGO_URL: string MONGO_URL: string
@@ -15,7 +11,7 @@ declare module 'next/config' {
} }
const getConfig: () => { const getConfig: () => {
serverRuntimeConfig: ServerRuntimeConfig, serverRuntimeConfig: ServerRuntimeConfig
publicRuntimeConfig: PublicRuntimeConfig publicRuntimeConfig: PublicRuntimeConfig
} }
export default getConfig export default getConfig

View File

@@ -1,14 +1,14 @@
export function createPath(container: DOMRect, start: DOMRect, end: DOMRect) { export function createPath(container: DOMRect, start: DOMRect, end: DOMRect) {
const startX = Math.round(start.x + start.width/2 - container.x) const startX = Math.round(start.x + start.width / 2 - container.x)
const startY = Math.round(start.bottom - container.y) const startY = Math.round(start.bottom - container.y)
const endX = Math.round(end.x + end.width/2 - container.x) const endX = Math.round(end.x + end.width / 2 - container.x)
const endY = Math.round(end.top - container.y) const endY = Math.round(end.top - container.y)
const mid = Math.round((start.bottom + end.top) / 2 - container.y) const mid = Math.round((start.bottom + end.top) / 2 - container.y)
return `M${startX},${startY} C${startX},${mid} ${endX},${mid} ${endX},${endY}` return `M${startX},${startY} C${startX},${mid} ${endX},${mid} ${endX},${endY}`
} }
export function drawLine(container: DOMRect, elem: DOMRect) { export function drawLine(container: DOMRect, elem: DOMRect) {
const x = Math.round(elem.x + elem.width/2 - container.x) const x = Math.round(elem.x + elem.width / 2 - container.x)
const top = Math.round(elem.top - container.y) const top = Math.round(elem.top - container.y)
const bottom = Math.round(elem.bottom - container.y) const bottom = Math.round(elem.bottom - container.y)
return `M${x},${top} L${x},${bottom}` return `M${x},${top} L${x},${bottom}`

View File

@@ -1,4 +1,4 @@
import {ValidationError} from "jsonschema"; import { ValidationError } from 'jsonschema'
export interface ErrorMessage { export interface ErrorMessage {
message: string // Human readable error message message: string // Human readable error message

View File

@@ -1,5 +1,5 @@
import {Dict} from "./types"; import { Dict } from './types'
import {PRNG} from "seedrandom"; import { PRNG } from 'seedrandom'
export function isNonNullable<T>(any: T): any is NonNullable<T> { export function isNonNullable<T>(any: T): any is NonNullable<T> {
return any !== undefined && any !== null return any !== undefined && any !== null
@@ -29,12 +29,12 @@ export function uniquify<T>(array: T[]): T[] {
export function shuffleInplace<T>(array: T[], rng: PRNG): T[] { export function shuffleInplace<T>(array: T[], rng: PRNG): T[] {
for (let i = array.length - 1; i > 0; i--) { for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(rng.quick() * (i + 1)); const j = Math.floor(rng.quick() * (i + 1))
[array[i], array[j]] = [array[j], array[i]]; ;[array[i], array[j]] = [array[j], array[i]]
} }
return array return array
} }
export function fixedEncodeURIComponent(str: string): string { export function fixedEncodeURIComponent(str: string): string {
return encodeURIComponent(str).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16)); return encodeURIComponent(str).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16))
} }

View File

@@ -32,6 +32,7 @@ class FetchOnce<T> {
this.pendingList.push([resolve, reject]) this.pendingList.push([resolve, reject])
break break
case ResolvableState.DONE: case ResolvableState.DONE:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
resolve(this.data!) resolve(this.data!)
break break
case ResolvableState.ERROR: case ResolvableState.ERROR:

View File

@@ -1,7 +1,6 @@
import { ErrorMessage } from '../types/FrontendApi' import { ErrorMessage } from '../types/FrontendApi'
import {NextApiHandler, NextApiRequest, NextApiResponse} from 'next' import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'
import { logger } from './logger' import { logger } from './logger'
import {NextFetchEvent, NextMiddleware, NextRequest} from "next/server";
export class NetworkError extends Error { export class NetworkError extends Error {
public content?: ErrorMessage public content?: ErrorMessage

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-console */
export const logger = { export const logger = {
verbose: console.log, verbose: console.log,
debug: console.log, debug: console.log,

View File

@@ -6,9 +6,11 @@ import { compile, JSONSchema } from 'json-schema-to-typescript'
import * as fs from 'fs/promises' import * as fs from 'fs/promises'
import { join } from 'path' import { join } from 'path'
import { NetworkError } from '../utils/errors' import { NetworkError } from '../utils/errors'
import getConfig from "next/config"; import getConfig from 'next/config'
const {publicRuntimeConfig: {TENANT_TYPE}} = getConfig() const {
publicRuntimeConfig: { TENANT_TYPE }
} = getConfig()
const validatorStorage = new Validator() const validatorStorage = new Validator()

View File

@@ -16,9 +16,9 @@ export function addSchemas() {
type: 'object', type: 'object',
required: ['type', 'factories'], required: ['type', 'factories'],
properties: { properties: {
type: {type: 'string', enum: ['exports', 'malls']}, type: { type: 'string', enum: ['exports', 'malls'] },
factories: {type: 'array', items: {type: 'string', minLength: 3}} factories: { type: 'array', items: { type: 'string', minLength: 3 } }
}, }
}, },
{ {
id: 'GroupIdParam', id: 'GroupIdParam',
@@ -34,16 +34,16 @@ export function addSchemas() {
type: 'object', type: 'object',
required: ['type', 'factories'], required: ['type', 'factories'],
properties: { properties: {
type: {type: 'string', enum: ['ignored', 'base']}, type: { type: 'string', enum: ['ignored', 'base'] },
factories: {type: 'array', items: {type: 'string', minLength: 3}} factories: { type: 'array', items: { type: 'string', minLength: 3 } }
}, }
}, },
{ {
id: 'IdParam', id: 'IdParam',
type: 'object', type: 'object',
required: ['id'], required: ['id'],
properties: { properties: {
id: { type: 'string', minLength: 24, maxLength: 24 }, id: { type: 'string', minLength: 24, maxLength: 24 }
} }
} }
]) ])

View File

@@ -1,57 +1,68 @@
html, html,
body { body {
padding: 0; padding: 0;
margin: 0; margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen, font-family:
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif; -apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
Oxygen,
Ubuntu,
Cantarell,
"Fira Sans",
"Droid Sans",
"Helvetica Neue",
sans-serif;
} }
body { body {
color: black; padding: 2em;
background: #FAFAFA; background: #fafafa;
padding: 2em; color: black;
} }
body.scroll { body.scroll {
width: 100vw; width: 100vw;
height: 100vh; height: 100vh;
padding: 0; padding: 0;
} }
a { a {
color: inherit; color: inherit;
text-decoration: none; text-decoration: none;
} }
* { * {
box-sizing: border-box; box-sizing: border-box;
} }
:is(h1, h2, h3, h4, h5, h6):is(:first-child) { :is(h1, h2, h3, h4, h5, h6):is(:first-child) {
margin-block-start: 0; margin-block-start: 0;
} }
h3 { h3 {
margin-block: 1.5em 1em; margin-block: 1.5em 1em;
} }
h4 { h4 {
margin-block: 1em 0.3em; font-weight: 500;
font-weight: 500; margin-block: 1em 0.3em;
} }
@media (prefers-color-scheme: dark) { @media (prefers-color-scheme: dark) {
html { html {
color-scheme: dark; color-scheme: dark;
} }
body {
color: white; body {
background: #111; background: #111;
} color: white;
}
} }
@media (max-width: 1200px) { @media (max-width: 1200px) {
body { body {
padding-inline: 0.5em; padding-inline: 0.5em;
} }
} }

12
tsconfig.test.json Normal file
View File

@@ -0,0 +1,12 @@
{
"extends": "./tsconfig.json",
"include": [
"**/*.spec.ts",
"**/*.test.ts",
"jest.config.js",
"next.config.js",
"src/backend-custom-server/index",
"scripts/*"
],
"exclude": ["dist", ".next", "out", "node_modules", "cypress"]
}

1053
yarn.lock

File diff suppressed because it is too large Load Diff