From aeaa468ca14c22549dd6302dbbaba20ce606fde4 Mon Sep 17 00:00:00 2001 From: Codex Date: Sat, 5 Dec 2026 00:48:52 +0000 Subject: [PATCH] Refine Context Metrics chart and controls layout --- .../Browser/context-metrics-acceptance.cjs | 2 +- PlotLine.Tests/Browser/context-metrics.cjs | 74 ++++++-- PlotLine/Views/Writing/_ContextMetrics.cshtml | 10 +- PlotLine/wwwroot/css/context-metrics.css | 93 ++++++++- PlotLine/wwwroot/js/context-metrics.js | 179 +++++++++++++++--- 5 files changed, 310 insertions(+), 48 deletions(-) diff --git a/PlotLine.Tests/Browser/context-metrics-acceptance.cjs b/PlotLine.Tests/Browser/context-metrics-acceptance.cjs index 032539eb..a87566d7 100644 --- a/PlotLine.Tests/Browser/context-metrics-acceptance.cjs +++ b/PlotLine.Tests/Browser/context-metrics-acceptance.cjs @@ -42,7 +42,7 @@ let session,stage='login'; await page.waitForFunction(id=>Number(document.querySelector(`[data-metric-row="${id}"] input`).dataset.savedValue)>1,metricId); const saved=Number(await row().locator('input').getAttribute('data-saved-value')); stage='narrow layout';await page.setViewportSize({width:580,height:1000}); - const layout=await page.locator('[data-context-pane="0"] .context-metrics-panels').evaluate(el=>{const [a,b]=el.children;return {stacked:b.getBoundingClientRect().top>=a.getBoundingClientRect().bottom,overflow:el.scrollWidth>el.clientWidth+2};}); + const layout=await page.locator('[data-context-pane="0"] .context-metrics-panels').evaluate(el=>{const a=el.querySelector('.context-metrics-curve'),b=el.querySelector('.context-metrics-controls');return {stacked:b.getBoundingClientRect().top>=a.getBoundingClientRect().bottom,overflow:el.scrollWidth>el.clientWidth+2};}); assert(layout.stacked&&!layout.overflow); await page.setViewportSize({width:1440,height:1000}); stage='split panes';await page.locator('[data-context-layout]').selectOption('columns');await page.locator('[data-context-pane="1"] [data-context-tab]').selectOption('metrics'); diff --git a/PlotLine.Tests/Browser/context-metrics.cjs b/PlotLine.Tests/Browser/context-metrics.cjs index d053b336..bca306e5 100644 --- a/PlotLine.Tests/Browser/context-metrics.cjs +++ b/PlotLine.Tests/Browser/context-metrics.cjs @@ -1,11 +1,12 @@ // Focused interaction/race checks; live persistence is tested separately in Development. const {chromium}=require('playwright'); const fs=require('node:fs'); +const path=require('node:path'); const assert=require('node:assert/strict'); (async()=>{ const browser=await chromium.launch({headless:true}); try { - const page=await browser.newPage(); let reject=false; const writes=[]; + const page=await browser.newPage({viewport:{width:1200,height:760}}); let reject=false; const writes=[]; await page.route('http://metrics.test/**',route=>{ if(route.request().method()==='POST'){ const body=route.request().postDataJSON(); writes.push(body); @@ -14,31 +15,80 @@ const assert=require('node:assert/strict'); return route.fulfill({contentType:'text/html',body:'
'}); }); await page.goto('http://metrics.test'); - await page.evaluate(()=>{window.Chart=class{constructor(c,config){window.chartConfig=config;}update(){}destroy(){window.destroyed=true;}};window.guards=[];document.addEventListener('context-panel-state',e=>guards.push(e.detail));}); + const errors=[]; + page.on('pageerror', error=>errors.push(error.message)); + await page.addScriptTag({path:path.join(path.dirname(require.resolve('chart.js')), 'chart.umd.js')}); + await page.addStyleTag({content:'*{box-sizing:border-box}'+['context-workspace','context-metrics'].map(file=> + fs.readFileSync(`PlotLine/wwwroot/css/${file}.css`,'utf8')).join('\n')}); for(const file of ['metric-curves','context-metrics'])await page.addScriptTag({content:fs.readFileSync(`PlotLine/wwwroot/js/${file}.js`,'utf8')}); await page.evaluate(()=>{ - document.querySelector('main').innerHTML=`

