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 { createContext, FC, useCallback, useContext, useMemo, useState } from 'react'
|
||||||
import {Group} from "../../src/types";
|
import { Group } from '../../src/types'
|
||||||
import {ReactNodeLike} from "prop-types";
|
import { ReactNodeLike } from 'prop-types'
|
||||||
import pako from "pako";
|
import pako from 'pako'
|
||||||
import {Dict} from "../../src/types";
|
import { Dict } from '../../src/types'
|
||||||
import {fixedEncodeURIComponent} from "../../src/utils";
|
import { fixedEncodeURIComponent } from '../../src/utils'
|
||||||
import {GroupRenameBody, GroupSetFactoryArrayBody, SetFactoryArrayBody} from "../../src/types/ApiSchemasFrontend";
|
import {
|
||||||
|
GroupRenameBody,
|
||||||
|
GroupSetFactoryArrayBody,
|
||||||
|
SetFactoryArrayBody
|
||||||
|
} from '../../src/types/ApiSchemasFrontend'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
children: ReactNodeLike
|
children: ReactNodeLike
|
||||||
@@ -31,8 +35,8 @@ interface GroupContextType {
|
|||||||
removeGroup(name: string): void
|
removeGroup(name: string): void
|
||||||
renameGroup(name: string, newName: string): void
|
renameGroup(name: string, newName: string): void
|
||||||
|
|
||||||
setFactories(name: string, factories: string[], type: 'exports'|'malls'): void
|
setFactories(name: string, factories: string[], type: 'exports' | 'malls'): void
|
||||||
getInputType(uid: string): 'base'|'produced'|'unknown'
|
getInputType(uid: string): 'base' | 'produced' | 'unknown'
|
||||||
|
|
||||||
store(): Uint8Array
|
store(): Uint8Array
|
||||||
load(str: Uint8Array): void
|
load(str: Uint8Array): void
|
||||||
@@ -43,29 +47,47 @@ const defaultValues: GroupContextType = {
|
|||||||
exportedFactories: new Set(),
|
exportedFactories: new Set(),
|
||||||
|
|
||||||
ignoredFactories: [],
|
ignoredFactories: [],
|
||||||
setIgnoredFactories() {},
|
setIgnoredFactories() {
|
||||||
|
return
|
||||||
|
},
|
||||||
|
|
||||||
baseFactories: [],
|
baseFactories: [],
|
||||||
setBaseFactories() {},
|
setBaseFactories() {
|
||||||
|
return
|
||||||
|
},
|
||||||
|
|
||||||
groups: {},
|
groups: {},
|
||||||
addGroup() {},
|
addGroup() {
|
||||||
removeGroup() {},
|
return
|
||||||
renameGroup() {},
|
},
|
||||||
|
removeGroup() {
|
||||||
|
return
|
||||||
|
},
|
||||||
|
renameGroup() {
|
||||||
|
return
|
||||||
|
},
|
||||||
|
|
||||||
setFactories() {},
|
setFactories() {
|
||||||
getInputType() {return 'unknown'},
|
return
|
||||||
|
},
|
||||||
|
getInputType() {
|
||||||
|
return 'unknown'
|
||||||
|
},
|
||||||
|
|
||||||
store() {return new Uint8Array(0)},
|
store() {
|
||||||
load() {}
|
return new Uint8Array(0)
|
||||||
|
},
|
||||||
|
load() {
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const GroupContext = createContext<GroupContextType>(defaultValues);
|
const GroupContext = createContext<GroupContextType>(defaultValues)
|
||||||
export const useGroups = () => useContext(GroupContext)
|
export const useGroups = () => useContext(GroupContext)
|
||||||
|
|
||||||
interface StoredFile {
|
interface StoredFile {
|
||||||
groups: Dict<Group>,
|
groups: Dict<Group>
|
||||||
basicValues: string[],
|
basicValues: string[]
|
||||||
excludedSuggestions: string[]
|
excludedSuggestions: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -80,124 +102,167 @@ export const postFetchJson = async (url: string, body: Dict<unknown>) => {
|
|||||||
return res.json()
|
return res.json()
|
||||||
}
|
}
|
||||||
|
|
||||||
export const GroupProvider: FC<Props> = ({children, id, initial}) => {
|
export const GroupProvider: FC<Props> = ({ children, id, initial }) => {
|
||||||
const [excludedSuggestions, _setExcludedSuggestions] = useState<string[]>(initial.ignored)
|
const [excludedSuggestions, _setExcludedSuggestions] = useState<string[]>(initial.ignored)
|
||||||
const [basicValues, _setBasicValues] = useState<string[]>(initial.base)
|
const [basicValues, _setBasicValues] = useState<string[]>(initial.base)
|
||||||
const [groups, setGroups] = useState<Dict<Group>>(initial.groups)
|
const [groups, setGroups] = useState<Dict<Group>>(initial.groups)
|
||||||
|
|
||||||
const doNotSuggest = useMemo<Set<string>>(() => {
|
const doNotSuggest = useMemo<Set<string>>(() => {
|
||||||
return new Set([...Object.values(groups).flatMap(group => [...group.exports, ...group.malls]), ...excludedSuggestions, ...basicValues])
|
return new Set([
|
||||||
|
...Object.values(groups).flatMap(group => [...group.exports, ...group.malls]),
|
||||||
|
...excludedSuggestions,
|
||||||
|
...basicValues
|
||||||
|
])
|
||||||
}, [basicValues, groups, excludedSuggestions])
|
}, [basicValues, groups, excludedSuggestions])
|
||||||
|
|
||||||
const exportedFactories = useMemo<Set<string>>(() => {
|
const exportedFactories = useMemo<Set<string>>(() => {
|
||||||
return new Set([...Object.values(groups).flatMap(group => [...group.exports])])
|
return new Set([...Object.values(groups).flatMap(group => [...group.exports])])
|
||||||
}, [groups])
|
}, [groups])
|
||||||
|
|
||||||
const setExcludedSuggestions = useCallback<typeof _setExcludedSuggestions>((val) => {
|
const setExcludedSuggestions = useCallback<typeof _setExcludedSuggestions>(
|
||||||
|
val => {
|
||||||
_setExcludedSuggestions(val)
|
_setExcludedSuggestions(val)
|
||||||
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, {
|
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, {
|
||||||
type: 'ignored',
|
type: 'ignored',
|
||||||
factories: val
|
factories: val
|
||||||
} as SetFactoryArrayBody)
|
} as SetFactoryArrayBody).catch(console.error)
|
||||||
.catch(console.error)
|
},
|
||||||
}, [id])
|
[id]
|
||||||
|
)
|
||||||
|
|
||||||
const setBasicValues = useCallback<typeof _setBasicValues>((val) => {
|
const setBasicValues = useCallback<typeof _setBasicValues>(
|
||||||
|
val => {
|
||||||
_setBasicValues(val)
|
_setBasicValues(val)
|
||||||
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, {
|
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/factories`, {
|
||||||
type: 'base',
|
type: 'base',
|
||||||
factories: val
|
factories: val
|
||||||
} as SetFactoryArrayBody)
|
} as SetFactoryArrayBody).catch(console.error)
|
||||||
.catch(console.error)
|
},
|
||||||
}, [id])
|
[id]
|
||||||
|
)
|
||||||
|
|
||||||
const addGroup = useCallback((name: string, exports: string[] = [], malls: string[] = []) => {
|
const addGroup = useCallback(
|
||||||
|
(name: string, exports: string[] = [], malls: string[] = []) => {
|
||||||
name = name.replace(/[.$]/g, '')
|
name = name.replace(/[.$]/g, '')
|
||||||
if (name in groups) return false
|
if (name in groups) return false
|
||||||
setGroups(groups => {
|
setGroups(g => {
|
||||||
groups[name] = { name, exports, malls }
|
g[name] = { name, exports, malls }
|
||||||
return {...groups}
|
return { ...g }
|
||||||
})
|
})
|
||||||
;(async () => {
|
;(async () => {
|
||||||
await postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/add`, {})
|
await postFetchJson(
|
||||||
|
`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/add`,
|
||||||
|
{}
|
||||||
|
)
|
||||||
if (exports.length) {
|
if (exports.length) {
|
||||||
await postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`, {
|
await postFetchJson(
|
||||||
|
`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`,
|
||||||
|
{
|
||||||
type: 'exports',
|
type: 'exports',
|
||||||
factories: exports
|
factories: exports
|
||||||
} as GroupSetFactoryArrayBody)
|
} as GroupSetFactoryArrayBody
|
||||||
|
)
|
||||||
}
|
}
|
||||||
if (malls.length) {
|
if (malls.length) {
|
||||||
await postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`, {
|
await postFetchJson(
|
||||||
|
`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`,
|
||||||
|
{
|
||||||
type: 'malls',
|
type: 'malls',
|
||||||
factories: exports
|
factories: exports
|
||||||
} as GroupSetFactoryArrayBody)
|
} as GroupSetFactoryArrayBody
|
||||||
|
)
|
||||||
}
|
}
|
||||||
})().catch(console.error)
|
})().catch(console.error)
|
||||||
return true
|
return true
|
||||||
}, [groups, id])
|
},
|
||||||
const removeGroup = useCallback((name: string) => {
|
[groups, id]
|
||||||
|
)
|
||||||
|
const removeGroup = useCallback(
|
||||||
|
(name: string) => {
|
||||||
name = name.replace(/[.$]/g, '')
|
name = name.replace(/[.$]/g, '')
|
||||||
setGroups(groups => {
|
setGroups(g => {
|
||||||
delete groups[name]
|
delete g[name]
|
||||||
console.log(groups[name])
|
return { ...g }
|
||||||
return {...groups}
|
|
||||||
})
|
})
|
||||||
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/remove`, {})
|
postFetchJson(
|
||||||
.catch(console.error)
|
`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/remove`,
|
||||||
}, [id])
|
{}
|
||||||
const renameGroup = useCallback((name: string, newName: string) => {
|
).catch(console.error)
|
||||||
|
},
|
||||||
|
[id]
|
||||||
|
)
|
||||||
|
const renameGroup = useCallback(
|
||||||
|
(name: string, newName: string) => {
|
||||||
name = name.replace(/[.$]/g, '')
|
name = name.replace(/[.$]/g, '')
|
||||||
newName = newName.replace(/[.$]/g, '')
|
newName = newName.replace(/[.$]/g, '')
|
||||||
if (newName in groups) return
|
if (newName in groups) return
|
||||||
setGroups(groups => {
|
setGroups(g => {
|
||||||
groups[newName] = {...groups[name], name: newName}
|
g[newName] = { ...g[name], name: newName }
|
||||||
delete groups[name]
|
delete g[name]
|
||||||
return {...groups}
|
return { ...g }
|
||||||
})
|
})
|
||||||
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/rename`, {
|
postFetchJson(
|
||||||
|
`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/rename`,
|
||||||
|
{
|
||||||
newName
|
newName
|
||||||
} as GroupRenameBody)
|
} as GroupRenameBody
|
||||||
.catch(console.error)
|
).catch(console.error)
|
||||||
}, [groups, id])
|
},
|
||||||
|
[groups, id]
|
||||||
|
)
|
||||||
|
|
||||||
const setFactories = useCallback((name: string, factories: string[], type: 'exports'|'malls') => {
|
const setFactories = useCallback(
|
||||||
|
(name: string, factories: string[], type: 'exports' | 'malls') => {
|
||||||
name = name.replace(/[.$]/g, '')
|
name = name.replace(/[.$]/g, '')
|
||||||
setGroups(groups => {
|
setGroups(g => {
|
||||||
groups[name] = {...groups[name], [type]: factories}
|
g[name] = { ...g[name], [type]: factories }
|
||||||
return {...groups}
|
return { ...g }
|
||||||
})
|
})
|
||||||
postFetchJson(`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`, {
|
postFetchJson(
|
||||||
|
`/api/${fixedEncodeURIComponent(id)}/group/${fixedEncodeURIComponent(name)}/factories`,
|
||||||
|
{
|
||||||
type,
|
type,
|
||||||
factories
|
factories
|
||||||
} as GroupSetFactoryArrayBody)
|
} as GroupSetFactoryArrayBody
|
||||||
.catch(console.error)
|
).catch(console.error)
|
||||||
}, [id])
|
},
|
||||||
const getInputType = useCallback((uid: string) => {
|
[id]
|
||||||
|
)
|
||||||
|
const getInputType = useCallback(
|
||||||
|
(uid: string) => {
|
||||||
if (basicValues.includes(uid)) return 'base'
|
if (basicValues.includes(uid)) return 'base'
|
||||||
else if (exportedFactories.has(uid)) return 'produced'
|
else if (exportedFactories.has(uid)) return 'produced'
|
||||||
else return 'unknown'
|
else return 'unknown'
|
||||||
}, [basicValues, exportedFactories])
|
},
|
||||||
|
[basicValues, exportedFactories]
|
||||||
|
)
|
||||||
|
|
||||||
const store = useCallback(() => {
|
const store = useCallback(() => {
|
||||||
const btoa = (bin: Uint8Array) => Buffer.from(bin).toString('base64')
|
// const btoa = (bin: Uint8Array) => Buffer.from(bin).toString('base64')
|
||||||
const value: StoredFile = {
|
const value: StoredFile = {
|
||||||
groups, basicValues, excludedSuggestions
|
groups,
|
||||||
|
basicValues,
|
||||||
|
excludedSuggestions
|
||||||
}
|
}
|
||||||
const uncompressed = JSON.stringify(value)
|
const uncompressed = JSON.stringify(value)
|
||||||
return pako.deflate(uncompressed)
|
return pako.deflate(uncompressed)
|
||||||
}, [basicValues, excludedSuggestions, groups])
|
}, [basicValues, excludedSuggestions, groups])
|
||||||
|
|
||||||
const load = useCallback((compressed: Uint8Array) => {
|
const load = useCallback(
|
||||||
const atob = (str: string) => Buffer.from(str, 'base64')
|
(compressed: Uint8Array) => {
|
||||||
const uncompressed = pako.inflate(compressed, {to: "string"})
|
// const atob = (str: string) => Buffer.from(str, 'base64')
|
||||||
|
const uncompressed = pako.inflate(compressed, { to: 'string' })
|
||||||
const value: StoredFile = JSON.parse(uncompressed)
|
const value: StoredFile = JSON.parse(uncompressed)
|
||||||
if (!value.groups || !value.basicValues || !value.excludedSuggestions) return
|
if (!value.groups || !value.basicValues || !value.excludedSuggestions) return
|
||||||
setGroups(value.groups)
|
setGroups(value.groups)
|
||||||
setBasicValues(value.basicValues)
|
setBasicValues(value.basicValues)
|
||||||
setExcludedSuggestions(value.excludedSuggestions)
|
setExcludedSuggestions(value.excludedSuggestions)
|
||||||
}, [])
|
},
|
||||||
|
[setBasicValues, setExcludedSuggestions]
|
||||||
|
)
|
||||||
|
|
||||||
const value: GroupContextType = useMemo(() => ({
|
const value: GroupContextType = useMemo(
|
||||||
|
() => ({
|
||||||
doNotSuggest,
|
doNotSuggest,
|
||||||
exportedFactories,
|
exportedFactories,
|
||||||
|
|
||||||
@@ -217,6 +282,23 @@ export const GroupProvider: FC<Props> = ({children, id, initial}) => {
|
|||||||
|
|
||||||
store,
|
store,
|
||||||
load
|
load
|
||||||
}), [addGroup, basicValues, doNotSuggest, excludedSuggestions, exportedFactories, getInputType, groups, load, removeGroup, renameGroup, setBasicValues, setExcludedSuggestions, setFactories, store])
|
}),
|
||||||
|
[
|
||||||
|
addGroup,
|
||||||
|
basicValues,
|
||||||
|
doNotSuggest,
|
||||||
|
excludedSuggestions,
|
||||||
|
exportedFactories,
|
||||||
|
getInputType,
|
||||||
|
groups,
|
||||||
|
load,
|
||||||
|
removeGroup,
|
||||||
|
renameGroup,
|
||||||
|
setBasicValues,
|
||||||
|
setExcludedSuggestions,
|
||||||
|
setFactories,
|
||||||
|
store
|
||||||
|
]
|
||||||
|
)
|
||||||
return <GroupContext.Provider value={value}>{children}</GroupContext.Provider>
|
return <GroupContext.Provider value={value}>{children}</GroupContext.Provider>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
.span {
|
.span {
|
||||||
background: #DDD;
|
background: #ddd;
|
||||||
font-size: 2em;
|
font-size: 2em;
|
||||||
border: 1px solid white;
|
border: 1px solid white;
|
||||||
display: inline-block;
|
display: inline-block;
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
import {FC, HTMLProps, useMemo} from "react"
|
import { FC, HTMLProps, useMemo } from 'react'
|
||||||
import {Entity} from "../../../src/types"
|
import { Entity } from '../../../src/types'
|
||||||
import {useFactories} from "../../../src/hooks/useFactories"
|
import { useFactories } from '../../../src/hooks/useFactories'
|
||||||
import styles from './EntityIcon.module.css'
|
import styles from './EntityIcon.module.css'
|
||||||
import cx from "classnames";
|
import cx from 'classnames'
|
||||||
|
|
||||||
interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> {
|
interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> {
|
||||||
value: Entity|string
|
value: Entity | string
|
||||||
amount?: number
|
amount?: number
|
||||||
}
|
}
|
||||||
|
|
||||||
export const EntityIcon: FC<Props> = ({className, value, amount, ...rest}) => {
|
export const EntityIcon: FC<Props> = ({ className, value, amount, ...rest }) => {
|
||||||
const {findFactory} = useFactories()
|
const { findFactory } = useFactories()
|
||||||
const entity = useMemo<Entity>(() => {
|
const entity = useMemo<Entity>(() => {
|
||||||
return typeof value === "object"
|
return typeof value === 'object'
|
||||||
? value
|
? value
|
||||||
: value === '/Time'
|
: value === '/Time'
|
||||||
? {
|
? {
|
||||||
@@ -29,9 +29,15 @@ export const EntityIcon: FC<Props> = ({className, value, amount, ...rest}) => {
|
|||||||
}
|
}
|
||||||
}, [findFactory, value])
|
}, [findFactory, value])
|
||||||
|
|
||||||
return <span {...rest} className={cx(className, styles.span)} title={entity.name}>
|
return (
|
||||||
|
<span {...rest} className={cx(className, styles.span)} title={entity.name}>
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img className={cx(styles.img, amount === undefined ? styles.noAmount : undefined)} src={`https://wiki.factorio.com${entity.image}`} alt={entity.name}/>
|
<img
|
||||||
|
className={cx(styles.img, amount === undefined ? styles.noAmount : undefined)}
|
||||||
|
src={`https://wiki.factorio.com${entity.image}`}
|
||||||
|
alt={entity.name}
|
||||||
|
/>
|
||||||
{amount !== undefined && <span className={styles.amount}>{amount}</span>}
|
{amount !== undefined && <span className={styles.amount}>{amount}</span>}
|
||||||
</span>
|
</span>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,33 @@
|
|||||||
import {FC, HTMLProps, memo, useMemo} from "react"
|
import { FC, HTMLProps, memo, useMemo } from 'react'
|
||||||
import {EnrichedEntity, Entity} from "../../../src/types"
|
import { EnrichedEntity } from '../../../src/types'
|
||||||
import {useFactories} from "../../../src/hooks/useFactories"
|
import { useFactories } from '../../../src/hooks/useFactories'
|
||||||
import styles from './EntitySpan.module.css'
|
import styles from './EntitySpan.module.css'
|
||||||
import {RecipeSpan} from "../Recipe/Recipe";
|
import { RecipeSpan } from '../Recipe/Recipe'
|
||||||
import {LeftClickIcon} from "../LeftClickIcon/LeftClickIcon";
|
import { LeftClickIcon } from '../LeftClickIcon/LeftClickIcon'
|
||||||
import cx from 'classnames';
|
import cx from 'classnames'
|
||||||
import {EntityIcon} from "../EntityIcon/EntityIcon";
|
import { EntityIcon } from '../EntityIcon/EntityIcon'
|
||||||
|
|
||||||
interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> {
|
interface Props extends Omit<HTMLProps<HTMLSpanElement>, 'value'> {
|
||||||
value: EnrichedEntity|string
|
value: EnrichedEntity | string
|
||||||
state?: 'base'|'produced'|'unknown'
|
state?: 'base' | 'produced' | 'unknown'
|
||||||
leftClickText?: string
|
leftClickText?: string
|
||||||
rightClickText?: string
|
rightClickText?: string
|
||||||
simpleStyle?: boolean
|
simpleStyle?: boolean
|
||||||
className?: string
|
className?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
const EntitySpanUnmemo: FC<Props> = ({className, value, state, leftClickText, rightClickText, simpleStyle, ...rest}) => {
|
const EntitySpanUnmemo: FC<Props> = ({
|
||||||
const {findFactory} = useFactories()
|
className,
|
||||||
|
value,
|
||||||
|
state,
|
||||||
|
leftClickText,
|
||||||
|
rightClickText,
|
||||||
|
simpleStyle,
|
||||||
|
...rest
|
||||||
|
}) => {
|
||||||
|
const { findFactory } = useFactories()
|
||||||
const entity = useMemo<EnrichedEntity>(() => {
|
const entity = useMemo<EnrichedEntity>(() => {
|
||||||
return typeof value === "object"
|
return typeof value === 'object'
|
||||||
? value
|
? value
|
||||||
: findFactory(value) ?? {
|
: findFactory(value) ?? {
|
||||||
usedBy: [],
|
usedBy: [],
|
||||||
@@ -30,34 +38,52 @@ const EntitySpanUnmemo: FC<Props> = ({className, value, state, leftClickText, ri
|
|||||||
}
|
}
|
||||||
}, [findFactory, value])
|
}, [findFactory, value])
|
||||||
|
|
||||||
return <span className={cx(className, simpleStyle ? styles.spanSimple : styles.span)} {...rest}>
|
return (
|
||||||
|
<span className={cx(className, simpleStyle ? styles.spanSimple : styles.span)} {...rest}>
|
||||||
{/* eslint-disable-next-line @next/next/no-img-element */}
|
{/* eslint-disable-next-line @next/next/no-img-element */}
|
||||||
<img className={styles.img} src={`https://wiki.factorio.com${entity.image}`} alt={entity.name}/>
|
<img
|
||||||
|
className={styles.img}
|
||||||
|
src={`https://wiki.factorio.com${entity.image}`}
|
||||||
|
alt={entity.name}
|
||||||
|
/>
|
||||||
<span className={styles[state ?? 'unknown']}>{entity.name}</span>
|
<span className={styles[state ?? 'unknown']}>{entity.name}</span>
|
||||||
<div className={styles.tooltip}>
|
<div className={styles.tooltip}>
|
||||||
{entity.recipe && (
|
{entity.recipe && (
|
||||||
<>
|
<>
|
||||||
<div className={styles.strong}>Recipe</div>
|
<div className={styles.strong}>Recipe</div>
|
||||||
<RecipeSpan recipe={entity.recipe}/>
|
<RecipeSpan recipe={entity.recipe} />
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
{entity.usedBy?.length ? (
|
{entity.usedBy?.length ? (
|
||||||
<>
|
<>
|
||||||
<div className={styles.strong}>Used By</div>
|
<div className={styles.strong}>Used By</div>
|
||||||
<div className={styles.usedBy}>
|
<div className={styles.usedBy}>
|
||||||
{entity.usedBy.map(used => <EntityIcon value={used} key={used.name}/>)}
|
{entity.usedBy.map(used => (
|
||||||
|
<EntityIcon value={used} key={used.name} />
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
) : null}
|
) : null}
|
||||||
{(leftClickText || rightClickText) && (
|
{(leftClickText || rightClickText) && (
|
||||||
<>
|
<>
|
||||||
<div className={styles.strong}>Actions</div>
|
<div className={styles.strong}>Actions</div>
|
||||||
{leftClickText && <div><LeftClickIcon className={styles.leftClick} classClick={styles.clickBtn}/> {leftClickText}</div>}
|
{leftClickText && (
|
||||||
{rightClickText && <div><LeftClickIcon className={styles.rightClick} classClick={styles.clickBtn}/> {rightClickText}</div>}
|
<div>
|
||||||
|
<LeftClickIcon className={styles.leftClick} classClick={styles.clickBtn} />{' '}
|
||||||
|
{leftClickText}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
{rightClickText && (
|
||||||
|
<div>
|
||||||
|
<LeftClickIcon className={styles.rightClick} classClick={styles.clickBtn} />{' '}
|
||||||
|
{rightClickText}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</span>
|
</span>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const EntitySpan = memo(EntitySpanUnmemo)
|
export const EntitySpan = memo(EntitySpanUnmemo)
|
||||||
|
|||||||
@@ -4,8 +4,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.select :global(.factory-select__multi-value),
|
.select :global(.factory-select__multi-value),
|
||||||
.select :global(.factory-select__menu)
|
.select :global(.factory-select__menu) {
|
||||||
{
|
|
||||||
background-color: #444;
|
background-color: #444;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -18,6 +17,6 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.select :global(.factory-select__multi-value__label) {
|
.select :global(.factory-select__multi-value__label) {
|
||||||
color: #DDDDDD;
|
color: #dddddd;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import {FC, memo, useEffect, useMemo, useState} from "react";
|
import { FC, memo, useMemo } from 'react'
|
||||||
import Select from "react-select";
|
import Select from 'react-select'
|
||||||
import {isNonNullable} from "../../../src/utils";
|
import { isNonNullable } from '../../../src/utils'
|
||||||
import details from "../../../res/details.json";
|
import details from '../../../res/details.json'
|
||||||
import styles from "./FactorySelect.module.css";
|
import styles from './FactorySelect.module.css'
|
||||||
import {EntitySpan} from "../EntitySpan/EntitySpan";
|
import { EntitySpan } from '../EntitySpan/EntitySpan'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
id: string
|
id: string
|
||||||
@@ -16,23 +16,26 @@ const options = details.map(detail => ({
|
|||||||
value: detail.href
|
value: detail.href
|
||||||
}))
|
}))
|
||||||
|
|
||||||
const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => {
|
const FactorySelectBase: FC<Props> = ({ id, factories, onSetFactories }) => {
|
||||||
const state = useMemo<typeof options>(() => {
|
const state = useMemo<typeof options>(() => {
|
||||||
return factories
|
return factories
|
||||||
.map(factory => options.find(option => option.value === factory))
|
.map(factory => options.find(option => option.value === factory))
|
||||||
.filter(isNonNullable)
|
.filter(isNonNullable)
|
||||||
}, [factories])
|
}, [factories])
|
||||||
|
|
||||||
return <Select
|
return (
|
||||||
|
<Select
|
||||||
id={id}
|
id={id}
|
||||||
instanceId={id}
|
instanceId={id}
|
||||||
value={state}
|
value={state}
|
||||||
components={{
|
components={{
|
||||||
MultiValueLabel: ({data, innerProps}) => (
|
MultiValueLabel: ({ data, innerProps }) => (
|
||||||
<EntitySpan {...innerProps} value={data.value} simpleStyle={true}/>
|
<EntitySpan {...innerProps} value={data.value} simpleStyle={true} />
|
||||||
),
|
),
|
||||||
Option: ({innerProps, data}) => (
|
Option: ({ innerProps, data }) => (
|
||||||
<div {...innerProps} className={styles.option}><EntitySpan value={data.value} simpleStyle={true}/></div>
|
<div {...innerProps} className={styles.option}>
|
||||||
|
<EntitySpan value={data.value} simpleStyle={true} />
|
||||||
|
</div>
|
||||||
)
|
)
|
||||||
}}
|
}}
|
||||||
isMulti
|
isMulti
|
||||||
@@ -41,8 +44,9 @@ const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => {
|
|||||||
onSetFactories(e.map(s => s?.value))
|
onSetFactories(e.map(s => s?.value))
|
||||||
}}
|
}}
|
||||||
className={styles.select}
|
className={styles.select}
|
||||||
classNamePrefix={"factory-select"}
|
classNamePrefix={'factory-select'}
|
||||||
/>
|
/>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const FactorySelect = memo(FactorySelectBase)
|
export const FactorySelect = memo(FactorySelectBase)
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
import {FC, memo, useCallback, useMemo, useState} from "react";
|
import { FC, memo, useCallback, useMemo, useState } from 'react'
|
||||||
import {FactorySelect} from "../FactorySelect/FactorySelect";
|
import { FactorySelect } from '../FactorySelect/FactorySelect'
|
||||||
import {useFactories} from "../../../src/hooks/useFactories";
|
import { useFactories } from '../../../src/hooks/useFactories'
|
||||||
import {EnrichedEntity, Group} from "../../../src/types";
|
import { EnrichedEntity, Group } from '../../../src/types'
|
||||||
import styles from "./GroupBox.module.css"
|
import styles from './GroupBox.module.css'
|
||||||
import {EntitySpan} from "../EntitySpan/EntitySpan";
|
import { EntitySpan } from '../EntitySpan/EntitySpan'
|
||||||
import {useGroups} from "../../contexts/GroupProvider";
|
import { useGroups } from '../../contexts/GroupProvider'
|
||||||
import {calculateInputs} from "../../../src/calculateInputs";
|
import { calculateInputs } from '../../../src/calculateInputs'
|
||||||
import {fixedEncodeURIComponent, uniquify} from "../../../src/utils";
|
import { fixedEncodeURIComponent, uniquify } from '../../../src/utils'
|
||||||
import Link from "next/link";
|
import Link from 'next/link'
|
||||||
import {useRouter} from "next/router";
|
import { useRouter } from 'next/router'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
group: Group
|
group: Group
|
||||||
@@ -16,7 +16,7 @@ interface Props {
|
|||||||
|
|
||||||
const GroupBoxBase: FC<Props> = ({ group }) => {
|
const GroupBoxBase: FC<Props> = ({ group }) => {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const {factories, findFactory} = useFactories()
|
const { factories, findFactory } = useFactories()
|
||||||
const {
|
const {
|
||||||
doNotSuggest,
|
doNotSuggest,
|
||||||
setFactories,
|
setFactories,
|
||||||
@@ -28,24 +28,14 @@ const GroupBoxBase: FC<Props> = ({ group }) => {
|
|||||||
removeGroup,
|
removeGroup,
|
||||||
getInputType
|
getInputType
|
||||||
} = useGroups()
|
} = useGroups()
|
||||||
const {
|
const { name, exports, malls } = group
|
||||||
name,
|
|
||||||
exports,
|
|
||||||
malls
|
|
||||||
} = group
|
|
||||||
|
|
||||||
const [isDeleteConfirm, setDeleteConfirm] = useState(false)
|
const [isDeleteConfirm, setDeleteConfirm] = useState(false)
|
||||||
|
|
||||||
const [inputs, intermediates] = useMemo(() => {
|
const [inputs, intermediates] = useMemo(() => {
|
||||||
const allProducingFactories = [...exports, ...malls]
|
const allProducingFactories = [...exports, ...malls]
|
||||||
return calculateInputs(
|
return calculateInputs(allProducingFactories, baseFactories, exportedFactories, findFactory)
|
||||||
allProducingFactories,
|
}, [exports, malls, baseFactories, findFactory, exportedFactories])
|
||||||
ignoredFactories,
|
|
||||||
baseFactories,
|
|
||||||
exportedFactories,
|
|
||||||
findFactory
|
|
||||||
)
|
|
||||||
}, [exports, malls, ignoredFactories, baseFactories, findFactory, exportedFactories])
|
|
||||||
|
|
||||||
const [suggestionsExport, suggestionMall] = useMemo<[EnrichedEntity[], EnrichedEntity[]]>(() => {
|
const [suggestionsExport, suggestionMall] = useMemo<[EnrichedEntity[], EnrichedEntity[]]>(() => {
|
||||||
const selectedValues = uniquify([...exports, ...malls])
|
const selectedValues = uniquify([...exports, ...malls])
|
||||||
@@ -58,7 +48,8 @@ const GroupBoxBase: FC<Props> = ({ group }) => {
|
|||||||
const prerequisites = Object.keys(factory.recipe.prerequisites ?? {})
|
const prerequisites = Object.keys(factory.recipe.prerequisites ?? {})
|
||||||
return prerequisites.every(pre => availableIngredients.includes(pre))
|
return prerequisites.every(pre => availableIngredients.includes(pre))
|
||||||
})
|
})
|
||||||
.reduce((acc, factory) =>
|
.reduce(
|
||||||
|
(acc, factory) =>
|
||||||
(factory.usedBy?.length ?? 0) >= 3
|
(factory.usedBy?.length ?? 0) >= 3
|
||||||
? [[...acc[0], factory], acc[1]]
|
? [[...acc[0], factory], acc[1]]
|
||||||
: [acc[0], [...acc[1], factory]],
|
: [acc[0], [...acc[1], factory]],
|
||||||
@@ -66,48 +57,64 @@ const GroupBoxBase: FC<Props> = ({ group }) => {
|
|||||||
)
|
)
|
||||||
}, [exports, malls, intermediates, inputs, factories, doNotSuggest])
|
}, [exports, malls, intermediates, inputs, factories, doNotSuggest])
|
||||||
|
|
||||||
const addFactory = useCallback((uid: string, type: Parameters<typeof setFactories>[2]) => {
|
const addFactory = useCallback(
|
||||||
|
(uid: string, type: Parameters<typeof setFactories>[2]) => {
|
||||||
setFactories(name, [...group[type], uid], type)
|
setFactories(name, [...group[type], uid], type)
|
||||||
}, [group, name, setFactories])
|
},
|
||||||
|
[group, name, setFactories]
|
||||||
|
)
|
||||||
|
|
||||||
const setExportFactories = useCallback((factories: string[]) => setFactories(name, factories, 'exports'), [setFactories, name])
|
const setExportFactories = useCallback(
|
||||||
const setMallFactories = useCallback((factories: string[]) => setFactories(name, factories, 'malls'), [setFactories, name])
|
(exportFactories: string[]) => setFactories(name, exportFactories, 'exports'),
|
||||||
|
[setFactories, name]
|
||||||
|
)
|
||||||
|
const setMallFactories = useCallback(
|
||||||
|
(mallFactories: string[]) => setFactories(name, mallFactories, 'malls'),
|
||||||
|
[setFactories, name]
|
||||||
|
)
|
||||||
|
|
||||||
return <div className={styles.root}>
|
return (
|
||||||
|
<div className={styles.root}>
|
||||||
<h3
|
<h3
|
||||||
contentEditable={true}
|
contentEditable={true}
|
||||||
suppressContentEditableWarning={true}
|
suppressContentEditableWarning={true}
|
||||||
onBlur={event => {
|
onBlur={event => {
|
||||||
event.currentTarget.innerText = event.currentTarget.innerText.trim()
|
event.currentTarget.innerText = event.currentTarget.innerText.trim()
|
||||||
renameGroup(name, event.currentTarget.innerText);
|
renameGroup(name, event.currentTarget.innerText)
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
{name}
|
{name}
|
||||||
</h3>
|
</h3>
|
||||||
<Link href={{pathname: `/visualize/${fixedEncodeURIComponent(group.name)}`, query: router.query}}>👁</Link>
|
<Link
|
||||||
|
href={{
|
||||||
|
pathname: `/visualize/${fixedEncodeURIComponent(group.name)}`,
|
||||||
|
query: router.query
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
👁
|
||||||
|
</Link>
|
||||||
<button
|
<button
|
||||||
className={styles.quit}
|
className={styles.quit}
|
||||||
onBlur={() => setDeleteConfirm(false)}
|
onBlur={() => setDeleteConfirm(false)}
|
||||||
onClick={() => !isDeleteConfirm ? setDeleteConfirm(true) : removeGroup(name)} style={{display: 'block'}}
|
onClick={() => (!isDeleteConfirm ? setDeleteConfirm(true) : removeGroup(name))}
|
||||||
|
style={{ display: 'block' }}
|
||||||
>
|
>
|
||||||
{isDeleteConfirm ? 'Delete GroupBox?' : 'X'}
|
{isDeleteConfirm ? 'Delete GroupBox?' : 'X'}
|
||||||
</button>
|
</button>
|
||||||
<h4>Exported Factories</h4>
|
<h4>Exported Factories</h4>
|
||||||
<FactorySelect
|
<FactorySelect
|
||||||
id={name+"-exports"}
|
id={name + '-exports'}
|
||||||
factories={exports}
|
factories={exports}
|
||||||
onSetFactories={setExportFactories}
|
onSetFactories={setExportFactories}
|
||||||
/>
|
/>
|
||||||
<h4>Mall Factories</h4>
|
<h4>Mall Factories</h4>
|
||||||
<FactorySelect
|
<FactorySelect id={name + '-malls'} factories={malls} onSetFactories={setMallFactories} />
|
||||||
id={name+"-malls"}
|
{inputs.length ? (
|
||||||
factories={malls}
|
<>
|
||||||
onSetFactories={setMallFactories}
|
|
||||||
/>
|
|
||||||
{ inputs.length ? <>
|
|
||||||
<h4>Input Factories ({inputs.length})</h4>
|
<h4>Input Factories ({inputs.length})</h4>
|
||||||
<div className={styles.flex}>
|
<div className={styles.flex}>
|
||||||
{ inputs.map(input => <EntitySpan
|
{inputs.map(input => (
|
||||||
|
<EntitySpan
|
||||||
key={input}
|
key={input}
|
||||||
value={input}
|
value={input}
|
||||||
state={getInputType(input)}
|
state={getInputType(input)}
|
||||||
@@ -115,24 +122,32 @@ const GroupBoxBase: FC<Props> = ({ group }) => {
|
|||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
setIgnoredFactories([...ignoredFactories, input])
|
setIgnoredFactories([...ignoredFactories, input])
|
||||||
}}
|
}}
|
||||||
rightClickText={"Exclude this recipe from suggestions"}
|
rightClickText={'Exclude this recipe from suggestions'}
|
||||||
/>) }
|
/>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</> : null }
|
</>
|
||||||
{ intermediates.length ? <>
|
) : null}
|
||||||
|
{intermediates.length ? (
|
||||||
|
<>
|
||||||
<h4>Intermediate Factories ({intermediates.length})</h4>
|
<h4>Intermediate Factories ({intermediates.length})</h4>
|
||||||
<div className={styles.flex}>
|
<div className={styles.flex}>
|
||||||
{ intermediates.map(intermediate => <EntitySpan
|
{intermediates.map(intermediate => (
|
||||||
|
<EntitySpan
|
||||||
key={intermediate}
|
key={intermediate}
|
||||||
value={intermediate}
|
value={intermediate}
|
||||||
state={getInputType(intermediate)}
|
state={getInputType(intermediate)}
|
||||||
/>) }
|
/>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</> : null }
|
</>
|
||||||
{ suggestionsExport.length ? <>
|
) : null}
|
||||||
|
{suggestionsExport.length ? (
|
||||||
|
<>
|
||||||
<h4>Suggestions (Export)</h4>
|
<h4>Suggestions (Export)</h4>
|
||||||
<div className={styles.flex}>
|
<div className={styles.flex}>
|
||||||
{ suggestionsExport.map(suggestion => <EntitySpan
|
{suggestionsExport.map(suggestion => (
|
||||||
|
<EntitySpan
|
||||||
key={suggestion.href}
|
key={suggestion.href}
|
||||||
value={suggestion}
|
value={suggestion}
|
||||||
onClick={() => addFactory(suggestion.href, 'exports')}
|
onClick={() => addFactory(suggestion.href, 'exports')}
|
||||||
@@ -140,15 +155,19 @@ const GroupBoxBase: FC<Props> = ({ group }) => {
|
|||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
setIgnoredFactories([...ignoredFactories, suggestion.href])
|
setIgnoredFactories([...ignoredFactories, suggestion.href])
|
||||||
}}
|
}}
|
||||||
leftClickText={"Add to exported factories"}
|
leftClickText={'Add to exported factories'}
|
||||||
rightClickText={"Exclude this recipe from suggestions"}
|
rightClickText={'Exclude this recipe from suggestions'}
|
||||||
/>) }
|
/>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</> : null }
|
</>
|
||||||
{ suggestionMall.length ? <>
|
) : null}
|
||||||
|
{suggestionMall.length ? (
|
||||||
|
<>
|
||||||
<h4>Suggestions (Mall)</h4>
|
<h4>Suggestions (Mall)</h4>
|
||||||
<div className={styles.flex}>
|
<div className={styles.flex}>
|
||||||
{ suggestionMall.map(suggestion => <EntitySpan
|
{suggestionMall.map(suggestion => (
|
||||||
|
<EntitySpan
|
||||||
key={suggestion.href}
|
key={suggestion.href}
|
||||||
value={suggestion}
|
value={suggestion}
|
||||||
onClick={() => addFactory(suggestion.href, 'malls')}
|
onClick={() => addFactory(suggestion.href, 'malls')}
|
||||||
@@ -156,12 +175,15 @@ const GroupBoxBase: FC<Props> = ({ group }) => {
|
|||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
setIgnoredFactories([...ignoredFactories, suggestion.href])
|
setIgnoredFactories([...ignoredFactories, suggestion.href])
|
||||||
}}
|
}}
|
||||||
leftClickText={"Add to mall factories"}
|
leftClickText={'Add to mall factories'}
|
||||||
rightClickText={"Exclude this recipe from suggestions"}
|
rightClickText={'Exclude this recipe from suggestions'}
|
||||||
/>) }
|
/>
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</> : null }
|
</>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export const GroupBox = memo(GroupBoxBase)
|
export const GroupBox = memo(GroupBoxBase)
|
||||||
|
|||||||
@@ -1,18 +1,18 @@
|
|||||||
import {FC, useMemo, useRef, useState} from "react";
|
import { FC, useMemo, useRef, useState } from 'react'
|
||||||
import {GroupBox} from "./GroupBox/GroupBox";
|
import { GroupBox } from './GroupBox/GroupBox'
|
||||||
import styles from "./Home.module.css"
|
import styles from './Home.module.css'
|
||||||
import {useFactories} from "../../src/hooks/useFactories";
|
import { useFactories } from '../../src/hooks/useFactories'
|
||||||
import {EnrichedEntity} from "../../src/types";
|
import { EnrichedEntity } from '../../src/types'
|
||||||
import {EntitySpan} from "./EntitySpan/EntitySpan";
|
import { EntitySpan } from './EntitySpan/EntitySpan'
|
||||||
import {useGroups} from "../contexts/GroupProvider";
|
import { useGroups } from '../contexts/GroupProvider'
|
||||||
import {Preferences} from "./Preferences/Preferences";
|
import { Preferences } from './Preferences/Preferences'
|
||||||
import {download, streamToArrayBuffer} from "../../src/download";
|
import { download, streamToArrayBuffer } from '../../src/download'
|
||||||
import Link from "next/link";
|
import Link from 'next/link'
|
||||||
import {useRouter} from "next/router";
|
import { useRouter } from 'next/router'
|
||||||
|
|
||||||
export const Home: FC = () => {
|
export const Home: FC = () => {
|
||||||
const router = useRouter()
|
const router = useRouter()
|
||||||
const {factories} = useFactories()
|
const { factories } = useFactories()
|
||||||
const {
|
const {
|
||||||
groups,
|
groups,
|
||||||
addGroup,
|
addGroup,
|
||||||
@@ -23,13 +23,14 @@ export const Home: FC = () => {
|
|||||||
store,
|
store,
|
||||||
load
|
load
|
||||||
} = useGroups()
|
} = useGroups()
|
||||||
const [newGroupValue, setNewGroupValue] = useState("New group")
|
const [newGroupValue, setNewGroupValue] = useState('New group')
|
||||||
const inputRef = useRef<HTMLInputElement>(null)
|
const inputRef = useRef<HTMLInputElement>(null)
|
||||||
|
|
||||||
const [missingExport, missingMall] = useMemo<[EnrichedEntity[], EnrichedEntity[]]>(() => {
|
const [missingExport, missingMall] = useMemo<[EnrichedEntity[], EnrichedEntity[]]>(() => {
|
||||||
return factories
|
return factories
|
||||||
.filter(factory => !doNotSuggest.has(factory.href) && factory.recipe)
|
.filter(factory => !doNotSuggest.has(factory.href) && factory.recipe)
|
||||||
.reduce((acc, factory) =>
|
.reduce(
|
||||||
|
(acc, factory) =>
|
||||||
(factory.usedBy?.length ?? 0) >= 3
|
(factory.usedBy?.length ?? 0) >= 3
|
||||||
? [[...acc[0], factory], acc[1]]
|
? [[...acc[0], factory], acc[1]]
|
||||||
: [acc[0], [...acc[1], factory]],
|
: [acc[0], [...acc[1], factory]],
|
||||||
@@ -40,49 +41,66 @@ export const Home: FC = () => {
|
|||||||
return (
|
return (
|
||||||
<main>
|
<main>
|
||||||
<h1>Factorio Microservices</h1>
|
<h1>Factorio Microservices</h1>
|
||||||
<button onClick={() => {
|
<button
|
||||||
download('factorio-microservices.bin', store());
|
onClick={() => {
|
||||||
}}>Store</button>
|
download('factorio-microservices.bin', store())
|
||||||
<button onClick={async () => {
|
}}
|
||||||
const res = await fetch( '/api/submit', {
|
>
|
||||||
|
Store
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
onClick={async () => {
|
||||||
|
const res = await fetch('/api/submit', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json'
|
'Content-Type': 'application/json'
|
||||||
},
|
},
|
||||||
body: JSON.stringify({groups, ignored: ignoredFactories, base: baseFactories})
|
body: JSON.stringify({ groups, ignored: ignoredFactories, base: baseFactories })
|
||||||
})
|
})
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const { uuid } = await res.json()
|
const { uuid } = await res.json()
|
||||||
if (uuid) await router.push({query: {...router.query, id: uuid}})
|
if (uuid) await router.push({ query: { ...router.query, id: uuid } })
|
||||||
}
|
}
|
||||||
}}>Upload</button>
|
}}
|
||||||
<input type={"file"} multiple={false} ref={inputRef} onChange={async evt => {
|
>
|
||||||
const stream = evt.currentTarget.files?.[0].stream() as globalThis.ReadableStream<Uint8Array>|undefined
|
Upload
|
||||||
|
</button>
|
||||||
|
<input
|
||||||
|
type={'file'}
|
||||||
|
multiple={false}
|
||||||
|
ref={inputRef}
|
||||||
|
onChange={async evt => {
|
||||||
|
const stream = evt.currentTarget.files?.[0].stream() as
|
||||||
|
| globalThis.ReadableStream<Uint8Array>
|
||||||
|
| undefined
|
||||||
if (stream) {
|
if (stream) {
|
||||||
const array = await streamToArrayBuffer(stream)
|
const array = await streamToArrayBuffer(stream)
|
||||||
load(array)
|
load(array)
|
||||||
if (inputRef.current) inputRef.current.value = null as unknown as string
|
if (inputRef.current) inputRef.current.value = null as unknown as string
|
||||||
}
|
}
|
||||||
}}/>
|
}}
|
||||||
<Link href={{pathname: '/visualize', query: router.query}}>Visualize</Link>
|
/>
|
||||||
|
<Link href={{ pathname: '/visualize', query: router.query }}>Visualize</Link>
|
||||||
<Preferences />
|
<Preferences />
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend>Missing export factories</legend>
|
<legend>Missing export factories</legend>
|
||||||
<div className={styles.missingFactories}>
|
<div className={styles.missingFactories}>
|
||||||
{ missingExport.map(missing => (
|
{missingExport.map(missing => (
|
||||||
<EntitySpan
|
<EntitySpan
|
||||||
key={missing.href}
|
key={missing.href}
|
||||||
value={missing}
|
value={missing}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
addGroup(newGroupValue !== "New group" ? newGroupValue : missing.name, [missing.href])
|
addGroup(newGroupValue !== 'New group' ? newGroupValue : missing.name, [
|
||||||
setNewGroupValue("New group")
|
missing.href
|
||||||
|
])
|
||||||
|
setNewGroupValue('New group')
|
||||||
}}
|
}}
|
||||||
onContextMenu={event => {
|
onContextMenu={event => {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
setIgnoredFactories([...ignoredFactories, missing.href])
|
setIgnoredFactories([...ignoredFactories, missing.href])
|
||||||
}}
|
}}
|
||||||
leftClickText={"Create a new group with this name and item as exported factory"}
|
leftClickText={'Create a new group with this name and item as exported factory'}
|
||||||
rightClickText={"Exclude this recipe from suggestions"}
|
rightClickText={'Exclude this recipe from suggestions'}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
@@ -90,31 +108,34 @@ export const Home: FC = () => {
|
|||||||
<fieldset>
|
<fieldset>
|
||||||
<legend>Missing mall factories</legend>
|
<legend>Missing mall factories</legend>
|
||||||
<div className={styles.missingFactories}>
|
<div className={styles.missingFactories}>
|
||||||
{ missingMall.map(missing => (
|
{missingMall.map(missing => (
|
||||||
<EntitySpan
|
<EntitySpan
|
||||||
key={missing.href}
|
key={missing.href}
|
||||||
value={missing}
|
value={missing}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
addGroup(newGroupValue !== "New group" ? newGroupValue : missing.name, [], [missing.href])
|
addGroup(
|
||||||
setNewGroupValue("New group")
|
newGroupValue !== 'New group' ? newGroupValue : missing.name,
|
||||||
|
[],
|
||||||
|
[missing.href]
|
||||||
|
)
|
||||||
|
setNewGroupValue('New group')
|
||||||
}}
|
}}
|
||||||
onContextMenu={event => {
|
onContextMenu={event => {
|
||||||
event.preventDefault()
|
event.preventDefault()
|
||||||
setIgnoredFactories([...ignoredFactories, missing.href])
|
setIgnoredFactories([...ignoredFactories, missing.href])
|
||||||
}}
|
}}
|
||||||
leftClickText={"Create a new group with this name and item as mall factory"}
|
leftClickText={'Create a new group with this name and item as mall factory'}
|
||||||
rightClickText={"Exclude this recipe from suggestions"}
|
rightClickText={'Exclude this recipe from suggestions'}
|
||||||
/>
|
/>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
<div className={styles.grid}>
|
<div className={styles.grid}>
|
||||||
{
|
{Object.values(groups)
|
||||||
Object
|
|
||||||
.values(groups)
|
|
||||||
.sort((a, b) => a.name.localeCompare(b.name))
|
.sort((a, b) => a.name.localeCompare(b.name))
|
||||||
.map((group) => <GroupBox key={group.name} group={group} />)
|
.map(group => (
|
||||||
}
|
<GroupBox key={group.name} group={group} />
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</main>
|
</main>
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {FC} from "react";
|
import { FC } from 'react'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
className?: string
|
className?: string
|
||||||
@@ -6,11 +6,25 @@ interface Props {
|
|||||||
classClick?: string
|
classClick?: string
|
||||||
}
|
}
|
||||||
|
|
||||||
export const LeftClickIcon: FC<Props> = ({className, classBody, classClick}) => {
|
export const LeftClickIcon: FC<Props> = ({ className, classBody, classClick }) => {
|
||||||
return (
|
return (
|
||||||
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" x="0px" y="0px" viewBox="0 0 100 100" className={className}>
|
<svg
|
||||||
<path className={classBody} d="M51.552,8.117v32.554l-3.095,0.009c-9.203,0.027-17.447,0.297-24.509,0.803l-0.291,0.021 c-0.026,1.733-0.036,3.521-0.036,5.378c0,24.854,1.527,45,26.379,45c24.854,0,26.379-20.146,26.379-45 C76.379,22.563,74.903,8.701,51.552,8.117z" />
|
xmlns='http://www.w3.org/2000/svg'
|
||||||
<path className={classClick} id="click" d="M48.448,37.577V8.117C27.971,8.629,24.313,19.354,23.727,38.388C29.914,37.945,38.002,37.607,48.448,37.577z" />
|
version='1.1'
|
||||||
|
x='0px'
|
||||||
|
y='0px'
|
||||||
|
viewBox='0 0 100 100'
|
||||||
|
className={className}
|
||||||
|
>
|
||||||
|
<path
|
||||||
|
className={classBody}
|
||||||
|
d='M51.552,8.117v32.554l-3.095,0.009c-9.203,0.027-17.447,0.297-24.509,0.803l-0.291,0.021 c-0.026,1.733-0.036,3.521-0.036,5.378c0,24.854,1.527,45,26.379,45c24.854,0,26.379-20.146,26.379-45 C76.379,22.563,74.903,8.701,51.552,8.117z'
|
||||||
|
/>
|
||||||
|
<path
|
||||||
|
className={classClick}
|
||||||
|
id='click'
|
||||||
|
d='M48.448,37.577V8.117C27.971,8.629,24.313,19.354,23.727,38.388C29.914,37.945,38.002,37.607,48.448,37.577z'
|
||||||
|
/>
|
||||||
</svg>
|
</svg>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,17 +1,13 @@
|
|||||||
import {FC, useState} from "react";
|
import { FC, useState } from 'react'
|
||||||
import {FactorySelect} from "../FactorySelect/FactorySelect";
|
import { FactorySelect } from '../FactorySelect/FactorySelect'
|
||||||
import {useGroups} from "../../contexts/GroupProvider";
|
import { useGroups } from '../../contexts/GroupProvider'
|
||||||
|
|
||||||
export const Preferences: FC = () => {
|
export const Preferences: FC = () => {
|
||||||
const {
|
const { addGroup, baseFactories, setBaseFactories, ignoredFactories, setIgnoredFactories } =
|
||||||
addGroup,
|
useGroups()
|
||||||
baseFactories,
|
const [newGroupValue, setNewGroupValue] = useState('New group')
|
||||||
setBaseFactories,
|
return (
|
||||||
ignoredFactories,
|
<>
|
||||||
setIgnoredFactories
|
|
||||||
} = useGroups()
|
|
||||||
const [newGroupValue, setNewGroupValue] = useState("New group")
|
|
||||||
return <>
|
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend>Basic Values</legend>
|
<legend>Basic Values</legend>
|
||||||
<FactorySelect
|
<FactorySelect
|
||||||
@@ -30,13 +26,17 @@ export const Preferences: FC = () => {
|
|||||||
</fieldset>
|
</fieldset>
|
||||||
<fieldset>
|
<fieldset>
|
||||||
<legend>Add new groups</legend>
|
<legend>Add new groups</legend>
|
||||||
<input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)}/>
|
<input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)} />
|
||||||
<button disabled={!newGroupValue} onClick={() => {
|
<button
|
||||||
|
disabled={!newGroupValue}
|
||||||
|
onClick={() => {
|
||||||
addGroup(newGroupValue)
|
addGroup(newGroupValue)
|
||||||
setNewGroupValue("New group")
|
setNewGroupValue('New group')
|
||||||
}}>
|
}}
|
||||||
|
>
|
||||||
Add group "{newGroupValue}"
|
Add group "{newGroupValue}"
|
||||||
</button>
|
</button>
|
||||||
</fieldset>
|
</fieldset>
|
||||||
</>
|
</>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,24 +1,29 @@
|
|||||||
import {FC} from "react"
|
import { FC } from 'react'
|
||||||
import {Recipe} from "../../../src/types"
|
import { Recipe } from '../../../src/types'
|
||||||
import {EntityIcon} from "../EntityIcon/EntityIcon";
|
import { EntityIcon } from '../EntityIcon/EntityIcon'
|
||||||
import styles from './Recipe.module.css'
|
import styles from './Recipe.module.css'
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
recipe: Recipe
|
recipe: Recipe
|
||||||
}
|
}
|
||||||
|
|
||||||
export const RecipeSpan: FC<Props> = ({recipe}) => {
|
export const RecipeSpan: FC<Props> = ({ recipe }) => {
|
||||||
const toEntityIcon = ([key, amount]: [string, number]) => <EntityIcon key={key} value={key} amount={amount} />
|
const toEntityIcon = ([key, amount]: [string, number]) => (
|
||||||
const joinByPlus = (elems: JSX.Element[]) => elems.reduce((acc, curr) => {
|
<EntityIcon key={key} value={key} amount={amount} />
|
||||||
|
)
|
||||||
|
const joinByPlus = (elems: JSX.Element[]) =>
|
||||||
|
elems.reduce((acc, curr) => {
|
||||||
if (acc.length) {
|
if (acc.length) {
|
||||||
return [...acc, '+', curr]
|
return [...acc, '+', curr]
|
||||||
} else {
|
} else {
|
||||||
return [curr]
|
return [curr]
|
||||||
}
|
}
|
||||||
}, [] as (JSX.Element|string)[])
|
}, [] as (JSX.Element | string)[])
|
||||||
const before = Object.entries({...recipe.prerequisites}).map(toEntityIcon)
|
const before = Object.entries({ ...recipe.prerequisites }).map(toEntityIcon)
|
||||||
const after = Object.entries({...recipe.output}).map(toEntityIcon)
|
const after = Object.entries({ ...recipe.output }).map(toEntityIcon)
|
||||||
return <span className={styles.recipe}>
|
return (
|
||||||
|
<span className={styles.recipe}>
|
||||||
{joinByPlus([toEntityIcon(['/Time', recipe.time]), ...before])} → {joinByPlus(after)}
|
{joinByPlus([toEntityIcon(['/Time', recipe.time]), ...before])} → {joinByPlus(after)}
|
||||||
</span>
|
</span>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,8 +17,8 @@
|
|||||||
.node {
|
.node {
|
||||||
padding: 0.5em;
|
padding: 0.5em;
|
||||||
border-radius: 4px;
|
border-radius: 4px;
|
||||||
border: 1px solid #DDDDDD;
|
border: 1px solid #dddddd;
|
||||||
background-color: #EEE;
|
background-color: #eee;
|
||||||
}
|
}
|
||||||
|
|
||||||
.hidden {
|
.hidden {
|
||||||
|
|||||||
@@ -1,29 +1,44 @@
|
|||||||
import {FC, HTMLProps, PropsWithChildren, useEffect, useRef, useState} from "react";
|
import { FC, HTMLProps, PropsWithChildren, useEffect, useRef, useState } from 'react'
|
||||||
import styles from './ProducingGraph.module.css'
|
import styles from './ProducingGraph.module.css'
|
||||||
import {EntityIcon} from "../../home/EntityIcon/EntityIcon";
|
import { EntityIcon } from '../../home/EntityIcon/EntityIcon'
|
||||||
import {createPath, drawLine} from "../../../src/svg";
|
import { createPath, drawLine } from '../../../src/svg'
|
||||||
import {AdditionalNode, GraphNode, GraphNodeWithIds, isAdditionalNode} from "../../../src/graph-untangle/types";
|
import {
|
||||||
import {graphUntangled} from "../../../src/graph-untangle";
|
AdditionalNode,
|
||||||
import {Dict} from "../../../src/types";
|
GraphNode,
|
||||||
|
GraphNodeWithIds,
|
||||||
|
isAdditionalNode
|
||||||
|
} from '../../../src/graph-untangle/types'
|
||||||
|
import { graphUntangled } from '../../../src/graph-untangle'
|
||||||
|
import { Dict } from '../../../src/types'
|
||||||
|
|
||||||
interface Props<T extends {}> {
|
interface Props<T extends Dict<unknown>> {
|
||||||
nodes: GraphNode<T>[]
|
nodes: GraphNode<T>[]
|
||||||
inputs: string[]
|
inputs: string[]
|
||||||
outputs?: string[]
|
outputs?: string[]
|
||||||
childType: FC<HTMLProps<HTMLDivElement> & {node: GraphNode<T>}>
|
childType: FC<HTMLProps<HTMLDivElement> & { node: GraphNode<T> }>
|
||||||
}
|
}
|
||||||
|
|
||||||
export const ProducingGraph = <T extends Dict<unknown>,>({nodes, inputs, outputs, childType: ChildType}: PropsWithChildren<Props<T>>) => {
|
export const ProducingGraph = <T extends Dict<unknown>>({
|
||||||
|
nodes,
|
||||||
|
inputs,
|
||||||
|
outputs,
|
||||||
|
childType: ChildType
|
||||||
|
}: PropsWithChildren<Props<T>>) => {
|
||||||
const planeRef = useRef<HTMLDivElement>(null)
|
const planeRef = useRef<HTMLDivElement>(null)
|
||||||
const [[rows, nodeMap], setGraph] = useState<[string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>]>(graphUntangled(nodes, inputs, outputs ?? [], 3000))
|
const [[rows, nodeMap]] = useState<[string[][], Dict<GraphNodeWithIds<T | AdditionalNode>>]>(
|
||||||
|
graphUntangled(nodes, inputs, outputs ?? [], 3000)
|
||||||
|
)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!planeRef.current) return
|
if (!planeRef.current) return
|
||||||
const plane = planeRef.current
|
const plane = planeRef.current
|
||||||
function createSvgElement() {
|
function createSvgElement() {
|
||||||
const elem = document.createElementNS("http://www.w3.org/2000/svg", "svg")
|
const elem = document.createElementNS('http://www.w3.org/2000/svg', 'svg')
|
||||||
elem.id = 'arrows'
|
elem.id = 'arrows'
|
||||||
elem.setAttribute('style', 'position: absolute; inset: 0 0 0 0; pointer-events: none; z-index: -10;')
|
elem.setAttribute(
|
||||||
|
'style',
|
||||||
|
'position: absolute; inset: 0 0 0 0; pointer-events: none; z-index: -10;'
|
||||||
|
)
|
||||||
elem.setAttributeNS(null, 'stroke', 'black')
|
elem.setAttributeNS(null, 'stroke', 'black')
|
||||||
elem.setAttributeNS(null, 'fill', 'none')
|
elem.setAttributeNS(null, 'fill', 'none')
|
||||||
plane.appendChild(elem)
|
plane.appendChild(elem)
|
||||||
@@ -37,69 +52,75 @@ export const ProducingGraph = <T extends Dict<unknown>,>({nodes, inputs, outputs
|
|||||||
svg.setAttributeNS(null, 'viewBox', `0 0 ${width} ${height}`)
|
svg.setAttributeNS(null, 'viewBox', `0 0 ${width} ${height}`)
|
||||||
svg.replaceChildren()
|
svg.replaceChildren()
|
||||||
|
|
||||||
let paths: string[] = []
|
const paths: string[] = []
|
||||||
plane.querySelectorAll('[data-outputs]').forEach(startNode => {
|
plane.querySelectorAll('[data-outputs]').forEach(startNode => {
|
||||||
if (!(startNode instanceof HTMLElement)) return
|
if (!(startNode instanceof HTMLElement)) return
|
||||||
(startNode.dataset.outputs?.split(' ') ?? []).forEach(output => {
|
;(startNode.dataset.outputs?.split(' ') ?? []).forEach(output => {
|
||||||
const endNode = plane.querySelector(`[data-name="${output}"]`)
|
const endNode = plane.querySelector(`[data-name="${output}"]`)
|
||||||
if (!(endNode instanceof HTMLElement)) return
|
if (!(endNode instanceof HTMLElement)) return
|
||||||
paths.push(createPath(plane.getBoundingClientRect(), startNode.getBoundingClientRect(), endNode.getBoundingClientRect()))
|
paths.push(
|
||||||
|
createPath(
|
||||||
|
plane.getBoundingClientRect(),
|
||||||
|
startNode.getBoundingClientRect(),
|
||||||
|
endNode.getBoundingClientRect()
|
||||||
|
)
|
||||||
|
)
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
plane.querySelectorAll('[data-hidden="true"][data-outputs]').forEach(elem => {
|
plane.querySelectorAll('[data-hidden="true"][data-outputs]').forEach(elem => {
|
||||||
if (!(elem instanceof HTMLElement)) return
|
if (!(elem instanceof HTMLElement)) return
|
||||||
paths.push(drawLine(plane.getBoundingClientRect(), elem.getBoundingClientRect()))
|
paths.push(drawLine(plane.getBoundingClientRect(), elem.getBoundingClientRect()))
|
||||||
})
|
})
|
||||||
const path = document.createElementNS('http://www.w3.org/2000/svg',"path")
|
const path = document.createElementNS('http://www.w3.org/2000/svg', 'path')
|
||||||
path.setAttributeNS(null, 'd', paths.join(' '))
|
path.setAttributeNS(null, 'd', paths.join(' '))
|
||||||
svg.appendChild(path)
|
svg.appendChild(path)
|
||||||
})
|
})
|
||||||
|
|
||||||
return <div className={styles.plane} ref={planeRef}>
|
return (
|
||||||
|
<div className={styles.plane} ref={planeRef}>
|
||||||
{rows.map((row, colIdx) => (
|
{rows.map((row, colIdx) => (
|
||||||
<div className={styles.row} key={colIdx} data-row={true}>
|
<div className={styles.row} key={colIdx} data-row={true}>
|
||||||
{
|
{row.map(uid => {
|
||||||
row.map((uid) => {
|
|
||||||
const node = nodeMap[uid]
|
const node = nodeMap[uid]
|
||||||
return (
|
return !isAdditionalNode(node) ? (
|
||||||
!isAdditionalNode(node)
|
<span
|
||||||
? <span
|
|
||||||
data-name={node.___uid}
|
data-name={node.___uid}
|
||||||
data-inputs={node.___uidInputs.join(' ')}
|
data-inputs={node.___uidInputs.join(' ')}
|
||||||
data-outputs={node.___uidOutputs.join(' ')}
|
data-outputs={node.___uidOutputs.join(' ')}
|
||||||
key={node.___uid}
|
key={node.___uid}
|
||||||
data-hidden={node.___uidOutputs.length > 0}>
|
data-hidden={node.___uidOutputs.length > 0}
|
||||||
<ChildType
|
>
|
||||||
className={styles.node}
|
<ChildType className={styles.node} node={node} />
|
||||||
node={node}
|
|
||||||
/>
|
|
||||||
</span>
|
</span>
|
||||||
: node.___type === 'h'
|
) : node.___type === 'h' ? (
|
||||||
? <span
|
<span
|
||||||
className={styles.hidden}
|
className={styles.hidden}
|
||||||
key={node.___uid}
|
key={node.___uid}
|
||||||
data-name={node.___uid}
|
data-name={node.___uid}
|
||||||
data-inputs={node.___uidInputs.join(' ')}
|
data-inputs={node.___uidInputs.join(' ')}
|
||||||
data-outputs={node.___uidOutputs.join(' ')}
|
data-outputs={node.___uidOutputs.join(' ')}
|
||||||
data-hidden={true}></span>
|
data-hidden={true}
|
||||||
: node.___type === 'i'
|
></span>
|
||||||
? <span
|
) : node.___type === 'i' ? (
|
||||||
|
<span
|
||||||
key={node.___uid}
|
key={node.___uid}
|
||||||
data-name={node.___uid}
|
data-name={node.___uid}
|
||||||
data-outputs={node.___uidOutputs.join(' ')}
|
data-outputs={node.___uidOutputs.join(' ')}
|
||||||
data-hidden={true}>
|
data-hidden={true}
|
||||||
<EntityIcon value={node.name}/>
|
>
|
||||||
|
<EntityIcon value={node.name} />
|
||||||
</span>
|
</span>
|
||||||
: <EntityIcon
|
) : (
|
||||||
|
<EntityIcon
|
||||||
key={node.___uid}
|
key={node.___uid}
|
||||||
value={node.name}
|
value={node.name}
|
||||||
data-name={node.___uid}
|
data-name={node.___uid}
|
||||||
data-inputs={node.___uidInputs.join(' ')}
|
data-inputs={node.___uidInputs.join(' ')}
|
||||||
/>
|
/>
|
||||||
);
|
)
|
||||||
})
|
})}
|
||||||
}
|
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,25 +1,25 @@
|
|||||||
import {FC, PropsWithChildren, useEffect, useRef} from "react";
|
import { FC, PropsWithChildren, useEffect, useRef } from 'react'
|
||||||
import IndianaDragScoll from "react-indiana-drag-scroll";
|
import IndianaDragScoll from 'react-indiana-drag-scroll'
|
||||||
import styles from './ScrollContainer.module.css'
|
import styles from './ScrollContainer.module.css'
|
||||||
|
|
||||||
export const ScrollContainer: FC<PropsWithChildren> = ({children}) => {
|
export const ScrollContainer: FC<PropsWithChildren> = ({ children }) => {
|
||||||
const container = useRef<HTMLDivElement>(null);
|
const container = useRef<HTMLDivElement>(null)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (container.current) {
|
if (container.current) {
|
||||||
container.current.oncontextmenu = e => e.preventDefault()
|
container.current.oncontextmenu = e => e.preventDefault()
|
||||||
}
|
}
|
||||||
}, []);
|
}, [])
|
||||||
|
|
||||||
return <IndianaDragScoll
|
return (
|
||||||
|
<IndianaDragScoll
|
||||||
className={styles.container}
|
className={styles.container}
|
||||||
buttons={[2]}
|
buttons={[2]}
|
||||||
innerRef={container}
|
innerRef={container}
|
||||||
hideScrollbars={false}
|
hideScrollbars={false}
|
||||||
activationDistance={5}
|
activationDistance={5}
|
||||||
>
|
>
|
||||||
<div className={styles.inner}>
|
<div className={styles.inner}>{children}</div>
|
||||||
{children}
|
|
||||||
</div>
|
|
||||||
</IndianaDragScoll>
|
</IndianaDragScoll>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import {FC, HTMLProps} from "react";
|
import { FC, HTMLProps } from 'react'
|
||||||
import {GraphNode} from "../../shared/ProducingGraph/ProducingGraph";
|
import { Recipe } from '../../../src/types'
|
||||||
import {Recipe} from "../../../src/types";
|
import cx from 'classnames'
|
||||||
import cx from "classnames";
|
import styles from './NodeDetails.module.css'
|
||||||
import styles from "./NodeDetails.module.css";
|
import { RecipeSpan } from '../../home/Recipe/Recipe'
|
||||||
import {RecipeSpan} from "../../home/Recipe/Recipe";
|
import { GraphNode } from '../../../src/graph-untangle/types'
|
||||||
|
|
||||||
export type DetailGraphNode = GraphNode<{
|
export type DetailGraphNode = GraphNode<{
|
||||||
recipes: Recipe[]
|
recipes: Recipe[]
|
||||||
@@ -13,9 +13,13 @@ interface Props extends HTMLProps<HTMLDivElement> {
|
|||||||
node: DetailGraphNode
|
node: DetailGraphNode
|
||||||
}
|
}
|
||||||
|
|
||||||
export const NodeDetails: FC<Props> = ({node, className, ...props}) => {
|
export const NodeDetails: FC<Props> = ({ node, className, ...props }) => {
|
||||||
return <div {...props} className={cx(className, styles.root)}>
|
return (
|
||||||
|
<div {...props} className={cx(className, styles.root)}>
|
||||||
<h3>{node.name}</h3>
|
<h3>{node.name}</h3>
|
||||||
{node.recipes.map((recipe, idx) => <RecipeSpan key={idx} recipe={recipe}/>)}
|
{node.recipes.map((recipe, idx) => (
|
||||||
|
<RecipeSpan key={idx} recipe={recipe} />
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -6,7 +6,7 @@
|
|||||||
.tiny {
|
.tiny {
|
||||||
font-size: 0.5em;
|
font-size: 0.5em;
|
||||||
margin-top: -1.6em;
|
margin-top: -1.6em;
|
||||||
}
|
}
|
||||||
|
|
||||||
.small {
|
.small {
|
||||||
font-size: 0.8em;
|
font-size: 0.8em;
|
||||||
@@ -15,4 +15,3 @@
|
|||||||
.linkOut {
|
.linkOut {
|
||||||
margin-inline-end: 0.5em;
|
margin-inline-end: 0.5em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,14 +1,13 @@
|
|||||||
import {FC, HTMLProps} from "react";
|
import { FC, HTMLProps } from 'react'
|
||||||
import {GraphNode} from "../../shared/ProducingGraph/ProducingGraph";
|
import { EnrichedEntity } from '../../../src/types'
|
||||||
import {EnrichedEntity, Recipe} from "../../../src/types";
|
import cx from 'classnames'
|
||||||
import cx from "classnames";
|
import styles from './NodeOverview.module.css'
|
||||||
import styles from "./NodeOverview.module.css";
|
import Link from 'next/link'
|
||||||
import {RecipeSpan} from "../../home/Recipe/Recipe";
|
import { EntityIcon } from '../../home/EntityIcon/EntityIcon'
|
||||||
import Link from "next/link";
|
import { GraphNode } from '../../../src/graph-untangle/types'
|
||||||
import {EntityIcon} from "../../home/EntityIcon/EntityIcon";
|
|
||||||
|
|
||||||
export type OverviewGraphNode = GraphNode<{
|
export type OverviewGraphNode = GraphNode<{
|
||||||
icons: (EnrichedEntity|string)[]
|
icons: (EnrichedEntity | string)[]
|
||||||
linkOut: string
|
linkOut: string
|
||||||
}>
|
}>
|
||||||
|
|
||||||
@@ -16,21 +15,38 @@ interface Props extends HTMLProps<HTMLDivElement> {
|
|||||||
node: OverviewGraphNode
|
node: OverviewGraphNode
|
||||||
}
|
}
|
||||||
|
|
||||||
export const NodeOverview: FC<Props> = ({node, className, ...props}) => {
|
export const NodeOverview: FC<Props> = ({ node, className, ...props }) => {
|
||||||
return <div {...props} className={cx(className, styles.root)}>
|
return (
|
||||||
<h3><span className={styles.linkOut}><Link href={node.linkOut}>🔗</Link></span>{node.name}</h3>
|
<div {...props} className={cx(className, styles.root)}>
|
||||||
{ node.icons?.length ? <div className={styles.tiny}>
|
<h3>
|
||||||
{node.icons.map((input) => <EntityIcon key={typeof input === "string" ? input : input.href} value={input} />)}
|
<span className={styles.linkOut}>
|
||||||
</div> : null }
|
<Link href={node.linkOut}>🔗</Link>
|
||||||
|
</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>
|
<h4>Inputs</h4>
|
||||||
<div className={styles.small}>
|
<div className={styles.small}>
|
||||||
{node.inputs.map((input) => <EntityIcon key={input} value={input} />)}
|
{node.inputs.map(input => (
|
||||||
|
<EntityIcon key={input} value={input} />
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
{node.outputs.length ? <>
|
{node.outputs.length ? (
|
||||||
|
<>
|
||||||
<h4>Outputs</h4>
|
<h4>Outputs</h4>
|
||||||
<div className={styles.small}>
|
<div className={styles.small}>
|
||||||
{node.outputs.map((input) => <EntityIcon key={input} value={input} />)}
|
{node.outputs.map(input => (
|
||||||
|
<EntityIcon key={input} value={input} />
|
||||||
|
))}
|
||||||
</div>
|
</div>
|
||||||
</>: null}
|
</>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,72 +1,74 @@
|
|||||||
import {useRouter} from "next/router";
|
import { useRouter } from 'next/router'
|
||||||
import {GroupProvider, useGroups} from "../contexts/GroupProvider";
|
import { useGroups } from '../contexts/GroupProvider'
|
||||||
import {useFactories} from "../../src/hooks/useFactories";
|
import { useFactories } from '../../src/hooks/useFactories'
|
||||||
import {FC, useEffect, useMemo} from "react";
|
import { FC, useEffect, useMemo } from 'react'
|
||||||
import {calculateInputs} from "../../src/calculateInputs";
|
import { calculateInputs } from '../../src/calculateInputs'
|
||||||
import {DetailGraphNode, NodeDetails} from "./NodeDetails/NodeDetails";
|
import { DetailGraphNode, NodeDetails } from './NodeDetails/NodeDetails'
|
||||||
import {groupBy, isNonNullable, uniquify} from "../../src/utils";
|
import { groupBy, isNonNullable, uniquify } from '../../src/utils'
|
||||||
import {EnrichedEntity} from "../../src/types";
|
import { EnrichedEntity } from '../../src/types'
|
||||||
import Head from "next/head";
|
import Head from 'next/head'
|
||||||
import {ScrollContainer} from "../shared/ScrollContainer/ScrollContainer";
|
import { ScrollContainer } from '../shared/ScrollContainer/ScrollContainer'
|
||||||
import {ProducingGraph} from "../shared/ProducingGraph/ProducingGraph";
|
import { ProducingGraph } from '../shared/ProducingGraph/ProducingGraph'
|
||||||
|
|
||||||
export const PageDetails: FC = () => {
|
export const PageDetails: FC = () => {
|
||||||
const {query: {name}} = useRouter()
|
|
||||||
const {
|
const {
|
||||||
exportedFactories,
|
query: { name }
|
||||||
baseFactories,
|
} = useRouter()
|
||||||
ignoredFactories,
|
const { exportedFactories, baseFactories, groups } = useGroups()
|
||||||
groups
|
const { findFactory } = useFactories()
|
||||||
} = useGroups()
|
|
||||||
const {
|
|
||||||
findFactory
|
|
||||||
} = useFactories()
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
document.body.classList.add("scroll");
|
document.body.classList.add('scroll')
|
||||||
return () => document.body.classList.remove("scroll")
|
return () => document.body.classList.remove('scroll')
|
||||||
}, []);
|
}, [])
|
||||||
|
|
||||||
const group = typeof name === 'string' ? groups[name] : undefined
|
const group = typeof name === 'string' ? groups[name] : undefined
|
||||||
|
|
||||||
const [inputFactories, intermediateFactories] = useMemo<ReturnType<typeof calculateInputs>>(() => {
|
const [inputFactories, intermediateFactories] = useMemo<
|
||||||
|
ReturnType<typeof calculateInputs>
|
||||||
|
>(() => {
|
||||||
if (!group) return [[], []]
|
if (!group) return [[], []]
|
||||||
return calculateInputs(
|
return calculateInputs(
|
||||||
[...group.exports, ...group.malls],
|
[...group.exports, ...group.malls],
|
||||||
ignoredFactories,
|
|
||||||
baseFactories,
|
baseFactories,
|
||||||
exportedFactories,
|
exportedFactories,
|
||||||
findFactory
|
findFactory
|
||||||
)
|
)
|
||||||
}, [baseFactories, exportedFactories, findFactory, group, ignoredFactories])
|
}, [baseFactories, exportedFactories, findFactory, group])
|
||||||
|
|
||||||
const producingNodes: DetailGraphNode[] = useMemo(() => {
|
const producingNodes: DetailGraphNode[] = useMemo(() => {
|
||||||
if (!group) return []
|
if (!group) return []
|
||||||
const nodes = uniquify([...intermediateFactories, ...group.exports, ...group.malls])
|
const nodes = uniquify([...intermediateFactories, ...group.exports, ...group.malls])
|
||||||
.map(findFactory)
|
.map(findFactory)
|
||||||
.filter(isNonNullable)
|
.filter(isNonNullable)
|
||||||
.map((factory: EnrichedEntity) => ({
|
.map(
|
||||||
inputs: Object.keys(factory.recipe?.prerequisites ?? {}).sort((a, b) => a.localeCompare(b)),
|
(factory: EnrichedEntity) =>
|
||||||
|
({
|
||||||
|
inputs: Object.keys(factory.recipe?.prerequisites ?? {}).sort((a, b) =>
|
||||||
|
a.localeCompare(b)
|
||||||
|
),
|
||||||
outputs: Object.keys(factory.recipe?.output ?? {}).sort((a, b) => a.localeCompare(b)),
|
outputs: Object.keys(factory.recipe?.output ?? {}).sort((a, b) => a.localeCompare(b)),
|
||||||
name: factory.name,
|
name: factory.name,
|
||||||
recipes: [factory.recipe]
|
recipes: [factory.recipe]
|
||||||
} as DetailGraphNode))
|
} as DetailGraphNode)
|
||||||
return Object
|
)
|
||||||
.values(groupBy(nodes, node => node.inputs.join()))
|
return Object.values(groupBy(nodes, node => node.inputs.join())).map(
|
||||||
.map(nodesOfInput => ({
|
nodesOfInput =>
|
||||||
|
({
|
||||||
inputs: nodesOfInput[0].inputs,
|
inputs: nodesOfInput[0].inputs,
|
||||||
outputs: uniquify(nodesOfInput.flatMap(node => node.outputs)),
|
outputs: uniquify(nodesOfInput.flatMap(node => node.outputs)),
|
||||||
name: nodesOfInput.map(node => node.name).join(', '),
|
name: nodesOfInput.map(node => node.name).join(', '),
|
||||||
recipes: nodesOfInput.flatMap(node => node.recipes)
|
recipes: nodesOfInput.flatMap(node => node.recipes)
|
||||||
} as DetailGraphNode))
|
} as DetailGraphNode)
|
||||||
|
)
|
||||||
}, [findFactory, group, intermediateFactories])
|
}, [findFactory, group, intermediateFactories])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<Head>
|
<Head>
|
||||||
<title>Factorio Microservices</title>
|
<title>Factorio Microservices</title>
|
||||||
<meta name="description" content="Create Factorio microservices" />
|
<meta name='description' content='Create Factorio microservices' />
|
||||||
<link rel="icon" href="/public/favicon.ico" />
|
<link rel='icon' href='/public/favicon.ico' />
|
||||||
</Head>
|
</Head>
|
||||||
<main>
|
<main>
|
||||||
<ScrollContainer>
|
<ScrollContainer>
|
||||||
|
|||||||
15
package.json
15
package.json
@@ -6,7 +6,11 @@
|
|||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start",
|
"start": "next start",
|
||||||
"lint": "next lint"
|
"lint": "next lint",
|
||||||
|
"lint:fix": "tsc --noEmit && prettier --write --loglevel warn . && eslint --fix . && stylelint --fix **/*.css",
|
||||||
|
"eslint:fix": "eslint --fix .",
|
||||||
|
"stylelint:fix": " stylelint --fix **/*.css",
|
||||||
|
"prepare": "husky install"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"classnames": "^2.3.1",
|
"classnames": "^2.3.1",
|
||||||
@@ -30,9 +34,18 @@
|
|||||||
"@types/react": "18.0.17",
|
"@types/react": "18.0.17",
|
||||||
"@types/react-dom": "18.0.6",
|
"@types/react-dom": "18.0.6",
|
||||||
"@types/seedrandom": "^3.0.2",
|
"@types/seedrandom": "^3.0.2",
|
||||||
|
"@typescript-eslint/eslint-plugin": "^5.33.1",
|
||||||
|
"@typescript-eslint/parser": "^5.33.1",
|
||||||
"eslint": "8.21.0",
|
"eslint": "8.21.0",
|
||||||
"eslint-config-next": "12.2.4",
|
"eslint-config-next": "12.2.4",
|
||||||
|
"eslint-plugin-unused-imports": "^2.0.0",
|
||||||
|
"husky": "^8.0.1",
|
||||||
"json-schema-to-typescript": "^11.0.2",
|
"json-schema-to-typescript": "^11.0.2",
|
||||||
|
"lint-staged": "^13.0.3",
|
||||||
|
"prettier": "^2.7.1",
|
||||||
|
"stylelint": "^14.10.0",
|
||||||
|
"stylelint-config-idiomatic-order": "^8.1.0",
|
||||||
|
"stylelint-config-standard": "^27.0.0",
|
||||||
"typescript": "4.7.4"
|
"typescript": "4.7.4"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import '../styles/globals.css'
|
import '../styles/globals.css'
|
||||||
import type { AppProps } from 'next/app'
|
import type { AppProps } from 'next/app'
|
||||||
import {GroupProvider} from "../components/contexts/GroupProvider";
|
import { FC } from 'react'
|
||||||
import {FC} from "react";
|
|
||||||
|
|
||||||
const MyApp: FC<AppProps> = ({ Component, pageProps }) => {
|
const MyApp: FC<AppProps> = ({ Component, pageProps }) => {
|
||||||
return <Component {...pageProps} />
|
return <Component {...pageProps} />
|
||||||
|
|||||||
@@ -1,9 +1,9 @@
|
|||||||
import {Html, Main, NextScript, DocumentProps, Head} from 'next/document';
|
import { Html, Main, NextScript, DocumentProps, Head } from 'next/document'
|
||||||
import {FC} from "react";
|
import { FC } from 'react'
|
||||||
import Dict = NodeJS.Dict;
|
import Dict = NodeJS.Dict
|
||||||
|
|
||||||
const MyDocument: FC<DocumentProps> = ({ __NEXT_DATA__ }) => {
|
const MyDocument: FC<DocumentProps> = ({ __NEXT_DATA__ }) => {
|
||||||
const pageProps: Dict<unknown>|undefined = __NEXT_DATA__?.props?.pageProps;
|
const pageProps: Dict<unknown> | undefined = __NEXT_DATA__?.props?.pageProps
|
||||||
return (
|
return (
|
||||||
<Html>
|
<Html>
|
||||||
<Head />
|
<Head />
|
||||||
@@ -12,7 +12,7 @@ const MyDocument: FC<DocumentProps> = ({ __NEXT_DATA__ }) => {
|
|||||||
<NextScript />
|
<NextScript />
|
||||||
</body>
|
</body>
|
||||||
</Html>
|
</Html>
|
||||||
);
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export default MyDocument
|
export default MyDocument
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import {nextHandler} from "../../../src/utils/errors";
|
import { nextHandler } from '../../../src/utils/errors'
|
||||||
import {validate} from "../../../src/validation";
|
import { validate } from '../../../src/validation'
|
||||||
import {IdParam, SetFactoryArrayBody} from "../../../src/types/ApiSchemas";
|
import { IdParam, SetFactoryArrayBody } from '../../../src/types/ApiSchemas'
|
||||||
import {setFactories} from "../../../src/database/groups";
|
import { setFactories } from '../../../src/database/groups'
|
||||||
import {waitForInitSchemas} from "../../../src/validation/schemas";
|
import { waitForInitSchemas } from '../../../src/validation/schemas'
|
||||||
|
|
||||||
const handler = nextHandler(async (req, res) => {
|
const handler = nextHandler(async (req, res) => {
|
||||||
if (req.method !== 'POST') throw new Error('Invalid method')
|
if (req.method !== 'POST') throw new Error('Invalid method')
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import {nextHandler} from "../../../../../src/utils/errors";
|
import { nextHandler } from '../../../../../src/utils/errors'
|
||||||
import {validate} from "../../../../../src/validation";
|
import { validate } from '../../../../../src/validation'
|
||||||
import {GroupIdParam} from "../../../../../src/types/ApiSchemas";
|
import { GroupIdParam } from '../../../../../src/types/ApiSchemas'
|
||||||
import {addGroup} from "../../../../../src/database/groups";
|
import { addGroup } from '../../../../../src/database/groups'
|
||||||
import {waitForInitSchemas} from "../../../../../src/validation/schemas";
|
import { waitForInitSchemas } from '../../../../../src/validation/schemas'
|
||||||
|
|
||||||
const handler = nextHandler(async (req, res) => {
|
const handler = nextHandler(async (req, res) => {
|
||||||
if (req.method !== 'POST') throw new Error('Invalid method')
|
if (req.method !== 'POST') throw new Error('Invalid method')
|
||||||
|
|||||||
@@ -1,14 +1,17 @@
|
|||||||
import {nextHandler} from "../../../../../src/utils/errors";
|
import { nextHandler } from '../../../../../src/utils/errors'
|
||||||
import {validate} from "../../../../../src/validation";
|
import { validate } from '../../../../../src/validation'
|
||||||
import {GroupIdParam, GroupSetFactoryArrayBody} from "../../../../../src/types/ApiSchemas";
|
import { GroupIdParam, GroupSetFactoryArrayBody } from '../../../../../src/types/ApiSchemas'
|
||||||
import {setFactoriesOfGroup} from "../../../../../src/database/groups";
|
import { setFactoriesOfGroup } from '../../../../../src/database/groups'
|
||||||
import {waitForInitSchemas} from "../../../../../src/validation/schemas";
|
import { waitForInitSchemas } from '../../../../../src/validation/schemas'
|
||||||
|
|
||||||
const handler = nextHandler(async (req, res) => {
|
const handler = nextHandler(async (req, res) => {
|
||||||
if (req.method !== 'POST') throw new Error('Invalid method')
|
if (req.method !== 'POST') throw new Error('Invalid method')
|
||||||
await waitForInitSchemas.resolve()
|
await waitForInitSchemas.resolve()
|
||||||
const { transformed: params } = validate<GroupIdParam>(req.query, '/GroupIdParam')
|
const { transformed: params } = validate<GroupIdParam>(req.query, '/GroupIdParam')
|
||||||
const { transformed: body } = validate<GroupSetFactoryArrayBody>(req.body, '/GroupSetFactoryArrayBody')
|
const { transformed: body } = validate<GroupSetFactoryArrayBody>(
|
||||||
|
req.body,
|
||||||
|
'/GroupSetFactoryArrayBody'
|
||||||
|
)
|
||||||
|
|
||||||
const success = await setFactoriesOfGroup(params.id, params.name, body.type, body.factories)
|
const success = await setFactoriesOfGroup(params.id, params.name, body.type, body.factories)
|
||||||
res.json({ success })
|
res.json({ success })
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import {nextHandler} from "../../../../../src/utils/errors";
|
import { nextHandler } from '../../../../../src/utils/errors'
|
||||||
import {validate} from "../../../../../src/validation";
|
import { validate } from '../../../../../src/validation'
|
||||||
import {GroupIdParam} from "../../../../../src/types/ApiSchemas";
|
import { GroupIdParam } from '../../../../../src/types/ApiSchemas'
|
||||||
import {removeGroup} from "../../../../../src/database/groups";
|
import { removeGroup } from '../../../../../src/database/groups'
|
||||||
import {waitForInitSchemas} from "../../../../../src/validation/schemas";
|
import { waitForInitSchemas } from '../../../../../src/validation/schemas'
|
||||||
|
|
||||||
const handler = nextHandler(async (req, res) => {
|
const handler = nextHandler(async (req, res) => {
|
||||||
if (req.method !== 'POST') throw new Error('Invalid method')
|
if (req.method !== 'POST') throw new Error('Invalid method')
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
import {nextHandler} from "../../../../../src/utils/errors";
|
import { nextHandler } from '../../../../../src/utils/errors'
|
||||||
import {validate} from "../../../../../src/validation";
|
import { validate } from '../../../../../src/validation'
|
||||||
import {GroupIdParam, GroupRenameBody} from "../../../../../src/types/ApiSchemas";
|
import { GroupIdParam, GroupRenameBody } from '../../../../../src/types/ApiSchemas'
|
||||||
import {renameGroup} from "../../../../../src/database/groups";
|
import { renameGroup } from '../../../../../src/database/groups'
|
||||||
import {waitForInitSchemas} from "../../../../../src/validation/schemas";
|
import { waitForInitSchemas } from '../../../../../src/validation/schemas'
|
||||||
|
|
||||||
const handler = nextHandler(async (req, res) => {
|
const handler = nextHandler(async (req, res) => {
|
||||||
if (req.method !== 'POST') throw new Error('Invalid method')
|
if (req.method !== 'POST') throw new Error('Invalid method')
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
import {GroupData, setGroups} from "../../../src/database/groups";
|
import { NetworkError, nextHandler } from '../../../src/utils/errors'
|
||||||
import {NetworkError, nextHandler} from "../../../src/utils/errors";
|
import getConfig from 'next/config'
|
||||||
import getConfig from "next/config";
|
import { waitForInitSchemas } from '../../../src/validation/schemas'
|
||||||
import {addSchemas, waitForInitSchemas} from "../../../src/validation/schemas";
|
|
||||||
|
|
||||||
const {publicRuntimeConfig: {TENANT_TYPE}} = getConfig()
|
const {
|
||||||
|
publicRuntimeConfig: { TENANT_TYPE }
|
||||||
|
} = getConfig()
|
||||||
|
|
||||||
const handler = nextHandler(async (req, res) => {
|
const handler = nextHandler(async (req, res) => {
|
||||||
if (req.method !== 'GET') throw new NetworkError('Invalid method')
|
if (req.method !== 'GET') throw new NetworkError('Invalid method')
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {GroupData, setGroups} from "../../src/database/groups";
|
import { GroupData, setGroups } from '../../src/database/groups'
|
||||||
import {nextHandler} from "../../src/utils/errors";
|
import { nextHandler } from '../../src/utils/errors'
|
||||||
import {waitForInitSchemas} from "../../src/validation/schemas";
|
import { waitForInitSchemas } from '../../src/validation/schemas'
|
||||||
|
|
||||||
const handler = nextHandler(async (req, res) => {
|
const handler = nextHandler(async (req, res) => {
|
||||||
if (req.method !== 'POST') throw new Error('Invalid method')
|
if (req.method !== 'POST') throw new Error('Invalid method')
|
||||||
|
|||||||
@@ -1,23 +1,18 @@
|
|||||||
import type {GetServerSideProps, NextPage} from 'next'
|
import type { NextPage } from 'next'
|
||||||
import Head from 'next/head'
|
import Head from 'next/head'
|
||||||
import {Home} from "../components/home/Home";
|
import { Home } from '../components/home/Home'
|
||||||
import {useEffect} from "react";
|
import { GroupProvider } from '../components/contexts/GroupProvider'
|
||||||
import {GroupProvider} from "../components/contexts/GroupProvider";
|
import { getServerSidePropsGroupProvider, PropsGroupProvider } from '../src/getServerSideProps'
|
||||||
import {getGroup, setGroups} from "../src/database/groups";
|
|
||||||
import {Dict, Group} from "../src/types";
|
|
||||||
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../src/getServerSideProps";
|
|
||||||
|
|
||||||
|
const Page: NextPage<PropsGroupProvider> = ({ id, ...initial }) => {
|
||||||
|
|
||||||
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
|
|
||||||
return (
|
return (
|
||||||
<GroupProvider id={id} initial={initial}>
|
<GroupProvider id={id} initial={initial}>
|
||||||
<Head>
|
<Head>
|
||||||
<title>Factorio Microservices</title>
|
<title>Factorio Microservices</title>
|
||||||
<meta name="description" content="Create Factorio microservices" />
|
<meta name='description' content='Create Factorio microservices' />
|
||||||
<link rel="icon" href="/favicon.ico" />
|
<link rel='icon' href='/favicon.ico' />
|
||||||
</Head>
|
</Head>
|
||||||
<Home/>
|
<Home />
|
||||||
</GroupProvider>
|
</GroupProvider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,13 +1,12 @@
|
|||||||
import type { NextPage } from 'next'
|
import type { NextPage } from 'next'
|
||||||
import {GroupProvider} from "../../components/contexts/GroupProvider";
|
import { GroupProvider } from '../../components/contexts/GroupProvider'
|
||||||
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../../src/getServerSideProps";
|
import { getServerSidePropsGroupProvider, PropsGroupProvider } from '../../src/getServerSideProps'
|
||||||
import {PageDetails} from "../../components/visualize/PageDetails";
|
import { PageDetails } from '../../components/visualize/PageDetails'
|
||||||
|
|
||||||
|
const Page: NextPage<PropsGroupProvider> = ({ id, ...initial }) => {
|
||||||
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
|
|
||||||
return (
|
return (
|
||||||
<GroupProvider id={id} initial={initial}>
|
<GroupProvider id={id} initial={initial}>
|
||||||
<PageDetails/>
|
<PageDetails />
|
||||||
</GroupProvider>
|
</GroupProvider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,36 +1,31 @@
|
|||||||
import type {NextPage} from 'next'
|
import type { NextPage } from 'next'
|
||||||
import Head from 'next/head'
|
import Head from 'next/head'
|
||||||
import {GroupProvider, useGroups} from "../../components/contexts/GroupProvider";
|
import { GroupProvider, useGroups } from '../../components/contexts/GroupProvider'
|
||||||
import {useFactories} from "../../src/hooks/useFactories";
|
import { useFactories } from '../../src/hooks/useFactories'
|
||||||
import {ProducingGraph} from "../../components/shared/ProducingGraph/ProducingGraph";
|
import { ProducingGraph } from '../../components/shared/ProducingGraph/ProducingGraph'
|
||||||
import {useEffect, useMemo} from "react";
|
import { useEffect, useMemo } from 'react'
|
||||||
import {calculateInputs} from "../../src/calculateInputs";
|
import { calculateInputs } from '../../src/calculateInputs'
|
||||||
import {NodeOverview, OverviewGraphNode} from "../../components/visualize/NodeOverview/NodeOverview";
|
import {
|
||||||
import {fixedEncodeURIComponent} from "../../src/utils";
|
NodeOverview,
|
||||||
import {ScrollContainer} from "../../components/shared/ScrollContainer/ScrollContainer";
|
OverviewGraphNode
|
||||||
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../../src/getServerSideProps";
|
} from '../../components/visualize/NodeOverview/NodeOverview'
|
||||||
|
import { fixedEncodeURIComponent } from '../../src/utils'
|
||||||
|
import { ScrollContainer } from '../../components/shared/ScrollContainer/ScrollContainer'
|
||||||
|
import { getServerSidePropsGroupProvider, PropsGroupProvider } from '../../src/getServerSideProps'
|
||||||
|
|
||||||
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
|
const Page: NextPage<PropsGroupProvider> = ({ id, ...initial }) => {
|
||||||
const {
|
const { exportedFactories, baseFactories, groups } = useGroups()
|
||||||
exportedFactories,
|
const { findFactory } = useFactories()
|
||||||
ignoredFactories,
|
|
||||||
baseFactories,
|
|
||||||
groups
|
|
||||||
} = useGroups()
|
|
||||||
const {
|
|
||||||
findFactory
|
|
||||||
} = useFactories()
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
document.body.classList.add("scroll");
|
document.body.classList.add('scroll')
|
||||||
return () => document.body.classList.remove("scroll")
|
return () => document.body.classList.remove('scroll')
|
||||||
}, []);
|
}, [])
|
||||||
|
|
||||||
const producingNodes: OverviewGraphNode[] = useMemo(() => {
|
const producingNodes: OverviewGraphNode[] = useMemo(() => {
|
||||||
return Object.values(groups).map(group => ({
|
return Object.values(groups).map(group => ({
|
||||||
inputs: calculateInputs(
|
inputs: calculateInputs(
|
||||||
[...group.exports, ...group.malls],
|
[...group.exports, ...group.malls],
|
||||||
ignoredFactories,
|
|
||||||
baseFactories,
|
baseFactories,
|
||||||
exportedFactories,
|
exportedFactories,
|
||||||
findFactory
|
findFactory
|
||||||
@@ -40,19 +35,19 @@ const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
|
|||||||
icons: [...group.exports, ...group.malls],
|
icons: [...group.exports, ...group.malls],
|
||||||
linkOut: `./visualize/${fixedEncodeURIComponent(group.name)}`
|
linkOut: `./visualize/${fixedEncodeURIComponent(group.name)}`
|
||||||
}))
|
}))
|
||||||
}, [baseFactories, exportedFactories, findFactory, groups, ignoredFactories])
|
}, [baseFactories, exportedFactories, findFactory, groups])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<GroupProvider id={id} initial={initial}>
|
<GroupProvider id={id} initial={initial}>
|
||||||
<Head>
|
<Head>
|
||||||
<title>Factorio Microservices</title>
|
<title>Factorio Microservices</title>
|
||||||
<meta name="description" content="Create Factorio microservices" />
|
<meta name='description' content='Create Factorio microservices' />
|
||||||
<link rel="icon" href="/public/favicon.ico" />
|
<link rel='icon' href='/public/favicon.ico' />
|
||||||
</Head>
|
</Head>
|
||||||
<main>
|
<main>
|
||||||
<ScrollContainer>
|
<ScrollContainer>
|
||||||
<h1>Factorio Microservices</h1>
|
<h1>Factorio Microservices</h1>
|
||||||
<ProducingGraph nodes={producingNodes} inputs={baseFactories} childType={NodeOverview}/>
|
<ProducingGraph nodes={producingNodes} inputs={baseFactories} childType={NodeOverview} />
|
||||||
</ScrollContainer>
|
</ScrollContainer>
|
||||||
</main>
|
</main>
|
||||||
</GroupProvider>
|
</GroupProvider>
|
||||||
|
|||||||
File diff suppressed because one or more lines are too long
@@ -1,20 +1,24 @@
|
|||||||
import {EnrichedEntity} from "./types";
|
import { EnrichedEntity } from './types'
|
||||||
|
|
||||||
export const calculateInputs = (allProducingFactories: string[], ignoredFactories: string[], baseFactories: string[], exportedFactories: Set<string>, findFactory: (uid: string) => EnrichedEntity|undefined) => {
|
export const calculateInputs = (
|
||||||
const prducingSet = new Set(allProducingFactories)
|
allProducingFactories: string[],
|
||||||
const ignored = new Set(ignoredFactories)
|
baseFactories: string[],
|
||||||
|
exportedFactories: Set<string>,
|
||||||
|
findFactory: (uid: string) => EnrichedEntity | undefined
|
||||||
|
) => {
|
||||||
|
const producingSet = new Set(allProducingFactories)
|
||||||
const base = new Set(baseFactories)
|
const base = new Set(baseFactories)
|
||||||
const inputs = new Set<string>()
|
const inputs = new Set<string>()
|
||||||
const intermediates = new Set<string>()
|
const intermediates = new Set<string>()
|
||||||
|
|
||||||
let next: string|undefined
|
let next: string | undefined
|
||||||
while (next = allProducingFactories.pop()) {
|
while ((next = allProducingFactories.pop())) {
|
||||||
const pres = Object.keys(findFactory(next)?.recipe?.prerequisites ?? {})
|
const pres = Object.keys(findFactory(next)?.recipe?.prerequisites ?? {})
|
||||||
for (const pre of pres) {
|
for (const pre of pres) {
|
||||||
if (exportedFactories.has(pre) || base.has(pre)) {
|
if (exportedFactories.has(pre) || base.has(pre)) {
|
||||||
if (!prducingSet.has(pre)) inputs.add(pre)
|
if (!producingSet.has(pre)) inputs.add(pre)
|
||||||
} else if (!intermediates.has(pre)) {
|
} else if (!intermediates.has(pre)) {
|
||||||
if (!prducingSet.has(pre)) intermediates.add(pre)
|
if (!producingSet.has(pre)) intermediates.add(pre)
|
||||||
allProducingFactories.push(pre)
|
allProducingFactories.push(pre)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,22 +1,22 @@
|
|||||||
import {database} from "./start";
|
import { database } from './start'
|
||||||
import {Dict, Group} from "../types";
|
import { Dict, Group } from '../types'
|
||||||
import {Filter, ObjectId} from "mongodb";
|
import { Filter, ObjectId } from 'mongodb'
|
||||||
|
|
||||||
export interface GroupData {
|
export interface GroupData {
|
||||||
groups: Dict<Group>,
|
groups: Dict<Group>
|
||||||
ignored: string[],
|
ignored: string[]
|
||||||
base: string[]
|
base: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export type InsertMeta<T> = T & {
|
export type InsertMeta<T> = T & {
|
||||||
createdOn: Date,
|
createdOn: Date
|
||||||
modifiedOn: Date,
|
modifiedOn: Date
|
||||||
accessedOn: Date
|
accessedOn: Date
|
||||||
}
|
}
|
||||||
|
|
||||||
type GroupFilter = Filter<InsertMeta<GroupData>>
|
type GroupFilter = Filter<InsertMeta<GroupData>>
|
||||||
|
|
||||||
export async function setGroups(data: GroupData): Promise<string|undefined> {
|
export async function setGroups(data: GroupData): Promise<string | undefined> {
|
||||||
const collection = (await database.resolve())?.collection('setups')
|
const collection = (await database.resolve())?.collection('setups')
|
||||||
if (!collection) return
|
if (!collection) return
|
||||||
const result = await collection.insertOne({
|
const result = await collection.insertOne({
|
||||||
@@ -25,7 +25,6 @@ export async function setGroups(data: GroupData): Promise<string|undefined> {
|
|||||||
modifiedOn: new Date(),
|
modifiedOn: new Date(),
|
||||||
accessedOn: new Date()
|
accessedOn: new Date()
|
||||||
})
|
})
|
||||||
console.log(result.insertedId, result.insertedId.toString())
|
|
||||||
return result.insertedId.toString()
|
return result.insertedId.toString()
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -35,38 +34,48 @@ function getUuid(uuid: string): GroupFilter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setFactories(uuid: string, type: 'ignored'|'base', factories: string[]): Promise<boolean> {
|
export async function setFactories(
|
||||||
|
uuid: string,
|
||||||
|
type: 'ignored' | 'base',
|
||||||
|
factories: string[]
|
||||||
|
): Promise<boolean> {
|
||||||
const collection = (await database.resolve())?.collection('setups')
|
const collection = (await database.resolve())?.collection('setups')
|
||||||
if (!collection) return false
|
if (!collection) return false
|
||||||
collection.updateOne(getUuid(uuid), {$set: {[type]: factories} as never})
|
collection.updateOne(getUuid(uuid), { $set: { [type]: factories } as never })
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
export async function getGroup(uuid: string) {
|
export async function getGroup(uuid: string) {
|
||||||
const collection = (await database.resolve())?.collection('setups')
|
const collection = (await database.resolve())?.collection('setups')
|
||||||
if (!collection) return
|
if (!collection) return
|
||||||
const data = (await collection.findOne(getUuid(uuid))) ?? undefined
|
const data = (await collection.findOne(getUuid(uuid))) ?? undefined
|
||||||
if (data) {
|
if (data) {
|
||||||
await collection.updateOne(getUuid(uuid), { $set: {accessedOn: new Date()}})
|
await collection.updateOne(getUuid(uuid), { $set: { accessedOn: new Date() } })
|
||||||
}
|
}
|
||||||
return data
|
return data
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function renameGroup(uuid: string, oldName: string, newName: string): Promise<boolean> {
|
export async function renameGroup(
|
||||||
|
uuid: string,
|
||||||
|
oldName: string,
|
||||||
|
newName: string
|
||||||
|
): Promise<boolean> {
|
||||||
oldName = oldName.replace(/[.$]/g, '')
|
oldName = oldName.replace(/[.$]/g, '')
|
||||||
newName = newName.replace(/[.$]/g, '')
|
newName = newName.replace(/[.$]/g, '')
|
||||||
const data = await getGroup(uuid)
|
const data = await getGroup(uuid)
|
||||||
if (data?.groups && !(newName in data.groups)) {
|
if (data?.groups && !(newName in data.groups)) {
|
||||||
const collection = (await database.resolve())?.collection('setups')
|
const collection = (await database.resolve())?.collection('setups')
|
||||||
console.log("fere", `groups.${oldName}`, `groups.${newName}`)
|
|
||||||
if (!collection) return false
|
if (!collection) return false
|
||||||
await collection.updateOne(getUuid(uuid), { $set: {
|
await collection.updateOne(getUuid(uuid), {
|
||||||
|
$set: {
|
||||||
[`groups.${oldName}.name`]: newName
|
[`groups.${oldName}.name`]: newName
|
||||||
} as never})
|
} as never
|
||||||
await collection.updateOne(getUuid(uuid), { $rename: {
|
})
|
||||||
|
await collection.updateOne(getUuid(uuid), {
|
||||||
|
$rename: {
|
||||||
[`groups.${oldName}`]: `groups.${newName}`
|
[`groups.${oldName}`]: `groups.${newName}`
|
||||||
}})
|
}
|
||||||
|
})
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
@@ -78,7 +87,9 @@ export async function addGroup(uuid: string, name: string): Promise<boolean> {
|
|||||||
if (data?.groups && !(name in data.groups)) {
|
if (data?.groups && !(name in data.groups)) {
|
||||||
const collection = (await database.resolve())?.collection('setups')
|
const collection = (await database.resolve())?.collection('setups')
|
||||||
if (!collection) return false
|
if (!collection) return false
|
||||||
await collection.updateOne(getUuid(uuid), {$set: {[`groups.${name}`]: {name, exports: [], malls: []} as never}})
|
await collection.updateOne(getUuid(uuid), {
|
||||||
|
$set: { [`groups.${name}`]: { name, exports: [], malls: [] } as never }
|
||||||
|
})
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
@@ -90,20 +101,26 @@ export async function removeGroup(uuid: string, name: string): Promise<boolean>
|
|||||||
if (data?.groups && name in data.groups) {
|
if (data?.groups && name in data.groups) {
|
||||||
const collection = (await database.resolve())?.collection('setups')
|
const collection = (await database.resolve())?.collection('setups')
|
||||||
if (!collection) return false
|
if (!collection) return false
|
||||||
console.log(`groups.${name}`)
|
await collection.updateOne(getUuid(uuid), { $unset: { [`groups.${name}`]: '' } })
|
||||||
await collection.updateOne(getUuid(uuid), {$unset: {[`groups.${name}`]: ""}})
|
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function setFactoriesOfGroup(uuid: string, name: string, type: 'exports'|'malls', factories: string[]): Promise<boolean> {
|
export async function setFactoriesOfGroup(
|
||||||
|
uuid: string,
|
||||||
|
name: string,
|
||||||
|
type: 'exports' | 'malls',
|
||||||
|
factories: string[]
|
||||||
|
): Promise<boolean> {
|
||||||
name = name.replace(/[.$]/g, '')
|
name = name.replace(/[.$]/g, '')
|
||||||
const data = await getGroup(uuid)
|
const data = await getGroup(uuid)
|
||||||
if (data?.groups && (name in data.groups)) {
|
if (data?.groups && name in data.groups) {
|
||||||
const collection = (await database.resolve())?.collection('setups')
|
const collection = (await database.resolve())?.collection('setups')
|
||||||
if (!collection) return false
|
if (!collection) return false
|
||||||
await collection.updateOne(getUuid(uuid), {$set: {[`groups.${name}.${type}`]: factories} as never})
|
await collection.updateOne(getUuid(uuid), {
|
||||||
|
$set: { [`groups.${name}.${type}`]: factories } as never
|
||||||
|
})
|
||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
return false
|
return false
|
||||||
|
|||||||
@@ -1,23 +1,21 @@
|
|||||||
import {Collection, Db, MongoClient} from 'mongodb'
|
import { Collection, Db, MongoClient } from 'mongodb'
|
||||||
import getConfig from 'next/config'
|
import getConfig from 'next/config'
|
||||||
import {Resolvable} from "../utils/Resolvable";
|
import { Resolvable } from '../utils/Resolvable'
|
||||||
import {GroupData, InsertMeta} from "./groups";
|
import { GroupData, InsertMeta } from './groups'
|
||||||
|
import { logger } from '../utils/logger'
|
||||||
|
|
||||||
const { serverRuntimeConfig: {
|
const {
|
||||||
MONGO_URL,
|
serverRuntimeConfig: { MONGO_URL, MONGO_USER, MONGO_PASS, MONGO_DB }
|
||||||
MONGO_USER,
|
} = getConfig()
|
||||||
MONGO_PASS,
|
|
||||||
MONGO_DB
|
|
||||||
} } = getConfig()
|
|
||||||
|
|
||||||
async function getDatabase() {
|
async function getDatabase() {
|
||||||
const url = `mongodb://${MONGO_USER ? `${MONGO_USER}:${MONGO_PASS ?? ''}@` : ''}${MONGO_URL}`;
|
const url = `mongodb://${MONGO_USER ? `${MONGO_USER}:${MONGO_PASS ?? ''}@` : ''}${MONGO_URL}`
|
||||||
const client = new MongoClient(url);
|
const client = new MongoClient(url)
|
||||||
await client.connect();
|
await client.connect()
|
||||||
console.log('Connected successfully to server')
|
logger.info('Connected successfully to server')
|
||||||
return client.db(MONGO_DB) as unknown as (Omit<Db, 'collection'> & {
|
return client.db(MONGO_DB) as unknown as Omit<Db, 'collection'> & {
|
||||||
collection : (_: 'setups') => Collection<InsertMeta<GroupData>>
|
collection: (_: 'setups') => Collection<InsertMeta<GroupData>>
|
||||||
})
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export const database = new Resolvable(getDatabase)
|
export const database = new Resolvable(getDatabase)
|
||||||
|
|||||||
@@ -1,29 +1,30 @@
|
|||||||
export function download(filename: string, data: Uint8Array) {
|
export function download(filename: string, data: Uint8Array) {
|
||||||
const tag = document.createElement("a");
|
const tag = document.createElement('a')
|
||||||
tag.style.display = "none";
|
tag.style.display = 'none'
|
||||||
document.body.appendChild(tag);
|
document.body.appendChild(tag)
|
||||||
const blob = new Blob([data], {type: "octet/stream"}),
|
const blob = new Blob([data], { type: 'octet/stream' }),
|
||||||
url = window.URL.createObjectURL(blob);
|
url = window.URL.createObjectURL(blob)
|
||||||
tag.href = url;
|
tag.href = url
|
||||||
tag.download = filename;
|
tag.download = filename
|
||||||
tag.click();
|
tag.click()
|
||||||
window.URL.revokeObjectURL(url);
|
window.URL.revokeObjectURL(url)
|
||||||
document.body.removeChild(tag);
|
document.body.removeChild(tag)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function streamToArrayBuffer(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
|
export async function streamToArrayBuffer(stream: ReadableStream<Uint8Array>): Promise<Uint8Array> {
|
||||||
let result = new Uint8Array(0);
|
let result = new Uint8Array(0)
|
||||||
const reader = stream.getReader();
|
const reader = stream.getReader()
|
||||||
while (true) { // eslint-disable-line no-constant-condition
|
while (true) {
|
||||||
const { done, value } = await reader.read();
|
// eslint-disable-line no-constant-condition
|
||||||
|
const { done, value } = await reader.read()
|
||||||
if (done) {
|
if (done) {
|
||||||
break;
|
break
|
||||||
}
|
}
|
||||||
|
|
||||||
const newResult = new Uint8Array(result.length + value.length);
|
const newResult = new Uint8Array(result.length + value.length)
|
||||||
newResult.set(result);
|
newResult.set(result)
|
||||||
newResult.set(value, result.length);
|
newResult.set(value, result.length)
|
||||||
result = newResult
|
result = newResult
|
||||||
}
|
}
|
||||||
return result;
|
return result
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import {GetServerSideProps} from "next";
|
import { GetServerSideProps } from 'next'
|
||||||
import {getGroup, setGroups} from "./database/groups";
|
import { getGroup, setGroups } from './database/groups'
|
||||||
import {Dict, Group} from "./types";
|
import { Dict, Group } from './types'
|
||||||
|
|
||||||
export interface PropsGroupProvider {
|
export interface PropsGroupProvider {
|
||||||
id: string
|
id: string
|
||||||
@@ -9,9 +9,11 @@ export interface PropsGroupProvider {
|
|||||||
base: string[]
|
base: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvider> = async ({query}) => {
|
export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvider> = async ({
|
||||||
|
query
|
||||||
|
}) => {
|
||||||
const id = Array.isArray(query?.id) ? query.id[0] : query?.id
|
const id = Array.isArray(query?.id) ? query.id[0] : query?.id
|
||||||
const data = id && await getGroup(id)
|
const data = id && (await getGroup(id))
|
||||||
if (data) {
|
if (data) {
|
||||||
return {
|
return {
|
||||||
props: {
|
props: {
|
||||||
@@ -22,15 +24,14 @@ export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvi
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else if (!id) {
|
} else if (!id) {
|
||||||
const newId = await setGroups({groups: {}, base: [], ignored: []})
|
const newId = await setGroups({ groups: {}, base: [], ignored: [] })
|
||||||
return {
|
return {
|
||||||
redirect: {
|
redirect: {
|
||||||
destination: `?id=${newId}`,
|
destination: `?id=${newId}`,
|
||||||
permanent: false,
|
permanent: false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
console.log(data)
|
|
||||||
return {
|
return {
|
||||||
notFound: true
|
notFound: true
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,31 +1,48 @@
|
|||||||
import {AdditionalNode, GraphNode, GraphNodeWithIds, isAdditionalNode} from "./types";
|
import { AdditionalNode, GraphNode, GraphNodeWithIds } from './types'
|
||||||
import {Dict} from "../types";
|
import { Dict } from '../types'
|
||||||
import deepcopy from "deepcopy";
|
import deepcopy from 'deepcopy'
|
||||||
import {isNonNullable, shuffleInplace, sortByProperty, uniquify} from "../utils";
|
import { isNonNullable, shuffleInplace, sortByProperty, uniquify } from '../utils'
|
||||||
import seedrandom from "seedrandom";
|
import seedrandom from 'seedrandom'
|
||||||
|
|
||||||
function generateIds<T extends Dict<unknown>>(node: GraphNode<T>, nodeUid: () => string): GraphNodeWithIds<T> {
|
function generateIds<T extends Dict<unknown>>(
|
||||||
|
node: GraphNode<T>,
|
||||||
|
nodeUid: () => string
|
||||||
|
): GraphNodeWithIds<T> {
|
||||||
return {
|
return {
|
||||||
...node,
|
...node,
|
||||||
___uid: `${node.name.replace(/[^a-z]/gi, '').toLowerCase().substring(0, 3)}_${nodeUid()}`,
|
___uid: `${node.name
|
||||||
|
.replace(/[^a-z]/gi, '')
|
||||||
|
.toLowerCase()
|
||||||
|
.substring(0, 3)}_${nodeUid()}`,
|
||||||
___uidInputs: [],
|
___uidInputs: [],
|
||||||
___uidOutputs: []
|
___uidOutputs: []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function generateAdditional<T extends Dict<unknown>>(uid: string, type: 'i'|'h'|'o', nodeUid: () => string): GraphNodeWithIds<AdditionalNode> {
|
function generateAdditional(
|
||||||
|
uid: string,
|
||||||
|
type: 'i' | 'h' | 'o',
|
||||||
|
nodeUid: () => string
|
||||||
|
): GraphNodeWithIds<AdditionalNode> {
|
||||||
return {
|
return {
|
||||||
inputs: type !== 'i' ? [uid] : [],
|
inputs: type !== 'i' ? [uid] : [],
|
||||||
outputs: type !== 'o' ? [uid] : [],
|
outputs: type !== 'o' ? [uid] : [],
|
||||||
name: uid,
|
name: uid,
|
||||||
___type: type,
|
___type: type,
|
||||||
___uid: `${uid.replace(/[^a-z]/gi, '').toLowerCase().substring(0, 3)}_${nodeUid()}_${type}`,
|
___uid: `${uid
|
||||||
|
.replace(/[^a-z]/gi, '')
|
||||||
|
.toLowerCase()
|
||||||
|
.substring(0, 3)}_${nodeUid()}_${type}`,
|
||||||
___uidInputs: [],
|
___uidInputs: [],
|
||||||
___uidOutputs: []
|
___uidOutputs: []
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNode<T>[], nodeUid: () => string): [string[][], Dict<GraphNodeWithIds<T>>] {
|
function splitIntoRows<T extends Dict<unknown>>(
|
||||||
|
inputs: string[],
|
||||||
|
nodes: GraphNode<T>[],
|
||||||
|
nodeUid: () => string
|
||||||
|
): [string[][], Dict<GraphNodeWithIds<T>>] {
|
||||||
const nodesWithId: Dict<GraphNodeWithIds<T>> = {}
|
const nodesWithId: Dict<GraphNodeWithIds<T>> = {}
|
||||||
const available = new Set(inputs)
|
const available = new Set(inputs)
|
||||||
let queue = [...nodes]
|
let queue = [...nodes]
|
||||||
@@ -35,7 +52,7 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
|
|||||||
const availableOfRow: string[] = []
|
const availableOfRow: string[] = []
|
||||||
rows.push([])
|
rows.push([])
|
||||||
|
|
||||||
queue = queue.filter((node) => {
|
queue = queue.filter(node => {
|
||||||
const isPlaceable = node.inputs.every(input => available.has(input))
|
const isPlaceable = node.inputs.every(input => available.has(input))
|
||||||
if (isPlaceable) {
|
if (isPlaceable) {
|
||||||
const nodeWithId: GraphNodeWithIds<T> = generateIds(node, nodeUid)
|
const nodeWithId: GraphNodeWithIds<T> = generateIds(node, nodeUid)
|
||||||
@@ -48,7 +65,7 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
|
|||||||
availableOfRow.map(uid => available.add(uid))
|
availableOfRow.map(uid => available.add(uid))
|
||||||
|
|
||||||
if (amount === queue.length) {
|
if (amount === queue.length) {
|
||||||
console.warn("Loop detected! Left over:", queue)
|
console.warn('Loop detected! Left over:', queue)
|
||||||
rows.pop()
|
rows.pop()
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
@@ -56,78 +73,123 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
|
|||||||
return [rows, nodesWithId]
|
return [rows, nodesWithId]
|
||||||
}
|
}
|
||||||
|
|
||||||
function addAdditionalNodes<T extends Dict<unknown>>(rowsRaw: string[][], nodesRaw: Dict<GraphNodeWithIds<T>>, inputs: string[], outputs: string[], nodeUid: () => string): [string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>] {
|
function addAdditionalNodes<T extends Dict<unknown>>(
|
||||||
|
rowsRaw: string[][],
|
||||||
|
nodesRaw: Dict<GraphNodeWithIds<T>>,
|
||||||
|
inputs: string[],
|
||||||
|
outputs: string[],
|
||||||
|
nodeUid: () => string
|
||||||
|
): [string[][], Dict<GraphNodeWithIds<T | AdditionalNode>>] {
|
||||||
const addedInputs: Dict<number> = {}
|
const addedInputs: Dict<number> = {}
|
||||||
const res: string[][] = deepcopy([[], ...rowsRaw, []])
|
const res: string[][] = deepcopy([[], ...rowsRaw, []])
|
||||||
const resNodes: Dict<GraphNodeWithIds<T|AdditionalNode>> = deepcopy(nodesRaw)
|
const resNodes: Dict<GraphNodeWithIds<T | AdditionalNode>> = deepcopy(nodesRaw)
|
||||||
for (let i = 0; i < rowsRaw.length; i++) {
|
for (let i = 0; i < rowsRaw.length; i++) {
|
||||||
const rowInputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].inputs))
|
const rowInputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].inputs))
|
||||||
for (let rowInput of rowInputs) {
|
for (const rowInput of rowInputs) {
|
||||||
if (rowInput in addedInputs) {
|
if (rowInput in addedInputs) {
|
||||||
for (let j = addedInputs[rowInput]+1; j < i+1; j++) {
|
for (let j = addedInputs[rowInput] + 1; j < i + 1; j++) {
|
||||||
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowInput, 'h', nodeUid)
|
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(
|
||||||
|
rowInput,
|
||||||
|
'h',
|
||||||
|
nodeUid
|
||||||
|
)
|
||||||
res[j].push(nodeWithId.___uid)
|
res[j].push(nodeWithId.___uid)
|
||||||
resNodes[nodeWithId.___uid] = nodeWithId
|
resNodes[nodeWithId.___uid] = nodeWithId
|
||||||
}
|
}
|
||||||
addedInputs[rowInput] = i
|
addedInputs[rowInput] = i
|
||||||
} else if (inputs.includes(rowInput)) {
|
} else if (inputs.includes(rowInput)) {
|
||||||
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowInput, 'i', nodeUid)
|
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(
|
||||||
|
rowInput,
|
||||||
|
'i',
|
||||||
|
nodeUid
|
||||||
|
)
|
||||||
res[i].push(nodeWithId.___uid)
|
res[i].push(nodeWithId.___uid)
|
||||||
resNodes[nodeWithId.___uid] = nodeWithId
|
resNodes[nodeWithId.___uid] = nodeWithId
|
||||||
addedInputs[rowInput] = i
|
addedInputs[rowInput] = i
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
const rowOutputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].outputs))
|
const rowOutputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].outputs))
|
||||||
for (let rowOutput of rowOutputs) {
|
for (const rowOutput of rowOutputs) {
|
||||||
if (outputs?.includes(rowOutput)) {
|
if (outputs?.includes(rowOutput)) {
|
||||||
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowOutput, 'o', nodeUid)
|
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(
|
||||||
res[i+2].push(nodeWithId.___uid)
|
rowOutput,
|
||||||
|
'o',
|
||||||
|
nodeUid
|
||||||
|
)
|
||||||
|
res[i + 2].push(nodeWithId.___uid)
|
||||||
resNodes[nodeWithId.___uid] = nodeWithId
|
resNodes[nodeWithId.___uid] = nodeWithId
|
||||||
}
|
}
|
||||||
addedInputs[rowOutput] = i+1
|
addedInputs[rowOutput] = i + 1
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (res[res.length-1].length === 0) res.splice(res.length-1, 1)
|
if (res[res.length - 1].length === 0) res.splice(res.length - 1, 1)
|
||||||
return [res, resNodes]
|
return [res, resNodes]
|
||||||
}
|
}
|
||||||
|
|
||||||
function linkNodes<T extends Dict<unknown>>(rowsWithInOut: string[][], nodesWithInOut: Dict<GraphNodeWithIds<T|AdditionalNode>>): Dict<GraphNodeWithIds<T|AdditionalNode>> {
|
function linkNodes<T extends Dict<unknown>>(
|
||||||
type Store = {input: Dict<string[]>[], output: Dict<string[]>[]}
|
rowsWithInOut: string[][],
|
||||||
|
nodesWithInOut: Dict<GraphNodeWithIds<T | AdditionalNode>>
|
||||||
|
): Dict<GraphNodeWithIds<T | AdditionalNode>> {
|
||||||
|
type Store = { input: Dict<string[]>[], output: Dict<string[]>[] }
|
||||||
|
|
||||||
const store: Store = {
|
const store: Store = {
|
||||||
input: Array.from(rowsWithInOut, Object),
|
input: Array.from(rowsWithInOut, Object),
|
||||||
output: Array.from(rowsWithInOut, Object)
|
output: Array.from(rowsWithInOut, Object)
|
||||||
}
|
}
|
||||||
const nodesPremapping = (node: GraphNodeWithIds<T|AdditionalNode>, rowIdx: number) => {
|
const nodesPremapping = (node: GraphNodeWithIds<T | AdditionalNode>, rowIdx: number) => {
|
||||||
node.inputs.forEach(input => store.input[rowIdx][input] = [...(store.input[rowIdx][input] ?? []), node.___uid])
|
node.inputs.forEach(
|
||||||
node.outputs.forEach(output => store.output[rowIdx][output] = [...(store.output[rowIdx][output] ?? []), node.___uid])
|
input => (store.input[rowIdx][input] = [...(store.input[rowIdx][input] ?? []), node.___uid])
|
||||||
};
|
)
|
||||||
const linkInOut = (node: GraphNodeWithIds<T|AdditionalNode>, rowIdx: number) => {
|
node.outputs.forEach(
|
||||||
|
output =>
|
||||||
|
(store.output[rowIdx][output] = [...(store.output[rowIdx][output] ?? []), node.___uid])
|
||||||
|
)
|
||||||
|
}
|
||||||
|
const linkInOut = (node: GraphNodeWithIds<T | AdditionalNode>, rowIdx: number) => {
|
||||||
if (rowIdx > 0)
|
if (rowIdx > 0)
|
||||||
node.___uidInputs = uniquify(node.inputs.flatMap(input => store.output[rowIdx - 1][input]).filter(isNonNullable))
|
node.___uidInputs = uniquify(
|
||||||
if (rowIdx < rowsWithInOut.length-1)
|
node.inputs.flatMap(input => store.output[rowIdx - 1][input]).filter(isNonNullable)
|
||||||
node.___uidOutputs = uniquify(node.outputs.flatMap(output => store.input[rowIdx + 1][output]).filter(isNonNullable))
|
)
|
||||||
};
|
if (rowIdx < rowsWithInOut.length - 1)
|
||||||
|
node.___uidOutputs = uniquify(
|
||||||
|
node.outputs.flatMap(output => store.input[rowIdx + 1][output]).filter(isNonNullable)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
rowsWithInOut.forEach((row, rowIdx) => row.forEach(uid => nodesPremapping(nodesWithInOut[uid], rowIdx)))
|
rowsWithInOut.forEach((row, rowIdx) =>
|
||||||
|
row.forEach(uid => nodesPremapping(nodesWithInOut[uid], rowIdx))
|
||||||
|
)
|
||||||
rowsWithInOut.forEach((row, rowIdx) => row.forEach(uid => linkInOut(nodesWithInOut[uid], rowIdx)))
|
rowsWithInOut.forEach((row, rowIdx) => row.forEach(uid => linkInOut(nodesWithInOut[uid], rowIdx)))
|
||||||
return nodesWithInOut
|
return nodesWithInOut
|
||||||
}
|
}
|
||||||
|
|
||||||
function crossingsOf<T extends Dict<unknown>>(fixed: string[], flex: string[], nodes: Dict<GraphNodeWithIds<T|AdditionalNode>>, isDown: boolean): [number[][], number] {
|
function crossingsOf<T extends Dict<unknown>>(
|
||||||
|
fixed: string[],
|
||||||
|
flex: string[],
|
||||||
|
nodes: Dict<GraphNodeWithIds<T | AdditionalNode>>,
|
||||||
|
isDown: boolean
|
||||||
|
): [number[][], number] {
|
||||||
const result = Array.from(flex, () => Array.from(flex, () => 9999999))
|
const result = Array.from(flex, () => Array.from(flex, () => 9999999))
|
||||||
let score = 0
|
let score = 0
|
||||||
for (let i = 0; i < flex.length-1; i++) {
|
for (let i = 0; i < flex.length - 1; i++) {
|
||||||
for (let j = i+1; j < flex.length; j++) {
|
for (let j = i + 1; j < flex.length; j++) {
|
||||||
const inputsI = new Set(nodes[flex[i]][isDown ? '___uidInputs' : '___uidOutputs'])
|
const inputsI = new Set(nodes[flex[i]][isDown ? '___uidInputs' : '___uidOutputs'])
|
||||||
const inputsJ = new Set(nodes[flex[j]][isDown ? '___uidInputs' : '___uidOutputs'])
|
const inputsJ = new Set(nodes[flex[j]][isDown ? '___uidInputs' : '___uidOutputs'])
|
||||||
const diff = fixed.reduce(([size, acc], curr) => {
|
const diff =
|
||||||
|
fixed.reduce(
|
||||||
|
([size, acc], curr) => {
|
||||||
inputsI.has(curr) && size--
|
inputsI.has(curr) && size--
|
||||||
return [size, acc + (inputsJ.has(curr) ? size : 0)]
|
return [size, acc + (inputsJ.has(curr) ? size : 0)]
|
||||||
}, [inputsI.size, 0])[1] - fixed.reduce(([size, acc], curr) => {
|
},
|
||||||
|
[inputsI.size, 0]
|
||||||
|
)[1] -
|
||||||
|
fixed.reduce(
|
||||||
|
([size, acc], curr) => {
|
||||||
inputsJ.has(curr) && size--
|
inputsJ.has(curr) && size--
|
||||||
return [size, acc + (inputsI.has(curr) ? size : 0)]
|
return [size, acc + (inputsI.has(curr) ? size : 0)]
|
||||||
}, [inputsJ.size, 0])[1]
|
},
|
||||||
|
[inputsJ.size, 0]
|
||||||
|
)[1]
|
||||||
result[i][j] = diff
|
result[i][j] = diff
|
||||||
result[j][i] = -diff
|
result[j][i] = -diff
|
||||||
score += diff
|
score += diff
|
||||||
@@ -136,82 +198,102 @@ function crossingsOf<T extends Dict<unknown>>(fixed: string[], flex: string[], n
|
|||||||
return [result, score]
|
return [result, score]
|
||||||
}
|
}
|
||||||
|
|
||||||
function optimizeOrder<T extends Dict<unknown>>(rowsWithInOut: string[][], nodesWithInOut: Dict<GraphNodeWithIds<T|AdditionalNode>>): [string[][], number] {
|
function optimizeOrder<T extends Dict<unknown>>(
|
||||||
|
rowsWithInOut: string[][],
|
||||||
function addCosts(costsUp: [number[][], number], costsDown: [number[][], number]): [number[][], number] {
|
nodesWithInOut: Dict<GraphNodeWithIds<T | AdditionalNode>>
|
||||||
|
): [string[][], number] {
|
||||||
|
function addCosts(
|
||||||
|
costsUp: [number[][], number],
|
||||||
|
costsDown: [number[][], number]
|
||||||
|
): [number[][], number] {
|
||||||
return [
|
return [
|
||||||
costsUp[0].map((row, rowIdx) => row.map((col, colIdx) => col+costsDown[0][rowIdx][colIdx])),
|
costsUp[0].map((row, rowIdx) => row.map((col, colIdx) => col + costsDown[0][rowIdx][colIdx])),
|
||||||
costsUp[1] + costsDown[1]
|
costsUp[1] + costsDown[1]
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
|
|
||||||
function improveRow(top: string[]|undefined, mid: string[], bot: string[]|undefined) {
|
function improveRow(top: string[] | undefined, mid: string[], bot: string[] | undefined) {
|
||||||
const costsUp = top ? crossingsOf(top, mid, nodesWithInOut, true) : undefined
|
const costsUp = top ? crossingsOf(top, mid, nodesWithInOut, true) : undefined
|
||||||
const costsDown = bot ? crossingsOf(bot, mid, nodesWithInOut, false) : undefined
|
const costsDown = bot ? crossingsOf(bot, mid, nodesWithInOut, false) : undefined
|
||||||
const [costs, scoreConst] = costsUp && costsDown ? addCosts(costsUp, costsDown) : costsDown ?? costsUp ?? [undefined, 0]
|
const [costs, scoreConst] =
|
||||||
|
costsUp && costsDown ? addCosts(costsUp, costsDown) : costsDown ?? costsUp ?? [undefined, 0]
|
||||||
let score = scoreConst
|
let score = scoreConst
|
||||||
if (!costs) return score
|
if (!costs) return score
|
||||||
let improvementInRow = true
|
let improvementInRow = true
|
||||||
while (improvementInRow) {
|
while (improvementInRow) {
|
||||||
improvementInRow = false
|
improvementInRow = false
|
||||||
const colBest = costs
|
const colBest = costs
|
||||||
.map((_, idx) => costs
|
.map(
|
||||||
|
(_, idx) =>
|
||||||
|
costs
|
||||||
.slice(0, idx)
|
.slice(0, idx)
|
||||||
.map(r => r[idx])
|
.map(r => r[idx])
|
||||||
.reverse()
|
.reverse()
|
||||||
.reduce(([sum, best], curr, i) => {
|
.reduce(
|
||||||
|
([sum, best], curr, i) => {
|
||||||
return sum + curr > best.sum
|
return sum + curr > best.sum
|
||||||
? [sum + curr, {sum: sum+curr, move: -i-1, idx}] as const
|
? ([sum + curr, { sum: sum + curr, move: -i - 1, idx }] as const)
|
||||||
: [sum + curr, best] as const
|
: ([sum + curr, best] as const)
|
||||||
}, [0, {sum: -10000, move: 0, idx: 0}] as readonly [number, Reduce])[1]
|
},
|
||||||
|
[0, { sum: -10000, move: 0, idx: 0 }] as readonly [number, Reduce]
|
||||||
|
)[1]
|
||||||
)
|
)
|
||||||
.filter(isNonNullable)
|
.filter(isNonNullable)
|
||||||
const rowBest = costs
|
const rowBest = costs
|
||||||
.map((_, idx) => costs[idx]
|
.map(
|
||||||
.slice(idx+1)
|
(_, idx) =>
|
||||||
.reduce(([sum, best], curr, i) => {
|
costs[idx].slice(idx + 1).reduce(
|
||||||
|
([sum, best], curr, i) => {
|
||||||
return sum + curr > best.sum
|
return sum + curr > best.sum
|
||||||
? [sum + curr, {sum: sum+curr, move: i+1, idx}] as const
|
? ([sum + curr, { sum: sum + curr, move: i + 1, idx }] as const)
|
||||||
: [sum + curr, best] as const
|
: ([sum + curr, best] as const)
|
||||||
}, [0, {sum: -10000, move: 0, idx: 0}] as readonly [number, Reduce])[1]
|
},
|
||||||
|
[0, { sum: -10000, move: 0, idx: 0 }] as readonly [number, Reduce]
|
||||||
|
)[1]
|
||||||
)
|
)
|
||||||
.filter(isNonNullable)
|
.filter(isNonNullable)
|
||||||
const replacement = [...colBest, ...rowBest].sort(sortByProperty(red => -red.sum))[0]
|
const replacement = [...colBest, ...rowBest].sort(sortByProperty(red => -red.sum))[0]
|
||||||
if (replacement.sum > 0) {
|
if (replacement.sum > 0) {
|
||||||
score -= 2*replacement.sum
|
score -= 2 * replacement.sum
|
||||||
improvement = true
|
improvement = true
|
||||||
improvementInRow = true
|
improvementInRow = true
|
||||||
costs.splice(replacement.move+replacement.idx, 0, ...costs.splice(replacement.idx, 1))
|
costs.splice(replacement.move + replacement.idx, 0, ...costs.splice(replacement.idx, 1))
|
||||||
costs.map(col => col.splice(replacement.move+replacement.idx, 0, ...col.splice(replacement.idx, 1)))
|
costs.map(col =>
|
||||||
mid.splice(replacement.move+replacement.idx, 0, ...mid.splice(replacement.idx, 1))
|
col.splice(replacement.move + replacement.idx, 0, ...col.splice(replacement.idx, 1))
|
||||||
|
)
|
||||||
|
mid.splice(replacement.move + replacement.idx, 0, ...mid.splice(replacement.idx, 1))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return score
|
return score
|
||||||
}
|
}
|
||||||
|
|
||||||
type Reduce = {sum: number, move: number, idx: number}
|
type Reduce = { sum: number, move: number, idx: number }
|
||||||
let improvement = true
|
let improvement = true
|
||||||
let scores: number[] = []
|
const scores: number[] = []
|
||||||
while (improvement) {
|
while (improvement) {
|
||||||
improvement = false
|
improvement = false
|
||||||
rowsWithInOut.reduce((top, mid, idx) => {
|
rowsWithInOut.reduce((top, mid, idx) => {
|
||||||
scores[idx] = improveRow(top, mid, rowsWithInOut[idx+1])
|
scores[idx] = improveRow(top, mid, rowsWithInOut[idx + 1])
|
||||||
return mid
|
return mid
|
||||||
}, undefined as string[]|undefined)
|
}, undefined as string[] | undefined)
|
||||||
rowsWithInOut.reduceRight((bot, mid, idx) => {
|
rowsWithInOut.reduceRight((bot, mid, idx) => {
|
||||||
scores[idx] = improveRow(rowsWithInOut[idx-1], mid, bot)
|
scores[idx] = improveRow(rowsWithInOut[idx - 1], mid, bot)
|
||||||
return mid
|
return mid
|
||||||
}, undefined as string[]|undefined)
|
}, undefined as string[] | undefined)
|
||||||
}
|
}
|
||||||
return [rowsWithInOut, scores.reduce((a, b) => a+b)]
|
return [rowsWithInOut, scores.reduce((a, b) => a + b)]
|
||||||
}
|
}
|
||||||
|
|
||||||
export function findBest<T extends Dict<unknown>>(rowsWithInOut: string[][], nodesWithInOut: Dict<GraphNodeWithIds<T|AdditionalNode>>, timeLimit: number) {
|
export function findBest<T extends Dict<unknown>>(
|
||||||
|
rowsWithInOut: string[][],
|
||||||
|
nodesWithInOut: Dict<GraphNodeWithIds<T | AdditionalNode>>,
|
||||||
|
timeLimit: number
|
||||||
|
) {
|
||||||
let bestScore = Infinity
|
let bestScore = Infinity
|
||||||
let bestRows = deepcopy(rowsWithInOut)
|
let bestRows = deepcopy(rowsWithInOut)
|
||||||
let limit = Date.now() + timeLimit
|
const limit = Date.now() + timeLimit
|
||||||
let iterSinceImprovements = 0
|
let iterSinceImprovements = 0
|
||||||
let rng = seedrandom.alea("We are SEEED, ya!")
|
const rng = seedrandom.alea('We are SEEED, ya!')
|
||||||
while (true) {
|
while (true) {
|
||||||
if (Date.now() > limit) break
|
if (Date.now() > limit) break
|
||||||
if (iterSinceImprovements > 100) break
|
if (iterSinceImprovements > 100) break
|
||||||
@@ -223,21 +305,31 @@ export function findBest<T extends Dict<unknown>>(rowsWithInOut: string[][], nod
|
|||||||
} else {
|
} else {
|
||||||
iterSinceImprovements++
|
iterSinceImprovements++
|
||||||
}
|
}
|
||||||
rowsOptimized.forEach((row, ) => shuffleInplace(row, rng))
|
rowsOptimized.forEach(row => shuffleInplace(row, rng))
|
||||||
}
|
}
|
||||||
console.log(bestScore)
|
|
||||||
return bestRows
|
return bestRows
|
||||||
}
|
}
|
||||||
|
|
||||||
export function graphUntangled<T extends Dict<unknown>>(nodes: GraphNode<T>[], inputs: string[], outputs: string[], timeLimit = 0): [string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>] {
|
export function graphUntangled<T extends Dict<unknown>>(
|
||||||
const nodeSeed = seedrandom.alea("node")
|
nodes: GraphNode<T>[],
|
||||||
|
inputs: string[],
|
||||||
|
outputs: string[],
|
||||||
|
timeLimit = 0
|
||||||
|
): [string[][], Dict<GraphNodeWithIds<T | AdditionalNode>>] {
|
||||||
|
const nodeSeed = seedrandom.alea('node')
|
||||||
const nodeUid = () => Math.abs(nodeSeed.int32()).toString(16).substring(0, 3)
|
const nodeUid = () => Math.abs(nodeSeed.int32()).toString(16).substring(0, 3)
|
||||||
//console.log('---------------')
|
//console.log('---------------')
|
||||||
const [rowsRaw, nodesRaw] = splitIntoRows(inputs, nodes, nodeUid)
|
const [rowsRaw, nodesRaw] = splitIntoRows(inputs, nodes, nodeUid)
|
||||||
//console.log("Step 1")
|
//console.log("Step 1")
|
||||||
//console.table(rowsRaw)
|
//console.table(rowsRaw)
|
||||||
//console.table(nodesRaw)
|
//console.table(nodesRaw)
|
||||||
const [rowsWithInOut, nodesWithInOut] = addAdditionalNodes(rowsRaw, nodesRaw, inputs, outputs, nodeUid)
|
const [rowsWithInOut, nodesWithInOut] = addAdditionalNodes(
|
||||||
|
rowsRaw,
|
||||||
|
nodesRaw,
|
||||||
|
inputs,
|
||||||
|
outputs,
|
||||||
|
nodeUid
|
||||||
|
)
|
||||||
//console.log("Step 2")
|
//console.log("Step 2")
|
||||||
//console.table(rowsWithInOut)
|
//console.table(rowsWithInOut)
|
||||||
//console.table(nodesWithInOut)
|
//console.table(nodesWithInOut)
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {Dict} from "../types";
|
import { Dict } from '../types'
|
||||||
|
|
||||||
interface GraphNodeBase {
|
interface GraphNodeBase {
|
||||||
inputs: string[]
|
inputs: string[]
|
||||||
@@ -14,7 +14,8 @@ export type GraphNodeWithIds<T extends Dict<unknown>> = GraphNode<T> & {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export type AdditionalNode = {
|
export type AdditionalNode = {
|
||||||
___type: 'i'|'h'|'o'
|
___type: 'i' | 'h' | 'o'
|
||||||
}
|
}
|
||||||
|
|
||||||
export const isAdditionalNode = (node: unknown): node is GraphNodeWithIds<AdditionalNode> => !!(node && typeof node === 'object' && '___type' in node)
|
export const isAdditionalNode = (node: unknown): node is GraphNodeWithIds<AdditionalNode> =>
|
||||||
|
!!(node && typeof node === 'object' && '___type' in node)
|
||||||
|
|||||||
@@ -8,18 +8,18 @@ export function useEventListener<K extends keyof WindowEventMap>(
|
|||||||
eventName: K,
|
eventName: K,
|
||||||
handler: (event: WindowEventMap[K]) => void,
|
handler: (event: WindowEventMap[K]) => void,
|
||||||
element?: undefined,
|
element?: undefined,
|
||||||
options?: boolean | AddEventListenerOptions,
|
options?: boolean | AddEventListenerOptions
|
||||||
): void
|
): void
|
||||||
|
|
||||||
// Element Event based useEventListener interface
|
// Element Event based useEventListener interface
|
||||||
export function useEventListener<
|
export function useEventListener<
|
||||||
K extends keyof HTMLElementEventMap,
|
K extends keyof HTMLElementEventMap,
|
||||||
T extends HTMLElement = HTMLDivElement,
|
T extends HTMLElement = HTMLDivElement
|
||||||
>(
|
>(
|
||||||
eventName: K,
|
eventName: K,
|
||||||
handler: (event: HTMLElementEventMap[K]) => void,
|
handler: (event: HTMLElementEventMap[K]) => void,
|
||||||
element: RefObject<T>,
|
element: RefObject<T>,
|
||||||
options?: boolean | AddEventListenerOptions,
|
options?: boolean | AddEventListenerOptions
|
||||||
): void
|
): void
|
||||||
|
|
||||||
// Document Event based useEventListener interface
|
// Document Event based useEventListener interface
|
||||||
@@ -27,20 +27,18 @@ export function useEventListener<K extends keyof DocumentEventMap>(
|
|||||||
eventName: K,
|
eventName: K,
|
||||||
handler: (event: DocumentEventMap[K]) => void,
|
handler: (event: DocumentEventMap[K]) => void,
|
||||||
element: RefObject<Document>,
|
element: RefObject<Document>,
|
||||||
options?: boolean | AddEventListenerOptions,
|
options?: boolean | AddEventListenerOptions
|
||||||
): void
|
): void
|
||||||
|
|
||||||
export function useEventListener<
|
export function useEventListener<
|
||||||
KW extends keyof WindowEventMap,
|
KW extends keyof WindowEventMap,
|
||||||
KH extends keyof HTMLElementEventMap,
|
KH extends keyof HTMLElementEventMap,
|
||||||
T extends HTMLElement | void = void,
|
T extends HTMLElement | void = void
|
||||||
>(
|
>(
|
||||||
eventName: KW | KH,
|
eventName: KW | KH,
|
||||||
handler: (
|
handler: (event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event) => void,
|
||||||
event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event,
|
|
||||||
) => void,
|
|
||||||
element?: RefObject<T>,
|
element?: RefObject<T>,
|
||||||
options?: boolean | AddEventListenerOptions,
|
options?: boolean | AddEventListenerOptions
|
||||||
) {
|
) {
|
||||||
// Create a ref that stores handler
|
// Create a ref that stores handler
|
||||||
const savedHandler = useRef(handler)
|
const savedHandler = useRef(handler)
|
||||||
|
|||||||
@@ -1,23 +1,23 @@
|
|||||||
import {EnrichedEntity, Entity} from "../types";
|
import { EnrichedEntity, Entity } from '../types'
|
||||||
import details from "../../res/details.json";
|
import details from '../../res/details.json'
|
||||||
import manual from "../../res/manual.json";
|
import manual from '../../res/manual.json'
|
||||||
|
|
||||||
const joined = [...details, ...manual] as Entity[]
|
const joined = [...details, ...manual] as Entity[]
|
||||||
|
|
||||||
const factories = joined.map((detail: EnrichedEntity) => {
|
const factories = joined.map((detail: EnrichedEntity) => {
|
||||||
detail.usedBy = joined
|
detail.usedBy = joined.filter(f =>
|
||||||
.filter(f => Object
|
Object.keys(f.recipe?.prerequisites ?? {}).includes(detail.href)
|
||||||
.keys(f.recipe?.prerequisites ?? {})
|
|
||||||
.includes(detail.href)
|
|
||||||
)
|
)
|
||||||
return detail;
|
return detail
|
||||||
})
|
})
|
||||||
|
|
||||||
const detailsMap = Object.fromEntries(factories.map((detail: EnrichedEntity) => [detail.href, detail]))
|
const detailsMap = Object.fromEntries(
|
||||||
|
factories.map((detail: EnrichedEntity) => [detail.href, detail])
|
||||||
|
)
|
||||||
|
|
||||||
export const useFactories = () => ({
|
export const useFactories = () => ({
|
||||||
factories,
|
factories,
|
||||||
findFactory: (uid: string): EnrichedEntity|undefined => {
|
findFactory: (uid: string): EnrichedEntity | undefined => {
|
||||||
return detailsMap[uid]
|
return detailsMap[uid]
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -1,4 +1,3 @@
|
|||||||
import { useEffect, useLayoutEffect } from 'react'
|
import { useEffect, useLayoutEffect } from 'react'
|
||||||
|
|
||||||
export const useIsomorphicLayoutEffect =
|
export const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect
|
||||||
typeof window !== 'undefined' ? useLayoutEffect : useEffect
|
|
||||||
|
|||||||
@@ -1,10 +1,4 @@
|
|||||||
import {
|
import { Dispatch, SetStateAction, useCallback, useEffect, useState } from 'react'
|
||||||
Dispatch,
|
|
||||||
SetStateAction,
|
|
||||||
useCallback,
|
|
||||||
useEffect,
|
|
||||||
useState,
|
|
||||||
} from 'react'
|
|
||||||
|
|
||||||
// See: https://usehooks-ts.com/react-hook/use-event-listener
|
// See: https://usehooks-ts.com/react-hook/use-event-listener
|
||||||
import { useEventListener } from './useEventListener'
|
import { useEventListener } from './useEventListener'
|
||||||
@@ -41,11 +35,12 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
|
|||||||
|
|
||||||
// Return a wrapped version of useState's setter function that ...
|
// Return a wrapped version of useState's setter function that ...
|
||||||
// ... persists the new value to localStorage.
|
// ... persists the new value to localStorage.
|
||||||
const setValue: SetValue<T> = useCallback(value => {
|
const setValue: SetValue<T> = useCallback(
|
||||||
|
value => {
|
||||||
// Prevent build error "window is undefined" but keeps working
|
// Prevent build error "window is undefined" but keeps working
|
||||||
if (typeof window == 'undefined') {
|
if (typeof window == 'undefined') {
|
||||||
console.warn(
|
console.warn(
|
||||||
`Tried setting localStorage key “${key}” even though environment is not a client`,
|
`Tried setting localStorage key “${key}” even though environment is not a client`
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -64,7 +59,9 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
|
|||||||
} catch (error) {
|
} catch (error) {
|
||||||
console.warn(`Error setting localStorage key “${key}”:`, error)
|
console.warn(`Error setting localStorage key “${key}”:`, error)
|
||||||
}
|
}
|
||||||
}, [key, storedValue])
|
},
|
||||||
|
[key, storedValue]
|
||||||
|
)
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setStoredValue(readValue())
|
setStoredValue(readValue())
|
||||||
@@ -78,7 +75,7 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
|
|||||||
}
|
}
|
||||||
setStoredValue(readValue())
|
setStoredValue(readValue())
|
||||||
},
|
},
|
||||||
[key, readValue],
|
[key, readValue]
|
||||||
)
|
)
|
||||||
|
|
||||||
// this only works for other documents, not the current one
|
// this only works for other documents, not the current one
|
||||||
|
|||||||
6
src/next-types.d.ts
vendored
6
src/next-types.d.ts
vendored
@@ -1,7 +1,3 @@
|
|||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
declare module 'next/config' {
|
declare module 'next/config' {
|
||||||
export interface ServerRuntimeConfig {
|
export interface ServerRuntimeConfig {
|
||||||
MONGO_URL: string
|
MONGO_URL: string
|
||||||
@@ -15,7 +11,7 @@ declare module 'next/config' {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const getConfig: () => {
|
const getConfig: () => {
|
||||||
serverRuntimeConfig: ServerRuntimeConfig,
|
serverRuntimeConfig: ServerRuntimeConfig
|
||||||
publicRuntimeConfig: PublicRuntimeConfig
|
publicRuntimeConfig: PublicRuntimeConfig
|
||||||
}
|
}
|
||||||
export default getConfig
|
export default getConfig
|
||||||
|
|||||||
@@ -1,14 +1,14 @@
|
|||||||
export function createPath(container: DOMRect, start: DOMRect, end: DOMRect) {
|
export function createPath(container: DOMRect, start: DOMRect, end: DOMRect) {
|
||||||
const startX = Math.round(start.x + start.width/2 - container.x)
|
const startX = Math.round(start.x + start.width / 2 - container.x)
|
||||||
const startY = Math.round(start.bottom - container.y)
|
const startY = Math.round(start.bottom - container.y)
|
||||||
const endX = Math.round(end.x + end.width/2 - container.x)
|
const endX = Math.round(end.x + end.width / 2 - container.x)
|
||||||
const endY = Math.round(end.top - container.y)
|
const endY = Math.round(end.top - container.y)
|
||||||
const mid = Math.round((start.bottom + end.top) / 2 - container.y)
|
const mid = Math.round((start.bottom + end.top) / 2 - container.y)
|
||||||
return `M${startX},${startY} C${startX},${mid} ${endX},${mid} ${endX},${endY}`
|
return `M${startX},${startY} C${startX},${mid} ${endX},${mid} ${endX},${endY}`
|
||||||
}
|
}
|
||||||
|
|
||||||
export function drawLine(container: DOMRect, elem: DOMRect) {
|
export function drawLine(container: DOMRect, elem: DOMRect) {
|
||||||
const x = Math.round(elem.x + elem.width/2 - container.x)
|
const x = Math.round(elem.x + elem.width / 2 - container.x)
|
||||||
const top = Math.round(elem.top - container.y)
|
const top = Math.round(elem.top - container.y)
|
||||||
const bottom = Math.round(elem.bottom - container.y)
|
const bottom = Math.round(elem.bottom - container.y)
|
||||||
return `M${x},${top} L${x},${bottom}`
|
return `M${x},${top} L${x},${bottom}`
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {ValidationError} from "jsonschema";
|
import { ValidationError } from 'jsonschema'
|
||||||
|
|
||||||
export interface ErrorMessage {
|
export interface ErrorMessage {
|
||||||
message: string // Human readable error message
|
message: string // Human readable error message
|
||||||
|
|||||||
10
src/utils.ts
10
src/utils.ts
@@ -1,5 +1,5 @@
|
|||||||
import {Dict} from "./types";
|
import { Dict } from './types'
|
||||||
import {PRNG} from "seedrandom";
|
import { PRNG } from 'seedrandom'
|
||||||
|
|
||||||
export function isNonNullable<T>(any: T): any is NonNullable<T> {
|
export function isNonNullable<T>(any: T): any is NonNullable<T> {
|
||||||
return any !== undefined && any !== null
|
return any !== undefined && any !== null
|
||||||
@@ -29,12 +29,12 @@ export function uniquify<T>(array: T[]): T[] {
|
|||||||
|
|
||||||
export function shuffleInplace<T>(array: T[], rng: PRNG): T[] {
|
export function shuffleInplace<T>(array: T[], rng: PRNG): T[] {
|
||||||
for (let i = array.length - 1; i > 0; i--) {
|
for (let i = array.length - 1; i > 0; i--) {
|
||||||
const j = Math.floor(rng.quick() * (i + 1));
|
const j = Math.floor(rng.quick() * (i + 1))
|
||||||
[array[i], array[j]] = [array[j], array[i]];
|
;[array[i], array[j]] = [array[j], array[i]]
|
||||||
}
|
}
|
||||||
return array
|
return array
|
||||||
}
|
}
|
||||||
|
|
||||||
export function fixedEncodeURIComponent(str: string): string {
|
export function fixedEncodeURIComponent(str: string): string {
|
||||||
return encodeURIComponent(str).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16));
|
return encodeURIComponent(str).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16))
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -32,6 +32,7 @@ class FetchOnce<T> {
|
|||||||
this.pendingList.push([resolve, reject])
|
this.pendingList.push([resolve, reject])
|
||||||
break
|
break
|
||||||
case ResolvableState.DONE:
|
case ResolvableState.DONE:
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||||
resolve(this.data!)
|
resolve(this.data!)
|
||||||
break
|
break
|
||||||
case ResolvableState.ERROR:
|
case ResolvableState.ERROR:
|
||||||
|
|||||||
@@ -1,7 +1,6 @@
|
|||||||
import { ErrorMessage } from '../types/FrontendApi'
|
import { ErrorMessage } from '../types/FrontendApi'
|
||||||
import {NextApiHandler, NextApiRequest, NextApiResponse} from 'next'
|
import { NextApiHandler, NextApiRequest, NextApiResponse } from 'next'
|
||||||
import { logger } from './logger'
|
import { logger } from './logger'
|
||||||
import {NextFetchEvent, NextMiddleware, NextRequest} from "next/server";
|
|
||||||
|
|
||||||
export class NetworkError extends Error {
|
export class NetworkError extends Error {
|
||||||
public content?: ErrorMessage
|
public content?: ErrorMessage
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
/* eslint-disable no-console */
|
||||||
export const logger = {
|
export const logger = {
|
||||||
verbose: console.log,
|
verbose: console.log,
|
||||||
debug: console.log,
|
debug: console.log,
|
||||||
|
|||||||
@@ -6,9 +6,11 @@ import { compile, JSONSchema } from 'json-schema-to-typescript'
|
|||||||
import * as fs from 'fs/promises'
|
import * as fs from 'fs/promises'
|
||||||
import { join } from 'path'
|
import { join } from 'path'
|
||||||
import { NetworkError } from '../utils/errors'
|
import { NetworkError } from '../utils/errors'
|
||||||
import getConfig from "next/config";
|
import getConfig from 'next/config'
|
||||||
|
|
||||||
const {publicRuntimeConfig: {TENANT_TYPE}} = getConfig()
|
const {
|
||||||
|
publicRuntimeConfig: { TENANT_TYPE }
|
||||||
|
} = getConfig()
|
||||||
|
|
||||||
const validatorStorage = new Validator()
|
const validatorStorage = new Validator()
|
||||||
|
|
||||||
|
|||||||
@@ -16,9 +16,9 @@ export function addSchemas() {
|
|||||||
type: 'object',
|
type: 'object',
|
||||||
required: ['type', 'factories'],
|
required: ['type', 'factories'],
|
||||||
properties: {
|
properties: {
|
||||||
type: {type: 'string', enum: ['exports', 'malls']},
|
type: { type: 'string', enum: ['exports', 'malls'] },
|
||||||
factories: {type: 'array', items: {type: 'string', minLength: 3}}
|
factories: { type: 'array', items: { type: 'string', minLength: 3 } }
|
||||||
},
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'GroupIdParam',
|
id: 'GroupIdParam',
|
||||||
@@ -34,16 +34,16 @@ export function addSchemas() {
|
|||||||
type: 'object',
|
type: 'object',
|
||||||
required: ['type', 'factories'],
|
required: ['type', 'factories'],
|
||||||
properties: {
|
properties: {
|
||||||
type: {type: 'string', enum: ['ignored', 'base']},
|
type: { type: 'string', enum: ['ignored', 'base'] },
|
||||||
factories: {type: 'array', items: {type: 'string', minLength: 3}}
|
factories: { type: 'array', items: { type: 'string', minLength: 3 } }
|
||||||
},
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
id: 'IdParam',
|
id: 'IdParam',
|
||||||
type: 'object',
|
type: 'object',
|
||||||
required: ['id'],
|
required: ['id'],
|
||||||
properties: {
|
properties: {
|
||||||
id: { type: 'string', minLength: 24, maxLength: 24 },
|
id: { type: 'string', minLength: 24, maxLength: 24 }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
])
|
])
|
||||||
|
|||||||
@@ -2,14 +2,24 @@ html,
|
|||||||
body {
|
body {
|
||||||
padding: 0;
|
padding: 0;
|
||||||
margin: 0;
|
margin: 0;
|
||||||
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
|
font-family:
|
||||||
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
|
-apple-system,
|
||||||
|
BlinkMacSystemFont,
|
||||||
|
"Segoe UI",
|
||||||
|
Roboto,
|
||||||
|
Oxygen,
|
||||||
|
Ubuntu,
|
||||||
|
Cantarell,
|
||||||
|
"Fira Sans",
|
||||||
|
"Droid Sans",
|
||||||
|
"Helvetica Neue",
|
||||||
|
sans-serif;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
color: black;
|
|
||||||
background: #FAFAFA;
|
|
||||||
padding: 2em;
|
padding: 2em;
|
||||||
|
background: #fafafa;
|
||||||
|
color: black;
|
||||||
}
|
}
|
||||||
|
|
||||||
body.scroll {
|
body.scroll {
|
||||||
@@ -36,17 +46,18 @@ h3 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
h4 {
|
h4 {
|
||||||
margin-block: 1em 0.3em;
|
|
||||||
font-weight: 500;
|
font-weight: 500;
|
||||||
|
margin-block: 1em 0.3em;
|
||||||
}
|
}
|
||||||
|
|
||||||
@media (prefers-color-scheme: dark) {
|
@media (prefers-color-scheme: dark) {
|
||||||
html {
|
html {
|
||||||
color-scheme: dark;
|
color-scheme: dark;
|
||||||
}
|
}
|
||||||
|
|
||||||
body {
|
body {
|
||||||
color: white;
|
|
||||||
background: #111;
|
background: #111;
|
||||||
|
color: white;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
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