mirror of
https://github.com/gpxstudio/gpx.studio.git
synced 2026-11-01 20:19:39 +00:00
Migration to new Rust-based engine (#401)
* wasm first steps * parsing start * parsing continued * progress * progress * progress * progress * progress * progress * progress * progress * fixes * reorganize * change type * fix * progress * refactoring * progress * progress * progress * keep style info * progress * progress * remove (copy) in name * progress * merge methods into 1 * splice * progress * progress * progress * cleaning * progress * progress * progress * visibility * progress * progress * progress * progress * progress * fixes * progress * fix markers * fix * progress * progress * progress * progress * progress * progress * small fix * use engine info * fix popups * small fix * progress * progress * progress * clean tool * handle self closing elements * reduce data exchanges across boundary * copy on wasm side to avoid any data corruption * speed fix * routing * refactoring * reverse * reverse * crop * split * merge * progress * time tool * fix bounds for waypoints * reduce * fix reactivity * handle corrupt time data * export * progress * remove gpx js package * remove todo * update readme * cleaning * progress * fix link fields * remove unused fields * refactoring and tests * import and export of routes, ref #192 * per-chunk categories storage * cross-tab sync * outdated state * refactoring * reorder methods * refactoring * fix * improve flow * renaming * progress * progress * fix * progress * per file history * keep original flag * use history variant * fix * progress * file explorer * progress * fix * sticky folders * improved sticky folders * fix sortable * fix sortable * fix * fix tab size * no file delete on desktop * fix routing on other file * fix sorting * remember language * open links in browser * commit missing changes * avoid selecting on resize * clarify filename * explorer actions * fix folder styling * drop anywhere in folder * cleaning * fixes * remove focus-ring * full screen * small fix * consistent highlight color * improved preview * performance improvements * sparser data transfers * sparser data transfers * show popup once data is loaded * fix routing control size * fix * sparse desktop build * remove custom ign styles * use new endpoint for openhikingmap * strip native menu * reorder context menu items * route full support * route - track conversion * create route file action * route export, filter out anchors at high zoom level * clarify name handling * move hide & center to view * routes continued * update docs * fix power format, closes #378 * lint fixes * fix display of additional data with gaps, closes #361 * fix linting issues * fix import modules * fix multidrag * change base to resolve * fix type errors * fix layer typings * fix last type error * each keys * improve typings * deploy to cloudflare --------- Co-authored-by: vcoppe <vcoppe@hexaly.com>
This commit is contained in:
1 parent
6a0d434371
commit
8fe7d8d64d
484 files changed
+53949
-41152
No files matched your search
@@ -0,0 +1,18 @@
|
||||
import type { Backend } from './types';
|
||||
|
||||
export type { Backend } from './types';
|
||||
|
||||
/** Whether the page runs in the desktop app, which has the engine in its own process. */
|
||||
export function inDesktopApp() {
|
||||
return typeof window !== 'undefined' && '__TAURI_INTERNALS__' in window;
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the engine of the files: the one of the desktop app when the page runs in it, the
|
||||
* WebAssembly module otherwise.
|
||||
*/
|
||||
export async function loadBackend(): Promise<Backend> {
|
||||
return inDesktopApp()
|
||||
? (await import('./tauri')).createTauriBackend()
|
||||
: (await import('./wasm')).createWasmBackend();
|
||||
}
|
||||
@@ -0,0 +1,253 @@
|
||||
import { invoke } from '@tauri-apps/api/core';
|
||||
import { listen } from '@tauri-apps/api/event';
|
||||
import type { Outcome, RouteAttributes, StorageOpened } from 'gpx-wasm';
|
||||
import type { Backend, FolderEntry, WorkspaceState } from './types';
|
||||
|
||||
/** An array that a command returns as its bytes. */
|
||||
const array = async <T>(
|
||||
command: string,
|
||||
type: { new (buffer: ArrayBuffer): T },
|
||||
args?: Record<string, unknown>
|
||||
) => new type(await invoke<ArrayBuffer>(command, args));
|
||||
|
||||
/** Like `array`, for the arrays that can be absent: the first byte tells whether they are there. */
|
||||
const optionalArray = async <T>(
|
||||
command: string,
|
||||
type: { new (buffer: ArrayBuffer): T },
|
||||
args?: Record<string, unknown>
|
||||
) => {
|
||||
const bytes = await invoke<ArrayBuffer>(command, args);
|
||||
return new Uint8Array(bytes)[0] === 1 ? new type(bytes.slice(1)) : undefined;
|
||||
};
|
||||
|
||||
const category = (c?: RouteAttributes['surface']) =>
|
||||
c && { starts: Array.from(c.starts), values: Array.from(c.values), names: c.names };
|
||||
|
||||
/**
|
||||
* The engine in the Rust process of the desktop app, reached through its commands (see
|
||||
* `tauri/src/commands`). Typed arrays are returned as bytes, little-endian.
|
||||
*/
|
||||
export async function createTauriBackend(): Promise<Backend> {
|
||||
const f64 = (command: string, args?: Record<string, unknown>) =>
|
||||
array(command, Float64Array, args);
|
||||
const u32 = (command: string) => array(command, Uint32Array);
|
||||
const u8 = (command: string) => array(command, Uint8Array);
|
||||
const f64Optional = (command: string) => optionalArray(command, Float64Array);
|
||||
|
||||
return {
|
||||
select: (fileIds, mode) => invoke('select', { fileIds, mode }),
|
||||
select_all: () => invoke('select_all'),
|
||||
arrow_select: (down, add) => invoke('arrow_select', { down, add }),
|
||||
select_routes: (fileId, routeIds, mode) =>
|
||||
invoke('select_routes', { fileId, routeIds, mode }),
|
||||
select_tracks: (fileId, trackIds, mode) =>
|
||||
invoke('select_tracks', { fileId, trackIds, mode }),
|
||||
select_segments: (fileId, trackId, segmentIds, mode) =>
|
||||
invoke('select_segments', { fileId, trackId, segmentIds, mode }),
|
||||
select_waypoint_group: (fileId, mode) => invoke('select_waypoint_group', { fileId, mode }),
|
||||
select_waypoints: (fileId, waypointIds, mode) =>
|
||||
invoke('select_waypoints', { fileId, waypointIds, mode }),
|
||||
|
||||
undo: () => invoke('undo'),
|
||||
redo: () => invoke('redo'),
|
||||
copy: () => invoke('copy'),
|
||||
cut: () => invoke('cut'),
|
||||
paste: () => invoke('paste'),
|
||||
|
||||
new_file: (name, lng, lat, ele, route) =>
|
||||
invoke('new_file', { name, lng, lat, ele, route }),
|
||||
load_files: (files) => {
|
||||
const data = new Uint8Array(files.reduce((sum, file) => sum + file.data.length, 0));
|
||||
let offset = 0;
|
||||
for (const file of files) {
|
||||
data.set(file.data, offset);
|
||||
offset += file.data.length;
|
||||
}
|
||||
// headers are ASCII
|
||||
const header = (value: unknown) => encodeURIComponent(JSON.stringify(value));
|
||||
return invoke('load_files', data, {
|
||||
headers: {
|
||||
lengths: header(files.map((file) => file.data.length)),
|
||||
names: header(files.map((file) => file.name)),
|
||||
},
|
||||
});
|
||||
},
|
||||
duplicate: () => invoke('duplicate'),
|
||||
delete: (wholeFiles) => invoke('delete', { wholeFiles }),
|
||||
delete_all: () => invoke('delete_all'),
|
||||
reorder: (fileIds, index) => invoke('reorder', { fileIds, index }),
|
||||
// an infinite index is the end of the list, which JSON cannot tell
|
||||
move_elements: (what, to) =>
|
||||
invoke('move_elements', {
|
||||
what,
|
||||
to: { ...to, index: Math.min(to.index, Number.MAX_SAFE_INTEGER) },
|
||||
}),
|
||||
metadata: (name, desc) => invoke('metadata', { name, desc }),
|
||||
style: (color, opacity, width) => invoke('style', { color, opacity, width }),
|
||||
convert: () => invoke('convert'),
|
||||
new_route: () => invoke('new_route'),
|
||||
new_track: () => invoke('new_track'),
|
||||
new_track_segment: () => invoke('new_track_segment'),
|
||||
|
||||
new_waypoint: (lng, lat, ele, name, desc, icon, link) =>
|
||||
invoke('new_waypoint', { lng, lat, ele, name, desc, icon, link }),
|
||||
update_waypoint: (fileId, waypointId, lng, lat, ele, name, desc, icon, link) =>
|
||||
invoke('update_waypoint', {
|
||||
fileId,
|
||||
waypointId,
|
||||
lng,
|
||||
lat,
|
||||
ele,
|
||||
name,
|
||||
desc,
|
||||
icon,
|
||||
link,
|
||||
}),
|
||||
move_waypoint: (fileId, waypointId, lng, lat, ele) =>
|
||||
invoke('move_waypoint', { fileId, waypointId, lng, lat, ele }),
|
||||
delete_waypoint: (fileId, waypointId) => invoke('delete_waypoint', { fileId, waypointId }),
|
||||
|
||||
reverse: () => invoke('reverse'),
|
||||
extract: () => invoke('extract'),
|
||||
round_trip: () => invoke('round_trip'),
|
||||
elevation: (ele) => invoke('elevation', { ele: Array.from(ele) }),
|
||||
change_timestamps: (startTime, speed, ratio) =>
|
||||
invoke('change_timestamps', { startTime, speed, ratio }),
|
||||
create_artificial_timestamps: (startTime, totalTime) =>
|
||||
invoke('create_artificial_timestamps', { startTime, totalTime }),
|
||||
clean: (west, south, east, north, inside, trkpt, wpt) =>
|
||||
invoke('clean', {
|
||||
west,
|
||||
south,
|
||||
east,
|
||||
north,
|
||||
cleanType: inside ? 'inside' : 'outside',
|
||||
trkpt,
|
||||
wpt,
|
||||
}),
|
||||
merge: (mergeType, removeGaps) => invoke('merge', { mergeType, removeGaps }),
|
||||
reduce: (tolerance) => invoke('reduce', { tolerance }),
|
||||
crop: (start, end) => invoke('crop', { start, end }),
|
||||
split: (revision, at, splitType) => invoke('split', { revision, at, splitType }),
|
||||
route: (revision, start, end, lng, lat, ele, attributes, anchors) =>
|
||||
invoke('route', {
|
||||
revision,
|
||||
start,
|
||||
end,
|
||||
lng: Array.from(lng),
|
||||
lat: Array.from(lat),
|
||||
ele: Array.from(ele),
|
||||
attributes: {
|
||||
surface: category(attributes.surface),
|
||||
highway: category(attributes.highway),
|
||||
sacScale: category(attributes.sacScale),
|
||||
mtbScale: category(attributes.mtbScale),
|
||||
},
|
||||
anchors: Array.from(anchors),
|
||||
}),
|
||||
insert_anchor: (revision, lng, lat) => invoke('insert_anchor', { revision, lng, lat }),
|
||||
change_loop_start: (revision, index) => invoke('change_loop_start', { revision, index }),
|
||||
|
||||
can_undo: () => invoke('can_undo'),
|
||||
can_redo: () => invoke('can_redo'),
|
||||
can_paste: () => invoke('can_paste'),
|
||||
clipboard: async () => (await invoke('clipboard')) ?? undefined,
|
||||
selection: () => invoke('selection'),
|
||||
file_order: () => invoke('file_order'),
|
||||
file_structure: async (fileId) => (await invoke('file_structure', { fileId })) ?? undefined,
|
||||
file_statistics: async (fileId) =>
|
||||
(await invoke('file_statistics', { fileId })) ?? undefined,
|
||||
waypoint: async (fileId, waypointId) =>
|
||||
(await invoke('waypoint', { fileId, waypointId })) ?? undefined,
|
||||
trackpoint: async (fileId, segmentId, index) =>
|
||||
(await invoke('trackpoint', { fileId, segmentId, index })) ?? undefined,
|
||||
export_file: async (fileId, time, hr, cad, atemp, power, osm) => {
|
||||
const file = await optionalArray('export_file', Uint8Array, {
|
||||
fileId,
|
||||
time,
|
||||
hr,
|
||||
cad,
|
||||
atemp,
|
||||
power,
|
||||
osm,
|
||||
});
|
||||
return file as Uint8Array<ArrayBuffer> | undefined;
|
||||
},
|
||||
exportable_data: (fileIds) => invoke('exportable_data', { fileIds }),
|
||||
reduction_distances: () => f64('reduction_distances'),
|
||||
segment_coordinates: (segmentId) => f64('segment_coordinates', { segmentId }),
|
||||
waypoint_coordinates: (fileId) => f64('waypoint_coordinates', { fileId }),
|
||||
|
||||
selection_statistics: () => invoke('selection_statistics'),
|
||||
slice_statistics: async (start, end) =>
|
||||
(await invoke('slice_statistics', { start, end })) ?? undefined,
|
||||
total_distance: () => f64('total_distance'),
|
||||
lng: () => f64('lng'),
|
||||
lat: () => f64('lat'),
|
||||
ele: () => f64('ele'),
|
||||
speed: () => f64Optional('speed'),
|
||||
hr: () => f64Optional('hr'),
|
||||
cad: () => f64Optional('cad'),
|
||||
atemp: () => f64Optional('atemp'),
|
||||
power: () => f64Optional('power'),
|
||||
slope_segment_starts: () => u32('slope_segment_starts'),
|
||||
slope_segment_slopes: () => f64('slope_segment_slopes'),
|
||||
selection_point: async (index) => (await invoke('selection_point', { index })) ?? undefined,
|
||||
surface_starts: () => u32('surface_starts'),
|
||||
surface_values: () => u8('surface_values'),
|
||||
surfaces: () => invoke('surfaces'),
|
||||
highway_starts: () => u32('highway_starts'),
|
||||
highway_values: () => u8('highway_values'),
|
||||
highways: () => invoke('highways'),
|
||||
sac_scale_starts: () => u32('sac_scale_starts'),
|
||||
sac_scale_values: () => u8('sac_scale_values'),
|
||||
sac_scales: () => invoke('sac_scales'),
|
||||
mtb_scale_starts: () => u32('mtb_scale_starts'),
|
||||
mtb_scale_values: () => u8('mtb_scale_values'),
|
||||
mtb_scales: () => invoke('mtb_scales'),
|
||||
anchor_indices: () => u32('anchor_indices'),
|
||||
anchor_zooms: () => u8('anchor_zooms'),
|
||||
segment_starts: () => u32('segment_starts'),
|
||||
segment_ids: () => invoke('segment_ids'),
|
||||
routing_revision: () => invoke('routing_revision'),
|
||||
|
||||
desktop: {
|
||||
workspace: () => invoke<WorkspaceState>('workspace_state'),
|
||||
openFiles: () => invoke<Outcome>('open_files'),
|
||||
openPaths: (paths, preview) => invoke<Outcome>('open_paths', { paths, preview }),
|
||||
keepFiles: (fileIds) => invoke('keep_files', { fileIds }),
|
||||
openFolder: (unsaved) => invoke<Outcome>('open_folder', { unsaved }),
|
||||
closeFolder: (unsaved) => invoke<Outcome>('close_folder', { unsaved }),
|
||||
closeFiles: (fileIds, unsaved) => invoke<Outcome>('close_files', { fileIds, unsaved }),
|
||||
saveFiles: (fileIds) => invoke<boolean>('save_files', { fileIds }),
|
||||
saveFileAs: (fileId) => invoke<boolean>('save_file_as', { fileId }),
|
||||
reloadFiles: (fileIds) => invoke<Outcome>('reload_files', { fileIds }),
|
||||
exportFiles: (fileIds, options) =>
|
||||
invoke<boolean>('export_files', { fileIds, options }),
|
||||
listFolder: (path) => invoke<FolderEntry[]>('list_folder', { path }),
|
||||
openUrl: (url) => invoke('open_url', { url }),
|
||||
newFile: (name, folder, route) => invoke<Outcome>('new_file', { name, folder, route }),
|
||||
createFolder: (parent, name) => invoke<string>('create_folder', { parent, name }),
|
||||
renamePath: (path, name) => invoke('rename_path', { path, name }),
|
||||
renameFile: (fileId, name) => invoke<boolean>('rename_file', { fileId, name }),
|
||||
movePaths: (paths, folder) => invoke('move_paths', { paths, folder }),
|
||||
deletePaths: (paths) => invoke<Outcome>('delete_paths', { paths }),
|
||||
revealPath: (path) => invoke('reveal_path', { path }),
|
||||
listen: async (onEngineChanged, onWorkspaceChanged, onFilesOpened, onFolderChanged) => {
|
||||
await listen<Outcome>('files-opened', (event) => onFilesOpened(event.payload));
|
||||
await listen<Outcome>('engine-changed', (event) => onEngineChanged(event.payload));
|
||||
await listen<WorkspaceState>('workspace-changed', (event) =>
|
||||
onWorkspaceChanged(event.payload)
|
||||
);
|
||||
await listen<string[]>('folder-changed', () => onFolderChanged());
|
||||
},
|
||||
},
|
||||
|
||||
importsLegacyData: false,
|
||||
open_storage: () => invoke<StorageOpened>('open_storage'),
|
||||
flush_storage: () => invoke('flush_storage'),
|
||||
sync_storage: () => invoke('sync_storage'),
|
||||
set_setting: (key, value) => invoke('set_setting', { key, value }),
|
||||
delete_setting: (key) => invoke('delete_setting', { key }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,349 @@
|
||||
import type {
|
||||
Clipboard,
|
||||
FileStructure,
|
||||
GlobalStatistics,
|
||||
MoveTarget,
|
||||
Outcome,
|
||||
RouteAttributes,
|
||||
Selection,
|
||||
SelectionPoint,
|
||||
StorageOpened,
|
||||
TrackpointDetails,
|
||||
WaypointDetails,
|
||||
} from 'gpx-wasm';
|
||||
import type { ExportOptions, MergeType, SelectMode, SplitType } from '../types';
|
||||
|
||||
/** What the desktop app knows of a file of the engine and the file system. */
|
||||
export type FileStatus = {
|
||||
/** Where the file is on the disk, absent for a file that only is in the engine. */
|
||||
path?: string;
|
||||
/**
|
||||
* The folder where the file is written the first time it is saved, for a file that is not on
|
||||
* the disk and comes from (or was made in) the open folder.
|
||||
*/
|
||||
folder?: string;
|
||||
/**
|
||||
* The file is not the one on the disk: it has edits, is not on the disk, or the file on the
|
||||
* disk is not the one that was read (it was replaced, or is gone).
|
||||
*/
|
||||
dirty: boolean;
|
||||
/** The file on the disk was replaced by something else: saving overwrites it. */
|
||||
replaced: boolean;
|
||||
/** The file on the disk is gone. */
|
||||
missing: boolean;
|
||||
/** The file is open as a preview (a single click in the tree), which the next one replaces. */
|
||||
preview: boolean;
|
||||
};
|
||||
|
||||
/** An entry of the tree of the open folder: a folder, or a GPX file. */
|
||||
export type FolderEntry = {
|
||||
name: string;
|
||||
path: string;
|
||||
isDir: boolean;
|
||||
};
|
||||
|
||||
/** What to do with the files of a folder that have unsaved edits when it is closed. */
|
||||
export type UnsavedChoice = 'save' | 'discard';
|
||||
|
||||
export type WorkspaceState = {
|
||||
/** The folder that is open, and watched. */
|
||||
folder?: string;
|
||||
files: Record<string, FileStatus>;
|
||||
};
|
||||
|
||||
/**
|
||||
* What the desktop app adds: its files are linked to files of the file system. Only the backend of
|
||||
* the desktop app has it.
|
||||
*/
|
||||
export interface DesktopFiles {
|
||||
workspace(): Promise<WorkspaceState>;
|
||||
/** Opens the files that the user picks, which get selected. */
|
||||
openFiles(): Promise<Outcome>;
|
||||
/**
|
||||
* Opens files of the file system by their path, like the ones of the tree of the folder. With
|
||||
* `preview`, a single file is open as a preview: the next preview replaces it, until it is
|
||||
* edited or opened for good. Otherwise they are open for good.
|
||||
*/
|
||||
openPaths(paths: string[], preview?: boolean): Promise<Outcome>;
|
||||
/** The files are open for good: the preview among them is not a preview anymore. */
|
||||
keepFiles(fileIds: string[]): Promise<void>;
|
||||
/**
|
||||
* Opens the folder that the user picks, which is watched. Its files are not opened: they are
|
||||
* in its tree (`listFolder`). The folder that was open is closed with its files (see
|
||||
* `closeFiles` for `unsaved`).
|
||||
*/
|
||||
openFolder(unsaved?: UnsavedChoice): Promise<Outcome>;
|
||||
/** Closes the open folder: it is not watched anymore, and its files are closed. */
|
||||
closeFolder(unsaved?: UnsavedChoice): Promise<Outcome>;
|
||||
/**
|
||||
* Closes files. What to do with the ones that have unsaved edits: `save` them first (the user
|
||||
* is asked where to put the ones that have no place), `discard` the edits, or keep them open
|
||||
* when it is not said.
|
||||
*/
|
||||
closeFiles(fileIds: string[], unsaved?: UnsavedChoice): Promise<Outcome>;
|
||||
/**
|
||||
* Writes files to the disk, replacing what is there (the user is asked where to put the ones
|
||||
* that have no place: a file, or a folder for several of them). Resolves to false if the user
|
||||
* cancelled.
|
||||
*/
|
||||
saveFiles(fileIds: string[]): Promise<boolean>;
|
||||
/** Writes a file where the user says, which is where it is from then on. False if cancelled. */
|
||||
saveFileAs(fileId: string): Promise<boolean>;
|
||||
/** Reads files again from the disk: their edits are lost (one undo step). */
|
||||
reloadFiles(fileIds: string[]): Promise<Outcome>;
|
||||
/**
|
||||
* Writes copies of files where the user says (a file, or a folder for several). The files stay
|
||||
* as they are. False if the user cancelled.
|
||||
*/
|
||||
exportFiles(fileIds: string[], options: ExportOptions): Promise<boolean>;
|
||||
/** The folders and GPX files in a folder of the open folder (the open folder by default). */
|
||||
listFolder(path?: string): Promise<FolderEntry[]>;
|
||||
/** Opens a web page (or an email to write) in the app of the system for it. */
|
||||
openUrl(url: string): Promise<void>;
|
||||
/**
|
||||
* Makes a new file, written at once in `folder` (a folder of the open folder), and selects it.
|
||||
* With `route`, it starts with an empty route.
|
||||
*/
|
||||
newFile(name: string, folder: string, route: boolean): Promise<Outcome>;
|
||||
/** Makes a folder in a folder of the open folder (numbered if the name is taken): its path. */
|
||||
createFolder(parent: string, name: string): Promise<string>;
|
||||
/**
|
||||
* Renames a file or a folder of the open folder, on the disk only (an open file keeps its name).
|
||||
* Not undoable.
|
||||
*/
|
||||
renamePath(path: string, name: string): Promise<void>;
|
||||
/**
|
||||
* Renames the file on the disk of an open file, next to where it is; its name in the engine
|
||||
* stays. Not undoable. False for a file that is not on the disk.
|
||||
*/
|
||||
renameFile(fileId: string, name: string): Promise<boolean>;
|
||||
/** Moves files and folders of the open folder into a folder of it. */
|
||||
movePaths(paths: string[], folder: string): Promise<void>;
|
||||
/**
|
||||
* Moves files and folders of the open folder to the trash. The open files among them are
|
||||
* closed, unless they have edits.
|
||||
*/
|
||||
deletePaths(paths: string[]): Promise<Outcome>;
|
||||
/** Shows a file or a folder in the file manager of the system. */
|
||||
revealPath(path: string): Promise<void>;
|
||||
/**
|
||||
* Tells when the engine changed without being asked, because the files on the disk did (the
|
||||
* outcome to apply), when the status of the files changed, when files were opened with the
|
||||
* app from the system (the outcome to apply, which selected them), and when something changed
|
||||
* in the open folder (the tree of its files is to be read again).
|
||||
*/
|
||||
listen(
|
||||
onEngineChanged: (outcome: Outcome) => void,
|
||||
onWorkspaceChanged: (workspace: WorkspaceState) => void,
|
||||
onFilesOpened: (outcome: Outcome) => void,
|
||||
onFolderChanged: () => void
|
||||
): Promise<void>;
|
||||
}
|
||||
|
||||
/**
|
||||
* What the facade needs of the engine of the files, wherever it runs: the WASM module in the
|
||||
* browser (`wasm.ts`), or the Rust process of the desktop app, through its commands (`tauri.ts`).
|
||||
* Both give the same results: see `gpx-rs/src/api` for what each function does.
|
||||
*
|
||||
* Everything is asynchronous, because the desktop app is reached through messages. Ids are
|
||||
* hyphenated UUID strings, the arrays of numbers are typed arrays, and what the functions that
|
||||
* edit the files or change the selection return is an `Outcome`.
|
||||
*/
|
||||
export interface Backend {
|
||||
// Selection
|
||||
select(fileIds: string[], mode: SelectMode): Promise<Outcome>;
|
||||
select_all(): Promise<Outcome>;
|
||||
arrow_select(down: boolean, add: boolean): Promise<Outcome>;
|
||||
select_routes(fileId: string, routeIds: string[], mode: SelectMode): Promise<Outcome>;
|
||||
select_tracks(fileId: string, trackIds: string[], mode: SelectMode): Promise<Outcome>;
|
||||
select_segments(
|
||||
fileId: string,
|
||||
trackId: string,
|
||||
segmentIds: string[],
|
||||
mode: SelectMode
|
||||
): Promise<Outcome>;
|
||||
select_waypoint_group(fileId: string, mode: SelectMode): Promise<Outcome>;
|
||||
select_waypoints(fileId: string, waypointIds: string[], mode: SelectMode): Promise<Outcome>;
|
||||
|
||||
// History and clipboard
|
||||
undo(): Promise<Outcome>;
|
||||
redo(): Promise<Outcome>;
|
||||
copy(): Promise<Outcome>;
|
||||
cut(): Promise<Outcome>;
|
||||
paste(): Promise<Outcome>;
|
||||
|
||||
// Files
|
||||
new_file(
|
||||
name: string,
|
||||
lng: number | undefined,
|
||||
lat: number | undefined,
|
||||
ele: number | undefined,
|
||||
route: boolean
|
||||
): Promise<Outcome>;
|
||||
load_files(files: { data: Uint8Array; name: string }[]): Promise<Outcome>;
|
||||
duplicate(): Promise<Outcome>;
|
||||
delete(wholeFiles: boolean): Promise<Outcome>;
|
||||
delete_all(): Promise<Outcome>;
|
||||
reorder(fileIds: string[], index: number): Promise<Outcome>;
|
||||
move_elements(what: Selection, to: MoveTarget): Promise<Outcome>;
|
||||
metadata(name: string, desc: string): Promise<Outcome>;
|
||||
style(color?: string, opacity?: number, width?: number): Promise<Outcome>;
|
||||
convert(): Promise<Outcome>;
|
||||
new_route(): Promise<Outcome>;
|
||||
new_track(): Promise<Outcome>;
|
||||
new_track_segment(): Promise<Outcome>;
|
||||
|
||||
// Waypoints
|
||||
new_waypoint(
|
||||
lng: number,
|
||||
lat: number,
|
||||
ele: number,
|
||||
name: string,
|
||||
desc: string,
|
||||
icon: string,
|
||||
link: string
|
||||
): Promise<Outcome>;
|
||||
update_waypoint(
|
||||
fileId: string,
|
||||
waypointId: string,
|
||||
lng: number,
|
||||
lat: number,
|
||||
ele: number,
|
||||
name: string,
|
||||
desc: string,
|
||||
icon: string,
|
||||
link: string
|
||||
): Promise<Outcome>;
|
||||
move_waypoint(
|
||||
fileId: string,
|
||||
waypointId: string,
|
||||
lng: number,
|
||||
lat: number,
|
||||
ele: number
|
||||
): Promise<Outcome>;
|
||||
delete_waypoint(fileId: string, waypointId: string): Promise<Outcome>;
|
||||
|
||||
// Tools
|
||||
reverse(): Promise<Outcome>;
|
||||
extract(): Promise<Outcome>;
|
||||
round_trip(): Promise<Outcome>;
|
||||
elevation(ele: Float64Array): Promise<Outcome>;
|
||||
change_timestamps(startTime: number, speed: number, ratio: number): Promise<Outcome>;
|
||||
create_artificial_timestamps(startTime: number, totalTime: number): Promise<Outcome>;
|
||||
clean(
|
||||
west: number,
|
||||
south: number,
|
||||
east: number,
|
||||
north: number,
|
||||
inside: boolean,
|
||||
trackpoints: boolean,
|
||||
waypoints: boolean
|
||||
): Promise<Outcome>;
|
||||
merge(type: MergeType, removeGaps: boolean): Promise<Outcome>;
|
||||
reduce(tolerance: number): Promise<Outcome>;
|
||||
crop(start: number, end: number): Promise<Outcome>;
|
||||
split(revision: number, at: number, type: SplitType): Promise<Outcome>;
|
||||
route(
|
||||
revision: number,
|
||||
start: number,
|
||||
end: number,
|
||||
lng: Float64Array,
|
||||
lat: Float64Array,
|
||||
ele: Float64Array,
|
||||
attributes: RouteAttributes,
|
||||
anchors: Uint32Array
|
||||
): Promise<Outcome>;
|
||||
insert_anchor(revision: number, lng: number, lat: number): Promise<Outcome>;
|
||||
change_loop_start(revision: number, index: number): Promise<Outcome>;
|
||||
|
||||
// The files and the selection
|
||||
can_undo(): Promise<boolean>;
|
||||
can_redo(): Promise<boolean>;
|
||||
can_paste(): Promise<boolean>;
|
||||
clipboard(): Promise<Clipboard | undefined>;
|
||||
selection(): Promise<Selection>;
|
||||
file_order(): Promise<string[]>;
|
||||
file_structure(fileId: string): Promise<FileStructure | undefined>;
|
||||
file_statistics(fileId: string): Promise<GlobalStatistics | undefined>;
|
||||
waypoint(fileId: string, waypointId: string): Promise<WaypointDetails | undefined>;
|
||||
trackpoint(
|
||||
fileId: string,
|
||||
segmentId: string,
|
||||
index: number
|
||||
): Promise<TrackpointDetails | undefined>;
|
||||
/** A file as GPX (UTF-8 bytes), `undefined` if it does not exist. */
|
||||
export_file(
|
||||
fileId: string,
|
||||
time: boolean,
|
||||
hr: boolean,
|
||||
cad: boolean,
|
||||
atemp: boolean,
|
||||
power: boolean,
|
||||
osm: boolean
|
||||
): Promise<Uint8Array<ArrayBuffer> | undefined>;
|
||||
exportable_data(fileIds: string[]): Promise<number>;
|
||||
reduction_distances(): Promise<Float64Array>;
|
||||
segment_coordinates(segmentId: string): Promise<Float64Array>;
|
||||
waypoint_coordinates(fileId: string): Promise<Float64Array>;
|
||||
|
||||
// The statistics of the selection
|
||||
selection_statistics(): Promise<GlobalStatistics | undefined>;
|
||||
slice_statistics(start: number, end: number): Promise<GlobalStatistics | undefined>;
|
||||
total_distance(): Promise<Float64Array>;
|
||||
lng(): Promise<Float64Array>;
|
||||
lat(): Promise<Float64Array>;
|
||||
ele(): Promise<Float64Array>;
|
||||
speed(): Promise<Float64Array | undefined>;
|
||||
hr(): Promise<Float64Array | undefined>;
|
||||
cad(): Promise<Float64Array | undefined>;
|
||||
atemp(): Promise<Float64Array | undefined>;
|
||||
power(): Promise<Float64Array | undefined>;
|
||||
slope_segment_starts(): Promise<Uint32Array>;
|
||||
slope_segment_slopes(): Promise<Float64Array>;
|
||||
selection_point(index: number): Promise<SelectionPoint | undefined>;
|
||||
surface_starts(): Promise<Uint32Array>;
|
||||
surface_values(): Promise<Uint8Array>;
|
||||
surfaces(): Promise<string[]>;
|
||||
highway_starts(): Promise<Uint32Array>;
|
||||
highway_values(): Promise<Uint8Array>;
|
||||
highways(): Promise<string[]>;
|
||||
sac_scale_starts(): Promise<Uint32Array>;
|
||||
sac_scale_values(): Promise<Uint8Array>;
|
||||
sac_scales(): Promise<string[]>;
|
||||
mtb_scale_starts(): Promise<Uint32Array>;
|
||||
mtb_scale_values(): Promise<Uint8Array>;
|
||||
mtb_scales(): Promise<string[]>;
|
||||
anchor_indices(): Promise<Uint32Array>;
|
||||
anchor_zooms(): Promise<Uint8Array>;
|
||||
segment_starts(): Promise<Uint32Array>;
|
||||
segment_ids(): Promise<string[]>;
|
||||
routing_revision(): Promise<number>;
|
||||
|
||||
/** Present when the files are linked to the file system (the desktop app). */
|
||||
readonly desktop?: DesktopFiles;
|
||||
|
||||
// Storage
|
||||
/**
|
||||
* Whether the files that the previous versions of the app kept in the browser can be imported
|
||||
* (they are in the IndexedDB of the browser).
|
||||
*/
|
||||
readonly importsLegacyData: boolean;
|
||||
/**
|
||||
* Opens the storage: the files that it holds are put in the engine, and the changes of the
|
||||
* files are kept from then on. `onSaved` is called after the files were written, `onBehind`
|
||||
* when a write was refused because another window wrote since (call `sync_storage` then), and
|
||||
* `onNewer` when what is stored comes from a newer version of the app.
|
||||
*/
|
||||
open_storage(
|
||||
name: string,
|
||||
onSaved: () => void,
|
||||
onBehind: () => void,
|
||||
onNewer: () => void
|
||||
): Promise<StorageOpened>;
|
||||
/** Resolves when what was changed has been written to the storage. */
|
||||
flush_storage(): Promise<void>;
|
||||
/** Reads the files again if another window wrote them since, and tells what changed. */
|
||||
sync_storage(): Promise<Outcome>;
|
||||
set_setting(key: string, json: string): Promise<void>;
|
||||
delete_setting(key: string): Promise<void>;
|
||||
}
|
||||
@@ -0,0 +1,177 @@
|
||||
import type { Backend } from './types';
|
||||
import type { MergeType, SelectMode, SplitType } from '../types';
|
||||
|
||||
type Wasm = typeof import('gpx-wasm');
|
||||
|
||||
/** A call of the module, which is synchronous, as an asynchronous one. */
|
||||
const lift =
|
||||
<A extends unknown[], R>(f: (...args: A) => R) =>
|
||||
async (...args: A): Promise<R> =>
|
||||
f(...args);
|
||||
|
||||
/** Hyphenated UUID strings to the concatenated 16-byte form the module takes. */
|
||||
function idsToBytes(ids: string[]): Uint8Array {
|
||||
const bytes = new Uint8Array(ids.length * 16);
|
||||
ids.forEach((id, i) => {
|
||||
const hex = id.replaceAll('-', '');
|
||||
for (let j = 0; j < 16; j++) {
|
||||
bytes[i * 16 + j] = parseInt(hex.slice(2 * j, 2 * j + 2), 16);
|
||||
}
|
||||
});
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/** The engine in the page, as the WebAssembly module of `wasm`. */
|
||||
export async function createWasmBackend(): Promise<Backend> {
|
||||
const w: Wasm = await import('gpx-wasm');
|
||||
w.start();
|
||||
|
||||
const mode = (m: SelectMode) =>
|
||||
({ replace: w.SelectMode.Replace, add: w.SelectMode.Add, toggle: w.SelectMode.Toggle })[m];
|
||||
const splitType = (t: SplitType) =>
|
||||
({
|
||||
files: w.SplitType.Files,
|
||||
routes: w.SplitType.Routes,
|
||||
tracks: w.SplitType.Tracks,
|
||||
segments: w.SplitType.Segments,
|
||||
})[t];
|
||||
const mergeType = (t: MergeType) => (t === 'connect' ? w.MergeType.Connect : w.MergeType.Group);
|
||||
|
||||
return {
|
||||
select: lift((ids, m) => w.select(idsToBytes(ids), mode(m))),
|
||||
select_all: lift(w.select_all),
|
||||
arrow_select: lift(w.arrow_select),
|
||||
select_routes: lift((file, ids, m) => w.select_routes(file, idsToBytes(ids), mode(m))),
|
||||
select_tracks: lift((file, ids, m) => w.select_tracks(file, idsToBytes(ids), mode(m))),
|
||||
select_segments: lift((file, track, ids, m) =>
|
||||
w.select_segments(file, track, idsToBytes(ids), mode(m))
|
||||
),
|
||||
select_waypoint_group: lift((file, m) => w.select_waypoint_group(file, mode(m))),
|
||||
select_waypoints: lift((file, ids, m) =>
|
||||
w.select_waypoints(file, idsToBytes(ids), mode(m))
|
||||
),
|
||||
|
||||
undo: lift(w.undo),
|
||||
redo: lift(w.redo),
|
||||
copy: lift(w.copy),
|
||||
cut: lift(w.cut),
|
||||
paste: lift(w.paste),
|
||||
|
||||
new_file: lift(w.new_file),
|
||||
load_files: lift((files) => {
|
||||
const lengths = Uint32Array.from(files.map((file) => file.data.length));
|
||||
const data = new Uint8Array(lengths.reduce((sum, length) => sum + length, 0));
|
||||
let offset = 0;
|
||||
for (const file of files) {
|
||||
data.set(file.data, offset);
|
||||
offset += file.data.length;
|
||||
}
|
||||
return w.load_files(
|
||||
data,
|
||||
lengths,
|
||||
files.map((file) => file.name)
|
||||
);
|
||||
}),
|
||||
duplicate: lift(w.duplicate),
|
||||
delete: lift(w._delete),
|
||||
delete_all: lift(w.delete_all),
|
||||
reorder: lift((ids, index) => w.reorder(idsToBytes(ids), index)),
|
||||
move_elements: lift(w.move_elements),
|
||||
metadata: lift(w.metadata),
|
||||
style: lift(w.style),
|
||||
convert: lift(w.convert),
|
||||
new_route: lift(w.new_route),
|
||||
new_track: lift(w.new_track),
|
||||
new_track_segment: lift(w.new_track_segment),
|
||||
|
||||
new_waypoint: lift(w.new_waypoint),
|
||||
update_waypoint: lift(w.update_waypoint),
|
||||
move_waypoint: lift(w.move_waypoint),
|
||||
delete_waypoint: lift(w.delete_waypoint),
|
||||
|
||||
reverse: lift(w.reverse),
|
||||
extract: lift(w.extract),
|
||||
round_trip: lift(w.round_trip),
|
||||
elevation: lift(w.elevation),
|
||||
change_timestamps: lift(w.changeTimestamps),
|
||||
create_artificial_timestamps: lift(w.createArtificialTimestamps),
|
||||
clean: lift((west, south, east, north, inside, trackpoints, waypoints) =>
|
||||
w.clean(
|
||||
west,
|
||||
south,
|
||||
east,
|
||||
north,
|
||||
inside ? w.CleanType.Inside : w.CleanType.Outside,
|
||||
trackpoints,
|
||||
waypoints
|
||||
)
|
||||
),
|
||||
merge: lift((type, removeGaps) => w.merge(mergeType(type), removeGaps)),
|
||||
reduce: lift(w.reduce),
|
||||
crop: lift(w.crop),
|
||||
split: lift((revision, at, type) => w.split(revision, at, splitType(type))),
|
||||
route: lift(w.route),
|
||||
insert_anchor: lift(w.insert_anchor),
|
||||
change_loop_start: lift(w.change_loop_start),
|
||||
|
||||
can_undo: lift(w.can_undo),
|
||||
can_redo: lift(w.can_redo),
|
||||
can_paste: lift(w.can_paste),
|
||||
clipboard: lift(w.clipboard),
|
||||
selection: lift(w.selection),
|
||||
file_order: lift(w.file_order),
|
||||
file_structure: lift(w.file_structure),
|
||||
file_statistics: lift(w.file_statistics),
|
||||
waypoint: lift(w.waypoint),
|
||||
trackpoint: lift(w.trackpoint),
|
||||
// a copy out of the memory of the engine, so a plain ArrayBuffer
|
||||
export_file: lift(
|
||||
(...args: Parameters<Backend['export_file']>) =>
|
||||
w.export_file(...args) as Uint8Array<ArrayBuffer> | undefined
|
||||
),
|
||||
exportable_data: lift((ids) => w.exportable_data(idsToBytes(ids))),
|
||||
reduction_distances: lift(w.reduction_distances),
|
||||
segment_coordinates: lift(w.segment_coordinates),
|
||||
waypoint_coordinates: lift(w.waypoint_coordinates),
|
||||
|
||||
selection_statistics: lift(w.selection_statistics),
|
||||
slice_statistics: lift(w.slice_statistics),
|
||||
total_distance: lift(w.total_distance),
|
||||
lng: lift(w.lng),
|
||||
lat: lift(w.lat),
|
||||
ele: lift(w.ele),
|
||||
speed: lift(w.speed),
|
||||
hr: lift(w.hr),
|
||||
cad: lift(w.cad),
|
||||
atemp: lift(w.atemp),
|
||||
power: lift(w.power),
|
||||
slope_segment_starts: lift(w.slope_segment_starts),
|
||||
slope_segment_slopes: lift(w.slope_segment_slopes),
|
||||
selection_point: lift(w.selection_point),
|
||||
surface_starts: lift(w.surface_starts),
|
||||
surface_values: lift(w.surface_values),
|
||||
surfaces: lift(w.surfaces),
|
||||
highway_starts: lift(w.highway_starts),
|
||||
highway_values: lift(w.highway_values),
|
||||
highways: lift(w.highways),
|
||||
sac_scale_starts: lift(w.sac_scale_starts),
|
||||
sac_scale_values: lift(w.sac_scale_values),
|
||||
sac_scales: lift(w.sac_scales),
|
||||
mtb_scale_starts: lift(w.mtb_scale_starts),
|
||||
mtb_scale_values: lift(w.mtb_scale_values),
|
||||
mtb_scales: lift(w.mtb_scales),
|
||||
anchor_indices: lift(w.anchor_indices),
|
||||
anchor_zooms: lift(w.anchor_zooms),
|
||||
segment_starts: lift(w.segment_starts),
|
||||
segment_ids: lift(w.segment_ids),
|
||||
routing_revision: lift(w.routing_revision),
|
||||
|
||||
importsLegacyData: true,
|
||||
open_storage: (name, onSaved, onBehind, onNewer) =>
|
||||
w.open_storage(name, onSaved, onBehind, onNewer),
|
||||
flush_storage: () => w.flush_storage(),
|
||||
sync_storage: () => w.sync_storage(),
|
||||
set_setting: lift(w.set_setting),
|
||||
delete_setting: lift(w.delete_setting),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
/** A flat `[lng, lat, ...]` array as positions. */
|
||||
export function toPositions(flat: Float64Array): [number, number][] {
|
||||
const positions: [number, number][] = new Array(flat.length / 2);
|
||||
for (let i = 0; i < positions.length; i++) {
|
||||
positions[i] = [flat[2 * i], flat[2 * i + 1]];
|
||||
}
|
||||
return positions;
|
||||
}
|
||||
@@ -0,0 +1,506 @@
|
||||
// The frontend side of the engine, against the real engine (the WASM module of `wasm`, which has
|
||||
// to be built: `wasm-pack build --target bundler` in `wasm`).
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { beforeEach, describe, it } from 'node:test';
|
||||
import { get } from 'svelte/store';
|
||||
import { isHidden } from '$lib/engine/file-visibility';
|
||||
import {
|
||||
ALL_EXPORT_OPTIONS,
|
||||
engine,
|
||||
FileStateCollectionObserver,
|
||||
type ExportOptions,
|
||||
type FileState,
|
||||
} from '$lib/engine';
|
||||
|
||||
function fixture(name: string): Uint8Array {
|
||||
return new Uint8Array(
|
||||
readFileSync(new URL(`../../../../gpx-rs/data/${name}.gpx`, import.meta.url))
|
||||
);
|
||||
}
|
||||
|
||||
async function load(...names: string[]) {
|
||||
return engine.loadFiles(names.map((name) => ({ data: fixture(name), name })));
|
||||
}
|
||||
|
||||
function fileStates(): FileState[] {
|
||||
return [...get(engine.files).values()].map((store) => get(store));
|
||||
}
|
||||
|
||||
function lastError() {
|
||||
return get(engine.lastError);
|
||||
}
|
||||
|
||||
beforeEach(async () => {
|
||||
await engine.ready;
|
||||
await engine.deleteAll();
|
||||
});
|
||||
|
||||
describe('files', () => {
|
||||
it('creates a file, selects it, and can take it back', async () => {
|
||||
assert.equal(await engine.newFile('route'), true);
|
||||
const [id] = get(engine.order);
|
||||
assert.equal(get(engine.order).length, 1);
|
||||
assert.equal(get(get(engine.files).get(id)!).structure.name, 'route');
|
||||
assert.deepEqual(get(engine.selection), { type: 'file', fileIds: [id] });
|
||||
assert.equal(get(engine.canUndo), true);
|
||||
|
||||
await engine.undo();
|
||||
assert.deepEqual(get(engine.order), []);
|
||||
assert.equal(get(engine.files).size, 0);
|
||||
assert.equal(get(engine.canRedo), true);
|
||||
await engine.redo();
|
||||
assert.deepEqual(get(engine.order), [id]);
|
||||
});
|
||||
|
||||
it('starts a new file with a track when given a trackpoint', async () => {
|
||||
await engine.newFile('start', { lng: 4.4, lat: 50.8, ele: 120 });
|
||||
const file = fileStates()[0];
|
||||
assert.equal(file.structure.tracks.length, 1);
|
||||
assert.equal(file.segments.features.length, 1);
|
||||
assert.deepEqual(file.segments.features[0].geometry.coordinates, [[4.4, 50.8]]);
|
||||
assert.equal(get(engine.statistics).length, 1);
|
||||
assert.equal(get(engine.statistics).ele[0], 120);
|
||||
});
|
||||
|
||||
it('loads several files in one undo step and selects the first one', async () => {
|
||||
assert.equal(await load('simple', 'with_tracks'), true);
|
||||
const ids = get(engine.order);
|
||||
assert.equal(ids.length, 2);
|
||||
assert.deepEqual(get(engine.selection), { type: 'file', fileIds: [ids[0]] });
|
||||
// the names of the files are the ones of the data, or the given ones
|
||||
assert.deepEqual(
|
||||
fileStates().map((file) => file.structure.name),
|
||||
['simple', 'with_tracks']
|
||||
);
|
||||
|
||||
await engine.undo();
|
||||
assert.equal(get(engine.files).size, 0);
|
||||
});
|
||||
|
||||
it('skips what cannot be read, and tells why when nothing could', async () => {
|
||||
const broken = { data: new TextEncoder().encode('<gpx><trk></gpx>'), name: 'broken' };
|
||||
assert.equal(await engine.loadFiles([broken]), false);
|
||||
assert.match(lastError() ?? '', /^invalid data/);
|
||||
assert.equal(get(engine.files).size, 0);
|
||||
|
||||
assert.equal(
|
||||
await engine.loadFiles([broken, { data: fixture('simple'), name: 'ok' }]),
|
||||
true
|
||||
);
|
||||
assert.equal(get(engine.files).size, 1);
|
||||
assert.equal(lastError(), undefined);
|
||||
});
|
||||
|
||||
it('duplicates and deletes the selection', async () => {
|
||||
await load('simple');
|
||||
await engine.duplicate();
|
||||
assert.equal(get(engine.order).length, 2);
|
||||
const [original, copy] = get(engine.order);
|
||||
assert.notEqual(original, copy);
|
||||
|
||||
await engine.delete();
|
||||
assert.equal(get(engine.files).size, 1);
|
||||
assert.equal(await engine.deleteAll(), true);
|
||||
assert.equal(await engine.deleteAll(), false);
|
||||
assert.equal(lastError(), 'nothing to do');
|
||||
});
|
||||
|
||||
it('reorders the files', async () => {
|
||||
await load('simple', 'with_tracks', 'with_waypoint');
|
||||
const [a, b, c] = get(engine.order);
|
||||
await engine.reorder([c], 0);
|
||||
assert.deepEqual(get(engine.order), [c, a, b]);
|
||||
assert.equal(get(engine.canUndo), true);
|
||||
// an order is not an edit: only the loading is undone
|
||||
await engine.undo();
|
||||
assert.equal(get(engine.files).size, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('errors', () => {
|
||||
it('keeps the reason of the last call that did nothing', async () => {
|
||||
assert.equal(lastError(), 'nothing to do');
|
||||
await engine.newFile('a');
|
||||
assert.equal(lastError(), undefined);
|
||||
|
||||
await engine.select([]);
|
||||
assert.equal(await engine.reverse(), false);
|
||||
assert.equal(lastError(), 'nothing to do');
|
||||
// a call with wrong arguments says so
|
||||
assert.equal(await engine.crop(5, 1), false);
|
||||
assert.match(lastError() ?? '', /reversed/);
|
||||
// the next success clears it
|
||||
assert.equal(await engine.newFile('b'), true);
|
||||
assert.equal(lastError(), undefined);
|
||||
});
|
||||
|
||||
it('refuses a stale routing revision', async () => {
|
||||
await engine.newFile('a', { lng: 4, lat: 50 });
|
||||
assert.equal(await engine.insertAnchor(-1, 4, 50), false);
|
||||
assert.match(lastError() ?? '', /selection changed/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('selection', () => {
|
||||
/** The selected files, when files are selected. */
|
||||
const selectedFiles = () => {
|
||||
const selection = get(engine.selection);
|
||||
return selection.type === 'file' ? selection.fileIds : [];
|
||||
};
|
||||
|
||||
it('adds and toggles files', async () => {
|
||||
await load('simple', 'with_tracks', 'with_waypoint');
|
||||
const [a, b, c] = get(engine.order);
|
||||
await engine.select([a]);
|
||||
await engine.select([b], 'add');
|
||||
assert.deepEqual(new Set(selectedFiles()), new Set([a, b]));
|
||||
await engine.select([a], 'toggle');
|
||||
assert.deepEqual(selectedFiles(), [b]);
|
||||
await engine.select([]);
|
||||
assert.deepEqual(get(engine.selection), { type: 'empty' });
|
||||
|
||||
assert.equal(await engine.selectAll(), true);
|
||||
assert.deepEqual(new Set(selectedFiles()), new Set([a, b, c]));
|
||||
});
|
||||
|
||||
it('selects tracks and segments of a file', async () => {
|
||||
await load('with_tracks_and_segments');
|
||||
const file = fileStates()[0];
|
||||
const track = file.structure.tracks[0];
|
||||
await engine.selectTracks(file.structure.id, [track.id]);
|
||||
assert.deepEqual(get(engine.selection), {
|
||||
type: 'track',
|
||||
fileId: file.structure.id,
|
||||
trackIds: [track.id],
|
||||
});
|
||||
// the statistics follow the selection
|
||||
const trackLength = get(engine.statistics).length;
|
||||
assert.ok(trackLength > 0);
|
||||
await engine.select([file.structure.id]);
|
||||
assert.ok(get(engine.statistics).length > trackLength);
|
||||
});
|
||||
|
||||
it('selects routes, whose segments are on the map', async () => {
|
||||
await load('with_routes');
|
||||
const file = fileStates()[0];
|
||||
const { id, routes, tracks } = file.structure;
|
||||
assert.equal(routes.length, 2);
|
||||
assert.equal(tracks.length, 0);
|
||||
// the segments of the map are the ones of the routes
|
||||
assert.deepEqual(
|
||||
file.segments.features.map((f) => f.properties.routeId),
|
||||
routes.map((route) => route.id)
|
||||
);
|
||||
assert.deepEqual(
|
||||
file.segments.features.map((f) => f.properties.segmentId),
|
||||
routes.map((route) => route.segment.id)
|
||||
);
|
||||
|
||||
await engine.selectRoutes(id, [routes[1].id]);
|
||||
assert.deepEqual(get(engine.selection), {
|
||||
type: 'route',
|
||||
fileId: id,
|
||||
routeIds: [routes[1].id],
|
||||
});
|
||||
assert.equal(get(engine.statistics).length, routes[1].segment.length);
|
||||
|
||||
await engine.select([id]);
|
||||
assert.equal(await engine.newRoute(), true);
|
||||
assert.equal(fileStates()[0].structure.routes.length, 3);
|
||||
});
|
||||
|
||||
it('creates a file that starts with an empty route', async () => {
|
||||
assert.equal(await engine.newFile('routes', undefined, true), true);
|
||||
const [state] = fileStates();
|
||||
assert.equal(state.structure.routes.length, 1);
|
||||
assert.equal(state.structure.routes[0].segment.length, 0);
|
||||
assert.equal(state.structure.tracks.length, 0);
|
||||
assert.deepEqual(get(engine.selection), { type: 'file', fileIds: [state.structure.id] });
|
||||
});
|
||||
|
||||
it('ignores what does not exist', async () => {
|
||||
await load('simple');
|
||||
const before = get(engine.selection);
|
||||
assert.equal(await engine.select(['00000000-0000-0000-0000-000000000000'], 'add'), false);
|
||||
assert.deepEqual(get(engine.selection), before);
|
||||
});
|
||||
});
|
||||
|
||||
describe('statistics', () => {
|
||||
it('describes the selection', async () => {
|
||||
await load('simple');
|
||||
const statistics = get(engine.statistics);
|
||||
const file = fileStates()[0];
|
||||
assert.ok(statistics.length > 1);
|
||||
assert.equal(statistics.lng.length, statistics.length);
|
||||
assert.equal(statistics.ele.length, statistics.length);
|
||||
assert.equal(statistics.totalDistance[0], 0);
|
||||
assert.ok(statistics.global.totalDistance > 0);
|
||||
assert.equal(statistics.global.totalDistance, file.statistics.totalDistance);
|
||||
assert.equal((await statistics.point(0))!.time, undefined);
|
||||
assert.ok(statistics.global.bounds!.west <= statistics.global.bounds!.east);
|
||||
|
||||
await engine.select([]);
|
||||
assert.equal(get(engine.statistics).length, 0);
|
||||
assert.equal(get(engine.statistics).global.totalDistance, 0);
|
||||
});
|
||||
|
||||
it('has timestamps when the file has some', async () => {
|
||||
await load('with_time');
|
||||
const statistics = get(engine.statistics);
|
||||
assert.ok((await statistics.point(0))!.time! > 0);
|
||||
assert.ok(statistics.global.totalTime! > 0);
|
||||
assert.ok(statistics.global.movingSpeed === undefined || statistics.global.movingSpeed > 0);
|
||||
});
|
||||
|
||||
it('reads the metrics that are requested, and only these', async () => {
|
||||
await load('with_hr');
|
||||
assert.equal(get(engine.statistics).hr, undefined);
|
||||
|
||||
const request = engine.requestStatistics();
|
||||
await request.set(['hr', 'anchors', 'slopeSegment']);
|
||||
const statistics = get(engine.statistics);
|
||||
assert.equal(statistics.slopeSegments!.starts[0], 0);
|
||||
assert.equal(
|
||||
statistics.slopeSegments!.starts.length,
|
||||
statistics.slopeSegments!.slopes.length
|
||||
);
|
||||
assert.equal(statistics.hr!.length, statistics.length);
|
||||
assert.ok(statistics.hr!.some((hr) => !Number.isNaN(hr)));
|
||||
assert.equal(statistics.cad, undefined);
|
||||
assert.equal(statistics.anchors!.indices[0], 0);
|
||||
assert.equal(statistics.anchors!.indices.at(-1), statistics.length - 1);
|
||||
|
||||
// they are read again after a change, without being asked again
|
||||
await engine.select([]);
|
||||
await engine.select([get(engine.order)[0]]);
|
||||
assert.ok(get(engine.statistics).hr);
|
||||
request.release();
|
||||
await engine.select([]);
|
||||
await engine.select([get(engine.order)[0]]);
|
||||
assert.equal(get(engine.statistics).hr, undefined);
|
||||
});
|
||||
|
||||
it('gives the statistics of a part of the selection', async () => {
|
||||
await load('simple');
|
||||
const statistics = get(engine.statistics);
|
||||
const part = (await statistics.slice(2, 5))!;
|
||||
assert.ok(part.totalDistance > 0);
|
||||
assert.ok(part.totalDistance < statistics.global.totalDistance);
|
||||
assert.equal(await statistics.slice(0, statistics.length + 10), undefined);
|
||||
|
||||
// a slice is only valid for the selection it was made on
|
||||
await engine.select([]);
|
||||
assert.equal(await statistics.slice(2, 5), undefined);
|
||||
});
|
||||
|
||||
it('gives the data of a trackpoint of the selection', async () => {
|
||||
await load('simple');
|
||||
const statistics = get(engine.statistics);
|
||||
const point = (await statistics.point(3))!;
|
||||
assert.ok(point.slopeSegmentDistance! > 0);
|
||||
assert.equal(typeof point.slope, 'number');
|
||||
assert.equal(await statistics.point(statistics.length), undefined);
|
||||
|
||||
// only for the selection it was read for
|
||||
await engine.select([]);
|
||||
assert.equal(await statistics.point(3), undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('file state', () => {
|
||||
it('has one feature per segment and keeps the unchanged ones when editing', async () => {
|
||||
await load('with_tracks_and_segments');
|
||||
const before = fileStates()[0];
|
||||
assert.equal(
|
||||
before.segments.features.length,
|
||||
before.structure.tracks.reduce((sum, track) => sum + track.segments.length, 0)
|
||||
);
|
||||
|
||||
// renaming does not touch the segments: they are the same objects
|
||||
await engine.metadata('renamed', 'description');
|
||||
const renamed = fileStates()[0];
|
||||
assert.equal(renamed.structure.name, 'renamed');
|
||||
assert.equal(renamed.structure.desc, 'description');
|
||||
renamed.segments.features.forEach((feature, i) => {
|
||||
assert.equal(feature, before.segments.features[i]);
|
||||
});
|
||||
|
||||
// reversing a file reverses its tracks and their points
|
||||
await engine.reverse();
|
||||
const reversed = fileStates()[0].segments.features.map((f) => f.geometry.coordinates);
|
||||
const expected = [...renamed.segments.features]
|
||||
.reverse()
|
||||
.map((f) => [...f.geometry.coordinates].reverse());
|
||||
assert.deepEqual(reversed, expected);
|
||||
await engine.undo();
|
||||
fileStates()[0].segments.features.forEach((feature, i) => {
|
||||
assert.deepEqual(
|
||||
feature.geometry.coordinates,
|
||||
renamed.segments.features[i].geometry.coordinates
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it('colors the files, and keeps the color of a file', async () => {
|
||||
await load('simple', 'with_tracks');
|
||||
const [a, b] = fileStates();
|
||||
assert.notEqual(a.color, b.color);
|
||||
|
||||
await engine.select([a.structure.id]);
|
||||
await engine.style({ color: 'ff0000' });
|
||||
assert.equal(get(get(engine.files).get(a.structure.id)!).color, '#ff0000');
|
||||
const styled = get(get(engine.files).get(a.structure.id)!).segments.features[0];
|
||||
assert.equal(styled.properties.color, '#ff0000');
|
||||
|
||||
await engine.undo();
|
||||
assert.equal(get(get(engine.files).get(a.structure.id)!).color, a.color);
|
||||
});
|
||||
|
||||
it('has the waypoints as features', async () => {
|
||||
await load('with_waypoint');
|
||||
const file = fileStates()[0];
|
||||
assert.ok(file.waypoints.features.length > 0);
|
||||
const feature = file.waypoints.features[0];
|
||||
const details = (await engine.waypoint(file.structure.id, feature.properties.waypointId))!;
|
||||
assert.deepEqual(feature.geometry.coordinates, [details.lng, details.lat]);
|
||||
assert.equal(feature.properties.name, details.name);
|
||||
assert.equal(details.links?.[0].href, 'https://gpx.studio');
|
||||
assert.equal(details.links?.[0].text, 'waypoint link text');
|
||||
});
|
||||
});
|
||||
|
||||
describe('waypoints', () => {
|
||||
const waypoint = {
|
||||
lng: 4.4,
|
||||
lat: 50.8,
|
||||
ele: 100,
|
||||
name: 'summit',
|
||||
desc: 'a nice view',
|
||||
icon: 'Summit',
|
||||
link: 'https://example.com',
|
||||
};
|
||||
|
||||
it('creates, edits, moves and deletes a waypoint', async () => {
|
||||
await engine.newFile('file');
|
||||
assert.equal(await engine.newWaypoint(waypoint), true);
|
||||
const file = fileStates()[0];
|
||||
const id = file.waypoints.features[0].properties.waypointId;
|
||||
const fileId = file.structure.id;
|
||||
|
||||
let details = (await engine.waypoint(fileId, id))!;
|
||||
assert.equal(details.name, 'summit');
|
||||
assert.equal(details.sym, 'Summit');
|
||||
assert.equal(details.links![0].href, 'https://example.com');
|
||||
|
||||
await engine.updateWaypoint(fileId, id, { ...waypoint, name: 'peak', link: '' });
|
||||
details = (await engine.waypoint(fileId, id))!;
|
||||
assert.equal(details.name, 'peak');
|
||||
assert.equal(details.links, undefined);
|
||||
|
||||
await engine.moveWaypoint(fileId, id, 5, 51, 200);
|
||||
assert.deepEqual(fileStates()[0].waypoints.features[0].geometry.coordinates, [5, 51]);
|
||||
assert.equal((await engine.waypoint(fileId, id))!.ele, 200);
|
||||
|
||||
await engine.deleteWaypoint(fileId, id);
|
||||
assert.equal(fileStates()[0].waypoints.features.length, 0);
|
||||
assert.equal(await engine.waypoint(fileId, id), undefined);
|
||||
assert.equal(await engine.deleteWaypoint(fileId, id), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clipboard', () => {
|
||||
it('copies and pastes', async () => {
|
||||
await load('simple');
|
||||
assert.equal(get(engine.clipboard), undefined);
|
||||
assert.equal(get(engine.canPaste), false);
|
||||
await engine.copy();
|
||||
assert.equal(get(engine.clipboard)?.type, 'files');
|
||||
assert.equal(get(engine.canPaste), true);
|
||||
await engine.paste();
|
||||
assert.equal(get(engine.files).size, 2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('observer of the files', () => {
|
||||
it('tells which files appear and disappear', async () => {
|
||||
const added: string[] = [];
|
||||
const removed: string[] = [];
|
||||
let destroyed = 0;
|
||||
await load('simple');
|
||||
const [first] = get(engine.order);
|
||||
const observer = new FileStateCollectionObserver(
|
||||
(files) => files.forEach((_, id) => added.push(id)),
|
||||
(id) => removed.push(id),
|
||||
() => destroyed++
|
||||
);
|
||||
// the files that exist are reported at once
|
||||
assert.deepEqual(added, [first]);
|
||||
|
||||
await load('with_tracks');
|
||||
const second = get(engine.order).find((id) => id !== first)!;
|
||||
assert.deepEqual(added, [first, second]);
|
||||
|
||||
// editing a file does not make it appear again
|
||||
await engine.metadata('x', '');
|
||||
assert.equal(added.length, 2);
|
||||
|
||||
await engine.deleteAll();
|
||||
assert.deepEqual(new Set(removed), new Set([first, second]));
|
||||
observer.destroy();
|
||||
assert.equal(destroyed, 1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('export', () => {
|
||||
const text = async (id: string, options: Partial<ExportOptions> = {}) =>
|
||||
new TextDecoder().decode(
|
||||
await engine.exportFile(id, { ...ALL_EXPORT_OPTIONS, ...options })
|
||||
);
|
||||
|
||||
it('writes tracks as tracks', async () => {
|
||||
await load('with_tracks_and_segments');
|
||||
const file = fileStates()[0];
|
||||
const segments = file.structure.tracks.reduce(
|
||||
(sum, track) => sum + track.segments.length,
|
||||
0
|
||||
);
|
||||
const tracks = await text(file.structure.id);
|
||||
assert.ok(tracks.includes('<trk>') && !tracks.includes('<rte>'));
|
||||
assert.equal(tracks.match(/<trkseg>/g)?.length, segments);
|
||||
});
|
||||
|
||||
it('can read back the routes it writes', async () => {
|
||||
await load('with_routes');
|
||||
const [id] = get(engine.order);
|
||||
const before = fileStates()[0].structure.routes.length;
|
||||
const routes = (await engine.exportFile(id))!;
|
||||
const written = new TextDecoder().decode(routes);
|
||||
assert.equal(written.match(/<rte>/g)?.length, before);
|
||||
assert.ok(!written.includes('<trk>') && written.includes('<rtept'));
|
||||
|
||||
await engine.loadFiles([{ data: routes, name: 'routes' }]);
|
||||
const [, loaded] = get(engine.order);
|
||||
const state = get(get(engine.files).get(loaded)!);
|
||||
assert.equal(state.structure.routes.length, before);
|
||||
assert.equal(state.structure.tracks.length, 0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('visibility', () => {
|
||||
it('hides the selection and shows it again', async () => {
|
||||
await load('simple');
|
||||
const id = get(engine.order)[0];
|
||||
const state = () => get(get(engine.files).get(id)!);
|
||||
assert.equal(isHidden(state(), id), false);
|
||||
|
||||
await engine.setSelectionHidden(true);
|
||||
assert.equal(isHidden(state(), id), true);
|
||||
// the statistics still count what is hidden
|
||||
assert.ok(get(engine.statistics).length > 0);
|
||||
|
||||
await engine.setSelectionHidden(false);
|
||||
assert.equal(isHidden(state(), id), false);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,63 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import { FileColorAllocator, normalizeColor } from '$lib/engine/file-colors';
|
||||
|
||||
describe('normalizeColor', () => {
|
||||
it('adds the # of hex colors that have none', () => {
|
||||
assert.equal(normalizeColor('ff0000'), '#ff0000');
|
||||
assert.equal(normalizeColor('FF00aa'), '#FF00aa');
|
||||
assert.equal(normalizeColor('#ff0000'), '#ff0000');
|
||||
assert.equal(normalizeColor('red'), 'red');
|
||||
assert.equal(normalizeColor('fff'), 'fff');
|
||||
assert.equal(normalizeColor('hsl(0, 70%, 50%)'), 'hsl(0, 70%, 50%)');
|
||||
});
|
||||
});
|
||||
|
||||
describe('FileColorAllocator', () => {
|
||||
it('uses the color the tracks define', () => {
|
||||
const colors = new FileColorAllocator();
|
||||
assert.equal(colors.resolve('a', [undefined, 'ff9900', '0000ff']), '#ff9900');
|
||||
assert.equal(colors.resolve('b', ['#123456']), '#123456');
|
||||
});
|
||||
|
||||
it('gives the files different palette colors while some are unused', () => {
|
||||
const colors = new FileColorAllocator();
|
||||
const given = Array.from({ length: 11 }, (_, i) => colors.resolve(`file-${i}`, []));
|
||||
assert.equal(new Set(given).size, 11);
|
||||
// then the least used ones again
|
||||
const twelfth = colors.resolve('file-11', []);
|
||||
assert.equal(twelfth, given[0]);
|
||||
});
|
||||
|
||||
it('keeps the color of a file when its style comes and goes', () => {
|
||||
const colors = new FileColorAllocator();
|
||||
const palette = colors.resolve('a', []);
|
||||
colors.resolve('b', []);
|
||||
// a style is defined, then removed (edit, undo): the file gets its color back
|
||||
assert.equal(colors.resolve('a', ['ff0000']), '#ff0000');
|
||||
assert.equal(colors.resolve('a', []), palette);
|
||||
assert.equal(colors.resolve('a', [undefined]), palette);
|
||||
});
|
||||
|
||||
it('does not count the colors files define as used palette colors twice', () => {
|
||||
const colors = new FileColorAllocator();
|
||||
const first = colors.resolve('a', []);
|
||||
// a file with the color of the palette uses it
|
||||
colors.resolve('b', [first]);
|
||||
const next = colors.resolve('c', []);
|
||||
assert.notEqual(next, first);
|
||||
});
|
||||
|
||||
it('frees the colors of the files that go away', () => {
|
||||
const colors = new FileColorAllocator();
|
||||
const a = colors.resolve('a', []);
|
||||
const b = colors.resolve('b', []);
|
||||
assert.notEqual(a, b);
|
||||
colors.release('a');
|
||||
// a color that nobody uses is picked first again
|
||||
assert.equal(colors.resolve('c', []), a);
|
||||
// and a file that comes back gets a color again
|
||||
colors.release('b');
|
||||
colors.resolve('b', []);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
const PALETTE = [
|
||||
'#ff0000',
|
||||
'#0000ff',
|
||||
'#46e646',
|
||||
'#00ccff',
|
||||
'#ff9900',
|
||||
'#ff00ff',
|
||||
'#ffff32',
|
||||
'#288228',
|
||||
'#9933ff',
|
||||
'#50f0be',
|
||||
'#8c645a',
|
||||
];
|
||||
|
||||
/** GPX style colors are hex digits, with or without the leading `#`. */
|
||||
export function normalizeColor(color: string): string {
|
||||
return /^[0-9a-f]{6}$/i.test(color) ? `#${color}` : color;
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the base color of each file: the color defined by the file itself if any, otherwise a
|
||||
* palette color, the least used one when the file first shows up. A file keeps its palette color
|
||||
* for its whole lifetime, so that it does not change when style information comes and goes
|
||||
* (edits, undo, redo).
|
||||
*/
|
||||
export class FileColorAllocator {
|
||||
/** Palette color reserved for each file. */
|
||||
private _reserved = new Map<string, string>();
|
||||
/** Color currently displayed for each file. */
|
||||
private _base = new Map<string, string>();
|
||||
|
||||
/** Updates (and returns) the base color of a file, given the colors defined by its tracks. */
|
||||
resolve(fileId: string, trackColors: (string | undefined)[]): string {
|
||||
const explicit = trackColors.find((color) => color !== undefined);
|
||||
if (explicit === undefined && !this._reserved.has(fileId)) {
|
||||
this._reserved.set(fileId, this.leastUsed());
|
||||
}
|
||||
const color =
|
||||
explicit !== undefined ? normalizeColor(explicit) : this._reserved.get(fileId)!;
|
||||
this._base.set(fileId, color);
|
||||
return color;
|
||||
}
|
||||
|
||||
release(fileId: string) {
|
||||
this._reserved.delete(fileId);
|
||||
this._base.delete(fileId);
|
||||
}
|
||||
|
||||
private leastUsed(): string {
|
||||
const usage = new Map(PALETTE.map((color) => [color, 0]));
|
||||
this._base.forEach((color) => {
|
||||
const count = usage.get(color);
|
||||
if (count !== undefined) {
|
||||
usage.set(color, count + 1);
|
||||
}
|
||||
});
|
||||
return PALETTE.reduce((a, b) => (usage.get(a)! <= usage.get(b)! ? a : b));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import type { Feature, LineString } from 'geojson';
|
||||
import { normalizeColor, type FileColorAllocator } from '$lib/engine/file-colors';
|
||||
import type { Visibility } from '$lib/engine/file-visibility';
|
||||
import type { Backend } from './backend';
|
||||
import { toPositions } from './convert';
|
||||
import {
|
||||
EMPTY_STATISTICS,
|
||||
type FileState,
|
||||
type PathInfo,
|
||||
type SegmentNode,
|
||||
type SegmentProperties,
|
||||
} from './types';
|
||||
|
||||
/** Reads the state of a file, reusing from `previous` what did not change. */
|
||||
export async function readFileState(
|
||||
backend: Backend,
|
||||
id: string,
|
||||
colors: FileColorAllocator,
|
||||
visibility: ReadonlyMap<string, Visibility>,
|
||||
previous?: FileState
|
||||
): Promise<FileState | null> {
|
||||
const structure = await backend.file_structure(id);
|
||||
if (!structure) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const paths: PathInfo[] = [...structure.routes, ...structure.tracks];
|
||||
const color = colors.resolve(
|
||||
id,
|
||||
paths.map((path) => path.color)
|
||||
);
|
||||
|
||||
const previousSegments = new Map(
|
||||
previous?.segments.features.map((f) => [f.properties.segmentId, f]) ?? []
|
||||
);
|
||||
// the coordinates of the segments that changed, read together
|
||||
const segments: (
|
||||
| Feature<LineString, SegmentProperties>
|
||||
| Promise<Feature<LineString, SegmentProperties>>
|
||||
)[] = [];
|
||||
const addSegment = (
|
||||
segment: SegmentNode,
|
||||
path: PathInfo,
|
||||
parent: Pick<SegmentProperties, 'routeId' | 'trackId'>
|
||||
) => {
|
||||
const properties: SegmentProperties = {
|
||||
fileId: id,
|
||||
...parent,
|
||||
segmentId: segment.id,
|
||||
rev: segment.rev,
|
||||
color: path.color !== undefined ? normalizeColor(path.color) : color,
|
||||
opacity: path.opacity,
|
||||
width: path.width,
|
||||
};
|
||||
const old = previousSegments.get(segment.id);
|
||||
const unchanged =
|
||||
old !== undefined &&
|
||||
(Object.keys(properties) as (keyof SegmentProperties)[]).every(
|
||||
(key) => old.properties[key] === properties[key]
|
||||
);
|
||||
segments.push(
|
||||
unchanged
|
||||
? old
|
||||
: backend.segment_coordinates(segment.id).then((coordinates) => ({
|
||||
type: 'Feature',
|
||||
geometry: {
|
||||
type: 'LineString',
|
||||
coordinates: toPositions(coordinates),
|
||||
},
|
||||
properties,
|
||||
}))
|
||||
);
|
||||
};
|
||||
structure.routes.forEach((route) => addSegment(route.segment, route, { routeId: route.id }));
|
||||
structure.tracks.forEach((track) => {
|
||||
track.segments.forEach((segment) => addSegment(segment, track, { trackId: track.id }));
|
||||
});
|
||||
const segmentFeatures = await Promise.all(segments);
|
||||
|
||||
const previousStructure = previous?.structure;
|
||||
const waypointsUnchanged =
|
||||
previousStructure !== undefined &&
|
||||
previousStructure.waypointsRev === structure.waypointsRev &&
|
||||
previousStructure.waypoints.length === structure.waypoints.length &&
|
||||
previousStructure.waypoints.every(
|
||||
(w, i) =>
|
||||
w.id === structure.waypoints[i].id &&
|
||||
w.name === structure.waypoints[i].name &&
|
||||
w.sym === structure.waypoints[i].sym
|
||||
);
|
||||
let waypoints = previous?.waypoints;
|
||||
if (!waypoints || !waypointsUnchanged) {
|
||||
const coordinates = toPositions(await backend.waypoint_coordinates(id));
|
||||
waypoints = {
|
||||
type: 'FeatureCollection',
|
||||
features: structure.waypoints.map((waypoint, index) => ({
|
||||
type: 'Feature',
|
||||
geometry: { type: 'Point', coordinates: coordinates[index] },
|
||||
properties: {
|
||||
fileId: id,
|
||||
waypointId: waypoint.id,
|
||||
index,
|
||||
name: waypoint.name,
|
||||
sym: waypoint.sym,
|
||||
},
|
||||
})),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
structure,
|
||||
color,
|
||||
statistics: (await backend.file_statistics(id)) ?? EMPTY_STATISTICS,
|
||||
segments: { type: 'FeatureCollection', features: segmentFeatures },
|
||||
waypoints,
|
||||
visibility: visibility.get(id) ?? new Map(),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,221 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { FileStructure } from 'gpx-wasm';
|
||||
import {
|
||||
isHidden,
|
||||
isSegmentHidden,
|
||||
isWaypointHidden,
|
||||
parseVisibility,
|
||||
setHidden,
|
||||
stringifyVisibility,
|
||||
waypointsKey,
|
||||
type Visibility,
|
||||
type VisibilityState,
|
||||
} from '$lib/engine/file-visibility';
|
||||
|
||||
const segment = (id: string) => ({ id, rev: `rev-${id}`, length: 2 });
|
||||
|
||||
// F
|
||||
// ├── waypoints: W1, W2
|
||||
// ├── T1: S1, S2
|
||||
// └── T2: S3
|
||||
const structure: FileStructure = {
|
||||
id: 'F',
|
||||
name: 'file',
|
||||
waypointsRev: 'wpt-rev',
|
||||
waypoints: [{ id: 'W1' }, { id: 'W2' }],
|
||||
routes: [],
|
||||
tracks: [
|
||||
{ id: 'T1', segments: [segment('S1'), segment('S2')] },
|
||||
{ id: 'T2', segments: [segment('S3')] },
|
||||
],
|
||||
};
|
||||
const WPTS = waypointsKey('F');
|
||||
const elements = ['F', WPTS, 'W1', 'W2', 'T1', 'S1', 'S2', 'T2', 'S3'];
|
||||
|
||||
/** Applies the actions one after the other, starting with everything visible. */
|
||||
function apply(...actions: [ids: string[], hidden: boolean][]): VisibilityState {
|
||||
let visibility: Visibility = new Map();
|
||||
for (const [ids, hidden] of actions) {
|
||||
visibility = setHidden(structure, visibility, ids, hidden);
|
||||
}
|
||||
return { structure, visibility };
|
||||
}
|
||||
|
||||
function hiddenElements(state: VisibilityState): string[] {
|
||||
return elements.filter((id) => isHidden(state, id));
|
||||
}
|
||||
|
||||
describe('file visibility', () => {
|
||||
it('shows everything by default', () => {
|
||||
assert.deepEqual(hiddenElements(apply()), []);
|
||||
});
|
||||
|
||||
it('hides an element and what is below it', () => {
|
||||
assert.deepEqual(hiddenElements(apply([['T1'], true])), ['T1', 'S1', 'S2']);
|
||||
assert.deepEqual(hiddenElements(apply([['S1'], true])), ['S1']);
|
||||
assert.deepEqual(hiddenElements(apply([[WPTS], true])), [WPTS, 'W1', 'W2']);
|
||||
assert.deepEqual(hiddenElements(apply([['W2'], true])), ['W2']);
|
||||
});
|
||||
|
||||
it('hides a whole file', () => {
|
||||
assert.deepEqual(hiddenElements(apply([['F'], true])), elements);
|
||||
});
|
||||
|
||||
it('shows again what was hidden', () => {
|
||||
assert.deepEqual(hiddenElements(apply([['F'], true], [['F'], false])), []);
|
||||
assert.deepEqual(hiddenElements(apply([['S1'], true], [['S1'], false])), []);
|
||||
});
|
||||
|
||||
it('keeps the other segments hidden when one is shown below a hidden file', () => {
|
||||
const state = apply([['F'], true], [['S1'], false]);
|
||||
assert.deepEqual(hiddenElements(state), [WPTS, 'W1', 'W2', 'S2', 'T2', 'S3']);
|
||||
// the file and the track of the visible segment are not hidden, they have visible content
|
||||
assert.equal(isHidden(state, 'F'), false);
|
||||
assert.equal(isHidden(state, 'T1'), false);
|
||||
assert.equal(isHidden(state, 'S1'), false);
|
||||
});
|
||||
|
||||
it('hides the file again once what was shown is hidden', () => {
|
||||
const state = apply([['F'], true], [['S1'], false], [['S1'], true]);
|
||||
assert.deepEqual(hiddenElements(state), elements);
|
||||
});
|
||||
|
||||
it('resets what was shown below when hiding a parent', () => {
|
||||
const state = apply([['F'], true], [['S1'], false], [['F'], true]);
|
||||
assert.deepEqual(hiddenElements(state), elements);
|
||||
assert.equal(state.visibility.has('S1'), false);
|
||||
});
|
||||
|
||||
it('resets what was hidden below when showing a parent', () => {
|
||||
const state = apply([['S1', 'S3', 'W1'], true], [['F'], false]);
|
||||
assert.deepEqual(hiddenElements(state), []);
|
||||
assert.equal(state.visibility.has('S1'), false);
|
||||
});
|
||||
|
||||
it('shows a track hidden below a hidden file, with all its segments', () => {
|
||||
const state = apply([['F'], true], [['T1'], false]);
|
||||
assert.deepEqual(hiddenElements(state), [WPTS, 'W1', 'W2', 'T2', 'S3']);
|
||||
});
|
||||
|
||||
it('shows a waypoint below a hidden file', () => {
|
||||
const state = apply([['F'], true], [['W1'], false]);
|
||||
assert.deepEqual(hiddenElements(state), ['W2', 'T1', 'S1', 'S2', 'T2', 'S3']);
|
||||
assert.equal(isHidden(state, WPTS), false);
|
||||
assert.equal(isHidden(state, 'F'), false);
|
||||
});
|
||||
|
||||
it('hides a segment shown inside a hidden track of a visible file', () => {
|
||||
const state = apply([['T1'], true], [['S2'], false]);
|
||||
assert.deepEqual(hiddenElements(state), ['S1']);
|
||||
});
|
||||
|
||||
it('does not touch the other branches of the tree', () => {
|
||||
const state = apply([['T1'], true], [['T2'], true], [['T1'], false]);
|
||||
assert.deepEqual(hiddenElements(state), ['T2', 'S3']);
|
||||
});
|
||||
|
||||
it('has leaf helpers agreeing with isHidden', () => {
|
||||
const states = [
|
||||
apply(),
|
||||
apply([['F'], true]),
|
||||
apply([['F'], true], [['S1'], false], [['W2'], false]),
|
||||
apply([['T1'], true], [['S2'], false]),
|
||||
apply([[WPTS], true], [['W1'], false]),
|
||||
];
|
||||
for (const state of states) {
|
||||
for (const track of structure.tracks) {
|
||||
for (const { id } of track.segments) {
|
||||
assert.equal(isSegmentHidden(state, track.id, id), isHidden(state, id));
|
||||
}
|
||||
}
|
||||
for (const { id } of structure.waypoints) {
|
||||
assert.equal(isWaypointHidden(state, id), isHidden(state, id));
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('hides a route, which is a leaf like a waypoint', () => {
|
||||
const withRoute: FileStructure = {
|
||||
...structure,
|
||||
routes: [{ id: 'R', segment: segment('RS') }],
|
||||
};
|
||||
const state = (...actions: [ids: string[], hidden: boolean][]): VisibilityState => {
|
||||
let visibility: Visibility = new Map();
|
||||
for (const [ids, hidden] of actions) {
|
||||
visibility = setHidden(withRoute, visibility, ids, hidden);
|
||||
}
|
||||
return { structure: withRoute, visibility };
|
||||
};
|
||||
assert.equal(isHidden(state([['R'], true]), 'R'), true);
|
||||
assert.equal(isHidden(state([['R'], true]), 'F'), false);
|
||||
assert.equal(isSegmentHidden(state([['R'], true]), 'R', 'RS'), true);
|
||||
// with its file, and shown on its own below it
|
||||
assert.equal(isHidden(state([['F'], true]), 'R'), true);
|
||||
const shown = state([['F'], true], [['R'], false]);
|
||||
assert.equal(isHidden(shown, 'R'), false);
|
||||
assert.equal(isHidden(shown, 'F'), false);
|
||||
assert.equal(isHidden(shown, 'T1'), true);
|
||||
});
|
||||
|
||||
it('does not consider unknown ids hidden', () => {
|
||||
assert.equal(isHidden(apply([['F'], true]), 'unknown'), false);
|
||||
});
|
||||
|
||||
it('does not mutate the previous visibility', () => {
|
||||
const before: Visibility = new Map([['S1', false]]);
|
||||
setHidden(structure, before, ['F'], true);
|
||||
assert.deepEqual([...before], [['S1', false]]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('kept visibility', () => {
|
||||
const visibility = (entries: [string, boolean][]): Visibility => new Map(entries);
|
||||
|
||||
it('comes back as it was kept', () => {
|
||||
const files = new Map([
|
||||
[
|
||||
'F',
|
||||
visibility([
|
||||
['F', false],
|
||||
['S1', true],
|
||||
[WPTS, false],
|
||||
]),
|
||||
],
|
||||
['G', visibility([['G', false]])],
|
||||
]);
|
||||
const json = stringifyVisibility(files, () => true);
|
||||
assert.deepEqual(parseVisibility(json), files);
|
||||
});
|
||||
|
||||
it('leaves out the files that are gone and the ones with nothing set', () => {
|
||||
const files = new Map([
|
||||
['F', visibility([['F', false]])],
|
||||
['G', visibility([['G', false]])],
|
||||
['H', visibility([])],
|
||||
]);
|
||||
const json = stringifyVisibility(files, (fileId) => fileId !== 'G');
|
||||
assert.deepEqual([...parseVisibility(json).keys()], ['F']);
|
||||
});
|
||||
|
||||
it('is nothing when there is nothing to keep', () => {
|
||||
assert.equal(
|
||||
stringifyVisibility(new Map(), () => true),
|
||||
undefined
|
||||
);
|
||||
assert.equal(
|
||||
stringifyVisibility(new Map([['F', visibility([['F', false]])]]), () => false),
|
||||
undefined
|
||||
);
|
||||
assert.equal(parseVisibility(undefined).size, 0);
|
||||
});
|
||||
|
||||
it('ignores what is not visibility', () => {
|
||||
assert.equal(parseVisibility('not json').size, 0);
|
||||
assert.equal(parseVisibility('3').size, 0);
|
||||
assert.equal(parseVisibility('null').size, 0);
|
||||
const parsed = parseVisibility('{"F":{"F":false,"S1":"no"},"G":3,"H":{}}');
|
||||
assert.deepEqual([...parsed.keys()], ['F']);
|
||||
assert.deepEqual([...parsed.get('F')!], [['F', false]]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,175 @@
|
||||
import type { FileStructure } from 'gpx-wasm';
|
||||
|
||||
/**
|
||||
* Visibility the user set explicitly, by element id (file, route, track, segment, waypoint, or the
|
||||
* waypoints of the file as a whole, see `waypointsKey`): `false` hides, `true` shows. An element
|
||||
* without entry follows its parent, and everything is shown by default.
|
||||
*/
|
||||
export type Visibility = ReadonlyMap<string, boolean>;
|
||||
|
||||
/** What is needed to tell whether the elements of a file are hidden (a `FileState` fits). */
|
||||
export type VisibilityState = { structure: FileStructure; visibility: Visibility };
|
||||
|
||||
/** Id to hide or show all the waypoints of a file at once. */
|
||||
export function waypointsKey(fileId: string): string {
|
||||
return `${fileId}:waypoints`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Ids from the file down to `id` in the file tree (file, routes, tracks, segments / waypoints
|
||||
* group).
|
||||
*/
|
||||
function pathTo(structure: FileStructure, id: string): string[] {
|
||||
const fileId = structure.id;
|
||||
if (id === fileId) {
|
||||
return [fileId];
|
||||
}
|
||||
if (id === waypointsKey(fileId)) {
|
||||
return [fileId, id];
|
||||
}
|
||||
if (structure.waypoints.some((waypoint) => waypoint.id === id)) {
|
||||
return [fileId, waypointsKey(fileId), id];
|
||||
}
|
||||
if (structure.routes.some((route) => route.id === id)) {
|
||||
return [fileId, id];
|
||||
}
|
||||
for (const track of structure.tracks) {
|
||||
if (track.id === id) {
|
||||
return [fileId, id];
|
||||
}
|
||||
if (track.segments.some((segment) => segment.id === id)) {
|
||||
return [fileId, track.id, id];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function children(structure: FileStructure, id: string): string[] {
|
||||
if (id === structure.id) {
|
||||
return [
|
||||
waypointsKey(id),
|
||||
...structure.routes.map((route) => route.id),
|
||||
...structure.tracks.map((track) => track.id),
|
||||
];
|
||||
}
|
||||
if (id === waypointsKey(structure.id)) {
|
||||
return structure.waypoints.map((waypoint) => waypoint.id);
|
||||
}
|
||||
return structure.tracks.find((track) => track.id === id)?.segments.map((s) => s.id) ?? [];
|
||||
}
|
||||
|
||||
function descendants(structure: FileStructure, id: string): string[] {
|
||||
return children(structure, id).flatMap((child) => [child, ...descendants(structure, child)]);
|
||||
}
|
||||
|
||||
/** The closest explicit visibility on a path (from the file down): whether it is hidden. */
|
||||
function followsHidden(visibility: Visibility, path: string[]): boolean {
|
||||
for (let i = path.length - 1; i >= 0; i--) {
|
||||
const shown = visibility.get(path[i]);
|
||||
if (shown !== undefined) {
|
||||
return !shown;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an element is hidden: its closest explicit ancestor (or itself) is hidden, and none
|
||||
* of its descendants was shown. A file whose only visible segment was shown on its own is not
|
||||
* hidden, its other segments are. Unknown ids are not hidden.
|
||||
*/
|
||||
export function isHidden({ structure, visibility }: VisibilityState, id: string): boolean {
|
||||
return (
|
||||
followsHidden(visibility, pathTo(structure, id)) &&
|
||||
!descendants(structure, id).some((descendant) => visibility.get(descendant) === true)
|
||||
);
|
||||
}
|
||||
|
||||
// Leaf elements have no descendants: no need to look at the structure.
|
||||
|
||||
/** Whether a segment is hidden: `parentId` is its route (which is a leaf), or its track. */
|
||||
export function isSegmentHidden(
|
||||
{ structure, visibility }: VisibilityState,
|
||||
parentId: string,
|
||||
segmentId: string
|
||||
): boolean {
|
||||
return followsHidden(visibility, [structure.id, parentId, segmentId]);
|
||||
}
|
||||
|
||||
export function isWaypointHidden(
|
||||
{ structure, visibility }: VisibilityState,
|
||||
waypointId: string
|
||||
): boolean {
|
||||
return followsHidden(visibility, [structure.id, waypointsKey(structure.id), waypointId]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hides or shows elements of a file, and returns the new visibility. What was set explicitly
|
||||
* below these elements is reset, so that hiding a file then showing one of its segments leaves
|
||||
* only that segment visible, and hiding the file again hides all of it.
|
||||
*/
|
||||
export function setHidden(
|
||||
structure: FileStructure,
|
||||
visibility: Visibility,
|
||||
ids: string[],
|
||||
hidden: boolean
|
||||
): Visibility {
|
||||
const next = new Map(visibility);
|
||||
ids.forEach((id) => {
|
||||
descendants(structure, id).forEach((child) => next.delete(child));
|
||||
next.set(id, !hidden);
|
||||
});
|
||||
return next;
|
||||
}
|
||||
|
||||
/** Name under which the visibility of the files is kept in the storage. */
|
||||
export const VISIBILITY_KEY = 'visibility';
|
||||
|
||||
/**
|
||||
* The visibility of the files as JSON, to keep it: the explicit visibility of each file by id,
|
||||
* leaving out the files that `keep` refuses (the ones that are gone) and the ones that have none.
|
||||
* `undefined` when there is nothing to keep.
|
||||
*/
|
||||
export function stringifyVisibility(
|
||||
files: ReadonlyMap<string, Visibility>,
|
||||
keep: (fileId: string) => boolean
|
||||
): string | undefined {
|
||||
const data: Record<string, Record<string, boolean>> = {};
|
||||
files.forEach((visibility, fileId) => {
|
||||
if (visibility.size > 0 && keep(fileId)) {
|
||||
data[fileId] = Object.fromEntries(visibility);
|
||||
}
|
||||
});
|
||||
return Object.keys(data).length > 0 ? JSON.stringify(data) : undefined;
|
||||
}
|
||||
|
||||
/** What `stringifyVisibility` gave back. What does not make sense is left out. */
|
||||
export function parseVisibility(json: string | undefined): Map<string, Visibility> {
|
||||
const files = new Map<string, Visibility>();
|
||||
if (json === undefined) {
|
||||
return files;
|
||||
}
|
||||
try {
|
||||
const data: unknown = JSON.parse(json);
|
||||
if (typeof data !== 'object' || data === null) {
|
||||
return files;
|
||||
}
|
||||
for (const [fileId, entries] of Object.entries(data)) {
|
||||
if (typeof entries !== 'object' || entries === null) {
|
||||
continue;
|
||||
}
|
||||
const visibility = new Map<string, boolean>();
|
||||
for (const [id, shown] of Object.entries(entries)) {
|
||||
if (typeof shown === 'boolean') {
|
||||
visibility.set(id, shown);
|
||||
}
|
||||
}
|
||||
if (visibility.size > 0) {
|
||||
files.set(fileId, visibility);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// not something that was kept
|
||||
}
|
||||
return files;
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
// The engine of the files, as the UI sees it: stores that follow what the WASM engine holds.
|
||||
//
|
||||
// - `engine.ts`: the facade, with the actions and the stores
|
||||
// - `types.ts`: the types of what it gives
|
||||
// - `file-state.ts`: reads the state of a file (GeoJSON features, statistics...) from the engine
|
||||
// - `statistics.ts`: reads the statistics of the selection, and only the metrics that are needed
|
||||
// - `storage.ts`: opens the storage of the browser, and imports what the old versions kept
|
||||
// - `observer.ts`: tells when the stores of the files appear and disappear
|
||||
// - `convert.ts`: conversions between the UI's values and the engine's
|
||||
|
||||
export * from './types';
|
||||
export { engine } from './engine';
|
||||
export { FileStateCollectionObserver } from './observer';
|
||||
@@ -0,0 +1,50 @@
|
||||
import type { Readable } from 'svelte/store';
|
||||
import { engine } from './engine';
|
||||
import type { FileState, FileStatesCallback } from './types';
|
||||
|
||||
/**
|
||||
* Tells when file stores appear and disappear, so that their subscribers know when to
|
||||
* subscribe and unsubscribe. `onFilesAdded` is called with the stores of the new files only
|
||||
* (including the ones already present when the observer is created).
|
||||
*/
|
||||
export class FileStateCollectionObserver {
|
||||
private _fileIds = new Set<string>();
|
||||
private _onFilesAdded: FileStatesCallback;
|
||||
private _onFileRemoved: (fileId: string) => void;
|
||||
private _onDestroy: () => void;
|
||||
private _unsubscribe: () => void;
|
||||
|
||||
constructor(
|
||||
onFilesAdded: FileStatesCallback,
|
||||
onFileRemoved: (fileId: string) => void,
|
||||
onDestroy: () => void
|
||||
) {
|
||||
this._onFilesAdded = onFilesAdded;
|
||||
this._onFileRemoved = onFileRemoved;
|
||||
this._onDestroy = onDestroy;
|
||||
|
||||
this._unsubscribe = engine.files.subscribe((files) => {
|
||||
this._fileIds.forEach((fileId) => {
|
||||
if (!files.has(fileId)) {
|
||||
this._onFileRemoved(fileId);
|
||||
this._fileIds.delete(fileId);
|
||||
}
|
||||
});
|
||||
const newFiles = new Map<string, Readable<FileState>>();
|
||||
files.forEach((store, fileId) => {
|
||||
if (!this._fileIds.has(fileId)) {
|
||||
newFiles.set(fileId, store);
|
||||
this._fileIds.add(fileId);
|
||||
}
|
||||
});
|
||||
if (newFiles.size > 0) {
|
||||
this._onFilesAdded(newFiles);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
destroy() {
|
||||
this._onDestroy();
|
||||
this._unsubscribe();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import type { Clipboard, FileStructure, Selection } from 'gpx-wasm';
|
||||
import type { VisibilityState } from '$lib/engine/file-visibility';
|
||||
import {
|
||||
coversSegments,
|
||||
elementId,
|
||||
fileConversion,
|
||||
hasSelectionWithin,
|
||||
isCovered,
|
||||
isInClipboard,
|
||||
isEmpty,
|
||||
isSelected,
|
||||
isSelectionHidden,
|
||||
selectedElementIds,
|
||||
selectedFileIds,
|
||||
selectionSize,
|
||||
type FileTreeNode,
|
||||
} from '$lib/engine/selection-helpers';
|
||||
|
||||
// Two files; F1 has the route R1, the tracks T1 (segments S1, S2) and T2 (segment S3), and
|
||||
// waypoints W1, W2.
|
||||
const nodes: Record<string, FileTreeNode> = {
|
||||
F1: { type: 'file', fileId: 'F1' },
|
||||
F2: { type: 'file', fileId: 'F2' },
|
||||
R1: { type: 'route', fileId: 'F1', routeId: 'R1' },
|
||||
T1: { type: 'track', fileId: 'F1', trackId: 'T1' },
|
||||
T2: { type: 'track', fileId: 'F1', trackId: 'T2' },
|
||||
S1: { type: 'segment', fileId: 'F1', trackId: 'T1', segmentId: 'S1' },
|
||||
S2: { type: 'segment', fileId: 'F1', trackId: 'T1', segmentId: 'S2' },
|
||||
S3: { type: 'segment', fileId: 'F1', trackId: 'T2', segmentId: 'S3' },
|
||||
WPTS: { type: 'waypoints', fileId: 'F1' },
|
||||
W1: { type: 'waypoint', fileId: 'F1', waypointId: 'W1' },
|
||||
W2: { type: 'waypoint', fileId: 'F1', waypointId: 'W2' },
|
||||
// same ids in another file
|
||||
F2_WPTS: { type: 'waypoints', fileId: 'F2' },
|
||||
};
|
||||
|
||||
const empty: Selection = { type: 'empty' };
|
||||
const files = (...fileIds: string[]): Selection => ({ type: 'file', fileIds });
|
||||
const routes = (...routeIds: string[]): Selection => ({ type: 'route', fileId: 'F1', routeIds });
|
||||
const tracks = (...trackIds: string[]): Selection => ({ type: 'track', fileId: 'F1', trackIds });
|
||||
const segments = (trackId: string, ...segmentIds: string[]): Selection => ({
|
||||
type: 'segment',
|
||||
fileId: 'F1',
|
||||
trackId,
|
||||
segmentIds,
|
||||
});
|
||||
const waypoints: Selection = { type: 'waypoints', fileId: 'F1' };
|
||||
const waypoint = (...waypointIds: string[]): Selection => ({
|
||||
type: 'waypoint',
|
||||
fileId: 'F1',
|
||||
waypointIds,
|
||||
});
|
||||
|
||||
/** The names of the nodes for which `predicate` holds, to compare with what is expected. */
|
||||
function matching(selection: Selection, predicate: typeof isSelected): string[] {
|
||||
return Object.keys(nodes).filter((name) => predicate(selection, nodes[name]));
|
||||
}
|
||||
|
||||
describe('selection helpers', () => {
|
||||
it('tells whether the selection is made of segments', () => {
|
||||
for (const selection of [files('F1'), routes('R1'), tracks('T1'), segments('T1', 'S1')]) {
|
||||
assert.equal(coversSegments(selection), true);
|
||||
}
|
||||
for (const selection of [empty, waypoints, waypoint('W1')]) {
|
||||
assert.equal(coversSegments(selection), false);
|
||||
}
|
||||
});
|
||||
|
||||
it('tells whether the selection is empty', () => {
|
||||
assert.equal(isEmpty(empty), true);
|
||||
assert.equal(isEmpty(files('F1')), false);
|
||||
assert.equal(isEmpty(waypoints), false);
|
||||
});
|
||||
|
||||
it('lists the files holding something selected', () => {
|
||||
assert.deepEqual(selectedFileIds(empty), []);
|
||||
assert.deepEqual(selectedFileIds(files('F1', 'F2')), ['F1', 'F2']);
|
||||
assert.deepEqual(selectedFileIds(tracks('T1')), ['F1']);
|
||||
assert.deepEqual(selectedFileIds(segments('T1', 'S1')), ['F1']);
|
||||
assert.deepEqual(selectedFileIds(waypoints), ['F1']);
|
||||
assert.deepEqual(selectedFileIds(waypoint('W1')), ['F1']);
|
||||
});
|
||||
|
||||
it('gives the id of the element of a node', () => {
|
||||
assert.deepEqual(
|
||||
Object.keys(nodes).map((name) => elementId(nodes[name])),
|
||||
[
|
||||
'F1',
|
||||
'F2',
|
||||
'R1',
|
||||
'T1',
|
||||
'T2',
|
||||
'S1',
|
||||
'S2',
|
||||
'S3',
|
||||
'F1:waypoints',
|
||||
'W1',
|
||||
'W2',
|
||||
'F2:waypoints',
|
||||
]
|
||||
);
|
||||
});
|
||||
|
||||
it('tells which nodes are in the clipboard', () => {
|
||||
const clipboard = (type: Clipboard['type'], ids: string[]): Clipboard => ({
|
||||
type,
|
||||
ids,
|
||||
cut: true,
|
||||
});
|
||||
assert.deepEqual(
|
||||
matching(empty, (_, node) => isInClipboard(undefined, node)),
|
||||
[]
|
||||
);
|
||||
const inClipboard = (c: Clipboard) =>
|
||||
Object.keys(nodes).filter((name) => isInClipboard(c, nodes[name]));
|
||||
assert.deepEqual(inClipboard(clipboard('files', ['F2'])), ['F2']);
|
||||
assert.deepEqual(inClipboard(clipboard('tracks', ['T2', 'S1'])), ['T2']);
|
||||
assert.deepEqual(inClipboard(clipboard('routes', ['R1', 'T1'])), ['R1']);
|
||||
assert.deepEqual(inClipboard(clipboard('segments', ['S1', 'S3'])), ['S1', 'S3']);
|
||||
assert.deepEqual(inClipboard(clipboard('waypoints', ['W2'])), ['W2']);
|
||||
// not mixed up with the other kinds of elements
|
||||
assert.deepEqual(inClipboard(clipboard('files', ['T1', 'S1', 'W1'])), []);
|
||||
});
|
||||
|
||||
it('counts the selected elements', () => {
|
||||
assert.equal(selectionSize(empty), 0);
|
||||
assert.equal(selectionSize(files('F1', 'F2')), 2);
|
||||
assert.equal(selectionSize(routes('R1')), 1);
|
||||
assert.equal(selectionSize(tracks('T1')), 1);
|
||||
assert.equal(selectionSize(segments('T1', 'S1', 'S2')), 2);
|
||||
assert.equal(selectionSize(waypoints), 1);
|
||||
assert.equal(selectionSize(waypoint('W1', 'W2')), 2);
|
||||
});
|
||||
|
||||
it('lists the ids of the selected elements by file', () => {
|
||||
assert.deepEqual(selectedElementIds(empty), []);
|
||||
assert.deepEqual(selectedElementIds(files('F1', 'F2')), [
|
||||
{ fileId: 'F1', ids: ['F1'] },
|
||||
{ fileId: 'F2', ids: ['F2'] },
|
||||
]);
|
||||
assert.deepEqual(selectedElementIds(routes('R1')), [{ fileId: 'F1', ids: ['R1'] }]);
|
||||
assert.deepEqual(selectedElementIds(tracks('T1', 'T2')), [
|
||||
{ fileId: 'F1', ids: ['T1', 'T2'] },
|
||||
]);
|
||||
assert.deepEqual(selectedElementIds(segments('T1', 'S1')), [{ fileId: 'F1', ids: ['S1'] }]);
|
||||
assert.deepEqual(selectedElementIds(waypoints), [{ fileId: 'F1', ids: ['F1:waypoints'] }]);
|
||||
assert.deepEqual(selectedElementIds(waypoint('W1')), [{ fileId: 'F1', ids: ['W1'] }]);
|
||||
});
|
||||
|
||||
describe('isSelected', () => {
|
||||
it('matches the selected nodes only', () => {
|
||||
assert.deepEqual(matching(empty, isSelected), []);
|
||||
assert.deepEqual(matching(files('F1', 'F2'), isSelected), ['F1', 'F2']);
|
||||
assert.deepEqual(matching(routes('R1'), isSelected), ['R1']);
|
||||
assert.deepEqual(matching(tracks('T1', 'T2'), isSelected), ['T1', 'T2']);
|
||||
assert.deepEqual(matching(segments('T1', 'S1'), isSelected), ['S1']);
|
||||
assert.deepEqual(matching(waypoints, isSelected), ['WPTS']);
|
||||
assert.deepEqual(matching(waypoint('W2'), isSelected), ['W2']);
|
||||
});
|
||||
|
||||
it('does not mix up the track of a segment, nor the file', () => {
|
||||
// S3 belongs to T2: selecting "S3 of T1" does not select it
|
||||
assert.equal(isSelected(segments('T1', 'S3'), nodes.S3), false);
|
||||
assert.equal(isSelected(files('F2'), nodes.F1), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isCovered', () => {
|
||||
it('covers everything below a selected file', () => {
|
||||
assert.deepEqual(
|
||||
matching(files('F1'), isCovered),
|
||||
Object.keys(nodes).filter((name) => name !== 'F2' && name !== 'F2_WPTS')
|
||||
);
|
||||
});
|
||||
|
||||
it('covers the segments of a selected track, not its siblings', () => {
|
||||
assert.deepEqual(matching(tracks('T1'), isCovered), ['T1', 'S1', 'S2']);
|
||||
assert.deepEqual(matching(routes('R1'), isCovered), ['R1']);
|
||||
});
|
||||
|
||||
it('covers the waypoints below the waypoints node', () => {
|
||||
assert.deepEqual(matching(waypoints, isCovered), ['WPTS', 'W1', 'W2']);
|
||||
});
|
||||
|
||||
it('does not cover parents, siblings or the other files', () => {
|
||||
assert.deepEqual(matching(segments('T1', 'S1'), isCovered), ['S1']);
|
||||
assert.deepEqual(matching(waypoint('W1'), isCovered), ['W1']);
|
||||
assert.deepEqual(matching(empty, isCovered), []);
|
||||
});
|
||||
});
|
||||
|
||||
describe('hasSelectionWithin', () => {
|
||||
it('looks at the descendants of a file, whatever their kind', () => {
|
||||
for (const selection of [
|
||||
files('F1'),
|
||||
routes('R1'),
|
||||
tracks('T1'),
|
||||
segments('T1', 'S1'),
|
||||
waypoints,
|
||||
waypoint('W1'),
|
||||
]) {
|
||||
assert.equal(hasSelectionWithin(selection, nodes.F1), true);
|
||||
assert.equal(hasSelectionWithin(selection, nodes.F2), false);
|
||||
}
|
||||
assert.equal(hasSelectionWithin(empty, nodes.F1), false);
|
||||
});
|
||||
|
||||
it('looks at a route, which has no node below it', () => {
|
||||
assert.deepEqual(matching(routes('R1'), hasSelectionWithin), ['F1', 'R1']);
|
||||
});
|
||||
|
||||
it('looks at the segments of a track', () => {
|
||||
assert.deepEqual(matching(tracks('T1'), hasSelectionWithin), ['F1', 'T1']);
|
||||
assert.deepEqual(matching(segments('T1', 'S2'), hasSelectionWithin), [
|
||||
'F1',
|
||||
'T1',
|
||||
'S2',
|
||||
]);
|
||||
});
|
||||
|
||||
it('looks at the waypoints below the waypoints node', () => {
|
||||
assert.deepEqual(matching(waypoints, hasSelectionWithin), ['F1', 'WPTS']);
|
||||
assert.deepEqual(matching(waypoint('W1'), hasSelectionWithin), ['F1', 'WPTS', 'W1']);
|
||||
});
|
||||
|
||||
it('does not look at ancestors', () => {
|
||||
// a selected file does not mean that its segments hold a selection
|
||||
assert.deepEqual(matching(files('F1'), hasSelectionWithin), ['F1']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSelectionHidden', () => {
|
||||
const segment = (id: string) => ({ id, rev: id, length: 2 });
|
||||
const structure: FileStructure = {
|
||||
id: 'F1',
|
||||
name: 'file',
|
||||
waypointsRev: 'rev',
|
||||
waypoints: [{ id: 'W1' }, { id: 'W2' }],
|
||||
routes: [],
|
||||
tracks: [
|
||||
{ id: 'T1', segments: [segment('S1'), segment('S2')] },
|
||||
{ id: 'T2', segments: [segment('S3')] },
|
||||
],
|
||||
};
|
||||
const states = (...hidden: string[]) =>
|
||||
new Map<string, VisibilityState>([
|
||||
[
|
||||
'F1',
|
||||
{ structure, visibility: new Map(hidden.map((id) => [id, false] as const)) },
|
||||
],
|
||||
]);
|
||||
|
||||
it('is false when nothing is selected', () => {
|
||||
assert.equal(isSelectionHidden(empty, states('F1')), false);
|
||||
});
|
||||
|
||||
it('is true when everything selected is hidden', () => {
|
||||
assert.equal(isSelectionHidden(files('F1'), states('F1')), true);
|
||||
assert.equal(isSelectionHidden(tracks('T1', 'T2'), states('T1', 'T2')), true);
|
||||
// through a hidden parent
|
||||
assert.equal(isSelectionHidden(segments('T1', 'S1', 'S2'), states('T1')), true);
|
||||
assert.equal(isSelectionHidden(waypoint('W1', 'W2'), states('F1:waypoints')), true);
|
||||
assert.equal(isSelectionHidden(waypoints, states('F1:waypoints')), true);
|
||||
});
|
||||
|
||||
it('is false as soon as one selected element is visible', () => {
|
||||
assert.equal(isSelectionHidden(files('F1'), states()), false);
|
||||
assert.equal(isSelectionHidden(tracks('T1', 'T2'), states('T1')), false);
|
||||
assert.equal(isSelectionHidden(waypoint('W1', 'W2'), states('W1')), false);
|
||||
});
|
||||
|
||||
it('is false for files that are not known', () => {
|
||||
assert.equal(isSelectionHidden(files('F1', 'F2'), states('F1')), false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('fileConversion', () => {
|
||||
const segment = (id: string) => ({ id, rev: id, length: 2 });
|
||||
const structure = (routes: string[], tracks: string[]): { structure: FileStructure } => ({
|
||||
structure: {
|
||||
id: 'F',
|
||||
name: 'file',
|
||||
waypointsRev: 'rev',
|
||||
waypoints: [],
|
||||
routes: routes.map((id) => ({ id, segment: segment(`${id}-S`) })),
|
||||
tracks: tracks.map((id) => ({ id, segments: [segment(`${id}-S`)] })),
|
||||
},
|
||||
});
|
||||
const states = new Map([
|
||||
['routes', structure(['R1', 'R2'], [])],
|
||||
['tracks', structure([], ['T1'])],
|
||||
['both', structure(['R1'], ['T1'])],
|
||||
['none', structure([], [])],
|
||||
]);
|
||||
|
||||
it('converts files with tracks only to routes, and routes only to tracks', () => {
|
||||
assert.equal(fileConversion(files('tracks'), states), 'route');
|
||||
assert.equal(fileConversion(files('routes'), states), 'track');
|
||||
});
|
||||
|
||||
it('does not convert files with both, neither, or a mix of the two', () => {
|
||||
assert.equal(fileConversion(files('both'), states), undefined);
|
||||
assert.equal(fileConversion(files('none'), states), undefined);
|
||||
assert.equal(fileConversion(files('routes', 'tracks'), states), undefined);
|
||||
assert.equal(fileConversion(files('unknown'), states), undefined);
|
||||
});
|
||||
|
||||
it('only converts files', () => {
|
||||
assert.equal(fileConversion(empty, states), undefined);
|
||||
assert.equal(fileConversion(tracks('T1'), states), undefined);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,280 @@
|
||||
import type { Clipboard, FileStructure, PathInfo, Selection } from 'gpx-wasm';
|
||||
import { isHidden, waypointsKey, type VisibilityState } from '$lib/engine/file-visibility';
|
||||
|
||||
/**
|
||||
* An element of the file tree, to ask questions about the selection:
|
||||
*
|
||||
* file ─┬─ route
|
||||
* ├─ track ─── segment
|
||||
* └─ waypoints ─── waypoint
|
||||
*
|
||||
* A route is like a track of a single segment, which is not a node of its own. `waypoints` is the
|
||||
* node standing for all the waypoints of a file.
|
||||
*/
|
||||
export type FileTreeNode =
|
||||
| { type: 'file'; fileId: string }
|
||||
| { type: 'route'; fileId: string; routeId: string }
|
||||
| { type: 'track'; fileId: string; trackId: string }
|
||||
| { type: 'segment'; fileId: string; trackId: string; segmentId: string }
|
||||
| { type: 'waypoints'; fileId: string }
|
||||
| { type: 'waypoint'; fileId: string; waypointId: string };
|
||||
|
||||
/**
|
||||
* The id of the element of a node, as used by the visibility (`waypointsKey` for the waypoints
|
||||
* node).
|
||||
*/
|
||||
export function elementId(node: FileTreeNode): string {
|
||||
switch (node.type) {
|
||||
case 'file':
|
||||
return node.fileId;
|
||||
case 'route':
|
||||
return node.routeId;
|
||||
case 'track':
|
||||
return node.trackId;
|
||||
case 'segment':
|
||||
return node.segmentId;
|
||||
case 'waypoints':
|
||||
return waypointsKey(node.fileId);
|
||||
case 'waypoint':
|
||||
return node.waypointId;
|
||||
}
|
||||
}
|
||||
|
||||
/** The name, description and style of a route or track node, `undefined` for the other nodes. */
|
||||
export function pathInfo(structure: FileStructure, node: FileTreeNode): PathInfo | undefined {
|
||||
switch (node.type) {
|
||||
case 'route':
|
||||
return structure.routes.find((route) => route.id === node.routeId);
|
||||
case 'track':
|
||||
return structure.tracks.find((track) => track.id === node.trackId);
|
||||
default:
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the selection is made of segments: files, routes, tracks or segments, not waypoints (the
|
||||
* selection the tools that work on trackpoints work on).
|
||||
*/
|
||||
export function coversSegments(selection: Selection): boolean {
|
||||
return (
|
||||
selection.type === 'file' ||
|
||||
selection.type === 'route' ||
|
||||
selection.type === 'track' ||
|
||||
selection.type === 'segment'
|
||||
);
|
||||
}
|
||||
|
||||
export function isEmpty(selection: Selection): boolean {
|
||||
return selection.type === 'empty';
|
||||
}
|
||||
|
||||
/** Ids of the files holding something selected (or selected themselves). */
|
||||
export function selectedFileIds(selection: Selection): string[] {
|
||||
switch (selection.type) {
|
||||
case 'empty':
|
||||
return [];
|
||||
case 'file':
|
||||
return selection.fileIds;
|
||||
default:
|
||||
return [selection.fileId];
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the node is one of the elements in the clipboard. */
|
||||
export function isInClipboard(clipboard: Clipboard | undefined, node: FileTreeNode): boolean {
|
||||
if (!clipboard) {
|
||||
return false;
|
||||
}
|
||||
switch (node.type) {
|
||||
case 'file':
|
||||
return clipboard.type === 'files' && clipboard.ids.includes(node.fileId);
|
||||
case 'route':
|
||||
return clipboard.type === 'routes' && clipboard.ids.includes(node.routeId);
|
||||
case 'track':
|
||||
return clipboard.type === 'tracks' && clipboard.ids.includes(node.trackId);
|
||||
case 'segment':
|
||||
return clipboard.type === 'segments' && clipboard.ids.includes(node.segmentId);
|
||||
case 'waypoint':
|
||||
return clipboard.type === 'waypoints' && clipboard.ids.includes(node.waypointId);
|
||||
case 'waypoints':
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** Number of selected elements (the waypoints node counts for one). */
|
||||
export function selectionSize(selection: Selection): number {
|
||||
switch (selection.type) {
|
||||
case 'empty':
|
||||
return 0;
|
||||
case 'file':
|
||||
return selection.fileIds.length;
|
||||
case 'route':
|
||||
return selection.routeIds.length;
|
||||
case 'track':
|
||||
return selection.trackIds.length;
|
||||
case 'segment':
|
||||
return selection.segmentIds.length;
|
||||
case 'waypoints':
|
||||
return 1;
|
||||
case 'waypoint':
|
||||
return selection.waypointIds.length;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The ids of the selected elements, by file, as used by the visibility (a file, its routes, its
|
||||
* tracks, its segments, its waypoints, or `waypointsKey` for the waypoints node).
|
||||
*/
|
||||
export function selectedElementIds(selection: Selection): { fileId: string; ids: string[] }[] {
|
||||
switch (selection.type) {
|
||||
case 'empty':
|
||||
return [];
|
||||
case 'file':
|
||||
return selection.fileIds.map((fileId) => ({ fileId, ids: [fileId] }));
|
||||
case 'route':
|
||||
return [{ fileId: selection.fileId, ids: selection.routeIds }];
|
||||
case 'track':
|
||||
return [{ fileId: selection.fileId, ids: selection.trackIds }];
|
||||
case 'segment':
|
||||
return [{ fileId: selection.fileId, ids: selection.segmentIds }];
|
||||
case 'waypoints':
|
||||
return [{ fileId: selection.fileId, ids: [waypointsKey(selection.fileId)] }];
|
||||
case 'waypoint':
|
||||
return [{ fileId: selection.fileId, ids: selection.waypointIds }];
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the node itself is selected. */
|
||||
export function isSelected(selection: Selection, node: FileTreeNode): boolean {
|
||||
switch (node.type) {
|
||||
case 'file':
|
||||
return selection.type === 'file' && selection.fileIds.includes(node.fileId);
|
||||
case 'route':
|
||||
return (
|
||||
selection.type === 'route' &&
|
||||
selection.fileId === node.fileId &&
|
||||
selection.routeIds.includes(node.routeId)
|
||||
);
|
||||
case 'track':
|
||||
return (
|
||||
selection.type === 'track' &&
|
||||
selection.fileId === node.fileId &&
|
||||
selection.trackIds.includes(node.trackId)
|
||||
);
|
||||
case 'segment':
|
||||
return (
|
||||
selection.type === 'segment' &&
|
||||
selection.fileId === node.fileId &&
|
||||
selection.trackId === node.trackId &&
|
||||
selection.segmentIds.includes(node.segmentId)
|
||||
);
|
||||
case 'waypoints':
|
||||
return selection.type === 'waypoints' && selection.fileId === node.fileId;
|
||||
case 'waypoint':
|
||||
return (
|
||||
selection.type === 'waypoint' &&
|
||||
selection.fileId === node.fileId &&
|
||||
selection.waypointIds.includes(node.waypointId)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** The parent of a node, `undefined` for a file. */
|
||||
function parent(node: FileTreeNode): FileTreeNode | undefined {
|
||||
switch (node.type) {
|
||||
case 'file':
|
||||
return undefined;
|
||||
case 'route':
|
||||
case 'track':
|
||||
case 'waypoints':
|
||||
return { type: 'file', fileId: node.fileId };
|
||||
case 'segment':
|
||||
return { type: 'track', fileId: node.fileId, trackId: node.trackId };
|
||||
case 'waypoint':
|
||||
return { type: 'waypoints', fileId: node.fileId };
|
||||
}
|
||||
}
|
||||
|
||||
/** Whether the node, or one of its ancestors, is selected: the node is covered by the selection. */
|
||||
export function isCovered(selection: Selection, node: FileTreeNode): boolean {
|
||||
for (let n: FileTreeNode | undefined = node; n; n = parent(n)) {
|
||||
if (isSelected(selection, n)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Whether the node, or one of its descendants, is selected. */
|
||||
export function hasSelectionWithin(selection: Selection, node: FileTreeNode): boolean {
|
||||
switch (node.type) {
|
||||
case 'file':
|
||||
return selectedFileIds(selection).includes(node.fileId);
|
||||
case 'track':
|
||||
return (
|
||||
isSelected(selection, node) ||
|
||||
(selection.type === 'segment' &&
|
||||
selection.fileId === node.fileId &&
|
||||
selection.trackId === node.trackId)
|
||||
);
|
||||
case 'waypoints':
|
||||
return (
|
||||
isSelected(selection, node) ||
|
||||
(selection.type === 'waypoint' && selection.fileId === node.fileId)
|
||||
);
|
||||
case 'route':
|
||||
case 'segment':
|
||||
case 'waypoint':
|
||||
return isSelected(selection, node);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether all the selected elements are hidden (false when nothing is selected). `states` holds
|
||||
* the files by id: an element of an unknown file is not hidden.
|
||||
*/
|
||||
export function isSelectionHidden(
|
||||
selection: Selection,
|
||||
states: ReadonlyMap<string, VisibilityState>
|
||||
): boolean {
|
||||
const selected = selectedElementIds(selection);
|
||||
return (
|
||||
selected.length > 0 &&
|
||||
selected.every(({ fileId, ids }) => {
|
||||
const state = states.get(fileId);
|
||||
return state !== undefined && ids.every((id) => isHidden(state, id));
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* What the selected files convert to: `'route'` when they all have tracks only (with segments),
|
||||
* `'track'` when they all have routes only, `undefined` otherwise (other selections, files with
|
||||
* both or neither, or a mix of the two). `states` holds the files by id.
|
||||
*/
|
||||
export function fileConversion(
|
||||
selection: Selection,
|
||||
states: ReadonlyMap<string, { structure: FileStructure }>
|
||||
): 'route' | 'track' | undefined {
|
||||
if (selection.type !== 'file' || selection.fileIds.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
const targets = new Set(
|
||||
selection.fileIds.map((fileId) => {
|
||||
const structure = states.get(fileId)?.structure;
|
||||
if (structure === undefined) {
|
||||
return undefined;
|
||||
} else if (structure.routes.length > 0 && structure.tracks.length === 0) {
|
||||
return 'track' as const;
|
||||
} else if (
|
||||
structure.routes.length === 0 &&
|
||||
structure.tracks.some((track) => track.segments.length > 0)
|
||||
) {
|
||||
return 'route' as const;
|
||||
}
|
||||
return undefined;
|
||||
})
|
||||
);
|
||||
return targets.size === 1 ? targets.values().next().value : undefined;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { readable, type Readable } from 'svelte/store';
|
||||
import { engine, FileStateCollectionObserver, type FileState, type Selection } from '$lib/engine';
|
||||
import { fileConversion, isSelectionHidden } from '$lib/engine/selection-helpers';
|
||||
|
||||
/**
|
||||
* A value computed from the selection and the states of the files. It follows the selection and,
|
||||
* through the observer of the files, the state of every file (hiding, editing).
|
||||
*/
|
||||
function fromSelectionAndFiles<T>(
|
||||
initial: T,
|
||||
compute: (selection: Selection, states: ReadonlyMap<string, FileState>) => T
|
||||
): Readable<T> {
|
||||
return readable(initial, (set) => {
|
||||
let selection: Selection = { type: 'empty' };
|
||||
const states = new Map<string, FileState>();
|
||||
const unsubscribes = new Map<string, () => void>();
|
||||
|
||||
const update = () => set(compute(selection, states));
|
||||
|
||||
const unsubscribeSelection = engine.selection.subscribe(($selection) => {
|
||||
selection = $selection;
|
||||
update();
|
||||
});
|
||||
const observer = new FileStateCollectionObserver(
|
||||
(files) => {
|
||||
files.forEach((store, fileId) => {
|
||||
unsubscribes.set(
|
||||
fileId,
|
||||
store.subscribe(($file) => {
|
||||
states.set(fileId, $file);
|
||||
update();
|
||||
})
|
||||
);
|
||||
});
|
||||
},
|
||||
(fileId) => {
|
||||
unsubscribes.get(fileId)?.();
|
||||
unsubscribes.delete(fileId);
|
||||
states.delete(fileId);
|
||||
update();
|
||||
},
|
||||
() => {
|
||||
unsubscribes.forEach((unsubscribe) => unsubscribe());
|
||||
unsubscribes.clear();
|
||||
states.clear();
|
||||
}
|
||||
);
|
||||
|
||||
return () => {
|
||||
unsubscribeSelection();
|
||||
observer.destroy();
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
/** Whether all the selected elements are hidden. */
|
||||
export const allHidden = fromSelectionAndFiles(false, isSelectionHidden);
|
||||
|
||||
/** What the selected files convert to, see `fileConversion`. */
|
||||
export const selectedFilesConversion = fromSelectionAndFiles<'route' | 'track' | undefined>(
|
||||
undefined,
|
||||
fileConversion
|
||||
);
|
||||
@@ -0,0 +1,214 @@
|
||||
import { get, writable, type Readable } from 'svelte/store';
|
||||
import type { CategoryIntervals } from '$lib/engine/trackpoint-categories';
|
||||
import type { Backend } from './backend';
|
||||
import {
|
||||
EMPTY_SELECTION_STATISTICS,
|
||||
EMPTY_STATISTICS,
|
||||
type SelectionStatistics,
|
||||
type StatisticsMetric,
|
||||
type StatisticsRequest,
|
||||
} from './types';
|
||||
|
||||
/**
|
||||
* The statistics of the selection, read from the buffers of the engine. Only the metrics that a
|
||||
* consumer asked for are read (see `request`).
|
||||
*/
|
||||
export class StatisticsReader {
|
||||
private _store = writable<SelectionStatistics>(EMPTY_SELECTION_STATISTICS);
|
||||
readonly store: Readable<SelectionStatistics> = { subscribe: this._store.subscribe };
|
||||
/** Identifies the statistics currently in the engine's buffers. */
|
||||
private _version = 0;
|
||||
/** What each consumer of the statistics asked for. */
|
||||
private _requests = new Set<Set<StatisticsMetric>>();
|
||||
/** The metrics that were read for the current statistics. */
|
||||
private _loaded = new Set<StatisticsMetric>();
|
||||
|
||||
/** The engine, as of the last time the statistics were read. */
|
||||
private _backend: Backend | null = null;
|
||||
|
||||
/** @param enqueue Does a task after the calls to the engine that were made before it. */
|
||||
constructor(private enqueue: <T>(task: () => Promise<T>) => Promise<T>) {}
|
||||
|
||||
/**
|
||||
* Reads the statistics of the selection again, after it or the files changed. Resolves to what
|
||||
* puts them in the store, for the caller to do it together with its other updates.
|
||||
*/
|
||||
async refresh(backend: Backend): Promise<() => void> {
|
||||
this._backend = backend;
|
||||
const statistics = await this.read(backend);
|
||||
return () => this._store.set(statistics);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the statistics buffers of the engine (the getters copy them), but only the metrics
|
||||
* that were requested.
|
||||
*/
|
||||
private async read(backend: Backend): Promise<SelectionStatistics> {
|
||||
const version = ++this._version;
|
||||
this._loaded.clear();
|
||||
const [global, totalDistance, lng, lat, ele] = await Promise.all([
|
||||
backend.selection_statistics(),
|
||||
backend.total_distance(),
|
||||
backend.lng(),
|
||||
backend.lat(),
|
||||
backend.ele(),
|
||||
]);
|
||||
const current = <T>(read: () => Promise<T | undefined>) =>
|
||||
this.enqueue(async () => (version === this._version ? read() : undefined));
|
||||
const statistics: SelectionStatistics = {
|
||||
global: global ?? EMPTY_STATISTICS,
|
||||
length: totalDistance.length,
|
||||
totalDistance,
|
||||
lng,
|
||||
lat,
|
||||
ele,
|
||||
slice: (start, end) => current(() => backend.slice_statistics(start, end)),
|
||||
point: (index) => current(() => backend.selection_point(index)),
|
||||
};
|
||||
await this.readMetrics(backend, statistics, this.requestedMetrics());
|
||||
return statistics;
|
||||
}
|
||||
|
||||
private requestedMetrics(): Set<StatisticsMetric> {
|
||||
const metrics = new Set<StatisticsMetric>();
|
||||
this._requests.forEach((request) => request.forEach((m) => metrics.add(m)));
|
||||
return metrics;
|
||||
}
|
||||
|
||||
/** Reads the metrics that were not read yet into `statistics`, which is the current one. */
|
||||
private async readMetrics(
|
||||
backend: Backend,
|
||||
statistics: SelectionStatistics,
|
||||
metrics: Set<StatisticsMetric>
|
||||
) {
|
||||
const categories = async (
|
||||
starts: Promise<Uint32Array>,
|
||||
values: Promise<Uint8Array>,
|
||||
names: Promise<string[]>
|
||||
): Promise<CategoryIntervals> => {
|
||||
const [s, v, n] = await Promise.all([starts, values, names]);
|
||||
return { starts: s, values: v, names: n };
|
||||
};
|
||||
|
||||
const missing = [...metrics].filter((metric) => !this._loaded.has(metric));
|
||||
missing.forEach((metric) => this._loaded.add(metric));
|
||||
await Promise.all(
|
||||
missing.map(async (metric) => {
|
||||
switch (metric) {
|
||||
case 'speed':
|
||||
statistics.speed = await backend.speed();
|
||||
break;
|
||||
case 'hr':
|
||||
statistics.hr = await backend.hr();
|
||||
break;
|
||||
case 'cad':
|
||||
statistics.cad = await backend.cad();
|
||||
break;
|
||||
case 'atemp':
|
||||
statistics.atemp = await backend.atemp();
|
||||
break;
|
||||
case 'power':
|
||||
statistics.power = await backend.power();
|
||||
break;
|
||||
case 'slopeSegment': {
|
||||
const [starts, slopes] = await Promise.all([
|
||||
backend.slope_segment_starts(),
|
||||
backend.slope_segment_slopes(),
|
||||
]);
|
||||
statistics.slopeSegments = { starts, slopes };
|
||||
break;
|
||||
}
|
||||
case 'surface':
|
||||
statistics.surface = await categories(
|
||||
backend.surface_starts(),
|
||||
backend.surface_values(),
|
||||
backend.surfaces()
|
||||
);
|
||||
break;
|
||||
case 'anchors': {
|
||||
const [indices, zooms, segmentStarts, segmentIds, revision] =
|
||||
await Promise.all([
|
||||
backend.anchor_indices(),
|
||||
backend.anchor_zooms(),
|
||||
backend.segment_starts(),
|
||||
backend.segment_ids(),
|
||||
backend.routing_revision(),
|
||||
]);
|
||||
statistics.anchors = {
|
||||
indices,
|
||||
zooms,
|
||||
segmentStarts,
|
||||
segmentIds,
|
||||
revision,
|
||||
};
|
||||
break;
|
||||
}
|
||||
case 'highway':
|
||||
[statistics.highway, statistics.sacScale, statistics.mtbScale] =
|
||||
await Promise.all([
|
||||
categories(
|
||||
backend.highway_starts(),
|
||||
backend.highway_values(),
|
||||
backend.highways()
|
||||
),
|
||||
categories(
|
||||
backend.sac_scale_starts(),
|
||||
backend.sac_scale_values(),
|
||||
backend.sac_scales()
|
||||
),
|
||||
categories(
|
||||
backend.mtb_scale_starts(),
|
||||
backend.mtb_scale_values(),
|
||||
backend.mtb_scales()
|
||||
),
|
||||
]);
|
||||
break;
|
||||
}
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a consumer of the statistics that needs some of the metrics that are not part of
|
||||
* them by default (see `StatisticsMetric`). The metrics asked for by all the consumers are
|
||||
* added to `statistics`: the ones that are missing are read right away, and then after each
|
||||
* change of the selection or of the files, and the store is updated. Call `release` when the
|
||||
* consumer goes away.
|
||||
*/
|
||||
request(): StatisticsRequest {
|
||||
const wanted = new Set<StatisticsMetric>();
|
||||
this._requests.add(wanted);
|
||||
return {
|
||||
set: (metrics) => {
|
||||
wanted.clear();
|
||||
for (const metric of metrics) {
|
||||
wanted.add(metric);
|
||||
}
|
||||
return this.loadMissing();
|
||||
},
|
||||
release: () => {
|
||||
this._requests.delete(wanted);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Reads the requested metrics that are not in the current statistics yet. */
|
||||
private async loadMissing() {
|
||||
const metrics = this.requestedMetrics();
|
||||
if ([...metrics].every((metric) => this._loaded.has(metric))) {
|
||||
return;
|
||||
}
|
||||
// queued, so that the buffers of the engine still are the ones of the current statistics:
|
||||
// they are read after every action
|
||||
await this.enqueue(async () => {
|
||||
const backend = this._backend;
|
||||
const requested = this.requestedMetrics();
|
||||
if (!backend || [...requested].every((metric) => this._loaded.has(metric))) {
|
||||
return;
|
||||
}
|
||||
const statistics = { ...get(this._store) };
|
||||
await this.readMetrics(backend, statistics, requested);
|
||||
this._store.set(statistics);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { LEGACY_IMPORTED_KEY, readLegacyData } from '$lib/storage/legacy-import';
|
||||
import { parseVisibility, VISIBILITY_KEY, type Visibility } from '$lib/engine/file-visibility';
|
||||
import type { Outcome, StorageOpened } from 'gpx-wasm';
|
||||
import type { Backend } from './backend';
|
||||
|
||||
/** Name of the IndexedDB database that keeps the files and the settings. */
|
||||
const STORAGE_NAME = 'gpx-studio';
|
||||
|
||||
/** Name of the channel that tells the tabs that the files were written. */
|
||||
const CHANNEL_NAME = 'gpx-studio-storage';
|
||||
|
||||
/** What opening the storage needs of the engine facade. */
|
||||
export type StorageHost = {
|
||||
backend: Backend;
|
||||
/** The explicit visibility per file, to fill with the one that was saved. */
|
||||
visibility: Map<string, Visibility>;
|
||||
/** Applies what a call changed to what the facade keeps of the files. */
|
||||
sync(update: Outcome): void;
|
||||
/** Tells that what is stored comes from a newer version of the app: nothing can be saved. */
|
||||
outdated(): void;
|
||||
hasFiles(): boolean;
|
||||
loadFiles(files: { data: Uint8Array; name: string }[]): Promise<boolean>;
|
||||
deselect(): Promise<boolean>;
|
||||
};
|
||||
|
||||
/**
|
||||
* Keeps the files of the engine as the ones that another tab saved: when a tab writes, the others
|
||||
* are told, and read the storage again if it has changed since they last did, which overwrites
|
||||
* what they hold (see `sync_storage`). The same happens when a write of this tab is refused
|
||||
* because of that, and when the tab is shown again (a hidden tab can miss messages).
|
||||
*/
|
||||
function followOtherTabs(host: StorageHost): {
|
||||
saved: () => void;
|
||||
behind: () => void;
|
||||
newer: () => void;
|
||||
} {
|
||||
const { backend } = host;
|
||||
let reading = Promise.resolve();
|
||||
const refresh = () => {
|
||||
reading = reading
|
||||
.then(async () => host.sync(await backend.sync_storage()))
|
||||
.catch((error) => console.error('The files could not be read again', error));
|
||||
};
|
||||
const channel =
|
||||
typeof BroadcastChannel === 'undefined' ? undefined : new BroadcastChannel(CHANNEL_NAME);
|
||||
if (channel) {
|
||||
channel.onmessage = refresh;
|
||||
}
|
||||
if (typeof document !== 'undefined') {
|
||||
document.addEventListener('visibilitychange', () => {
|
||||
if (document.visibilityState === 'visible') {
|
||||
refresh();
|
||||
}
|
||||
});
|
||||
}
|
||||
return {
|
||||
saved: () => channel?.postMessage('saved'),
|
||||
behind: refresh,
|
||||
newer: () => host.outdated(),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the storage: the files that it holds are put in the engine, and the
|
||||
* changes of the files are kept from then on. Resolves to the settings, as JSON strings by key.
|
||||
*
|
||||
* The first time, what the previous versions of the app kept in the browser is imported.
|
||||
*/
|
||||
export async function openStoredFiles(host: StorageHost): Promise<Record<string, string>> {
|
||||
const { backend } = host;
|
||||
let opened: StorageOpened;
|
||||
const tabs = followOtherTabs(host);
|
||||
try {
|
||||
opened = await backend.open_storage(STORAGE_NAME, tabs.saved, tabs.behind, tabs.newer);
|
||||
} catch (error) {
|
||||
console.error('The files cannot be kept in this browser', error);
|
||||
return {};
|
||||
}
|
||||
let settings = opened.settings;
|
||||
// what was hidden, which the files that were restored need when they are read
|
||||
parseVisibility(settings[VISIBILITY_KEY]).forEach((visibility, fileId) =>
|
||||
host.visibility.set(fileId, visibility)
|
||||
);
|
||||
host.sync(opened.outcome);
|
||||
|
||||
if (
|
||||
backend.importsLegacyData &&
|
||||
settings[LEGACY_IMPORTED_KEY] === undefined &&
|
||||
!host.hasFiles()
|
||||
) {
|
||||
settings = { ...settings, ...(await importLegacyData(host)) };
|
||||
await backend.flush_storage();
|
||||
}
|
||||
return settings;
|
||||
}
|
||||
|
||||
/** Puts the files and the settings of the former database in the engine. */
|
||||
async function importLegacyData(host: StorageHost): Promise<Record<string, string>> {
|
||||
const { backend } = host;
|
||||
const imported: Record<string, string> = {};
|
||||
try {
|
||||
const legacy = await readLegacyData();
|
||||
if (legacy) {
|
||||
const encoder = new TextEncoder();
|
||||
if (legacy.files.length > 0) {
|
||||
await host.loadFiles(
|
||||
legacy.files.map((file) => ({
|
||||
data: encoder.encode(file.gpx),
|
||||
name: file.name,
|
||||
}))
|
||||
);
|
||||
await host.deselect();
|
||||
}
|
||||
for (const [key, value] of Object.entries(legacy.settings)) {
|
||||
await backend.set_setting(key, value);
|
||||
imported[key] = value;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
// it is tried again next time
|
||||
console.error('The files of the previous version could not be imported', error);
|
||||
return imported;
|
||||
}
|
||||
await backend.set_setting(LEGACY_IMPORTED_KEY, 'true');
|
||||
imported[LEGACY_IMPORTED_KEY] = 'true';
|
||||
return imported;
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { describe, it } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
categoryIntervals,
|
||||
categoryValue,
|
||||
categoryValues,
|
||||
intervalAt,
|
||||
type CategoryIntervals,
|
||||
} from '$lib/engine/trackpoint-categories';
|
||||
|
||||
describe('categoryValues', () => {
|
||||
// asphalt, asphalt, unknown, gravel, gravel, gravel, unknown
|
||||
const intervals: CategoryIntervals = {
|
||||
starts: new Uint32Array([0, 2, 3, 6]),
|
||||
values: new Uint8Array([1, 0, 2, 0]),
|
||||
names: ['asphalt', 'gravel'],
|
||||
};
|
||||
|
||||
it('is the name of the value of the interval of each trackpoint', () => {
|
||||
assert.deepEqual(categoryValues(intervals, 7), [
|
||||
'asphalt',
|
||||
'asphalt',
|
||||
undefined,
|
||||
'gravel',
|
||||
'gravel',
|
||||
'gravel',
|
||||
undefined,
|
||||
]);
|
||||
});
|
||||
|
||||
it('goes on with the last interval until the last trackpoint', () => {
|
||||
const last = { ...intervals, values: new Uint8Array([1, 0, 2, 2]) };
|
||||
assert.deepEqual(categoryValues(last, 9).slice(5), [
|
||||
'gravel',
|
||||
'gravel',
|
||||
'gravel',
|
||||
'gravel',
|
||||
]);
|
||||
});
|
||||
|
||||
it('does not go past the trackpoints', () => {
|
||||
assert.deepEqual(categoryValues(intervals, 3), ['asphalt', 'asphalt', undefined]);
|
||||
assert.deepEqual(categoryValues(intervals, 0), []);
|
||||
});
|
||||
|
||||
it('is undefined without intervals, or for a code without name', () => {
|
||||
assert.deepEqual(categoryValues(undefined, 2), [undefined, undefined]);
|
||||
const unnamed = { starts: new Uint32Array([0]), values: new Uint8Array([3]), names: [] };
|
||||
assert.deepEqual(categoryValues(unnamed, 2), [undefined, undefined]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('categoryIntervals', () => {
|
||||
it('groups the trackpoints that share a value', () => {
|
||||
const values = ['asphalt', 'asphalt', undefined, 'gravel', 'gravel', 'asphalt', undefined];
|
||||
const intervals = categoryIntervals(values);
|
||||
assert.deepEqual([...intervals.starts], [0, 2, 3, 5, 6]);
|
||||
assert.deepEqual([...intervals.values], [1, 0, 2, 1, 0]);
|
||||
assert.deepEqual(intervals.names, ['asphalt', 'gravel']);
|
||||
// and it goes back to the values
|
||||
assert.deepEqual(categoryValues(intervals, values.length), values);
|
||||
});
|
||||
|
||||
it('has no intervals when the value is unknown everywhere', () => {
|
||||
for (const values of [[], [undefined, undefined]]) {
|
||||
const intervals = categoryIntervals(values);
|
||||
assert.equal(intervals.starts.length, 0);
|
||||
assert.equal(intervals.values.length, 0);
|
||||
assert.deepEqual(intervals.names, []);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('intervalAt', () => {
|
||||
const starts = new Uint32Array([0, 2, 3, 6]);
|
||||
|
||||
it('is the interval that the trackpoint is in', () => {
|
||||
const intervals = [0, 1, 2, 3, 4, 5, 6, 9].map((index) => intervalAt(starts, index));
|
||||
assert.deepEqual(intervals, [0, 0, 1, 2, 2, 2, 3, 3]);
|
||||
});
|
||||
|
||||
it('is -1 when there is no interval', () => {
|
||||
assert.equal(intervalAt(new Uint32Array(), 0), -1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('categoryValue', () => {
|
||||
const intervals: CategoryIntervals = {
|
||||
starts: new Uint32Array([0, 2, 3, 6]),
|
||||
values: new Uint8Array([1, 0, 2, 0]),
|
||||
names: ['asphalt', 'gravel'],
|
||||
};
|
||||
|
||||
it('is the value of each trackpoint, as categoryValues', () => {
|
||||
const values = categoryValues(intervals, 7);
|
||||
values.forEach((value, index) => assert.equal(categoryValue(intervals, index), value));
|
||||
});
|
||||
|
||||
it('is unknown without intervals', () => {
|
||||
assert.equal(categoryValue(undefined, 3), undefined);
|
||||
assert.equal(
|
||||
categoryValue({ starts: new Uint32Array(), values: new Uint8Array(), names: [] }, 0),
|
||||
undefined
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,97 @@
|
||||
/**
|
||||
* A category of the engine (surface, highway...) for each trackpoint, as the intervals of
|
||||
* consecutive trackpoints that share the same value: `starts[i]` is the index of the first
|
||||
* trackpoint of the interval `i`, which lasts until the next start (or the last trackpoint). Its
|
||||
* `values[i]` is 0 when the value is unknown, else 1 + the index of the value in `names`.
|
||||
*/
|
||||
export type CategoryIntervals = {
|
||||
starts: Uint32Array;
|
||||
values: Uint8Array;
|
||||
/** Names of the values, by code: a name keeps its index. */
|
||||
names: string[];
|
||||
};
|
||||
|
||||
/**
|
||||
* The value of each of the `length` trackpoints for a category of the engine, `undefined` when it
|
||||
* is unknown, or when the category is missing (it is unknown for every trackpoint). The intervals
|
||||
* are scanned once, so it takes a time linear in `length`.
|
||||
*/
|
||||
export function categoryValues(
|
||||
intervals: CategoryIntervals | undefined,
|
||||
length: number
|
||||
): (string | undefined)[] {
|
||||
const result: (string | undefined)[] = new Array(length).fill(undefined);
|
||||
if (!intervals) {
|
||||
return result;
|
||||
}
|
||||
const { starts, values, names } = intervals;
|
||||
for (let i = 0; i < starts.length; i++) {
|
||||
if (!values[i]) {
|
||||
continue; // unknown, already `undefined`
|
||||
}
|
||||
const name = names[values[i] - 1];
|
||||
const end = i + 1 < starts.length ? Math.min(starts[i + 1], length) : length;
|
||||
result.fill(name, starts[i], end);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** The index of the interval of `starts` (sorted) that the trackpoint `index` is in, -1 if none. */
|
||||
export function intervalAt(starts: Uint32Array, index: number): number {
|
||||
let low = 0;
|
||||
let high = starts.length;
|
||||
// the first interval that starts after the trackpoint
|
||||
while (low < high) {
|
||||
const middle = (low + high) >>> 1;
|
||||
if (starts[middle] <= index) {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
return low - 1;
|
||||
}
|
||||
|
||||
/** The value of the trackpoint `index` for a category, `undefined` when it is unknown. */
|
||||
export function categoryValue(
|
||||
intervals: CategoryIntervals | undefined,
|
||||
index: number
|
||||
): string | undefined {
|
||||
if (!intervals) {
|
||||
return undefined;
|
||||
}
|
||||
const value = intervals.values[intervalAt(intervals.starts, index)];
|
||||
return value ? intervals.names[value - 1] : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The intervals of the trackpoints that share a value, for a value per trackpoint (`undefined`
|
||||
* when unknown): the inverse of `categoryValues`. The names are in the order of their first
|
||||
* appearance. A value that is unknown everywhere gives no intervals.
|
||||
*/
|
||||
export function categoryIntervals(values: readonly (string | undefined)[]): CategoryIntervals {
|
||||
const starts: number[] = [];
|
||||
const codes: number[] = [];
|
||||
const names: string[] = [];
|
||||
const known = new Map<string, number>();
|
||||
let last: number | undefined = undefined;
|
||||
values.forEach((value, index) => {
|
||||
let code = 0;
|
||||
if (value !== undefined) {
|
||||
if (!known.has(value)) {
|
||||
names.push(value);
|
||||
known.set(value, names.length);
|
||||
}
|
||||
code = known.get(value)!;
|
||||
}
|
||||
if (code !== last) {
|
||||
starts.push(index);
|
||||
codes.push(code);
|
||||
last = code;
|
||||
}
|
||||
});
|
||||
if (names.length === 0) {
|
||||
return { starts: new Uint32Array(), values: new Uint8Array(), names };
|
||||
}
|
||||
return { starts: Uint32Array.from(starts), values: Uint8Array.from(codes), names };
|
||||
}
|
||||
@@ -0,0 +1,265 @@
|
||||
import type { Readable } from 'svelte/store';
|
||||
import type { FeatureCollection, LineString, Point } from 'geojson';
|
||||
import type { Visibility } from '$lib/engine/file-visibility';
|
||||
import type { CategoryIntervals } from '$lib/engine/trackpoint-categories';
|
||||
import type { FileStructure, GlobalStatistics, SelectionPoint } from 'gpx-wasm';
|
||||
|
||||
export type { FileStatus, FolderEntry, UnsavedChoice, WorkspaceState } from './backend/types';
|
||||
|
||||
export type {
|
||||
Clipboard,
|
||||
WaypointDetails,
|
||||
TrackpointDetails,
|
||||
MoveTarget,
|
||||
GlobalStatistics,
|
||||
SelectionPoint,
|
||||
FileStructure,
|
||||
FilesUpdate,
|
||||
Outcome,
|
||||
Selection,
|
||||
PathInfo,
|
||||
RouteNode,
|
||||
TrackNode,
|
||||
SegmentNode,
|
||||
WaypointNode,
|
||||
} from 'gpx-wasm';
|
||||
|
||||
/**
|
||||
* How a merge puts the selected elements together: `connect` makes a single segment of their
|
||||
* trackpoints, `group` keeps them as they are, in the first one.
|
||||
*/
|
||||
export type MergeType = 'connect' | 'group';
|
||||
|
||||
/**
|
||||
* What a split cuts in two: the file, the route, the track or the segment of the trackpoint. Only
|
||||
* a trackpoint of a route cuts a route, and only one of a track cuts a track or a segment.
|
||||
*/
|
||||
export type SplitType = 'files' | 'routes' | 'tracks' | 'segments';
|
||||
|
||||
/**
|
||||
* How elements combine with the current selection: they `replace` it, are `add`ed to it, or are
|
||||
* `toggle`d (the ones already selected are removed). Adding and toggling only merge with elements
|
||||
* of the same kind in the same place (same file, same track for segments), otherwise the new
|
||||
* elements replace the selection.
|
||||
*/
|
||||
export type SelectMode = 'replace' | 'add' | 'toggle';
|
||||
|
||||
/** A segment of the map: the one of a route (`routeId`), or one of a track (`trackId`). */
|
||||
export type SegmentProperties = {
|
||||
fileId: string;
|
||||
routeId?: string;
|
||||
trackId?: string;
|
||||
segmentId: string;
|
||||
/** Changes when the trackpoints of the segment change. */
|
||||
rev: string;
|
||||
/** Color of the route or track, or else the base color of the file. */
|
||||
color: string;
|
||||
/** Only when the route or track defines it. */
|
||||
opacity?: number;
|
||||
width?: number;
|
||||
};
|
||||
|
||||
export type WaypointProperties = {
|
||||
fileId: string;
|
||||
waypointId: string;
|
||||
index: number;
|
||||
name?: string;
|
||||
sym?: string;
|
||||
};
|
||||
|
||||
/** The data of a waypoint to create or to change. Empty strings are fields it does not have. */
|
||||
export type NewWaypoint = {
|
||||
lng: number;
|
||||
lat: number;
|
||||
ele: number;
|
||||
name: string;
|
||||
desc: string;
|
||||
icon: string;
|
||||
link: string;
|
||||
};
|
||||
|
||||
/** Everything the UI knows about one file. */
|
||||
export type FileState = {
|
||||
structure: FileStructure;
|
||||
/**
|
||||
* Color of the file: the one defined by its routes and tracks if any, otherwise one from the
|
||||
* palette.
|
||||
*/
|
||||
color: string;
|
||||
/** Global statistics of the file. */
|
||||
statistics: GlobalStatistics;
|
||||
/** One LineString feature per segment (of the routes, then of the tracks), in file order. */
|
||||
segments: FeatureCollection<LineString, SegmentProperties>;
|
||||
/** One Point feature per waypoint, in file order. */
|
||||
waypoints: FeatureCollection<Point, WaypointProperties>;
|
||||
/**
|
||||
* Visibility the user set explicitly (see `Visibility` and `isHidden`, `isSegmentHidden`,
|
||||
* `isWaypointHidden` in `file-visibility`). Hidden elements are still part of the statistics.
|
||||
*/
|
||||
visibility: Visibility;
|
||||
};
|
||||
|
||||
export const EMPTY_STATISTICS: GlobalStatistics = {
|
||||
totalDistance: 0,
|
||||
elevationGain: 0,
|
||||
elevationLoss: 0,
|
||||
};
|
||||
|
||||
/**
|
||||
* New trackpoints for `Engine.route`, as arrays with an entry per trackpoint. The OSM attributes
|
||||
* are the names of the values (`undefined` when unknown), they are left unknown if missing.
|
||||
*/
|
||||
export type RoutePoints = {
|
||||
lng: ArrayLike<number>;
|
||||
lat: ArrayLike<number>;
|
||||
ele: ArrayLike<number>;
|
||||
surface?: readonly (string | undefined)[];
|
||||
highway?: readonly (string | undefined)[];
|
||||
sacScale?: readonly (string | undefined)[];
|
||||
mtbScale?: readonly (string | undefined)[];
|
||||
};
|
||||
|
||||
/** Which data of the trackpoints a file is exported with (see `Engine.exportFile`). */
|
||||
export type ExportOptions = {
|
||||
time: boolean;
|
||||
hr: boolean;
|
||||
cad: boolean;
|
||||
atemp: boolean;
|
||||
power: boolean;
|
||||
/** The OpenStreetMap data: surface, highway, SAC scale and MTB scale. */
|
||||
osm: boolean;
|
||||
};
|
||||
|
||||
export const ALL_EXPORT_OPTIONS: ExportOptions = {
|
||||
time: true,
|
||||
hr: true,
|
||||
cad: true,
|
||||
atemp: true,
|
||||
power: true,
|
||||
osm: true,
|
||||
};
|
||||
|
||||
/**
|
||||
* Statistics of the selection that are only read from the engine when something asks for them
|
||||
* (see `Engine.requestStatistics`). A metric can bring several arrays.
|
||||
*/
|
||||
export type StatisticsMetric =
|
||||
| 'speed'
|
||||
| 'hr'
|
||||
| 'cad'
|
||||
| 'atemp'
|
||||
| 'power'
|
||||
/** `slopeSegments`. */
|
||||
| 'slopeSegment'
|
||||
| 'surface'
|
||||
/** `highway`, `sacScale` and `mtbScale`. */
|
||||
| 'highway'
|
||||
/** `anchors`. */
|
||||
| 'anchors';
|
||||
|
||||
/**
|
||||
* The anchors of the routing tool among the trackpoints of the selection: the points that can be
|
||||
* dragged to reroute a segment, which are few of them. The arrays are as long as the number of
|
||||
* anchors, in the order of the trackpoints.
|
||||
*/
|
||||
export type SelectionAnchors = {
|
||||
/** Index of the anchor in the trackpoints of the selection. */
|
||||
indices: Uint32Array;
|
||||
/** Lowest map zoom level at which the anchor is shown (0 for the ends of the segments). */
|
||||
zooms: Uint8Array;
|
||||
/**
|
||||
* Index of the first trackpoint of each segment of the selection that has some: anchors that
|
||||
* are between two consecutive starts belong to the same segment.
|
||||
*/
|
||||
segmentStarts: Uint32Array;
|
||||
/** Id of each of these segments. */
|
||||
segmentIds: string[];
|
||||
/**
|
||||
* Changes when the selected segments, or their trackpoints, change. The indices in the
|
||||
* selection (of trackpoints, of anchors) only mean something for one revision, which commands
|
||||
* that use them have to give.
|
||||
*/
|
||||
revision: number;
|
||||
};
|
||||
|
||||
/**
|
||||
* The smoothed elevation segments of the selection, over which the slope is averaged, as the
|
||||
* intervals of trackpoints that belong to the same one: segment `i` starts at the trackpoint
|
||||
* `starts[i]` and lasts until the next start (or the last trackpoint), with a slope of
|
||||
* `slopes[i]` (%). Their length is in `SelectionStatistics.point`.
|
||||
*/
|
||||
export type SlopeSegments = {
|
||||
starts: Uint32Array;
|
||||
slopes: Float64Array;
|
||||
};
|
||||
|
||||
/**
|
||||
* The statistics of the selection: its global statistics, and the values at each of its
|
||||
* trackpoints (all the selected segments, one after the other). The arrays are copies. What is
|
||||
* only needed for one trackpoint at a time (its time, its OSM data...) is read with `point`.
|
||||
*
|
||||
* Distances are cumulative over the whole selection. Distances are in km, speeds in km/h, times in
|
||||
* ms (timestamps since the epoch, as 64-bit integers), elevations in m and slopes in %.
|
||||
*
|
||||
* The values of the trackpoints that the selection does not have at all (for example the heart
|
||||
* rates, when no trackpoint has any) are `undefined`, and so are the ones that were not requested
|
||||
* (see `StatisticsMetric`). Otherwise they have one entry per trackpoint, missing measures are
|
||||
* NaN.
|
||||
*/
|
||||
export type SelectionStatistics = {
|
||||
global: GlobalStatistics;
|
||||
/** Number of trackpoints. */
|
||||
length: number;
|
||||
totalDistance: Float64Array;
|
||||
lng: Float64Array;
|
||||
lat: Float64Array;
|
||||
ele: Float64Array;
|
||||
|
||||
// the following need to be requested
|
||||
speed?: Float64Array;
|
||||
hr?: Float64Array;
|
||||
cad?: Float64Array;
|
||||
atemp?: Float64Array;
|
||||
power?: Float64Array;
|
||||
slopeSegments?: SlopeSegments;
|
||||
surface?: CategoryIntervals;
|
||||
highway?: CategoryIntervals;
|
||||
/** SAC hiking scale. */
|
||||
sacScale?: CategoryIntervals;
|
||||
/** Mountain biking scale. */
|
||||
mtbScale?: CategoryIntervals;
|
||||
anchors?: SelectionAnchors;
|
||||
|
||||
/**
|
||||
* Global statistics of the trackpoints from `start` to `end` (both included), for example
|
||||
* the part of the elevation profile that was dragged over. `undefined` if the range is not
|
||||
* in the selection, or if the selection is not the current one anymore.
|
||||
*/
|
||||
slice(start: number, end: number): Promise<GlobalStatistics | undefined>;
|
||||
/**
|
||||
* All the data of the trackpoint at `index`, for example the one hovered on the elevation
|
||||
* profile. `undefined` if it is not in the selection, or if the selection is not the current
|
||||
* one anymore.
|
||||
*/
|
||||
point(index: number): Promise<SelectionPoint | undefined>;
|
||||
};
|
||||
|
||||
export const EMPTY_SELECTION_STATISTICS: SelectionStatistics = {
|
||||
global: EMPTY_STATISTICS,
|
||||
length: 0,
|
||||
totalDistance: new Float64Array(),
|
||||
lng: new Float64Array(),
|
||||
lat: new Float64Array(),
|
||||
ele: new Float64Array(),
|
||||
slice: async () => undefined,
|
||||
point: async () => undefined,
|
||||
};
|
||||
|
||||
export type StatisticsRequest = {
|
||||
/** Replaces the metrics needed by this consumer. Resolves when the missing ones are read. */
|
||||
set(metrics: Iterable<StatisticsMetric>): Promise<void>;
|
||||
/** The consumer does not need any metric anymore. */
|
||||
release(): void;
|
||||
};
|
||||
|
||||
export type FileStatesCallback = (files: Map<string, Readable<FileState>>) => void;
|
||||
@@ -0,0 +1,93 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { describe, it } from 'node:test';
|
||||
import {
|
||||
editableName,
|
||||
fileIdAt,
|
||||
folderName,
|
||||
isWithin,
|
||||
parentOf,
|
||||
relocated,
|
||||
subfolder,
|
||||
} from '$lib/engine/workspace';
|
||||
|
||||
describe('subfolder', () => {
|
||||
it('is where a file is in the folder', () => {
|
||||
assert.equal(subfolder('/home/me/tracks', '/home/me/tracks/a.gpx'), '');
|
||||
assert.equal(subfolder('/home/me/tracks', '/home/me/tracks/2024/may/a.gpx'), '2024/may');
|
||||
assert.equal(
|
||||
subfolder('C:\\Users\\me\\tracks', 'C:\\Users\\me\\tracks\\2024\\a.gpx'),
|
||||
'2024'
|
||||
);
|
||||
});
|
||||
|
||||
it('is nothing for a file that is not in the folder', () => {
|
||||
assert.equal(subfolder('/home/me/tracks', '/home/me/other/a.gpx'), undefined);
|
||||
assert.equal(subfolder('/home/me/tracks', '/home/me/tracks-old/a.gpx'), undefined);
|
||||
assert.equal(subfolder('/home/me/tracks', undefined), undefined);
|
||||
assert.equal(subfolder(undefined, '/home/me/tracks/a.gpx'), undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('folderName', () => {
|
||||
it('is the last part of the path', () => {
|
||||
assert.equal(folderName('/home/me/tracks'), 'tracks');
|
||||
assert.equal(folderName('/home/me/tracks/'), 'tracks');
|
||||
assert.equal(folderName('C:\\Users\\me\\tracks'), 'tracks');
|
||||
});
|
||||
});
|
||||
|
||||
describe('fileIdAt', () => {
|
||||
const workspace = {
|
||||
files: {
|
||||
a: { path: '/tracks/a.gpx' },
|
||||
b: { path: '/tracks/sub/b.gpx' },
|
||||
c: {},
|
||||
},
|
||||
};
|
||||
|
||||
it('is the open file that is linked to the path', () => {
|
||||
assert.equal(fileIdAt(workspace, '/tracks/a.gpx'), 'a');
|
||||
assert.equal(fileIdAt(workspace, '/tracks/sub/b.gpx'), 'b');
|
||||
});
|
||||
|
||||
it('is nothing for a file that is not open', () => {
|
||||
assert.equal(fileIdAt(workspace, '/tracks/other.gpx'), undefined);
|
||||
assert.equal(fileIdAt(undefined, '/tracks/a.gpx'), undefined);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parentOf', () => {
|
||||
it('is the folder that holds the path', () => {
|
||||
assert.equal(parentOf('/home/me/tracks/a.gpx'), '/home/me/tracks');
|
||||
assert.equal(parentOf('C:\\Users\\me\\a.gpx'), 'C:\\Users\\me');
|
||||
});
|
||||
});
|
||||
|
||||
describe('relocated', () => {
|
||||
it('is where a path is once moved or renamed', () => {
|
||||
assert.equal(relocated('/me/tracks/a.gpx', '/me/trips'), '/me/trips/a.gpx');
|
||||
assert.equal(relocated('/me/tracks', '/me', 'rides'), '/me/rides');
|
||||
assert.equal(relocated('C:\\me\\tracks', 'C:\\me', 'rides'), 'C:\\me\\rides');
|
||||
});
|
||||
});
|
||||
|
||||
describe('isWithin', () => {
|
||||
it('is the folder itself or what is in it', () => {
|
||||
assert.ok(isWithin('/home/me/tracks', '/home/me/tracks'));
|
||||
assert.ok(isWithin('/home/me/tracks/2024/a.gpx', '/home/me/tracks'));
|
||||
assert.ok(isWithin('C:\\me\\tracks\\a.gpx', 'C:\\me\\tracks'));
|
||||
});
|
||||
|
||||
it('is not a folder whose name begins the same', () => {
|
||||
assert.ok(!isWithin('/home/me/tracks-old/a.gpx', '/home/me/tracks'));
|
||||
assert.ok(!isWithin('/home/me', '/home/me/tracks'));
|
||||
});
|
||||
});
|
||||
|
||||
describe('editableName', () => {
|
||||
it('leaves out the extension of a file, not of a folder', () => {
|
||||
assert.equal(editableName('ride.gpx', false), 'ride');
|
||||
assert.equal(editableName('my.trips', true), 'my.trips');
|
||||
assert.equal(editableName('.hidden', false), '.hidden');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
/** `\` and `/` alike. */
|
||||
function parts(path: string): string[] {
|
||||
return path.split(/[\\/]+/).filter((part) => part !== '');
|
||||
}
|
||||
|
||||
/** The name of the folder, the last part of its path. */
|
||||
export function folderName(folder: string): string {
|
||||
return parts(folder).at(-1) ?? folder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a file is in the open folder: the folders between them, as a path (`''` if it is in the
|
||||
* folder itself). `undefined` for a file that is not in the folder (or not on the disk).
|
||||
*/
|
||||
export function subfolder(
|
||||
folder: string | undefined,
|
||||
path: string | undefined
|
||||
): string | undefined {
|
||||
if (folder === undefined || path === undefined) {
|
||||
return undefined;
|
||||
}
|
||||
const root = parts(folder);
|
||||
const file = parts(path);
|
||||
if (file.length <= root.length || root.some((part, i) => part !== file[i])) {
|
||||
return undefined;
|
||||
}
|
||||
return file.slice(root.length, -1).join('/');
|
||||
}
|
||||
|
||||
/** The id of the open file that is linked to the file at `path`, `undefined` if there is none. */
|
||||
export function fileIdAt(
|
||||
workspace: { files: Record<string, { path?: string }> } | undefined,
|
||||
path: string
|
||||
): string | undefined {
|
||||
return Object.entries(workspace?.files ?? {}).find(([, file]) => file.path === path)?.[0];
|
||||
}
|
||||
|
||||
/** The folder that holds `path`. */
|
||||
export function parentOf(path: string): string {
|
||||
const index = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'));
|
||||
return index > 0 ? path.slice(0, index) : path;
|
||||
}
|
||||
|
||||
/** Where `path` is once moved into `folder`, renamed `name` if it is given. */
|
||||
export function relocated(path: string, folder: string, name?: string): string {
|
||||
const parent = parentOf(path);
|
||||
return `${folder}${path[parent.length]}${name ?? path.slice(parent.length + 1)}`;
|
||||
}
|
||||
|
||||
/** Whether `path` is `folder` or something in it. */
|
||||
export function isWithin(path: string, folder: string): boolean {
|
||||
return path === folder || (path.startsWith(folder) && /[\\/]/.test(path[folder.length]));
|
||||
}
|
||||
|
||||
/** The name of a file without its extension, or the name of a folder (`isDir`). */
|
||||
export function editableName(name: string, isDir: boolean): string {
|
||||
const dot = name.lastIndexOf('.');
|
||||
return isDir || dot <= 0 ? name : name.slice(0, dot);
|
||||
}
|
||||
Reference in new issue
Block a user