Added GroupProvider

This commit is contained in:
Sebastian Seedorf
2022-08-10 15:58:03 +02:00
parent 8dfc844c24
commit e4250f0344
6 changed files with 208 additions and 126 deletions

View File

@@ -0,0 +1,126 @@
import {createContext, FC, useContext, useMemo, useState} from "react";
import {Group, NewGroup} from "../../src/types";
import {useLocalStorage} from "../../src/hooks/useLocalStorage";
import {sortByProperty} from "../../src/utils";
import {ReactNodeLike} from "prop-types";
interface Props {
children: ReactNodeLike
}
interface GroupContextType {
doNotSuggest: Set<string>
ignoredFactories: string[]
setIgnoredFactories(factories: string[]): void
baseFactories: string[]
setBaseFactories(factories: string[]): void
groups: NewGroup[]
addGroup(name: string, exported?: string[], malls?: string[]): void
removeGroup(idx: number): void
renameGroup(idx: number, newName: string): void
getGroup(idx: number): NewGroup
setFactories(idx: number, factories: string[], type: 'inputs'|'intermediates'|'exports'|'malls'): void
getInputType(uid: string): 'base'|'produced'|'unknown'
}
const defaultValues: GroupContextType = {
doNotSuggest: new Set(),
ignoredFactories: [],
setIgnoredFactories() {},
baseFactories: [],
setBaseFactories() {},
groups: [],
addGroup() {},
removeGroup() {},
renameGroup() {},
getGroup() {return {name: 'Lorem', inputs: [], intermediates: [], exports: [], malls: []}},
setFactories() {},
getInputType() {return 'unknown'}
}
const GroupContext = createContext<GroupContextType>(defaultValues);
export const useGroups = () => useContext(GroupContext)
export const GroupProvider: FC<Props> = ({children}) => {
const [excludedSuggestions, setExcludedSuggestions] = useLocalStorage<string[]>('excludedSuggestions', [])
const [basicValues, setBasicValues] = useLocalStorage<string[]>('basicValues', [])
const [oldGroups, setGroups] = useLocalStorage<Group[]>('serviceGroups', [])
const groups = useMemo<NewGroup[]>(() => {
return oldGroups.map(groupToNewGroup)
}, [oldGroups])
const doNotSuggest = useMemo<Set<string>>(() => {
return new Set([...groups.flatMap(group => [...group.exports, ...group.malls, ...(group.malls.length ? group.intermediates : [])]), ...excludedSuggestions, ...basicValues])
}, [basicValues, groups, excludedSuggestions])
const exportedFactories = useMemo<Set<string>>(() => {
return new Set([...groups.flatMap(group => [...group.exports])])
}, [groups])
const value: GroupContextType = {
doNotSuggest,
ignoredFactories: excludedSuggestions,
setIgnoredFactories: setExcludedSuggestions,
baseFactories: basicValues,
setBaseFactories: setBasicValues,
groups,
addGroup(name: string, exports: string[] = [], malls: string[] = []) {
setGroups(groups => {
groups.push({ name, inputs: [], intermediates: [], exports, malls })
return groups.sort(sortByProperty(group => group.name))
})
},
removeGroup(idx: number) {
setGroups(groups => {
groups.splice(idx, 1)
return groups
})
},
renameGroup(idx: number, newName: string) {
setGroups(groups => {
groups[idx].name = newName
return groups.sort(sortByProperty(group => group.name))
})
},
getGroup(idx: number) {
return groups[idx]
},
setFactories(idx: number, factories: string[], type: 'inputs'|'intermediates'|'exports'|'malls') {
setGroups(groups => {
const group = groupToNewGroup(groups[idx])
group[type] = factories
groups[idx] = group
return groups
})
},
getInputType(uid: string) {
if (basicValues.includes(uid)) return 'base'
else if (exportedFactories.has(uid)) return 'produced'
else return 'unknown'
}
}
return <GroupContext.Provider value={value}>{children}</GroupContext.Provider>
}
function groupToNewGroup(group: Group): NewGroup {
return 'malls' in group ? group : {
name: group.name,
inputs: group.inputs,
intermediates: group.intermediates,
exports: group.isExported ? group.factories : [],
malls: !group.isExported ? group.factories : []
}
}