`; - PlotDirectorContextLifecycles.metrics.mount(document.querySelector('main>div')); + const root=document.querySelector('main'); + root.dataset.contextWorkspace=''; + root.className='context-workspace'; + root.style.height='720px'; + const metric='

'; + const pane=hidden=>`
${metric}
`; + root.innerHTML=`
${pane(false)}
${pane(true)}
`; + window.metrics=[...root.querySelectorAll('[data-context-metrics]')]; + window.mountMetric=i=>PlotDirectorContextLifecycles.metrics.mount(metrics[i],{paneId:i,windowId:'fixture'}); + window.chart=()=>Chart.getChart(metrics[0].querySelector('canvas')); + mountMetric(0); }); - assert.deepEqual(await page.evaluate(()=>chartConfig.data.datasets[0].data.map(p=>p.y)),[0,null]); - const input=page.locator('[type=range]'); + const divider=page.locator('.context-metrics-divider').first(); + assert.equal(await divider.getAttribute('aria-valuenow'),'75'); + await page.waitForFunction(()=>chart().height>400); + const firstHeight=await page.locator('canvas').first().evaluate(el=>el.clientHeight); + await page.evaluate(()=>{document.querySelector('[data-layout]').dataset.layout='columns';metrics[1].closest('section.context-pane').hidden=false;mountMetric(1);}); + assert.equal(await divider.isVisible(),false); + await page.evaluate(()=>document.querySelector('[data-layout]').dataset.layout='rows'); + assert.equal(await divider.isVisible(),true); + await page.waitForFunction(height=>chart().height{PlotDirectorContextLifecycles.metrics.dispose(metrics[0]);mountMetric(0);}); + assert.equal(await divider.getAttribute('aria-valuenow'),split); + await divider.dblclick(); + assert.equal(await divider.getAttribute('aria-valuenow'),'75'); + + assert.deepEqual(await page.evaluate(()=>chart().data.datasets[0].data.map(p=>p.y)),[0,null]); + assert.deepEqual(await page.evaluate(()=>[chart().scales.y.min,chart().scales.y.max]),[1,10]); + await page.waitForFunction(()=>chart().width===chart().canvas.parentElement.clientWidth); + const hit=await page.evaluate(()=>{ + const chartInstance=chart(), box=chartInstance.canvas.getBoundingClientRect(); + const {left,top,width,height}=chartInstance.legend.legendHitBoxes[0]; + return {x:box.x+left+width/2,y:box.y+top+height/2}; + }); + await page.mouse.click(hit.x,hit.y); + await page.waitForFunction(()=>!chart().isDatasetVisible(0)); + await page.evaluate(()=>{PlotDirectorContextLifecycles.metrics.dispose(metrics[0]);mountMetric(0);}); + assert.equal(await page.evaluate(()=>chart().isDatasetVisible(0)),false); + await page.mouse.click(hit.x,hit.y); + await page.waitForFunction(()=>chart().isDatasetVisible(0)); + const input=page.locator('[type=range]').first(); await input.focus(); await page.keyboard.press('ArrowRight'); await page.waitForFunction(()=>document.querySelector('[data-metrics-status]').textContent==='Saved'); assert.equal(writes[0].value,1); assert.equal(writes[0].sceneID,2); reject=true; await input.focus();await page.keyboard.press('ArrowRight'); await page.waitForFunction(()=>document.querySelector('[data-metrics-error]').textContent==='Save rejected'); - assert.equal(await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.canRefresh(document.querySelector('main>div'))),false); - await page.locator('[data-metrics-cancel]').click(); + assert.equal(await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.canRefresh(metrics[0])),false); + await page.locator('[data-metrics-cancel]').first().click(); assert.equal(await input.inputValue(),'1'); - assert.equal(await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.canRefresh(document.querySelector('main>div'))),true); + assert.equal(await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.canRefresh(metrics[0])),true); // A pointer commit on the minimum must record zero even if the range value did not change. reject=false; await input.evaluate(el=>{el.value='0';el.dispatchEvent(new PointerEvent('pointerdown',{bubbles:true}));document.dispatchEvent(new PointerEvent('pointerup'));}); await page.waitForFunction(()=>document.querySelector('[data-metrics-status]').textContent==='Saved'); assert.equal(writes.at(-1).value,0); - await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.dispose(document.querySelector('main>div'))); - assert.equal(await page.evaluate(()=>destroyed),true); - console.log('PASS Context metric zero/unset, keyboard and pointer commit, failed save guard/discard and disposal'); + await page.evaluate(()=>PlotDirectorContextLifecycles.metrics.dispose(metrics[0])); + assert.equal(await page.evaluate(()=>chart()),undefined); + assert.deepEqual(errors,[]); + console.log('PASS Context Metrics layouts, divider and legend persistence, fixed axis, zero/unset, keyboard and pointer commits, failed save recovery and disposal'); }finally{await browser.close();} })().catch(e=>{console.error(e);process.exitCode=1;}); diff --git a/PlotLine/Views/Writing/_ContextMetrics.cshtml b/PlotLine/Views/Writing/_ContextMetrics.cshtml index 67ed3865..77fea088 100644 --- a/PlotLine/Views/Writing/_ContextMetrics.cshtml +++ b/PlotLine/Views/Writing/_ContextMetrics.cshtml @@ -12,23 +12,23 @@

Metrics · @scope.Label

-

Current scene and up to five scenes either side in manuscript order. Unset values are gaps. Adjust a slider to preview; release or finish a keyboard adjustment to save.

@if (!timeline.MetricGraphs.Any()) {

No active metrics are enabled for this project.

} else {

Timeline curves

+

Current scene

@foreach(var metric in timeline.MetricGraphs) { var value=metric.Points.FirstOrDefault(p=>p.SceneID==scope.SceneID)?.Value; -
-

- +

+ diff --git a/PlotLine/wwwroot/css/context-metrics.css b/PlotLine/wwwroot/css/context-metrics.css index 81b12b0b..35ff58b2 100644 --- a/PlotLine/wwwroot/css/context-metrics.css +++ b/PlotLine/wwwroot/css/context-metrics.css @@ -1,8 +1,85 @@ -.context-metrics-panels{display:flex;gap:1rem;align-items:stretch;flex-wrap:wrap} -.context-metrics-curve,.context-metrics-controls{border:1px solid var(--bs-border-color);border-radius:.4rem;padding:.75rem;overflow:auto;resize:both;min-width:250px;max-width:100%;min-height:240px} -.context-metrics-curve{flex:2 1 auto;width:60%}.context-metrics-controls{flex:1 1 auto;width:30%} -.context-metrics-canvas{position:relative;height:280px;min-width:230px} -.context-metric-control{display:grid;grid-template-columns:1fr auto;gap:.3rem;margin-bottom:.75rem} -.context-metric-control input{grid-column:1/-1;width:100%;accent-color:var(--metric-colour)} -.context-metric-control output{font-variant-numeric:tabular-nums}.context-metric-control small{grid-column:1/-1;color:var(--bs-secondary-color)} -@media(max-width:650px){.context-metrics-curve,.context-metrics-controls{width:100%;min-width:0;flex-basis:100%;resize:vertical}} +[data-context-metrics] { + display: flex; + flex-direction: column; + height: 100%; +} +.context-metrics-panels { + --metrics-divider-size: .75rem; + --metrics-graph-min: 15rem; + --metrics-controls-min: 15rem; + display: grid; + grid-template-columns: clamp(var(--metrics-graph-min), calc(var(--metrics-graph-width, 75%) - var(--metrics-divider-size) / 2), calc(100% - var(--metrics-controls-min) - var(--metrics-divider-size))) var(--metrics-divider-size) minmax(0, 1fr); + grid-template-rows: minmax(0, 1fr); + flex: 1; + min-height: 11rem; +} +.context-metrics-curve, .context-metrics-controls { + min-width: 0; + border: 1px solid var(--bs-border-color); + border-radius: .4rem; + padding: .5rem; +} +.context-metrics-curve { + display: flex; + flex-direction: column; +} +.context-metrics-canvas { + position: relative; + flex: 1; + min-height: 0; + overflow: hidden; +} +.context-metrics-controls { + overflow: auto; +} +.context-metrics-divider { + cursor: col-resize; + touch-action: none; + display: grid; + place-items: center; +} +.context-metrics-divider::after { + content: ""; + width: 2px; + height: 2rem; + background: var(--bs-secondary-color); +} +.context-metrics-divider:is(:hover, :focus-visible)::after { + width: 4px; + background: var(--bs-body-color); +} +.context-metric-control { + display: grid; + grid-template-columns: minmax(0, 1.15fr) minmax(3rem, 1fr) 2.7rem; + align-items: center; + gap: .4rem; + padding-block: .35rem; +} +.context-metric-control input { + width: 100%; + accent-color: var(--metric-colour); +} +.context-metric-control output { + text-align: end; + font-variant-numeric: tabular-nums; +} +.context-metrics-feedback { + margin: .25rem 0 0; +} +.context-metrics-feedback:empty { + margin: 0; +} +@container (width < 42rem) { + .context-metrics-panels { + grid-template-columns: minmax(0, 1fr); + grid-template-rows: minmax(11rem, 1fr) auto; + gap: .5rem; + min-height: auto; + } + .context-metrics-divider { + display: none; + } + .context-metrics-controls { + overflow: visible; + } +} diff --git a/PlotLine/wwwroot/js/context-metrics.js b/PlotLine/wwwroot/js/context-metrics.js index 543067e1..597cc0d1 100644 --- a/PlotLine/wwwroot/js/context-metrics.js +++ b/PlotLine/wwwroot/js/context-metrics.js @@ -1,7 +1,7 @@ (() => { 'use strict'; const instances = new WeakMap(); - function mount(node) { + function mount(node, context = {}) { if (instances.has(node)) return; const script = node.querySelector('[data-metrics-payload]'); if (!script) return; @@ -11,7 +11,13 @@ const retry = node.querySelector('[data-metrics-retry]'), cancel = node.querySelector('[data-metrics-cancel]'); const sliders = [...node.querySelectorAll('[data-metric-slider]')]; const abort = new AbortController(); - let chart, dirty = null, busy = false, alive = true, pointing = false; + const preferenceKey = `plotdirector.context.metrics.v1.${node.closest('[data-context-workspace]')?.dataset.user}.${context.windowId}.${context.paneId}`; + let preferences = {}; + try { preferences = JSON.parse(localStorage.getItem(preferenceKey)) || {}; } catch {} + const persist = () => { + try { localStorage.setItem(preferenceKey, JSON.stringify(preferences)); } catch {} + }; + let chart, hovered, focused, legendMetric, dirty = null, busy = false, alive = true, pointing = false; // Cached fragments can be remounted after a successful edit before a server refresh. for (const input of sliders) { const metric = payload.metrics.find(m => m.metricTypeId === Number(input.dataset.metricSlider)); @@ -19,15 +25,72 @@ if (input.dataset.savedValue !== '') metric.points.push({ sceneId, value: Number(input.dataset.savedValue) }); } const datasets = window.PlotDirectorMetricCurves.datasets(node, payload); - datasets.forEach(d => { d.spanGaps = false; }); + const hidden = new Set(Array.isArray(preferences.hidden) ? preferences.hidden : []); + datasets.forEach(dataset => { + dataset.spanGaps = false; + dataset.hidden = hidden.has(dataset.metricTypeId); + }); + function highlight() { + const active = legendMetric ?? Number((dirty || hovered || focused)?.dataset.metricSlider); + datasets.forEach(dataset => { + const emphasized = dataset.metricTypeId === active; + dataset.borderWidth = emphasized ? 4 : 2; + dataset.pointRadius = emphasized ? 5 : 3; + }); + chart?.update('none'); + } + const panels = node.querySelector('.context-metrics-panels'); + const divider = node.querySelector('.context-metrics-divider'); + function paintSplit() { + panels.style.setProperty('--metrics-graph-width', `${preferences.split ?? 75}%`); + const width = panels.clientWidth; + if (!width || !divider.offsetWidth) return; + const limits = getComputedStyle(panels).gridTemplateColumns.split(' ').map(parseFloat); + divider.setAttribute('aria-valuenow', String(Math.round((limits[0] + limits[1] / 2) / width * 100))); + } + function setSplit(value) { + preferences.split = Math.max(0, Math.min(100, value)); + paintSplit(); + persist(); + } + let resize; + if (divider) { + const options = { signal: abort.signal }; + let pointer; + let offset; + divider.addEventListener('pointerdown', event => { + if (event.button !== 0 || pointer != null) return; + pointer = event.pointerId; + const bounds = divider.getBoundingClientRect(); + offset = event.clientX - bounds.left - bounds.width / 2; + divider.setPointerCapture(pointer); + }, options); + divider.addEventListener('pointermove', event => { + if (event.pointerId !== pointer) return; + const bounds = panels.getBoundingClientRect(); + setSplit((event.clientX - bounds.left - offset) / bounds.width * 100); + }, options); + divider.addEventListener('lostpointercapture', () => { pointer = null; }, options); + divider.addEventListener('dblclick', () => setSplit(75), options); + divider.addEventListener('keydown', event => { + const current = Number(divider.getAttribute('aria-valuenow')); + const next = { ArrowLeft: current - 2, ArrowRight: current + 2, Home: 0, End: 100 }[event.key]; + if (next == null) return; + event.preventDefault(); + setSplit(next); + }, options); + paintSplit(); + resize = new ResizeObserver(paintSplit); + resize.observe(panels); + } const guard = () => node.dispatchEvent(new CustomEvent('context-panel-state', { bubbles: true, detail: { dirty: !!dirty, busy, deferRefresh: !!dirty || busy } })); function display(input, value, preview = false) { - const text = value == null ? 'Unset' : `${value}${preview ? ' · preview' : ''}`; + const text = value == null ? 'Unset' : String(value); input.closest('label').querySelector('output').textContent = text; - input.setAttribute('aria-valuetext', text); + input.setAttribute('aria-valuetext', preview ? `${text}, preview` : text); const dataset = datasets.find(d => d.metricTypeId === Number(input.dataset.metricSlider)); dataset.data[index].y = value; - chart?.update('none'); + highlight(); } function preview(input) { if (busy || dirty && dirty !== input) return; @@ -39,7 +102,7 @@ async function save() { if (!dirty || busy) return; const input = dirty; - busy = true; guard(); sliders.forEach(s => s.disabled = true); retry.hidden = cancel.hidden = true; + busy = true; guard(); input.setAttribute('aria-disabled', 'true'); retry.hidden = cancel.hidden = true; status.textContent = 'Saving…'; error.textContent = ''; try { const response = await fetch('/SceneMetrics/UpdateSceneMetricValue', { @@ -58,30 +121,90 @@ window.PlotDirector?.toast?.error(e.message); } finally { busy = false; - if (alive) { sliders.forEach(s => s.disabled = !!dirty && dirty !== s); guard(); } + if (alive) { + input.removeAttribute('aria-disabled'); + sliders.forEach(s => s.disabled = !!dirty && dirty !== s); + highlight(); + guard(); + } } } + const colour = token => getComputedStyle(node).getPropertyValue(token).trim(); if (window.Chart) { + const axes = { color: colour('--bs-body-color') }; + const grid = { color: colour('--bs-border-color') }; chart = new Chart(node.querySelector('canvas'), { type: 'line', data: { datasets }, options: { responsive: true, maintainAspectRatio: false, animation: false, - scales: { x: { type: 'linear', min: 0, max: payload.scenes.length, ticks: { stepSize: .5, callback: v => payload.scenes[v - .5]?.axisLabel || '' } }, - y: { min: Math.min(1, ...payload.metrics.map(m => m.minValue)), max: Math.max(10, ...payload.metrics.map(m => m.maxValue)), ticks: { stepSize: 1 } } }, - plugins: { tooltip: { callbacks: { title: items => payload.scenes[Math.floor(items[0].parsed.x)]?.sceneTitle || '' } } } + scales: { + x: { type: 'linear', min: 0, max: payload.scenes.length, grid, + ticks: { ...axes, stepSize: .5, callback: v => payload.scenes[v - .5]?.axisLabel || '', + font: tick => tick.tick?.value === index + .5 ? { weight: 'bold' } : {} } }, + y: { min: 1, max: 10, grid, ticks: { ...axes, stepSize: 1 } } + }, + plugins: { + legend: { + labels: { ...axes, boxWidth: 14 }, + onClick(event, item) { + const dataset = datasets[item.datasetIndex]; + dataset.hidden = !dataset.hidden; + if (dataset.hidden) hidden.add(dataset.metricTypeId); + else hidden.delete(dataset.metricTypeId); + preferences.hidden = [...hidden]; + persist(); + highlight(); + }, + onHover(event, item) { + legendMetric = datasets[item.datasetIndex].metricTypeId; + highlight(); + }, + onLeave() { legendMetric = undefined; highlight(); } + }, + tooltip: { callbacks: { title: items => payload.scenes[Math.floor(items[0].parsed.x)]?.sceneTitle || '' } } + } }, plugins: [{ id: 'contextCurrentScene', beforeDatasetsDraw(c) { - const {ctx, chartArea, scales} = c; - ctx.save(); ctx.fillStyle = getComputedStyle(node).getPropertyValue('--pd-data-1').trim() || '#2f6f63'; ctx.globalAlpha = .12; - ctx.fillRect(scales.x.getPixelForValue(index), chartArea.top, scales.x.getPixelForValue(index + 1) - scales.x.getPixelForValue(index), chartArea.height); ctx.restore(); + if (index < 0) return; + const { ctx, chartArea, scales } = c; + const left = scales.x.getPixelForValue(index); + const width = scales.x.getPixelForValue(index + 1) - left; + ctx.save(); + ctx.fillStyle = colour('--bs-body-color'); + ctx.globalAlpha = .16; + ctx.fillRect(left, chartArea.top, width, chartArea.height); + ctx.globalAlpha = .75; + ctx.fillRect(left, chartArea.bottom - 3, width, 3); + ctx.restore(); } }] }); } else error.textContent = 'Chart unavailable. Saved metric controls remain available.'; sliders.forEach((input, i) => { - input.closest('label').style.setProperty('--metric-colour', window.PlotDirectorMetricCurves.colour(node, i)); - input.addEventListener('pointerdown', () => { pointing = true; preview(input); }, { signal: abort.signal }); - input.addEventListener('input', () => preview(input), { signal: abort.signal }); - input.addEventListener('change', () => { if (!pointing) void save(); }, { signal: abort.signal }); - input.addEventListener('blur', () => { if (!pointing && dirty === input) void save(); }, { signal: abort.signal }); + const row = input.closest('label'); + const options = { signal: abort.signal }; + row.style.setProperty('--metric-colour', window.PlotDirectorMetricCurves.colour(node, i)); + row.addEventListener('pointerenter', () => { hovered = input; highlight(); }, options); + row.addEventListener('pointerleave', () => { hovered = undefined; highlight(); }, options); + input.addEventListener('focus', () => { focused = input; highlight(); }, options); + input.addEventListener('pointerdown', event => { + if (busy) { event.preventDefault(); return; } + pointing = true; + preview(input); + }, options); + input.addEventListener('keydown', event => { + if (busy && event.key !== 'Tab') event.preventDefault(); + if (!busy && event.key === 'Home' && input.dataset.savedValue === '' && input.value === input.min) { + event.preventDefault(); + preview(input); + void save(); + } + }, options); + input.addEventListener('input', () => preview(input), options); + input.addEventListener('change', () => { if (!pointing) void save(); }, options); + input.addEventListener('blur', () => { + focused = undefined; + highlight(); + if (!pointing && dirty === input && retry.hidden) void save(); + }, options); }); document.addEventListener('pointerup', () => { if (pointing) { pointing = false; void save(); } }, { signal: abort.signal }); document.addEventListener('pointercancel', () => { pointing = false; }, { signal: abort.signal }); @@ -90,11 +213,23 @@ if (!dirty || busy) return; const input = dirty, value = input.dataset.savedValue === '' ? null : Number(input.dataset.savedValue); input.value = value ?? input.min; display(input, value); dirty = null; - sliders.forEach(s => s.disabled = false); retry.hidden = cancel.hidden = true; error.textContent = ''; status.textContent = ''; guard(); + sliders.forEach(s => s.disabled = false); retry.hidden = cancel.hidden = true; error.textContent = ''; status.textContent = ''; highlight(); guard(); }, { signal: abort.signal }); - const theme = new MutationObserver(() => { datasets.forEach((d, i) => { d.borderColor = d.backgroundColor = d.pointBackgroundColor = window.PlotDirectorMetricCurves.colour(node, i); }); chart?.update('none'); }); + const theme = new MutationObserver(() => { + datasets.forEach((dataset, i) => { + const metricColour = window.PlotDirectorMetricCurves.colour(node, i); + dataset.borderColor = dataset.backgroundColor = dataset.pointBackgroundColor = metricColour; + sliders[i].closest('label').style.setProperty('--metric-colour', metricColour); + }); + if (chart) { + chart.options.scales.x.ticks.color = chart.options.scales.y.ticks.color = + chart.options.plugins.legend.labels.color = colour('--bs-body-color'); + chart.options.scales.x.grid.color = chart.options.scales.y.grid.color = colour('--bs-border-color'); + chart.update('none'); + } + }); theme.observe(document.documentElement, {attributes: true, attributeFilter: ['data-theme', 'data-bs-theme', 'data-app-theme']}); - instances.set(node, { guarded: () => !!dirty || busy, dispose() { alive = false; abort.abort(); theme.disconnect(); chart?.destroy(); } }); + instances.set(node, { guarded: () => !!dirty || busy, dispose() { alive = false; abort.abort(); theme.disconnect(); resize?.disconnect(); chart?.destroy(); } }); } window.PlotDirectorContextLifecycles = { ...(window.PlotDirectorContextLifecycles || {}), metrics: { mount, canRefresh: node => !instances.get(node)?.guarded(),