@steambrew/client
Version:
A support library for creating plugins with Millennium.
72 lines (71 loc) • 3.03 kB
JavaScript
import { jsx as _jsx } from "react/jsx-runtime";
import { createContext, useContext, useEffect, useState } from 'react';
import { EUIMode } from '../../globals/steam-client/shared';
export class MillenniumRouterState {
constructor() {
this._routes = new Map();
// Update when support for new UIModes is added
this._routePatches = new Map([
[EUIMode.GamePad, new Map()],
[EUIMode.Desktop, new Map()],
]);
this.eventBus = new EventTarget();
}
publicState() {
return { routes: this._routes, routePatches: this._routePatches };
}
addRoute(path, component, props = {}) {
this._routes.set(path, { props, component });
this.notifyUpdate();
}
addPatch(path, patch, uiMode) {
const patchesForMode = this._routePatches.get(uiMode);
if (!patchesForMode)
throw new Error(`UI mode ${uiMode} not supported.`);
let patchList = patchesForMode.get(path);
if (!patchList) {
patchList = new Set();
patchesForMode.set(path, patchList);
}
patchList.add(patch);
this.notifyUpdate();
return patch;
}
removePatch(path, patch, uiMode) {
const patchesForMode = this._routePatches.get(uiMode);
if (!patchesForMode)
throw new Error(`UI mode ${uiMode} not supported.`);
const patchList = patchesForMode.get(path);
patchList?.delete(patch);
if (patchList?.size == 0) {
patchesForMode.delete(path);
}
this.notifyUpdate();
}
removeRoute(path) {
this._routes.delete(path);
this.notifyUpdate();
}
notifyUpdate() {
this.eventBus.dispatchEvent(new Event('update'));
}
}
const MillenniumRouterStateContext = createContext(null);
export const useMillenniumRouterState = () => useContext(MillenniumRouterStateContext);
export const MillenniumRouterStateContextProvider = ({ children, millenniumRouterState: millenniumRouterState }) => {
const [publicMillenniumRouterState, setPublicMillenniumRouterState] = useState({
...millenniumRouterState.publicState(),
});
useEffect(() => {
function onUpdate() {
setPublicMillenniumRouterState({ ...millenniumRouterState.publicState() });
}
millenniumRouterState.eventBus.addEventListener('update', onUpdate);
return () => millenniumRouterState.eventBus.removeEventListener('update', onUpdate);
}, []);
const addRoute = millenniumRouterState.addRoute.bind(millenniumRouterState);
const addPatch = millenniumRouterState.addPatch.bind(millenniumRouterState);
const removePatch = millenniumRouterState.removePatch.bind(millenniumRouterState);
const removeRoute = millenniumRouterState.removeRoute.bind(millenniumRouterState);
return (_jsx(MillenniumRouterStateContext.Provider, { value: { ...publicMillenniumRouterState, addRoute, addPatch, removePatch, removeRoute }, children: children }));
};