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 {useLocalStorage} from "../../src/hooks/useLocalStorage";
|
||||
import {ReactNodeLike} from "prop-types";
|
||||
@@ -7,6 +7,12 @@ import {Dict} from "../../src/types";
|
||||
|
||||
interface Props {
|
||||
children: ReactNodeLike
|
||||
id: string
|
||||
initial: {
|
||||
groups: Dict<Group>
|
||||
ignored: string[]
|
||||
base: string[]
|
||||
}
|
||||
}
|
||||
|
||||
interface GroupContextType {
|
||||
@@ -62,10 +68,10 @@ interface StoredFile {
|
||||
excludedSuggestions: string[]
|
||||
}
|
||||
|
||||
export const GroupProvider: FC<Props> = ({children}) => {
|
||||
const [excludedSuggestions, setExcludedSuggestions] = useLocalStorage<string[]>('excludedSuggestions', [])
|
||||
const [basicValues, setBasicValues] = useLocalStorage<string[]>('basicValues', [])
|
||||
const [groups, setGroups] = useLocalStorage<Dict<Group>>('serviceGroups', {})
|
||||
export const GroupProvider: FC<Props> = ({children, initial}) => {
|
||||
const [excludedSuggestions, setExcludedSuggestions] = useState<string[]>(initial.ignored)
|
||||
const [basicValues, setBasicValues] = useState<string[]>(initial.base)
|
||||
const [groups, setGroups] = useState<Dict<Group>>(initial.groups)
|
||||
|
||||
const doNotSuggest = useMemo<Set<string>>(() => {
|
||||
return new Set([...Object.values(groups).flatMap(group => [...group.exports, ...group.malls]), ...excludedSuggestions, ...basicValues])
|
||||
|
||||
@@ -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 {isNonNullable} from "../../../src/utils";
|
||||
import details from "../../../res/details.json";
|
||||
@@ -17,11 +17,10 @@ const options = details.map(detail => ({
|
||||
}))
|
||||
|
||||
const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => {
|
||||
const [state, setState] = useState<typeof options>([])
|
||||
useEffect(() => {
|
||||
setState(factories
|
||||
const state = useMemo<typeof options>(() => {
|
||||
return factories
|
||||
.map(factory => options.find(option => option.value === factory))
|
||||
.filter(isNonNullable))
|
||||
.filter(isNonNullable)
|
||||
}, [factories])
|
||||
|
||||
return <Select
|
||||
@@ -38,7 +37,6 @@ const FactorySelectBase: FC<Props> = ({id, factories, onSetFactories}) => {
|
||||
isMulti
|
||||
options={options as never}
|
||||
onChange={e => {
|
||||
setState(e as typeof options)
|
||||
onSetFactories(e.map(s => s?.value))
|
||||
}}
|
||||
className={styles.select}
|
||||
|
||||
@@ -8,12 +8,14 @@ import {useGroups} from "../../contexts/GroupProvider";
|
||||
import {calculateInputs} from "../../../src/calculateInputs";
|
||||
import {fixedEncodeURIComponent, uniquify} from "../../../src/utils";
|
||||
import Link from "next/link";
|
||||
import {useRouter} from "next/router";
|
||||
|
||||
interface Props {
|
||||
group: Group
|
||||
}
|
||||
|
||||
const GroupBoxBase: FC<Props> = ({ group }) => {
|
||||
const router = useRouter()
|
||||
const {factories, findFactory} = useFactories()
|
||||
const {
|
||||
doNotSuggest,
|
||||
@@ -82,7 +84,7 @@ const GroupBoxBase: FC<Props> = ({ group }) => {
|
||||
>
|
||||
{name}
|
||||
</h3>
|
||||
<Link href={`./visualize/${fixedEncodeURIComponent(group.name)}`}>👁</Link>
|
||||
<Link href={{pathname: `/visualize/${fixedEncodeURIComponent(group.name)}`, query: router.query}}>👁</Link>
|
||||
<button
|
||||
className={styles.quit}
|
||||
onBlur={() => setDeleteConfirm(false)}
|
||||
|
||||
@@ -8,8 +8,10 @@ import {useGroups} from "../contexts/GroupProvider";
|
||||
import {Preferences} from "./Preferences/Preferences";
|
||||
import {download, streamToArrayBuffer} from "../../src/download";
|
||||
import Link from "next/link";
|
||||
import {useRouter} from "next/router";
|
||||
|
||||
export const Home: FC = () => {
|
||||
const router = useRouter()
|
||||
const {factories} = useFactories()
|
||||
const {
|
||||
groups,
|
||||
@@ -42,13 +44,17 @@ export const Home: FC = () => {
|
||||
download('factorio-microservices.bin', store());
|
||||
}}>Store</button>
|
||||
<button onClick={async () => {
|
||||
await fetch( '/api/submit', {
|
||||
const res = await fetch( '/api/submit', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
},
|
||||
body: JSON.stringify({groups, ignored: ignoredFactories, base: baseFactories})
|
||||
})
|
||||
if (res.ok) {
|
||||
const { uuid } = await res.json()
|
||||
if (uuid) await router.push({query: {...router.query, id: uuid}})
|
||||
}
|
||||
}}>Upload</button>
|
||||
<input type={"file"} multiple={false} ref={inputRef} onChange={async evt => {
|
||||
const stream = evt.currentTarget.files?.[0].stream() as globalThis.ReadableStream<Uint8Array>|undefined
|
||||
@@ -58,7 +64,7 @@ export const Home: FC = () => {
|
||||
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 />
|
||||
<fieldset>
|
||||
<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>>) => {
|
||||
const planeRef = useRef<HTMLDivElement>(null)
|
||||
const [[rows, nodeMap], setGraph] = useState<[string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>]>([[], {}])
|
||||
useEffect(() => {
|
||||
setGraph(graphUntangled(nodes, inputs, outputs ?? []))
|
||||
setTimeout(() => setGraph(graphUntangled(nodes, inputs, outputs ?? [], 3000)), 0)
|
||||
}, [inputs, nodes, outputs])
|
||||
const [[rows, nodeMap], setGraph] = useState<[string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>]>(graphUntangled(nodes, inputs, outputs ?? [], 3000))
|
||||
|
||||
useEffect(() => {
|
||||
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",
|
||||
"mongodb": "^4.8.1",
|
||||
"next": "12.2.4",
|
||||
"next-superjson-plugin": "^0.3.0",
|
||||
"pako": "^2.0.4",
|
||||
"react": "18.2.0",
|
||||
"react-dom": "18.2.0",
|
||||
|
||||
@@ -4,9 +4,7 @@ import {GroupProvider} from "../components/contexts/GroupProvider";
|
||||
import {FC} from "react";
|
||||
|
||||
const MyApp: FC<AppProps> = ({ Component, pageProps }) => {
|
||||
return <GroupProvider>
|
||||
<Component {...pageProps} />
|
||||
</GroupProvider>
|
||||
return <Component {...pageProps} />
|
||||
}
|
||||
|
||||
export default MyApp
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
import {NextApiHandler} from "next";
|
||||
import {Dict, Group} from "../../src/types";
|
||||
import {setGroups} from "../../src/database/groups";
|
||||
import {GroupData, setGroups} from "../../src/database/groups";
|
||||
|
||||
const handler: NextApiHandler = async (req, res) => {
|
||||
if (req.method !== 'POST') throw new Error('Invalid method')
|
||||
const {groups, ignored, base} = req.body as {groups: Dict<Group>, ignored: string[], base: string[]}
|
||||
const uuid = await setGroups(groups, ignored, base)
|
||||
console.log(uuid)
|
||||
const data = req.body as GroupData
|
||||
|
||||
const uuid = await setGroups(data)
|
||||
res.json({ uuid })
|
||||
}
|
||||
|
||||
|
||||
@@ -1,19 +1,27 @@
|
||||
import type { NextPage } from 'next'
|
||||
import type {GetServerSideProps, NextPage} from 'next'
|
||||
import Head from 'next/head'
|
||||
import {Home} from "../components/home/Home";
|
||||
import {useEffect} from "react";
|
||||
import {GroupProvider} from "../components/contexts/GroupProvider";
|
||||
import {getGroup, setGroups} from "../src/database/groups";
|
||||
import {Dict, Group} from "../src/types";
|
||||
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../src/getServerSideProps";
|
||||
|
||||
const Page: NextPage = () => {
|
||||
|
||||
|
||||
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
|
||||
return (
|
||||
<>
|
||||
<GroupProvider id={id} initial={initial}>
|
||||
<Head>
|
||||
<title>Factorio Microservices</title>
|
||||
<meta name="description" content="Create Factorio microservices" />
|
||||
<link rel="icon" href="/favicon.ico" />
|
||||
</Head>
|
||||
<Home/>
|
||||
</>
|
||||
</GroupProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export const getServerSideProps = getServerSidePropsGroupProvider
|
||||
|
||||
export default Page
|
||||
|
||||
@@ -1,93 +1,17 @@
|
||||
import type { NextPage } from 'next'
|
||||
import Head from 'next/head'
|
||||
import {useGroups} from "../../components/contexts/GroupProvider";
|
||||
import {useFactories} from "../../src/hooks/useFactories";
|
||||
import {ProducingGraph} from "../../components/shared/ProducingGraph/ProducingGraph";
|
||||
import {useEffect, useMemo} from "react";
|
||||
import {calculateInputs} from "../../src/calculateInputs";
|
||||
import {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";
|
||||
import {GroupProvider} from "../../components/contexts/GroupProvider";
|
||||
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../../src/getServerSideProps";
|
||||
import {PageDetails} from "../../components/visualize/PageDetails";
|
||||
|
||||
|
||||
|
||||
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])
|
||||
|
||||
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
|
||||
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>
|
||||
</>
|
||||
<GroupProvider id={id} initial={initial}>
|
||||
<PageDetails/>
|
||||
</GroupProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export async function getServerSideProps() {
|
||||
return { props: { bodyClassName: 'scroll' } };
|
||||
}
|
||||
export const getServerSideProps = getServerSidePropsGroupProvider
|
||||
|
||||
export default Page
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import type {NextPage} from 'next'
|
||||
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 {ProducingGraph} from "../../components/shared/ProducingGraph/ProducingGraph";
|
||||
import {useEffect, useMemo} from "react";
|
||||
@@ -8,8 +8,9 @@ import {calculateInputs} from "../../src/calculateInputs";
|
||||
import {NodeOverview, OverviewGraphNode} from "../../components/visualize/NodeOverview/NodeOverview";
|
||||
import {fixedEncodeURIComponent} from "../../src/utils";
|
||||
import {ScrollContainer} from "../../components/shared/ScrollContainer/ScrollContainer";
|
||||
import {getServerSidePropsGroupProvider, PropsGroupProvider} from "../../src/getServerSideProps";
|
||||
|
||||
const Page: NextPage = () => {
|
||||
const Page: NextPage<PropsGroupProvider> = ({id, ...initial}) => {
|
||||
const {
|
||||
exportedFactories,
|
||||
ignoredFactories,
|
||||
@@ -42,7 +43,7 @@ const Page: NextPage = () => {
|
||||
}, [baseFactories, exportedFactories, findFactory, groups, ignoredFactories])
|
||||
|
||||
return (
|
||||
<>
|
||||
<GroupProvider id={id} initial={initial}>
|
||||
<Head>
|
||||
<title>Factorio Microservices</title>
|
||||
<meta name="description" content="Create Factorio microservices" />
|
||||
@@ -54,8 +55,10 @@ const Page: NextPage = () => {
|
||||
<ProducingGraph nodes={producingNodes} inputs={baseFactories} childType={NodeOverview}/>
|
||||
</ScrollContainer>
|
||||
</main>
|
||||
</>
|
||||
</GroupProvider>
|
||||
)
|
||||
}
|
||||
|
||||
export const getServerSideProps = getServerSidePropsGroupProvider
|
||||
|
||||
export default Page
|
||||
|
||||
@@ -1,19 +1,44 @@
|
||||
import {database} from "./start";
|
||||
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[]) {
|
||||
const collection = (await database.resolve())?.collection('setups')
|
||||
export interface GroupData {
|
||||
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
|
||||
await collection.deleteMany({}).catch(e => {
|
||||
if (e.message !== 'ns not found') throw e
|
||||
})
|
||||
const result = await collection.insertOne({
|
||||
groups,
|
||||
ignored,
|
||||
base,
|
||||
...data,
|
||||
createdOn: new Date(),
|
||||
modifiedOn: new Date()
|
||||
modifiedOn: new Date(),
|
||||
accessedOn: new Date()
|
||||
})
|
||||
console.log(result.insertedId, 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 seedrandom from "seedrandom";
|
||||
|
||||
|
||||
|
||||
function generateIds<T extends Dict<unknown>>(node: GraphNode<T>): GraphNodeWithIds<T> {
|
||||
function generateIds<T extends Dict<unknown>>(node: GraphNode<T>, nodeUid: () => string): GraphNodeWithIds<T> {
|
||||
return {
|
||||
...node,
|
||||
___uid: `${node.name.replace(/[^a-z]/gi, '').toLowerCase().substring(0, 3)}_${crypto.randomUUID().substring(0, 3)}`,
|
||||
___uid: `${node.name.replace(/[^a-z]/gi, '').toLowerCase().substring(0, 3)}_${nodeUid()}`,
|
||||
___uidInputs: [],
|
||||
___uidOutputs: []
|
||||
}
|
||||
}
|
||||
|
||||
function generateAdditional<T extends Dict<unknown>>(uid: string, type: 'i'|'h'|'o'): GraphNodeWithIds<AdditionalNode> {
|
||||
function generateAdditional<T extends Dict<unknown>>(uid: string, type: 'i'|'h'|'o', nodeUid: () => string): GraphNodeWithIds<AdditionalNode> {
|
||||
return {
|
||||
inputs: type !== 'i' ? [uid] : [],
|
||||
outputs: type !== 'o' ? [uid] : [],
|
||||
name: uid,
|
||||
___type: type,
|
||||
___uid: `${uid.replace(/[^a-z]/gi, '').toLowerCase().substring(0, 3)}_${crypto.randomUUID().substring(0, 3)}_${type}`,
|
||||
___uid: `${uid.replace(/[^a-z]/gi, '').toLowerCase().substring(0, 3)}_${nodeUid()}_${type}`,
|
||||
___uidInputs: [],
|
||||
___uidOutputs: []
|
||||
}
|
||||
}
|
||||
|
||||
function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNode<T>[]): [string[][], Dict<GraphNodeWithIds<T>>] {
|
||||
function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNode<T>[], nodeUid: () => string): [string[][], Dict<GraphNodeWithIds<T>>] {
|
||||
const nodesWithId: Dict<GraphNodeWithIds<T>> = {}
|
||||
const available = new Set(inputs)
|
||||
let queue = [...nodes]
|
||||
@@ -40,7 +38,7 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
|
||||
queue = queue.filter((node) => {
|
||||
const isPlaceable = node.inputs.every(input => available.has(input))
|
||||
if (isPlaceable) {
|
||||
const nodeWithId: GraphNodeWithIds<T> = generateIds(node)
|
||||
const nodeWithId: GraphNodeWithIds<T> = generateIds(node, nodeUid)
|
||||
rows[rows.length - 1].push(nodeWithId.___uid)
|
||||
nodesWithId[nodeWithId.___uid] = nodeWithId
|
||||
availableOfRow.push(...node.outputs)
|
||||
@@ -58,7 +56,7 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
|
||||
return [rows, nodesWithId]
|
||||
}
|
||||
|
||||
function addAdditionalNodes<T extends Dict<unknown>>(rowsRaw: string[][], nodesRaw: Dict<GraphNodeWithIds<T>>, inputs: string[], outputs: string[]): [string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>] {
|
||||
function addAdditionalNodes<T extends Dict<unknown>>(rowsRaw: string[][], nodesRaw: Dict<GraphNodeWithIds<T>>, inputs: string[], outputs: string[], nodeUid: () => string): [string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>] {
|
||||
const addedInputs: Dict<number> = {}
|
||||
const res: string[][] = deepcopy([[], ...rowsRaw, []])
|
||||
const resNodes: Dict<GraphNodeWithIds<T|AdditionalNode>> = deepcopy(nodesRaw)
|
||||
@@ -67,13 +65,13 @@ function addAdditionalNodes<T extends Dict<unknown>>(rowsRaw: string[][], nodesR
|
||||
for (let rowInput of rowInputs) {
|
||||
if (rowInput in addedInputs) {
|
||||
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)
|
||||
resNodes[nodeWithId.___uid] = nodeWithId
|
||||
}
|
||||
addedInputs[rowInput] = i
|
||||
} 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)
|
||||
resNodes[nodeWithId.___uid] = nodeWithId
|
||||
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))
|
||||
for (let rowOutput of rowOutputs) {
|
||||
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)
|
||||
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>>] {
|
||||
const nodeSeed = seedrandom.alea("node")
|
||||
const nodeUid = () => Math.abs(nodeSeed.int32()).toString(16).substring(0, 3)
|
||||
//console.log('---------------')
|
||||
const [rowsRaw, nodesRaw] = splitIntoRows(inputs, nodes)
|
||||
const [rowsRaw, nodesRaw] = splitIntoRows(inputs, nodes, nodeUid)
|
||||
//console.log("Step 1")
|
||||
//console.table(rowsRaw)
|
||||
//console.table(nodesRaw)
|
||||
const [rowsWithInOut, nodesWithInOut] = addAdditionalNodes(rowsRaw, nodesRaw, inputs, outputs)
|
||||
const [rowsWithInOut, nodesWithInOut] = addAdditionalNodes(rowsRaw, nodesRaw, inputs, outputs, nodeUid)
|
||||
//console.log("Step 2")
|
||||
//console.table(rowsWithInOut)
|
||||
//console.table(nodesWithInOut)
|
||||
|
||||
Reference in New Issue
Block a user