Merge rc187-live-fe (layout C): image and model across the middle, checks over small square shell plots on the right, narrow windows flow with the plots below

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UqXYdJDrM65gxsCn2PrbfK
This commit is contained in:
leonarski_fandClaude Opus 5.5 committed 2026-11-14 08:51:23 +01:00
commit 66c3d6ea89
6 files changed
+213 -70

No files matched your search

@@ -11,7 +11,7 @@ import {livePalette} from "../livePalette";
// rejected (red) as bands over both panels, each with the reason it saw; serial: the indexing rate. The
// second panel is empty until there is a merge.
const PLOT_MARGIN = {t: 6, b: 22, l: 42, r: 42};
const PLOT_MARGIN = {t: 6, b: 26, l: 46, r: 46};
// Points of one receiver plot, polled while the run is on; coarser bins on a long serial collection
function useCollectionPlot(type: plot_type, s: rugnux_live_status) {
@@ -31,8 +31,8 @@ function Empty({text}: { text: string }) {
function RugnuxCollectionPlots({s, height}: { s: rugnux_live_status, height: number }) {
const theme = useTheme();
const pal = livePalette(theme.palette.mode);
// type that grows with the strip, so a 4k screen does not get 11 px labels
const size = Math.round(Math.min(16, Math.max(10, height / 15)));
// type that grows with the strip, so a 4k screen does not get 11 px labels, within the margins' room
const size = Math.round(Math.min(13, Math.max(10, height / 15)));
const font = {color: theme.palette.text.secondary, size};
const axis = {gridcolor: pal.grid, zerolinecolor: pal.grid, tickfont: {size: size - 1}};
const title = (text: string, color: string) => ({text, standoff: 4, font: {size: size - 1, color}});
+2 -2
View File
@@ -157,7 +157,7 @@ function ModelTile({s, modelLoaded}: { s: rugnux_live_status, modelLoaded: boole
}
// column: the tiles as a rail, top to bottom, sharing the rail's height (two or three to a row on a phone,
// where the rail is the width of the screen)
// where the rail is the width of the screen); else a row of tiles, five to a row, ten on a wide screen
// givenCell: the unit cell the collection was started with, if any
function RugnuxHero({s, modelLoaded, givenCell, column}:
{ s: rugnux_live_status, modelLoaded: boolean, givenCell?: string, column?: boolean }) {
@@ -176,7 +176,7 @@ function RugnuxHero({s, modelLoaded, givenCell, column}:
<Box sx={{display: "grid", gap: 1, minHeight: 0, ...(column
? {gridTemplateColumns: {xs: "repeat(2, minmax(0, 1fr))", sm: "repeat(3, minmax(0, 1fr))", md: "1fr"}, gridAutoRows: {md: "minmax(0, 1fr)"}, flexGrow: 1,
"& > *": {display: "flex", flexDirection: "column", justifyContent: "center"}}
: {gridTemplateColumns: {xs: "repeat(3, minmax(0, 1fr))", md: "repeat(10, minmax(0, 1fr))"}})}}>
: {gridTemplateColumns: {xs: "repeat(3, minmax(0, 1fr))", sm: "repeat(5, minmax(0, 1fr))", xl: "repeat(10, minmax(0, 1fr))"}})}}>
<Tile value={num(o.fit ?? o.d_min, x => `${x.toFixed(2)} Å`)} caption="Resolution" tone={pending}
tip={o.fit !== undefined
? `Where the CC½ fall-off is fitted: the resolution to quote. The reflections are written to ${o.d_min?.toFixed(2)} Å, a shell beyond, on purpose.`
+132 -55
View File
@@ -25,13 +25,15 @@ import ExpandMoreIcon from "@mui/icons-material/ExpandMore";
import ClearAllIcon from "@mui/icons-material/ClearAll";
import {lazy, Suspense, useEffect, useRef, useState} from "react";
// The live page as one control-room screen, in the app's own light or dark: a stage the height of the window,
// edged in the colour of the run's phase, that shows everything at once - images, structure, statistics.
// The live page as one control-room screen, in the app's own light or dark: on a wide window a stage the height
// of the window, edged in the colour of the run's phase, that shows everything at once - images, structure,
// statistics; in a narrower one the same pieces flow down the page (FlowDashboard).
// Across the top, the phase, the two progress bars (the detector's and rugnux's) and the clock the run is
// judged by. Below, left to right: the hero numbers of the merge as a rail, the diffraction image the broker
// is on, the placed model in Mol* (the run's step until there is one), and the triage badges over the merging
// statistics by shell. Under the image and the model, the collection image by image: spots and background,
// and the per-image scale with the frames the merge left out. Everything else - the timeline, step notes,
// is on, the placed model in Mol* (the run's step until there is one), and the triage badges over the merge by
// resolution shell - completeness and CC1/2, small and square. Under the image and the model, the collection
// image by image: spots and background, and the per-image scale with the frames the merge left out. Everything
// else - the timeline, step notes,
// summary rows, warnings, the serial pre-pass geometry - sits under a "Details" fold below the stage, and the
// settings under that.
@@ -183,76 +185,102 @@ function Centre({s, pal}: { s: rugnux_live_status, pal: LivePalette }) {
return <Division sx={{flexGrow: 1}} label="Run"><RunConsole s={s} pal={pal}/></Division>;
}
// Height of an element in px, kept up to date as the page resizes: the plots need theirs in pixels.
function useHeight() {
// Size of an element in px, kept up to date as the page resizes: the plots need theirs in pixels.
function useSize() {
const ref = useRef<HTMLDivElement>(null);
const [height, setHeight] = useState(0);
const [size, setSize] = useState({width: 0, height: 0});
useEffect(() => {
if (!ref.current)
return;
const observer = new ResizeObserver(entries => setHeight(entries[0].contentRect.height));
const observer = new ResizeObserver(entries => setSize({width: entries[0].contentRect.width, height: entries[0].contentRect.height}));
observer.observe(ref.current);
return () => observer.disconnect();
}, []);
return [ref, height] as const;
return [ref, size.width, size.height] as const;
}
// The height of the collection strip and the side of the image window, from the window's height so the
// stage holds everything without scrolling: the image takes what the header and the strip leave.
const STRIP = "clamp(150px, 11vh, 260px)";
const IMAGE = "clamp(240px, min(calc(88vh - 430px), 30vw), 1500px)";
const RAIL = "clamp(200px, 12vw, 420px)";
// The checks: what the pathology checklist made of the merge, a failed run's message, or what is still to come
function Checks({s, pal}: { s: rugnux_live_status, pal: LivePalette }) {
if (s.triage && s.triage.length > 0)
return <RugnuxTriage items={s.triage}/>;
if (s.state === "Failed")
return <Typography sx={{color: pal.serious, fontWeight: 600}}>{s.message}</Typography>;
return <Later text={s.stills ? "checks after the first merge" : "checks after the run"}/>;
}
function Dashboard({s, name, givenCell, deadline_s, modelLoaded, measuring, pal}:
{ s: rugnux_live_status, name?: string, givenCell?: string, deadline_s: number, modelLoaded: boolean,
measuring: boolean, pal: LivePalette }) {
// Only on the fixed-height stage (xl) do the plots take their height from their box; below it the
// stage flows and the boxes take their height from the plots, so a measured height would feed back.
const stage = useMediaQuery(useTheme().breakpoints.up("xl"));
const [plotsRef, plotsHeight] = useHeight();
const [stripRef, stripHeight] = useHeight();
const later = s.stills ? "after the first merge" : "after scaling";
// Spots and predictions are drawn on an image only where the broker analysed it: a serial run's images after
// the pre-pass. A rotation run's images are analysed by rugnux's own passes and carry neither.
const overlays = s.stills !== undefined && s.stills.images_analysed > 0;
const hairline = {borderLeft: {xl: "1px solid"}, borderColor: {xl: "divider"}, pl: {xl: 2.5}};
// row: the two plots side by side; else one above the other
function ShellPlotsOrLater({s, height, row}: { s: rugnux_live_status, height: number, row?: boolean }) {
if (!s.shells || s.shells.length === 0)
return <Later text={s.stills ? "after the first merge" : "after scaling"}/>;
return <RugnuxShellPlots shells={s.shells} d_min={s.overall?.d_min ?? s.d_min} fit={s.resolution_fit} row={row} height={height}/>;
}
// The right panel: the checks, and under them the shell plots, small and square, one above the other
// (side: their side in px; sx: how the plots' division takes its height - on the stage, what the checks leave)
function RightPanel({s, pal, side, sx}: { s: rugnux_live_status, pal: LivePalette, side: number, sx?: object }) {
return (
<>
<Box sx={{flex: "0 1 auto", maxHeight: "40%", overflowY: "auto", display: "flex", "& > *": {flexShrink: 0}}}>
<Checks s={s} pal={pal}/>
</Box>
<Division label={<>By resolution{s.stills && s.shells_merge && ` · ${s.shells_merge}`}</>} sx={sx}>
<Box sx={{display: "flex", flexGrow: 1, minHeight: 0}}>
<Box sx={{width: side, maxWidth: "100%"}}><ShellPlotsOrLater s={s} height={side}/></Box>
</Box>
</Division>
</>
);
}
type DashboardProps = { s: rugnux_live_status, name?: string, givenCell?: string, deadline_s: number, modelLoaded: boolean,
measuring: boolean, pal: LivePalette };
// Spots and predictions are drawn on an image only where the broker analysed it: a serial run's images after
// the pre-pass. A rotation run's images are analysed by rugnux's own passes and carry neither.
const overlaysOn = (s: rugnux_live_status) => s.stills !== undefined && s.stills.images_analysed > 0;
// The height of the collection strip along the bottom and the width of the rail and the right panel, from the
// window so the stage holds everything without scrolling: the image and the model take what is left.
const STRIP = "clamp(150px, 14vh, 260px)";
const RAIL = "clamp(200px, 12vw, 420px)";
const RIGHT = "clamp(220px, 15vw, 360px)";
const AXIS_TITLE = 18; // what the lower of two stacked shell plots adds for the axis title (RugnuxShellPlots)
// The stage of a wide window (xl): the height of the window, nothing scrolls.
function StageDashboard({s, name, givenCell, deadline_s, modelLoaded, measuring, pal}: DashboardProps) {
const [stripRef, , stripHeight] = useSize();
const [imageRef, , imageHeight] = useSize();
const [rightRef, rightWidth, rightHeight] = useSize();
// the shell plots, square, one above the other in the right panel: as large as its width or height allows
const side = Math.max(120, Math.min(rightWidth, (rightHeight - AXIS_TITLE) / 2));
const hairline = {borderLeft: "1px solid", borderColor: "divider", pl: 2.5};
return (
<Box sx={{display: "grid", gridTemplateRows: "auto minmax(0, 1fr)", gap: 2.5, height: "100%", minHeight: 0}}>
<Header s={s} name={name} deadline_s={deadline_s} measuring={measuring} pal={pal}/>
<Box sx={{display: "grid", gap: 2.5, minHeight: 0,
gridTemplateColumns: {xs: "1fr", md: `${RAIL} minmax(0, 1fr)`, xl: `${RAIL} ${IMAGE} minmax(0, 1fr) minmax(360px, 27%)`},
gridTemplateRows: {xs: "auto", xl: `minmax(0, 1fr) ${STRIP}`}}}>
<Division label="Merge" sx={{gridColumn: {xl: 1}, gridRow: {xl: "1 / 3"}}}>
<Box sx={{display: "grid", gap: 2.5, minHeight: 0, gridTemplateColumns: `${RAIL} auto minmax(0, 1fr) ${RIGHT}`,
gridTemplateRows: `minmax(0, 1fr) ${STRIP}`}}>
<Division label="Merge" sx={{gridColumn: 1, gridRow: "1 / 3"}}>
<RugnuxHero s={s} modelLoaded={modelLoaded} givenCell={givenCell} column/>
</Division>
<Division label="Image" sx={{...hairline, gridColumn: {xl: 2}, minHeight: {xs: 320, xl: 0}}}>
<RugnuxImage measuring={measuring} overlays={overlays}/>
{/* the image, square with the row's height, in a column of its own width; the model takes the rest */}
<Division label="Image" sx={{...hairline, gridColumn: 2, gridRow: 1}}>
<Box ref={imageRef} sx={{flexGrow: 1, minHeight: 0}}>
<Box sx={{width: `${imageHeight}px`}}>
<RugnuxImage measuring={measuring} overlays={overlaysOn(s)}/>
</Box>
</Box>
</Division>
{/* below the stage the model takes the whole width under the image, only as tall as Mol* needs, and
nothing when there is no model to show */}
<Box sx={{gridColumn: {md: "1 / 3", xl: 3}, minHeight: {xs: modelShown(s) ? 480 : 0, xl: 0}, display: "flex", flexDirection: "column"}}>
<Box sx={{...hairline, gridColumn: 3, gridRow: 1, minHeight: 0, display: "flex", flexDirection: "column"}}>
<Centre s={s} pal={pal}/>
</Box>
<Box sx={{display: "flex", flexDirection: "column", gap: 2.5, minHeight: 0, gridColumn: {md: "1 / 3", xl: 4}, gridRow: {xl: "1 / 3"}, ...hairline}}>
<Division sx={{flex: "0 1 auto", maxHeight: "40%", overflowY: "auto", "& > *": {flexShrink: 0}}}>
{s.triage && s.triage.length > 0 ? <RugnuxTriage items={s.triage}/>
: s.state === "Failed" ? <Typography sx={{color: pal.serious, fontWeight: 600}}>{s.message}</Typography>
: <Later text={s.stills ? "checks after the first merge" : "checks after the run"}/>}
</Division>
<Division sx={{flex: {xs: "none", xl: "1 1 0"}}} label={<>By resolution{s.stills && s.shells_merge && ` · ${s.shells_merge}`}</>}>
<Box ref={plotsRef} sx={{flexGrow: 1, minHeight: {xs: 200, xl: 0}, display: "flex"}}>
{s.shells && s.shells.length > 0
? <Box sx={{width: "100%"}}>
<RugnuxShellPlots shells={s.shells} d_min={s.overall?.d_min ?? s.d_min} fit={s.resolution_fit}
height={stage ? Math.max(150, plotsHeight / 2) : 220}/>
</Box>
: <Later text={later}/>}
</Box>
</Division>
{/* the checks over the shell plots, small and square - a point a shell */}
<Box ref={rightRef} sx={{...hairline, gridColumn: 4, gridRow: "1 / 3", minHeight: 0, display: "flex", flexDirection: "column", gap: 2.5}}>
<RightPanel s={s} pal={pal} side={side} sx={{flex: "1 1 0", minHeight: 0}}/>
</Box>
<Division label="Collection" sx={{gridColumn: {md: "1 / 3", xl: "2 / 4"}, gridRow: {xl: 2}, ...hairline, minHeight: {xs: 200, xl: 0}}}>
{/* the collection image by image along the bottom, wide - a point an image */}
<Division label="Collection" sx={{...hairline, gridColumn: "2 / 4", gridRow: 2, minHeight: 0}}>
<Box ref={stripRef} sx={{flexGrow: 1, minHeight: 0}}>
<RugnuxCollectionPlots s={s} height={stage ? Math.max(130, stripHeight) : 160}/>
<RugnuxCollectionPlots s={s} height={Math.max(130, stripHeight)}/>
</Box>
</Division>
</Box>
@@ -260,6 +288,55 @@ function Dashboard({s, name, givenCell, deadline_s, modelLoaded, measuring, pal}
);
}
// The side of the square shell plots, the height of the collection strip and the width of the right panel,
// below the stage
const FLOW_SQUARE = 240;
const FLOW_STRIP = 200;
const FLOW_RIGHT = 220;
// A narrower window (the common case: a browser beside other windows), where the page scrolls: the merge's
// numbers as a row of tiles under the header, then the image and the model side by side, as large as the width
// allows - one above the other where that would leave them under 360 px - with the right panel (the checks over
// the shell plots, small and square) beside them from 1200 px, then the collection plots, wide. Narrower than
// that, the shell plots come after the collection, with the checks beside them.
function FlowDashboard({s, name, givenCell, deadline_s, modelLoaded, measuring, pal}: DashboardProps) {
const twoUp = useMediaQuery("(min-width: 1000px)");
const wide = useMediaQuery("(min-width: 1200px)");
return (
<Stack spacing={2.5}>
<Header s={s} name={name} deadline_s={deadline_s} measuring={measuring} pal={pal}/>
<Division label="Merge"><RugnuxHero s={s} modelLoaded={modelLoaded} givenCell={givenCell}/></Division>
<Box sx={{display: "grid", gap: 2.5, alignItems: "stretch",
gridTemplateColumns: wide ? `1fr 1fr ${FLOW_RIGHT}px` : twoUp ? "1fr 1fr" : "1fr"}}>
<Division label="Image"><RugnuxImage measuring={measuring} overlays={overlaysOn(s)}/></Division>
{/* beside the image the model is as tall as the image; under it, as tall as Mol* needs */}
<Box sx={{display: "flex", flexDirection: "column", minHeight: twoUp ? 0 : modelShown(s) ? 480 : 0}}>
<Centre s={s} pal={pal}/>
</Box>
{/* the row grows to the panel where it is taller than the image: the model fills it */}
{wide && <Box sx={{display: "flex", flexDirection: "column", gap: 2.5}}>
<RightPanel s={s} pal={pal} side={FLOW_RIGHT}/>
</Box>}
</Box>
<Division label="Collection"><RugnuxCollectionPlots s={s} height={FLOW_STRIP}/></Division>
{!wide && <Box sx={{display: "grid", gap: 2.5, gridTemplateColumns: twoUp ? "auto minmax(0, 1fr)" : "1fr", alignItems: "start"}}>
<Division label={<>By resolution{s.stills && s.shells_merge && ` · ${s.shells_merge}`}</>}
sx={{width: 2 * FLOW_SQUARE + 12, maxWidth: "100%", minHeight: {xs: 120, sm: FLOW_SQUARE}}}>
<Box sx={{display: "flex", flexGrow: 1, "& > *": {width: "100%"}}}><ShellPlotsOrLater s={s} height={FLOW_SQUARE} row/></Box>
</Division>
<Division label="Checks" sx={{minHeight: 120}}>
<Box sx={{display: "flex", flexGrow: 1}}><Checks s={s} pal={pal}/></Box>
</Division>
</Box>}
</Stack>
);
}
function Dashboard(props: DashboardProps) {
const stage = useMediaQuery(useTheme().breakpoints.up("xl"));
return stage ? <StageDashboard {...props}/> : <FlowDashboard {...props}/>;
}
// What the stage leaves out, below it: the timeline, the steps with their notes, the summary rows
// and warnings, the model's scores, and the serial pre-pass geometry.
function Details({s, deadline_s}: { s: rugnux_live_status, deadline_s: number }) {
+12 -7
View File
@@ -2,9 +2,11 @@ import {useEffect, useRef, useState} from "react";
import {Box, Typography, useTheme} from "@mui/material";
import {rugnux_live_shell} from "../client";
import Plot from "./Plot";
import {livePalette} from "../livePalette";
// Completeness and CC1/2 by resolution shell, the two columns of rugnux's shell table read first, one panel each,
// one under the other on one axis: labelled once, under the lower panel. Each shell is drawn at 1/d^2 of its
// one under the other on one axis: labelled once, under the lower panel - or side by side (row), each on its own
// axis, as panels like the collection's. Each shell is drawn at 1/d^2 of its
// d_min, the axis labelled in d at round values - as many as the panel's width holds - and the resolution of the
// merge is a dashed line, named once, on the upper panel: where the CC1/2 fall-off is fitted, which the written
// range (the end of the axis) deliberately reaches a shell beyond; without a fit, the written limit itself.
@@ -49,26 +51,29 @@ function dTicks(x0: number, x1: number, widthPx: number) {
}
// height: of each panel in px; d_min: the written limit of the merge; fit: where its CC1/2 fall-off is fitted
function RugnuxShellPlots({shells, d_min, fit, merge, height = 300}:
{ shells: rugnux_live_shell[], d_min?: number, fit?: number, merge?: string, height?: number }) {
function RugnuxShellPlots({shells, d_min, fit, merge, row, height = 300}:
{ shells: rugnux_live_shell[], d_min?: number, fit?: number, merge?: string, row?: boolean, height?: number }) {
const theme = useTheme();
const grid = theme.palette.mode === "dark" ? "rgba(255,255,255,.12)" : "#eee";
const [ref, width] = useWidth();
const panelWidth = row ? (width - 12) / 2 : width;
const x = shells.map(sh => 1 / (sh.d_min * sh.d_min));
const limit = fit ?? d_min;
const cut = limit !== undefined ? 1 / (limit * limit) : undefined;
const x0 = 0;
const x1 = 1.03 * Math.max(x[x.length - 1], d_min !== undefined ? 1 / (d_min * d_min) : 0, cut ?? 0);
const ticks = dTicks(x0, x1, Math.max(width - MARGIN.l - MARGIN.r, 100));
const ticks = dTicks(x0, x1, Math.max(panelWidth - MARGIN.l - MARGIN.r, 100));
return (
<Box ref={ref}>
<Box ref={ref} sx={row ? {display: "grid", gridTemplateColumns: "1fr 1fr", gap: 1.5,
"& > *": {bgcolor: livePalette(theme.palette.mode).panel, borderRadius: 1}} : undefined}>
{merge && <Typography color="text.secondary" sx={{mb: 1}}>Merge of {merge}</Typography>}
{PANELS.map((panel, i) => {
if (!shells.some(sh => panel.value(sh) !== undefined))
return null;
const lower = i === PANELS.length - 1;
const panelHeight = lower ? height + AXIS_TITLE : height;
// the axis is named under the lower panel; side by side, under each, within the panel's height
const lower = row || i === PANELS.length - 1;
const panelHeight = lower && !row ? height + AXIS_TITLE : height;
return (
<Plot key={panel.title}
style={{width: "100%", height: panelHeight}}
@@ -12,6 +12,7 @@ import {applyModelDisplay, clearScene, getStructureAtoms, getStructureBox, Loade
import {loadMapLayer, MAP_COLORS, MapLayer, removeMapLayer, setLayerVisible} from "./structure/loadMaps";
import {FullCellMap, fullCellFromCcp4, prepareMap} from "./structure/densityCrop";
import {revealCamera} from "./structure/reveal";
import {fitCamera} from "./structure/fitCamera";
import {PEAK_MAP_RADIUS_A, viewPeak} from "./structure/peakView";
@@ -19,7 +20,8 @@ import {PEAK_MAP_RADIUS_A, viewPeak} from "./structure/peakView";
// 2mFo-DFc at 1 sigma, mFo-DFc at +-3 sigma and (where the data carry anomalous signal) the anomalous difference
// map at 4 sigma, in Mol*. Set up as aaredb's structure viewer (gitea.psi.ch/mx/aaredb, pages/StructureView.tsx
// and components/Structure/, the PSI MX group's own code): its plugin, Coot mouse controls, model presets, map
// meshes, crop and carve - on a black stage. It is not a viewer to work in: what it shows is gone with the next
// meshes, crop and carve - on a black stage, the model fitted to the panel (fitCamera.ts), and again whenever the
// panel changes shape. It is not a viewer to work in: what it shows is gone with the next
// collection, so the controls are a toggle for the difference map and arrows through the refined model's
// difference-map peaks (the blobs of the live result, highest first), in a bar over the stage. Every map is carved
// within the same radius of the atoms (aaredb carves 2Fo-Fc only); at a peak the maps are drawn uncarved within
@@ -88,6 +90,7 @@ function RugnuxStructureViewer({resultKey, anomalous, anomalousSignal, fill, pea
const [hasMap, setHasMap] = useState<Record<Kind, boolean>>({twofofc: false, fofc: false, anom: false});
// The stage stays dark until the first model and its maps are in, then fades up as the camera eases in.
const [revealed, setRevealed] = useState(false);
const stageRef = useRef<HTMLDivElement>(null);
// aaredb factory defaults (state/viewerDefaults.ts:16-23); anomalous as a difference map, +4 sigma
const SIGMA: Record<Kind, number> = {twofofc: 1.0, fofc: 3.0, anom: 4.0};
@@ -159,6 +162,7 @@ function RugnuxStructureViewer({resultKey, anomalous, anomalousSignal, fill, pea
}
if (firstScene && !abort.signal.aborted) {
await nextFrames(); // the camera reset loadModel asked for is applied on a draw
fitCamera(plugin, atoms, 0);
if (!reducedMotion())
revealCamera(plugin, REVEAL_MS);
}
@@ -176,6 +180,22 @@ function RugnuxStructureViewer({resultKey, anomalous, anomalousSignal, fill, pea
return () => abort.abort();
}, [pluginReady, resultKey, anomalous]);
// The panel changed shape: the whole model is fitted to it again (a peak keeps its own view)
useEffect(() => {
const stage = stageRef.current;
if (!stage)
return;
const observer = new ResizeObserver(() => {
const plugin = pluginRef.current;
if (plugin && sceneLoadedRef.current && peakRef.current === null) {
plugin.handleResize();
fitCamera(plugin, atomsRef.current, 0);
}
});
observer.observe(stage);
return () => observer.disconnect();
}, []);
const toggleLayer = useCallback((kind: Kind, visible: boolean) => {
setShow(s => ({...s, [kind]: visible}));
const plugin = pluginRef.current;
@@ -198,7 +218,9 @@ function RugnuxStructureViewer({resultKey, anomalous, anomalousSignal, fill, pea
// at a peak the side chains about it matter: sticks over the cartoon
applyModelDisplay(plugin, modelRefsRef.current, i === null ? REPR : 'both', false);
if (i === null) {
plugin.managers.camera.reset(undefined, reducedMotion() ? 0 : 400);
plugin.managers.camera.reset(undefined, 0);
await nextFrames(); // the reset is applied on a draw; the fit starts from it
fitCamera(plugin, atomsRef.current, reducedMotion() ? 0 : 400);
return;
}
const p = sortedRef.current[i];
@@ -270,7 +292,7 @@ function RugnuxStructureViewer({resultKey, anomalous, anomalousSignal, fill, pea
</Box>
</Tooltip>)}
</Box>
<Box sx={{position: 'relative', flexGrow: 1, minHeight: 0}}>
<Box ref={stageRef} sx={{position: 'relative', flexGrow: 1, minHeight: 0}}>
<Box sx={{position: 'absolute', inset: 0, opacity: revealed ? 1 : 0,
transition: 'opacity 900ms ease-out', '@media (prefers-reduced-motion: reduce)': {transition: 'none'}}}>
<MolstarCanvas onReady={onPluginReady}/>
@@ -0,0 +1,39 @@
import { PluginContext } from 'molstar/lib/mol-plugin/context';
import { Vec3 } from 'molstar/lib/mol-math/linear-algebra';
// The camera moved along its line of sight until the atoms fill the panel: Mol*'s own reset frames the
// structure's bounding sphere within the panel's shorter side, which leaves a compact molecule small in a
// wide or tall panel. Here the atoms' extent across and up the view is what has to fit, with a little air,
// so the model is as large as the panel lets it be, whatever the panel's shape; the view direction and the
// focus radius (the clipping) are left as they are.
const AIR = 1.08;
export function fitCamera(plugin: PluginContext, atoms: Float32Array, durationMs: number): void {
const camera = plugin.canvas3d?.camera;
if (!camera || atoms.length < 3)
return;
const s = camera.getSnapshot();
const dir = Vec3.normalize(Vec3(), Vec3.sub(Vec3(), s.position, s.target));
const up = Vec3.normalize(Vec3(), Vec3.sub(Vec3(), s.up, Vec3.scale(Vec3(), dir, Vec3.dot(s.up, dir))));
const right = Vec3.cross(Vec3(), up, dir);
const n = atoms.length / 3;
const centre = Vec3();
for (let i = 0; i < atoms.length; i += 3)
Vec3.add(centre, centre, Vec3.create(atoms[i], atoms[i + 1], atoms[i + 2]));
Vec3.scale(centre, centre, 1 / n);
let hx = 0, hy = 0, hz = 0;
const d = Vec3();
for (let i = 0; i < atoms.length; i += 3) {
Vec3.sub(d, Vec3.create(atoms[i], atoms[i + 1], atoms[i + 2]), centre);
hx = Math.max(hx, Math.abs(Vec3.dot(d, right)));
hy = Math.max(hy, Math.abs(Vec3.dot(d, up)));
hz = Math.max(hz, Math.abs(Vec3.dot(d, dir)));
}
const { width, height } = camera.viewport;
const t = Math.tan(s.fov / 2);
// the extent across the view fits the width, the one up the view the height; the nearest atoms sit hz
// in front of the centre
const distance = Math.max(hy / t, hx / (t * Math.max(width / Math.max(height, 1), 1e-3))) * AIR + hz;
camera.setState({ ...s, target: centre, position: Vec3.add(Vec3(), centre, Vec3.scale(Vec3(), dir, distance)) },
durationMs, { easing: 'cubic-out' });
}