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

View File

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

View File

@@ -1,8 +1,8 @@
import {FC, HTMLProps, useMemo} from "react"
import {Entity} from "../../../src/types"
import {useFactories} from "../../../src/hooks/useFactories"
import { FC, HTMLProps, useMemo } from 'react'
import { Entity } from '../../../src/types'
import { useFactories } from '../../../src/hooks/useFactories'
import styles from './EntityIcon.module.css'
import cx from "classnames";
import cx from 'classnames'
interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> {
value: Entity | string
@@ -12,7 +12,7 @@ interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> {
export const EntityIcon: FC<Props> = ({ className, value, amount, ...rest }) => {
const { findFactory } = useFactories()
const entity = useMemo<Entity>(() => {
return typeof value === "object"
return typeof value === 'object'
? value
: value === '/Time'
? {
@@ -29,9 +29,15 @@ export const EntityIcon: FC<Props> = ({className, value, amount, ...rest}) => {
}
}, [findFactory, value])
return <span {...rest} className={cx(className, styles.span)} title={entity.name}>
return (
<span {...rest} className={cx(className, styles.span)} title={entity.name}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img className={cx(styles.img, amount === undefined ? styles.noAmount : undefined)} src={`https://wiki.factorio.com${entity.image}`} alt={entity.name}/>
<img
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,11 +1,11 @@
import {FC, HTMLProps, memo, useMemo} from "react"
import {EnrichedEntity, Entity} from "../../../src/types"
import {useFactories} from "../../../src/hooks/useFactories"
import { FC, HTMLProps, memo, useMemo } from 'react'
import { EnrichedEntity } from '../../../src/types'
import { useFactories } from '../../../src/hooks/useFactories'
import styles from './EntitySpan.module.css'
import {RecipeSpan} from "../Recipe/Recipe";
import {LeftClickIcon} from "../LeftClickIcon/LeftClickIcon";
import cx from 'classnames';
import {EntityIcon} from "../EntityIcon/EntityIcon";
import { RecipeSpan } from '../Recipe/Recipe'
import { LeftClickIcon } from '../LeftClickIcon/LeftClickIcon'
import cx from 'classnames'
import { EntityIcon } from '../EntityIcon/EntityIcon'
interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> {
value: EnrichedEntity | string
@@ -16,10 +16,18 @@ interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> {
className?: string
}
const EntitySpanUnmemo: FC<Props> = ({className, value, state, leftClickText, rightClickText, simpleStyle, ...rest}) => {
const EntitySpanUnmemo: FC<Props> = ({
className,
value,
state,
leftClickText,
rightClickText,
simpleStyle,
...rest
}) => {
const { findFactory } = useFactories()
const entity = useMemo<EnrichedEntity>(() => {
return typeof value === "object"
return typeof value === 'object'
? value
: findFactory(value) ?? {
usedBy: [],
@@ -30,9 +38,14 @@ const EntitySpanUnmemo: FC<Props> = ({className, value, state, leftClickText, ri
}
}, [findFactory, value])
return <span className={cx(className, simpleStyle ? styles.spanSimple : styles.span)} {...rest}>
return (
<span className={cx(className, simpleStyle ? styles.spanSimple : styles.span)} {...rest}>
{/* eslint-disable-next-line @next/next/no-img-element */}
<img className={styles.img} src={`https://wiki.factorio.com${entity.image}`} alt={entity.name}/>
<img
className={styles.img}
src={`https://wiki.factorio.com${entity.image}`}
alt={entity.name}
/>
<span className={styles[state ?? 'unknown']}>{entity.name}</span>
<div className={styles.tooltip}>
{entity.recipe && (
@@ -45,19 +58,32 @@ const EntitySpanUnmemo: FC<Props> = ({className, value, state, leftClickText, ri
<>
<div className={styles.strong}>Used By</div>
<div className={styles.usedBy}>
{entity.usedBy.map(used => <EntityIcon value={used} key={used.name}/>)}
{entity.usedBy.map(used => (
<EntityIcon value={used} key={used.name} />
))}
</div>
</>
) : null}
{(leftClickText || rightClickText) && (
<>
<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>}
{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)

View File

@@ -4,8 +4,7 @@
}
.select :global(.factory-select__multi-value),
.select :global(.factory-select__menu)
{
.select :global(.factory-select__menu) {
background-color: #444;
}
@@ -18,6 +17,6 @@
}
.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 Select from "react-select";
import {isNonNullable} from "../../../src/utils";
import details from "../../../res/details.json";
import styles from "./FactorySelect.module.css";
import {EntitySpan} from "../EntitySpan/EntitySpan";
import { FC, memo, useMemo } from 'react'
import Select from 'react-select'
import { isNonNullable } from '../../../src/utils'
import details from '../../../res/details.json'
import styles from './FactorySelect.module.css'
import { EntitySpan } from '../EntitySpan/EntitySpan'
interface Props {
id: string
@@ -23,7 +23,8 @@ const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => {
.filter(isNonNullable)
}, [factories])
return <Select
return (
<Select
id={id}
instanceId={id}
value={state}
@@ -32,7 +33,9 @@ const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => {
<EntitySpan {...innerProps} value={data.value} simpleStyle={true} />
),
Option: ({ innerProps, data }) => (
<div {...innerProps} className={styles.option}><EntitySpan value={data.value} simpleStyle={true}/></div>
<div {...innerProps} className={styles.option}>
<EntitySpan value={data.value} simpleStyle={true} />
</div>
)
}}
isMulti
@@ -41,8 +44,9 @@ const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => {
onSetFactories(e.map(s => s?.value))
}}
className={styles.select}
classNamePrefix={"factory-select"}
classNamePrefix={'factory-select'}
/>
)
}
export const FactorySelect = memo(FactorySelectBase)

View File

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

View File

@@ -1,14 +1,14 @@
import {FC, useMemo, useRef, useState} from "react";
import {GroupBox} from "./GroupBox/GroupBox";
import styles from "./Home.module.css"
import {useFactories} from "../../src/hooks/useFactories";
import {EnrichedEntity} from "../../src/types";
import {EntitySpan} from "./EntitySpan/EntitySpan";
import {useGroups} from "../contexts/GroupProvider";
import {Preferences} from "./Preferences/Preferences";
import {download, streamToArrayBuffer} from "../../src/download";
import Link from "next/link";
import {useRouter} from "next/router";
import { FC, useMemo, useRef, useState } from 'react'
import { GroupBox } from './GroupBox/GroupBox'
import styles from './Home.module.css'
import { useFactories } from '../../src/hooks/useFactories'
import { EnrichedEntity } from '../../src/types'
import { EntitySpan } from './EntitySpan/EntitySpan'
import { useGroups } from '../contexts/GroupProvider'
import { Preferences } from './Preferences/Preferences'
import { download, streamToArrayBuffer } from '../../src/download'
import Link from 'next/link'
import { useRouter } from 'next/router'
export const Home: FC = () => {
const router = useRouter()
@@ -23,13 +23,14 @@ export const Home: FC = () => {
store,
load
} = useGroups()
const [newGroupValue, setNewGroupValue] = useState("New group")
const [newGroupValue, setNewGroupValue] = useState('New group')
const inputRef = useRef<HTMLInputElement>(null)
const [missingExport, missingMall] = useMemo<[EnrichedEntity[], EnrichedEntity[]]>(() => {
return factories
.filter(factory => !doNotSuggest.has(factory.href) && factory.recipe)
.reduce((acc, factory) =>
.reduce(
(acc, factory) =>
(factory.usedBy?.length ?? 0) >= 3
? [[...acc[0], factory], acc[1]]
: [acc[0], [...acc[1], factory]],
@@ -40,10 +41,15 @@ export const Home: FC = () => {
return (
<main>
<h1>Factorio Microservices</h1>
<button onClick={() => {
download('factorio-microservices.bin', store());
}}>Store</button>
<button onClick={async () => {
<button
onClick={() => {
download('factorio-microservices.bin', store())
}}
>
Store
</button>
<button
onClick={async () => {
const res = await fetch('/api/submit', {
method: 'POST',
headers: {
@@ -55,15 +61,25 @@ export const Home: FC = () => {
const { uuid } = await res.json()
if (uuid) await router.push({ query: { ...router.query, id: uuid } })
}
}}>Upload</button>
<input type={"file"} multiple={false} ref={inputRef} onChange={async evt => {
const stream = evt.currentTarget.files?.[0].stream() as globalThis.ReadableStream<Uint8Array>|undefined
}}
>
Upload
</button>
<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 />
<fieldset>
@@ -74,15 +90,17 @@ export const Home: FC = () => {
key={missing.href}
value={missing}
onClick={() => {
addGroup(newGroupValue !== "New group" ? newGroupValue : missing.name, [missing.href])
setNewGroupValue("New group")
addGroup(newGroupValue !== 'New group' ? newGroupValue : missing.name, [
missing.href
])
setNewGroupValue('New group')
}}
onContextMenu={event => {
event.preventDefault()
setIgnoredFactories([...ignoredFactories, missing.href])
}}
leftClickText={"Create a new group with this name and item as exported factory"}
rightClickText={"Exclude this recipe from suggestions"}
leftClickText={'Create a new group with this name and item as exported factory'}
rightClickText={'Exclude this recipe from suggestions'}
/>
))}
</div>
@@ -95,26 +113,29 @@ export const Home: FC = () => {
key={missing.href}
value={missing}
onClick={() => {
addGroup(newGroupValue !== "New group" ? newGroupValue : missing.name, [], [missing.href])
setNewGroupValue("New group")
addGroup(
newGroupValue !== 'New group' ? newGroupValue : missing.name,
[],
[missing.href]
)
setNewGroupValue('New group')
}}
onContextMenu={event => {
event.preventDefault()
setIgnoredFactories([...ignoredFactories, missing.href])
}}
leftClickText={"Create a new group with this name and item as mall factory"}
rightClickText={"Exclude this recipe from suggestions"}
leftClickText={'Create a new group with this name and item as mall factory'}
rightClickText={'Exclude this recipe from suggestions'}
/>
))}
</div>
</fieldset>
<div className={styles.grid}>
{
Object
.values(groups)
{Object.values(groups)
.sort((a, b) => a.name.localeCompare(b.name))
.map((group) => <GroupBox key={group.name} group={group} />)
}
.map(group => (
<GroupBox key={group.name} group={group} />
))}
</div>
</main>
)

View File

@@ -1,4 +1,4 @@
import {FC} from "react";
import { FC } from 'react'
interface Props {
className?: string
@@ -8,9 +8,23 @@ interface Props {
export const LeftClickIcon: FC<Props> = ({ className, classBody, classClick }) => {
return (
<svg xmlns="http://www.w3.org/2000/svg" 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
xmlns='http://www.w3.org/2000/svg'
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>
)
}

View File

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

View File

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

View File

@@ -17,8 +17,8 @@
.node {
padding: 0.5em;
border-radius: 4px;
border: 1px solid #DDDDDD;
background-color: #EEE;
border: 1px solid #dddddd;
background-color: #eee;
}
.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 {EntityIcon} from "../../home/EntityIcon/EntityIcon";
import {createPath, drawLine} from "../../../src/svg";
import {AdditionalNode, GraphNode, GraphNodeWithIds, isAdditionalNode} from "../../../src/graph-untangle/types";
import {graphUntangled} from "../../../src/graph-untangle";
import {Dict} from "../../../src/types";
import { EntityIcon } from '../../home/EntityIcon/EntityIcon'
import { createPath, drawLine } from '../../../src/svg'
import {
AdditionalNode,
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>[]
inputs: string[]
outputs?: string[]
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 [[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(() => {
if (!planeRef.current) return
const plane = planeRef.current
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.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, 'fill', 'none')
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.replaceChildren()
let paths: string[] = []
const paths: string[] = []
plane.querySelectorAll('[data-outputs]').forEach(startNode => {
if (!(startNode instanceof HTMLElement)) return
(startNode.dataset.outputs?.split(' ') ?? []).forEach(output => {
;(startNode.dataset.outputs?.split(' ') ?? []).forEach(output => {
const endNode = plane.querySelector(`[data-name="${output}"]`)
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 => {
if (!(elem instanceof HTMLElement)) return
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(' '))
svg.appendChild(path)
})
return <div className={styles.plane} ref={planeRef}>
return (
<div className={styles.plane} ref={planeRef}>
{rows.map((row, colIdx) => (
<div className={styles.row} key={colIdx} data-row={true}>
{
row.map((uid) => {
{row.map(uid => {
const node = nodeMap[uid]
return (
!isAdditionalNode(node)
? <span
return !isAdditionalNode(node) ? (
<span
data-name={node.___uid}
data-inputs={node.___uidInputs.join(' ')}
data-outputs={node.___uidOutputs.join(' ')}
key={node.___uid}
data-hidden={node.___uidOutputs.length > 0}>
<ChildType
className={styles.node}
node={node}
/>
data-hidden={node.___uidOutputs.length > 0}
>
<ChildType className={styles.node} node={node} />
</span>
: node.___type === 'h'
? <span
) : node.___type === 'h' ? (
<span
className={styles.hidden}
key={node.___uid}
data-name={node.___uid}
data-inputs={node.___uidInputs.join(' ')}
data-outputs={node.___uidOutputs.join(' ')}
data-hidden={true}></span>
: node.___type === 'i'
? <span
data-hidden={true}
></span>
) : node.___type === 'i' ? (
<span
key={node.___uid}
data-name={node.___uid}
data-outputs={node.___uidOutputs.join(' ')}
data-hidden={true}>
data-hidden={true}
>
<EntityIcon value={node.name} />
</span>
: <EntityIcon
) : (
<EntityIcon
key={node.___uid}
value={node.name}
data-name={node.___uid}
data-inputs={node.___uidInputs.join(' ')}
/>
);
})
}
)
})}
</div>
))}
</div>
)
}

View File

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

View File

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

View File

@@ -15,4 +15,3 @@
.linkOut {
margin-inline-end: 0.5em;
}

View File

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

View File

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

View File

@@ -6,7 +6,11 @@
"dev": "next dev",
"build": "next build",
"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": {
"classnames": "^2.3.1",
@@ -30,9 +34,18 @@
"@types/react": "18.0.17",
"@types/react-dom": "18.0.6",
"@types/seedrandom": "^3.0.2",
"@typescript-eslint/eslint-plugin": "^5.33.1",
"@typescript-eslint/parser": "^5.33.1",
"eslint": "8.21.0",
"eslint-config-next": "12.2.4",
"eslint-plugin-unused-imports": "^2.0.0",
"husky": "^8.0.1",
"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"
}
}

View File

@@ -1,7 +1,6 @@
import '../styles/globals.css'
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 }) => {
return <Component {...pageProps} />

View File

@@ -1,9 +1,9 @@
import {Html, Main, NextScript, DocumentProps, Head} from 'next/document';
import {FC} from "react";
import Dict = NodeJS.Dict;
import { Html, Main, NextScript, DocumentProps, Head } from 'next/document'
import { FC } from 'react'
import Dict = NodeJS.Dict
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 (
<Html>
<Head />
@@ -12,7 +12,7 @@ const MyDocument: FC<DocumentProps> = ({ __NEXT_DATA__ }) => {
<NextScript />
</body>
</Html>
);
)
}
export default MyDocument

View File

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

View File

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

View File

@@ -1,14 +1,17 @@
import {nextHandler} from "../../../../../src/utils/errors";
import {validate} from "../../../../../src/validation";
import {GroupIdParam, GroupSetFactoryArrayBody} from "../../../../../src/types/ApiSchemas";
import {setFactoriesOfGroup} from "../../../../../src/database/groups";
import {waitForInitSchemas} from "../../../../../src/validation/schemas";
import { nextHandler } from '../../../../../src/utils/errors'
import { validate } from '../../../../../src/validation'
import { GroupIdParam, GroupSetFactoryArrayBody } from '../../../../../src/types/ApiSchemas'
import { setFactoriesOfGroup } from '../../../../../src/database/groups'
import { waitForInitSchemas } from '../../../../../src/validation/schemas'
const handler = nextHandler(async (req, res) => {
if (req.method !== 'POST') throw new Error('Invalid method')
await waitForInitSchemas.resolve()
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)
res.json({ success })

View File

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

View File

@@ -1,8 +1,8 @@
import {nextHandler} from "../../../../../src/utils/errors";
import {validate} from "../../../../../src/validation";
import {GroupIdParam, GroupRenameBody} from "../../../../../src/types/ApiSchemas";
import {renameGroup} from "../../../../../src/database/groups";
import {waitForInitSchemas} from "../../../../../src/validation/schemas";
import { nextHandler } from '../../../../../src/utils/errors'
import { validate } from '../../../../../src/validation'
import { GroupIdParam, GroupRenameBody } from '../../../../../src/types/ApiSchemas'
import { renameGroup } from '../../../../../src/database/groups'
import { waitForInitSchemas } from '../../../../../src/validation/schemas'
const handler = nextHandler(async (req, res) => {
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 getConfig from "next/config";
import {addSchemas, waitForInitSchemas} from "../../../src/validation/schemas";
import { NetworkError, nextHandler } from '../../../src/utils/errors'
import getConfig from 'next/config'
import { waitForInitSchemas } from '../../../src/validation/schemas'
const {publicRuntimeConfig: {TENANT_TYPE}} = getConfig()
const {
publicRuntimeConfig: { TENANT_TYPE }
} = getConfig()
const handler = nextHandler(async (req, res) => {
if (req.method !== 'GET') throw new NetworkError('Invalid method')

View File

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

View File

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

View File

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

View File

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

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) => {
const prducingSet = new Set(allProducingFactories)
const ignored = new Set(ignoredFactories)
export const calculateInputs = (
allProducingFactories: string[],
baseFactories: string[],
exportedFactories: Set<string>,
findFactory: (uid: string) => EnrichedEntity | undefined
) => {
const producingSet = new Set(allProducingFactories)
const base = new Set(baseFactories)
const inputs = new Set<string>()
const intermediates = new Set<string>()
let next: string | undefined
while (next = allProducingFactories.pop()) {
while ((next = allProducingFactories.pop())) {
const pres = Object.keys(findFactory(next)?.recipe?.prerequisites ?? {})
for (const pre of pres) {
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)) {
if (!prducingSet.has(pre)) intermediates.add(pre)
if (!producingSet.has(pre)) intermediates.add(pre)
allProducingFactories.push(pre)
}
}

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
import {GetServerSideProps} from "next";
import {getGroup, setGroups} from "./database/groups";
import {Dict, Group} from "./types";
import { GetServerSideProps } from 'next'
import { getGroup, setGroups } from './database/groups'
import { Dict, Group } from './types'
export interface PropsGroupProvider {
id: string
@@ -9,9 +9,11 @@ export interface PropsGroupProvider {
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 data = id && await getGroup(id)
const data = id && (await getGroup(id))
if (data) {
return {
props: {
@@ -26,11 +28,10 @@ export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvi
return {
redirect: {
destination: `?id=${newId}`,
permanent: false,
permanent: false
}
}
} else {
console.log(data)
return {
notFound: true
}

View File

@@ -1,31 +1,48 @@
import {AdditionalNode, GraphNode, GraphNodeWithIds, isAdditionalNode} from "./types";
import {Dict} from "../types";
import deepcopy from "deepcopy";
import {isNonNullable, shuffleInplace, sortByProperty, uniquify} from "../utils";
import seedrandom from "seedrandom";
import { AdditionalNode, GraphNode, GraphNodeWithIds } from './types'
import { Dict } from '../types'
import deepcopy from 'deepcopy'
import { isNonNullable, shuffleInplace, sortByProperty, uniquify } from '../utils'
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 {
...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: [],
___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 {
inputs: type !== 'i' ? [uid] : [],
outputs: type !== 'o' ? [uid] : [],
name: uid,
___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: [],
___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 available = new Set(inputs)
let queue = [...nodes]
@@ -35,7 +52,7 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
const availableOfRow: string[] = []
rows.push([])
queue = queue.filter((node) => {
queue = queue.filter(node => {
const isPlaceable = node.inputs.every(input => available.has(input))
if (isPlaceable) {
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))
if (amount === queue.length) {
console.warn("Loop detected! Left over:", queue)
console.warn('Loop detected! Left over:', queue)
rows.pop()
break
}
@@ -56,31 +73,49 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
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 res: string[][] = deepcopy([[], ...rowsRaw, []])
const resNodes: Dict<GraphNodeWithIds<T | AdditionalNode>> = deepcopy(nodesRaw)
for (let i = 0; i < rowsRaw.length; i++) {
const rowInputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].inputs))
for (let rowInput of rowInputs) {
for (const rowInput of rowInputs) {
if (rowInput in addedInputs) {
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)
resNodes[nodeWithId.___uid] = nodeWithId
}
addedInputs[rowInput] = i
} 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)
resNodes[nodeWithId.___uid] = nodeWithId
addedInputs[rowInput] = i
}
}
const rowOutputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].outputs))
for (let rowOutput of rowOutputs) {
for (const rowOutput of rowOutputs) {
if (outputs?.includes(rowOutput)) {
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowOutput, 'o', nodeUid)
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(
rowOutput,
'o',
nodeUid
)
res[i + 2].push(nodeWithId.___uid)
resNodes[nodeWithId.___uid] = nodeWithId
}
@@ -91,7 +126,10 @@ function addAdditionalNodes<T extends Dict<unknown>>(rowsRaw: string[][], nodesR
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>>(
rowsWithInOut: string[][],
nodesWithInOut: Dict<GraphNodeWithIds<T | AdditionalNode>>
): Dict<GraphNodeWithIds<T | AdditionalNode>> {
type Store = { input: Dict<string[]>[], output: Dict<string[]>[] }
const store: Store = {
@@ -99,35 +137,59 @@ function linkNodes<T extends Dict<unknown>>(rowsWithInOut: string[][], nodesWith
output: Array.from(rowsWithInOut, Object)
}
const nodesPremapping = (node: GraphNodeWithIds<T | AdditionalNode>, rowIdx: number) => {
node.inputs.forEach(input => store.input[rowIdx][input] = [...(store.input[rowIdx][input] ?? []), node.___uid])
node.outputs.forEach(output => store.output[rowIdx][output] = [...(store.output[rowIdx][output] ?? []), node.___uid])
};
node.inputs.forEach(
input => (store.input[rowIdx][input] = [...(store.input[rowIdx][input] ?? []), node.___uid])
)
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)
node.___uidInputs = uniquify(node.inputs.flatMap(input => store.output[rowIdx - 1][input]).filter(isNonNullable))
node.___uidInputs = uniquify(
node.inputs.flatMap(input => store.output[rowIdx - 1][input]).filter(isNonNullable)
)
if (rowIdx < rowsWithInOut.length - 1)
node.___uidOutputs = uniquify(node.outputs.flatMap(output => store.input[rowIdx + 1][output]).filter(isNonNullable))
};
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)))
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))
let score = 0
for (let i = 0; i < flex.length - 1; i++) {
for (let j = i + 1; j < flex.length; j++) {
const inputsI = new Set(nodes[flex[i]][isDown ? '___uidInputs' : '___uidOutputs'])
const inputsJ = new Set(nodes[flex[j]][isDown ? '___uidInputs' : '___uidOutputs'])
const diff = fixed.reduce(([size, acc], curr) => {
const diff =
fixed.reduce(
([size, acc], curr) => {
inputsI.has(curr) && size--
return [size, acc + (inputsJ.has(curr) ? size : 0)]
}, [inputsI.size, 0])[1] - fixed.reduce(([size, acc], curr) => {
},
[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]
},
[inputsJ.size, 0]
)[1]
result[i][j] = diff
result[j][i] = -diff
score += diff
@@ -136,9 +198,14 @@ function crossingsOf<T extends Dict<unknown>>(fixed: string[], flex: string[], n
return [result, score]
}
function optimizeOrder<T extends Dict<unknown>>(rowsWithInOut: string[][], nodesWithInOut: Dict<GraphNodeWithIds<T|AdditionalNode>>): [string[][], number] {
function addCosts(costsUp: [number[][], number], costsDown: [number[][], number]): [number[][], number] {
function optimizeOrder<T extends Dict<unknown>>(
rowsWithInOut: string[][],
nodesWithInOut: Dict<GraphNodeWithIds<T | AdditionalNode>>
): [string[][], number] {
function addCosts(
costsUp: [number[][], number],
costsDown: [number[][], number]
): [number[][], number] {
return [
costsUp[0].map((row, rowIdx) => row.map((col, colIdx) => col + costsDown[0][rowIdx][colIdx])),
costsUp[1] + costsDown[1]
@@ -148,32 +215,41 @@ function optimizeOrder<T extends Dict<unknown>>(rowsWithInOut: string[][], nodes
function improveRow(top: string[] | undefined, mid: string[], bot: string[] | undefined) {
const costsUp = top ? crossingsOf(top, mid, nodesWithInOut, true) : 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
if (!costs) return score
let improvementInRow = true
while (improvementInRow) {
improvementInRow = false
const colBest = costs
.map((_, idx) => costs
.map(
(_, idx) =>
costs
.slice(0, idx)
.map(r => r[idx])
.reverse()
.reduce(([sum, best], curr, i) => {
.reduce(
([sum, best], curr, i) => {
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]
? ([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)
const rowBest = costs
.map((_, idx) => costs[idx]
.slice(idx+1)
.reduce(([sum, best], curr, i) => {
.map(
(_, idx) =>
costs[idx].slice(idx + 1).reduce(
([sum, best], curr, i) => {
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]
? ([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)
const replacement = [...colBest, ...rowBest].sort(sortByProperty(red => -red.sum))[0]
@@ -182,7 +258,9 @@ function optimizeOrder<T extends Dict<unknown>>(rowsWithInOut: string[][], nodes
improvement = true
improvementInRow = true
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 =>
col.splice(replacement.move + replacement.idx, 0, ...col.splice(replacement.idx, 1))
)
mid.splice(replacement.move + replacement.idx, 0, ...mid.splice(replacement.idx, 1))
}
}
@@ -191,7 +269,7 @@ function optimizeOrder<T extends Dict<unknown>>(rowsWithInOut: string[][], nodes
type Reduce = { sum: number, move: number, idx: number }
let improvement = true
let scores: number[] = []
const scores: number[] = []
while (improvement) {
improvement = false
rowsWithInOut.reduce((top, mid, idx) => {
@@ -206,12 +284,16 @@ function optimizeOrder<T extends Dict<unknown>>(rowsWithInOut: string[][], nodes
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 bestRows = deepcopy(rowsWithInOut)
let limit = Date.now() + timeLimit
const limit = Date.now() + timeLimit
let iterSinceImprovements = 0
let rng = seedrandom.alea("We are SEEED, ya!")
const rng = seedrandom.alea('We are SEEED, ya!')
while (true) {
if (Date.now() > limit) break
if (iterSinceImprovements > 100) break
@@ -223,21 +305,31 @@ export function findBest<T extends Dict<unknown>>(rowsWithInOut: string[][], nod
} else {
iterSinceImprovements++
}
rowsOptimized.forEach((row, ) => shuffleInplace(row, rng))
rowsOptimized.forEach(row => shuffleInplace(row, rng))
}
console.log(bestScore)
return bestRows
}
export function graphUntangled<T extends Dict<unknown>>(nodes: GraphNode<T>[], inputs: string[], outputs: string[], timeLimit = 0): [string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>] {
const nodeSeed = seedrandom.alea("node")
export function graphUntangled<T extends Dict<unknown>>(
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)
//console.log('---------------')
const [rowsRaw, nodesRaw] = splitIntoRows(inputs, nodes, nodeUid)
//console.log("Step 1")
//console.table(rowsRaw)
//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.table(rowsWithInOut)
//console.table(nodesWithInOut)

View File

@@ -1,4 +1,4 @@
import {Dict} from "../types";
import { Dict } from '../types'
interface GraphNodeBase {
inputs: string[]
@@ -17,4 +17,5 @@ export type AdditionalNode = {
___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,
handler: (event: WindowEventMap[K]) => void,
element?: undefined,
options?: boolean | AddEventListenerOptions,
options?: boolean | AddEventListenerOptions
): void
// Element Event based useEventListener interface
export function useEventListener<
K extends keyof HTMLElementEventMap,
T extends HTMLElement = HTMLDivElement,
T extends HTMLElement = HTMLDivElement
>(
eventName: K,
handler: (event: HTMLElementEventMap[K]) => void,
element: RefObject<T>,
options?: boolean | AddEventListenerOptions,
options?: boolean | AddEventListenerOptions
): void
// Document Event based useEventListener interface
@@ -27,20 +27,18 @@ export function useEventListener<K extends keyof DocumentEventMap>(
eventName: K,
handler: (event: DocumentEventMap[K]) => void,
element: RefObject<Document>,
options?: boolean | AddEventListenerOptions,
options?: boolean | AddEventListenerOptions
): void
export function useEventListener<
KW extends keyof WindowEventMap,
KH extends keyof HTMLElementEventMap,
T extends HTMLElement | void = void,
T extends HTMLElement | void = void
>(
eventName: KW | KH,
handler: (
event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event,
) => void,
handler: (event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event) => void,
element?: RefObject<T>,
options?: boolean | AddEventListenerOptions,
options?: boolean | AddEventListenerOptions
) {
// Create a ref that stores handler
const savedHandler = useRef(handler)

View File

@@ -1,19 +1,19 @@
import {EnrichedEntity, Entity} from "../types";
import details from "../../res/details.json";
import manual from "../../res/manual.json";
import { EnrichedEntity, Entity } from '../types'
import details from '../../res/details.json'
import manual from '../../res/manual.json'
const joined = [...details, ...manual] as Entity[]
const factories = joined.map((detail: EnrichedEntity) => {
detail.usedBy = joined
.filter(f => Object
.keys(f.recipe?.prerequisites ?? {})
.includes(detail.href)
detail.usedBy = joined.filter(f =>
Object.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 = () => ({
factories,

View File

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

View File

@@ -1,10 +1,4 @@
import {
Dispatch,
SetStateAction,
useCallback,
useEffect,
useState,
} from 'react'
import { Dispatch, SetStateAction, useCallback, useEffect, useState } from 'react'
// See: https://usehooks-ts.com/react-hook/use-event-listener
import { useEventListener } from './useEventListener'
@@ -41,11 +35,12 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue: SetValue<T> = useCallback(value => {
const setValue: SetValue<T> = useCallback(
value => {
// Prevent build error "window is undefined" but keeps working
if (typeof window == 'undefined') {
console.warn(
`Tried setting localStorage key “${key}” even though environment is not a client`,
`Tried setting localStorage key “${key}” even though environment is not a client`
)
}
@@ -64,7 +59,9 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
} catch (error) {
console.warn(`Error setting localStorage key “${key}”:`, error)
}
}, [key, storedValue])
},
[key, storedValue]
)
useEffect(() => {
setStoredValue(readValue())
@@ -78,7 +75,7 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
}
setStoredValue(readValue())
},
[key, readValue],
[key, readValue]
)
// 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' {
export interface ServerRuntimeConfig {
MONGO_URL: string
@@ -15,7 +11,7 @@ declare module 'next/config' {
}
const getConfig: () => {
serverRuntimeConfig: ServerRuntimeConfig,
serverRuntimeConfig: ServerRuntimeConfig
publicRuntimeConfig: PublicRuntimeConfig
}
export default getConfig

View File

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

View File

@@ -1,5 +1,5 @@
import {Dict} from "./types";
import {PRNG} from "seedrandom";
import { Dict } from './types'
import { PRNG } from 'seedrandom'
export function isNonNullable<T>(any: T): any is NonNullable<T> {
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[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(rng.quick() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
const j = Math.floor(rng.quick() * (i + 1))
;[array[i], array[j]] = [array[j], array[i]]
}
return array
}
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])
break
case ResolvableState.DONE:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
resolve(this.data!)
break
case ResolvableState.ERROR:

View File

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

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-console */
export const logger = {
verbose: 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 { join } from 'path'
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()

View File

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

View File

@@ -2,14 +2,24 @@ html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
font-family:
-apple-system,
BlinkMacSystemFont,
"Segoe UI",
Roboto,
Oxygen,
Ubuntu,
Cantarell,
"Fira Sans",
"Droid Sans",
"Helvetica Neue",
sans-serif;
}
body {
color: black;
background: #FAFAFA;
padding: 2em;
background: #fafafa;
color: black;
}
body.scroll {
@@ -36,17 +46,18 @@ h3 {
}
h4 {
margin-block: 1em 0.3em;
font-weight: 500;
margin-block: 1em 0.3em;
}
@media (prefers-color-scheme: dark) {
html {
color-scheme: dark;
}
body {
color: white;
background: #111;
color: white;
}
}

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