All files / lib state.svelte.js

16.19% Statements 17/105
0% Branches 0/78
0% Functions 0/53
20% Lines 17/85

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                                                                                                                                    5x                                   5x   5x   5x   5x   5x   5x   5x   5x   5x   5x   5x   5x       5x                                       5x                                               5x                                                                                                                                                                                                                                                                                           5x  
import { match } from 'arktype';
import { Estimation as ETA } from 'arrival-time';
import { watch } from 'runed';
import { SvelteMap, SvelteSet } from 'svelte/reactivity';
 
import { MetadataInferOptionsNeural } from '$lib/schemas/metadata.js';
 
import { tables } from './idb.svelte.js';
import { getMetadataValue } from './metadata.js';
 
/**
 * @import * as DB from './database';
 * @import { TypedMetadataValue } from './metadata';
 * @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>>}
 */
 
class UIState {
	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 {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 {
			void tables.Session.update(id, 'openedAt', new Date().toISOString());
			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));
 
	/**
	 * @param {import('./database').Image} image
	 * @returns {import('./metadata').TypedMetadataValue<'boundingbox'>|undefined}
	 */
	cropMetadataValueOf(image) {
		return getMetadataValue(image, 'boundingbox', this.cropMetadataId);
	}
 
	/** @type {string} */
	cropMetadataId = $derived(
		tables.Metadata.state.find(
			(m) =>
				this.currentProtocol?.metadata.includes(m.id) &&
				this.currentProtocol?.crop?.metadata === m.id
		)?.id ?? 'crop'
	);
 
	/** @type {string} */
	cropConfirmationMetadataId = $derived(
		tables.Metadata.state.find(
			(m) =>
				this.currentProtocol?.metadata.includes(m.id) &&
				this.currentProtocol?.crop?.confirmationMetadata === m.id
		)?.id ?? ''
	);
 
	/**
	 * @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/metadata.js').MetadataInferOptionsNeural.infer['neural']} */
	classificationModels = $derived(
		tables.Metadata.state.find((m) => m.id === this.classificationMetadataId)?.infer?.neural ??
			[]
	);
	/** @type {NonNullable<typeof import('$lib/schemas/protocols.js').Protocol.infer['crop']['infer']>} */
	cropModels = $derived(this.currentProtocol?.crop?.infer ?? []);
 
	/** @type {number} */
	selectedCropModel = $derived.by(() => {
		if (!this.currentProtocolId) return -1;
		const metadataId = this.cropMetadataId;
		if (!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.classificationModels.length > 0 && this.selectedClassificationModel !== -1
	);
 
	/**
	 * @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
		});
	}
 
	/** @type {string|undefined} */
	classificationMetadataId = $derived.by(() => {
		const isCandidate = match
			.case(
				{
					id: 'string',
					type: '"enum"',
					infer: MetadataInferOptionsNeural
				},
				({ id }) => this.currentProtocol?.metadata.includes(id)
			)
			.default(() => false);
		return tables.Metadata.state.find((m) => isCandidate(m))?.id;
	});
}
 
export const uiState = new UIState();