mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-13 23:14:53 +09:00
Currently the web interface implements configs by pulling the state directly in the components where they are used. I need to access the instance config for a plugin, which would require me to duplicate parts of the instance config retrival code. Instead, I implement it here under lib. This allows 3rd party consumers to get immediate access if we decide to implement a subscription model for configs in the future.
30 lines
1.0 KiB
TypeScript
30 lines
1.0 KiB
TypeScript
import { useCallback, useContext, useEffect, useState, useSyncExternalStore } from "react";
|
|
import { Static } from "@sinclair/typebox";
|
|
import { Config, InstanceConfigGetRequest } from "@clusterio/lib";
|
|
import ControlContext from "../components/ControlContext";
|
|
|
|
export function useInstance(id?: number) {
|
|
const [instances, synced] = useInstances();
|
|
return [id !== undefined ? instances.get(id) : undefined, synced] as const;
|
|
}
|
|
|
|
export function useInstances() {
|
|
const control = useContext(ControlContext);
|
|
const subscribe = useCallback((callback: () => void) => control.instances.subscribe(callback), [control]);
|
|
return useSyncExternalStore(subscribe, () => control.instances.getSnapshot());
|
|
}
|
|
|
|
export function useInstanceConfig(id?: number) {
|
|
let control = useContext(ControlContext);
|
|
const [config, setConfig] = useState(undefined as undefined | Static<typeof Config.jsonSchema>);
|
|
|
|
useEffect(() => {
|
|
if (id) {
|
|
control.send(new InstanceConfigGetRequest(id))
|
|
.then(conf => setConfig(conf));
|
|
}
|
|
}, [id]);
|
|
|
|
return config;
|
|
};
|