Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cirro-studio/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "spatial-data-studio-cirro",
"private": true,
"version": "1.9.1",
"version": "1.10.0",
"type": "module",
"scripts": {
"dev": "vite",
Expand Down
2 changes: 1 addition & 1 deletion cirro-studio/src/app/Shell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ function ProjectPicker({ projects, loggedIn, onSettings }: { projects: CirroProj
// What read-only means here, and how to keep work for good.
function ReadOnlyBadge({ loggedIn, onSignIn }: { loggedIn: boolean; onSignIn: () => void }) {
return (
<Popover className="shell-access" label="Read-only">
<Popover className="shell-access" label={<>Read-only ▾</>}>
{() => (
<div className="menu shell-access-panel">
<p>You can look and run every analysis here. What you save stays in this browser: not on other computers, and nobody else sees it.</p>
Expand Down
4 changes: 4 additions & 0 deletions cirro-studio/src/app/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,10 @@ const sameAddress = (a: string, b: string) => {
return sorted(a) === sorted(b);
};

/** Moving to another stage, or back to the overview, leaves a stage's selection and search
* behind. */
export const LEAVING_STAGE = { [SELECT_PARAM]: null, [QUERY_PARAM]: null, [FILTER_PARAM]: null };

/** Stepping out (Esc, ×) goes back in history when the previous entry is where it leads,
* so stepping in and out doesn't pile up entries; otherwise it navigates there. */
export function stepBack(update: Record<string, string | null>) {
Expand Down
37 changes: 35 additions & 2 deletions cirro-studio/src/figures/ChartFigure.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@
// a heatmap from neighborhood enrichment, stacked bars from a composition.
import { useEffect, useRef, useState } from 'react';
import type { AsyncReadable } from '@zarrita/storage';
import { downloadBlob } from '@cirrobio/spatial-viewer';
import { Heatmap } from '../charts/Heatmap';
import { StackedBars } from '../charts/StackedBars';
import { Volcano } from '../charts/Volcano';
import { describeError } from '../cirro/session';
import { useSize } from '../lib/useSize';
import { GENE_TEST_COLUMN, matrixOf, readDataFrame, type DataFrame } from '../reports/store';
import { fileStem, pngBlob, standaloneSvg, svgBlob } from './export';
import type { ChartSpec, FigureSpec } from './spec';

const num = (df: DataFrame, column: string) => {
Expand Down Expand Up @@ -64,10 +66,41 @@ export function ChartFigure({ spec, store, table }: { spec: FigureSpec; store: R
live = false;
};
}, [store, table, resultPath, marksPath]);
const [exporting, setExporting] = useState(false);
// The chart as it is drawn here, at the width the figure was kept at. No PDF: the PDF
// writer loses the labels' halos and with them the labels, and the SVG is the vector copy.
const download = async (format: 'svg' | 'png') => {
const drawn = ref.current?.querySelector('svg');
if (!drawn) return;
setProblem(null);
setExporting(true);
try {
const svg = standaloneSvg(drawn);
const page = { widthMm: spec.width_mm, heightMm: (spec.width_mm * drawn.clientHeight) / drawn.clientWidth };
const blob = format === 'svg' ? svgBlob(svg) : await pngBlob(svg, page);
downloadBlob(blob, `${fileStem(spec.title)}.${format}`);
} catch (e) {
setProblem(describeError(e));
} finally {
setExporting(false);
}
};
return (
<div className="chart-figure" ref={ref}>
<h2>{spec.title}</h2>
{spec.caption && <p className="muted">{spec.caption}</p>}
<header className="report-head">
<div className="report-title">
<h2>{spec.title}</h2>
{spec.caption && <p className="muted">{spec.caption}</p>}
</div>
{chart && tables && (
<div className="button-row">
<span className="muted">Download</span>
{(['png', 'svg'] as const).map((f) => (
<button key={f} type="button" className="button button-small" disabled={exporting} onClick={() => void download(f)}>{f.toUpperCase()}</button>
))}
</div>
)}
</header>
{problem && <p className="notice notice-danger">{problem}</p>}
{chart && tables && width > 0 && <Chart chart={chart} df={tables.df} marks={tables.marks} width={Math.min(width, 720)} />}
</div>
Expand Down
26 changes: 25 additions & 1 deletion cirro-studio/src/figures/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,13 +38,37 @@ export function withPhys(png: Uint8Array<ArrayBuffer>, dpi: number): Uint8Array<
return out;
}

/** A figure's title as a file name, without its extension. */
export const fileStem = (title: string) => title.trim().replace(/[^A-Za-z0-9]+/g, '-').replace(/^-|-$/g, '').toLowerCase() || 'figure';

type PageSize = Pick<FigureLayout, 'widthMm' | 'heightMm'>;

// What a chart's stylesheet sets, which a file of its own has to carry itself.
const PAINT = ['fill', 'fill-opacity', 'stroke', 'stroke-width', 'stroke-dasharray', 'stroke-linejoin', 'paint-order', 'opacity', 'font-family', 'font-size', 'font-weight', 'text-anchor'];

/** A chart drawn on the page as an SVG that stands alone: the paint its stylesheet gives
* each element written onto the element. */
export function standaloneSvg(svg: SVGSVGElement): string {
const copy = svg.cloneNode(true) as SVGSVGElement;
const drawn = [svg, ...svg.querySelectorAll('*')];
const copied = [copy, ...copy.querySelectorAll('*')];
drawn.forEach((el, i) => {
const style = getComputedStyle(el);
for (const p of PAINT) copied[i].setAttribute(p, style.getPropertyValue(p));
copied[i].removeAttribute('class');
});
copy.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
copy.setAttribute('viewBox', `0 0 ${svg.clientWidth} ${svg.clientHeight}`);
return new XMLSerializer().serializeToString(copy);
}

export function svgBlob(svg: string): Blob {
return new Blob([svg], { type: 'image/svg+xml' });
}

/** Rasterise the figure at `dpi`, white background, through the browser's own SVG
* renderer (the same one that shows the preview). */
export async function pngBlob(svg: string, layout: FigureLayout, dpi = FIGURE_DPI): Promise<Blob> {
export async function pngBlob(svg: string, layout: PageSize, dpi = FIGURE_DPI): Promise<Blob> {
const width = Math.round((layout.widthMm / 25.4) * dpi);
const height = Math.round((layout.heightMm / 25.4) * dpi);
const url = URL.createObjectURL(svgBlob(svg));
Expand Down
1 change: 1 addition & 0 deletions cirro-studio/src/item/DraftBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ export function DraftBar({ wb, baseSize, datasetName }: { wb: Workbench; baseSiz
<span className="muted"> · {formatBytes(wb.draftBytes)} to save</span>
</span>
<span className="draft-list">
{wb.changes.length > 3 && <span className="muted draft-earlier">+{wb.changes.length - 3} earlier</span>}
{wb.changes.slice(-3).map((c, i) => {
const text = describeChange(c);
return <span key={i} className={`chip chip-static ${isRemoval(c) ? 'chip-removed' : ''}`} title={text}>{text}</span>;
Expand Down
15 changes: 8 additions & 7 deletions cirro-studio/src/item/Facts.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// The line above a picture: its name, what it is, how big, where it came from and what
// it was made into, whose data it is (for public data), and a way to its page in Cirro.
// The line above a picture: its name, what it is, whose data it is (for public data), where
// it came from and what it was made into. Details holds the rest: how big, when it was
// added, and a way to its page in Cirro.
import type { ReactNode } from 'react';
import type { CatalogItem } from '../data/model';
import { stageOf, type Library, type StageId } from '../app/library';
Expand Down Expand Up @@ -36,13 +37,10 @@ export function Facts({ title, item, origin, kind, stage, from, into, extra, uns
)}
<h1 className="facts-title">{title}</h1>
<span className="facts-kind"><span className="dot" /> {kind}</span>
{item.size > 0 && <span>{formatBytes(item.size)}</span>}
{dataset && <span className="muted">{dataset.processName}</span>}
{dataset?.createdAt && <span className="muted">{formatDate(dataset.createdAt)}</span>}
{credit && <span className="muted"><CreditLine credit={credit} /></span>}
{extra}
{credit && <span className="muted facts-credit"><CreditLine credit={credit} /></span>}
{from.length > 0 && <span className="facts-kin">from {from.map((k) => <KinChip key={k.item.key} kin={k} />)}</span>}
{into.length > 0 && <span className="facts-kin">made into {into.slice(0, 3).map((k) => <KinChip key={k.item.key} kin={k} />)}{into.length > 3 && <span className="muted"> +{into.length - 3}</span>}</span>}
{extra}
<span className="facts-spacer" />
{collection.access === 'write' && (
<button type="button" className="button button-small" title="Every squidpy and scanpy analysis, on a machine in this project, in a new tab"
Expand All @@ -57,6 +55,9 @@ export function Facts({ title, item, origin, kind, stage, from, into, extra, uns
{dataset?.description && <><dt>About</dt><dd>{dataset.description}</dd></>}
{source && <><dt>Saved on</dt><dd>{source.name}</dd></>}
{credit?.changes && <><dt>{source ? 'Processing of the original' : 'Processing'}</dt><dd>{credit.changes}</dd></>}
{item.size > 0 && <><dt>Size</dt><dd>{formatBytes(item.size)}</dd></>}
{dataset?.processName && <><dt>Data type</dt><dd>{dataset.processName}</dd></>}
{dataset?.createdAt && <><dt>Added</dt><dd>{formatDate(dataset.createdAt)}</dd></>}
<dt>Path</dt><dd className="mono">{item.path || '(whole dataset)'}</dd>
{dataset?.createdBy && <><dt>Made by</dt><dd>{dataset.createdBy}</dd></>}
{dataset?.folders.length ? <><dt>Folder</dt><dd>{dataset.folders.join(', ')}</dd></> : null}
Expand Down
60 changes: 28 additions & 32 deletions cirro-studio/src/item/StorePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import { refOfItem } from '../app/library';
import { OPEN_DOCS_URL } from '../app/appInfo';
import { ACROSS_PARAM, LENS_PARAM, navigate, openedStore, stepBack, TASK_PARAM, useRoute } from '../app/route';
import { useStudio } from '../app/studio';
import { formatCount, plural, RemoveButton, SettingsIcon, tint } from '../app/ui';
import { formatCount, RemoveButton, SettingsIcon, tint } from '../app/ui';
import { describeError } from '../cirro/session';
import type { StoreItem, VersionItem } from '../data/model';
import { ChartFigure } from '../figures/ChartFigure';
Expand Down Expand Up @@ -76,6 +76,10 @@ function FigureCaption({ figure, wb }: { figure: FigureSpec; wb: Workbench }) {
<p className="caption-figure">{figure.caption || figure.title}</p>
<div className="button-row">
{unsaved && <span className="chip chip-static">In the unsaved changes</span>}
{figure.view.kind === 'canvas' && (
<button type="button" className="button button-small" title="As a PNG, PDF or SVG, from Save as a figure"
onClick={() => navigate({ section: 'task', [TASK_PARAM]: 'figure' })}>Download…</button>
)}
<RemoveButton onRemove={() => void remove()} />
</div>
{problem && <p className="notice notice-danger">{problem}</p>}
Expand Down Expand Up @@ -210,20 +214,6 @@ export function StorePage({ item, entity }: { item: StoreItem | VersionItem; ent
let displayBody: ReactNode;
if (onCanvas) {
displayBody = <div className="display-settings studio-ui" ref={setSettings} />;
} else if (lens === 'composition' && displays.spatial) {
displayBody = (
<div className="display-note studio-ui">
<p className="muted">The composition counts the {unit}s in each group of what the tissue is colored by, across the groups of another column if you choose one.</p>
<ColorBySelect value={displays.spatial.encoding.color_by ?? ''} obsFields={fields!.obs} layers={fields!.layers}
hasX={fields!.has_x} onChange={(path) => updateEncoding(wb.key, 'spatial', { color_by: path })} />
<label className="field">
<span>Across</span>
<ObsFieldSelect fields={fields!.obs.filter((f) => f.kind === 'categorical')} value={across ?? ''} placeholder="The whole tissue"
onChange={(c) => navigate({ [ACROSS_PARAM]: c || null }, { replace: true })} />
</label>
{across && <button type="button" className="link-button" onClick={() => navigate({ [ACROSS_PARAM]: null }, { replace: true })}>Count the whole tissue</button>}
</div>
);
} else {
displayBody = <p className="muted display-note">Display settings apply to the tissue and the {unit} map.</p>;
}
Expand Down Expand Up @@ -259,37 +249,42 @@ export function StorePage({ item, entity }: { item: StoreItem | VersionItem; ent
<Facts title={title} item={item} origin={entity?.base ?? undefined}
kind={item.kind === 'version' ? `Version${wb.levels.length > 1 ? ` ${wb.levels.length - 1}` : ''} · ${item.title}` : 'Spatial data'}
stage="spatial" from={from} into={into} unsaved={wb.changes.length > 0}
extra={(
<>
{fields && <span className="facts-summary">{summary(fields, unit)}</span>}
{saved > 0 && (
<button type="button" className="kin-chip" onClick={() => chooseLens('versions')}>
{plural(saved, ['version', 'versions'])} saved
</button>
)}
</>
)} />
extra={fields && <span className="facts-summary">{summary(fields, unit)}</span>} />
{!wb.handle ? (
<div className="picture-loading">
<span className="spinner" />
<p className="muted">Opening {item.kind === 'version' ? 'the version and the store under it' : 'the store'}…</p>
</div>
) : (
<DatasetCanvases wbKey={wb.key} handle={wb.handle} dataVersions={wb.dataVersions} selecting={selecting} inset={overlayInset}>
<ViewFrame drawers={drawers} sheet={!onCanvas}
<ViewFrame drawers={drawers} sheet={!onCanvas} barRoom={overlayInset.top}
bar={(
<div className="view-bar" data-backdrop={backdrop} ref={setBar}>
<ViewTabs views={views} reports={reportViews} figures={figureViews} current={lens} onChoose={chooseLens} />
{onCanvas && (
{(onCanvas || lens === 'composition') && (
<div className="view-side">
{/* What colors the cells, in reach on the view: the most common change there is. */}
{/* What colors the cells (and so what the composition counts), in reach on the
view: the most common change there is. */}
{fields && displays[canvasSlot] && (
<div className="view-color studio-ui">
<div className="view-color view-labelled studio-ui">
<span>Color by</span>
<ColorBySelect value={colorBy ?? ''} obsFields={fields.obs} layers={fields.layers} hasX={fields.has_x}
onChange={(path) => updateEncoding(wb.key, canvasSlot, { color_by: path })} />
</div>
)}
<div ref={setTools} />
{lens === 'composition' && (
<div className="view-color view-labelled studio-ui">
<span>Across</span>
<ObsFieldSelect fields={fields!.obs.filter((f) => f.kind === 'categorical')} value={across ?? ''} placeholder="The whole tissue"
onChange={(c) => navigate({ [ACROSS_PARAM]: c || null }, { replace: true })} />
{/* The picker has no empty choice. */}
{across && (
<button type="button" className="icon-button" title="Count the whole tissue" aria-label="Count the whole tissue"
onClick={() => navigate({ [ACROSS_PARAM]: null }, { replace: true })}>×</button>
)}
</div>
)}
{onCanvas && <div ref={setTools} />}
</div>
)}
</div>
Expand All @@ -302,8 +297,9 @@ export function StorePage({ item, entity }: { item: StoreItem | VersionItem; ent
<TaskList hasCells={hasCells} hasGenes={Boolean(fields?.has_x)} reports={reports} figures={figures} onFigure={(id) => chooseLens(`figure:${id}`)} />
),
}}
// Versions has nothing to set, so it takes the drawer's side of the page.
right={lens === 'versions' ? undefined : {
// Versions and a report have nothing to set, and the composition's two choices are on
// the bar, so they take the drawer's side of the page.
right={lens === 'versions' || lens === 'composition' || reportOpen ? undefined : {
label: 'Display',
icon: <SettingsIcon />,
content: (
Expand Down
22 changes: 13 additions & 9 deletions cirro-studio/src/item/ViewFrame.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,8 @@ type Side = 'left' | 'right';
interface Open { left: boolean; right: boolean }

const STORAGE_KEY = appKey('drawers');
const LEFT_WIDTH = 300;
// A task's panel holds charts and tables, so the tasks drawer widens while one is open.
const TASK_WIDTH = 380;
// One width for the task list and an open task, so the views bar holds still between them.
const LEFT_WIDTH = 340;
const RIGHT_WIDTH = 288;
const GAP = 12;
// The room a closed drawer's tab takes at the top corner, which the views bar keeps clear of.
Expand All @@ -22,6 +21,9 @@ export const BAR_ROOM = 40;
// Below this the drawers start closed, and only one is out at a time: both would cover
// most of the view.
const ROOMY_WIDTH = 1100;
// Below this a drawer covers close to half the view, so a page opens with both away
// whatever was kept open on a wider window.
const TIGHT_WIDTH = 860;

function useNarrow(): boolean {
const [narrow, setNarrow] = useState(() => window.innerWidth < ROOMY_WIDTH);
Expand All @@ -34,6 +36,7 @@ function useNarrow(): boolean {
}

function initialOpen(): Open {
if (window.innerWidth < TIGHT_WIDTH) return { left: false, right: false };
try {
const saved = JSON.parse(localStorage.getItem(STORAGE_KEY) ?? 'null') as Open | null;
if (saved) return saved;
Expand Down Expand Up @@ -98,13 +101,12 @@ export function useDrawers(working: boolean): Drawers {
window.addEventListener('keydown', onKey);
return () => window.removeEventListener('keydown', onKey);
}, [toggle, toggleBoth]);
const left = working ? TASK_WIDTH : LEFT_WIDTH;
// Kept as one object while the drawers stay put: the canvas host is rebuilt when it changes.
const inset = useMemo(
() => ({ left: open.left ? left + GAP : 0, right: open.right ? RIGHT_WIDTH + GAP : 0 }),
[open.left, open.right, left],
() => ({ left: open.left ? LEFT_WIDTH + GAP : 0, right: open.right ? RIGHT_WIDTH + GAP : 0 }),
[open.left, open.right],
);
return { open, toggle, widths: { left, right: RIGHT_WIDTH }, inset };
return { open, toggle, widths: { left: LEFT_WIDTH, right: RIGHT_WIDTH }, inset };
}

const Chevron = ({ to }: { to: Side }) => (
Expand Down Expand Up @@ -149,16 +151,18 @@ function Drawer({ side, spec, open, onToggle }: { side: Side; spec: DrawerSpec;
* chart rather than the tissue) keeps clear of the open drawers instead of running under
* them. Without `right` (a view with nothing to set) the right drawer and its tab are
* away, and the view has that side to itself. */
export function ViewFrame({ drawers, left, right, bar, main, sheet = false }: {
export function ViewFrame({ drawers, left, right, bar, main, sheet = false, barRoom = BAR_ROOM }: {
drawers: Drawers; left: DrawerSpec; right?: DrawerSpec; bar?: ReactNode; main: ReactNode; sheet?: boolean;
// The bar's measured room, where it can wrap to a second row.
barRoom?: number;
}) {
const insetRight = right ? drawers.inset.right : 0;
const style = {
'--drawer-left': `${drawers.widths.left}px`, '--drawer-right': `${drawers.widths.right}px`, '--drawer-gap': `${GAP}px`,
'--inset-left': `${drawers.inset.left}px`, '--inset-right': `${insetRight}px`,
'--bar-left': `${drawers.open.left ? drawers.inset.left + GAP : TAB_ROOM}px`,
'--bar-right': `${!right ? GAP : drawers.open.right ? insetRight + GAP : TAB_ROOM}px`,
'--bar-room': `${BAR_ROOM}px`,
'--bar-room': `${barRoom}px`,
} as CSSProperties;
return (
<div className={bar ? 'frame frame-barred' : 'frame'} style={style}>
Expand Down
Loading
Loading