Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby
22.7 KB
Raw Blame
import { Controller } from "@hotwired/stimulus";
import * as d3 from "d3";
import { sankey, sankeyCenter } from "d3-sankey";
import { formatCashFlowCurrency } from "utils/cash_flow_chart_data";
import { CHART_TOOLTIP_CLASSES } from "utils/chart_tooltip";
import { sankeyLabelOnRight } from "utils/sankey_align";
import { hiddenSankeyLabels } from "utils/sankey_labels";
import { sankeyNodeHasChildren, zoomSankeyData } from "utils/sankey_zoom";
import {
  buildCategoryTransactionsUrl,
  isNavigableCategoryNode,
} from "utils/transactions_filter_url";

let nextChartId = 0;

// Preview-only renderer. Keep the legacy Sankey unchanged during comparison.
export default class extends Controller {
  static targets = ["chart", "zoomOutButton", "sortSegment"];

  static values = {
    data: Object,
    labels: Object,
    nodeWidth: { type: Number, default: 15 },
    nodePadding: { type: Number, default: 20 },
    currency: { type: String, default: "USD" },
    startDate: String,
    endDate: String,
  };

  // Visual constants
  static HOVER_OPACITY = 0.4;
  static HOVER_FILTER = "saturate(1.3) brightness(1.1)";
  static EXTENT_MARGIN = 16;
  static MIN_NODE_PADDING = 4;
  static MAX_PADDING_RATIO = 0.4;
  static CORNER_RADIUS = 8;
  static ZOOM_TRANSITION_MS = 220;
  static DEFAULT_COLOR = "var(--color-gray-400)";
  static CSS_VAR_MAP = {
    "var(--color-success)": "#10A861",
    "var(--color-destructive)": "#EC2222",
    "var(--color-gray-400)": "#9E9E9E",
    "var(--color-gray-500)": "#737373",
  };
  static MIN_LABEL_SPACING = 28; // Minimum vertical space needed for labels (2 lines)
  static SORT_ORDERS = ["auto", "ascending", "descending"];
  static SORT_STORAGE_KEY = "cashflowSankeySortOrder";
  static SORT_EVENT = "cashflow-sankey:sort-changed";

