Compare commits

...

6 Commits

Author SHA1 Message Date
Ross b527eb1139 many updates 2026-05-21 22:44:13 +01:00
Ross 6a0552c843 feat(mobile): implement mobile stack drag-and-drop functionality with improved viewport handling 2026-05-19 14:47:41 +01:00
Ross a5c530a907 feat(mobile): enhance mobile interaction with new touch controls and layout adjustments 2026-05-19 14:26:28 +01:00
Ross 41f13ade5e feat(b-values): implement parsing for multiple b-value formats and update default setting 2026-05-19 13:26:32 +01:00
Ross b0d8c72636 feat(logger): enhance logging configuration with minLevel and silent option
- Added a new LogLevel "silent" to suppress logging output.
- Replaced the debug boolean flag in LoggerConfig with a minLevel property to specify the minimum log level.
- Updated shouldLog function to respect the new minLevel configuration.
- Modified parseDebugFlag to return appropriate LogLevel based on truthy values.
- Updated main.tsx to accommodate changes in logging configuration, including parsing minLevel from attributes and options.
- Deprecated the debug flag in favor of minLevel for better clarity and control over logging behavior.
2026-05-19 12:55:44 +01:00
Ross 4dd63668b0 feat(logging): implement structured logging with configurable options
- Added a logger utility to manage logging levels and formats.
- Integrated logging into main application and non-DICOM test components.
- Enhanced error handling with logging for invalid JSON data.
- Introduced global functions to set and get logging configurations.
- Updated DICOM viewer mounting logic to support logging configurations.
2026-05-19 09:41:52 +01:00
6 changed files with 2461 additions and 542 deletions
+82 -26
View File
@@ -5,17 +5,36 @@
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Fluoro Multiframe Test</title>
<style>
html,body{height:100%;margin:0}
.dicom-viewer-root{width:100%;height:100vh;background:#222;color:#fff}
html,
body {
height: 100%;
margin: 0;
}
.dicom-viewer-root {
width: 100%;
height: 100vh;
background: #222;
color: #fff;
}
</style>
</head>
<body>
<div id="main_viewer" class="dicom-viewer-root" data-auto-cache-stack="false"></div>
<div
id="main_viewer"
class="dicom-viewer-root"
data-auto-cache-stack="false"
></div>
<!-- Provide noop React Refresh preamble to avoid plugin-react runtime errors -->
<script>
window.$RefreshReg$ = window.$RefreshReg$ || function() {};
window.$RefreshSig$ = window.$RefreshSig$ || function() { return function(type) { return type; }; };
window.$RefreshReg$ = window.$RefreshReg$ || function () {};
window.$RefreshSig$ =
window.$RefreshSig$ ||
function () {
return function (type) {
return type;
};
};
</script>
<script type="module" src="/src/main.tsx"></script>
@@ -23,49 +42,86 @@
<script>
// Viewer state for fluoro multiframe images (using relative paths from public/test_images/)
const state = {
"grid": {"rows": 1, "cols": 2},
"modes": ["stack", "stack"],
"stacks": [
{"i": ["wadouri:test_images/fluro/series_2369/1.3.12.2.1107.5.4.5.180506.30000026031914043350300000126.4.dcm"]},
{"i": ["wadouri:test_images/multibvalues/IMG_792_og2P5S6.dcm", "wadouri:test_images/multibvalues/IMG_793_3tKkg87.dcm"]}
grid: { rows: 1, cols: 2 },
modes: ["stack", "stack"],
stacks: [
{
i: [
"wadouri:https://www.penracourses.org.uk/media/atlas/dicom/1.3.12.2.1107.5.4.5.180506.30000026031914043350300000126.4.dcm",
],
},
],
"stackIdx": [0, 1],
"stackPos": [0, 1],
"props": [
{"voiRange": {"lower": 0, "upper": 500}, "invert": false, "interpolationType": 1, "VOILUTFunction": "LINEAR", "colormap": {"name": "Grayscale", "opacity": []}},
{"voiRange": {"lower": 0, "upper": 500}, "invert": false, "interpolationType": 1, "VOILUTFunction": "LINEAR", "colormap": {"name": "Grayscale", "opacity": []}}
stackIdx: [0, 1],
stackPos: [0, 1],
props: [
{
voiRange: { lower: 0, upper: 500 },
invert: false,
interpolationType: 1,
VOILUTFunction: "LINEAR",
colormap: { name: "Grayscale", opacity: [] },
},
{
voiRange: { lower: 0, upper: 500 },
invert: false,
interpolationType: 1,
VOILUTFunction: "LINEAR",
colormap: { name: "Grayscale", opacity: [] },
},
],
"cam": [
{"viewUp": [0, 0, 1], "viewPlaneNormal": [1, 0, 0], "position": [150, 0, 0], "focalPoint": [0, 0, 0], "parallelProjection": true, "parallelScale": 100, "viewAngle": 90, "flipHorizontal": false, "flipVertical": false, "rotation": 0},
{"viewUp": [0, 0, 1], "viewPlaneNormal": [1, 0, 0], "position": [150, 0, 0], "focalPoint": [0, 0, 0], "parallelProjection": true, "parallelScale": 100, "viewAngle": 90, "flipHorizontal": false, "flipVertical": false, "rotation": 0}
cam: [
{
viewUp: [0, 0, 1],
viewPlaneNormal: [1, 0, 0],
position: [150, 0, 0],
focalPoint: [0, 0, 0],
parallelProjection: true,
parallelScale: 100,
viewAngle: 90,
flipHorizontal: false,
flipVertical: false,
rotation: 0,
},
{
viewUp: [0, 0, 1],
viewPlaneNormal: [1, 0, 0],
position: [150, 0, 0],
focalPoint: [0, 0, 0],
parallelProjection: true,
parallelScale: 100,
viewAngle: 90,
flipHorizontal: false,
flipVertical: false,
rotation: 0,
},
],
"orientations": [null, null],
"volumeSliceIndices": [null, null]
orientations: [null, null],
volumeSliceIndices: [null, null],
};
function callWhenReady(fnName, payload) {
const maxWait = 5000;
const start = Date.now();
(function check() {
if (window[fnName] && typeof window[fnName] === 'function') {
if (window[fnName] && typeof window[fnName] === "function") {
try {
window[fnName](payload);
console.log('imported viewer state via', fnName);
console.log("imported viewer state via", fnName);
} catch (e) {
console.error('importViewerState call failed', e);
console.error("importViewerState call failed", e);
}
return;
}
if (Date.now() - start > maxWait) {
console.warn('Timed out waiting for', fnName);
console.warn("Timed out waiting for", fnName);
return;
}
setTimeout(check, 2000);
})();
}
document.addEventListener('DOMContentLoaded', () => {
callWhenReady('importViewerState', state);
document.addEventListener("DOMContentLoaded", () => {
callWhenReady("importViewerState", state);
});
</script>
</body>
File diff suppressed because one or more lines are too long
+1762 -408
View File
File diff suppressed because it is too large Load Diff
+181
View File
@@ -0,0 +1,181 @@
export type LogLevel = "debug" | "info" | "warn" | "error" | "silent";
export type LogFormat = "compact" | "verbose" | "json";
export type LoggerConfig = {
minLevel: LogLevel;
format: LogFormat;
namespace: string;
dedupeWindowMs: number;
};
const LEVEL_ORDER: Record<LogLevel, number> = {
debug: 0,
info: 1,
warn: 2,
error: 3,
silent: 4,
};
const DEFAULT_CONFIG: LoggerConfig = {
minLevel: "warn",
format: "compact",
namespace: "dv3d",
dedupeWindowMs: 1200,
};
let loggerConfig: LoggerConfig = { ...DEFAULT_CONFIG };
const lastMessageByFingerprint = new Map<string, number>();
type LogContext = {
namespace?: string;
dedupeKey?: string;
};
function nowIso() {
return new Date().toISOString();
}
function getConsoleMethod(level: LogLevel) {
if (level === "debug") return console.debug.bind(console);
if (level === "info") return console.info.bind(console);
if (level === "warn") return console.warn.bind(console);
return console.error.bind(console);
}
function serializeArg(arg: unknown): unknown {
if (arg instanceof Error) {
return {
name: arg.name,
message: arg.message,
stack: arg.stack,
};
}
return arg;
}
function shouldLog(level: LogLevel) {
return LEVEL_ORDER[level] >= LEVEL_ORDER[loggerConfig.minLevel];
}
function shouldDedupe(level: LogLevel) {
return level === "debug" || level === "info";
}
function buildFingerprint(level: LogLevel, args: unknown[], ctx?: LogContext): string {
const base = ctx?.dedupeKey || `${ctx?.namespace || loggerConfig.namespace}:${level}`;
const message = args
.map((arg) => {
if (typeof arg === "string") return arg;
try {
return JSON.stringify(serializeArg(arg));
} catch {
return String(arg);
}
})
.join("|");
return `${base}:${message}`;
}
function isDuplicate(level: LogLevel, args: unknown[], ctx?: LogContext): boolean {
if (!shouldDedupe(level) || loggerConfig.dedupeWindowMs <= 0) {
return false;
}
const fingerprint = buildFingerprint(level, args, ctx);
const t = Date.now();
const last = lastMessageByFingerprint.get(fingerprint);
lastMessageByFingerprint.set(fingerprint, t);
if (last === undefined) {
return false;
}
return t - last < loggerConfig.dedupeWindowMs;
}
function createPrefix(level: LogLevel, namespace?: string) {
const ns = namespace || loggerConfig.namespace;
if (loggerConfig.format === "compact") {
return `[${ns}] ${level.toUpperCase()}`;
}
if (loggerConfig.format === "verbose") {
return `[${nowIso()}] [${ns}] [${level.toUpperCase()}]`;
}
return "";
}
function log(level: LogLevel, args: unknown[], ctx?: LogContext) {
if (!shouldLog(level)) {
return;
}
if (isDuplicate(level, args, ctx)) {
return;
}
if (loggerConfig.format === "json") {
getConsoleMethod(level)({
ts: nowIso(),
namespace: ctx?.namespace || loggerConfig.namespace,
level,
message: args.map(serializeArg),
});
return;
}
const prefix = createPrefix(level, ctx?.namespace);
getConsoleMethod(level)(prefix, ...args);
}
export function setLoggerConfig(config: Partial<LoggerConfig>) {
loggerConfig = {
...loggerConfig,
...config,
};
return getLoggerConfig();
}
export function getLoggerConfig(): LoggerConfig {
return { ...loggerConfig };
}
export function parseLogFormat(value: unknown): LogFormat {
if (value === "compact" || value === "verbose" || value === "json") {
return value;
}
return DEFAULT_CONFIG.format;
}
/** Parse a log level string. Falls back to the default ("warn") for unknown values. */
export function parseLogLevel(value: unknown): LogLevel {
if (value === "debug" || value === "info" || value === "warn" || value === "error" || value === "silent") {
return value;
}
return DEFAULT_CONFIG.minLevel;
}
/** Backward-compat helper: maps a truthy debug flag to minLevel "debug" or "warn". */
export function parseDebugFlag(value: unknown): LogLevel {
if (typeof value === "boolean") {
return value ? "debug" : "warn";
}
if (typeof value === "string") {
const normalized = value.trim().toLowerCase();
const truthy = normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on";
return truthy ? "debug" : "warn";
}
if (typeof value === "number") {
return value !== 0 ? "debug" : "warn";
}
return "warn";
}
export const logger = {
debug: (...args: unknown[]) => log("debug", args),
info: (...args: unknown[]) => log("info", args),
warn: (...args: unknown[]) => log("warn", args),
error: (...args: unknown[]) => log("error", args),
child: (namespace: string) => ({
debug: (...args: unknown[]) => log("debug", args, { namespace }),
info: (...args: unknown[]) => log("info", args, { namespace }),
warn: (...args: unknown[]) => log("warn", args, { namespace }),
error: (...args: unknown[]) => log("error", args, { namespace }),
}),
};
+106 -38
View File
@@ -1,12 +1,29 @@
import React from 'react'
import React from "react";
import { createRoot, type Root } from "react-dom/client";
import App from './App.tsx'
import './index.css'
import { availableImageIds } from "./lib/createImageIds.ts"
import App from "./App.tsx";
import "./index.css";
import { availableImageIds } from "./lib/createImageIds.ts";
import {
getLoggerConfig,
logger,
parseDebugFlag,
parseLogFormat,
parseLogLevel,
setLoggerConfig,
type LogFormat,
type LogLevel,
} from "./lib/logger";
type MountOptions = {
force?: boolean;
containerIds?: string[];
logging?: {
/** Minimum log level to emit. Takes precedence over `debug`. */
minLevel?: LogLevel;
/** @deprecated Use minLevel instead. true maps to "debug", false maps to "warn". */
debug?: boolean;
format?: LogFormat;
};
};
type ViewerDescriptor = {
@@ -14,6 +31,17 @@ type ViewerDescriptor = {
name?: string;
caseId?: string;
studyId?: string;
series?: Array<{
key?: string;
label?: string;
imageIds?: string[];
i?: string[];
name?: string;
seriesId?: string | number;
seriesInstanceUID?: string;
bValue?: number | null;
groupValues?: Record<string, string>;
}>;
};
type RootRecord = {
@@ -22,11 +50,14 @@ type RootRecord = {
};
const rootRegistry = new WeakMap<HTMLElement, RootRecord>();
const mainLogger = logger.child("main");
declare global {
interface Window {
mountDicomViewers?: (options?: MountOptions) => void;
remountDicomViewer?: (containerId: string) => void;
setDicomViewerLogging?: (config: { minLevel?: LogLevel; debug?: boolean; format?: LogFormat }) => void;
getDicomViewerLogging?: () => { minLevel: LogLevel; format: LogFormat; namespace: string; dedupeWindowMs: number };
}
}
@@ -83,8 +114,8 @@ const parseToDescriptors = (parsed: any): Array<ViewerDescriptor> => {
else if (Array.isArray(s.imageIds)) imageIds = s.imageIds;
else if (Array.isArray(s.i)) imageIds = s.i;
if (!Array.isArray(imageIds) || imageIds.length === 0 || !imageIds.every(x => typeof x === "string")) {
console.warn(`data-named-stacks: skipping invalid nested stack at parsed[${itemIdx}].stacks[${sIdx}]`, s);
if (!Array.isArray(imageIds) || imageIds.length === 0 || !imageIds.every((x) => typeof x === "string")) {
mainLogger.warn(`data-named-stacks: skipping invalid nested stack at parsed[${itemIdx}].stacks[${sIdx}]`, s);
return;
}
@@ -93,15 +124,16 @@ const parseToDescriptors = (parsed: any): Array<ViewerDescriptor> => {
name: s.name || s.label || undefined,
caseId,
studyId: s.studyId || studyId,
series: Array.isArray(s.series) ? s.series : undefined,
});
});
return;
}
if (item && typeof item === 'object' && (Array.isArray(item.imageIds) || Array.isArray(item.i))) {
if (item && typeof item === "object" && (Array.isArray(item.imageIds) || Array.isArray(item.i))) {
const imageIds = Array.isArray(item.imageIds) ? item.imageIds : item.i;
if (!Array.isArray(imageIds) || imageIds.length === 0 || !imageIds.every(x => typeof x === "string")) {
console.warn(`data-named-stacks: skipping invalid stack object at parsed[${itemIdx}]`, item);
if (!Array.isArray(imageIds) || imageIds.length === 0 || !imageIds.every((x) => typeof x === "string")) {
mainLogger.warn(`data-named-stacks: skipping invalid stack object at parsed[${itemIdx}]`, item);
return;
}
@@ -110,6 +142,7 @@ const parseToDescriptors = (parsed: any): Array<ViewerDescriptor> => {
name: item.name || item.label || undefined,
caseId: item.caseId || item.caseUID || undefined,
studyId: item.studyId || item.studyUID || item.studyInstanceUID || undefined,
series: Array.isArray(item.series) ? item.series : undefined,
});
return;
}
@@ -119,7 +152,7 @@ const parseToDescriptors = (parsed: any): Array<ViewerDescriptor> => {
return;
}
console.warn(`data-named-stacks: unknown or invalid entry at parsed[${itemIdx}] skipping`, item);
mainLogger.warn(`data-named-stacks: unknown or invalid entry at parsed[${itemIdx}] - skipping`, item);
});
return out;
@@ -127,24 +160,48 @@ const parseToDescriptors = (parsed: any): Array<ViewerDescriptor> => {
const getMountSignature = (container: HTMLElement): string => {
return JSON.stringify({
id: container.id || '',
empty: container.getAttribute('data-empty') || '',
namedStacks: container.getAttribute('data-named-stacks') || '',
images: container.getAttribute('data-images') || '',
autoCache: container.getAttribute('data-auto-cache-stack') || '',
annotation: container.getAttribute('data-annotationjson') || '',
viewerState: container.getAttribute('data-viewerstate') || '',
id: container.id || "",
empty: container.getAttribute("data-empty") || "",
namedStacks: container.getAttribute("data-named-stacks") || "",
images: container.getAttribute("data-images") || "",
autoCache: container.getAttribute("data-auto-cache-stack") || "",
annotation: container.getAttribute("data-annotationjson") || "",
viewerState: container.getAttribute("data-viewerstate") || "",
});
};
const shouldMountContainer = (container: HTMLElement, options?: MountOptions): boolean => {
if (!options?.containerIds || options.containerIds.length === 0) return true;
return options.containerIds.includes(container.id || '');
return options.containerIds.includes(container.id || "");
};
const getContainerLogConfig = (container: HTMLElement, options?: MountOptions) => {
const attrLevel = container.getAttribute("data-log-level");
const attrDebug = container.getAttribute("data-log-debug");
const attrFormat = container.getAttribute("data-log-format");
// Resolve minLevel: data-log-level > options.minLevel > data-log-debug (legacy) > options.debug (legacy)
let minLevel: LogLevel;
if (attrLevel !== null) {
minLevel = parseLogLevel(attrLevel);
} else if (options?.logging?.minLevel) {
minLevel = options.logging.minLevel;
} else if (attrDebug !== null) {
minLevel = parseDebugFlag(attrDebug);
} else if (options?.logging?.debug !== undefined) {
minLevel = parseDebugFlag(options.logging.debug);
} else {
minLevel = "warn";
}
const format = parseLogFormat(attrFormat ?? options?.logging?.format);
return { minLevel, format };
};
const mountContainer = (container: HTMLElement, imageStacks: () => Promise<any[]>, options?: MountOptions) => {
const signature = getMountSignature(container);
const existing = rootRegistry.get(container);
const initialLoggerConfig = getContainerLogConfig(container, options);
if (existing && !options?.force && existing.signature === signature) {
return;
@@ -155,14 +212,17 @@ const mountContainer = (container: HTMLElement, imageStacks: () => Promise<any[]
rootRegistry.delete(container);
}
setLoggerConfig(initialLoggerConfig);
const root = createRoot(container);
root.render(
<App
container_id={container.id || ''}
container_id={container.id || ""}
imageStacks={imageStacks}
autoCacheStack={(container.getAttribute('data-auto-cache-stack') === "true" || container.getAttribute('data-auto-cache-stack') === "1")}
annotationJson={container.getAttribute('data-annotationjson') || undefined}
viewerState={container.getAttribute('data-viewerstate') || undefined}
autoCacheStack={container.getAttribute("data-auto-cache-stack") === "true" || container.getAttribute("data-auto-cache-stack") === "1"}
annotationJson={container.getAttribute("data-annotationjson") || undefined}
viewerState={container.getAttribute("data-viewerstate") || undefined}
initialLoggerConfig={initialLoggerConfig}
/>
);
@@ -171,10 +231,9 @@ const mountContainer = (container: HTMLElement, imageStacks: () => Promise<any[]
export function mountDicomViewers(options?: MountOptions) {
// Test containers
const test_containers = document.querySelectorAll(".dicom-viewer-test-root");
test_containers.forEach((container) => {
const testContainers = document.querySelectorAll(".dicom-viewer-test-root");
testContainers.forEach((container) => {
if (!shouldMountContainer(container as HTMLElement, options)) return;
const id = container.id || '';
const imageStacks = () => availableImageIds();
mountContainer(container as HTMLElement, imageStacks, options);
});
@@ -185,10 +244,10 @@ export function mountDicomViewers(options?: MountOptions) {
if (!shouldMountContainer(container as HTMLElement, options)) return;
let imageStacks: () => Promise<any[]>;
const isEmpty = container.getAttribute('data-empty') === 'true';
const isEmpty = container.getAttribute("data-empty") === "true";
const dataNamed = container.getAttribute('data-named-stacks');
const dataImages = container.getAttribute('data-images');
const dataNamed = container.getAttribute("data-named-stacks");
const dataImages = container.getAttribute("data-images");
if (isEmpty) {
imageStacks = () => Promise.resolve([] as any[]);
@@ -197,7 +256,7 @@ export function mountDicomViewers(options?: MountOptions) {
try {
parsed = JSON.parse(dataNamed);
} catch (e) {
console.error("Invalid data-named-stacks JSON:", e);
mainLogger.error("Invalid data-named-stacks JSON:", e);
parsed = [];
}
const descriptors = parseToDescriptors(parsed);
@@ -207,15 +266,14 @@ export function mountDicomViewers(options?: MountOptions) {
try {
parsed = JSON.parse(dataImages);
} catch (e) {
console.error("Invalid data-images JSON:", e);
mainLogger.error("Invalid data-images JSON:", e);
parsed = [];
}
if (Array.isArray(parsed) && parsed.length > 0 && typeof parsed[0] === "string") {
imageStacks = () => Promise.resolve([toWadouri(parsed)]);
} else if (Array.isArray(parsed)) {
imageStacks = () => Promise.resolve(parsed.map(
stack => Array.isArray(stack) ? toWadouri(stack) : []
));
imageStacks = () =>
Promise.resolve(parsed.map((stack) => (Array.isArray(stack) ? toWadouri(stack) : [])));
} else {
imageStacks = () => Promise.resolve([[]]);
}
@@ -227,11 +285,21 @@ export function mountDicomViewers(options?: MountOptions) {
});
}
// Optionally, call it immediately for static containers:
mountDicomViewers();
// Expose globally for dynamic use.
(window as any).mountDicomViewers = mountDicomViewers;
(window as any).remountDicomViewer = (containerId: string) => {
window.mountDicomViewers = mountDicomViewers;
window.remountDicomViewer = (containerId: string) => {
mountDicomViewers({ force: true, containerIds: [containerId] });
};
};
window.setDicomViewerLogging = (config) => {
const minLevel = config.minLevel
? parseLogLevel(config.minLevel)
: config.debug !== undefined
? parseDebugFlag(config.debug)
: undefined;
setLoggerConfig({
minLevel,
format: config.format ? parseLogFormat(config.format) : undefined,
});
};
window.getDicomViewerLogging = () => getLoggerConfig();
+4 -1
View File
@@ -1,5 +1,8 @@
import React from 'react'
import { createRoot } from 'react-dom/client'
import { logger } from './lib/logger'
const testLogger = logger.child('nonDicomTest')
// Sample external images (use CORS-friendly URLs). These are Wikimedia Commons images.
const sampleImages = [
@@ -38,7 +41,7 @@ function mount() {
</React.StrictMode>
)
}).catch(err => {
console.error('Failed to load App for non-dicom test', err)
testLogger.error('Failed to load App for non-dicom test', err)
})
}