All files / lib state.svelte.js

71.33% Statements 112/157
51.75% Branches 59/114
77.77% Functions 56/72
74.4% Lines 93/125

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436                                                                            71x 71x                                                                                                           3x       3x 2x 1x       1x 1x 1x 1x       71x                                   71x   71x   71x   71x   71x   71x   71x   71x   71x   71x   71x   71x   71x       71x             3x 1x   2x     3x       19x   71x     19x     2x         71x     8x           71x             2x                                   5x 3x                 5x 4x                 15x 15x 14x 5x   9x               5x 5x 4x 4x 4x       1x 2x           2x   2x 1x 1x               3x 4x                 7x 7x 7x 17x 10x 10x 7x                 1x 1x 2x 2x 2x     1x                 2x 2x 2x   2x         5x   5x 3x 3x         4x 3x 3x 3x                       3x   71x                                                                                                                                 6x 5x   5x   4x 5x   2x         14x  
import { Estimation as ETA } from 'arrival-time';
import { SvelteMap, SvelteSet } from 'svelte/reactivity';
 
import { tables } from './idb.svelte.js';
import { getMetadataValue } from './metadata/index.js';
import { defaultClassificationMetadata, defaultCropMetadata } from './protocols.js';
import { isMetadataInProtocol } from './schemas/protocols.js';
import { mapValues, omit, pick, transformObject } from './utils.js';
 
/**
 * @import * as DB from './database';
 * @import { TypedMetadataValue } from './metadata/index.js';
 * @import { ZoomState } from './DraggableBoundingBox.svelte.js';
 */
 
/**
 * @template {string} [Groups=string]
 * @typedef Keybind
 * @type {object}
 * @property {Groups} [group] used to group keybinds together in help dialogs
 * @property {string} help
 * @property {(e: MouseEvent|KeyboardEvent) => unknown} do
 * @property {boolean} [hidden=false] hide the keybinding from help
 * @property {boolean} [debug=false] only activate the keybinding in debug mode, hide it from help otherwise
 * @property {(e: MouseEvent|KeyboardEvent) => boolean} [when=() => true] condition to check before executing the keybind
 * @property {boolean} [allowInModals=false] allow the keybind to be active even when a modal is open
 */
 
/**
 * @template {string} [Groups=string]
 * @typedef Keymap
 * @type {Record<string, Keybind<Groups>>}
 */
 
export class UIState {
	constructor() {
		// Can't use if(window) cuz variable might be undeclared
		// Can't use if(browser) cuz $app/environment imports don't work when transforming worker code
		try {
			window.uiState = this;
		} catch {
			// ok
		}
	}
 
	/**
	 * Returns a JSON-compatible object of the state.
	 * Used for debugging purposes
	 */
	snapshot() {
		return $state.snapshot({
			processing: pick(this.processing, 'files', 'total', 'done', 'time', 'task'),
			eta: this.eta,
			selection: this.selection,
			imageOpenedInCropper: this.imageOpenedInCropper,
			imagePreviouslyOpenedInCropper: this.imagePreviouslyOpenedInCropper,
			previewURLs: Object.fromEntries(this.previewURLs.entries()),
			globalPreviewURLs: Object.fromEntries(this.globalPreviewURLs.entries()),
			erroredImages: Object.fromEntries(this.erroredImages.entries()),
			loadingImages: Array.from(this.loadingImages),
			queuedImages: Array.from(this.queuedImages),
			keybinds: mapValues(this.keybinds, (bind) =>
				transformObject(bind, (key, value) => (key === 'do' ? undefined : [key, value]))
			),
			currentSessionId: this.currentSessionId,
			currentSession: this.currentSession ? omit(this.currentSession, 'metadata') : null,
			currentProtocol: this.currentProtocol ? pick(this.currentProtocol, 'id', 'name') : null,
			classificationMetadata: this.classificationMetadata
				? pick(this.classificationMetadata, 'id', 'infer')
				: null,
			cropMetadata: this.cropMetadata ? pick(this.cropMetadata, 'id', 'infer') : null,
			classificationModels: this.classificationModels,
			cropModels: this.cropModels,
			selectedCropModel: this.selectedCropModel,
			selectedClassificationModel: this.selectedClassificationModel,
			cropInferenceAvailable: this.cropInferenceAvailable,
			classificationInferenceAvailable: this.classificationInferenceAvailable,
		});
	}
 