View File

@@ -4,58 +4,45 @@ import {useDetails} from "../../../src/hooks/useDetails";
import {Entity, Group} from "../../../src/types"; import {Entity, Group} from "../../../src/types";
import styles from "./Group.module.css" import styles from "./Group.module.css"
import {EntitySpan} from "../EntitySpan/EntitySpan"; import {EntitySpan} from "../EntitySpan/EntitySpan";
import {useGroups} from "../../contexts/GroupProvider";
interface Props { interface Props {
onRemove: () => void index: number
onSetOutputFactories: (uids: string[]) => void
onSetIntermediateFactories: (uids: string[]) => void
onSetInputFactories: (uids: string[]) => void
onToggleExported: () => void
onRename: (name: string) => void
onDoIgnore: (name: string) => void
group: Group
sets: {
doNotSuggest: Set<string>
basic: Set<string>
exported: Set<string>
}
} }
export const GroupBox: FC<Props> = ({ export const GroupBox: FC<Props> = ({ index }) => {
onRemove, const details = useDetails()
onRename, const {
onSetOutputFactories, getGroup,
onSetIntermediateFactories, doNotSuggest,
onSetInputFactories, setFactories,
onToggleExported, ignoredFactories,
group: { setIgnoredFactories,
renameGroup,
removeGroup,
getInputType
} = useGroups()
const {
name,
inputs, inputs,
intermediates, intermediates,
factories, exports,
isExported, malls
name } = getGroup(index)
},
sets: {
doNotSuggest,
basic,
exported
},
onDoIgnore
}) => {
const details = useDetails()
const calculatedInputs = useMemo<string[]>(() => { const calculatedInputs = useMemo<string[]>(() => {
const allProducingFactories = [...intermediates, ...exports, ...malls]
const newData: string[] = details const newData: string[] = details
.filter(detail => intermediates.includes(detail.href) || factories.includes(detail.href)) .filter(detail => allProducingFactories.includes(detail.href))
.flatMap(detail => Object.keys(detail.recipe?.prerequisites ?? {})) .flatMap(detail => Object.keys(detail.recipe?.prerequisites ?? {}))
const uniqueInputs = Array.from(new Set(newData)) const uniqueInputs = Array.from(new Set(newData))
return uniqueInputs return uniqueInputs
.filter(input => !intermediates.includes(input) && !factories.includes(input)) .filter(input => !allProducingFactories.includes(input))
}, [details, intermediates, factories]) }, [details, intermediates, exports, malls])
const suggestions = useMemo<Entity[]>(() => { const suggestions = useMemo<Entity[]>(() => {
const availableIngredients = Array.from(new Set([...intermediates, ...factories, ...calculatedInputs, ...inputs])) const selectedValues = Array.from(new Set([...inputs, ...intermediates, ...exports, ...malls]))
const selectedValues = Array.from(new Set([...intermediates, ...factories, ...inputs])) const availableIngredients = Array.from(new Set([...selectedValues, ...calculatedInputs]))
return details return details
.filter(detail => { .filter(detail => {
if (!detail.recipe) return false if (!detail.recipe) return false
@@ -64,14 +51,10 @@ export const GroupBox: FC<Props> = ({
const prerequisites = Object.keys(detail.recipe?.prerequisites ?? {}) const prerequisites = Object.keys(detail.recipe?.prerequisites ?? {})
return prerequisites.every(pre => availableIngredients.includes(pre)) return prerequisites.every(pre => availableIngredients.includes(pre))
}) })
}, [inputs, doNotSuggest, details, calculatedInputs, intermediates, factories]) }, [doNotSuggest, details, calculatedInputs, inputs, intermediates, exports, malls])
const addIntermediateFactory = (uid: string) => { const addFactory = (uid: string, type: Parameters<typeof setFactories>[2]) => {
onSetIntermediateFactories([...intermediates, uid]) setFactories(index, [...intermediates, uid], 'intermediates')
}
const addOutputFactory = (uid: string) => {
onSetOutputFactories([...factories, uid])
} }
return <div style={{border: "2px solid black", padding: "0.5em", margin: "1em"}}> return <div style={{border: "2px solid black", padding: "0.5em", margin: "1em"}}>
@@ -81,27 +64,31 @@ export const GroupBox: FC<Props> = ({
suppressContentEditableWarning={true} suppressContentEditableWarning={true}
onBlur={event => { onBlur={event => {
event.currentTarget.innerText = event.currentTarget.innerText.trim() event.currentTarget.innerText = event.currentTarget.innerText.trim()
onRename(event.currentTarget.innerText); renameGroup(index, event.currentTarget.innerText);
}} }}
> >
{name} {name}
</h3> </h3>
<button onClick={onRemove} style={{display: 'block'}}>X</button> <button onClick={() => removeGroup(index)} style={{display: 'block'}}>X</button>
<input type={"checkbox"} onChange={onToggleExported} checked={isExported} style={{display: 'block'}}/>
<label>Additional Inputs</label> <label>Additional Inputs</label>
<FactorySelect <FactorySelect
factories={inputs} factories={inputs}
onSetFactories={onSetInputFactories} onSetFactories={factories => setFactories(index, factories, 'inputs')}
/> />
<label>Intermediate Factories</label> <label>Intermediate Factories</label>
<FactorySelect <FactorySelect
factories={intermediates} factories={intermediates}
onSetFactories={onSetIntermediateFactories} onSetFactories={factories => setFactories(index, factories, 'intermediates')}
/> />
<label>Output Factories</label> <label>Exported Factories</label>
<FactorySelect <FactorySelect
factories={factories} factories={exports}
onSetFactories={onSetOutputFactories} onSetFactories={factories => setFactories(index, factories, 'exports')}
/>
<label>Mall Factories</label>
<FactorySelect
factories={malls}
onSetFactories={factories => setFactories(index, factories, 'malls')}
/> />
<div className={styles.grid}> <div className={styles.grid}>
<div> <div>
@@ -110,8 +97,8 @@ export const GroupBox: FC<Props> = ({
{ {
calculatedInputs.map(input => <li key={input}><EntitySpan calculatedInputs.map(input => <li key={input}><EntitySpan
value={input} value={input}
onClick={() => addIntermediateFactory(input)} onClick={() => addFactory(input, 'intermediates')}
style={{color: basic.has(input) ? 'darkgreen' : exported.has(input) ? 'orange' : undefined}} style={{color: {base: 'darkgreen', produced: 'orange', unknown: undefined}[getInputType(input)]}}
leftClickText={"Add to intermediate factories"} leftClickText={"Add to intermediate factories"}
/></li>) /></li>)
} }
@@ -123,12 +110,12 @@ export const GroupBox: FC<Props> = ({
{suggestions.map(suggestion => <li key={suggestion.href}> {suggestions.map(suggestion => <li key={suggestion.href}>
<EntitySpan <EntitySpan
value={suggestion} value={suggestion}
onClick={() => addOutputFactory(suggestion.href)} onClick={() => addFactory(suggestion.href, 'exports')}
onContextMenu={event => { onContextMenu={event => {
event.preventDefault() event.preventDefault()
onDoIgnore(suggestion.href) setIgnoredFactories([...ignoredFactories, suggestion.href])
}} }}
leftClickText={"Add to output factories"} leftClickText={"Add to exported factories"}
rightClickText={"Exclude this recipe from suggestions"} rightClickText={"Exclude this recipe from suggestions"}
/> />
</li>)} </li>)}

View File

@@ -8,60 +8,25 @@ import {useDetails} from "../../src/hooks/useDetails";
import {Entity, Group} from "../../src/types"; import {Entity, Group} from "../../src/types";
import pako from 'pako'; import pako from 'pako';
import {EntitySpan} from "./EntitySpan/EntitySpan"; import {EntitySpan} from "./EntitySpan/EntitySpan";
import {useGroups} from "../contexts/GroupProvider";
export const HomeComponent: FC = () => { export const HomeComponent: FC = () => {
const details = useDetails() const details = useDetails()
const {
groups,
addGroup,
doNotSuggest,
baseFactories,
setBaseFactories,
ignoredFactories,
setIgnoredFactories
} = useGroups()
const [newGroupValue, setNewGroupValue] = useState("New group") const [newGroupValue, setNewGroupValue] = useState("New group")
const [excludedSuggestions, setExcludedSuggestions] = useLocalStorage<string[]>('excludedSuggestions', [])
const [basicValues, setBasicValues] = useLocalStorage<string[]>('basicValues', [])
const [groups, setGroups] = useLocalStorage<Group[]>('serviceGroups', [])
const [clientGroups, setClientGroups] = useState<Group[]>([])
const doNotSuggest = useMemo<Set<string>>(() => {
return new Set([...groups.flatMap(group => [...(group.name.includes('Mall') ? group.intermediates : []), ...group.factories]), ...excludedSuggestions, ...basicValues])
}, [basicValues, groups, excludedSuggestions])
const basicSet = useMemo<Set<string>>(() => {
return new Set(basicValues)
}, [basicValues])
const exportedSet = useMemo<Set<string>>(() => {
return new Set(groups
.filter(group => group.isExported)
.flatMap(group => group.factories)
)
}, [groups])
const missingFactories = useMemo<Entity[]>(() => { const missingFactories = useMemo<Entity[]>(() => {
return details.filter(detail => !doNotSuggest.has(detail.href) && detail.recipe) return details.filter(detail => !doNotSuggest.has(detail.href) && detail.recipe)
}, [details, doNotSuggest]) }, [details, doNotSuggest])
useEffect(() => setClientGroups(groups), [groups])
const removeGroup = (idx: number) => setGroups(groups => {
groups.splice(idx, 1)
return groups
})
const appendGroup = useCallback((name: string, factories: string[] = []) => setGroups(groups => {
groups.push({name, factories, intermediates: [], inputs: []})
groups.sort(sortByProperty(group => group.name))
return groups
}), [setGroups])
const setFactories = useCallback((idx: number, uids: string[], key: 'intermediates'|'factories'|'inputs') => setGroups(groups => {
groups[idx][key] = uids
return groups
}), [setGroups])
const renameGroup = useCallback((idx: number, name: string) => setGroups(groups => {
groups[idx].name = name
groups.sort(sortByProperty(group => group.name))
return groups
}), [setGroups])
const toggleExported = useCallback((idx: number) => setGroups(groups => {
groups[idx].isExported = !groups[idx].isExported
groups.sort(sortByProperty(group => group.name))
return groups
}), [setGroups])
const store = () => { const store = () => {
const string = JSON.stringify(groups) const string = JSON.stringify(groups)
const btoa = (bin: Uint8Array) => Buffer.from(bin).toString('base64') const btoa = (bin: Uint8Array) => Buffer.from(bin).toString('base64')
@@ -78,22 +43,22 @@ export const HomeComponent: FC = () => {
<fieldset> <fieldset>
<legend>Basic Values</legend> <legend>Basic Values</legend>
<FactorySelect <FactorySelect
factories={basicValues} factories={baseFactories}
onSetFactories={setBasicValues} onSetFactories={setBaseFactories}
/> />
</fieldset> </fieldset>
<fieldset> <fieldset>
<legend>Ignored Values</legend> <legend>Ignored Values</legend>
<FactorySelect <FactorySelect
factories={excludedSuggestions} factories={ignoredFactories}
onSetFactories={setExcludedSuggestions} onSetFactories={setIgnoredFactories}
/> />
</fieldset> </fieldset>
<fieldset> <fieldset>
<legend>Add new groups</legend> <legend>Add new groups</legend>
<input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)}/> <input value={newGroupValue} onChange={e => setNewGroupValue(e.target.value)}/>
<button disabled={!newGroupValue} onClick={() => { <button disabled={!newGroupValue} onClick={() => {
appendGroup(newGroupValue) addGroup(newGroupValue)
setNewGroupValue("New group") setNewGroupValue("New group")
}}> }}>
Add group &quot;{newGroupValue}&quot; Add group &quot;{newGroupValue}&quot;
@@ -107,12 +72,12 @@ export const HomeComponent: FC = () => {
key={missing.href} key={missing.href}
value={missing} value={missing}
onClick={() => { onClick={() => {
appendGroup(newGroupValue !== "New group" ? newGroupValue : missing.name, [missing.href]) addGroup(newGroupValue !== "New group" ? newGroupValue : missing.name, [missing.href])
setNewGroupValue("New group") setNewGroupValue("New group")
}} }}
onContextMenu={event => { onContextMenu={event => {
event.preventDefault() event.preventDefault()
setExcludedSuggestions([...excludedSuggestions, missing.href]) setIgnoredFactories([...ignoredFactories, missing.href])
}} }}
leftClickText={"Create a new factory with this item and name"} leftClickText={"Create a new factory with this item and name"}
rightClickText={"Exclude this recipe from suggestions"} rightClickText={"Exclude this recipe from suggestions"}
@@ -122,18 +87,7 @@ export const HomeComponent: FC = () => {
</fieldset> </fieldset>
<div className={styles.grid}> <div className={styles.grid}>
{ {
clientGroups.map((group, idx) => <GroupBox groups.map((group, idx) => <GroupBox key={idx} index={idx} />)
key={idx}
group={group}
onRemove={() => removeGroup(idx)}
onRename={(name: string) => renameGroup(idx, name)}
onSetOutputFactories={uids => setFactories(idx, uids, 'factories')}
onSetIntermediateFactories={uids => setFactories(idx, uids, 'intermediates')}
onSetInputFactories={uids => setFactories(idx, uids, 'inputs')}
onToggleExported={() => toggleExported(idx)}
sets={{doNotSuggest, basic: basicSet, exported: exportedSet}}
onDoIgnore={uid => setExcludedSuggestions([...excludedSuggestions, uid])}
/>)
} }
</div> </div>
</main> </main>

View File

@@ -1,8 +1,11 @@
import '../styles/globals.css' import '../styles/globals.css'
import type { AppProps } from 'next/app' import type { AppProps } from 'next/app'
import {GroupProvider} from "../components/contexts/GroupProvider";
function MyApp({ Component, pageProps }: AppProps) { function MyApp({ Component, pageProps }: AppProps) {
return <Component {...pageProps} /> return <GroupProvider>
<Component {...pageProps} />
</GroupProvider>
} }
export default MyApp export default MyApp

View File

@@ -21,7 +21,7 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
// Get from local storage then // Get from local storage then
// parse stored json or return initialValue // parse stored json or return initialValue
const readValue = useCallback((): T => { const readValue = useCallback((): T => {
// Prevent build error "window is undefined" but keep keep working // Prevent build error "window is undefined" but keep working
if (typeof window === 'undefined') { if (typeof window === 'undefined') {
return initialValue return initialValue
} }
@@ -88,7 +88,9 @@ export function useLocalStorage<T>(key: string, initialValue: T): [T, SetValue<T
// See: useLocalStorage() // See: useLocalStorage()
useEventListener('local-storage', handleStorageChange) useEventListener('local-storage', handleStorageChange)
return [storedValue, setValue] const [clientStoredValue, setClientStoredValue] = useState<T>(initialValue)
useEffect(() => setClientStoredValue(storedValue), [storedValue])
return [clientStoredValue, setValue]
} }
// A wrapper for "JSON.parse()"" to support "undefined" value // A wrapper for "JSON.parse()"" to support "undefined" value

View File

@@ -14,10 +14,20 @@ export interface Entity extends UnfetchedEntity {
recipe?: Recipe recipe?: Recipe
} }
export interface Group { export type Group = OldGroup|NewGroup
export interface OldGroup {
name: string name: string
isExported?: boolean isExported?: boolean
factories: string[] factories: string[]
intermediates: string[] intermediates: string[]
inputs: string[] inputs: string[]
} }
export interface NewGroup {
name: string
inputs: string[]
intermediates: string[]
exports: string[]
malls: string[]
}