Added SSR
This commit is contained in:
@@ -1,4 +1,4 @@
|
|||||||
import {createContext, FC, useCallback, useContext, useMemo} from "react";
|
import {createContext, FC, useCallback, useContext, useMemo, useState} from "react";
|
||||||
import {Group} from "../../src/types";
|
import {Group} from "../../src/types";
|
||||||
import {useLocalStorage} from "../../src/hooks/useLocalStorage";
|
import {useLocalStorage} from "../../src/hooks/useLocalStorage";
|
||||||
import {ReactNodeLike} from "prop-types";
|
import {ReactNodeLike} from "prop-types";
|
||||||
@@ -7,6 +7,12 @@ import {Dict} from "../../src/types";
|
|||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
children: ReactNodeLike
|
children: ReactNodeLike
|
||||||
|
id: string
|
||||||
|
initial: {
|
||||||
|
groups: Dict<Group>
|
||||||
|
ignored: string[]
|
||||||
|
base: string[]
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
interface GroupContextType {
|
interface GroupContextType {
|
||||||
@@ -62,10 +68,10 @@ interface StoredFile {
|
|||||||
excludedSuggestions: string[]
|
excludedSuggestions: string[]
|
||||||
}
|
}
|
||||||
|
|
||||||
export const GroupProvider: FC<Props> = ({children}) => {
|
export const GroupProvider: FC<Props> = ({children, initial}) => {
|
||||||
const [excludedSuggestions, setExcludedSuggestions] = useLocalStorage<string[]>('excludedSuggestions', [])
|
const [excludedSuggestions, setExcludedSuggestions] = useState<string[]>(initial.ignored)
|
||||||
const [basicValues, setBasicValues] = useLocalStorage<string[]>('basicValues', [])
|
const [basicValues, setBasicValues] = useState<string[]>(initial.base)
|
||||||
const [groups, setGroups] = useLocalStorage<Dict<Group>>('serviceGroups', {})
|
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])
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
import {FC, memo, useEffect, useState} from "react";
|
import {FC, memo, useEffect, useMemo, useState} 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";
|
||||||
@@ -17,11 +17,10 @@ const options = details.map(detail => ({
|
|||||||
}))
|
}))
|
||||||
|
|
||||||
const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => {
|
const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => {
|
||||||
const [state, setState] = useState<typeof options>([])
|
const state = useMemo<typeof options>(() => {
|
||||||
useEffect(() => {
|
return factories
|
||||||
setState(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
|
||||||
@@ -38,7 +37,6 @@ const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => {
|
|||||||
isMulti
|
isMulti
|
||||||
options={options as never}
|
options={options as never}
|
||||||
onChange={e => {
|
onChange={e => {
|
||||||
setState(e as typeof options)
|
|
||||||
onSetFactories(e.map(s => s?.value))
|
onSetFactories(e.map(s => s?.value))
|
||||||
}}
|
}}
|
||||||
className={styles.select}
|
className={styles.select}
|
||||||
|
|||||||
@@ -8,12 +8,14 @@ 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";
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
group: Group
|
group: Group
|
||||||
}
|
}
|
||||||
|
|
||||||
const GroupBoxBase: FC<Props> = ({ group }) => {
|
const GroupBoxBase: FC<Props> = ({ group }) => {
|
||||||
|
const router = useRouter()
|
||||||
const {factories, findFactory} = useFactories()
|
const {factories, findFactory} = useFactories()
|
||||||
const {
|
const {
|
||||||
doNotSuggest,
|
doNotSuggest,
|
||||||
@@ -82,7 +84,7 @@ const GroupBoxBase: FC<Props> = ({ group }) => {
|
|||||||
>
|
>
|
||||||
{name}
|
{name}
|
||||||
</h3>
|
</h3>
|
||||||
<Link href={`./visualize/${fixedEncodeURIComponent(group.name)}`}>👁</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)}
|
||||||
|
|||||||
@@ -8,8 +8,10 @@ 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";
|
||||||
|
|
||||||
export const Home: FC = () => {
|
export const Home: FC = () => {
|
||||||
|
const router = useRouter()
|
||||||
const {factories} = useFactories()
|
const {factories} = useFactories()
|
||||||
const {
|
const {
|
||||||
groups,
|
groups,
|
||||||
@@ -42,13 +44,17 @@ export const Home: FC = () => {
|
|||||||
download('factorio-microservices.bin', store());
|
download('factorio-microservices.bin', store());
|
||||||
}}>Store</button>
|
}}>Store</button>
|
||||||
<button onClick={async () => {
|
<button onClick={async () => {
|
||||||
await fetch( '/api/submit', {
|
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) {
|
||||||
|
const { uuid } = await res.json()
|
||||||
|
if (uuid) await router.push({query: {...router.query, id: uuid}})
|
||||||
|
}
|
||||||
}}>Upload</button>
|
}}>Upload</button>
|
||||||
<input type={"file"} multiple={false} ref={inputRef} onChange={async evt => {
|
<input type={"file"} multiple={false} ref={inputRef} onChange={async evt => {
|
||||||
const stream = evt.currentTarget.files?.[0].stream() as globalThis.ReadableStream<Uint8Array>|undefined
|
const stream = evt.currentTarget.files?.[0].stream() as globalThis.ReadableStream<Uint8Array>|undefined
|
||||||
@@ -58,7 +64,7 @@ export const Home: FC = () => {
|
|||||||
if (inputRef.current) inputRef.current.value = null as unknown as string
|
if (inputRef.current) inputRef.current.value = null as unknown as string
|
||||||
}
|
}
|
||||||
}}/>
|
}}/>
|
||||||
<Link href={'/visualize'}>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>
|
||||||
|
|||||||
@@ -15,11 +15,7 @@ interface Props<T extends {}> {
|
|||||||
|
|
||||||
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>>]>([[], {}])
|
const [[rows, nodeMap], setGraph] = useState<[string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>]>(graphUntangled(nodes, inputs, outputs ?? [], 3000))
|
||||||
useEffect(() => {
|
|
||||||
setGraph(graphUntangled(nodes, inputs, outputs ?? []))
|
|
||||||
setTimeout(() => setGraph(graphUntangled(nodes, inputs, outputs ?? [], 3000)), 0)
|
|
||||||
}, [inputs, nodes, outputs])
|
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!planeRef.current) return
|
if (!planeRef.current) return
|
||||||
|
|||||||
84
components/visualize/PageDetails.tsx
Normal file
84
components/visualize/PageDetails.tsx
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
import {useRouter} from "next/router";
|
||||||
|
import {GroupProvider, useGroups} from "../contexts/GroupProvider";
|
||||||
|
import {useFactories} from "../../src/hooks/useFactories";
|
||||||
|
import {FC, useEffect, useMemo} from "react";
|
||||||
|
import {calculateInputs} from "../../src/calculateInputs";
|
||||||
|
import {DetailGraphNode, NodeDetails} from "./NodeDetails/NodeDetails";
|
||||||
|
import {groupBy, isNonNullable, uniquify} from "../../src/utils";
|
||||||
|
import {EnrichedEntity} from "../../src/types";
|
||||||
|
import Head from "next/head";
|
||||||
|
import {ScrollContainer} from "../shared/ScrollContainer/ScrollContainer";
|
||||||
|
import {ProducingGraph} from "../shared/ProducingGraph/ProducingGraph";
|
||||||
|
|
||||||
|
export const PageDetails: FC = () => {
|
||||||
|
const {query: {name}} = useRouter()
|
||||||
|
const {
|
||||||
|
exportedFactories,
|
||||||
|
baseFactories,
|
||||||
|
ignoredFactories,
|
||||||
|
groups
|
||||||
|
} = useGroups()
|
||||||
|
const {
|
||||||
|
findFactory
|
||||||
|
} = useFactories()
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
document.body.classList.add("scroll");
|
||||||
|
return () => document.body.classList.remove("scroll")
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const group = typeof name === 'string' ? groups[name] : undefined
|
||||||
|
|
||||||
|
const [inputFactories, intermediateFactories] = useMemo<ReturnType<typeof calculateInputs>>(() => {
|
||||||
|
if (!group) return [[], []]
|
||||||
|
return calculateInputs(
|
||||||
|
[...group.exports, ...group.malls],
|
||||||
|
ignoredFactories,
|
||||||
|
baseFactories,
|
||||||
|
exportedFactories,
|
||||||
|
findFactory
|
||||||
|
)
|
||||||
|
}, [baseFactories, exportedFactories, findFactory, group, ignoredFactories])
|
||||||
|
|
||||||
|
const producingNodes: DetailGraphNode[] = useMemo(() => {
|
||||||
|
if (!group) return []
|
||||||
|
const nodes = uniquify([...intermediateFactories, ...group.exports, ...group.malls])
|
||||||
|
.map(findFactory)
|
||||||
|
.filter(isNonNullable)
|
||||||
|
.map((factory: EnrichedEntity) => ({
|
||||||
|
inputs: Object.keys(factory.recipe?.prerequisites ?? {}).sort((a, b) => a.localeCompare(b)),
|
||||||
|
outputs: Object.keys(factory.recipe?.output ?? {}).sort((a, b) => a.localeCompare(b)),
|
||||||
|
name: factory.name,
|
||||||
|
recipes: [factory.recipe]
|
||||||
|
} as DetailGraphNode))
|
||||||
|
return Object
|
||||||
|
.values(groupBy(nodes, node => node.inputs.join()))
|
||||||
|
.map(nodesOfInput => ({
|
||||||
|
inputs: nodesOfInput[0].inputs,
|
||||||
|
outputs: uniquify(nodesOfInput.flatMap(node => node.outputs)),
|
||||||
|
name: nodesOfInput.map(node => node.name).join(', '),
|
||||||
|
recipes: nodesOfInput.flatMap(node => node.recipes)
|
||||||
|
} as DetailGraphNode))
|
||||||
|
}, [findFactory, group, intermediateFactories])
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<Head>
|
||||||
|
<title>Factorio Microservices</title>
|
||||||
|
<meta name="description" content="Create Factorio microservices" />
|
||||||
|
<link rel="icon" href="/public/favicon.ico" />
|
||||||
|
</Head>
|
||||||
|
<main>
|
||||||
|
<ScrollContainer>
|
||||||
|
<h1>{name}</h1>
|
||||||
|
<ProducingGraph
|
||||||
|
nodes={producingNodes}
|
||||||
|
inputs={inputFactories}
|
||||||
|
outputs={group?.exports}
|
||||||
|
childType={NodeDetails}
|
||||||
|
/>
|
||||||
|
</ScrollContainer>
|
||||||
|
</main>
|
||||||
|
</>
|
||||||
|
)
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@
|
|||||||
"env-var": "^7.1.1",
|
"env-var": "^7.1.1",
|
||||||
"mongodb": "^4.8.1",
|
"mongodb": "^4.8.1",
|
||||||
"next": "12.2.4",
|
"next": "12.2.4",
|
||||||
|
"next-superjson-plugin": "^0.3.0",
|
||||||
"pako": "^2.0.4",
|
"pako": "^2.0.4",
|
||||||
"react": "18.2.0",
|
"react": "18.2.0",
|
||||||
"react-dom": "18.2.0",
|
"react-dom": "18.2.0",
|
||||||
|
|||||||
@@ -4,9 +4,7 @@ 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 <GroupProvider>
|
return <Component {...pageProps} />
|
||||||
<Component {...pageProps} />
|
|
||||||
</GroupProvider>
|
|
||||||
}
|
}
|
||||||
|
|
||||||
export default MyApp
|
export default MyApp
|
||||||
|
|||||||
@@ -1,12 +1,11 @@
|
|||||||
import {NextApiHandler} from "next";
|
import {NextApiHandler} from "next";
|
||||||
import {Dict, Group} from "../../src/types";
|
import {GroupData, setGroups} from "../../src/database/groups";
|
||||||
import {setGroups} from "../../src/database/groups";
|
|
||||||
|
|
||||||
const handler: NextApiHandler = async (req, res) => {
|
const handler: NextApiHandler = async (req, res) => {
|
||||||
if (req.method !== 'POST') throw new Error('Invalid method')
|
if (req.method !== 'POST') throw new Error('Invalid method')
|
||||||
const {groups, ignored, base} = req.body as {groups: Dict<Group>, ignored: string[], base: string[]}
|
const data = req.body as GroupData
|
||||||
const uuid = await setGroups(groups, ignored, base)
|
|
||||||
console.log(uuid)
|
const uuid = await setGroups(data)
|
||||||
res.json({ uuid })
|
res.json({ uuid })
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,19 +1,27 @@
|
|||||||
import type { NextPage } from 'next'
|
import type {GetServerSideProps, 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 {useEffect} from "react";
|
||||||
|
import {GroupProvider} from "../components/contexts/GroupProvider";
|
||||||
|
import {getGroup, setGroups} from "../src/database/groups";
|
||||||
|
import {Dict, Group} from "../src/types";
|
||||||
|
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../src/getServerSideProps";
|
||||||
|
|
||||||
const Page: NextPage = () => {
|
|
||||||
|
|
||||||
|
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
|
||||||
return (
|
return (
|
||||||
<>
|
<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>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const getServerSideProps = getServerSidePropsGroupProvider
|
||||||
|
|
||||||
export default Page
|
export default Page
|
||||||
|
|||||||
@@ -1,93 +1,17 @@
|
|||||||
import type { NextPage } from 'next'
|
import type { NextPage } from 'next'
|
||||||
import Head from 'next/head'
|
import {GroupProvider} from "../../components/contexts/GroupProvider";
|
||||||
import {useGroups} from "../../components/contexts/GroupProvider";
|
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../../src/getServerSideProps";
|
||||||
import {useFactories} from "../../src/hooks/useFactories";
|
import {PageDetails} from "../../components/visualize/PageDetails";
|
||||||
import {ProducingGraph} from "../../components/shared/ProducingGraph/ProducingGraph";
|
|
||||||
import {useEffect, useMemo} from "react";
|
|
||||||
import {calculateInputs} from "../../src/calculateInputs";
|
|
||||||
import {useRouter} from "next/router";
|
|
||||||
import {groupBy, isNonNullable, uniquify} from "../../src/utils";
|
|
||||||
import {EnrichedEntity} from "../../src/types";
|
|
||||||
import {DetailGraphNode, NodeDetails} from "../../components/visualize/NodeDetails/NodeDetails";
|
|
||||||
import {ScrollContainer} from "../../components/shared/ScrollContainer/ScrollContainer";
|
|
||||||
|
|
||||||
|
|
||||||
|
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
|
||||||
const Page: NextPage = () => {
|
|
||||||
const {query: {name}} = useRouter()
|
|
||||||
const {
|
|
||||||
exportedFactories,
|
|
||||||
baseFactories,
|
|
||||||
ignoredFactories,
|
|
||||||
groups
|
|
||||||
} = useGroups()
|
|
||||||
const {
|
|
||||||
findFactory
|
|
||||||
} = useFactories()
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
document.body.classList.add("scroll");
|
|
||||||
return () => document.body.classList.remove("scroll")
|
|
||||||
}, []);
|
|
||||||
|
|
||||||
const group = typeof name === 'string' ? groups[name] : undefined
|
|
||||||
|
|
||||||
const [inputFactories, intermediateFactories] = useMemo<ReturnType<typeof calculateInputs>>(() => {
|
|
||||||
if (!group) return [[], []]
|
|
||||||
return calculateInputs(
|
|
||||||
[...group.exports, ...group.malls],
|
|
||||||
ignoredFactories,
|
|
||||||
baseFactories,
|
|
||||||
exportedFactories,
|
|
||||||
findFactory
|
|
||||||
)
|
|
||||||
}, [baseFactories, exportedFactories, findFactory, group, ignoredFactories])
|
|
||||||
|
|
||||||
const producingNodes: DetailGraphNode[] = useMemo(() => {
|
|
||||||
if (!group) return []
|
|
||||||
const nodes = uniquify([...intermediateFactories, ...group.exports, ...group.malls])
|
|
||||||
.map(findFactory)
|
|
||||||
.filter(isNonNullable)
|
|
||||||
.map((factory: EnrichedEntity) => ({
|
|
||||||
inputs: Object.keys(factory.recipe?.prerequisites ?? {}).sort((a, b) => a.localeCompare(b)),
|
|
||||||
outputs: Object.keys(factory.recipe?.output ?? {}).sort((a, b) => a.localeCompare(b)),
|
|
||||||
name: factory.name,
|
|
||||||
recipes: [factory.recipe]
|
|
||||||
} as DetailGraphNode))
|
|
||||||
return Object
|
|
||||||
.values(groupBy(nodes, node => node.inputs.join()))
|
|
||||||
.map(nodesOfInput => ({
|
|
||||||
inputs: nodesOfInput[0].inputs,
|
|
||||||
outputs: uniquify(nodesOfInput.flatMap(node => node.outputs)),
|
|
||||||
name: nodesOfInput.map(node => node.name).join(', '),
|
|
||||||
recipes: nodesOfInput.flatMap(node => node.recipes)
|
|
||||||
} as DetailGraphNode))
|
|
||||||
}, [findFactory, group, intermediateFactories])
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<GroupProvider id={id} initial={initial}>
|
||||||
<Head>
|
<PageDetails/>
|
||||||
<title>Factorio Microservices</title>
|
</GroupProvider>
|
||||||
<meta name="description" content="Create Factorio microservices" />
|
|
||||||
<link rel="icon" href="/public/favicon.ico" />
|
|
||||||
</Head>
|
|
||||||
<main>
|
|
||||||
<ScrollContainer>
|
|
||||||
<h1>{name}</h1>
|
|
||||||
<ProducingGraph
|
|
||||||
nodes={producingNodes}
|
|
||||||
inputs={inputFactories}
|
|
||||||
outputs={group?.exports}
|
|
||||||
childType={NodeDetails}
|
|
||||||
/>
|
|
||||||
</ScrollContainer>
|
|
||||||
</main>
|
|
||||||
</>
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function getServerSideProps() {
|
export const getServerSideProps = getServerSidePropsGroupProvider
|
||||||
return { props: { bodyClassName: 'scroll' } };
|
|
||||||
}
|
|
||||||
|
|
||||||
export default Page
|
export default Page
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import type {NextPage} from 'next'
|
import type {NextPage} from 'next'
|
||||||
import Head from 'next/head'
|
import Head from 'next/head'
|
||||||
import {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";
|
||||||
@@ -8,8 +8,9 @@ import {calculateInputs} from "../../src/calculateInputs";
|
|||||||
import {NodeOverview, OverviewGraphNode} from "../../components/visualize/NodeOverview/NodeOverview";
|
import {NodeOverview, OverviewGraphNode} from "../../components/visualize/NodeOverview/NodeOverview";
|
||||||
import {fixedEncodeURIComponent} from "../../src/utils";
|
import {fixedEncodeURIComponent} from "../../src/utils";
|
||||||
import {ScrollContainer} from "../../components/shared/ScrollContainer/ScrollContainer";
|
import {ScrollContainer} from "../../components/shared/ScrollContainer/ScrollContainer";
|
||||||
|
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../../src/getServerSideProps";
|
||||||
|
|
||||||
const Page: NextPage = () => {
|
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
|
||||||
const {
|
const {
|
||||||
exportedFactories,
|
exportedFactories,
|
||||||
ignoredFactories,
|
ignoredFactories,
|
||||||
@@ -42,7 +43,7 @@ const Page: NextPage = () => {
|
|||||||
}, [baseFactories, exportedFactories, findFactory, groups, ignoredFactories])
|
}, [baseFactories, exportedFactories, findFactory, groups, ignoredFactories])
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<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" />
|
||||||
@@ -54,8 +55,10 @@ const Page: NextPage = () => {
|
|||||||
<ProducingGraph nodes={producingNodes} inputs={baseFactories} childType={NodeOverview}/>
|
<ProducingGraph nodes={producingNodes} inputs={baseFactories} childType={NodeOverview}/>
|
||||||
</ScrollContainer>
|
</ScrollContainer>
|
||||||
</main>
|
</main>
|
||||||
</>
|
</GroupProvider>
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export const getServerSideProps = getServerSidePropsGroupProvider
|
||||||
|
|
||||||
export default Page
|
export default Page
|
||||||
|
|||||||
@@ -1,19 +1,44 @@
|
|||||||
import {database} from "./start";
|
import {database} from "./start";
|
||||||
import {Dict, Group} from "../types";
|
import {Dict, Group} from "../types";
|
||||||
import crypto from "crypto"
|
import {Filter, ObjectId, WithId} from "mongodb";
|
||||||
|
|
||||||
export async function setGroups(groups: Dict<Group>, ignored: string[], base: string[]) {
|
export interface GroupData {
|
||||||
const collection = (await database.resolve())?.collection('setups')
|
groups: Dict<Group>,
|
||||||
|
ignored: string[],
|
||||||
|
base: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
type InsertMeta<T> = T & {
|
||||||
|
createdOn: Date,
|
||||||
|
modifiedOn: Date,
|
||||||
|
accessedOn: Date
|
||||||
|
}
|
||||||
|
|
||||||
|
type GroupFilter = Filter<InsertMeta<GroupData>>
|
||||||
|
|
||||||
|
export async function setGroups(data: GroupData) {
|
||||||
|
const collection = (await database.resolve())?.collection<InsertMeta<GroupData>>('setups')
|
||||||
if (!collection) return
|
if (!collection) return
|
||||||
await collection.deleteMany({}).catch(e => {
|
|
||||||
if (e.message !== 'ns not found') throw e
|
|
||||||
})
|
|
||||||
const result = await collection.insertOne({
|
const result = await collection.insertOne({
|
||||||
groups,
|
...data,
|
||||||
ignored,
|
|
||||||
base,
|
|
||||||
createdOn: new Date(),
|
createdOn: new Date(),
|
||||||
modifiedOn: new Date()
|
modifiedOn: new Date(),
|
||||||
|
accessedOn: new Date()
|
||||||
})
|
})
|
||||||
|
console.log(result.insertedId, result.insertedId.toString())
|
||||||
return result.insertedId.toString()
|
return result.insertedId.toString()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
export async function getGroup(uuid: string) {
|
||||||
|
const collection = (await database.resolve())?.collection<InsertMeta<GroupData>>('setups')
|
||||||
|
if (!collection) return
|
||||||
|
console.log(uuid)
|
||||||
|
const data = (await collection.findOne({
|
||||||
|
_id: new ObjectId(uuid)
|
||||||
|
} as GroupFilter)) ?? undefined
|
||||||
|
if (data) {
|
||||||
|
await collection.updateOne({_id: new ObjectId(uuid)}, { $set: {accessedOn: new Date()}})
|
||||||
|
}
|
||||||
|
return data
|
||||||
|
}
|
||||||
|
|||||||
38
src/getServerSideProps.ts
Normal file
38
src/getServerSideProps.ts
Normal file
@@ -0,0 +1,38 @@
|
|||||||
|
import {GetServerSideProps} from "next";
|
||||||
|
import {getGroup, setGroups} from "./database/groups";
|
||||||
|
import {Dict, Group} from "./types";
|
||||||
|
|
||||||
|
export interface PropsGroupProvider {
|
||||||
|
id: string
|
||||||
|
groups: Dict<Group>
|
||||||
|
ignored: string[]
|
||||||
|
base: string[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvider> = async ({query}) => {
|
||||||
|
const id = Array.isArray(query?.id) ? query.id[0] : query?.id
|
||||||
|
const data = id && await getGroup(id)
|
||||||
|
if (data) {
|
||||||
|
return {
|
||||||
|
props: {
|
||||||
|
id: data._id.toString(),
|
||||||
|
groups: data.groups,
|
||||||
|
ignored: data.ignored,
|
||||||
|
base: data.base
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else if (!id) {
|
||||||
|
const newId = await setGroups({groups: {}, base: [], ignored: []})
|
||||||
|
return {
|
||||||
|
redirect: {
|
||||||
|
destination: `?id=${newId}`,
|
||||||
|
permanent: false,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
console.log(data)
|
||||||
|
return {
|
||||||
|
notFound: true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -4,30 +4,28 @@ 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>): GraphNodeWithIds<T> {
|
|
||||||
return {
|
return {
|
||||||
...node,
|
...node,
|
||||||
___uid: `${node.name.replace(/[^a-z]/gi, '').toLowerCase().substring(0, 3)}_${crypto.randomUUID().substring(0, 3)}`,
|
___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'): GraphNodeWithIds<AdditionalNode> {
|
function generateAdditional<T extends Dict<unknown>>(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)}_${crypto.randomUUID().substring(0, 3)}_${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>[]): [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]
|
||||||
@@ -40,7 +38,7 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
|
|||||||
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)
|
const nodeWithId: GraphNodeWithIds<T> = generateIds(node, nodeUid)
|
||||||
rows[rows.length - 1].push(nodeWithId.___uid)
|
rows[rows.length - 1].push(nodeWithId.___uid)
|
||||||
nodesWithId[nodeWithId.___uid] = nodeWithId
|
nodesWithId[nodeWithId.___uid] = nodeWithId
|
||||||
availableOfRow.push(...node.outputs)
|
availableOfRow.push(...node.outputs)
|
||||||
@@ -58,7 +56,7 @@ 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[]): [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)
|
||||||
@@ -67,13 +65,13 @@ function addAdditionalNodes<T extends Dict<unknown>>(rowsRaw: string[][], nodesR
|
|||||||
for (let rowInput of rowInputs) {
|
for (let 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')
|
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')
|
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
|
||||||
@@ -82,7 +80,7 @@ function addAdditionalNodes<T extends Dict<unknown>>(rowsRaw: string[][], nodesR
|
|||||||
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 (let rowOutput of rowOutputs) {
|
||||||
if (outputs?.includes(rowOutput)) {
|
if (outputs?.includes(rowOutput)) {
|
||||||
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowOutput, 'o')
|
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowOutput, 'o', nodeUid)
|
||||||
res[i+2].push(nodeWithId.___uid)
|
res[i+2].push(nodeWithId.___uid)
|
||||||
resNodes[nodeWithId.___uid] = nodeWithId
|
resNodes[nodeWithId.___uid] = nodeWithId
|
||||||
}
|
}
|
||||||
@@ -232,12 +230,14 @@ export function findBest<T extends Dict<unknown>>(rowsWithInOut: string[][], nod
|
|||||||
}
|
}
|
||||||
|
|
||||||
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>>(nodes: GraphNode<T>[], inputs: string[], outputs: string[], timeLimit = 0): [string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>] {
|
||||||
|
const nodeSeed = seedrandom.alea("node")
|
||||||
|
const nodeUid = () => Math.abs(nodeSeed.int32()).toString(16).substring(0, 3)
|
||||||
//console.log('---------------')
|
//console.log('---------------')
|
||||||
const [rowsRaw, nodesRaw] = splitIntoRows(inputs, nodes)
|
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)
|
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)
|
||||||
|
|||||||
Reference in New Issue
Block a user