	processing = $state({
		/** @type {Array<{name: string; id: string; addedAt: Date }>} */
		files: [],
		/** @type {number} */
		total: 0,
		/** @type {number} */
		done: 0,
		/** @type {number} */
		time: 0,
		/** @type {''|'import'|'detection'|'classification'|'export'} */
		task: '',
		/** @type {number} */
		get progress() {
			return this.total ? this.done / this.total : 0;
		},
		/** @type {(id: string) => void} */
		removeFile(id) {
			const idx = this.files.findIndex((f) => f.id === id);
			if (idx === -1) return;
			this.files.splice(idx, 1);
		},
		/** @type {() => void} */
		reset() {
			this.total = 0;
			this.done = 0;
			this.time = 0;
			this.task = '';
		},
	});
 
	#eta = new ETA({ total: 0 });
 
	/** @param {number} total, @param {number} done */
	#updateETA(done, total) {
		if (done >= total || total === 0) {
			this.#eta.reset();
			return;
		}
 
		this.#eta.update(done, total);
	}
 
	eta = $derived.by(() => {
		this.#updateETA(this.processing.done, this.processing.total);
		return this.#eta.estimate();
	});
 
	/** @type {string[]} */
	selection = $state([]);
	/** @type {string | ''} */
	imageOpenedInCropper = $state('');
	/** @type {string | ''} */
	imagePreviouslyOpenedInCropper = $state('');
	/** @type {Map<string, string>} */
	previewURLs = new SvelteMap();
	/** @type {Map<string, string>} These persist across session changes */
	globalPreviewURLs = new SvelteMap();
	/** @type {Set<string>} Persisted set of inference session IDs loaded on the client */
	loadedInferenceSessions = new SvelteSet();
	/** @type {Map<string, string>} */
	erroredImages = new SvelteMap();
	/** @type {Set<string>} */
	loadingImages = new SvelteSet();
	/** @type {Set<string>} */
	queuedImages = new SvelteSet();
	/** @type {Keymap} */
	keybinds = $state({});
	/** @type {Map<string, import('./DraggableBoundingBox.svelte.js').ZoomState>} */
	cropperZoomStates = new SvelteMap();
	/** @type {undefined | ((newSelection: string[]) => void)} */
	setSelection = $state(undefined);
	/** @type {string | null} */
	_currentSessionId = $state(null);
 
	/** @type {string | null} */
	currentSessionId = $derived(
		this._currentSessionId || localStorage.getItem('currentSessionId') || null
	);
 
	/**
	 * @param {string | null} id
	 */
	async setCurrentSession(id) {
		if (id === null) {
			localStorage.removeItem('currentSessionId');
		} else {
			localStorage.setItem('currentSessionId', id);
		}
 
		this._currentSessionId = id;
	}
 
	/** @type {import('./database').Session | undefined}  */
	currentSession = $derived(tables.Session.state.find((s) => s.id === this.currentSessionId));
 
	currentProtocolId = $derived(this.currentSession?.protocol);
 
	/** @type {import('./database').Protocol | undefined} */
	currentProtocol = $derived(tables.Protocol.state.find((p) => p.id === this.currentProtocolId));
 
	classificationMetadata = $derived(
		this.currentProtocol
			? defaultClassificationMetadata(this.currentProtocol, tables.Metadata.state)
			: undefined
	);
 
	classificationMetadataId = $derived(this.classificationMetadata?.id);
 
	cropMetadata = $derived(
		this.currentProtocol
			? defaultCropMetadata(this.currentProtocol, tables.Metadata.state)
			: undefined
	);
 
	/** @type {string} */
	cropMetadataId = $derived(this.cropMetadata?.id ?? 'crop');
 
	/**
	 * @param {import('./database').Image} image
	 * @returns {import('./metadata').TypedMetadataValue<'boundingbox'>|undefined}
	 */
	cropMetadataValueOf(image) {
		return getMetadataValue(image, 'boundingbox', this.cropMetadataId);
	}
 
	/**
	 * @param {import('./database').Image} image
	 * @returns {import('./metadata').TypedMetadataValue<'enum'>|undefined}
	 */
 
	classificationMetadataValueOf(image) {
		if (!this.classificationMetadataId) return undefined;
		return getMetadataValue(image, 'enum', this.classificationMetadataId);
	}
 
	/**
	 * @param {string | undefined | null} imageFileId
	 * @returns {boolean}
	 */
	hasPreviewURL(imageFileId) {
		if (!imageFileId) return false;
		return this.globalPreviewURLs.has(imageFileId) || this.previewURLs.has(imageFileId);
	}
 
	/**
	 *
	 * @param {string | undefined | null} imageFileId
	 * @returns {string | undefined}
	 */
	getPreviewURL(imageFileId) {
		if (!imageFileId) return undefined;
		return this.previewURLs.get(imageFileId) || this.globalPreviewURLs.get(imageFileId);
	}
 
	/**
	 * @param {string | undefined | null} imageFileId
	 * @param {string} url
	 * @param {boolean} [global=false]
	 */
	setPreviewURL(imageFileId, url, global = false) {
		console.debug('setPreviewURL', { imageFileId, url, global });
		if (!imageFileId) return;
		if (global) {
			this.globalPreviewURLs.set(imageFileId, url);
		} else {
			this.previewURLs.set(imageFileId, url);
		}
	}
 
	/**
	 * @param {string} imageFileId
	 */
	revokePreviewURL(imageFileId) {
		const url = this.previewURLs.get(imageFileId);
		if (!url) return;
		URL.revokeObjectURL(url);
		this.previewURLs.delete(imageFileId);
		this.globalPreviewURLs.delete(imageFileId);
	}
 
	clearPreviewURLs() {
		for (const id of this.previewURLs.keys()) {
			this.revokePreviewURL(id);
		}
	}
 
	/** @type {typeof import('$lib/schemas/neural.js').NeuralEnumInference.infer[]} */
	classificationModels = $derived.by(() => {
		const inference = this.classificationMetadata?.infer;
 
		if (!inference) return [];
		Iif (!('neural' in inference)) return [];
		return inference.neural;
	});
 
	/**
	 * Classification metadata with an enabled neural model selection.
	 * @type {import('./database').Metadata[]}
	 */
	enabledClassificationMetadata = $derived.by(() => {
		return this.allClassificationMetadata.filter(
			(metadata) => (this.currentSession?.inferenceModels[metadata.id] ?? 0) !== -1
		);
	});
 
	/**
	 * All metadata with neural enum inference (not just the first one)
	 * @type {import('./database').Metadata[]}
	 */
	allClassificationMetadata = $derived.by(() => {
		const protocol = this.currentProtocol;
		Iif (!protocol) return [];
		const inferenceMetadata = tables.Metadata.state
			.filter((m) => m.type === 'enum')
			.filter((m) => isMetadataInProtocol(protocol, m.id))
			.filter((m) => m.infer && 'neural' in m.infer);
		return inferenceMetadata;
	});
 
	/**
	 * Maps metadata IDs to their neural inference models
	 * @type {import('./database').Metadata['id'] extends string ? Record<import('./database').Metadata['id'], typeof import('$lib/schemas/neural.js').NeuralEnumInference.infer[]> : never}
	 */
	allClassificationModels = $derived.by(() => {
		/** @type {Record<string, any>} */
		const result = {};
		for (const metadata of this.allClassificationMetadata) {
			const inference = metadata.infer;
			Eif (inference && 'neural' in inference) {
				result[metadata.id] = inference.neural;
			}
		}
		return result;
	});
 
	/**
	 * Maps metadata IDs to their selected model indices
	 * @type {import('./database').Metadata['id'] extends string ? Record<import('./database').Metadata['id'], number> : never}
	 */
	selectedClassificationModels = $derived.by(() => {
		/** @type {Record<string, number>} */
		const result = {};
		for (const metadata of this.allClassificationMetadata) {
			result[metadata.id] = this.currentSession?.inferenceModels[metadata.id] ?? 0;
		}
		return result;
	});
 
	/** @type {typeof import('$lib/schemas/neural.js').NeuralBoundingBoxInference.infer[]} */
	cropModels = $derived.by(() => {
		const inference = this.cropMetadata?.infer;
 
		if (!inference) return [];
		Iif (!('neural' in inference)) return [];
		return inference.neural;
	});
 
	/** @type {number} */
	selectedCropModel = $derived.by(() => {
		if (!this.currentProtocolId) return -1;
		const metadataId = this.cropMetadataId;
		Iif (!metadataId) return -1;
		return this.currentSession?.inferenceModels[metadataId] ?? 0;
	});
 
	/** @type {number} */
	selectedClassificationModel = $derived.by(() => {
		if (!this.currentProtocolId) return -1;
		const metadataId = this.classificationMetadataId;
		if (!metadataId) return -1;
		return this.currentSession?.inferenceModels[metadataId] ?? 0;
	});
 
	/** @type {boolean} */
	cropInferenceAvailable = $derived(this.cropModels.length > 0 && this.selectedCropModel !== -1);
	/** @type {boolean} */
	classificationInferenceAvailable = $derived(this.enabledClassificationMetadata.length > 0);
 
	/**
	 * Set the selected model index for a classification metadata.
	 * @param {string} metadataId
	 * @param {number} modelIndex -1 disables inference for that metadata
	 * @returns {Promise<void>}
	 */
	async setClassificationModelSelection(metadataId, modelIndex) {
		if (!this.currentSession) return;
 
		const current = this.currentSession.inferenceModels;
		if ((current[metadataId] ?? 0) === modelIndex) return;
 
		await tables.Session.update(this.currentSession.id, 'inferenceModels', {
			...current,
			[metadataId]: modelIndex,
		});
	}
 
	/**
	 * @param {{ classification?: number | null, crop?: number | null }} indices
	 * @returns {Promise<void>}
	 */
	async setModelSelections({ classification = null, crop = null }) {
		if (!this.currentSession) return;
 
		if (classification === null && crop === null) return; // no change
 
		const metadataIds = {
			classification: this.classificationMetadataId,
			crop: this.cropMetadataId,
		};
 
		if (!metadataIds.classification || !metadataIds.crop) return;
 
		const current = this.currentSession.inferenceModels;
		/** @type {Record<string, number>} */
		const changes = {};
 
		if (classification !== null && classification !== this.selectedClassificationModel) {
			changes[metadataIds.classification] = classification;
		}
		if (crop !== null && crop !== this.selectedCropModel) {
			changes[metadataIds.crop] = crop;
		}
 
		if (Object.keys(changes).length === 0) {
			return; // no change
		}
 
		await tables.Session.update(this.currentSession.id, 'inferenceModels', {
			...current,
			...changes,
		});
	}
 
	/**
	 * Toggle selection of given id(s).
	 * Does nothing if setSelection is not defined
	 *
	 * When given multiple IDs, it'll add them all unless they are all already selected, in which case it'll remove them all.
	 * @param {...string} ids
	 */
	toggleSelection(...ids) {
		if (!this.setSelection) return;
		if (ids.length === 0) return;
 
		const allSelected = ids.every((id) => this.selection.includes(id));
 
		if (allSelected) {
			this.setSelection(this.selection.filter((id) => !ids.includes(id)));
		} else {
			this.setSelection([...this.selection, ...ids]);
		}
	}
}
 
export const uiState = new UIState();