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 b485020..93a9aed 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 @@ -5,6 +5,7 @@ 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.ResearchLayout import dev.adamko.kafkatorio.webmap.research.researchPage import dev.adamko.kafkatorio.webmap.routing.SiteRouter import dev.adamko.kafkatorio.webmap.routing.SiteView @@ -92,7 +93,8 @@ object App : Application() { when (state.view) { SiteView.HOME -> homePage(state) SiteView.SERVER -> serverPage(state) - SiteView.RESEARCH -> researchPage(state) + SiteView.RESEARCH -> researchPage(state, ResearchLayout.LIST) + SiteView.RESEARCH_TREE -> researchPage(state, ResearchLayout.TREE) SiteView.PRODUCTION -> productionPage(state) } } 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 8598fa7..3ea7c61 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 @@ -18,7 +18,7 @@ fun Container.headerNav(state: SiteState) { 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)) { + navLink("Research", "/servers/${serverId.id}/research", className = navClass(state.view == SiteView.RESEARCH || state.view == SiteView.RESEARCH_TREE)) { setAttribute("data-navigo", "true") } } diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/ResearchTreeLayout.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/ResearchTreeLayout.kt new file mode 100644 index 0000000..cb45480 --- /dev/null +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/ResearchTreeLayout.kt @@ -0,0 +1,120 @@ +package dev.adamko.kafkatorio.webmap.research + +import kotlin.math.max +import kotlin.math.min + + +/** Where a technology is drawn in the tree, in pixels. [x] and [y] are its centre. */ +data class TreeNodePosition(val x: Double, val y: Double, val level: Int) + + +/** + * Lays out the technology tree from top to bottom, like the game's technology screen. + * + * Each technology goes in the row of its [ResearchModel.depth] (the longest chain of + * prerequisites), so every prerequisite is above the technologies that need it. + * Within a row, technologies are ordered and moved so they sit near the technologies they + * connect to, which keeps most links short and reduces crossings. + * + * (Internally the rows are called columns, and positions within them y, then swapped at the end.) + */ +class ResearchTreeLayout( + private val model: ResearchModel, + /** Vertical distance between rows */ + private val levelSpacing: Double = 170.0, + /** Horizontal distance between technologies in the same row */ + private val rowSpacing: Double = 128.0, +) { + + private val names: List = model.technologies.keys.toList() + + private val prerequisites: Map> = names.associateWith { name -> + model.technologies.getValue(name).prerequisites.filter { it in model.technologies } + } + + private val neighbours: Map> = names.associateWith { name -> + prerequisites.getValue(name) + model.successors[name].orEmpty() + } + + val positions: Map + + val width: Double + val height: Double + + init { + val columns: List> = run { + val maxDepth = names.maxOfOrNull { model.depth[it] ?: 0 } ?: 0 + val columns = List(maxDepth + 1) { mutableListOf() } + names.sortedWith(compareBy({ model.technologies[it]?.order ?: "" }, { it })) + .forEach { columns[model.depth[it] ?: 0].add(it) } + columns + } + + // 1. order each column by the average position of its neighbours (barycentre heuristic) + val rank = mutableMapOf() + fun updateRanks() = columns.forEach { column -> + column.forEachIndexed { i, name -> rank[name] = i - (column.size - 1) / 2.0 } + } + updateRanks() + repeat(12) { iteration -> + // sweep left-to-right, then right-to-left + val order = if (iteration % 2 == 0) columns.indices else columns.indices.reversed() + for (c in order) { + val column = columns[c] + val barycentre = column.associateWith { name -> + val linked = if (iteration % 2 == 0) prerequisites.getValue(name) else model.successors[name].orEmpty() + if (linked.isEmpty()) rank.getValue(name) else linked.sumOf { rank.getValue(it) } / linked.size + } + column.sortBy { barycentre.getValue(it) } + column.forEachIndexed { i, name -> rank[name] = i - (column.size - 1) / 2.0 } + } + } + + // 2. move each technology towards its neighbours, keeping the order and the spacing + val y = rank.mapValuesTo(mutableMapOf()) { (_, r) -> r * rowSpacing } + repeat(16) { iteration -> + val order = if (iteration % 2 == 0) columns.indices else columns.indices.reversed() + for (c in order) { + val column = columns[c] + if (column.isEmpty()) continue + val desired = column.map { name -> + val linked = neighbours.getValue(name) + if (linked.isEmpty()) y.getValue(name) else (y.getValue(name) + linked.sumOf { y.getValue(it) }) / (linked.size + 1) + } + packColumn(desired).forEachIndexed { i, newY -> y[column[i]] = newY } + } + } + + val minY = y.values.minOrNull() ?: 0.0 + val maxY = y.values.maxOrNull() ?: 0.0 + val padding = rowSpacing + positions = names.associateWith { name -> + val level = model.depth[name] ?: 0 + TreeNodePosition( + x = padding + y.getValue(name) - minY, + y = padding + level * levelSpacing, + level = level, + ) + } + width = padding * 2 + (maxY - minY) + height = padding * 2 + (columns.size - 1).coerceAtLeast(0) * levelSpacing + } + + + /** + * Place technologies as close as possible to [desired], in the same order, at least + * [rowSpacing] apart. + */ + private fun packColumn(desired: List): List { + val n = desired.size + // push down from the top, and up from the bottom, then take the average + val down = DoubleArray(n) + for (i in 0 until n) down[i] = if (i == 0) desired[i] else max(desired[i], down[i - 1] + rowSpacing) + val up = DoubleArray(n) + for (i in n - 1 downTo 0) up[i] = if (i == n - 1) desired[i] else min(desired[i], up[i + 1] - rowSpacing) + val result = DoubleArray(n) { (down[it] + up[it]) / 2 } + // averaging can squeeze technologies together, so restore the spacing + for (i in 1 until n) result[i] = max(result[i], result[i - 1] + rowSpacing) + return result.toList() + } +} diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/ResearchTreeView.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/ResearchTreeView.kt new file mode 100644 index 0000000..db70bb4 --- /dev/null +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/ResearchTreeView.kt @@ -0,0 +1,501 @@ +package dev.adamko.kafkatorio.webmap.research + +import io.kvision.core.Container +import io.kvision.core.onClick +import io.kvision.core.onEvent +import io.kvision.form.text.TextInput +import io.kvision.form.text.TextInputType +import io.kvision.html.Div +import io.kvision.html.button +import io.kvision.html.div +import io.kvision.html.image +import io.kvision.html.span +import kotlin.math.abs +import kotlin.math.exp +import kotlin.math.hypot +import kotlin.math.max +import kotlin.math.min +import kotlinx.browser.document +import kotlinx.browser.window +import org.w3c.dom.Element +import org.w3c.dom.HTMLElement +import org.w3c.dom.events.Event +import org.w3c.dom.events.KeyboardEvent +import org.w3c.dom.events.MouseEvent +import org.w3c.dom.events.WheelEvent +import org.w3c.dom.pointerevents.PointerEvent +import org.w3c.dom.url.URLSearchParams + + +private const val SVG_NS = "http://www.w3.org/2000/svg" + +private const val NODE_WIDTH = 104.0 +private const val NODE_HEIGHT = 88.0 + +private const val MIN_SCALE = 0.04 +private const val MAX_SCALE = 2.0 + +/** Below this zoom, names are hidden, so the tree is readable as an overview */ +private const val LABEL_SCALE = 0.45 + + +/** + * The technology tree, drawn like the game's technology screen: technologies are linked to their + * prerequisites, from the first technologies at the top to the last at the bottom. + * + * Drag to move, scroll (or pinch) to zoom. Selecting a technology highlights everything needed to + * research it, and what it leads to. + */ +internal class ResearchTreeView( + private val page: Container, + private val model: ResearchModel, + private val names: Names, +) { + + private val layout = ResearchTreeLayout(model) + + /** All prerequisites of each technology, including indirect ones */ + private val ancestors = mutableMapOf>() + + private lateinit var viewport: Div + private lateinit var canvas: HTMLElement + private var canvasRequested = false + private lateinit var selectionBar: Div + private lateinit var searchCount: Div + private lateinit var detail: TechnologyDetail + + private val nodes = mutableMapOf() + private val edges = mutableListOf>() + + // view + private var scale = 1.0 + private var offsetX = 0.0 + private var offsetY = 0.0 + + private var selected: String? = null + private var searchMatches: List = emptyList() + private var searchIndex = -1 + + + fun render() { + page.toolbar() + selectionBar = page.div(className = "research-tree-selection") + viewport = page.div(className = "research-tree-viewport") + viewport.addAfterInsertHook { + if (!canvasRequested) { + canvasRequested = true + val element = viewport.getElement() as HTMLElement + // don't change other widgets while KVision is still inserting this one + window.setTimeout({ initCanvas(element) }, 0) + } + } + page.div(className = "research-tree-help home-muted") { + content = "Drag to move, scroll or pinch to zoom. Click a technology to show what it needs; double-click for details." + } + + // registered before the pop-up's own listener, so Escape closes the pop-up before the selection + document.addEventListener("keydown", { event -> + if ((event as KeyboardEvent).key != "Escape" || !::canvas.isInitialized || !canvas.isConnected) return@addEventListener + if (!detail.isOpen) select(null) + }) + detail = TechnologyDetail(page, model, names, onShow = { name -> + // follow technologies opened from the pop-up, so the tree shows them when it's closed + if (::canvas.isInitialized && name != selected) select(name, centre = true) + }) + renderSelectionBar() + } + + + private fun Container.toolbar() { + div(className = "research-tree-toolbar") { + val searchInput = TextInput(TextInputType.SEARCH) { + placeholder = "Search technologies or recipes" + addCssClass("research-search") + } + searchInput.onEvent { + input = { search(searchInput.value?.trim()?.lowercase() ?: "") } + keydown = { event -> + if (event.key == "Enter") { + event.preventDefault() + nextSearchMatch(if (event.shiftKey) -1 else 1) + } + } + } + add(searchInput) + searchCount = div(className = "research-count home-muted") + + div(className = "research-tree-zoom") { + button("−", className = "research-filter-button") { + title = "Zoom out" + onClick { zoomBy(1 / 1.4) } + } + button("+", className = "research-filter-button") { + title = "Zoom in" + onClick { zoomBy(1.4) } + } + button("Fit", className = "research-filter-button") { + title = "Show the whole tree" + onClick { fit() } + } + model.research?.current?.let { current -> + button("Current research", className = "research-filter-button") { + onClick { select(current, centre = true) } + } + } + } + + div(className = "research-tree-legend") { + listOf( + TechnologyStatus.RESEARCHED, + TechnologyStatus.RESEARCHING, + TechnologyStatus.AVAILABLE, + TechnologyStatus.LOCKED, + ).forEach { status -> + span(status.label, className = "research-tree-legend-item tech-${status.name.lowercase()}") + } + } + } + } + + + //region drawing + + private fun initCanvas(viewportElement: HTMLElement) { + canvas = document.createElement("div") as HTMLElement + canvas.className = "research-tree-canvas" + canvas.style.width = "${layout.width}px" + canvas.style.height = "${layout.height}px" + + val svg = document.createElementNS(SVG_NS, "svg") + svg.setAttribute("class", "research-tree-edges") + svg.setAttribute("width", "${layout.width}") + svg.setAttribute("height", "${layout.height}") + canvas.appendChild(svg) + + model.technologies.forEach { (name, tech) -> + val to = layout.positions[name] ?: return@forEach + tech.prerequisites.forEach { prerequisite -> + val from = layout.positions[prerequisite] ?: return@forEach + val path = document.createElementNS(SVG_NS, "path") + // from the bottom of the prerequisite to the top of the technology that needs it + val y1 = from.y + NODE_HEIGHT / 2 + val y2 = to.y - NODE_HEIGHT / 2 + val bend = max(40.0, (y2 - y1) / 2) + path.setAttribute("d", "M${from.x},$y1 C${from.x},${y1 + bend} ${to.x},${y2 - bend} ${to.x},$y2") + val done = model.status[prerequisite] == TechnologyStatus.RESEARCHED + path.setAttribute("class", if (done) "tree-edge tree-edge-done" else "tree-edge") + svg.appendChild(path) + edges += Triple(prerequisite, name, path) + } + } + + model.technologies.forEach { (name, tech) -> + val position = layout.positions[name] ?: return@forEach + val status = model.status[name] ?: TechnologyStatus.LOCKED + val node = document.createElement("div") as HTMLElement + node.className = "tree-node tech-${status.name.lowercase()}" + node.setAttribute("data-tech", name) + node.style.left = "${position.x - NODE_WIDTH / 2}px" + node.style.top = "${position.y - NODE_HEIGHT / 2}px" + node.title = "${tech.displayName(name)}\n${status.label}\n${costText(name)}" + + val icon = document.createElement("img") as HTMLElement + icon.className = "tree-node-icon" + icon.setAttribute("src", "/kafkatorio/icons/technology/$name.png") + icon.setAttribute("alt", "") + icon.setAttribute("loading", "lazy") + icon.setAttribute("draggable", "false") + node.appendChild(icon) + + val label = document.createElement("div") as HTMLElement + label.className = "tree-node-name" + label.textContent = tech.displayName(name) + node.appendChild(label) + + canvas.appendChild(node) + nodes[name] = node + } + + viewportElement.appendChild(canvas) + initPanZoom(viewportElement) + + val requested = URLSearchParams(window.location.search).get("tech")?.takeIf { it in model.technologies } + val initial = requested ?: model.research?.current?.takeIf { it in model.technologies } + if (initial != null) { + scale = 1.0 + select(initial, centre = true) + } else { + showTop() + } + } + + + private fun costText(name: String): String { + val units = model.units(name) ?: return model.technologies.getValue(name).triggerDescription(names) + val packs = model.cost(name).keys.joinToString(", ") { names.item(it) } + return "${formatAmount(units)} × $packs" + } + + //endregion + + + //region selection + + private fun ancestorsOf(name: String): Set = ancestors.getOrPut(name) { + val result = mutableSetOf() + val stack = ArrayDeque(model.technologies[name]?.prerequisites.orEmpty()) + while (stack.isNotEmpty()) { + val next = stack.removeLast() + if (next in model.technologies && result.add(next)) { + stack.addAll(model.technologies.getValue(next).prerequisites) + } + } + result + } + + + private fun select(name: String?, centre: Boolean = false) { + val name = name?.takeIf { it in model.technologies } + selected = name + + val chain = name?.let { ancestorsOf(it) } ?: emptySet() + val next = name?.let { model.successors[it].orEmpty().toSet() } ?: emptySet() + + canvas.classList.toggle("has-selection", name != null) + nodes.forEach { (tech, node) -> + node.classList.toggle("tree-selected", tech == name) + node.classList.toggle("tree-ancestor", tech in chain) + node.classList.toggle("tree-successor", tech in next) + } + edges.forEach { (from, to, path) -> + val onChain = to == name || to in chain + val toNext = from == name && to in next + path.classList.toggle("tree-edge-chain", onChain) + path.classList.toggle("tree-edge-next", toNext) + // draw highlighted links on top + if (onChain || toNext) path.parentNode?.appendChild(path) + } + + if (name != null && centre) centreOn(name) + renderSelectionBar() + + val url = window.location.pathname + (name?.let { "?tech=$it" } ?: "") + window.history.replaceState(null, "", url) + } + + + private fun renderSelectionBar() { + selectionBar.removeAll() + val name = selected + if (name == null) { + selectionBar.span( + "Select a technology to highlight everything it needs.", + className = "home-muted", + ) + return + } + val tech = model.technologies.getValue(name) + val status = model.status[name] ?: TechnologyStatus.LOCKED + selectionBar.div(className = "research-tree-selected tech-${status.name.lowercase()}") { + image("/kafkatorio/icons/technology/$name.png", alt = "", className = "pack-icon") + span(tech.displayName(name), className = "tech-card-name") + span(status.label, className = "tech-status") + } + if (status != TechnologyStatus.RESEARCHED) { + val (toReach, count) = model.costToReach(name) + selectionBar.div(className = "research-tree-to-reach") { + span( + if (count <= 1) "No prerequisites left" else "${count - 1} prerequisites left", + className = "home-muted", + ) + model.sciencePacks.filter { it in toReach }.forEach { pack -> + span(className = "research-tree-pack") { + packIcon(pack, names, small = true) + span(formatAmount(toReach.getValue(pack))) + } + } + } + } + selectionBar.div(className = "research-tree-selection-actions") { + button("Details", className = "research-filter-button") { + onClick { detail.show(name) } + } + button("Clear", className = "research-filter-button") { + onClick { select(null) } + } + } + } + + //endregion + + + //region search + + private fun search(text: String) { + searchMatches = if (text.isEmpty()) emptyList() else { + model.technologies.filter { (name, tech) -> + tech.displayName(name).lowercase().contains(text) + || name.contains(text) + || tech.unlocks.any { names.recipe(it).lowercase().contains(text) } + }.keys.sortedWith(compareBy({ layout.positions[it]?.y ?: 0.0 }, { layout.positions[it]?.x ?: 0.0 })) + } + searchIndex = -1 + val matches = searchMatches.toSet() + canvas.classList.toggle("has-search", text.isNotEmpty()) + nodes.forEach { (name, node) -> node.classList.toggle("tree-match", name in matches) } + searchCount.content = when { + text.isEmpty() -> "" + searchMatches.isEmpty() -> "No matches" + else -> "${searchMatches.size} matches — press Enter to go to each" + } + } + + + private fun nextSearchMatch(step: Int) { + if (searchMatches.isEmpty()) return + searchIndex = (searchIndex + step).mod(searchMatches.size) + select(searchMatches[searchIndex], centre = true) + searchCount.content = "${searchIndex + 1} of ${searchMatches.size}" + } + + //endregion + + + //region pan and zoom + + private fun applyTransform() { + canvas.style.transform = "translate(${offsetX}px, ${offsetY}px) scale($scale)" + canvas.classList.toggle("zoomed-out", scale < LABEL_SCALE) + } + + + private fun viewportSize(): Pair { + val element = viewport.getElement() as? HTMLElement + return (element?.clientWidth?.toDouble() ?: 800.0) to (element?.clientHeight?.toDouble() ?: 600.0) + } + + + /** Zoom so that the point ([x], [y]) in the viewport stays still */ + private fun zoomAt(factor: Double, x: Double, y: Double) { + val newScale = (scale * factor).coerceIn(MIN_SCALE, MAX_SCALE) + offsetX = x - (x - offsetX) * newScale / scale + offsetY = y - (y - offsetY) * newScale / scale + scale = newScale + applyTransform() + } + + + private fun zoomBy(factor: Double) { + val (width, height) = viewportSize() + zoomAt(factor, width / 2, height / 2) + } + + + private fun fit() { + val (width, height) = viewportSize() + scale = min(width / layout.width, height / layout.height).coerceIn(MIN_SCALE, MAX_SCALE) + offsetX = (width - layout.width * scale) / 2 + offsetY = (height - layout.height * scale) / 2 + applyTransform() + } + + + /** Show the first technologies, at the top of the tree, at a readable zoom */ + private fun showTop() { + val (width, _) = viewportSize() + val firstRow = layout.positions.values.filter { it.level == 0 } + val centreX = firstRow.map { it.x }.average().takeIf { !it.isNaN() } ?: (layout.width / 2) + scale = 0.75 + offsetX = width / 2 - centreX * scale + offsetY = 24.0 - (firstRow.minOfOrNull { it.y } ?: 0.0) * scale + NODE_HEIGHT / 2 * scale + applyTransform() + } + + + private fun centreOn(name: String) { + val position = layout.positions[name] ?: return + val (width, height) = viewportSize() + if (scale < 0.6) scale = 1.0 + offsetX = width / 2 - position.x * scale + offsetY = height / 2 - position.y * scale + applyTransform() + } + + + private fun initPanZoom(element: HTMLElement) { + val pointers = mutableMapOf>() + var dragged = false + var pinchDistance = 0.0 + + fun local(event: MouseEvent): Pair { + val rect = element.getBoundingClientRect() + return (event.clientX - rect.left) to (event.clientY - rect.top) + } + + element.asDynamic().addEventListener("wheel", { event: WheelEvent -> + event.preventDefault() + // trackpads send small, frequent deltas; mouse wheels send ~100 per notch + val delta = if (event.deltaMode == 1) event.deltaY * 33 else event.deltaY + val (x, y) = local(event) + zoomAt(exp(-delta * 0.0015), x, y) + }, js("({passive: false})")) + + element.addEventListener("pointerdown", { event -> + event as PointerEvent + if (event.button.toInt() != 0) return@addEventListener + pointers[event.pointerId] = local(event) + if (pointers.size == 1) dragged = false + if (pointers.size == 2) { + val (a, b) = pointers.values.toList() + pinchDistance = hypot(a.first - b.first, a.second - b.second) + } + }) + + element.addEventListener("pointermove", { event -> + event as PointerEvent + val previous = pointers[event.pointerId] ?: return@addEventListener + val current = local(event) + pointers[event.pointerId] = current + if (pointers.size == 1) { + val dx = current.first - previous.first + val dy = current.second - previous.second + if (!dragged && abs(dx) + abs(dy) < 3) { + pointers[event.pointerId] = previous // not a drag yet + return@addEventListener + } + if (!dragged) element.setPointerCapture(event.pointerId) + dragged = true + offsetX += dx + offsetY += dy + applyTransform() + } else if (pointers.size == 2) { + dragged = true + val (a, b) = pointers.values.toList() + val distance = hypot(a.first - b.first, a.second - b.second) + if (pinchDistance > 0) zoomAt(distance / pinchDistance, (a.first + b.first) / 2, (a.second + b.second) / 2) + pinchDistance = distance + } + }) + + val release = { event: Event -> + pointers.remove((event as PointerEvent).pointerId) + pinchDistance = 0.0 + if (pointers.size == 1) dragged = true // don't treat the end of a pinch as a click + } + element.addEventListener("pointerup", release) + element.addEventListener("pointercancel", release) + + element.addEventListener("click", { event -> + if (dragged) return@addEventListener + val node = (event.target as? Element)?.closest("[data-tech]") + select(node?.getAttribute("data-tech")) + }) + + element.addEventListener("dblclick", { event -> + val node = (event.target as? Element)?.closest("[data-tech]") ?: return@addEventListener + node.getAttribute("data-tech")?.let { detail.show(it) } + }) + } + + //endregion +} diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/TechnologyDetail.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/TechnologyDetail.kt new file mode 100644 index 0000000..81bf882 --- /dev/null +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/TechnologyDetail.kt @@ -0,0 +1,209 @@ +package dev.adamko.kafkatorio.webmap.research + +import dev.adamko.kafkatorio.webmap.services.TechnologyInfo +import io.kvision.core.Container +import io.kvision.core.onClick +import io.kvision.html.Div +import io.kvision.html.button +import io.kvision.html.div +import io.kvision.html.h3 +import io.kvision.html.image +import io.kvision.html.link +import io.kvision.html.p +import io.kvision.html.span +import kotlinx.browser.document +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.intOrNull +import kotlinx.serialization.json.jsonPrimitive +import org.w3c.dom.events.KeyboardEvent + + +/** Display names of items and recipes, from the exported prototype data */ +internal class Names( + val items: Map, + val recipes: Map, +) { + fun item(name: String) = items[name] ?: name + fun recipe(name: String) = recipes[name] ?: name +} + + +/** + * A pop-up with everything about one technology: its cost, prerequisites, what it leads to, and + * what it unlocks. + * + * @param[treeLink] the link to show a technology in the tree, or `null` to not show the link + * @param[onShow] called whenever a technology is shown, including ones opened from the pop-up + */ +internal class TechnologyDetail( + page: Container, + private val model: ResearchModel, + private val names: Names, + private val treeLink: ((String) -> String)? = null, + private val onShow: (String) -> Unit = {}, +) { + + private val overlay: Div = page.div(className = "research-detail-overlay") { + visible = false + onClick { event -> if (event.target == getElement()) close() } + } + + init { + document.addEventListener("keydown", { event -> + if ((event as KeyboardEvent).key == "Escape") close() + }) + } + + val isOpen: Boolean get() = overlay.visible + + + fun close() { + overlay.visible = false + overlay.removeAll() + } + + + fun show(name: String) { + val tech = model.technologies[name] ?: return + val status = model.status[name] ?: TechnologyStatus.LOCKED + onShow(name) + overlay.removeAll() + overlay.div(className = "research-detail tech-${status.name.lowercase()}") { + button("×", className = "research-detail-close") { + title = "Close" + onClick { close() } + } + div(className = "research-detail-title") { + image("/kafkatorio/icons/technology/$name.png", alt = "", className = "research-detail-icon") + div { + h3(tech.displayName(name)) + span(status.label, className = "tech-status") + model.level(name)?.let { level -> + val max = tech.maxLevel?.jsonPrimitive?.let { it.intOrNull?.toString() ?: it.contentOrNull } + span(" Level $level${if (max == "infinite") " (infinite)" else ""}", className = "home-muted") + } + treeLink?.let { href -> + div(className = "research-detail-links") { + link("Show in tree", href(name), className = "tech-link") { + setAttribute("data-navigo", "true") + } + } + } + } + } + + val units = model.units(name) + div(className = "research-detail-section") { + h3("Cost") + if (units == null) { + p(tech.triggerDescription(names)) + } else { + val time = model.timePerUnit(name) + p("${formatAmount(units)} units${time?.let { ", ${formatAmount(it)}s each" } ?: ""}", className = "home-muted") + packList(model.cost(name)) + } + } + + if (status != TechnologyStatus.RESEARCHED) { + val (toReach, count) = model.costToReach(name) + if (count > 1) { + div(className = "research-detail-section") { + h3("Total to reach") + p("$count technologies, including the prerequisites that aren't researched yet", className = "home-muted") + packList(toReach) + } + } + } + + technologyList("Requires", tech.prerequisites) + technologyList("Leads to", model.successors[name].orEmpty()) + + if (tech.unlocks.isNotEmpty()) { + div(className = "research-detail-section") { + h3("Unlocks") + div(className = "recipe-list") { + tech.unlocks.forEach { recipe -> + div(className = "recipe-item") { + image("/kafkatorio/icons/recipe/$recipe.png", alt = "", className = "pack-icon pack-icon-small") + span(names.recipe(recipe)) + } + } + } + } + } + } + overlay.visible = true + if (treeLink != null) dev.adamko.kafkatorio.webmap.routing.SiteRouter.updatePageLinks() + } + + + private fun Container.packList(cost: SciencePackCost) { + div(className = "pack-list") { + model.sciencePacks.filter { it in cost }.forEach { pack -> + div(className = "pack-total") { + title = names.item(pack) + packIcon(pack, names) + span(formatAmount(cost.getValue(pack))) + } + } + } + } + + + private fun Container.technologyList(title: String, technologies: List) { + val known = technologies.filter { it in model.technologies } + if (known.isEmpty()) return + div(className = "research-detail-section") { + h3(title) + div(className = "tech-chip-list") { + known.sortedBy { model.depth[it] ?: 0 }.forEach { name -> + val status = model.status[name] ?: TechnologyStatus.LOCKED + div(className = "tech-chip tech-${status.name.lowercase()}") { + image("/kafkatorio/icons/technology/$name.png", alt = "", className = "pack-icon pack-icon-small") + span(model.technologies.getValue(name).displayName(name)) + onClick { show(name) } + } + } + } + } + } +} + + +internal fun Container.packIcon(pack: String, names: Names, small: Boolean = false) { + image( + "/kafkatorio/icons/item/$pack.png", + alt = names.item(pack), + className = if (small) "pack-icon pack-icon-small" else "pack-icon", + ) { + title = names.item(pack) + } +} + + +/** The in-game name. Technologies with levels (e.g. `Mining productivity 3`) already include it. */ +internal fun TechnologyInfo.displayName(id: String): String = name.ifBlank { id } + + +/** e.g. `Craft 10 Iron plate`, for technologies researched by doing something */ +internal fun TechnologyInfo.triggerDescription(names: Names): String { + val trigger = trigger ?: return "Unknown cost" + fun field(key: String) = trigger[key]?.jsonPrimitive?.contentOrNull + val type = field("type") ?: return "Unknown cost" + val count = field("count")?.let { "$it " } ?: "" + return when (type) { + "craft-item" -> "Craft $count${names.item(field("item") ?: "?")}" + "mine-entity" -> "Mine ${names.item(field("entity") ?: "?").replace('-', ' ')}" + "build-entity" -> "Build ${names.item(field("entity") ?: "?").replace('-', ' ')}" + else -> type.replace('-', ' ').replaceFirstChar { it.uppercase() } + } +} + + +internal fun formatAmount(amount: Double): String = when { + amount >= 1_000_000_000 -> "${(amount / 100_000_000).toLong() / 10.0}B" + amount >= 1_000_000 -> "${(amount / 100_000).toLong() / 10.0}M" + amount >= 10_000 -> "${(amount / 100).toLong() / 10.0}k" + amount == kotlin.math.floor(amount) -> amount.toLong().toString() + else -> "${(amount * 10).toLong() / 10.0}" +} diff --git a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/researchPage.kt b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/researchPage.kt index e51e51c..cd44e9f 100644 --- a/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/researchPage.kt +++ b/modules/web-map/src/main/kotlin/dev/adamko/kafkatorio/webmap/research/researchPage.kt @@ -14,31 +14,36 @@ import io.kvision.html.button import io.kvision.html.div import io.kvision.html.h1 import io.kvision.html.h2 -import io.kvision.html.h3 import io.kvision.html.image +import io.kvision.html.link import io.kvision.html.p import io.kvision.html.span -import kotlinx.browser.document import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.async import kotlinx.coroutines.launch -import kotlinx.serialization.json.contentOrNull -import kotlinx.serialization.json.intOrNull -import kotlinx.serialization.json.jsonPrimitive -import org.w3c.dom.events.KeyboardEvent private val researchPageScope = CoroutineScope(Dispatchers.Default + SupervisorJob()) -/** The technology tree, and what's researched, with the science packs each technology needs. */ -fun Container.researchPage(state: SiteState) { +/** How the technologies are shown on the research page */ +enum class ResearchLayout { LIST, TREE } + + +/** + * The technology tree, and what's researched, with the science packs each technology needs. + * + * Shown either as a list of technologies that can be filtered, or as a tree with the + * prerequisites linked together, like in the game. + */ +fun Container.researchPage(state: SiteState, layout: ResearchLayout) { val serverId = state.serverId ?: return - val page = div(className = "research-page") { - p("Loading research…", className = "home-muted") + val page = div(className = "research-page research-page-${layout.name.lowercase()}") { + researchLayoutTabs(serverId, layout) } + val loading = page.p("Loading research…", className = "home-muted") researchPageScope.launch { val technologies = async { runCatching { EventsServerClient.technologies() } @@ -50,22 +55,35 @@ fun Container.researchPage(state: SiteState) { val research = async { runCatching { EventsServerClient.research(serverId) }.getOrNull() } val model = ResearchModel(technologies.await(), research.await()) - page.removeAll() - if (model.technologies.isEmpty()) { - page.p("The technology tree hasn't been exported yet - see docs/guide.md.", className = "home-muted") - } else { - ResearchView(page, serverId, model, Names(itemNames.await(), recipeNames.await())).render() + val names = Names(itemNames.await(), recipeNames.await()) + page.remove(loading) + when { + model.technologies.isEmpty() -> + page.p("The technology tree hasn't been exported yet - see docs/guide.md.", className = "home-muted") + + layout == ResearchLayout.LIST -> ResearchView(page, serverId, model, names).render() + layout == ResearchLayout.TREE -> ResearchTreeView(page, model, names).render() } } } -private class Names( - val items: Map, - val recipes: Map, -) { - fun item(name: String) = items[name] ?: name - fun recipe(name: String) = recipes[name] ?: name +fun researchPath(serverId: FactorioServerId, layout: ResearchLayout): String = when (layout) { + ResearchLayout.LIST -> "/servers/${serverId.id}/research" + ResearchLayout.TREE -> "/servers/${serverId.id}/research/tree" +} + + +/** Links to switch between the list and the tree */ +private fun Container.researchLayoutTabs(serverId: FactorioServerId, current: ResearchLayout) { + div(className = "research-layout-tabs") { + listOf(ResearchLayout.LIST to "List", ResearchLayout.TREE to "Tree").forEach { (layout, label) -> + link(label, researchPath(serverId, layout), className = "research-filter-button") { + if (layout == current) addCssClass("active") + setAttribute("data-navigo", "true") + } + } + } } @@ -86,7 +104,7 @@ private class ResearchView( private lateinit var packFilterButtons: Map private lateinit var statusButtons: Map?, io.kvision.html.Button> private lateinit var resultCount: Div - private lateinit var detailOverlay: Div + private lateinit var detail: TechnologyDetail fun render() { @@ -97,12 +115,8 @@ private class ResearchView( page.div(className = "research-grid") { sortedTechnologies().forEach { name -> cards[name] = technologyCard(name) } } - detailOverlay = page.div(className = "research-detail-overlay") { - visible = false - onClick { event -> if (event.target == getElement()) closeDetail() } - } - document.addEventListener("keydown", { event -> - if ((event as KeyboardEvent).key == "Escape") closeDetail() + detail = TechnologyDetail(page, model, names, treeLink = { name -> + "${researchPath(serverId, ResearchLayout.TREE)}?tech=$name" }) applyFilters() } @@ -264,7 +278,7 @@ private class ResearchView( div(className = "tech-card-cost") { costSummary(name, tech) } span(status.label, className = "tech-status") } - onClick { showDetail(name) } + onClick { detail.show(name) } } } @@ -281,147 +295,12 @@ private class ResearchView( } - private fun Container.packIcon(pack: String, small: Boolean = false) { - image("/kafkatorio/icons/item/$pack.png", alt = names.item(pack), className = if (small) "pack-icon pack-icon-small" else "pack-icon") { - title = names.item(pack) - } - } + private fun Container.packIcon(pack: String, small: Boolean = false) = packIcon(pack, names, small) private fun Container.technologyLink(name: String) { span(model.technologies[name]?.displayName(name) ?: name, className = "tech-link") { - onClick { showDetail(name) } - } - } - - - private fun closeDetail() { - detailOverlay.visible = false - detailOverlay.removeAll() - } - - - private fun showDetail(name: String) { - val tech = model.technologies[name] ?: return - val status = model.status[name] ?: TechnologyStatus.LOCKED - detailOverlay.removeAll() - detailOverlay.div(className = "research-detail tech-${status.name.lowercase()}") { - button("×", className = "research-detail-close") { - title = "Close" - onClick { closeDetail() } - } - div(className = "research-detail-title") { - image("/kafkatorio/icons/technology/$name.png", alt = "", className = "research-detail-icon") - div { - h3(tech.displayName(name)) - span(status.label, className = "tech-status") - model.level(name)?.let { level -> - val max = tech.maxLevel?.jsonPrimitive?.let { it.intOrNull?.toString() ?: it.contentOrNull } - span(" Level $level${if (max == "infinite") " (infinite)" else ""}", className = "home-muted") - } - } - } - - val units = model.units(name) - div(className = "research-detail-section") { - h3("Cost") - if (units == null) { - p(tech.triggerDescription(names)) - } else { - val time = model.timePerUnit(name) - p("${formatAmount(units)} units${time?.let { ", ${formatAmount(it)}s each" } ?: ""}", className = "home-muted") - packList(model.cost(name)) - } - } - - if (status != TechnologyStatus.RESEARCHED) { - val (toReach, count) = model.costToReach(name) - if (count > 1) { - div(className = "research-detail-section") { - h3("Total to reach") - p("$count technologies, including the prerequisites that aren't researched yet", className = "home-muted") - packList(toReach) - } - } - } - - technologyList("Requires", tech.prerequisites) - technologyList("Leads to", model.successors[name].orEmpty()) - - if (tech.unlocks.isNotEmpty()) { - div(className = "research-detail-section") { - h3("Unlocks") - div(className = "recipe-list") { - tech.unlocks.forEach { recipe -> - div(className = "recipe-item") { - image("/kafkatorio/icons/recipe/$recipe.png", alt = "", className = "pack-icon pack-icon-small") - span(names.recipe(recipe)) - } - } - } - } - } - } - detailOverlay.visible = true - } - - - private fun Container.packList(cost: SciencePackCost) { - div(className = "pack-list") { - model.sciencePacks.filter { it in cost }.forEach { pack -> - div(className = "pack-total") { - title = names.item(pack) - packIcon(pack) - span(formatAmount(cost.getValue(pack))) - } - } - } - } - - - private fun Container.technologyList(title: String, technologies: List) { - val known = technologies.filter { it in model.technologies } - if (known.isEmpty()) return - div(className = "research-detail-section") { - h3(title) - div(className = "tech-chip-list") { - known.sortedBy { model.depth[it] ?: 0 }.forEach { name -> - val status = model.status[name] ?: TechnologyStatus.LOCKED - div(className = "tech-chip tech-${status.name.lowercase()}") { - image("/kafkatorio/icons/technology/$name.png", alt = "", className = "pack-icon pack-icon-small") - span(model.technologies.getValue(name).displayName(name)) - onClick { showDetail(name) } - } - } - } + onClick { detail.show(name) } } } } - - -/** The in-game name. Technologies with levels (e.g. `Mining productivity 3`) already include it. */ -private fun TechnologyInfo.displayName(id: String): String = name.ifBlank { id } - - -/** e.g. `Craft 10 Iron plate`, for technologies researched by doing something */ -private fun TechnologyInfo.triggerDescription(names: Names): String { - val trigger = trigger ?: return "Unknown cost" - fun field(key: String) = trigger[key]?.jsonPrimitive?.contentOrNull - val type = field("type") ?: return "Unknown cost" - val count = field("count")?.let { "$it " } ?: "" - return when (type) { - "craft-item" -> "Craft $count${names.item(field("item") ?: "?")}" - "mine-entity" -> "Mine ${names.item(field("entity") ?: "?").replace('-', ' ')}" - "build-entity" -> "Build ${names.item(field("entity") ?: "?").replace('-', ' ')}" - else -> type.replace('-', ' ').replaceFirstChar { it.uppercase() } - } -} - - -private fun formatAmount(amount: Double): String = when { - amount >= 1_000_000_000 -> "${(amount / 100_000_000).toLong() / 10.0}B" - amount >= 1_000_000 -> "${(amount / 100_000).toLong() / 10.0}M" - amount >= 10_000 -> "${(amount / 100).toLong() / 10.0}k" - amount == kotlin.math.floor(amount) -> amount.toLong().toString() - else -> "${(amount * 10).toLong() / 10.0}" -} 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 edd3b56..f118f90 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 @@ -2,6 +2,7 @@ package dev.adamko.kafkatorio.webmap.routing import dev.adamko.kafkatorio.schema.common.FactorioServerId import dev.adamko.kafkatorio.webmap.App +import dev.adamko.kafkatorio.webmap.research.ResearchLayout import dev.adamko.kafkatorio.webmap.state.SiteAction import dev.adamko.kafkatorio.webmap.rootJob import dev.adamko.kafkatorio.webmap.services.EventsServerClient @@ -41,9 +42,13 @@ object SiteRouter : CoroutineScope { val serverId = match.data["serverId"] as? String ?: error("invalid server id") App.siteStateStore.dispatch(SiteAction.ProductionPage(FactorioServerId(serverId))) } + .on(SiteView.RESEARCH_TREE) { match -> + val serverId = match.data["serverId"] as? String ?: error("invalid server id") + App.siteStateStore.dispatch(SiteAction.ResearchPage(FactorioServerId(serverId), ResearchLayout.TREE)) + } .on(SiteView.RESEARCH) { match -> val serverId = match.data["serverId"] as? String ?: error("invalid server id") - App.siteStateStore.dispatch(SiteAction.ResearchPage(FactorioServerId(serverId))) + App.siteStateStore.dispatch(SiteAction.ResearchPage(FactorioServerId(serverId), ResearchLayout.LIST)) } .on(SiteView.SERVER) { match -> println("routing.on SERVER ${JSON.stringify(match)}") 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 b8ec77d..0710c7a 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 @@ -27,4 +27,8 @@ sealed interface SiteView { object RESEARCH : DynamicPath { override val path: String = "/servers/:serverId/research" } + + object RESEARCH_TREE : DynamicPath { + override val path: String = "/servers/:serverId/research/tree" + } } 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 b66dd3d..dc7f4e5 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 @@ -4,13 +4,14 @@ import dev.adamko.kafkatorio.schema.common.FactorioServerId import dev.adamko.kafkatorio.schema.common.Tick import dev.adamko.kafkatorio.schema.packets.EventServerPacket import dev.adamko.kafkatorio.schema.packets.PlayerUpdate +import dev.adamko.kafkatorio.webmap.research.ResearchLayout import io.kvision.redux.RAction sealed interface SiteAction : RAction { object HomePage : SiteAction data class ServerPage(val serverId: FactorioServerId) : SiteAction - data class ResearchPage(val serverId: FactorioServerId) : SiteAction + data class ResearchPage(val serverId: FactorioServerId, val layout: ResearchLayout) : SiteAction data class ProductionPage(val serverId: FactorioServerId) : 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 a8045cf..91f690b 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 @@ -2,6 +2,7 @@ package dev.adamko.kafkatorio.webmap.state import dev.adamko.kafkatorio.schema.common.FactorioServerId import dev.adamko.kafkatorio.schema.packets.EventServerPacket +import dev.adamko.kafkatorio.webmap.research.ResearchLayout import dev.adamko.kafkatorio.webmap.rootJob import dev.adamko.kafkatorio.webmap.routing.SiteView import kotlin.coroutines.CoroutineContext @@ -37,7 +38,10 @@ data class SiteState( ?: FactorioGameState(action.serverId), ) - is SiteAction.ResearchPage -> copy(view = SiteView.RESEARCH, serverId = action.serverId) + is SiteAction.ResearchPage -> copy( + view = if (action.layout == ResearchLayout.TREE) SiteView.RESEARCH_TREE else SiteView.RESEARCH, + serverId = action.serverId, + ) is SiteAction.ProductionPage -> copy(view = SiteView.PRODUCTION, serverId = action.serverId) diff --git a/modules/web-map/src/main/resources/css/kafkatorio.css b/modules/web-map/src/main/resources/css/kafkatorio.css index 7c652e2..430a62f 100644 --- a/modules/web-map/src/main/resources/css/kafkatorio.css +++ b/modules/web-map/src/main/resources/css/kafkatorio.css @@ -594,6 +594,282 @@ header .navbar .navbar-toggler { } + +/* Research: list / tree switch */ + +.research-layout-tabs { + display: flex; + gap: 6px; + margin-bottom: 12px; +} + +.research-layout-tabs a.research-filter-button { + text-decoration: none; + color: inherit; +} + +.research-detail-links { + margin-top: 6px; +} + + +/* Research tree */ + +.research-page.research-page-tree { + max-width: none; + padding: 12px 0 16px; +} + +.research-tree-toolbar { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px 16px; + margin-bottom: 8px; +} + +.research-tree-toolbar .research-search { + width: 280px; + max-width: 100%; +} + +.research-tree-toolbar .research-count { + margin: 0; +} + +.research-tree-zoom { + display: flex; + gap: 4px; +} + +.research-tree-legend { + display: flex; + flex-wrap: wrap; + gap: 4px 12px; + margin-left: auto; + font-size: 0.85rem; +} + +.research-tree-legend-item::before { + content: ""; + display: inline-block; + width: 10px; + height: 10px; + margin-right: 5px; + border-radius: 2px; + background: var(--tech-status-colour); +} + +.research-tree-selection { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 6px 16px; + min-height: 44px; + padding: 6px 10px; + margin-bottom: 8px; + background: var(--kt-panel); + border: 1px solid var(--kt-border); + border-radius: 6px; +} + +.research-tree-selected { + display: flex; + align-items: center; + gap: 8px; +} + +.research-tree-to-reach { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 4px 10px; +} + +.research-tree-pack { + display: inline-flex; + align-items: center; + gap: 2px; + font-size: 0.9rem; +} + +.research-tree-selection-actions { + display: flex; + gap: 4px; + margin-left: auto; +} + +.research-tree-viewport { + position: relative; + height: calc(100vh - 230px); + min-height: 360px; + overflow: hidden; + background: #191819; + border: 1px solid var(--kt-border); + border-radius: 6px; + cursor: grab; + touch-action: none; + user-select: none; +} + +.research-tree-viewport:active { + cursor: grabbing; +} + +.research-tree-help { + margin-top: 6px; + font-size: 0.85rem; +} + +.research-tree-canvas { + position: absolute; + top: 0; + left: 0; + transform-origin: 0 0; + will-change: transform; +} + +.research-tree-edges { + position: absolute; + top: 0; + left: 0; + overflow: visible; + pointer-events: none; +} + +.tree-edge { + fill: none; + stroke: #5a5856; + stroke-width: 2; + opacity: 0.45; +} + +.tree-edge-done { + stroke: #4c8a3c; +} + +.tree-node { + position: absolute; + width: 104px; + height: 88px; + display: flex; + flex-direction: column; + align-items: center; + padding: 4px 2px 2px; + background: var(--kt-panel); + border: 2px solid var(--tech-status-colour); + border-radius: 6px; + cursor: pointer; + transition: box-shadow 0.15s; +} + +.tree-node:hover { + background: var(--kt-panel-raised); + box-shadow: 0 0 0 2px var(--tech-status-colour); +} + +.tree-node-icon { + width: 48px; + height: 48px; + flex-shrink: 0; + pointer-events: none; +} + +.tree-node.tech-locked .tree-node-icon { + filter: grayscale(0.7) brightness(0.8); +} + +.tree-node-name { + margin-top: 2px; + font-size: 11px; + line-height: 1.15; + text-align: center; + color: var(--kt-text); + overflow: hidden; + display: -webkit-box; + -webkit-line-clamp: 2; + -webkit-box-orient: vertical; +} + +/* zoomed out: show the shape of the tree, not the names */ +.research-tree-canvas.zoomed-out .tree-node-name { + display: none; +} + +.research-tree-canvas.zoomed-out .tree-node { + justify-content: center; +} + +.research-tree-canvas.zoomed-out .tree-node-icon { + width: 72px; + height: 72px; +} + +/* selection: everything needed for the selected technology, and what it leads to */ +/* dim the contents, not the node, so links don't show through it */ +.research-tree-canvas.has-selection .tree-node > *, +.research-tree-canvas.has-search .tree-node:not(.tree-match) > * { + opacity: 0.25; +} + +.research-tree-canvas.has-selection .tree-node, +.research-tree-canvas.has-search .tree-node:not(.tree-match) { + border-color: color-mix(in srgb, var(--tech-status-colour) 30%, var(--kt-panel)); +} + +.research-tree-canvas.has-selection .tree-edge { + opacity: 0.12; +} + +.research-tree-canvas.research-tree-canvas .tree-node.tree-ancestor > *, +.research-tree-canvas.research-tree-canvas .tree-node.tree-successor > *, +.research-tree-canvas.research-tree-canvas .tree-node.tree-selected > * { + opacity: 1; +} + +.research-tree-canvas.research-tree-canvas .tree-node.tree-ancestor, +.research-tree-canvas.research-tree-canvas .tree-node.tree-successor, +.research-tree-canvas.research-tree-canvas .tree-node.tree-selected { + border-color: var(--tech-status-colour); +} + +.tree-node.tree-selected { + box-shadow: 0 0 0 3px var(--kt-accent), 0 0 18px var(--kt-accent); + z-index: 2; +} + +.research-tree-canvas.has-selection .tree-edge.tree-edge-chain { + stroke: var(--kt-accent); + stroke-width: 3; + opacity: 0.9; +} + +.research-tree-canvas.has-selection .tree-edge.tree-edge-next { + stroke: #8fb8e8; + stroke-width: 3; + stroke-dasharray: 8 5; + opacity: 0.9; +} + +.tree-node.tree-match { + outline: 3px solid #8fb8e8; + outline-offset: 2px; +} + +@media (max-width: 600px) { + .research-tree-viewport { + height: calc(100vh - 300px); + } + + .research-tree-legend { + margin-left: 0; + } + + .research-tree-selection-actions { + margin-left: 0; + } +} + /* Production */ .production-page {