Linting
This commit is contained in:
3
.eslintignore
Normal file
3
.eslintignore
Normal file
@@ -0,0 +1,3 @@
|
||||
.next
|
||||
node_modules
|
||||
*.json
|
||||
@@ -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
12
.lintstagedrc
Normal 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
17
.stylelintrc.json
Normal 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": ".*"
|
||||
}
|
||||
}
|
||||
@@ -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
|
||||
@@ -31,8 +35,8 @@ interface GroupContextType {
|
||||
removeGroup(name: string): void
|
||||
renameGroup(name: string, newName: string): void
|
||||
|
||||
setFactories(name: string, factories: string[], type: 'exports'|'malls'): void
|
||||
getInputType(uid: string): 'base'|'produced'|'unknown'
|
||||
setFactories(name: string, factories: string[], type: 'exports' | 'malls'): void
|
||||
getInputType(uid: string): 'base' | 'produced' | 'unknown'
|
||||
|
||||
store(): Uint8Array
|
||||
load(str: Uint8Array): void
|
||||
@@ -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[]
|
||||
}
|
||||
|
||||
@@ -80,143 +102,203 @@ export const postFetchJson = async (url: string, body: Dict<unknown>) => {
|
||||
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 [basicValues, _setBasicValues] = useState<string[]>(initial.base)
|
||||
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) => {
|
||||
_setExcludedSuggestions(val)
|
||||
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, {
|
||||
type: 'ignored',
|
||||
factories: val
|
||||
} as SetFactoryArrayBody)
|
||||
.catch(console.error)
|
||||
}, [id])
|
||||
const setExcludedSuggestions = useCallback<typeof _setExcludedSuggestions>(
|
||||
val => {
|
||||
_setExcludedSuggestions(val)
|
||||
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, {
|
||||
type: 'ignored',
|
||||
factories: val
|
||||
} as SetFactoryArrayBody).catch(console.error)
|
||||
},
|
||||
[id]
|
||||
)
|
||||
|
||||
const setBasicValues = useCallback<typeof _setBasicValues>((val) => {
|
||||
_setBasicValues(val)
|
||||
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, {
|
||||
type: 'base',
|
||||
factories: val
|
||||
} as SetFactoryArrayBody)
|
||||
.catch(console.error)
|
||||
}, [id])
|
||||
const setBasicValues = useCallback<typeof _setBasicValues>(
|
||||
val => {
|
||||
_setBasicValues(val)
|
||||
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, {
|
||||
type: 'base',
|
||||
factories: val
|
||||
} as SetFactoryArrayBody).catch(console.error)
|
||||
},
|
||||
[id]
|
||||
)
|
||||
|
||||
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}
|
||||
})
|
||||
;(async () => {
|
||||
await postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/add`, {})
|
||||
if (exports.length) {
|
||||
await postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`, {
|
||||
type: 'exports',
|
||||
factories: exports
|
||||
} as GroupSetFactoryArrayBody)
|
||||
}
|
||||
if (malls.length) {
|
||||
await postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`, {
|
||||
type: 'malls',
|
||||
factories: exports
|
||||
} as GroupSetFactoryArrayBody)
|
||||
}
|
||||
})().catch(console.error)
|
||||
return true
|
||||
}, [groups, id])
|
||||
const removeGroup = useCallback((name: string) => {
|
||||
name = name.replace(/[.$]/g, '')
|
||||
setGroups(groups => {
|
||||
delete groups[name]
|
||||
console.log(groups[name])
|
||||
return {...groups}
|
||||
})
|
||||
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}
|
||||
})
|
||||
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/rename`, {
|
||||
newName
|
||||
} as GroupRenameBody)
|
||||
.catch(console.error)
|
||||
}, [groups, id])
|
||||
const addGroup = useCallback(
|
||||
(name: string, exports: string[] = [], malls: string[] = []) => {
|
||||
name = name.replace(/[.$]/g, '')
|
||||
if (name in groups) return false
|
||||
setGroups(g => {
|
||||
g[name] = { name, exports, malls }
|
||||
return { ...g }
|
||||
})
|
||||
;(async () => {
|
||||
await postFetchJson(
|
||||
`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/add`,
|
||||
{}
|
||||
)
|
||||
if (exports.length) {
|
||||
await postFetchJson(
|
||||
`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`,
|
||||
{
|
||||
type: 'exports',
|
||||
factories: exports
|
||||
} as GroupSetFactoryArrayBody
|
||||
)
|
||||
}
|
||||
if (malls.length) {
|
||||
await postFetchJson(
|
||||
`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`,
|
||||
{
|
||||
type: 'malls',
|
||||
factories: exports
|
||||
} as GroupSetFactoryArrayBody
|
||||
)
|
||||
}
|
||||
})().catch(console.error)
|
||||
return true
|
||||
},
|
||||
[groups, id]
|
||||
)
|
||||
const removeGroup = useCallback(
|
||||
(name: string) => {
|
||||
name = name.replace(/[.$]/g, '')
|
||||
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) => {
|
||||
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') => {
|
||||
name = name.replace(/[.$]/g, '')
|
||||
setGroups(groups => {
|
||||
groups[name] = {...groups[name], [type]: factories}
|
||||
return {...groups}
|
||||
})
|
||||
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`, {
|
||||
type,
|
||||
factories
|
||||
} 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])
|
||||
const setFactories = useCallback(
|
||||
(name: string, factories: string[], type: 'exports' | 'malls') => {
|
||||
name = name.replace(/[.$]/g, '')
|
||||
setGroups(g => {
|
||||
g[name] = { ...g[name], [type]: factories }
|
||||
return { ...g }
|
||||
})
|
||||
postFetchJson(
|
||||
`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`,
|
||||
{
|
||||
type,
|
||||
factories
|
||||
} 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]
|
||||
)
|
||||
|
||||
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 value: StoredFile = JSON.parse(uncompressed)
|
||||
if (!value.groups || !value.basicValues || !value.excludedSuggestions) return
|
||||
setGroups(value.groups)
|
||||
setBasicValues(value.basicValues)
|
||||
setExcludedSuggestions(value.excludedSuggestions)
|
||||
}, [])
|
||||
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(() => ({
|
||||
doNotSuggest,
|
||||
exportedFactories,
|
||||
const value: GroupContextType = useMemo(
|
||||
() => ({
|
||||
doNotSuggest,
|
||||
exportedFactories,
|
||||
|
||||
ignoredFactories: excludedSuggestions,
|
||||
setIgnoredFactories: setExcludedSuggestions,
|
||||
ignoredFactories: excludedSuggestions,
|
||||
setIgnoredFactories: setExcludedSuggestions,
|
||||
|
||||
baseFactories: basicValues,
|
||||
setBaseFactories: setBasicValues,
|
||||
baseFactories: basicValues,
|
||||
setBaseFactories: setBasicValues,
|
||||
|
||||
groups,
|
||||
addGroup,
|
||||
removeGroup,
|
||||
renameGroup,
|
||||
groups,
|
||||
addGroup,
|
||||
removeGroup,
|
||||
renameGroup,
|
||||
|
||||
setFactories,
|
||||
getInputType,
|
||||
setFactories,
|
||||
getInputType,
|
||||
|
||||
store,
|
||||
load
|
||||
}), [addGroup, basicValues, doNotSuggest, excludedSuggestions, exportedFactories, getInputType, groups, load, removeGroup, renameGroup, setBasicValues, setExcludedSuggestions, setFactories, store])
|
||||
store,
|
||||
load
|
||||
}),
|
||||
[
|
||||
addGroup,
|
||||
basicValues,
|
||||
doNotSuggest,
|
||||
excludedSuggestions,
|
||||
exportedFactories,
|
||||
getInputType,
|
||||
groups,
|
||||
load,
|
||||
removeGroup,
|
||||
renameGroup,
|
||||
setBasicValues,
|
||||
setExcludedSuggestions,
|
||||
setFactories,
|
||||
store
|
||||
]
|
||||
)
|
||||
return <GroupContext.Provider value={value}>{children}</GroupContext.Provider>
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
.span {
|
||||
background: #DDD;
|
||||
background: #ddd;
|
||||
font-size: 2em;
|
||||
border: 1px solid white;
|
||||
display: inline-block;
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
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
|
||||
value: Entity | string
|
||||
amount?: number
|
||||
}
|
||||
|
||||
export const EntityIcon: FC<Props> = ({className, value, amount, ...rest}) => {
|
||||
const {findFactory} = useFactories()
|
||||
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}>
|
||||
{/* 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}/>
|
||||
{amount !== undefined && <span className={styles.amount}>{amount}</span>}
|
||||
</span>
|
||||
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}
|
||||
/>
|
||||
{amount !== undefined && <span className={styles.amount}>{amount}</span>}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,25 +1,33 @@
|
||||
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
|
||||
state?: 'base'|'produced'|'unknown'
|
||||
value: EnrichedEntity | string
|
||||
state?: 'base' | 'produced' | 'unknown'
|
||||
leftClickText?: string
|
||||
rightClickText?: string
|
||||
simpleStyle?: boolean
|
||||
className?: string
|
||||
}
|
||||
|
||||
const EntitySpanUnmemo: FC<Props> = ({className, value, state, leftClickText, rightClickText, simpleStyle, ...rest}) => {
|
||||
const {findFactory} = useFactories()
|
||||
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,34 +38,52 @@ const EntitySpanUnmemo: FC<Props> = ({className, value, state, leftClickText, ri
|
||||
}
|
||||
}, [findFactory, value])
|
||||
|
||||
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}/>
|
||||
<span className={styles[state ?? 'unknown']}>{entity.name}</span>
|
||||
<div className={styles.tooltip}>
|
||||
{entity.recipe && (
|
||||
<>
|
||||
<div className={styles.strong}>Recipe</div>
|
||||
<RecipeSpan recipe={entity.recipe}/>
|
||||
</>
|
||||
)}
|
||||
{entity.usedBy?.length ? (
|
||||
<>
|
||||
<div className={styles.strong}>Used By</div>
|
||||
<div className={styles.usedBy}>
|
||||
{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>}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</span>
|
||||
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}
|
||||
/>
|
||||
<span className={styles[state ?? 'unknown']}>{entity.name}</span>
|
||||
<div className={styles.tooltip}>
|
||||
{entity.recipe && (
|
||||
<>
|
||||
<div className={styles.strong}>Recipe</div>
|
||||
<RecipeSpan recipe={entity.recipe} />
|
||||
</>
|
||||
)}
|
||||
{entity.usedBy?.length ? (
|
||||
<>
|
||||
<div className={styles.strong}>Used By</div>
|
||||
<div className={styles.usedBy}>
|
||||
{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>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export const EntitySpan = memo(EntitySpanUnmemo)
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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
|
||||
@@ -16,33 +16,37 @@ const options = details.map(detail => ({
|
||||
value: detail.href
|
||||
}))
|
||||
|
||||
const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => {
|
||||
const FactorySelectBase: FC<Props> = ({ id, factories, onSetFactories }) => {
|
||||
const state = useMemo<typeof options>(() => {
|
||||
return factories
|
||||
.map(factory => options.find(option => option.value === factory))
|
||||
.filter(isNonNullable)
|
||||
}, [factories])
|
||||
|
||||
return <Select
|
||||
id={id}
|
||||
instanceId={id}
|
||||
value={state}
|
||||
components={{
|
||||
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>
|
||||
)
|
||||
}}
|
||||
isMulti
|
||||
options={options as never}
|
||||
onChange={e => {
|
||||
onSetFactories(e.map(s => s?.value))
|
||||
}}
|
||||
className={styles.select}
|
||||
classNamePrefix={"factory-select"}
|
||||
/>
|
||||
return (
|
||||
<Select
|
||||
id={id}
|
||||
instanceId={id}
|
||||
value={state}
|
||||
components={{
|
||||
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>
|
||||
)
|
||||
}}
|
||||
isMulti
|
||||
options={options as never}
|
||||
onChange={e => {
|
||||
onSetFactories(e.map(s => s?.value))
|
||||
}}
|
||||
className={styles.select}
|
||||
classNamePrefix={'factory-select'}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export const FactorySelect = memo(FactorySelectBase)
|
||||
|
||||
@@ -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
|
||||
@@ -16,7 +16,7 @@ interface Props {
|
||||
|
||||
const GroupBoxBase: FC<Props> = ({ group }) => {
|
||||
const router = useRouter()
|
||||
const {factories, findFactory} = useFactories()
|
||||
const { factories, findFactory } = useFactories()
|
||||
const {
|
||||
doNotSuggest,
|
||||
setFactories,
|
||||
@@ -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,110 +48,142 @@ const GroupBoxBase: FC<Props> = ({ group }) => {
|
||||
const prerequisites = Object.keys(factory.recipe.prerequisites ?? {})
|
||||
return prerequisites.every(pre => availableIngredients.includes(pre))
|
||||
})
|
||||
.reduce((acc, factory) =>
|
||||
(factory.usedBy?.length ?? 0) >= 3
|
||||
? [[...acc[0], factory], acc[1]]
|
||||
: [acc[0], [...acc[1], factory]],
|
||||
.reduce(
|
||||
(acc, factory) =>
|
||||
(factory.usedBy?.length ?? 0) >= 3
|
||||
? [[...acc[0], factory], acc[1]]
|
||||
: [acc[0], [...acc[1], factory]],
|
||||
[[], []] as [EnrichedEntity[], EnrichedEntity[]]
|
||||
)
|
||||
}, [exports, malls, intermediates, inputs, factories, doNotSuggest])
|
||||
|
||||
const addFactory = useCallback((uid: string, type: Parameters<typeof setFactories>[2]) => {
|
||||
setFactories(name, [...group[type], uid], type)
|
||||
}, [group, name, setFactories])
|
||||
const addFactory = useCallback(
|
||||
(uid: string, type: Parameters<typeof setFactories>[2]) => {
|
||||
setFactories(name, [...group[type], uid], type)
|
||||
},
|
||||
[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}>
|
||||
<h3
|
||||
contentEditable={true}
|
||||
suppressContentEditableWarning={true}
|
||||
onBlur={event => {
|
||||
event.currentTarget.innerText = event.currentTarget.innerText.trim()
|
||||
renameGroup(name, event.currentTarget.innerText);
|
||||
}}
|
||||
>
|
||||
{name}
|
||||
</h3>
|
||||
<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'}}
|
||||
>
|
||||
{isDeleteConfirm ? 'Delete GroupBox?' : 'X'}
|
||||
</button>
|
||||
<h4>Exported Factories</h4>
|
||||
<FactorySelect
|
||||
id={name+"-exports"}
|
||||
factories={exports}
|
||||
onSetFactories={setExportFactories}
|
||||
/>
|
||||
<h4>Mall Factories</h4>
|
||||
<FactorySelect
|
||||
id={name+"-malls"}
|
||||
factories={malls}
|
||||
onSetFactories={setMallFactories}
|
||||
/>
|
||||
{ inputs.length ? <>
|
||||
<h4>Input Factories ({inputs.length})</h4>
|
||||
<div className={styles.flex}>
|
||||
{ inputs.map(input => <EntitySpan
|
||||
key={input}
|
||||
value={input}
|
||||
state={getInputType(input)}
|
||||
onContextMenu={event => {
|
||||
event.preventDefault()
|
||||
setIgnoredFactories([...ignoredFactories, input])
|
||||
}}
|
||||
rightClickText={"Exclude this recipe from suggestions"}
|
||||
/>) }
|
||||
</div>
|
||||
</> : null }
|
||||
{ intermediates.length ? <>
|
||||
<h4>Intermediate Factories ({intermediates.length})</h4>
|
||||
<div className={styles.flex}>
|
||||
{ intermediates.map(intermediate => <EntitySpan
|
||||
key={intermediate}
|
||||
value={intermediate}
|
||||
state={getInputType(intermediate)}
|
||||
/>) }
|
||||
</div>
|
||||
</> : null }
|
||||
{ suggestionsExport.length ? <>
|
||||
<h4>Suggestions (Export)</h4>
|
||||
<div className={styles.flex}>
|
||||
{ suggestionsExport.map(suggestion => <EntitySpan
|
||||
key={suggestion.href}
|
||||
value={suggestion}
|
||||
onClick={() => addFactory(suggestion.href, 'exports')}
|
||||
onContextMenu={event => {
|
||||
event.preventDefault()
|
||||
setIgnoredFactories([...ignoredFactories, suggestion.href])
|
||||
}}
|
||||
leftClickText={"Add to exported factories"}
|
||||
rightClickText={"Exclude this recipe from suggestions"}
|
||||
/>) }
|
||||
</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>
|
||||
return (
|
||||
<div className={styles.root}>
|
||||
<h3
|
||||
contentEditable={true}
|
||||
suppressContentEditableWarning={true}
|
||||
onBlur={event => {
|
||||
event.currentTarget.innerText = event.currentTarget.innerText.trim()
|
||||
renameGroup(name, event.currentTarget.innerText)
|
||||
}}
|
||||
>
|
||||
{name}
|
||||
</h3>
|
||||
<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' }}
|
||||
>
|
||||
{isDeleteConfirm ? 'Delete GroupBox?' : 'X'}
|
||||
</button>
|
||||
<h4>Exported Factories</h4>
|
||||
<FactorySelect
|
||||
id={name + '-exports'}
|
||||
factories={exports}
|
||||
onSetFactories={setExportFactories}
|
||||
/>
|
||||
<h4>Mall Factories</h4>
|
||||
<FactorySelect id={name + '-malls'} factories={malls} onSetFactories={setMallFactories} />
|
||||
{inputs.length ? (
|
||||
<>
|
||||
<h4>Input Factories ({inputs.length})</h4>
|
||||
<div className={styles.flex}>
|
||||
{inputs.map(input => (
|
||||
<EntitySpan
|
||||
key={input}
|
||||
value={input}
|
||||
state={getInputType(input)}
|
||||
onContextMenu={event => {
|
||||
event.preventDefault()
|
||||
setIgnoredFactories([...ignoredFactories, input])
|
||||
}}
|
||||
rightClickText={'Exclude this recipe from suggestions'}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
{intermediates.length ? (
|
||||
<>
|
||||
<h4>Intermediate Factories ({intermediates.length})</h4>
|
||||
<div className={styles.flex}>
|
||||
{intermediates.map(intermediate => (
|
||||
<EntitySpan
|
||||
key={intermediate}
|
||||
value={intermediate}
|
||||
state={getInputType(intermediate)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
{suggestionsExport.length ? (
|
||||
<>
|
||||
<h4>Suggestions (Export)</h4>
|
||||
<div className={styles.flex}>
|
||||
{suggestionsExport.map(suggestion => (
|
||||
<EntitySpan
|
||||
key={suggestion.href}
|
||||
value={suggestion}
|
||||
onClick={() => addFactory(suggestion.href, 'exports')}
|
||||
onContextMenu={event => {
|
||||
event.preventDefault()
|
||||
setIgnoredFactories([...ignoredFactories, suggestion.href])
|
||||
}}
|
||||
leftClickText={'Add to exported factories'}
|
||||
rightClickText={'Exclude this recipe from suggestions'}
|
||||
/>
|
||||
))}
|
||||
</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)
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
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()
|
||||
const {factories} = useFactories()
|
||||
const { factories } = useFactories()
|
||||
const {
|
||||
groups,
|
||||
addGroup,
|
||||
@@ -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,49 +41,66 @@ export const Home: FC = () => {
|
||||
return (
|
||||
<main>
|
||||
<h1>Factorio Microservices</h1>
|
||||
<button onClick={() => {
|
||||
download('factorio-microservices.bin', store());
|
||||
}}>Store</button>
|
||||
<button onClick={async () => {
|
||||
const res = await fetch( '/api/submit', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({groups, ignored: ignoredFactories, base: baseFactories})
|
||||
})
|
||||
if (res.ok) {
|
||||
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
|
||||
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>
|
||||
<button
|
||||
onClick={() => {
|
||||
download('factorio-microservices.bin', store())
|
||||
}}
|
||||
>
|
||||
Store
|
||||
</button>
|
||||
<button
|
||||
onClick={async () => {
|
||||
const res = await fetch('/api/submit', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({ groups, ignored: ignoredFactories, base: baseFactories })
|
||||
})
|
||||
if (res.ok) {
|
||||
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
|
||||
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>
|
||||
<legend>Missing export factories</legend>
|
||||
<div className={styles.missingFactories}>
|
||||
{ missingExport.map(missing => (
|
||||
{missingExport.map(missing => (
|
||||
<EntitySpan
|
||||
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>
|
||||
@@ -90,31 +108,34 @@ export const Home: FC = () => {
|
||||
<fieldset>
|
||||
<legend>Missing mall factories</legend>
|
||||
<div className={styles.missingFactories}>
|
||||
{ missingMall.map(missing => (
|
||||
{missingMall.map(missing => (
|
||||
<EntitySpan
|
||||
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)
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
.map((group) => <GroupBox key={group.name} group={group} />)
|
||||
}
|
||||
{Object.values(groups)
|
||||
.sort((a, b) => a.name.localeCompare(b.name))
|
||||
.map(group => (
|
||||
<GroupBox key={group.name} group={group} />
|
||||
))}
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {FC} from "react";
|
||||
import { FC } from 'react'
|
||||
|
||||
interface Props {
|
||||
className?: string
|
||||
@@ -6,11 +6,25 @@ interface Props {
|
||||
classClick?: string
|
||||
}
|
||||
|
||||
export const LeftClickIcon: FC<Props> = ({className, classBody, classClick}) => {
|
||||
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>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,42 +1,42 @@
|
||||
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 <>
|
||||
<fieldset>
|
||||
<legend>Basic Values</legend>
|
||||
<FactorySelect
|
||||
id={'baseFactoriesSelect'}
|
||||
factories={baseFactories}
|
||||
onSetFactories={setBaseFactories}
|
||||
/>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Ignored Values</legend>
|
||||
<FactorySelect
|
||||
id={'ignoredFactoriesSelect'}
|
||||
factories={ignoredFactories}
|
||||
onSetFactories={setIgnoredFactories}
|
||||
/>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Add new groups</legend>
|
||||
<input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)}/>
|
||||
<button disabled={!newGroupValue} onClick={() => {
|
||||
addGroup(newGroupValue)
|
||||
setNewGroupValue("New group")
|
||||
}}>
|
||||
Add group "{newGroupValue}"
|
||||
</button>
|
||||
</fieldset>
|
||||
</>
|
||||
const { addGroup, baseFactories, setBaseFactories, ignoredFactories, setIgnoredFactories } =
|
||||
useGroups()
|
||||
const [newGroupValue, setNewGroupValue] = useState('New group')
|
||||
return (
|
||||
<>
|
||||
<fieldset>
|
||||
<legend>Basic Values</legend>
|
||||
<FactorySelect
|
||||
id={'baseFactoriesSelect'}
|
||||
factories={baseFactories}
|
||||
onSetFactories={setBaseFactories}
|
||||
/>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Ignored Values</legend>
|
||||
<FactorySelect
|
||||
id={'ignoredFactoriesSelect'}
|
||||
factories={ignoredFactories}
|
||||
onSetFactories={setIgnoredFactories}
|
||||
/>
|
||||
</fieldset>
|
||||
<fieldset>
|
||||
<legend>Add new groups</legend>
|
||||
<input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)} />
|
||||
<button
|
||||
disabled={!newGroupValue}
|
||||
onClick={() => {
|
||||
addGroup(newGroupValue)
|
||||
setNewGroupValue('New group')
|
||||
}}
|
||||
>
|
||||
Add group "{newGroupValue}"
|
||||
</button>
|
||||
</fieldset>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,24 +1,29 @@
|
||||
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 {
|
||||
recipe: Recipe
|
||||
}
|
||||
|
||||
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) => {
|
||||
if (acc.length) {
|
||||
return [...acc, '+', curr]
|
||||
} else {
|
||||
return [curr]
|
||||
}
|
||||
}, [] 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}>
|
||||
{joinByPlus([toEntityIcon(['/Time', recipe.time]), ...before])} → {joinByPlus(after)}
|
||||
</span>
|
||||
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) => {
|
||||
if (acc.length) {
|
||||
return [...acc, '+', curr]
|
||||
} else {
|
||||
return [curr]
|
||||
}
|
||||
}, [] 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}>
|
||||
{joinByPlus([toEntityIcon(['/Time', recipe.time]), ...before])} → {joinByPlus(after)}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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>}>
|
||||
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}>
|
||||
{rows.map((row, colIdx) => (
|
||||
<div className={styles.row} key={colIdx} data-row={true}>
|
||||
{
|
||||
row.map((uid) => {
|
||||
return (
|
||||
<div className={styles.plane} ref={planeRef}>
|
||||
{rows.map((row, colIdx) => (
|
||||
<div className={styles.row} key={colIdx} data-row={true}>
|
||||
{row.map(uid => {
|
||||
const node = nodeMap[uid]
|
||||
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}
|
||||
/>
|
||||
</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
|
||||
key={node.___uid}
|
||||
data-name={node.___uid}
|
||||
data-outputs={node.___uidOutputs.join(' ')}
|
||||
data-hidden={true}>
|
||||
<EntityIcon value={node.name}/>
|
||||
</span>
|
||||
: <EntityIcon
|
||||
key={node.___uid}
|
||||
value={node.name}
|
||||
data-name={node.___uid}
|
||||
data-inputs={node.___uidInputs.join(' ')}
|
||||
/>
|
||||
);
|
||||
})
|
||||
}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
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} />
|
||||
</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
|
||||
key={node.___uid}
|
||||
data-name={node.___uid}
|
||||
data-outputs={node.___uidOutputs.join(' ')}
|
||||
data-hidden={true}
|
||||
>
|
||||
<EntityIcon value={node.name} />
|
||||
</span>
|
||||
) : (
|
||||
<EntityIcon
|
||||
key={node.___uid}
|
||||
value={node.name}
|
||||
data-name={node.___uid}
|
||||
data-inputs={node.___uidInputs.join(' ')}
|
||||
/>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
export const ScrollContainer: FC<PropsWithChildren> = ({ children }) => {
|
||||
const container = useRef<HTMLDivElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
if (container.current) {
|
||||
container.current.oncontextmenu = e => e.preventDefault()
|
||||
}
|
||||
}, []);
|
||||
}, [])
|
||||
|
||||
return <IndianaDragScoll
|
||||
className={styles.container}
|
||||
buttons={[2]}
|
||||
innerRef={container}
|
||||
hideScrollbars={false}
|
||||
activationDistance={5}
|
||||
>
|
||||
<div className={styles.inner}>
|
||||
{children}
|
||||
</div>
|
||||
</IndianaDragScoll>
|
||||
return (
|
||||
<IndianaDragScoll
|
||||
className={styles.container}
|
||||
buttons={[2]}
|
||||
innerRef={container}
|
||||
hideScrollbars={false}
|
||||
activationDistance={5}
|
||||
>
|
||||
<div className={styles.inner}>{children}</div>
|
||||
</IndianaDragScoll>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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[]
|
||||
@@ -13,9 +13,13 @@ interface Props extends HTMLProps<HTMLDivElement> {
|
||||
node: DetailGraphNode
|
||||
}
|
||||
|
||||
export const NodeDetails: FC<Props> = ({node, className, ...props}) => {
|
||||
return <div {...props} className={cx(className, styles.root)}>
|
||||
<h3>{node.name}</h3>
|
||||
{node.recipes.map((recipe, idx) => <RecipeSpan key={idx} recipe={recipe}/>)}
|
||||
</div>
|
||||
export const NodeDetails: FC<Props> = ({ node, className, ...props }) => {
|
||||
return (
|
||||
<div {...props} className={cx(className, styles.root)}>
|
||||
<h3>{node.name}</h3>
|
||||
{node.recipes.map((recipe, idx) => (
|
||||
<RecipeSpan key={idx} recipe={recipe} />
|
||||
))}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -4,9 +4,9 @@
|
||||
}
|
||||
|
||||
.tiny {
|
||||
font-size: 0.5em;
|
||||
margin-top: -1.6em;
|
||||
}
|
||||
font-size: 0.5em;
|
||||
margin-top: -1.6em;
|
||||
}
|
||||
|
||||
.small {
|
||||
font-size: 0.8em;
|
||||
@@ -15,4 +15,3 @@
|
||||
.linkOut {
|
||||
margin-inline-end: 0.5em;
|
||||
}
|
||||
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
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)[]
|
||||
icons: (EnrichedEntity | string)[]
|
||||
linkOut: string
|
||||
}>
|
||||
|
||||
@@ -16,21 +15,38 @@ interface Props extends HTMLProps<HTMLDivElement> {
|
||||
node: OverviewGraphNode
|
||||
}
|
||||
|
||||
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 }
|
||||
<h4>Inputs</h4>
|
||||
<div className={styles.small}>
|
||||
{node.inputs.map((input) => <EntityIcon key={input} value={input} />)}
|
||||
</div>
|
||||
{node.outputs.length ? <>
|
||||
<h4>Outputs</h4>
|
||||
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}
|
||||
<h4>Inputs</h4>
|
||||
<div className={styles.small}>
|
||||
{node.outputs.map((input) => <EntityIcon key={input} value={input} />)}
|
||||
{node.inputs.map(input => (
|
||||
<EntityIcon key={input} value={input} />
|
||||
))}
|
||||
</div>
|
||||
</>: null}
|
||||
</div>
|
||||
{node.outputs.length ? (
|
||||
<>
|
||||
<h4>Outputs</h4>
|
||||
<div className={styles.small}>
|
||||
{node.outputs.map(input => (
|
||||
<EntityIcon key={input} value={input} />
|
||||
))}
|
||||
</div>
|
||||
</>
|
||||
) : null}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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)),
|
||||
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 => ({
|
||||
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))
|
||||
.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 =>
|
||||
({
|
||||
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])
|
||||
|
||||
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>
|
||||
|
||||
15
package.json
15
package.json
@@ -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"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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} />
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
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 />
|
||||
<body className={pageProps?.bodyClassName as string}>
|
||||
<Main />
|
||||
<NextScript />
|
||||
<Main />
|
||||
<NextScript />
|
||||
</body>
|
||||
</Html>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
export default MyDocument
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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 })
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -1,23 +1,18 @@
|
||||
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}) => {
|
||||
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/>
|
||||
<Home />
|
||||
</GroupProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,13 +1,12 @@
|
||||
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}) => {
|
||||
const Page: NextPage<PropsGroupProvider> = ({ id, ...initial }) => {
|
||||
return (
|
||||
<GroupProvider id={id} initial={initial}>
|
||||
<PageDetails/>
|
||||
<PageDetails />
|
||||
</GroupProvider>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,36 +1,31 @@
|
||||
import type {NextPage} from 'next'
|
||||
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 Page: NextPage<PropsGroupProvider> = ({ id, ...initial }) => {
|
||||
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,19 +35,19 @@ 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>
|
||||
<h1>Factorio Microservices</h1>
|
||||
<ProducingGraph nodes={producingNodes} inputs={baseFactories} childType={NodeOverview}/>
|
||||
<ProducingGraph nodes={producingNodes} inputs={baseFactories} childType={NodeOverview} />
|
||||
</ScrollContainer>
|
||||
</main>
|
||||
</GroupProvider>
|
||||
|
||||
@@ -3072,4 +3072,4 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
]
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -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()) {
|
||||
let next: string | undefined
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,22 +1,22 @@
|
||||
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
|
||||
}
|
||||
|
||||
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')
|
||||
if (!collection) return
|
||||
const result = await collection.insertOne({
|
||||
@@ -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,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')
|
||||
if (!collection) return false
|
||||
collection.updateOne(getUuid(uuid), {$set: {[type]: factories} as never})
|
||||
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
|
||||
const data = (await collection.findOne(getUuid(uuid))) ?? undefined
|
||||
if (data) {
|
||||
await collection.updateOne(getUuid(uuid), { $set: {accessedOn: new Date()}})
|
||||
await collection.updateOne(getUuid(uuid), { $set: { accessedOn: new Date() } })
|
||||
}
|
||||
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
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
import {Collection, Db, MongoClient} from 'mongodb'
|
||||
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'> & {
|
||||
collection : (_: 'setups') => Collection<InsertMeta<GroupData>>
|
||||
})
|
||||
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)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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: {
|
||||
@@ -22,15 +24,14 @@ export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvi
|
||||
}
|
||||
}
|
||||
} else if (!id) {
|
||||
const newId = await setGroups({groups: {}, base: [], ignored: []})
|
||||
const newId = await setGroups({ groups: {}, base: [], ignored: [] })
|
||||
return {
|
||||
redirect: {
|
||||
destination: `?id=${newId}`,
|
||||
permanent: false,
|
||||
permanent: false
|
||||
}
|
||||
}
|
||||
} else {
|
||||
console.log(data)
|
||||
return {
|
||||
notFound: true
|
||||
}
|
||||
|
||||
@@ -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,78 +73,123 @@ 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)
|
||||
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)
|
||||
for (let j = addedInputs[rowInput] + 1; j < i + 1; j++) {
|
||||
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)
|
||||
res[i+2].push(nodeWithId.___uid)
|
||||
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(
|
||||
rowOutput,
|
||||
'o',
|
||||
nodeUid
|
||||
)
|
||||
res[i + 2].push(nodeWithId.___uid)
|
||||
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]
|
||||
}
|
||||
|
||||
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[]>[]}
|
||||
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 = {
|
||||
input: Array.from(rowsWithInOut, Object),
|
||||
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])
|
||||
};
|
||||
const linkInOut = (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.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))
|
||||
if (rowIdx < rowsWithInOut.length-1)
|
||||
node.___uidOutputs = uniquify(node.outputs.flatMap(output => store.input[rowIdx + 1][output]).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)
|
||||
)
|
||||
}
|
||||
|
||||
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++) {
|
||||
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) => {
|
||||
inputsI.has(curr) && size--
|
||||
return [size, acc + (inputsJ.has(curr) ? size : 0)]
|
||||
}, [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]
|
||||
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) => {
|
||||
inputsJ.has(curr) && size--
|
||||
return [size, acc + (inputsI.has(curr) ? size : 0)]
|
||||
},
|
||||
[inputsJ.size, 0]
|
||||
)[1]
|
||||
result[i][j] = diff
|
||||
result[j][i] = -diff
|
||||
score += diff
|
||||
@@ -136,82 +198,102 @@ 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[0].map((row, rowIdx) => row.map((col, colIdx) => col + costsDown[0][rowIdx][colIdx])),
|
||||
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 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
|
||||
.slice(0, idx)
|
||||
.map(r => r[idx])
|
||||
.reverse()
|
||||
.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]
|
||||
.map(
|
||||
(_, idx) =>
|
||||
costs
|
||||
.slice(0, idx)
|
||||
.map(r => r[idx])
|
||||
.reverse()
|
||||
.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]
|
||||
)
|
||||
.filter(isNonNullable)
|
||||
const rowBest = costs
|
||||
.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]
|
||||
.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]
|
||||
)
|
||||
.filter(isNonNullable)
|
||||
const replacement = [...colBest, ...rowBest].sort(sortByProperty(red => -red.sum))[0]
|
||||
if (replacement.sum > 0) {
|
||||
score -= 2*replacement.sum
|
||||
score -= 2 * replacement.sum
|
||||
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)))
|
||||
mid.splice(replacement.move+replacement.idx, 0, ...mid.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))
|
||||
)
|
||||
mid.splice(replacement.move + replacement.idx, 0, ...mid.splice(replacement.idx, 1))
|
||||
}
|
||||
}
|
||||
return score
|
||||
}
|
||||
|
||||
type Reduce = {sum: number, move: number, idx: number}
|
||||
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) => {
|
||||
scores[idx] = improveRow(top, mid, rowsWithInOut[idx+1])
|
||||
scores[idx] = improveRow(top, mid, rowsWithInOut[idx + 1])
|
||||
return mid
|
||||
}, undefined as string[]|undefined)
|
||||
}, undefined as string[] | undefined)
|
||||
rowsWithInOut.reduceRight((bot, mid, idx) => {
|
||||
scores[idx] = improveRow(rowsWithInOut[idx-1], mid, bot)
|
||||
scores[idx] = improveRow(rowsWithInOut[idx - 1], mid, bot)
|
||||
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 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)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {Dict} from "../types";
|
||||
import { Dict } from '../types'
|
||||
|
||||
interface GraphNodeBase {
|
||||
inputs: string[]
|
||||
@@ -14,7 +14,8 @@ export type GraphNodeWithIds<T extends Dict<unknown>> = GraphNode<T> & {
|
||||
}
|
||||
|
||||
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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,23 +1,23 @@
|
||||
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)
|
||||
)
|
||||
return detail;
|
||||
detail.usedBy = joined.filter(f =>
|
||||
Object.keys(f.recipe?.prerequisites ?? {}).includes(detail.href)
|
||||
)
|
||||
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,
|
||||
findFactory: (uid: string): EnrichedEntity|undefined => {
|
||||
findFactory: (uid: string): EnrichedEntity | undefined => {
|
||||
return detailsMap[uid]
|
||||
}
|
||||
})
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,30 +35,33 @@ 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 => {
|
||||
// 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`,
|
||||
)
|
||||
}
|
||||
const setValue: SetValue<T> = useCallback(
|
||||
value => {
|
||||
// Prevent build error "window is undefined" but keeps working
|
||||
if (typeof window == 'undefined') {
|
||||
console.warn(
|
||||
`Tried setting localStorage key “${key}” even though environment is not a client`
|
||||
)
|
||||
}
|
||||
|
||||
try {
|
||||
// Allow value to be a function so we have the same API as useState
|
||||
const newValue = value instanceof Function ? value(storedValue) : value
|
||||
try {
|
||||
// Allow value to be a function so we have the same API as useState
|
||||
const newValue = value instanceof Function ? value(storedValue) : value
|
||||
|
||||
// Save to local storage
|
||||
window.localStorage.setItem(key, JSON.stringify(newValue))
|
||||
// Save to local storage
|
||||
window.localStorage.setItem(key, JSON.stringify(newValue))
|
||||
|
||||
// Save state
|
||||
setStoredValue(newValue)
|
||||
// Save state
|
||||
setStoredValue(newValue)
|
||||
|
||||
// We dispatch a custom event so every useLocalStorage hook are notified
|
||||
window.dispatchEvent(new Event('local-storage'))
|
||||
} catch (error) {
|
||||
console.warn(`Error setting localStorage key “${key}”:`, error)
|
||||
}
|
||||
}, [key, storedValue])
|
||||
// We dispatch a custom event so every useLocalStorage hook are notified
|
||||
window.dispatchEvent(new Event('local-storage'))
|
||||
} catch (error) {
|
||||
console.warn(`Error setting localStorage key “${key}”:`, error)
|
||||
}
|
||||
},
|
||||
[key, storedValue]
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
setStoredValue(readValue())
|
||||
@@ -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
6
src/next-types.d.ts
vendored
@@ -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
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
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 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 mid = Math.round((start.bottom + end.top) / 2 - container.y)
|
||||
return `M${startX},${startY} C${startX},${mid} ${endX},${mid} ${endX},${endY}`
|
||||
}
|
||||
|
||||
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 bottom = Math.round(elem.bottom - container.y)
|
||||
return `M${x},${top} L${x},${bottom}`
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import {ValidationError} from "jsonschema";
|
||||
import { ValidationError } from 'jsonschema'
|
||||
|
||||
export interface ErrorMessage {
|
||||
message: string // Human readable error message
|
||||
|
||||
10
src/utils.ts
10
src/utils.ts
@@ -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))
|
||||
}
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { ErrorMessage } from '../types/FrontendApi'
|
||||
import {NextApiHandler, NextApiRequest, NextApiResponse} from 'next'
|
||||
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
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
/* eslint-disable no-console */
|
||||
export const logger = {
|
||||
verbose: console.log,
|
||||
debug: console.log,
|
||||
|
||||
@@ -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()
|
||||
|
||||
|
||||
@@ -16,9 +16,9 @@ export function addSchemas() {
|
||||
type: 'object',
|
||||
required: ['type', 'factories'],
|
||||
properties: {
|
||||
type: {type: 'string', enum: ['exports', 'malls']},
|
||||
factories: {type: 'array', items: {type: 'string', minLength: 3}}
|
||||
},
|
||||
type: { type: 'string', enum: ['exports', 'malls'] },
|
||||
factories: { type: 'array', items: { type: 'string', minLength: 3 } }
|
||||
}
|
||||
},
|
||||
{
|
||||
id: 'GroupIdParam',
|
||||
@@ -34,16 +34,16 @@ export function addSchemas() {
|
||||
type: 'object',
|
||||
required: ['type', 'factories'],
|
||||
properties: {
|
||||
type: {type: 'string', enum: ['ignored', 'base']},
|
||||
factories: {type: 'array', items: {type: 'string', minLength: 3}}
|
||||
},
|
||||
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 }
|
||||
}
|
||||
}
|
||||
])
|
||||
|
||||
@@ -1,57 +1,68 @@
|
||||
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;
|
||||
padding: 0;
|
||||
margin: 0;
|
||||
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;
|
||||
padding: 2em;
|
||||
background: #fafafa;
|
||||
color: black;
|
||||
}
|
||||
|
||||
body.scroll {
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
padding: 0;
|
||||
width: 100vw;
|
||||
height: 100vh;
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
a {
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
:is(h1, h2, h3, h4, h5, h6):is(:first-child) {
|
||||
margin-block-start: 0;
|
||||
margin-block-start: 0;
|
||||
}
|
||||
|
||||
h3 {
|
||||
margin-block: 1.5em 1em;
|
||||
margin-block: 1.5em 1em;
|
||||
}
|
||||
|
||||
h4 {
|
||||
margin-block: 1em 0.3em;
|
||||
font-weight: 500;
|
||||
font-weight: 500;
|
||||
margin-block: 1em 0.3em;
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
html {
|
||||
color-scheme: dark;
|
||||
}
|
||||
body {
|
||||
color: white;
|
||||
background: #111;
|
||||
}
|
||||
html {
|
||||
color-scheme: dark;
|
||||
}
|
||||
|
||||
body {
|
||||
background: #111;
|
||||
color: white;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1200px) {
|
||||
body {
|
||||
padding-inline: 0.5em;
|
||||
}
|
||||
body {
|
||||
padding-inline: 0.5em;
|
||||
}
|
||||
}
|
||||
|
||||
12
tsconfig.test.json
Normal file
12
tsconfig.test.json
Normal 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"]
|
||||
}
|
||||
Reference in New Issue
Block a user