From e1f8198b57147aad824ae39ef1fb576f97cb2a4c Mon Sep 17 00:00:00 2001 From: Lazzexus Date: Sun, 22 Nov 2026 10:26:16 +0100 Subject: [PATCH] Add a production dashboard Every minute, the mod diffs the force's production statistics for each surface against the totals it sent last time (kept in storage.productionTotals), and sends what was produced and consumed as a ProductionUpdate. events-server-web keeps the statistics in ring buffers (1440 minutes and 168 hours), and serves them at /kafkatorio/data/servers/{id}/production, for a range of game time and optionally one surface. The web map has a production page (/servers/{id}/production, linked from the header) with science packs used per minute (in total and per pack), production per minute as a line chart, and a searchable table of everything produced and consumed. export_building_icons.py now also exports every item and fluid icon and name (items.json, fluids.json), for the production page. Co-Authored-By: Claude Opus 5.5 --- docs/guide.md | 11 +- .../building-icons/export_building_icons.py | 43 +- .../schema/packets/kafkatorioPacketInstant.kt | 28 ++ .../typescript/generated/kafkatorio-schema.ts | 17 + .../main/events/productionUpdates.ts | 131 +++++ .../main/events/registerEventListeners.ts | 2 + .../src/main/typescript/main/global.d.ts | 2 + .../processor/config/kafkatorioTopics.kt | 3 + .../dev/adamko/kafkatorio/server/web/main.kt | 7 + .../web/production/ProductionService.kt | 235 +++++++++ .../server/web/rest/factorioServersRoutes.kt | 26 + .../kafkatorio/server/web/rest/restApi.kt | 4 +- .../adamko/kafkatorio/server/web/webServer.kt | 4 +- .../dev/adamko/kafkatorio/webmap/App.kt | 2 + .../kafkatorio/webmap/layout/headerNav.kt | 3 + .../kafkatorio/webmap/production/LineChart.kt | 235 +++++++++ .../webmap/production/productionPage.kt | 460 ++++++++++++++++++ .../kafkatorio/webmap/routing/SiteRouter.kt | 4 + .../kafkatorio/webmap/routing/SiteView.kt | 4 + .../webmap/services/EventsServerClient.kt | 41 ++ .../webmap/services/WebsocketService.kt | 2 + .../kafkatorio/webmap/state/SiteAction.kt | 1 + .../kafkatorio/webmap/state/SiteState.kt | 2 + .../src/main/resources/css/kafkatorio.css | 287 ++++++++++- 24 files changed, 1524 insertions(+), 30 deletions(-) create mode 100644 modules/events-mod/src/main/typescript/main/events/productionUpdates.ts create mode 100644 modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/production/ProductionService.kt create mode 100644 modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/production/LineChart.kt create mode 100644 modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/production/productionPage.kt diff --git a/docs/guide.md b/docs/guide.md index 3132982..7f65f00 100644 --- a/docs/guide.md +++ b/docs/guide.md @@ -88,9 +88,11 @@ on `127.0.0.1`, and Kafka isn't exposed at all. WebSocket support is enabled. 7. In Factorio, run `/kafkatorio prototypes` and then `/kafkatorio chunks 10` to send the existing map. -8. Optional: building icons. The web map's 'Building icons' layer uses icons and building sizes - exported from a Factorio client that has the same mods as the server (they're not in this repo, - since they belong to Wube and the mod authors). With the game closed, run +8. Optional: icons and names. The web map's 'Building icons' layer, the research page and the + production page use icons, building sizes, the technology tree and in-game names, exported from + a Factorio client that has the same mods as the server (they're not in this repo, since they + belong to Wube and the mod authors). Without them, those pages show less, or nothing. With the + game closed, run ```terminal factorio --dump-data @@ -100,4 +102,5 @@ on `127.0.0.1`, and Kafka isn't exposed at all. scp -r ./icons root@:/mnt/user/appdata/kafkatorio-platform/ ``` - Re-export them when the mods change. + Re-export them when the mods change. If [Pillow](https://pypi.org/project/pillow/) is installed, + the (large) technology icons are shrunk. diff --git a/docs/kafkatorio-platform/building-icons/export_building_icons.py b/docs/kafkatorio-platform/building-icons/export_building_icons.py index dc5030b..cbd300f 100644 --- a/docs/kafkatorio-platform/building-icons/export_building_icons.py +++ b/docs/kafkatorio-platform/building-icons/export_building_icons.py @@ -25,8 +25,10 @@ The output contains - recipe/.png - technologies.json: the technology tree, for the research page - technology/.png - - items.json: {"": ""}, for science packs and research triggers - - item/.png (science packs, and items in research triggers) + - items.json: {"": ""}, for the research and production pages + - item/.png + - fluids.json: {"": ""}, for the production page + - fluid/.png """ import json @@ -91,10 +93,12 @@ def main(script_output: Path, output_dir: Path): resources = {name: names.get(name, name) for name in data_raw.get("resource", {})} (output_dir / "resources.json").write_text(json.dumps(resources, indent=1, sort_keys=True)) - technologies, items = export_technologies(script_output, data_raw, output_dir) + technologies = export_technologies(script_output, data_raw, output_dir) + items = export_icons_and_names(script_output, output_dir, "item") + fluids = export_icons_and_names(script_output, output_dir, "fluid") print(f"exported {len(buildings)} buildings, {len(recipes)} recipes, {len(resources)} resources," - f" {len(technologies)} technologies and {len(items)} items to {output_dir}") + f" {len(technologies)} technologies, {len(items)} items and {len(fluids)} fluids to {output_dir}") def as_list(value) -> list: @@ -113,17 +117,13 @@ def copy_icon(source: Path, target: Path, max_size: int): image.save(target, optimize=True) -def export_technologies(script_output: Path, data_raw: dict, output_dir: Path) -> tuple[dict, dict]: +def export_technologies(script_output: Path, data_raw: dict, output_dir: Path) -> dict: """The technology tree, with the cost of each technology, and icons.""" tech_names = json.loads((script_output / "technology-locale.json").read_text()).get("names", {}) - item_names = json.loads((script_output / "item-locale.json").read_text()).get("names", {}) (output_dir / "technology").mkdir(exist_ok=True) - (output_dir / "item").mkdir(exist_ok=True) technologies = {} - # science packs, and items needed by research triggers - item_icons = set() for name, tech in data_raw.get("technology", {}).items(): if tech.get("hidden"): @@ -147,12 +147,9 @@ def export_technologies(script_output: Path, data_raw: dict, output_dir: Path) - } if tech.get("ignore_tech_cost_multiplier"): technology["cost"]["ignoreMultiplier"] = True - item_icons.update(pack for pack, _ in ingredients) trigger = tech.get("research_trigger") if trigger: technology["trigger"] = trigger - if "item" in trigger: - item_icons.add(trigger["item"] if isinstance(trigger["item"], str) else trigger["item"]["name"]) if max_level is not None: technology["maxLevel"] = max_level # a number, or "infinite" if tech.get("upgrade"): @@ -170,16 +167,20 @@ def export_technologies(script_output: Path, data_raw: dict, output_dir: Path) - if icon.exists(): copy_icon(icon, output_dir / "technology" / icon.name, TECHNOLOGY_ICON_SIZE) - items = {} - for item in sorted(item_icons): - items[item] = item_names.get(item, item) - icon = script_output / "item" / f"{item}.png" - if icon.exists(): - shutil.copyfile(icon, output_dir / "item" / icon.name) - (output_dir / "technologies.json").write_text(json.dumps(technologies, indent=1, sort_keys=True)) - (output_dir / "items.json").write_text(json.dumps(items, indent=1, sort_keys=True)) - return technologies, items + return technologies + + +def export_icons_and_names(script_output: Path, output_dir: Path, kind: str) -> dict: + """All icons of a kind (e.g. item, fluid) with their display names, as s.json""" + names = json.loads((script_output / f"{kind}-locale.json").read_text()).get("names", {}) + (output_dir / kind).mkdir(exist_ok=True) + exported = {} + for icon in sorted((script_output / kind).glob("*.png")): + exported[icon.stem] = names.get(icon.stem, icon.stem) + shutil.copyfile(icon, output_dir / kind / icon.name) + (output_dir / f"{kind}s.json").write_text(json.dumps(exported, indent=1, sort_keys=True)) + return exported if __name__ == "__main__": diff --git a/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/packets/kafkatorioPacketInstant.kt b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/packets/kafkatorioPacketInstant.kt index 627c37b..3351b38 100644 --- a/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/packets/kafkatorioPacketInstant.kt +++ b/modules/events-library/src/commonMain/kotlin/dev/adamko/kafkatorio/schema/packets/kafkatorioPacketInstant.kt @@ -4,6 +4,7 @@ import dev.adamko.kafkatorio.library.LuaJsonList import dev.adamko.kafkatorio.schema.common.FactorioPrototype import dev.adamko.kafkatorio.schema.common.PlayerIndex import dev.adamko.kafkatorio.schema.common.SurfaceIndex +import dev.adamko.kafkatorio.schema.common.Tick import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable @@ -102,3 +103,30 @@ data class ResearchUpdate( /** The map setting that multiplies the cost of all technologies */ val technologyPriceMultiplier: Double = 1.0, ) : KafkatorioInstantPacketData() + + +/** + * How much of each item and fluid a force produced and consumed on a surface, since the previous + * update (usually one minute). + */ +@Serializable +@SerialName("kafkatorio.packet.instant.ProductionUpdate") +data class ProductionUpdate( + val forceName: String, + val surfaceIndex: SurfaceIndex, + /** The game tick at the end of the period */ + val tick: Tick, + /** The length of the period, in ticks */ + val periodTicks: UInt, + val items: ProductionCounts = ProductionCounts(), + val fluids: ProductionCounts = ProductionCounts(), +) : KafkatorioInstantPacketData() { + + /** Amounts by item or fluid name. Names with no change are left out. */ + @Serializable + @SerialName("kafkatorio.packet.instant.ProductionUpdate.ProductionCounts") + data class ProductionCounts( + val produced: Map = emptyMap(), + val consumed: Map = emptyMap(), + ) +} diff --git a/modules/events-mod/src/main/typescript/generated/kafkatorio-schema.ts b/modules/events-mod/src/main/typescript/generated/kafkatorio-schema.ts index bdd7f8d..71bbf64 100644 --- a/modules/events-mod/src/main/typescript/generated/kafkatorio-schema.ts +++ b/modules/events-mod/src/main/typescript/generated/kafkatorio-schema.ts @@ -20,6 +20,7 @@ export type KafkatorioPacketData = | KafkatorioPacketData.MapChunkResourceUpdate | KafkatorioPacketData.MapChunkTileUpdate | KafkatorioPacketData.PlayerUpdate + | KafkatorioPacketData.ProductionUpdate | KafkatorioPacketData.PrototypesUpdate | KafkatorioPacketData.ResearchUpdate | KafkatorioPacketData.SurfaceUpdate; @@ -29,6 +30,7 @@ export namespace KafkatorioPacketData { ConfigurationUpdate = "kafkatorio.packet.instant.ConfigurationUpdate", ConsoleChatUpdate = "kafkatorio.packet.instant.ConsoleChatUpdate", ConsoleCommandUpdate = "kafkatorio.packet.instant.ConsoleCommandUpdate", + ProductionUpdate = "kafkatorio.packet.instant.ProductionUpdate", PrototypesUpdate = "kafkatorio.packet.instant.PrototypesUpdate", ResearchUpdate = "kafkatorio.packet.instant.ResearchUpdate", SurfaceUpdate = "kafkatorio.packet.instant.SurfaceUpdate", @@ -61,6 +63,16 @@ export namespace KafkatorioPacketData { parameters: string; } + export interface ProductionUpdate { + type: KafkatorioPacketData.Type.ProductionUpdate; + forceName: string; + surfaceIndex: SurfaceIndex; + tick: Tick; + periodTicks: UInt; + items?: ProductionCounts; + fluids?: ProductionCounts; + } + export interface PrototypesUpdate { type: KafkatorioPacketData.Type.PrototypesUpdate; prototypes: FactorioPrototype[]; @@ -165,6 +177,11 @@ export interface ConfigurationUpdateGameData { newVersion?: string | null; } +export interface ProductionCounts { + produced?: { [key: string]: number }; + consumed?: { [key: string]: number }; +} + export type Double = double; export interface EntityUpdateKey { diff --git a/modules/events-mod/src/main/typescript/main/events/productionUpdates.ts b/modules/events-mod/src/main/typescript/main/events/productionUpdates.ts new file mode 100644 index 0000000..9e4ac55 --- /dev/null +++ b/modules/events-mod/src/main/typescript/main/events/productionUpdates.ts @@ -0,0 +1,131 @@ +import PacketEmitter from "../emitting/PacketEmitter"; +import {KafkatorioPacketData, ProductionCounts, Tick, UInt} from "../../generated/kafkatorio-schema"; +import {LuaFlowStatistics, LuaForce, LuaSurface, OnTickEvent, SurfaceIndex} from "factorio:runtime" +import Type = KafkatorioPacketData.Type; + + +/** Send production statistics this often */ +const PRODUCTION_INTERVAL_TICKS = 60 * 60 + +/** Spread the surfaces over the interval, rather than sending them all on the same tick */ +const PRODUCTION_OFFSET_TICKS = 30 + + +/** Totals of a LuaFlowStatistics, by name. Produced = input, consumed = output. */ +interface FlowTotals { + produced: Record + consumed: Record +} + +interface ProductionTotals { + tick: number + items: FlowTotals + fluids: FlowTotals +} + + +/** + * Send what the 'player' force produced and consumed on each surface since the last update. + * + * Factorio's statistics are running totals, so the totals of the last update are kept in + * `storage`, and only the difference is sent. + */ +export function handleProductionTick(event: OnTickEvent) { + const offset = event.tick % PRODUCTION_INTERVAL_TICKS + if (offset % PRODUCTION_OFFSET_TICKS != 0) return + + const force = game.forces["player"] + if (force == undefined) return + + // e.g. surfaces 1, 3, 5... on offset 0, surfaces 2, 4... on offset 30 + const slots = PRODUCTION_INTERVAL_TICKS / PRODUCTION_OFFSET_TICKS + const slot = offset / PRODUCTION_OFFSET_TICKS + for (const [, surface] of game.surfaces) { + if (surface.index % slots == slot) { + emitProductionUpdate(force, surface, event.tick) + } + } +} + + +function emitProductionUpdate(force: LuaForce, surface: LuaSurface, tick: number) { + storage.productionTotals ??= {} + const key = `${force.name}/${surface.index}` + + const current: ProductionTotals = { + tick: tick, + items: flowTotals(force.get_item_production_statistics(surface)), + fluids: flowTotals(force.get_fluid_production_statistics(surface)), + } + const previous = storage.productionTotals[key] as ProductionTotals | undefined + storage.productionTotals[key] = current + + // the first time, there's nothing to compare with + if (previous == undefined) return + + const items = difference(previous.items, current.items) + const fluids = difference(previous.fluids, current.fluids) + if (isEmpty(items) && isEmpty(fluids)) return + + const update: KafkatorioPacketData.ProductionUpdate = { + type: Type.ProductionUpdate, + forceName: force.name, + surfaceIndex: surface.index as unknown as SurfaceIndex, + tick: tick as Tick, + periodTicks: (tick - previous.tick) as UInt, + items: items, + fluids: fluids, + } + PacketEmitter.emitInstantPacket(update) +} + + +function flowTotals(statistics: LuaFlowStatistics): FlowTotals { + const produced: Record = {} + const consumed: Record = {} + for (const [name, count] of pairs(statistics.input_counts)) { + produced[name] = count as number + } + for (const [name, count] of pairs(statistics.output_counts)) { + consumed[name] = count as number + } + return {produced: produced, consumed: consumed} +} + + +function difference(previous: FlowTotals, current: FlowTotals): ProductionCounts { + return { + produced: differenceOf(previous.produced, current.produced), + consumed: differenceOf(previous.consumed, current.consumed), + } +} + + +function differenceOf( + previous: Record, + current: Record, +): Record { + const result: Record = {} + for (const [name, count] of pairs(current)) { + const change = count - (previous[name] ?? 0) + // totals can go down if statistics are reset, so ignore negative changes + if (change > 0) { + result[name] = change + } + } + return result +} + + +function isEmpty(counts: ProductionCounts): boolean { + return isEmptyTable(counts.produced) && isEmptyTable(counts.consumed) +} + + +function isEmptyTable(table: Record | null | undefined): boolean { + if (table == undefined) return true + for (const [,] of pairs(table)) { + return false + } + return true +} diff --git a/modules/events-mod/src/main/typescript/main/events/registerEventListeners.ts b/modules/events-mod/src/main/typescript/main/events/registerEventListeners.ts index 5c51c56..ece5c91 100644 --- a/modules/events-mod/src/main/typescript/main/events/registerEventListeners.ts +++ b/modules/events-mod/src/main/typescript/main/events/registerEventListeners.ts @@ -2,6 +2,7 @@ import {isEventType} from "./eventTypeCheck"; import {Converters} from "./converters"; import {handleSurfaceUpdate} from "./surfaceUpdates"; import {handleResearchTick} from "./researchUpdates"; +import {handleProductionTick} from "./productionUpdates"; import EventCacheService from "../emitting/EventDataCache"; import MapChunkUpdate from "./handlers/MapChunkUpdateHandler"; import EntityUpdates from "./handlers/EntityUpdateHandler"; @@ -20,6 +21,7 @@ script.on_event(defines.events.on_tick, (event: OnTickEvent) => { } handleResearchTick(event) + handleProductionTick(event) const kPacket: KafkatorioPacketData | null = KafkatorioPacketQueue.dequeue() if (kPacket != null) { diff --git a/modules/events-mod/src/main/typescript/main/global.d.ts b/modules/events-mod/src/main/typescript/main/global.d.ts index c5f3513..464ad04 100644 --- a/modules/events-mod/src/main/typescript/main/global.d.ts +++ b/modules/events-mod/src/main/typescript/main/global.d.ts @@ -1,4 +1,6 @@ declare const storage: { MOD_VERSION: string FACTORIO_VERSION: string + /** The production statistics totals that were last sent, by `force/surface` */ + productionTotals?: Record } diff --git a/modules/events-processor-core/src/main/kotlin/dev/adamko/kafkatorio/processor/config/kafkatorioTopics.kt b/modules/events-processor-core/src/main/kotlin/dev/adamko/kafkatorio/processor/config/kafkatorioTopics.kt index e61c5f0..1ce4db3 100644 --- a/modules/events-processor-core/src/main/kotlin/dev/adamko/kafkatorio/processor/config/kafkatorioTopics.kt +++ b/modules/events-processor-core/src/main/kotlin/dev/adamko/kafkatorio/processor/config/kafkatorioTopics.kt @@ -10,6 +10,7 @@ import dev.adamko.kafkatorio.schema.packets.MapChunkEntityUpdate import dev.adamko.kafkatorio.schema.packets.MapChunkResourceUpdate import dev.adamko.kafkatorio.schema.packets.MapChunkTileUpdate import dev.adamko.kafkatorio.schema.packets.PlayerUpdate +import dev.adamko.kafkatorio.schema.packets.ProductionUpdate import dev.adamko.kafkatorio.schema.packets.PrototypesUpdate import dev.adamko.kafkatorio.schema.packets.ResearchUpdate import dev.adamko.kafkatorio.schema.packets.SurfaceUpdate @@ -77,6 +78,7 @@ val KafkatorioPacketData.topicName: String is MapChunkEntityUpdate -> packetTopicNames.getValue(MapChunkEntityUpdate::class) is MapChunkResourceUpdate -> packetTopicNames.getValue(MapChunkResourceUpdate::class) is ResearchUpdate -> packetTopicNames.getValue(ResearchUpdate::class) + is ProductionUpdate -> packetTopicNames.getValue(ProductionUpdate::class) } @@ -93,6 +95,7 @@ private val packetTopicNames: Map, String> = ma MapChunkResourceUpdate::class to "map-chunk-resource", KafkatorioPacketDataError::class to "error", ResearchUpdate::class to "research", + ProductionUpdate::class to "production", ).mapValues { (_, v) -> "$DOMAIN.packet.$v" } diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt index f8d07bd..4cb6014 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/main.kt @@ -5,6 +5,7 @@ import dev.adamko.kafkatorio.processor.core.launchTopology import dev.adamko.kafkatorio.server.processor.topology.broadcastToWebsocket import dev.adamko.kafkatorio.server.processor.topology.saveMapTiles import dev.adamko.kafkatorio.server.web.buildings.BuildingService +import dev.adamko.kafkatorio.server.web.production.ProductionService import dev.adamko.kafkatorio.server.web.research.ResearchService import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService @@ -25,6 +26,7 @@ suspend fun main(): Unit = coroutineScope { val buildingService = BuildingService(appProps) val surfaceService = SurfaceService(appProps) val researchService = ResearchService(appProps) + val productionService = ProductionService(appProps) launch { websocketBroadcaster(wsServer) @@ -54,6 +56,10 @@ suspend fun main(): Unit = coroutineScope { researchService.consume() } + launch { + productionService.consume() + } + launch { startWebServer( appProps = appProps, @@ -62,6 +68,7 @@ suspend fun main(): Unit = coroutineScope { buildingService = buildingService, surfaceService = surfaceService, researchService = researchService, + productionService = productionService, ) } } diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/production/ProductionService.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/production/ProductionService.kt new file mode 100644 index 0000000..655bdf7 --- /dev/null +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/production/ProductionService.kt @@ -0,0 +1,235 @@ +package dev.adamko.kafkatorio.server.web.production + +import dev.adamko.kafkatorio.processor.config.ApplicationProperties +import dev.adamko.kafkatorio.processor.config.topicName +import dev.adamko.kafkatorio.schema.common.FactorioServerId +import dev.adamko.kafkatorio.schema.packets.ProductionUpdate +import dev.adamko.kafkatorio.server.web.kafka.followTopic +import kotlinx.serialization.Serializable + + +/** + * Keeps how much of each item and fluid was produced and consumed over time, for the production + * dashboard. + * + * The amounts are kept per game minute for the last day, and per game hour for the last week. + * (The production topic keeps a week of data, which is read again on startup.) + */ +class ProductionService( + private val appProps: ApplicationProperties, +) { + + private val servers = mutableMapOf() + + + suspend fun consume(): Unit = followTopic( + appProps, + ProductionUpdate::class.topicName, + clientId = "kafkatorio.events-server-web.production", + ) { serverId, data -> + if (data is ProductionUpdate && data.forceName == PLAYER_FORCE) { + synchronized(servers) { + servers.getOrPut(serverId) { ServerProduction() }.add(data) + } + } + } + + + /** + * The amounts produced and consumed during the last [range], in [ProductionRange.buckets] + * buckets. If [surfaceIndex] is `null`, sum all surfaces. + */ + fun production( + serverId: FactorioServerId, + surfaceIndex: Int?, + range: ProductionRange, + ): ProductionReport = synchronized(servers) { + servers[serverId]?.report(surfaceIndex, range) + ?: ProductionReport(range = range.name, bucketMinutes = range.bucketMinutes, latestTick = null) + } + + + /** The surfaces that have production statistics */ + fun surfaces(serverId: FactorioServerId): Set = synchronized(servers) { + servers[serverId]?.surfaces?.keys?.toSet() ?: emptySet() + } + + + companion object { + const val PLAYER_FORCE = "player" + } +} + + +enum class ProductionRange( + val minutes: Int, + /** The size of each bucket */ + val bucketMinutes: Int, +) { + TEN_MINUTES(10, 1), + ONE_HOUR(60, 1), + SIX_HOURS(6 * 60, 5), + ONE_DAY(24 * 60, 20), + ONE_WEEK(7 * 24 * 60, 2 * 60), + ; + + val buckets: Int get() = minutes / bucketMinutes +} + + +@Serializable +data class ProductionReport( + val range: String, + val bucketMinutes: Int, + /** The game tick of the latest statistics, or `null` if there are none */ + val latestTick: Long?, + /** Sorted by the amount produced, largest first */ + val entries: List = emptyList(), +) + + +@Serializable +data class ProductionEntry( + /** `item` or `fluid` */ + val kind: String, + val name: String, + val produced: Double, + val consumed: Double, + /** The amount produced in each bucket, oldest first */ + val producedSeries: List, + val consumedSeries: List, +) + + +private const val TICKS_PER_MINUTE = 60 * 60 +private const val MINUTE_SLOTS = 24 * 60 +private const val HOUR_SLOTS = 7 * 24 + + +private class ServerProduction { + val surfaces = mutableMapOf() + var latestMinute = 0L + + fun add(update: ProductionUpdate) { + val minute = update.tick.value.toLong() / TICKS_PER_MINUTE + latestMinute = maxOf(latestMinute, minute) + surfaces.getOrPut(update.surfaceIndex.toString().toInt()) { SurfaceProduction() }.add(minute, update) + } + + fun report(surfaceIndex: Int?, range: ProductionRange): ProductionReport { + val selected = if (surfaceIndex == null) surfaces.values else listOfNotNull(surfaces[surfaceIndex]) + + val produced = mutableMapOf() + val consumed = mutableMapOf() + selected.forEach { surface -> + surface.addTo(produced, consumed, range, latestMinute) + } + + val entries = (produced.keys + consumed.keys).map { key -> + val producedSeries = produced[key] ?: DoubleArray(range.buckets) + val consumedSeries = consumed[key] ?: DoubleArray(range.buckets) + ProductionEntry( + kind = key.kind, + name = key.name, + produced = producedSeries.sum(), + consumed = consumedSeries.sum(), + producedSeries = producedSeries.toList(), + consumedSeries = consumedSeries.toList(), + ) + }.filter { it.produced > 0 || it.consumed > 0 } + .sortedWith(compareByDescending { it.produced }.thenByDescending { it.consumed }) + + return ProductionReport( + range = range.name, + bucketMinutes = range.bucketMinutes, + latestTick = if (surfaces.isEmpty()) null else latestMinute * TICKS_PER_MINUTE, + entries = entries, + ) + } +} + + +private data class Key(val kind: String, val name: String) + + +/** + * Ring buffers of the amounts per minute and per hour, for each item and fluid on a surface. + * + * Slots are reused as time goes on: each slot remembers which minute (or hour) it holds, and is + * cleared when it's reused for a later one. + */ +private class SurfaceProduction { + private val produced = mutableMapOf() + private val consumed = mutableMapOf() + + private val slotMinute = LongArray(MINUTE_SLOTS) { -1 } + private val slotHour = LongArray(HOUR_SLOTS) { -1 } + + fun add(minute: Long, update: ProductionUpdate) { + val hour = minute / 60 + val minuteSlot = (minute % MINUTE_SLOTS).toInt() + val hourSlot = (hour % HOUR_SLOTS).toInt() + + if (slotMinute[minuteSlot] != minute) { + if (slotMinute[minuteSlot] > minute) return // older than a day + slotMinute[minuteSlot] = minute + (produced.values + consumed.values).forEach { it.minutes[minuteSlot] = 0f } + } + if (slotHour[hourSlot] != hour) { + slotHour[hourSlot] = hour + (produced.values + consumed.values).forEach { it.hours[hourSlot] = 0f } + } + + fun record(target: MutableMap, kind: String, amounts: Map) { + amounts.forEach { (name, amount) -> + val slots = target.getOrPut(Key(kind, name)) { Amounts() } + slots.minutes[minuteSlot] += amount.toFloat() + slots.hours[hourSlot] += amount.toFloat() + } + } + record(produced, "item", update.items.produced) + record(consumed, "item", update.items.consumed) + record(produced, "fluid", update.fluids.produced) + record(consumed, "fluid", update.fluids.consumed) + } + + + /** Add the amounts in [range] into buckets, by key */ + fun addTo( + producedTotals: MutableMap, + consumedTotals: MutableMap, + range: ProductionRange, + latestMinute: Long, + ) { + val firstMinute = latestMinute - range.minutes + 1 + + fun sumInto(source: Map, target: MutableMap) { + source.forEach { (key, amounts) -> + val buckets = target.getOrPut(key) { DoubleArray(range.buckets) } + if (range.minutes <= MINUTE_SLOTS) { + for (slot in 0 until MINUTE_SLOTS) { + val minute = slotMinute[slot] + if (minute < firstMinute || minute > latestMinute) continue + buckets[((minute - firstMinute) / range.bucketMinutes).toInt()] += amounts.minutes[slot].toDouble() + } + } else { + val firstHour = firstMinute / 60 + for (slot in 0 until HOUR_SLOTS) { + val hour = slotHour[slot] + if (hour < firstHour || hour > latestMinute / 60) continue + val bucket = ((hour * 60 - firstMinute).coerceAtLeast(0) / range.bucketMinutes).toInt() + buckets[bucket.coerceAtMost(range.buckets - 1)] += amounts.hours[slot].toDouble() + } + } + } + } + sumInto(produced, producedTotals) + sumInto(consumed, consumedTotals) + } +} + + +private class Amounts { + val minutes = FloatArray(MINUTE_SLOTS) + val hours = FloatArray(HOUR_SLOTS) +} diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt index 59a79c8..7e41e51 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/factorioServersRoutes.kt @@ -9,6 +9,9 @@ import dev.adamko.kafkatorio.processor.config.ApplicationProperties import dev.adamko.kafkatorio.server.web.config.jsonMapper import dev.adamko.kafkatorio.server.web.buildings.BuildingService import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService +import dev.adamko.kafkatorio.server.web.production.ProductionRange +import dev.adamko.kafkatorio.server.web.production.ProductionReport +import dev.adamko.kafkatorio.server.web.production.ProductionService import dev.adamko.kafkatorio.server.web.research.ResearchService import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService import dev.adamko.kafkatorio.schema.packets.ResearchUpdate @@ -41,6 +44,7 @@ internal fun Routing.factorioServersRoutes( buildingService: BuildingService, surfaceService: SurfaceService, researchService: ResearchService, + productionService: ProductionService, ) { get { @@ -63,6 +67,16 @@ internal fun Routing.factorioServersRoutes( } } + get { request -> + val range = ProductionRange.values().firstOrNull { it.name.equals(request.range, ignoreCase = true) } + if (range == null) { + call.respond(HttpStatusCode.BadRequest) + return@get + } + val report = productionService.production(request.server.factorioServerId, request.surface, range) + call.respond(jsonMapper.encodeToJsonElement(ProductionReport.serializer(), report)) + } + get { tile -> handleTileRequest(tile, appProps) } @@ -170,6 +184,18 @@ data class FactorioServer( ) } + /** + * What the players' force produced and consumed. [surface] is a surface index, or `null` for + * all surfaces. [range] is a [ProductionRange]. + */ + @Serializable + @Resource("production") + data class Production( + val server: FactorioServer, + val surface: Int? = null, + val range: String = "ONE_HOUR", + ) + /** The research state of the players' force */ @Serializable @Resource("research") diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt index 1fb72b5..d25050f 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/rest/restApi.kt @@ -3,6 +3,7 @@ package dev.adamko.kafkatorio.server.web.rest import dev.adamko.kafkatorio.processor.config.ApplicationProperties import dev.adamko.kafkatorio.server.web.buildings.BuildingService import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService +import dev.adamko.kafkatorio.server.web.production.ProductionService import dev.adamko.kafkatorio.server.web.research.ResearchService import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService import io.ktor.http.ContentType @@ -32,6 +33,7 @@ internal fun Application.webmapTileServer( buildingService: BuildingService, surfaceService: SurfaceService, researchService: ResearchService, + productionService: ProductionService, ) { install(AutoHeadResponse) @@ -61,6 +63,6 @@ internal fun Application.webmapTileServer( } routing { - factorioServersRoutes(appProps, resourcePatchService, buildingService, surfaceService, researchService) + factorioServersRoutes(appProps, resourcePatchService, buildingService, surfaceService, researchService, productionService) } } diff --git a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt index 696895a..f241723 100644 --- a/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt +++ b/modules/events-server-web/src/main/kotlin/dev/adamko/kafkatorio/server/web/webServer.kt @@ -3,6 +3,7 @@ package dev.adamko.kafkatorio.server.web import dev.adamko.kafkatorio.processor.config.ApplicationProperties import dev.adamko.kafkatorio.server.web.buildings.BuildingService +import dev.adamko.kafkatorio.server.web.production.ProductionService import dev.adamko.kafkatorio.server.web.research.ResearchService import dev.adamko.kafkatorio.server.web.resources.ResourcePatchService import dev.adamko.kafkatorio.server.web.surfaces.SurfaceService @@ -21,6 +22,7 @@ internal suspend fun startWebServer( buildingService: BuildingService, surfaceService: SurfaceService, researchService: ResearchService, + productionService: ProductionService, ): Unit = coroutineScope { embeddedServer( @@ -30,7 +32,7 @@ internal suspend fun startWebServer( webmapWebsocketServer(wsServer) - webmapTileServer(appProps, resourcePatchService, buildingService, surfaceService, researchService) + webmapTileServer(appProps, resourcePatchService, buildingService, surfaceService, researchService, productionService) }.start(wait = true) } diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/App.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/App.kt index b15c757..b485020 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/App.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/App.kt @@ -4,6 +4,7 @@ import dev.adamko.kafkatorio.schema.packets.EventServerPacket import dev.adamko.kafkatorio.webmap.layout.headerNav import dev.adamko.kafkatorio.webmap.layout.homePage import dev.adamko.kafkatorio.webmap.layout.servers.serverPage +import dev.adamko.kafkatorio.webmap.production.productionPage import dev.adamko.kafkatorio.webmap.research.researchPage import dev.adamko.kafkatorio.webmap.routing.SiteRouter import dev.adamko.kafkatorio.webmap.routing.SiteView @@ -92,6 +93,7 @@ object App : Application() { SiteView.HOME -> homePage(state) SiteView.SERVER -> serverPage(state) SiteView.RESEARCH -> researchPage(state) + SiteView.PRODUCTION -> productionPage(state) } } SiteRouter.updatePageLinks() diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/layout/headerNav.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/layout/headerNav.kt index b64a479..8598fa7 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/layout/headerNav.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/layout/headerNav.kt @@ -15,6 +15,9 @@ fun Container.headerNav(state: SiteState) { navLink("Map", "/servers/${serverId.id}", className = navClass(state.view == SiteView.SERVER)) { setAttribute("data-navigo", "true") } + navLink("Production", "/servers/${serverId.id}/production", className = navClass(state.view == SiteView.PRODUCTION)) { + setAttribute("data-navigo", "true") + } navLink("Research", "/servers/${serverId.id}/research", className = navClass(state.view == SiteView.RESEARCH)) { setAttribute("data-navigo", "true") } diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/production/LineChart.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/production/LineChart.kt new file mode 100644 index 0000000..61b492b --- /dev/null +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/production/LineChart.kt @@ -0,0 +1,235 @@ +package dev.adamko.kafkatorio.webmap.production + +import kotlin.math.abs +import kotlin.math.ceil +import kotlin.math.floor +import kotlin.math.log10 +import kotlin.math.max +import kotlin.math.pow +import kotlin.math.roundToInt +import kotlinx.browser.document +import org.w3c.dom.Element +import org.w3c.dom.HTMLElement +import org.w3c.dom.events.MouseEvent + + +data class ChartSeries( + val label: String, + val colour: String, + val values: List, +) + + +/** + * A line chart drawn as SVG: a recessive grid, 2px lines, and a crosshair that shows every + * series' value at the hovered point. + */ +class LineChart( + private val root: HTMLElement, + /** e.g. `/min` */ + private val unit: String, +) { + + private var series: List = emptyList() + private var xLabels: List = emptyList() + + private val tooltip = (document.createElement("div") as HTMLElement).apply { + className = "chart-tooltip" + style.display = "none" + } + + + fun render(series: List, xLabels: List) { + this.series = series + this.xLabels = xLabels + redraw() + } + + + fun redraw() { + root.innerHTML = "" + root.appendChild(tooltip) + tooltip.style.display = "none" + + val width = max(root.clientWidth, 300).toDouble() + val height = HEIGHT + val points = xLabels.size + if (series.isEmpty() || points == 0) { + val empty = document.createElement("div") + empty.className = "chart-empty" + empty.textContent = "Select items in the table below to chart them." + root.appendChild(empty) + return + } + + // direct labels at the end of each line, when there are few enough to fit + val directLabels = series.size <= 4 + val right = if (directLabels) 120.0 else 16.0 + val plotWidth = width - LEFT - right + val plotHeight = height - TOP - BOTTOM + + val maxValue = series.maxOf { s -> s.values.maxOrNull() ?: 0.0 } + val ticks = niceTicks(maxValue) + val yMax = ticks.last() + + fun x(i: Int) = LEFT + if (points == 1) plotWidth / 2 else plotWidth * i / (points - 1) + fun y(value: Double) = TOP + plotHeight * (1 - value / yMax) + + val svg = svg("svg", "width" to width, "height" to height, "class" to "line-chart") + + // grid and y axis labels + ticks.forEach { tick -> + svg.add("line", "x1" to LEFT, "x2" to LEFT + plotWidth, "y1" to y(tick), "y2" to y(tick), "class" to "chart-grid") + svg.add("text", "x" to LEFT - 8, "y" to y(tick) + 4, "class" to "chart-axis-label", "text-anchor" to "end") + .textContent = formatRate(tick) + } + + // x axis labels: the first, middle and last + listOf(0, (points - 1) / 2, points - 1).distinct().forEach { i -> + val anchor = when (i) { + 0 -> "start" + points - 1 -> "end" + else -> "middle" + } + svg.add("text", "x" to x(i), "y" to height - 6, "class" to "chart-axis-label", "text-anchor" to anchor) + .textContent = xLabels[i] + } + + // lines + series.forEach { s -> + val path = s.values.mapIndexed { i, v -> "${if (i == 0) "M" else "L"}${x(i).fmt()},${y(v).fmt()}" }.joinToString("") + svg.add("path", "d" to path, "class" to "chart-line", "stroke" to s.colour) + } + + if (directLabels) { + // push labels apart so they don't overlap + val labelYs = series.map { y(it.values.lastOrNull() ?: 0.0) }.toMutableList() + val order = labelYs.indices.sortedBy { labelYs[it] } + for (k in 1 until order.size) { + val previous = labelYs[order[k - 1]] + if (labelYs[order[k]] - previous < 14) labelYs[order[k]] = previous + 14 + } + series.forEachIndexed { i, s -> + svg.add("circle", "cx" to x(points - 1), "cy" to y(s.values.lastOrNull() ?: 0.0), "r" to 3, "fill" to s.colour) + svg.add("text", "x" to x(points - 1) + 8, "y" to labelYs[i] + 4, "class" to "chart-direct-label") + .textContent = s.label.truncate(16) + } + } + + // crosshair + val crosshair = svg.add("line", "y1" to TOP, "y2" to TOP + plotHeight, "class" to "chart-crosshair") + crosshair.setAttribute("visibility", "hidden") + val markers = series.map { s -> + svg.add("circle", "r" to 4, "fill" to s.colour, "class" to "chart-marker").also { + it.setAttribute("visibility", "hidden") + } + } + val hitArea = svg.add("rect", "x" to LEFT, "y" to TOP, "width" to plotWidth, "height" to plotHeight, "fill" to "transparent") + + hitArea.addEventListener("pointermove", { event -> + val e = event as MouseEvent + val bounds = root.getBoundingClientRect() + val px = e.clientX - bounds.left + val i = if (points == 1) 0 else ((px - LEFT) / plotWidth * (points - 1)).roundToInt().coerceIn(0, points - 1) + crosshair.setAttribute("x1", x(i).fmt()) + crosshair.setAttribute("x2", x(i).fmt()) + crosshair.setAttribute("visibility", "visible") + markers.forEachIndexed { k, marker -> + marker.setAttribute("cx", x(i).fmt()) + marker.setAttribute("cy", y(series[k].values.getOrElse(i) { 0.0 }).fmt()) + marker.setAttribute("visibility", "visible") + } + showTooltip(i, x(i), width) + }) + hitArea.addEventListener("pointerleave", { + crosshair.setAttribute("visibility", "hidden") + markers.forEach { it.setAttribute("visibility", "hidden") } + tooltip.style.display = "none" + }) + + root.appendChild(svg) + } + + + private fun showTooltip(i: Int, x: Double, width: Double) { + tooltip.innerHTML = "" + val title = document.createElement("div") + title.className = "chart-tooltip-title" + title.textContent = xLabels[i] + tooltip.appendChild(title) + series.sortedByDescending { it.values.getOrElse(i) { 0.0 } }.forEach { s -> + val row = document.createElement("div") + row.className = "chart-tooltip-row" + val swatch = document.createElement("span") + swatch.className = "chart-swatch" + (swatch as HTMLElement).style.background = s.colour + val value = document.createElement("strong") + value.textContent = formatRate(s.values.getOrElse(i) { 0.0 }) + unit + val label = document.createElement("span") + label.textContent = " " + s.label + row.appendChild(swatch) + row.appendChild(value) + row.appendChild(label) + tooltip.appendChild(row) + } + tooltip.style.display = "block" + // keep the tooltip inside the chart, on the side away from the pointer + if (x > width / 2) { + tooltip.style.left = "" + tooltip.style.right = "${(width - x + 12).fmt()}px" + } else { + tooltip.style.right = "" + tooltip.style.left = "${(x + 12).fmt()}px" + } + } + + + companion object { + private const val HEIGHT = 300.0 + private const val LEFT = 56.0 + private const val TOP = 12.0 + private const val BOTTOM = 28.0 + } +} + + +/** 0, then 3-5 evenly spaced 'nice' values (1, 2, 2.5 or 5 x 10^n) covering [maxValue] */ +private fun niceTicks(maxValue: Double): List { + if (maxValue <= 0) return listOf(0.0, 1.0) + val rough = maxValue / 4 + val magnitude = 10.0.pow(floor(log10(rough))) + val step = listOf(1.0, 2.0, 2.5, 5.0, 10.0).map { it * magnitude }.first { it >= rough } + val count = ceil(maxValue / step).toInt() + return (0..count).map { it * step } +} + + +/** e.g. `1.2k`, `350`, `2.5` */ +fun formatRate(value: Double): String { + val v = abs(value) + val sign = if (value < 0) "-" else "" + return sign + when { + v >= 1_000_000 -> "${((v / 100_000).roundToInt() / 10.0).trimZero()}M" + v >= 1_000 -> "${((v / 100).roundToInt() / 10.0).trimZero()}k" + v >= 100 -> "${v.roundToInt()}" + v >= 10 -> "${((v * 10).roundToInt() / 10.0).trimZero()}" + else -> "${((v * 100).roundToInt() / 100.0).trimZero()}" + } +} + +private fun Double.trimZero(): String = toString().removeSuffix(".0") + +private fun Double.fmt(): String = ((this * 10).roundToInt() / 10.0).toString() + +private fun String.truncate(length: Int) = if (this.length <= length) this else take(length - 1) + "…" + + +private const val SVG_NS = "http://www.w3.org/2000/svg" + +private fun svg(tag: String, vararg attributes: Pair): Element = + document.createElementNS(SVG_NS, tag).apply { + attributes.forEach { (name, value) -> setAttribute(name, value.toString()) } + } + +private fun Element.add(tag: String, vararg attributes: Pair): Element = + svg(tag, *attributes).also { appendChild(it) } diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/production/productionPage.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/production/productionPage.kt new file mode 100644 index 0000000..b3e49a3 --- /dev/null +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/production/productionPage.kt @@ -0,0 +1,460 @@ +package dev.adamko.kafkatorio.webmap.production + +import dev.adamko.kafkatorio.schema.common.FactorioServerId +import dev.adamko.kafkatorio.schema.common.MapSurface +import dev.adamko.kafkatorio.webmap.research.packs +import dev.adamko.kafkatorio.webmap.services.EventsServerClient +import dev.adamko.kafkatorio.webmap.services.ProductionEntry +import dev.adamko.kafkatorio.webmap.services.ProductionReport +import dev.adamko.kafkatorio.webmap.state.SiteState +import io.kvision.core.Container +import io.kvision.core.onClick +import io.kvision.core.onEvent +import io.kvision.form.select.SimpleSelect +import io.kvision.form.text.TextInput +import io.kvision.form.text.TextInputType +import io.kvision.html.Button +import io.kvision.html.Div +import io.kvision.html.button +import io.kvision.html.div +import io.kvision.html.h1 +import io.kvision.html.h2 +import io.kvision.html.image +import io.kvision.html.p +import io.kvision.html.span +import kotlinx.browser.window +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.Job +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.async +import kotlinx.coroutines.launch +import org.w3c.dom.HTMLElement + + +private val productionPageScope = CoroutineScope(Dispatchers.Default + SupervisorJob()) + +/** Reloads the statistics while the page is shown */ +private var refreshJob: Int? = null + + +/** What's produced and consumed, over time. */ +fun Container.productionPage(state: SiteState) { + val serverId = state.serverId ?: return + val page = div(className = "production-page") { + p("Loading production statistics…", className = "home-muted") + } + productionPageScope.launch { + val itemNames = async { runCatching { EventsServerClient.itemNames() }.getOrDefault(emptyMap()) } + val fluidNames = async { runCatching { EventsServerClient.fluidNames() }.getOrDefault(emptyMap()) } + val surfaces = async { runCatching { EventsServerClient.surfaces(serverId) }.getOrDefault(emptyList()) } + val sciencePacks = async { + runCatching { EventsServerClient.technologies() }.getOrDefault(emptyMap()) + .values.flatMap { it.packs() }.toSet() + } + page.removeAll() + ProductionView( + page = page, + serverId = serverId, + itemNames = itemNames.await(), + fluidNames = fluidNames.await(), + surfaces = surfaces.await(), + sciencePacks = sciencePacks.await(), + ).render() + } +} + + +private enum class Kind(val label: String, val iconDir: String) { + ITEMS("Items", "item"), + FLUIDS("Fluids", "fluid"), +} + + +private enum class Range(val label: String, val api: String) { + TEN_MINUTES("10m", "TEN_MINUTES"), + ONE_HOUR("1h", "ONE_HOUR"), + SIX_HOURS("6h", "SIX_HOURS"), + ONE_DAY("24h", "ONE_DAY"), + ONE_WEEK("7d", "ONE_WEEK"), +} + + +private enum class SortColumn { NAME, PRODUCED, CONSUMED, NET } + + +private class ProductionView( + private val page: Container, + private val serverId: FactorioServerId, + private val itemNames: Map, + private val fluidNames: Map, + private val surfaces: List, + private val sciencePacks: Set, +) { + + // filters + private var surfaceIndex: Int? = 1 + private var range = Range.ONE_HOUR + private var kind = Kind.ITEMS + private var search = "" + private var sortColumn = SortColumn.PRODUCED + private var sortDescending = true + + private var report: ProductionReport? = null + private var loading: Job? = null + + /** Charted entries (`kind/name`), with their colour slot - colour follows the entry */ + private val charted = linkedMapOf() + private var chartedChosenByUser = false + + private lateinit var rangeButtons: Map + private lateinit var kindButtons: Map + private lateinit var tiles: Div + private lateinit var legend: Div + private lateinit var chart: LineChart + private lateinit var table: Div + private lateinit var status: Div + private lateinit var tableTitle: io.kvision.html.H2 + + + fun render() { + page.div(className = "production-header") { + h1("Production") + status = div(className = "home-muted") + } + page.filters() + tiles = page.div(className = "production-tiles") + + page.div(className = "production-section") { + h2("Production per minute") + legend = div(className = "chart-legend") + val chartRoot = div(className = "line-chart-root") + chartRoot.addAfterInsertHook { + if (!::chart.isInitialized) { + chart = LineChart(chartRoot.getElement() as HTMLElement, unit = "/min") + // don't change other widgets while KVision is still inserting this one + window.setTimeout({ redrawAll() }, 0) + } + } + } + + page.div(className = "production-section") { + div(className = "production-table-header") { + tableTitle = h2("") + val searchInput = TextInput(TextInputType.SEARCH) { + placeholder = "Search" + addCssClass("research-search") + } + searchInput.onEvent { + input = { + search = searchInput.value?.trim()?.lowercase() ?: "" + renderTable() + } + } + add(searchInput) + } + p("Select up to ${PALETTE.size} rows to chart them.", className = "home-muted") + table = div(className = "production-table") + } + + window.addEventListener("resize", { if (::chart.isInitialized) chart.redraw() }) + + refreshJob?.let { window.clearInterval(it) } + refreshJob = window.setInterval({ + // stop when the page isn't shown any more + if (!page.getElement().isConnectedCompat()) { + refreshJob?.let { window.clearInterval(it) } + } else { + load() + } + }, 60_000) + + load() + } + + + private fun Container.filters() { + div(className = "research-filters") { + val options = listOf("" to "All surfaces") + + surfaces.map { "${it.index}" to it.name.replaceFirstChar { c -> c.uppercase() } } + add(SimpleSelect(options = options, value = "1") { + addCssClass("production-surface") + onEvent { + change = { + surfaceIndex = self.value?.toIntOrNull() + load() + } + } + }) + + div(className = "research-status-filter") { + rangeButtons = Range.values().associateWith { r -> + button(r.label, className = "research-filter-button") { + title = "The last ${r.label} of game time" + onClick { + range = r + load() + } + } + } + } + + div(className = "research-status-filter") { + kindButtons = Kind.values().associateWith { k -> + button(k.label, className = "research-filter-button") { + onClick { + if (kind != k) { + kind = k + charted.clear() + chartedChosenByUser = false + redrawAll() + } + } + } + } + } + } + } + + + private fun load() { + loading?.cancel() + updateButtons() + loading = productionPageScope.launch { + val loaded = runCatching { EventsServerClient.production(serverId, surfaceIndex, range.api) } + .onFailure { println("[productionPage] failed to load production: $it") } + .getOrNull() + report = loaded + redrawAll() + } + } + + + private fun updateButtons() { + rangeButtons.forEach { (r, b) -> if (r == range) b.addCssClass("active") else b.removeCssClass("active") } + kindButtons.forEach { (k, b) -> if (k == kind) b.addCssClass("active") else b.removeCssClass("active") } + } + + + private fun redrawAll() { + updateButtons() + val report = report + status.content = when { + report == null -> "Couldn't load the production statistics." + report.latestTick == null -> "The game hasn't sent production statistics yet. They're sent every minute." + else -> "Game time ${formatGameTime(report.latestTick)} · averages over the last " + + formatDuration(coveredMinutes()) + + if (coveredMinutes() < rangeMinutes(range)) " (statistics started then)" else "" + } + renderTiles() + renderChart() + renderTable() + } + + + /** Averages are per minute of the range that has statistics, so a new server isn't diluted */ + private val minutes: Double get() = coveredMinutes().toDouble() + + + /** The minutes of the range since the first statistics, rounded to whole buckets */ + private fun coveredMinutes(): Int { + val report = report ?: return rangeMinutes(range) + val buckets = report.entries.firstOrNull()?.producedSeries?.size ?: return rangeMinutes(range) + val firstBucket = report.entries.minOfOrNull { entry -> + (entry.producedSeries.indices).firstOrNull { entry.producedSeries[it] > 0 || entry.consumedSeries[it] > 0 } + ?: buckets + } ?: 0 + return maxOf(1, buckets - firstBucket) * report.bucketMinutes + } + + private fun rangeMinutes(r: Range) = when (r) { + Range.TEN_MINUTES -> 10 + Range.ONE_HOUR -> 60 + Range.SIX_HOURS -> 6 * 60 + Range.ONE_DAY -> 24 * 60 + Range.ONE_WEEK -> 7 * 24 * 60 + } + + private fun entries(): List = + report?.entries.orEmpty().filter { it.kind == kind.iconDir } + + + /** Science per minute: the science packs consumed by research */ + private fun renderTiles() { + tiles.removeAll() + val packs = report?.entries.orEmpty().filter { it.kind == "item" && it.name in sciencePacks && it.consumed > 0 } + .sortedByDescending { it.consumed } + val spm = packs.sumOf { it.consumed } / minutes + + tiles.div(className = "stat-tile") { + div("Science packs per minute", className = "stat-tile-label") + div(formatRate(spm), className = "stat-tile-value") + div("consumed by research", className = "stat-tile-sub") + } + if (packs.isNotEmpty()) { + tiles.div(className = "stat-tile stat-tile-wide") { + div("By science pack", className = "stat-tile-label") + div(className = "pack-rates") { + packs.forEach { entry -> + div(className = "pack-rate") { + title = name(entry) + image("/kafkatorio/icons/item/${entry.name}.png", alt = name(entry), className = "pack-icon pack-icon-small") + span("${formatRate(entry.consumed / minutes)}/min") + } + } + } + } + } + } + + + private fun renderChart() { + if (!::chart.isInitialized) return + val entries = entries() + + // by default, chart what's produced the most + if (!chartedChosenByUser) { + charted.clear() + entries.take(DEFAULT_CHARTED).forEach { addToChart(it) } + } + + val bucketMinutes = report?.bucketMinutes ?: 1 + val byKey = entries.associateBy { key(it) } + val series = charted.mapNotNull { (key, slot) -> + val entry = byKey[key] ?: return@mapNotNull null + ChartSeries(name(entry), PALETTE[slot], entry.producedSeries.map { it / bucketMinutes }) + } + val buckets = report?.entries?.firstOrNull()?.producedSeries?.size ?: 0 + val labels = (0 until buckets).map { i -> + val minutesAgo = (buckets - 1 - i) * bucketMinutes + if (minutesAgo == 0) "now" else "-${formatDuration(minutesAgo)}" + } + chart.render(series, labels) + + legend.removeAll() + series.forEach { s -> + legend.div(className = "chart-legend-item") { + span(className = "chart-swatch") { setStyle("background", s.colour) } + span(s.label) + } + } + } + + + private fun addToChart(entry: ProductionEntry): Boolean { + if (charted.size >= PALETTE.size) return false + val used = charted.values.toSet() + charted[key(entry)] = PALETTE.indices.first { it !in used } + return true + } + + + private fun renderTable() { + tableTitle.content = "All ${kind.label.lowercase()}" + table.removeAll() + val rows = entries() + .filter { search.isEmpty() || name(it).lowercase().contains(search) || it.name.contains(search) } + .sortedWith(comparator()) + + if (rows.isEmpty()) { + table.p("Nothing to show.", className = "home-muted") + return + } + + table.div(className = "production-row production-row-header") { + headerCell("", null) + headerCell(kind.label.removeSuffix("s"), SortColumn.NAME) + headerCell("Produced /min", SortColumn.PRODUCED) + headerCell("Consumed /min", SortColumn.CONSUMED) + headerCell("Net /min", SortColumn.NET) + } + rows.forEach { entry -> + val slot = charted[key(entry)] + table.div(className = "production-row" + if (slot != null) " charted" else "") { + span(className = "chart-swatch production-row-swatch") { + if (slot != null) setStyle("background", PALETTE[slot]) + } + div(className = "production-name") { + image("/kafkatorio/icons/${kind.iconDir}/${entry.name}.png", alt = "", className = "pack-icon pack-icon-small") { + setAttribute("loading", "lazy") + } + span(name(entry)) + } + div(formatRate(entry.produced / minutes), className = "production-number") + div(formatRate(entry.consumed / minutes), className = "production-number") + val net = (entry.produced - entry.consumed) / minutes + div((if (net > 0) "+" else "") + formatRate(net), className = "production-number") + onClick { + chartedChosenByUser = true + if (charted.remove(key(entry)) == null) addToChart(entry) + renderChart() + renderTable() + } + } + } + } + + + private fun Container.headerCell(label: String, column: SortColumn?) { + div(className = "production-header-cell" + if (column == sortColumn) " sorted" else "") { + content = label + if (column == sortColumn) (if (sortDescending) " ▼" else " ▲") else "" + if (column != null) { + onClick { + if (sortColumn == column) sortDescending = !sortDescending + else { + sortColumn = column + sortDescending = column != SortColumn.NAME + } + renderTable() + } + } + } + } + + + private fun comparator(): Comparator { + val base: Comparator = when (sortColumn) { + SortColumn.NAME -> compareBy { name(it).lowercase() } + SortColumn.PRODUCED -> compareBy { it.produced } + SortColumn.CONSUMED -> compareBy { it.consumed } + SortColumn.NET -> compareBy { it.produced - it.consumed } + } + return if (sortDescending) base.reversed() else base + } + + + private fun key(entry: ProductionEntry) = "${entry.kind}/${entry.name}" + + private fun name(entry: ProductionEntry): String { + val names = if (entry.kind == "fluid") fluidNames else itemNames + return names[entry.name] ?: entry.name.replace('-', ' ').replaceFirstChar { it.uppercase() } + } + + + companion object { + private const val DEFAULT_CHARTED = 5 + + /** Categorical colours, validated for CVD separation on the dark chart surface */ + val PALETTE = listOf( + "#3987e5", "#d95926", "#199e70", "#c98500", "#d55181", "#008300", "#9085e9", "#e66767", + ) + } +} + + +private fun org.w3c.dom.Node?.isConnectedCompat(): Boolean = this?.asDynamic()?.isConnected == true + + +private fun formatDuration(minutes: Int): String = when { + minutes % (24 * 60) == 0 -> "${minutes / (24 * 60)}d" + minutes % 60 == 0 -> "${minutes / 60}h" + minutes > 60 -> "${minutes / 60}h${minutes % 60}m" + else -> "${minutes}m" +} + + +/** e.g. `412h 05m` */ +private fun formatGameTime(tick: Long): String { + val totalMinutes = tick / 3600 + return "${totalMinutes / 60}h ${(totalMinutes % 60).toString().padStart(2, '0')}m" +} diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/routing/SiteRouter.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/routing/SiteRouter.kt index 13e8fad..edd3b56 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/routing/SiteRouter.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/routing/SiteRouter.kt @@ -37,6 +37,10 @@ object SiteRouter : CoroutineScope { log("routing.on HOME") homepageView() } + .on(SiteView.PRODUCTION) { match -> + val serverId = match.data["serverId"] as? String ?: error("invalid server id") + App.siteStateStore.dispatch(SiteAction.ProductionPage(FactorioServerId(serverId))) + } .on(SiteView.RESEARCH) { match -> val serverId = match.data["serverId"] as? String ?: error("invalid server id") App.siteStateStore.dispatch(SiteAction.ResearchPage(FactorioServerId(serverId))) diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/routing/SiteView.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/routing/SiteView.kt index 110762a..b8ec77d 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/routing/SiteView.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/routing/SiteView.kt @@ -20,6 +20,10 @@ sealed interface SiteView { override val path: String = "/servers/:serverId/" } + object PRODUCTION : DynamicPath { + override val path: String = "/servers/:serverId/production" + } + object RESEARCH : DynamicPath { override val path: String = "/servers/:serverId/research" } diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt index e0e50e7..9f69a01 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/EventsServerClient.kt @@ -92,6 +92,22 @@ object EventsServerClient : suspend fun itemNames(): Map = displayNames("items.json") + /** Fetch the display name of each fluid (exported like [buildingInfo]). */ + suspend fun fluidNames(): Map = displayNames("fluids.json") + + + /** + * Fetch what the players' force produced and consumed during a range of game time (see + * `ProductionRange` in events-server-web). If [surfaceIndex] is `null`, sum all surfaces. + */ + suspend fun production(serverId: FactorioServerId, surfaceIndex: Int?, range: String): ProductionReport { + val surface = surfaceIndex?.let { "&surface=$it" } ?: "" + val url = "${window.location.origin}/kafkatorio/data/servers/${serverId.id}/production?range=$range$surface" + val json = window.fetch(url).await().text().await() + return lenientJson.decodeFromString(ProductionReport.serializer(), json) + } + + /** Fetch the research state of the players' force, or `null` if the mod hasn't sent it yet. */ suspend fun research(serverId: FactorioServerId): ResearchUpdate? { val response = window.fetch("${window.location.origin}/kafkatorio/data/servers/${serverId.id}/research").await() @@ -165,3 +181,28 @@ data class TechnologyCost( val ingredients: List> = emptyList(), val ignoreMultiplier: Boolean = false, ) + + +/** What was produced and consumed during a range of game time */ +@Serializable +data class ProductionReport( + val range: String, + val bucketMinutes: Int, + /** The game tick of the latest statistics, or `null` if there are none */ + val latestTick: Long? = null, + val entries: List = emptyList(), +) + + +@Serializable +data class ProductionEntry( + /** `item` or `fluid` */ + val kind: String, + val name: String, + /** The total amount produced during the range */ + val produced: Double, + val consumed: Double, + /** The amount produced in each bucket of [ProductionReport.bucketMinutes], oldest first */ + val producedSeries: List, + val consumedSeries: List, +) diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/WebsocketService.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/WebsocketService.kt index 54295d2..fd4739d 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/WebsocketService.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/services/WebsocketService.kt @@ -11,6 +11,7 @@ import dev.adamko.kafkatorio.schema.packets.MapChunkResourceUpdate import dev.adamko.kafkatorio.schema.packets.MapChunkTileUpdate import dev.adamko.kafkatorio.schema.packets.PlayerUpdate import dev.adamko.kafkatorio.schema.packets.PrototypesUpdate +import dev.adamko.kafkatorio.schema.packets.ProductionUpdate import dev.adamko.kafkatorio.schema.packets.ResearchUpdate import dev.adamko.kafkatorio.schema.packets.SurfaceUpdate import dev.adamko.kafkatorio.webmap.App @@ -100,6 +101,7 @@ object WebsocketService : CoroutineScope { is MapChunkTileUpdate, is PrototypesUpdate, is ResearchUpdate, + is ProductionUpdate, is SurfaceUpdate, is KafkatorioPacketDataError -> { // to be continued... diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/SiteAction.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/SiteAction.kt index 61742bf..b66dd3d 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/SiteAction.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/SiteAction.kt @@ -11,6 +11,7 @@ sealed interface SiteAction : RAction { object HomePage : SiteAction data class ServerPage(val serverId: FactorioServerId) : SiteAction data class ResearchPage(val serverId: FactorioServerId) : SiteAction + data class ProductionPage(val serverId: FactorioServerId) : SiteAction data class ServerIdsLoaded(val serverIds: List) : SiteAction diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/SiteState.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/SiteState.kt index eb0faeb..a8045cf 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/SiteState.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/state/SiteState.kt @@ -39,6 +39,8 @@ data class SiteState( is SiteAction.ResearchPage -> copy(view = SiteView.RESEARCH, serverId = action.serverId) + is SiteAction.ProductionPage -> copy(view = SiteView.PRODUCTION, serverId = action.serverId) + is SiteAction.ServerIdsLoaded -> copy(serverIds = action.serverIds) is SiteAction.FactorioUpdate -> copy( diff --git a/modules/web-map/src/main/resources/css/kafkatorio.css b/modules/web-map/src/main/resources/css/kafkatorio.css index 5d5973e..7c652e2 100644 --- a/modules/web-map/src/main/resources/css/kafkatorio.css +++ b/modules/web-map/src/main/resources/css/kafkatorio.css @@ -353,7 +353,7 @@ header .navbar .navbar-toggler { margin: 20px 0 8px; } -.research-filters .research-search { +.research-search { width: 320px; max-width: 100%; background: var(--kt-panel); @@ -361,14 +361,14 @@ header .navbar .navbar-toggler { color: var(--kt-text); } -.research-filters .research-search:focus { +.research-search:focus { background: var(--kt-panel); color: var(--kt-text); border-color: var(--kt-accent); box-shadow: none; } -.research-filters .research-search::placeholder { +.research-search::placeholder { color: var(--kt-muted); } @@ -594,6 +594,287 @@ header .navbar .navbar-toggler { } +/* Production */ + +.production-page { + max-width: 1300px; + margin: 0 auto; + padding: 24px 0 48px; +} + +.production-header h1 { + color: var(--kt-heading); + font-weight: 700; + font-size: 2rem; + margin-bottom: 2px; +} + +.production-surface select, +select.production-surface { + background: var(--kt-panel); + border: 1px solid var(--kt-border); + color: var(--kt-text); + min-width: 180px; +} + +.production-tiles { + display: flex; + flex-wrap: wrap; + gap: 12px; + margin: 8px 0 20px; +} + +.stat-tile { + background: var(--kt-panel); + border: 1px solid var(--kt-border); + border-radius: 8px; + padding: 12px 16px; + min-width: 200px; +} + +.stat-tile-wide { + flex: 1; + min-width: 280px; +} + +.stat-tile-label { + color: var(--kt-muted); + font-size: 0.9rem; +} + +.stat-tile-value { + color: var(--kt-heading); + font-size: 2.2rem; + font-weight: 700; + line-height: 1.1; + font-variant-numeric: tabular-nums; +} + +.stat-tile-sub { + color: var(--kt-muted); + font-size: 0.85rem; +} + +.pack-rates { + display: flex; + flex-wrap: wrap; + gap: 6px 16px; + margin-top: 6px; +} + +.pack-rate { + display: inline-flex; + align-items: center; + gap: 4px; + font-variant-numeric: tabular-nums; +} + +.production-section { + margin-top: 20px; +} + +.production-section h2 { + color: var(--kt-heading); + font-size: 1.25rem; + font-weight: 600; + margin-bottom: 6px; +} + +.chart-legend { + display: flex; + flex-wrap: wrap; + gap: 4px 16px; + margin-bottom: 6px; + min-height: 1.5em; +} + +.chart-legend-item { + display: inline-flex; + align-items: center; + gap: 6px; +} + +.chart-swatch { + display: inline-block; + width: 10px; + height: 10px; + border-radius: 2px; + flex-shrink: 0; +} + +.line-chart-root { + position: relative; + background: var(--kt-panel); + border: 1px solid var(--kt-border); + border-radius: 8px; + padding: 8px 4px 0; + min-height: 300px; +} + +.line-chart { + display: block; +} + +.chart-grid { + stroke: var(--kt-panel-raised); + stroke-width: 1; +} + +.chart-axis-label { + fill: var(--kt-muted); + font-size: 12px; + font-variant-numeric: tabular-nums; +} + +.chart-direct-label { + fill: var(--kt-text); + font-size: 12px; +} + +.chart-line { + fill: none; + stroke-width: 2; + stroke-linejoin: round; + stroke-linecap: round; +} + +.chart-crosshair { + stroke: var(--kt-muted); + stroke-width: 1; +} + +.chart-marker { + stroke: var(--kt-panel); + stroke-width: 2; +} + +.chart-empty { + padding: 100px 16px; + text-align: center; + color: var(--kt-muted); +} + +.chart-tooltip { + position: absolute; + top: 12px; + z-index: 10; + pointer-events: none; + background: #141314; + border: 1px solid var(--kt-border); + border-radius: 6px; + padding: 6px 10px; + font-size: 0.85rem; + white-space: nowrap; + box-shadow: 0 4px 16px rgba(0, 0, 0, 0.5); +} + +.chart-tooltip-title { + color: var(--kt-muted); + margin-bottom: 2px; +} + +.chart-tooltip-row { + display: flex; + align-items: center; + gap: 6px; +} + +.chart-tooltip-row strong { + font-variant-numeric: tabular-nums; +} + +.production-table-header { + display: flex; + flex-wrap: wrap; + align-items: center; + justify-content: space-between; + gap: 8px; +} + +.production-table-header .research-search { + width: 240px; +} + +.production-table { + background: var(--kt-panel); + border: 1px solid var(--kt-border); + border-radius: 8px; + overflow: hidden; +} + +.production-row { + display: grid; + grid-template-columns: 14px minmax(0, 1fr) repeat(3, minmax(70px, 120px)); + gap: 8px; + align-items: center; + padding: 4px 12px; + border-top: 1px solid var(--kt-panel-raised); + cursor: pointer; +} + +.production-row:hover { + background: var(--kt-panel-raised); +} + +.production-row.charted { + background: #383226; +} + +.production-row-header { + border-top: none; + cursor: default; + color: var(--kt-muted); + font-size: 0.85rem; + font-weight: 600; +} + +.production-row-header:hover { + background: none; +} + +.production-header-cell { + cursor: pointer; + user-select: none; +} + +.production-header-cell.sorted { + color: var(--kt-heading); +} + +.production-row-header .production-header-cell:nth-child(n+3) { + text-align: right; +} + +.production-name { + display: flex; + align-items: center; + gap: 8px; + min-width: 0; + overflow: hidden; + white-space: nowrap; + text-overflow: ellipsis; +} + +.production-number { + text-align: right; + font-variant-numeric: tabular-nums; +} + +@media (max-width: 600px) { + .production-row { + grid-template-columns: 10px minmax(0, 1fr) repeat(3, minmax(48px, 64px)); + gap: 4px; + padding: 4px 8px; + font-size: 0.85rem; + } + + .stat-tile { + min-width: 0; + flex: 1; + } +} + + /* Map */ .leaflet-tile {