mirror of
https://github.com/clusterio/clusterio.git
synced 2026-11-15 15:24:52 +09:00
Move all functions and classes currently available through lib/name and libName to be under a single flat namespace in lib. This make reorganising the lib namespace much simpler as the location of symbols can move without breaking the consumers of lib. The multi-entrypoint design was already problematic for the web plugin system which couldn't effectively use it due to how webpack's shared module system is awkward to set up with multiple entrypoints per package.
78 lines
1.6 KiB
React
78 lines
1.6 KiB
React
import { useEffect, useContext, useState } from "react";
|
|
import ControlContext from "../components/ControlContext";
|
|
|
|
import * as lib from "@clusterio/lib";
|
|
|
|
|
|
export function useHost(id) {
|
|
let control = useContext(ControlContext);
|
|
let [host, setHost] = useState({ loading: true });
|
|
|
|
function updateHost() {
|
|
// XXX optimize by requesting only the host in question
|
|
control.send(new lib.HostListRequest()).then(hosts => {
|
|
let match = hosts.find(i => i.id === id);
|
|
if (!match) {
|
|
setHost({ missing: true });
|
|
} else {
|
|
setHost({ ...match, present: true });
|
|
}
|
|
});
|
|
}
|
|
|
|
useEffect(() => {
|
|
if (!Number.isInteger(id)) {
|
|
setHost({ missing: true });
|
|
return undefined;
|
|
}
|
|
updateHost();
|
|
|
|
function updateHandler(newHost) {
|
|
setHost({ ...newHost, present: true });
|
|
}
|
|
|
|
control.onHostUpdate(id, updateHandler);
|
|
return () => {
|
|
control.offHostUpdate(id, updateHandler);
|
|
};
|
|
}, [id]);
|
|
|
|
return [host, updateHost];
|
|
}
|
|
|
|
export function useHostList() {
|
|
let control = useContext(ControlContext);
|
|
let [hostList, setHostList] = useState([]);
|
|
|
|
function updateHostList() {
|
|
control.send(new lib.HostListRequest()).then(hosts => {
|
|
setHostList(hosts);
|
|
});
|
|
}
|
|
|
|
useEffect(() => {
|
|
updateHostList();
|
|
|
|
function updateHandler(newHost) {
|
|
setHostList(oldList => {
|
|
let newList = oldList.concat();
|
|
let index = newList.findIndex(s => s.id === newHost.id);
|
|
if (index !== -1) {
|
|
newList[index] = newHost;
|
|
} else {
|
|
newList.push(newHost);
|
|
}
|
|
return newList;
|
|
});
|
|
}
|
|
|
|
control.onHostUpdate(null, updateHandler);
|
|
return () => {
|
|
control.offHostUpdate(null, updateHandler);
|
|
};
|
|
}, []);
|
|
|
|
|
|
return [hostList];
|
|
}
|