  connect() {
    this.gradientPrefix ||= `preview-sankey-${++nextChartId}`;
    this.connected = true;
    this.zoomRootId = null;
    this.resizeObserver = new ResizeObserver(() => this.#draw());
    this.resizeObserver.observe(this.#chartElement());
    this.tooltip = null;
    this.sortOrder = this.#storedSortOrder();
    // The dashboard renders this chart twice (inline and in the expand dialog):
    // keep every instance on the page in step when one changes the order.
    this.onSortChanged = (event) => this.#applySortOrder(event.detail.order);
    window.addEventListener(this.constructor.SORT_EVENT, this.onSortChanged);
    // A Turbo morph refresh (the sync toast's auto-refresh, or a broadcast
    // refresh stream) keeps this element and its controller but puts the
    // server markup back inside, so the sort controls show the default while
    // the order is kept here, and the tooltip appended outside this element
    // is dropped. The graph is fetched again by the cash-flow controller,
    // and the data value callback resets the zoom.
    this.onMorph = () => {
      if (!this.connected) return;

      this.tooltip?.remove();
      this.#createTooltip();
      this.#syncSortControls();
    };
    document.addEventListener("turbo:morph", this.onMorph);
    this.#createTooltip();
    this.#syncZoomControls();
    this.#syncSortControls();
    this.#draw();

    // Labels are measured to keep them off neighbouring bars; measure again
    // once the page font has replaced the fallback.
    if (document.fonts?.status === "loading") {
      document.fonts.ready.then(() => {
        if (this.connected) this.#draw();
      });
    }
  }

  dataValueChanged() {
    if (!this.connected) return;

    this.zoomRootId = null;
    this.#syncZoomControls();
    this.#draw();
  }

  disconnect() {
    this.connected = false;
    window.removeEventListener(this.constructor.SORT_EVENT, this.onSortChanged);
    document.removeEventListener("turbo:morph", this.onMorph);
    this.resizeObserver?.disconnect();
    clearTimeout(this.drawTimeout);
    this.tooltip?.remove();
    this.tooltip = null;
  }

  clear() {
    clearTimeout(this.drawTimeout);
    this.tooltip?.remove();
    this.tooltip = null;
    d3.select(this.#chartElement()).selectAll("svg").interrupt().remove();
  }

  // Top-to-bottom order of the nodes in each column. "auto" is d3-sankey's
  // default layout (minimises crossings); the others order by amount.
  setSort(event) {
    const order = event.currentTarget.dataset.sortOrder;
    if (!this.constructor.SORT_ORDERS.includes(order)) return;
    if (order === this.sortOrder) return;

    try {
      localStorage.setItem(this.constructor.SORT_STORAGE_KEY, order);
    } catch {
      // Ignore storage errors (e.g. private browsing); the choice still applies now.
    }
    window.dispatchEvent(
      new CustomEvent(this.constructor.SORT_EVENT, { detail: { order } }),
    );
  }

  #applySortOrder(order) {
    if (!this.constructor.SORT_ORDERS.includes(order)) return;
    if (order === this.sortOrder) return;

    this.sortOrder = order;
    this.#syncSortControls();
    this.#draw({ animate: true });
  }

  zoomOut() {
    if (!this.zoomRootId) return;

    this.focusAfterDraw = this.zoomRootId;
    this.zoomRootId = null;
    this.#syncZoomControls();
    this.#draw({ animate: true });
  }

  #draw({ animate = false } = {}) {
    const { nodes = [], links = [] } = this.#visibleData();

    // Hide tooltip and reset any hover states before redrawing
    this.#hideTooltip();

    const chartElement = this.#chartElement();
    const focusedNode = document.activeElement?.closest("[data-node-id]");
    if (chartElement.contains(focusedNode))
      this.focusAfterDraw ||= focusedNode.dataset.nodeId;
    const chart = d3.select(chartElement);

    clearTimeout(this.drawTimeout);
    chart.selectAll("svg").interrupt();

    if (!nodes.length || !links.length) {
      chart.selectAll("svg").remove();
      return;
    }

    if (animate) {
      chart
        .selectAll("svg")
        .transition()
        .duration(this.constructor.ZOOM_TRANSITION_MS / 2)
        .style("opacity", 0)
        .remove();

      this.drawTimeout = setTimeout(() => {
        this.#render(nodes, links, true);
      }, this.constructor.ZOOM_TRANSITION_MS / 2);
    } else {
      chart.selectAll("svg").remove();
      this.#render(nodes, links, false);
    }
  }

  #render(nodes, links, animate) {
    const chartElement = this.#chartElement();
    const chart = d3.select(chartElement);

    const width = chartElement.clientWidth || 600;
    const height = chartElement.clientHeight || 400;

    const svg = chart
      .append("svg")
      .attr("width", width)
      .attr("height", height)
      // Marks which order this drawing uses (a redraw fades the old one out).
      .attr("data-sort-order", this.sortOrder)
      .style("opacity", animate ? 0 : 1);

    const effectivePadding = this.#calculateNodePadding(nodes.length, height);
    const sankeyData = this.#generateSankeyData(
      nodes,
      links,
      width,
      height,
      effectivePadding,
    );

    this.#createGradients(svg, sankeyData.links);

