Refactor web_ui handling of exports

The handling of exported data such as locales and icons in web_ui was
based on a model where there is only one set of data exported per
cluster.  This model changed to have one set of exports per mod pack
when mod packs were introduced, but the existing web_ui code was
bodged to use exports from a "default mod pack" on the controller.

Refactor the code loading exported data to take the mod pack as an
argument for selecting which exported data to load.  The different kinds
of prototype metadata that can be loaded is consolidated into one
`useExportPrototypeMetadata` hook.  The logic for displaying icons is
put into a `FactorioIcon` component.  And the obsolete
`useExportManifest` hook is removed.

These changes allow the `/icon-reference` page to display exports on a
per mod pack basis.  Which has now been linked on the bottom of the mod
pack view page.
This commit is contained in:
Hornwitser committed 2026-03-16 17:11:47 +01:00
1 parent 4b85367d4e
commit 0d28a3ac3c
18 files changed
+391 -300

No files matched your search

@@ -0,0 +1,51 @@
import { ModPackGetDefaultRequest, type ModPack, isDeepStrictEqual } from "@clusterio/lib";
import type { Control } from "../util/websocket";
// TODO: replace this super duper expensive method with listening to a default mod pack id event.
class DefaultModPackStore {
refCount = 0;
interval: undefined | ReturnType<typeof setInterval>;
modPack: undefined | ModPack;
callbacks: (() => void)[] = [];
fetchDefaultModPack(control: Control) {
control.send(new ModPackGetDefaultRequest()).then(modPack => {
if (!isDeepStrictEqual(this.modPack, modPack)) {
this.modPack = modPack;
for (const callback of this.callbacks) {
callback();
}
}
}).catch(() => {
if (this.modPack !== undefined) {
this.modPack = undefined;
for (const callback of this.callbacks) {
callback();
}
}
});
}
subscribe(control: Control, callback: () => void) {
if (!this.refCount) {
const update = () => { this.fetchDefaultModPack(control); };
update();
this.interval = setInterval(update, 60e3);
}
this.callbacks.push(callback);
this.refCount += 1;
return () => {
this.callbacks.splice(this.callbacks.indexOf(callback), 1);
this.refCount -= 1;
if (!this.refCount) {
clearInterval(this.interval);
this.interval = undefined;
}
};
}
getSnapshot() {
return this.modPack;
}
};
export const defaultModPackStore = new DefaultModPackStore();
@@ -0,0 +1,61 @@
import { ExportLocale, logger } from "@clusterio/lib";
import notify from "../util/notify";
interface ExportLocaleCacheEntry {
callbacks: (() => void)[];
localePath: string | undefined;
data: Map<string, string>;
}
class ExportLocaleStore {
cache = new Map<number, ExportLocaleCacheEntry>();
_emptyMap = new Map();
async loadLocale(modPackId: number, cacheEntry: ExportLocaleCacheEntry) {
let response = await fetch(`${staticRoot}static/${cacheEntry.localePath}`);
if (response.ok) {
cacheEntry.data = new Map(await response.json() as ExportLocale);
for (const callback of cacheEntry.callbacks) {
callback();
}
} else {
notify(
`Failed to locale for mod pack ${modPackId}, server returned: ` +
`${response.status} ${response.statusText}`
);
}
}
subscribe(modPackId: number | undefined, localePath: string | undefined, callback: () => void) {
if (modPackId === undefined || !localePath) {
return () => {};
}
let cacheEntry = this.cache.get(modPackId);
if (!cacheEntry) {
cacheEntry = {
callbacks: [],
localePath: undefined,
data: new Map(),
};
this.cache.set(modPackId, cacheEntry);
}
if (cacheEntry.localePath !== localePath) {
cacheEntry.localePath = localePath;
this.loadLocale(modPackId, cacheEntry).catch(logger.error);
}
cacheEntry.callbacks.push(callback);
return () => {
cacheEntry.callbacks.splice(cacheEntry.callbacks.indexOf(callback), 1);
};
}
getSnapshot(modPackId: number | undefined): ReadonlyMap<string, string> {
if (modPackId === undefined) {
return this._emptyMap;
}
return this.cache.get(modPackId)?.data ?? this._emptyMap;
}
}
export const exportLocaleStore = new ExportLocaleStore();
@@ -0,0 +1,126 @@
import { ExportMetadata, ExportMetadataEntry, logger, ModPack } from "@clusterio/lib";
import unknownIconUrl from "../images/unknown-item.png";
import notify from "../util/notify";
export type PrototypeMetadataEntry = ExportMetadataEntry & { base_type: string };
interface MetadataCacheEntry {
callbacks: (() => void)[],
metadataPath: string | undefined,
spritesheetPath: string | undefined,
metadata: Map<string, Map<string, PrototypeMetadataEntry>>,
styleSheet: CSSStyleSheet,
}
class ExportPrototypeMetadataStore {
cache = new Map<number, MetadataCacheEntry>();
async loadMetadata(modPackId: number, cacheEntry: MetadataCacheEntry) {
const response = await fetch(`${staticRoot}static/${cacheEntry.metadataPath}`);
if (!response.ok) {
notify(
`Failed to fetch prototype metadata for mod pack ${modPackId}, server returned: ` +
`${response.status} ${response.statusText}`
);
// eslint-disable-next-line node/no-sync
cacheEntry.styleSheet.replaceSync("");
cacheEntry.metadata = new Map();
for (const callback of cacheEntry.callbacks) {
callback();
}
return;
}
const metadata = await response.json() as ExportMetadata;
const spriteUrl = `${staticRoot}static/${cacheEntry.spritesheetPath}`;
const styleContent: string[] = [];
styleContent.push(`\
.factorio-icon\
[data-mod-pack="${modPackId}"] {
background-image: url("${spriteUrl}");
}`);
for (const [baseName, prototypes] of Object.entries(metadata)) {
for (const prototype of prototypes) {
const icon = prototype.icon;
if (!icon) {
styleContent.push(`\
.factorio-icon\
[data-mod-pack="${modPackId}"]\
[data-type="${baseName}"]\
[data-name="${CSS.escape(prototype.name)}"] {
background-image: url("${unknownIconUrl}");
height: 32px;
width: 32px;
}`);
continue;
}
styleContent.push(`\
.factorio-icon\
[data-mod-pack="${modPackId}"]\
[data-type="${baseName}"]\
[data-name="${CSS.escape(prototype.name)}"] {
background-position: -${icon.x}px -${icon.y}px;
height: ${icon.size}px;
width: ${icon.size}px;
}`);
}
}
// eslint-disable-next-line node/no-sync
cacheEntry.styleSheet.replaceSync(styleContent.join("\n"));
cacheEntry.metadata = new Map(
Object.entries(metadata)
.map(([baseName, entries]) => [
baseName,
new Map(
entries.map(entry => [entry.name, { base_type: baseName, ...entry }])
),
])
);
for (const callback of cacheEntry.callbacks) {
callback();
}
}
subscribe(modPack: ModPack | undefined, callback: () => void) {
if (!modPack) {
return () => {};
}
const assets = modPack.exportManifest?.assets;
let cacheEntry = this.cache.get(modPack.id);
if (!cacheEntry) {
const styleSheet = new CSSStyleSheet();
document.adoptedStyleSheets.push(styleSheet);
cacheEntry = {
callbacks: [],
spritesheetPath: undefined,
metadataPath: undefined,
metadata: new Map(),
styleSheet,
};
this.cache.set(modPack.id, cacheEntry);
}
if (
cacheEntry.metadataPath !== assets?.metadata
|| cacheEntry.spritesheetPath !== assets?.spritesheet
) {
cacheEntry.metadataPath = assets?.metadata;
cacheEntry.spritesheetPath = assets?.spritesheet;
this.loadMetadata(modPack.id, cacheEntry).catch(logger.error);
}
cacheEntry.callbacks.push(callback);
return () => {
cacheEntry.callbacks.splice(cacheEntry.callbacks.indexOf(callback), 1);
};
}
getSnapshot(modPackId: number | undefined) {
if (modPackId === undefined) {
return undefined;
}
return this.cache.get(modPackId)?.metadata;
}
}
export const exportPrototypeMetadataStore = new ExportPrototypeMetadataStore();