This commit is contained in:
Sebastian Seedorf
2022-08-18 09:20:00 +02:00
parent 92b762bbd2
commit de95f57b18
60 changed files with 3450 additions and 994 deletions

View File

@@ -1,20 +1,24 @@
import {EnrichedEntity} from "./types";
import { EnrichedEntity } from './types'
export const calculateInputs = (allProducingFactories: string[], ignoredFactories: string[], baseFactories: string[], exportedFactories: Set<string>, findFactory: (uid: string) => EnrichedEntity|undefined) => {
const prducingSet = new Set(allProducingFactories)
const ignored = new Set(ignoredFactories)
export const calculateInputs = (
allProducingFactories: string[],
baseFactories: string[],
exportedFactories: Set<string>,
findFactory: (uid: string) => EnrichedEntity | undefined
) => {
const producingSet = new Set(allProducingFactories)
const base = new Set(baseFactories)
const inputs = new Set<string>()
const intermediates = new Set<string>()
let next: string|undefined
while (next = allProducingFactories.pop()) {
let next: string | undefined
while ((next = allProducingFactories.pop())) {
const pres = Object.keys(findFactory(next)?.recipe?.prerequisites ?? {})
for (const pre of pres) {
if (exportedFactories.has(pre) || base.has(pre)) {
if (!prducingSet.has(pre)) inputs.add(pre)
if (!producingSet.has(pre)) inputs.add(pre)
} else if (!intermediates.has(pre)) {
if (!prducingSet.has(pre)) intermediates.add(pre)
if (!producingSet.has(pre)) intermediates.add(pre)
allProducingFactories.push(pre)
}
}

View File

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

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
import {GetServerSideProps} from "next";
import {getGroup, setGroups} from "./database/groups";
import {Dict, Group} from "./types";
import { GetServerSideProps } from 'next'
import { getGroup, setGroups } from './database/groups'
import { Dict, Group } from './types'
export interface PropsGroupProvider {
id: string
@@ -9,9 +9,11 @@ export interface PropsGroupProvider {
base: string[]
}
export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvider> = async ({query}) => {
export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvider> = async ({
query
}) => {
const id = Array.isArray(query?.id) ? query.id[0] : query?.id
const data = id && await getGroup(id)
const data = id && (await getGroup(id))
if (data) {
return {
props: {
@@ -22,15 +24,14 @@ export const getServerSidePropsGroupProvider: GetServerSideProps<PropsGroupProvi
}
}
} else if (!id) {
const newId = await setGroups({groups: {}, base: [], ignored: []})
const newId = await setGroups({ groups: {}, base: [], ignored: [] })
return {
redirect: {
destination: `?id=${newId}`,
permanent: false,
permanent: false
}
}
} else {
console.log(data)
return {
notFound: true
}

View File

@@ -1,31 +1,48 @@
import {AdditionalNode, GraphNode, GraphNodeWithIds, isAdditionalNode} from "./types";
import {Dict} from "../types";
import deepcopy from "deepcopy";
import {isNonNullable, shuffleInplace, sortByProperty, uniquify} from "../utils";
import seedrandom from "seedrandom";
import { AdditionalNode, GraphNode, GraphNodeWithIds } from './types'
import { Dict } from '../types'
import deepcopy from 'deepcopy'
import { isNonNullable, shuffleInplace, sortByProperty, uniquify } from '../utils'
import seedrandom from 'seedrandom'
function generateIds<T extends Dict<unknown>>(node: GraphNode<T>, nodeUid: () => string): GraphNodeWithIds<T> {
function generateIds<T extends Dict<unknown>>(
node: GraphNode<T>,
nodeUid: () => string
): GraphNodeWithIds<T> {
return {
...node,
___uid: `${node.name.replace(/[^a-z]/gi, '').toLowerCase().substring(0, 3)}_${nodeUid()}`,
___uid: `${node.name
.replace(/[^a-z]/gi, '')
.toLowerCase()
.substring(0, 3)}_${nodeUid()}`,
___uidInputs: [],
___uidOutputs: []
}
}
function generateAdditional<T extends Dict<unknown>>(uid: string, type: 'i'|'h'|'o', nodeUid: () => string): GraphNodeWithIds<AdditionalNode> {
function generateAdditional(
uid: string,
type: 'i' | 'h' | 'o',
nodeUid: () => string
): GraphNodeWithIds<AdditionalNode> {
return {
inputs: type !== 'i' ? [uid] : [],
outputs: type !== 'o' ? [uid] : [],
name: uid,
___type: type,
___uid: `${uid.replace(/[^a-z]/gi, '').toLowerCase().substring(0, 3)}_${nodeUid()}_${type}`,
___uid: `${uid
.replace(/[^a-z]/gi, '')
.toLowerCase()
.substring(0, 3)}_${nodeUid()}_${type}`,
___uidInputs: [],
___uidOutputs: []
}
}
function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNode<T>[], nodeUid: () => string): [string[][], Dict<GraphNodeWithIds<T>>] {
function splitIntoRows<T extends Dict<unknown>>(
inputs: string[],
nodes: GraphNode<T>[],
nodeUid: () => string
): [string[][], Dict<GraphNodeWithIds<T>>] {
const nodesWithId: Dict<GraphNodeWithIds<T>> = {}
const available = new Set(inputs)
let queue = [...nodes]
@@ -35,7 +52,7 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
const availableOfRow: string[] = []
rows.push([])
queue = queue.filter((node) => {
queue = queue.filter(node => {
const isPlaceable = node.inputs.every(input => available.has(input))
if (isPlaceable) {
const nodeWithId: GraphNodeWithIds<T> = generateIds(node, nodeUid)
@@ -48,7 +65,7 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
availableOfRow.map(uid => available.add(uid))
if (amount === queue.length) {
console.warn("Loop detected! Left over:", queue)
console.warn('Loop detected! Left over:', queue)
rows.pop()
break
}
@@ -56,78 +73,123 @@ function splitIntoRows<T extends Dict<unknown>>(inputs: string[], nodes: GraphNo
return [rows, nodesWithId]
}
function addAdditionalNodes<T extends Dict<unknown>>(rowsRaw: string[][], nodesRaw: Dict<GraphNodeWithIds<T>>, inputs: string[], outputs: string[], nodeUid: () => string): [string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>] {
function addAdditionalNodes<T extends Dict<unknown>>(
rowsRaw: string[][],
nodesRaw: Dict<GraphNodeWithIds<T>>,
inputs: string[],
outputs: string[],
nodeUid: () => string
): [string[][], Dict<GraphNodeWithIds<T | AdditionalNode>>] {
const addedInputs: Dict<number> = {}
const res: string[][] = deepcopy([[], ...rowsRaw, []])
const resNodes: Dict<GraphNodeWithIds<T|AdditionalNode>> = deepcopy(nodesRaw)
const resNodes: Dict<GraphNodeWithIds<T | AdditionalNode>> = deepcopy(nodesRaw)
for (let i = 0; i < rowsRaw.length; i++) {
const rowInputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].inputs))
for (let rowInput of rowInputs) {
for (const rowInput of rowInputs) {
if (rowInput in addedInputs) {
for (let j = addedInputs[rowInput]+1; j < i+1; j++) {
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowInput, 'h', nodeUid)
for (let j = addedInputs[rowInput] + 1; j < i + 1; j++) {
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(
rowInput,
'h',
nodeUid
)
res[j].push(nodeWithId.___uid)
resNodes[nodeWithId.___uid] = nodeWithId
}
addedInputs[rowInput] = i
} else if (inputs.includes(rowInput)) {
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowInput, 'i', nodeUid)
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(
rowInput,
'i',
nodeUid
)
res[i].push(nodeWithId.___uid)
resNodes[nodeWithId.___uid] = nodeWithId
addedInputs[rowInput] = i
}
}
const rowOutputs = uniquify(rowsRaw[i].flatMap(row => resNodes[row].outputs))
for (let rowOutput of rowOutputs) {
for (const rowOutput of rowOutputs) {
if (outputs?.includes(rowOutput)) {
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(rowOutput, 'o', nodeUid)
res[i+2].push(nodeWithId.___uid)
const nodeWithId: GraphNodeWithIds<AdditionalNode> = generateAdditional(
rowOutput,
'o',
nodeUid
)
res[i + 2].push(nodeWithId.___uid)
resNodes[nodeWithId.___uid] = nodeWithId
}
addedInputs[rowOutput] = i+1
addedInputs[rowOutput] = i + 1
}
}
if (res[res.length-1].length === 0) res.splice(res.length-1, 1)
if (res[res.length - 1].length === 0) res.splice(res.length - 1, 1)
return [res, resNodes]
}
function linkNodes<T extends Dict<unknown>>(rowsWithInOut: string[][], nodesWithInOut: Dict<GraphNodeWithIds<T|AdditionalNode>>): Dict<GraphNodeWithIds<T|AdditionalNode>> {
type Store = {input: Dict<string[]>[], output: Dict<string[]>[]}
function linkNodes<T extends Dict<unknown>>(
rowsWithInOut: string[][],
nodesWithInOut: Dict<GraphNodeWithIds<T | AdditionalNode>>
): Dict<GraphNodeWithIds<T | AdditionalNode>> {
type Store = { input: Dict<string[]>[], output: Dict<string[]>[] }
const store: Store = {
input: Array.from(rowsWithInOut, Object),
output: Array.from(rowsWithInOut, Object)
}
const nodesPremapping = (node: GraphNodeWithIds<T|AdditionalNode>, rowIdx: number) => {
node.inputs.forEach(input => store.input[rowIdx][input] = [...(store.input[rowIdx][input] ?? []), node.___uid])
node.outputs.forEach(output => store.output[rowIdx][output] = [...(store.output[rowIdx][output] ?? []), node.___uid])
};
const linkInOut = (node: GraphNodeWithIds<T|AdditionalNode>, rowIdx: number) => {
const nodesPremapping = (node: GraphNodeWithIds<T | AdditionalNode>, rowIdx: number) => {
node.inputs.forEach(
input => (store.input[rowIdx][input] = [...(store.input[rowIdx][input] ?? []), node.___uid])
)
node.outputs.forEach(
output =>
(store.output[rowIdx][output] = [...(store.output[rowIdx][output] ?? []), node.___uid])
)
}
const linkInOut = (node: GraphNodeWithIds<T | AdditionalNode>, rowIdx: number) => {
if (rowIdx > 0)
node.___uidInputs = uniquify(node.inputs.flatMap(input => store.output[rowIdx - 1][input]).filter(isNonNullable))
if (rowIdx < rowsWithInOut.length-1)
node.___uidOutputs = uniquify(node.outputs.flatMap(output => store.input[rowIdx + 1][output]).filter(isNonNullable))
};
node.___uidInputs = uniquify(
node.inputs.flatMap(input => store.output[rowIdx - 1][input]).filter(isNonNullable)
)
if (rowIdx < rowsWithInOut.length - 1)
node.___uidOutputs = uniquify(
node.outputs.flatMap(output => store.input[rowIdx + 1][output]).filter(isNonNullable)
)
}
rowsWithInOut.forEach((row, rowIdx) => row.forEach(uid => nodesPremapping(nodesWithInOut[uid], rowIdx)))
rowsWithInOut.forEach((row, rowIdx) =>
row.forEach(uid => nodesPremapping(nodesWithInOut[uid], rowIdx))
)
rowsWithInOut.forEach((row, rowIdx) => row.forEach(uid => linkInOut(nodesWithInOut[uid], rowIdx)))
return nodesWithInOut
}
function crossingsOf<T extends Dict<unknown>>(fixed: string[], flex: string[], nodes: Dict<GraphNodeWithIds<T|AdditionalNode>>, isDown: boolean): [number[][], number] {
function crossingsOf<T extends Dict<unknown>>(
fixed: string[],
flex: string[],
nodes: Dict<GraphNodeWithIds<T | AdditionalNode>>,
isDown: boolean
): [number[][], number] {
const result = Array.from(flex, () => Array.from(flex, () => 9999999))
let score = 0
for (let i = 0; i < flex.length-1; i++) {
for (let j = i+1; j < flex.length; j++) {
for (let i = 0; i < flex.length - 1; i++) {
for (let j = i + 1; j < flex.length; j++) {
const inputsI = new Set(nodes[flex[i]][isDown ? '___uidInputs' : '___uidOutputs'])
const inputsJ = new Set(nodes[flex[j]][isDown ? '___uidInputs' : '___uidOutputs'])
const diff = fixed.reduce(([size, acc], curr) => {
inputsI.has(curr) && size--
return [size, acc + (inputsJ.has(curr) ? size : 0)]
}, [inputsI.size, 0])[1] - fixed.reduce(([size, acc], curr) => {
inputsJ.has(curr) && size--
return [size, acc + (inputsI.has(curr) ? size : 0)]
}, [inputsJ.size, 0])[1]
const diff =
fixed.reduce(
([size, acc], curr) => {
inputsI.has(curr) && size--
return [size, acc + (inputsJ.has(curr) ? size : 0)]
},
[inputsI.size, 0]
)[1] -
fixed.reduce(
([size, acc], curr) => {
inputsJ.has(curr) && size--
return [size, acc + (inputsI.has(curr) ? size : 0)]
},
[inputsJ.size, 0]
)[1]
result[i][j] = diff
result[j][i] = -diff
score += diff
@@ -136,82 +198,102 @@ function crossingsOf<T extends Dict<unknown>>(fixed: string[], flex: string[], n
return [result, score]
}
function optimizeOrder<T extends Dict<unknown>>(rowsWithInOut: string[][], nodesWithInOut: Dict<GraphNodeWithIds<T|AdditionalNode>>): [string[][], number] {
function addCosts(costsUp: [number[][], number], costsDown: [number[][], number]): [number[][], number] {
function optimizeOrder<T extends Dict<unknown>>(
rowsWithInOut: string[][],
nodesWithInOut: Dict<GraphNodeWithIds<T | AdditionalNode>>
): [string[][], number] {
function addCosts(
costsUp: [number[][], number],
costsDown: [number[][], number]
): [number[][], number] {
return [
costsUp[0].map((row, rowIdx) => row.map((col, colIdx) => col+costsDown[0][rowIdx][colIdx])),
costsUp[0].map((row, rowIdx) => row.map((col, colIdx) => col + costsDown[0][rowIdx][colIdx])),
costsUp[1] + costsDown[1]
]
}
function improveRow(top: string[]|undefined, mid: string[], bot: string[]|undefined) {
function improveRow(top: string[] | undefined, mid: string[], bot: string[] | undefined) {
const costsUp = top ? crossingsOf(top, mid, nodesWithInOut, true) : undefined
const costsDown = bot ? crossingsOf(bot, mid, nodesWithInOut, false) : undefined
const [costs, scoreConst] = costsUp && costsDown ? addCosts(costsUp, costsDown) : costsDown ?? costsUp ?? [undefined, 0]
const [costs, scoreConst] =
costsUp && costsDown ? addCosts(costsUp, costsDown) : costsDown ?? costsUp ?? [undefined, 0]
let score = scoreConst
if (!costs) return score
let improvementInRow = true
while (improvementInRow) {
improvementInRow = false
const colBest = costs
.map((_, idx) => costs
.slice(0, idx)
.map(r => r[idx])
.reverse()
.reduce(([sum, best], curr, i) => {
return sum + curr > best.sum
? [sum + curr, {sum: sum+curr, move: -i-1, idx}] as const
: [sum + curr, best] as const
}, [0, {sum: -10000, move: 0, idx: 0}] as readonly [number, Reduce])[1]
.map(
(_, idx) =>
costs
.slice(0, idx)
.map(r => r[idx])
.reverse()
.reduce(
([sum, best], curr, i) => {
return sum + curr > best.sum
? ([sum + curr, { sum: sum + curr, move: -i - 1, idx }] as const)
: ([sum + curr, best] as const)
},
[0, { sum: -10000, move: 0, idx: 0 }] as readonly [number, Reduce]
)[1]
)
.filter(isNonNullable)
const rowBest = costs
.map((_, idx) => costs[idx]
.slice(idx+1)
.reduce(([sum, best], curr, i) => {
return sum + curr > best.sum
? [sum + curr, {sum: sum+curr, move: i+1, idx}] as const
: [sum + curr, best] as const
}, [0, {sum: -10000, move: 0, idx: 0}] as readonly [number, Reduce])[1]
.map(
(_, idx) =>
costs[idx].slice(idx + 1).reduce(
([sum, best], curr, i) => {
return sum + curr > best.sum
? ([sum + curr, { sum: sum + curr, move: i + 1, idx }] as const)
: ([sum + curr, best] as const)
},
[0, { sum: -10000, move: 0, idx: 0 }] as readonly [number, Reduce]
)[1]
)
.filter(isNonNullable)
const replacement = [...colBest, ...rowBest].sort(sortByProperty(red => -red.sum))[0]
if (replacement.sum > 0) {
score -= 2*replacement.sum
score -= 2 * replacement.sum
improvement = true
improvementInRow = true
costs.splice(replacement.move+replacement.idx, 0, ...costs.splice(replacement.idx, 1))
costs.map(col => col.splice(replacement.move+replacement.idx, 0, ...col.splice(replacement.idx, 1)))
mid.splice(replacement.move+replacement.idx, 0, ...mid.splice(replacement.idx, 1))
costs.splice(replacement.move + replacement.idx, 0, ...costs.splice(replacement.idx, 1))
costs.map(col =>
col.splice(replacement.move + replacement.idx, 0, ...col.splice(replacement.idx, 1))
)
mid.splice(replacement.move + replacement.idx, 0, ...mid.splice(replacement.idx, 1))
}
}
return score
}
type Reduce = {sum: number, move: number, idx: number}
type Reduce = { sum: number, move: number, idx: number }
let improvement = true
let scores: number[] = []
const scores: number[] = []
while (improvement) {
improvement = false
rowsWithInOut.reduce((top, mid, idx) => {
scores[idx] = improveRow(top, mid, rowsWithInOut[idx+1])
scores[idx] = improveRow(top, mid, rowsWithInOut[idx + 1])
return mid
}, undefined as string[]|undefined)
}, undefined as string[] | undefined)
rowsWithInOut.reduceRight((bot, mid, idx) => {
scores[idx] = improveRow(rowsWithInOut[idx-1], mid, bot)
scores[idx] = improveRow(rowsWithInOut[idx - 1], mid, bot)
return mid
}, undefined as string[]|undefined)
}, undefined as string[] | undefined)
}
return [rowsWithInOut, scores.reduce((a, b) => a+b)]
return [rowsWithInOut, scores.reduce((a, b) => a + b)]
}
export function findBest<T extends Dict<unknown>>(rowsWithInOut: string[][], nodesWithInOut: Dict<GraphNodeWithIds<T|AdditionalNode>>, timeLimit: number) {
export function findBest<T extends Dict<unknown>>(
rowsWithInOut: string[][],
nodesWithInOut: Dict<GraphNodeWithIds<T | AdditionalNode>>,
timeLimit: number
) {
let bestScore = Infinity
let bestRows = deepcopy(rowsWithInOut)
let limit = Date.now() + timeLimit
const limit = Date.now() + timeLimit
let iterSinceImprovements = 0
let rng = seedrandom.alea("We are SEEED, ya!")
const rng = seedrandom.alea('We are SEEED, ya!')
while (true) {
if (Date.now() > limit) break
if (iterSinceImprovements > 100) break
@@ -223,21 +305,31 @@ export function findBest<T extends Dict<unknown>>(rowsWithInOut: string[][], nod
} else {
iterSinceImprovements++
}
rowsOptimized.forEach((row, ) => shuffleInplace(row, rng))
rowsOptimized.forEach(row => shuffleInplace(row, rng))
}
console.log(bestScore)
return bestRows
}
export function graphUntangled<T extends Dict<unknown>>(nodes: GraphNode<T>[], inputs: string[], outputs: string[], timeLimit = 0): [string[][], Dict<GraphNodeWithIds<T|AdditionalNode>>] {
const nodeSeed = seedrandom.alea("node")
export function graphUntangled<T extends Dict<unknown>>(
nodes: GraphNode<T>[],
inputs: string[],
outputs: string[],
timeLimit = 0
): [string[][], Dict<GraphNodeWithIds<T | AdditionalNode>>] {
const nodeSeed = seedrandom.alea('node')
const nodeUid = () => Math.abs(nodeSeed.int32()).toString(16).substring(0, 3)
//console.log('---------------')
const [rowsRaw, nodesRaw] = splitIntoRows(inputs, nodes, nodeUid)
//console.log("Step 1")
//console.table(rowsRaw)
//console.table(nodesRaw)
const [rowsWithInOut, nodesWithInOut] = addAdditionalNodes(rowsRaw, nodesRaw, inputs, outputs, nodeUid)
const [rowsWithInOut, nodesWithInOut] = addAdditionalNodes(
rowsRaw,
nodesRaw,
inputs,
outputs,
nodeUid
)
//console.log("Step 2")
//console.table(rowsWithInOut)
//console.table(nodesWithInOut)

View File

@@ -1,4 +1,4 @@
import {Dict} from "../types";
import { Dict } from '../types'
interface GraphNodeBase {
inputs: string[]
@@ -14,7 +14,8 @@ export type GraphNodeWithIds<T extends Dict<unknown>> = GraphNode<T> & {
}
export type AdditionalNode = {
___type: 'i'|'h'|'o'
___type: 'i' | 'h' | 'o'
}
export const isAdditionalNode = (node: unknown): node is GraphNodeWithIds<AdditionalNode> => !!(node && typeof node === 'object' && '___type' in node)
export const isAdditionalNode = (node: unknown): node is GraphNodeWithIds<AdditionalNode> =>
!!(node && typeof node === 'object' && '___type' in node)

View File

@@ -8,18 +8,18 @@ export function useEventListener<K extends keyof WindowEventMap>(
eventName: K,
handler: (event: WindowEventMap[K]) => void,
element?: undefined,
options?: boolean | AddEventListenerOptions,
options?: boolean | AddEventListenerOptions
): void
// Element Event based useEventListener interface
export function useEventListener<
K extends keyof HTMLElementEventMap,
T extends HTMLElement = HTMLDivElement,
>(
T extends HTMLElement = HTMLDivElement
>(
eventName: K,
handler: (event: HTMLElementEventMap[K]) => void,
element: RefObject<T>,
options?: boolean | AddEventListenerOptions,
options?: boolean | AddEventListenerOptions
): void
// Document Event based useEventListener interface
@@ -27,20 +27,18 @@ export function useEventListener<K extends keyof DocumentEventMap>(
eventName: K,
handler: (event: DocumentEventMap[K]) => void,
element: RefObject<Document>,
options?: boolean | AddEventListenerOptions,
options?: boolean | AddEventListenerOptions
): void
export function useEventListener<
KW extends keyof WindowEventMap,
KH extends keyof HTMLElementEventMap,
T extends HTMLElement | void = void,
>(
T extends HTMLElement | void = void
>(
eventName: KW | KH,
handler: (
event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event,
) => void,
handler: (event: WindowEventMap[KW] | HTMLElementEventMap[KH] | Event) => void,
element?: RefObject<T>,
options?: boolean | AddEventListenerOptions,
options?: boolean | AddEventListenerOptions
) {
// Create a ref that stores handler
const savedHandler = useRef(handler)

View File

@@ -1,23 +1,23 @@
import {EnrichedEntity, Entity} from "../types";
import details from "../../res/details.json";
import manual from "../../res/manual.json";
import { EnrichedEntity, Entity } from '../types'
import details from '../../res/details.json'
import manual from '../../res/manual.json'
const joined = [...details, ...manual] as Entity[]
const factories = joined.map((detail: EnrichedEntity) => {
detail.usedBy = joined
.filter(f => Object
.keys(f.recipe?.prerequisites ?? {})
.includes(detail.href)
)
return detail;
detail.usedBy = joined.filter(f =>
Object.keys(f.recipe?.prerequisites ?? {}).includes(detail.href)
)
return detail
})
const detailsMap = Object.fromEntries(factories.map((detail: EnrichedEntity) => [detail.href, detail]))
const detailsMap = Object.fromEntries(
factories.map((detail: EnrichedEntity) => [detail.href, detail])
)
export const useFactories = () => ({
factories,
findFactory: (uid: string): EnrichedEntity|undefined => {
findFactory: (uid: string): EnrichedEntity | undefined => {
return detailsMap[uid]
}
})

View File

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

View File

@@ -1,10 +1,4 @@
import {
Dispatch,
SetStateAction,
useCallback,
useEffect,
useState,
} from 'react'
import { Dispatch, SetStateAction, useCallback, useEffect, useState } from 'react'
// See: https://usehooks-ts.com/react-hook/use-event-listener
import { useEventListener } from './useEventListener'
@@ -41,30 +35,33 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
// Return a wrapped version of useState's setter function that ...
// ... persists the new value to localStorage.
const setValue: SetValue<T> = useCallback(value => {
// Prevent build error "window is undefined" but keeps working
if (typeof window == 'undefined') {
console.warn(
`Tried setting localStorage key “${key}” even though environment is not a client`,
)
}
const setValue: SetValue<T> = useCallback(
value => {
// Prevent build error "window is undefined" but keeps working
if (typeof window == 'undefined') {
console.warn(
`Tried setting localStorage key “${key}” even though environment is not a client`
)
}
try {
// Allow value to be a function so we have the same API as useState
const newValue = value instanceof Function ? value(storedValue) : value
try {
// Allow value to be a function so we have the same API as useState
const newValue = value instanceof Function ? value(storedValue) : value
// Save to local storage
window.localStorage.setItem(key, JSON.stringify(newValue))
// Save to local storage
window.localStorage.setItem(key, JSON.stringify(newValue))
// Save state
setStoredValue(newValue)
// Save state
setStoredValue(newValue)
// We dispatch a custom event so every useLocalStorage hook are notified
window.dispatchEvent(new Event('local-storage'))
} catch (error) {
console.warn(`Error setting localStorage key “${key}”:`, error)
}
}, [key, storedValue])
// We dispatch a custom event so every useLocalStorage hook are notified
window.dispatchEvent(new Event('local-storage'))
} catch (error) {
console.warn(`Error setting localStorage key “${key}”:`, error)
}
},
[key, storedValue]
)
useEffect(() => {
setStoredValue(readValue())
@@ -78,7 +75,7 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
}
setStoredValue(readValue())
},
[key, readValue],
[key, readValue]
)
// this only works for other documents, not the current one

6
src/next-types.d.ts vendored
View File

@@ -1,7 +1,3 @@
declare module 'next/config' {
export interface ServerRuntimeConfig {
MONGO_URL: string
@@ -15,7 +11,7 @@ declare module 'next/config' {
}
const getConfig: () => {
serverRuntimeConfig: ServerRuntimeConfig,
serverRuntimeConfig: ServerRuntimeConfig
publicRuntimeConfig: PublicRuntimeConfig
}
export default getConfig

View File

@@ -1,14 +1,14 @@
export function createPath(container: DOMRect, start: DOMRect, end: DOMRect) {
const startX = Math.round(start.x + start.width/2 - container.x)
const startX = Math.round(start.x + start.width / 2 - container.x)
const startY = Math.round(start.bottom - container.y)
const endX = Math.round(end.x + end.width/2 - container.x)
const endX = Math.round(end.x + end.width / 2 - container.x)
const endY = Math.round(end.top - container.y)
const mid = Math.round((start.bottom + end.top) / 2 - container.y)
return `M${startX},${startY} C${startX},${mid} ${endX},${mid} ${endX},${endY}`
}
export function drawLine(container: DOMRect, elem: DOMRect) {
const x = Math.round(elem.x + elem.width/2 - container.x)
const x = Math.round(elem.x + elem.width / 2 - container.x)
const top = Math.round(elem.top - container.y)
const bottom = Math.round(elem.bottom - container.y)
return `M${x},${top} L${x},${bottom}`

View File

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

View File

@@ -1,5 +1,5 @@
import {Dict} from "./types";
import {PRNG} from "seedrandom";
import { Dict } from './types'
import { PRNG } from 'seedrandom'
export function isNonNullable<T>(any: T): any is NonNullable<T> {
return any !== undefined && any !== null
@@ -29,12 +29,12 @@ export function uniquify<T>(array: T[]): T[] {
export function shuffleInplace<T>(array: T[], rng: PRNG): T[] {
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(rng.quick() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
const j = Math.floor(rng.quick() * (i + 1))
;[array[i], array[j]] = [array[j], array[i]]
}
return array
}
export function fixedEncodeURIComponent(str: string): string {
return encodeURIComponent(str).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16));
return encodeURIComponent(str).replace(/[!'()*]/g, c => '%' + c.charCodeAt(0).toString(16))
}

View File

@@ -32,6 +32,7 @@ class FetchOnce<T> {
this.pendingList.push([resolve, reject])
break
case ResolvableState.DONE:
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
resolve(this.data!)
break
case ResolvableState.ERROR:

View File

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

View File

@@ -1,3 +1,4 @@
/* eslint-disable no-console */
export const logger = {
verbose: console.log,
debug: console.log,

View File

@@ -6,9 +6,11 @@ import { compile, JSONSchema } from 'json-schema-to-typescript'
import * as fs from 'fs/promises'
import { join } from 'path'
import { NetworkError } from '../utils/errors'
import getConfig from "next/config";
import getConfig from 'next/config'
const {publicRuntimeConfig: {TENANT_TYPE}} = getConfig()
const {
publicRuntimeConfig: { TENANT_TYPE }
} = getConfig()
const validatorStorage = new Validator()

View File

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