    const linkPaths = this.#drawLinks(svg, sankeyData.links);
    const { nodeGroups, hiddenLabels } = this.#drawNodes(
      svg,
      sankeyData.nodes,
      width,
    );

    this.#attachHoverEvents(linkPaths, nodeGroups, sankeyData, hiddenLabels);

    if (animate) {
      svg
        .transition()
        .duration(this.constructor.ZOOM_TRANSITION_MS / 2)
        .style("opacity", 1);
    }
  }

  #chartElement() {
    return this.hasChartTarget ? this.chartTarget : this.element;
  }

  #visibleData() {
    if (!this.zoomRootId) return this.dataValue || {};

    return zoomSankeyData(this.dataValue, this.zoomRootId);
  }

  #storedSortOrder() {
    try {
      const stored = localStorage.getItem(this.constructor.SORT_STORAGE_KEY);
      return this.constructor.SORT_ORDERS.includes(stored) ? stored : "auto";
    } catch {
      return "auto";
    }
  }

  #syncSortControls() {
    this.sortSegmentTargets.forEach((segment) => {
      const active = segment.dataset.sortOrder === this.sortOrder;
      segment.classList.toggle("segmented-control__segment--active", active);
      segment.setAttribute("aria-pressed", active ? "true" : "false");
    });
  }

  #syncZoomControls() {
    this.zoomOutButtonTargets.forEach((button) => {
      button.hidden = !this.zoomRootId;
    });
  }

  #zoomIn(node) {
    if (!node.id || !sankeyNodeHasChildren(this.#visibleData(), node.id))
      return;

    if (this.element.contains(document.activeElement))
      this.focusAfterDraw = node.id;
    this.zoomRootId = node.id;
    this.#syncZoomControls();
    this.#draw({ animate: true });
  }

  #nodeAction(node) {
    if (sankeyNodeHasChildren(this.#visibleData(), node.id)) return "button";
    if (isNavigableCategoryNode(node.id) && node.filter_value) return "link";
    return null;
  }

  #activateNode(node) {
    const action = this.#nodeAction(node);
    if (action === "button") {
      this.#zoomIn(node);
    } else if (action === "link") {
      Turbo.visit(
        buildCategoryTransactionsUrl({
          filterValue: node.filter_value,
          startDate: this.startDateValue,
          endDate: this.endDateValue,
        }),
      );
    }
  }

  // Dynamic padding prevents padding from dominating when there are many nodes
  #calculateNodePadding(nodeCount, height) {
    const margin = this.constructor.EXTENT_MARGIN;
    const availableHeight = height - margin * 2;
    const maxPaddingTotal =
      availableHeight * this.constructor.MAX_PADDING_RATIO;
    const gaps = Math.max(nodeCount - 1, 1);
    const dynamicPadding = Math.min(
      this.nodePaddingValue,
      Math.floor(maxPaddingTotal / gaps),
    );
    return Math.max(this.constructor.MIN_NODE_PADDING, dynamicPadding);
  }

  #generateSankeyData(nodes, links, width, height, nodePadding) {
    const margin = this.constructor.EXTENT_MARGIN;
    const sankeyGenerator = sankey()
      // Centre alignment: a sink sits at its depth, a source one column
      // before the nearest node it feeds. The default pushes every sink to
      // the last column, which is the subcategories' once a family has any.
      .nodeAlign(sankeyCenter)
      .nodeWidth(this.nodeWidthValue)
      .nodePadding(nodePadding)
      .extent([
        [margin, margin],
        [width - margin, height - margin],
      ]);

    if (this.sortOrder === "ascending") {
      sankeyGenerator.nodeSort((a, b) => a.value - b.value);
    } else if (this.sortOrder === "descending") {
      sankeyGenerator.nodeSort((a, b) => b.value - a.value);
    }

    return sankeyGenerator({
      nodes: nodes.map((d) => ({
        ...d,
        // Structural labels belong to the UI locale, not the API fallback name.
        name: this.labelsValue[d.kind] || d.name,
      })),
      links: links.map((d) => ({ ...d })),
    });
  }

  #createGradients(svg, links) {
    const defs = svg.append("defs");

    links.forEach((link, i) => {
      const gradientId = this.#gradientId(link, i);
      const gradient = defs
        .append("linearGradient")
        .attr("id", gradientId)
        .attr("gradientUnits", "userSpaceOnUse")
        .attr("x1", link.source.x1)
        .attr("x2", link.target.x0);

      gradient
        .append("stop")
        .attr("offset", "0%")
        .attr("stop-color", this.#colorWithOpacity(link.source.color));

      gradient
        .append("stop")
        .attr("offset", "100%")
        .attr("stop-color", this.#colorWithOpacity(link.target.color));
    });
  }

  #gradientId(link, index) {
    return `${this.gradientPrefix}-link-gradient-${link.source.index}-${link.target.index}-${index}`;
  }

  #colorWithOpacity(nodeColor, opacity = 0.1) {
    const defaultColor = this.constructor.DEFAULT_COLOR;
    let colorStr = nodeColor || defaultColor;

    // Map CSS variables to hex values for d3 color manipulation
    colorStr = this.constructor.CSS_VAR_MAP[colorStr] || colorStr;

    // Unmapped CSS vars cannot be manipulated, return as-is
    if (colorStr.startsWith("var(--")) return colorStr;

    const d3Color = d3.color(colorStr);
    return d3Color ? d3Color.copy({ opacity }) : defaultColor;
  }

  #drawLinks(svg, links) {
    return svg
      .append("g")
      .attr("fill", "none")
      .selectAll("path")
      .data(links)
      .join("path")
      .attr("class", "sankey-link")
      .attr("d", (d) =>
        d3.linkHorizontal()({
          source: [d.source.x1, d.y0],
          target: [d.target.x0, d.y1],
        }),
      )
      .attr("stroke", (d, i) => `url(#${this.#gradientId(d, i)})`)
      .attr("stroke-width", (d) => Math.max(1, d.width))
      .style("transition", "opacity 0.3s ease");
  }

  #drawNodes(svg, nodes, width) {
    const nodeGroups = svg
      .append("g")
      .selectAll("g")
      .data(nodes)
      .join("g")
      .style("transition", "opacity 0.3s ease");

    nodeGroups
      .append("path")
      .attr("d", (d) => this.#nodePath(d))
      .attr("fill", (d) => d.color || this.constructor.DEFAULT_COLOR)
      .attr("stroke", (d) => (d.color ? "none" : "var(--color-gray-500)"));

    const hiddenLabels = this.#addNodeLabels(
      svg,
      nodeGroups,
      sankeyLabelOnRight(nodes, width),
      nodes,
    );

    return { nodeGroups, hiddenLabels };
  }

  #nodePath(node) {
    const { x0, y0, x1, y1 } = node;
    const height = y1 - y0;
    const radius = Math.max(
      0,
      Math.min(this.constructor.CORNER_RADIUS, height / 2),
    );

    const isSourceNode =
      node.sourceLinks?.length > 0 && !node.targetLinks?.length;
    const isTargetNode =
      node.targetLinks?.length > 0 && !node.sourceLinks?.length;

    // Too small for rounded corners
    if (height < radius * 2) {
      return this.#rectPath(x0, y0, x1, y1);
    }

    if (isSourceNode) {
      return this.#roundedLeftPath(x0, y0, x1, y1, radius);
    }

    if (isTargetNode) {
      return this.#roundedRightPath(x0, y0, x1, y1, radius);
    }

    return this.#rectPath(x0, y0, x1, y1);
  }

  #rectPath(x0, y0, x1, y1) {
    return `M ${x0},${y0} L ${x1},${y0} L ${x1},${y1} L ${x0},${y1} Z`;
  }

  #roundedLeftPath(x0, y0, x1, y1, r) {
    return `M ${x0 + r},${y0}
            L ${x1},${y0}
            L ${x1},${y1}
            L ${x0 + r},${y1}
            Q ${x0},${y1} ${x0},${y1 - r}
            L ${x0},${y0 + r}
            Q ${x0},${y0} ${x0 + r},${y0} Z`;
  }

  #roundedRightPath(x0, y0, x1, y1, r) {
    return `M ${x0},${y0}
            L ${x1 - r},${y0}
            Q ${x1},${y0} ${x1},${y0 + r}
            L ${x1},${y1 - r}
            Q ${x1},${y1} ${x1 - r},${y1}
            L ${x0},${y1} Z`;
  }

  #addNodeLabels(svg, nodeGroups, labelOnRight, nodes) {
    const controller = this;
    const hiddenLabels = this.#calculateHiddenLabels(
      nodes,
      this.#measureLabels(svg, nodes, labelOnRight),
    );

    nodeGroups
      .append("text")
      .attr(
        "class",
        "text-xs font-medium text-primary fill-current select-none",
      )
      .style("cursor", "default")
      .style("opacity", (d) => (hiddenLabels.has(d.index) ? 0 : 1))
      // A hidden label can sit over another node's bar; it must not take
      // that bar's hovers and clicks, even while hover reveals it.
      .style("pointer-events", (d) =>
        hiddenLabels.has(d.index) ? "none" : null,
      )
      .style("transition", "opacity 0.2s ease")
      .each(function (d) {
        controller.#writeLabel(d3.select(this), d, labelOnRight);
      });

    return hiddenLabels;
  }

  // Name above amount, beside the bar on the side the label rule picks.
  #writeLabel(textEl, d, labelOnRight) {
    const right = labelOnRight(d);
    const x = right ? d.x1 + 6 : d.x0 - 6;

    textEl
      .attr("x", x)
      .attr("y", (d.y1 + d.y0) / 2)
      .attr("dy", "-0.2em")
      .attr("text-anchor", right ? "start" : "end");

    textEl.selectAll("tspan").remove();
    textEl.append("tspan").text(d.name);
    textEl
      .append("tspan")
      .attr("x", x)
      .attr("dy", "1.2em")
      .attr("class", "font-mono text-secondary")
      .style("font-size", "0.65rem")
      .text(this.#formatCurrency(d.value));
  }

  // Where each label lands at this width, measured with an invisible probe
  // before the real labels are drawn, so the overlap rule can see a label
  // that reaches into the next column.
  #measureLabels(svg, nodes, labelOnRight) {
    const probe = svg
      .append("text")
      .attr("class", "text-xs font-medium select-none")
      .style("visibility", "hidden");

    const boxes = new Map();
    nodes.forEach((d) => {
      this.#writeLabel(probe, d, labelOnRight);
      const { x, y, width: boxWidth, height } = probe.node().getBBox();
      boxes.set(d.index, { x, y, width: boxWidth, height });
    });

    probe.remove();
    return boxes;
  }

  // Calculate which labels should be hidden to prevent overlap
  #calculateHiddenLabels(nodes, labelBoxes) {
    const height = this.#chartElement().clientHeight || 400;
    return hiddenSankeyLabels(nodes, {
      height,
      minSpacing: this.constructor.MIN_LABEL_SPACING,
      labelBoxes,
    });
  }

  #attachHoverEvents(linkPaths, nodeGroups, sankeyData, hiddenLabels) {
    const applyHover = (targetLinks) => {
      const targetSet = new Set(targetLinks);
      const connectedNodes = new Set(
        targetLinks.flatMap((l) => [l.source, l.target]),
      );

      linkPaths
        .style("opacity", (d) =>
          targetSet.has(d) ? 1 : this.constructor.HOVER_OPACITY,
        )
        .style("filter", (d) =>
          targetSet.has(d) ? this.constructor.HOVER_FILTER : "none",
        );

      nodeGroups.style("opacity", (d) =>
        connectedNodes.has(d) ? 1 : this.constructor.HOVER_OPACITY,
      );

      // Show labels for connected nodes (even if normally hidden)
      nodeGroups
        .selectAll("text")
        .style("opacity", (d) =>
          connectedNodes.has(d)
            ? 1
            : hiddenLabels.has(d.index)
              ? 0
              : this.constructor.HOVER_OPACITY,
        );
    };

    const resetHover = () => {
      linkPaths.style("opacity", 1).style("filter", "none");
      nodeGroups.style("opacity", 1);
      // Restore hidden labels to hidden state
      nodeGroups
        .selectAll("text")
        .style("opacity", (d) => (hiddenLabels.has(d.index) ? 0 : 1));
    };

    linkPaths
      .on("mouseenter", (event, d) => {
        applyHover([d]);
        // A link is a flow between two named nodes — without the names the
        // value floats context-free (the old tooltip showed only "$X (Y%)").
        this.#showTooltip(
          event,
          d.value,
          d.percentage,
          this.#tooltipContext(
            `${this.#esc(d.source.name)} → ${this.#esc(d.target.name)}`,
          ),
        );
      })
      .on("mousemove", (event) => this.#updateTooltipPosition(event))
      .on("mouseleave", () => {
        resetHover();
        this.#hideTooltip();
      });

    // One focus target per node; its bar and label share the same action.
    nodeGroups
      .attr("data-node-id", (d) => d.id)
      .attr("tabindex", (d) => (this.#nodeAction(d) ? 0 : null))
      .attr("role", (d) => this.#nodeAction(d))
      .attr("aria-label", (d) => `${d.name}, ${this.#formatCurrency(d.value)}`)
      .style("cursor", (d) => (this.#nodeAction(d) ? "pointer" : "default"))
      .on("click", (event, d) => {
        event.stopPropagation();
        this.#activateNode(d);
      })
      .on("keydown", (event, d) => {
        if (!["Enter", " "].includes(event.key) || !this.#nodeAction(d)) return;
        event.preventDefault();
        event.stopPropagation();
        this.#activateNode(d);
      })
      .on("focus", (event, d) => {
        applyHover(
          sankeyData.links.filter((l) => l.source === d || l.target === d),
        );
      })
      .on("blur", resetHover)
      .on("mouseenter", (event, d) => {
        applyHover(
          sankeyData.links.filter((l) => l.source === d || l.target === d),
        );
        this.#showTooltip(
          event,
          d.value,
          d.percentage,
          this.#tooltipContext(this.#esc(d.name)),
        );
      })
      .on("mousemove", (event) => this.#updateTooltipPosition(event))
      .on("mouseleave", () => {
        resetHover();
        this.#hideTooltip();
      });
    nodeGroups.selectAll("text").style("cursor", "inherit");

    if (this.focusAfterDraw) {
      nodeGroups
        .filter((d) => d.id === this.focusAfterDraw)
        .node()
        ?.focus();
      this.focusAfterDraw = null;
    }
  }

  // Tooltip methods

  #createTooltip() {
    const dialog = this.element.closest("dialog");
    this.tooltip = d3
      .select(dialog || document.body)
      .append("div")
      // Shared visual contract + this chart's positioning class; opacity is
      // toggled via inline style below.
      .attr("class", `${CHART_TOOLTIP_CLASSES} top-0 ph-no-capture`)
      .style("opacity", 0)
      .style("pointer-events", "none");
  }

  // Node names are user-named categories; escape anything interpolated into
  // .html() (the previous code injected them raw).
  #esc(s) {
    return String(s).replace(
      /[&<>"']/g,
      (c) =>
        ({
          "&": "&amp;",
          "<": "&lt;",
          ">": "&gt;",
          '"': "&quot;",
          "'": "&#39;",
        })[c],
    );
  }

  // Context line shared by node and link tooltips: the (escaped) name(s) of
  // what's hovered. No color swatch — the hover highlight on the diagram
  // itself already says which ribbon the card belongs to.
  #tooltipContext(label) {
    // max-w-64 gives truncate a constraint to fire against — an absolute
    // tooltip otherwise grows to fit and never ellipsizes deep flows.
    return `<div class="max-w-64 text-xs text-secondary mb-1 truncate">${label}</div>`;
  }

  #showTooltip(event, value, percentage, contextHtml = null) {
    if (!this.tooltip) this.#createTooltip();

    const valueLine = `<span class="font-medium tabular-nums">${this.#formatCurrency(value)}</span> <span class="text-secondary">(${percentage || 0}%)</span>`;
    const content = contextHtml
      ? `${contextHtml}<div>${valueLine}</div>`
      : valueLine;

    const isInDialog = !!this.element.closest("dialog");
    const x = isInDialog ? event.clientX : event.pageX;
    const y = isInDialog ? event.clientY : event.pageY;

    this.tooltip
      .html(content)
      .style("position", isInDialog ? "fixed" : "absolute")
      .style("left", `${x + 10}px`)
      .style("top", `${y - 10}px`)
      .transition()
      .duration(100)
      .style("opacity", 1);
  }

  #updateTooltipPosition(event) {
    if (this.tooltip) {
      const isInDialog = !!this.element.closest("dialog");
      const x = isInDialog ? event.clientX : event.pageX;
      const y = isInDialog ? event.clientY : event.pageY;

      this.tooltip?.style("left", `${x + 10}px`).style("top", `${y - 10}px`);
    }
  }

  #hideTooltip() {
    if (this.tooltip) {
      this.tooltip
        ?.transition()
        .duration(100)
        .style("opacity", 0)
        .style("pointer-events", "none");
    }
  }

  #formatCurrency(value) {
    return formatCashFlowCurrency(value, this.currencyValue);
  }
}