From 50ae08855b7f2dd874cd49711dc00ec273166b7f Mon Sep 17 00:00:00 2001 From: Jonathan Berrisch Date: Sun, 18 May 2025 23:07:42 +0200 Subject: [PATCH] Move update logic out of main code --- app.qmd | 64 ++++++++++++++++++++++++--------------------------------- 1 file changed, 27 insertions(+), 37 deletions(-) diff --git a/app.qmd b/app.qmd index 420a12e..465e1b3 100644 --- a/app.qmd +++ b/app.qmd @@ -23,6 +23,32 @@ maxMu = Math.max(...muValues) ``` ```{ojs} +function updateChartInner(g, x, y, linesGroup, color, line, data) { + // Update axes with transitions + x.domain([0, d3.max(data, d => d.x)]); + g.select(".x-axis").transition().duration(1500).call(d3.axisBottom(x).ticks(10)); + y.domain([0, d3.max(data, d => d.y)]); + g.select(".y-axis").transition().duration(1500).call(d3.axisLeft(y).ticks(5)); + + // Group data by basis function + const dataByFunction = Array.from(d3.group(data, d => d.b)); + const keyFn = d => d[0]; + + // Update basis function lines + const u = linesGroup.selectAll("path").data(dataByFunction, keyFn); + u.join( + enter => enter.append("path").attr("fill","none").attr("stroke-width",3) + .attr("stroke", (_, i) => color(i)).attr("d", d => line(d[1].map(pt => ({x: pt.x, y: 0})))) + .style("opacity",0), + update => update, + exit => exit.transition().duration(1000).style("opacity",0).remove() + ) + .transition().duration(1000) + .attr("d", d => line(d[1])) + .attr("stroke", (_, i) => color(i)) + .style("opacity",1); +} + chart = { // State variables for selected parameters let selectedMu = 0.5; @@ -172,43 +198,7 @@ chart = { // Function to update the chart with new data function updateChart(data) { - // Update axes with transitions - x.domain([0, d3.max(data, d => d.x)]); - g.select(".x-axis") - .transition().duration(1500) - .call(d3.axisBottom(x).ticks(10)); - y.domain([0, d3.max(data, d => d.y)]); - g.select(".y-axis") - .transition().duration(1500) - .call(d3.axisLeft(y).ticks(5)); - - // Group data by basis function - const dataByFunction = Array.from(d3.group(data, d => d.b)); - - // Update the chart title - // svg.select(".chart-title") - // .text(`B-spline Basis Functions (${selectedKnots} knots, μ = ${selectedMu})`); - - // Create a key function to track basis functions - const keyFn = d => d[0]; - - // Update basis function lines with proper enter/update/exit pattern - const u = linesGroup.selectAll("path") - .data(dataByFunction, keyFn); - u.join( - enter => enter.append("path") - .attr("fill", "none") - .attr("stroke-width", 3) - .attr("stroke", (_, i) => color(i)) - .attr("d", d => line(d[1].map(pt => ({x: pt.x, y: 0})))) - .style("opacity", 0), - update => update, - exit => exit.transition().duration(1000).style("opacity", 0).remove() - ) - .transition().duration(1000) - .attr("d", d => line(d[1])) - .attr("stroke", (_, i) => color(i)) - .style("opacity", 1); + updateChartInner(g, x, y, linesGroup, color, line, data); } // Store the update function