Skip to content

The OSINT investigator's workbench. One case, one folder, every tool. Local-first: your media and your investigations never leave your machine.

JavaScript

Walk Back and Forward, open Go to with Ctrl+K, and keep a case change from costing work (#100)

OsintMeThatfc5c67813239
diff --git a/README.md b/README.md
index 70bea5f..11eb978 100644
--- a/README.md
+++ b/README.md
@@ -80,33 +80,33 @@ extension, and cross-platform binaries with a bundled ffmpeg.
Every tool works one-shot (a scratch session, no setup) or inside a case, a
plain directory holding the whole investigation.
-## New in v0.3.1
-
-Detect sweeps an area for what appeared, and the map takes layers made elsewhere.
-
-- **Detect**, a tab of its own, sweeps drawn areas of Sentinel-2 for vessels, fires and
- flares, construction, small spots, surface change, burn scars, vegetation loss,
- new water or burned buildings. Candidates come strongest first, and only one you keep becomes a
- case pin.
-- Difference and Detect share one Sentinel-2 cloud and shadow mask.
-- Radar: five Sentinel-1 analyzers (vessels, any change, razed buildings, new
- structures, floods) see through cloud and at night, and Sentinel-1 passes are a
- basemap in Satellite, Compare and Detect.
-- Build your own analyzer from rules on bands, indices, ground classes or radar,
- with checks that turn red when a rule stops holding. Five examples ship with
- theirs.
-- A candidate opens in Compare with one press, and All dates in Compare lists
- every picture of a point to set on either side.
-- Satellite, Compare and Detect share one camera, and a middle-drag turns any map.
-- Inspect keeps one work per file, saved as you go, and Collage is a tab of its own.
-- Open KML, KMZ, GeoJSON and GPX files or a public My Maps as map layers, and add
- a GeoConfirmed conflict. A dated layer narrows to a period.
-- Proofs turn and crop their images, stamp numbered markers and blur boxes, and
- carry a sentence and the date their material was taken.
-- To-do lists on Home, every date typed day-first in the same field, a claim filed
- from where you are, and Reverse Search from a Media row or an Inspect frame.
-- Existing cases open as they are, with 0.3.0 Inspect sessions merged into one
- work per file, and older bundles still import.
+## New in v0.3.2
+
+No new tool this time: the tools you already have read faster, ask less and say
+more clearly what went wrong.
+
+- The browser's Back and Forward walk the tools and what you opened in them, and
+ ask before leaving unsaved work. **Ctrl+K** opens Go to, for a tool, a case or a
+ document.
+- An event is one line under the Timeline axis, with `@` mentions, and **Add
+ event** (Alt+N) opens it over any tool with that tool's view cited.
+- The Timeline draws each date as the instant, day, month or period it is, and
+ every date field reads on one Clock: the place's zone, UTC or any other.
+- The Board reads as an index of people, places and things. A subject's type can
+ be corrected, and two duplicates merged with an Undo.
+- The Graph proposes the links the case already implies, reviewed before they are
+ filed.
+- The Sheet opens on a home, with worklists of the files still to geolocate and of
+ your geolocations by point.
+- Files and the sidebar act on a right-click, and new work lands in the folder you
+ are working in.
+- FIRMS fires keep their size through a zoom, place names sit over the imagery,
+ and Compare and Detect take the whole screen.
+- The Detect analyzer builder works on the map, with checks made from pins and a
+ Test button.
+- A failure reads as one sentence saying what to do, and a second start opens
+ the Azimut already running.
+- Existing cases open as they are, and older bundles still import.
## Cases on disk
@@ -328,7 +328,7 @@ history keeps it.
```bash
source ~/.config/azimut/amo.env # AMO_JWT_ISSUER + AMO_JWT_SECRET, 0600 file outside the repo
python3 scripts/sign_extension.py # signs, writes packaging/updates.json
-gh release upload v0.3.1 dist-xpi/azimut-capture-0.3.1.xpi
+gh release upload v0.3.2 dist-xpi/azimut-capture-0.3.2.xpi
```
Then commit `packaging/updates.json`. That file is what
@@ -395,7 +395,7 @@ wheel + Windows/Linux/macOS binaries, attaches them to a GitHub release, and
publishes to PyPI. **Don't publish by hand.**
```bash
-git tag v0.3.1 && git push origin v0.3.1
+git tag v0.3.2 && git push origin v0.3.2
```
One-time setup: register the repo as a
diff --git a/docs/RELEASE_NOTES.md b/docs/RELEASE_NOTES.md
index 16eb70d..267de58 100644
--- a/docs/RELEASE_NOTES.md
+++ b/docs/RELEASE_NOTES.md
@@ -1,123 +1,120 @@
-# Azimut v0.3.1
+# Azimut v0.3.2
Azimut is a local OSINT workspace: media, geolocation work, proofs and notes in
one portable case folder, on your own machine.
-This release sweeps an area for what appeared, by day or by radar, and puts
-maps made elsewhere on yours.
+This is the improvement release. It adds no new tool. Every change below makes a
+tool you already have quicker to read, asks you fewer questions, or says more
+clearly what went wrong.
+
+## Getting around
+
+- **Ctrl+K** (⌘K on a Mac) opens **Go to**, which finds a tool, a case or a
+ document of the open case, the latest ones first.
+- The browser's Back and Forward buttons work in Azimut. They walk the tools you
+ opened, and inside a tool the folders, sheets, proofs, drafts and notes you went
+ to.
+- Back never drops work. Leaving a proof or a post with unsaved changes asks
+ first, and opening another one from its list now asks too.
+- Back on an open dialog closes it. Leaving Azimut with unsaved work is a
+ question the browser asks.
+
+## Timeline, Board and Graph
+
+- An event is one line under the Timeline axis: a date, a sentence with `@`
+ mentions, and its sources. **Add event** (Alt+N) opens the same line over any
+ tool, with that tool's view already cited.
+- The Timeline draws each date as what it is: a point for an instant, a bracket
+ for a day, a month or a year, a bar for a period. The axis and the list read as
+ one, and a picked entry shows its media without opening it.
+- Every date field has the same **Clock** chip: the place's zone, UTC, this
+ computer or any zone. A plain day can carry its zone too, and a new date reads
+ on its place's clock, else on the case's.
+- The Board reads as an index. People, places and things come first, each with
+ how many events name it and when; files and work fold under their own heading.
+ **Group: None** gives back the flat table.
+- Details opens beside the list, on a summary of the subject.
+- **Change type…** corrects a subject's type without losing a field or a link,
+ and **Merge…** joins two duplicates with a preview and an Undo.
+- Search finds a name whatever accents it was written with, in Latin, Greek,
+ Cyrillic, Arabic and Hebrew, and right-to-left text keeps its direction.
+- The Graph proposes the links the case already implies: the account a post's
+ address names, and points under 300 m apart as one site. Nothing is filed
+ before you review the list.
+- **Case** sits on the rail, one press from any tool.
+
+## Sheet, Files and the sidebar
+
+- The Sheet tab opens on a home with the recent sheets and the ones the case
+ could start. Close saves and comes back to it.
+- The Sheet home starts two worklists from the case: the files still to
+ geolocate, each done once a proof answers it, and your geolocations one row per
+ point.
+- Files and the sidebar act on a right-click, and **Move to…** is one dialog
+ everywhere.
+- Pick a work folder and new files and saved work land in it.
+- Files filters by type, or by what is linked to nothing yet.
+- The sidebar holds Folders, the case's To-do lists and the latest filed items.
+- A folder named in a save dialog shows in every folder picker. Renaming or
+ removing a folder also moves its notes and updates the Media Library filter.
+
+## Maps
+
+- FIRMS fires are drawn as marks that keep their size through a zoom.
+- Town and village names sit over the imagery in Satellite, Detect and the point
+ dialog, on by default beside Borders.
+- An added layer's row folds to one line. Drag the rows into the order the map
+ stacks them, and refresh every followed layer at once.
+- Compare and Detect take the whole screen, as Satellite does.
+- Difference reads in cyan and magenta, waits for tiles instead of failing on
+ them, and says on its button whether a reading is loading or up to date.
+- **Revert** takes an edited saved comparison back to its saved version.
+- A busy area lists all its Sentinel passes, up to five pages, each counted on the
+ request meter.
## Detect
-- **Detect** is a new tab under Map. Draw areas and it sweeps them on Sentinel-2
- at full resolution for vessels, fires, construction, burn scars, vegetation
- loss, new water, burned or destroyed buildings, or any change.
-- Radar analyzers read Sentinel-1 through cloud and at night: vessels, damaged
- buildings, new structures, floods. Settings → Imagery shows how to add the
- Sentinel-1 layer they need.
-- **New analyzer** builds your own from rules on bands, indices, ground classes
- or radar. Checks on places you trust turn red when a rule stops holding. Five
- examples ship with their checks.
-- **Find passes** lists the dates your areas really have, with coverage and
- cloud, up to a year back or between two days you pick. The cost in Copernicus
- requests shows before anything is fetched.
-- The When step warns when two passes see the sun at very different heights,
- since every building's shadow then reads as a change.
-- Candidates come strongest first. **Pin** files one in the case with its
- evidence crop and a dated claim, or open it in Compare.
-- A routine keeps an analyzer, its areas and a date rule, and **Run routine**
- repeats the sweep.
-- Detect needs Copernicus credentials in Settings.
-
-## Compare
-
-- Compare opens on Wayback a year back against today's World Imagery, with no
- key needed.
-- **All dates** lists every dated picture of a point, oldest first, to set on
- either side.
-- Sentinel-1 radar passes are a basemap in Satellite, Compare and Detect.
-- A saved comparison stands on the map, dated A → B, and reopens in Compare.
-- "Change assist" is now **Difference**, a switch over any of the four views.
- It masks clouds with Detect's Sentinel-2 mask, so a white roof no longer
- counts as one, and tone matching starts off on a Sentinel-2 pair.
-- New MNDWI and BSI indices, an export frame, numbered markers and blur boxes.
-- Right-click a point on the Satellite map to compare its last two Wayback
- pictures or Copernicus passes.
-
-## One camera for the maps
-
-- Satellite, Compare and Detect show the same ground: pan one and the others
- follow. Settings → General turns it off.
-- A middle-drag turns any map or Inspect frame; a middle click puts north back.
-
-## Layers from elsewhere
-
-- Open a KML, KMZ, GeoJSON or GPX file as a map layer, or follow a public Google
- My Maps URL. It keeps its own colours and icons and travels in bundles.
-- Add **GeoConfirmed** events over a span of dates, grouped by faction and
- linked to their sources.
-- Narrow a dated layer to a period on a strip of its events or a calendar.
-- A pin's card gives its coordinates to copy. Right-click the pin to compare its
- exact point or open its imagery history.
-- The map panel's Saved tab shows Media, Places or Captures. Media places the
- case's photos and videos and plays them beside the imagery.
-
-## Proofs
-
-- Turn or crop a panel or an overlay without touching its source.
-- Stamp numbered markers and blur boxes.
-- A proof can carry one sentence and the date its material was taken, shown on
- the Timeline.
-- Place a proof's point on a map instead of typing it.
-- A point taken from a capture is only the middle of its frame, so it shows
- greyed until you check it. Save and To post open the map on each unchecked
- point first. **Later** saves the proof and keeps those points off the case map.
-
-## Inspect and Collage
-
-- Inspect keeps one work per file, saved as you go. There are no sessions to
- open or save.
-- **Collage** is a tab of its own and lays out frames from any number of files.
-- The first time a case opens, its 0.3.0 Inspect sessions of one file become
- one work: the latest is kept, with the others' notes and names.
-
-## Elsewhere
-
-- **To-do lists** on Home, saved with the case.
-- One date field across the app: type a day, a month, a year or a range, or
- pick it on a calendar with how sure you are.
-- File a claim straight from Details, a Board row or a Graph node.
-- Send a picture to Reverse Search from the Media Library or an Inspect frame.
-- Every icon button has a tooltip.
+- The analyzer builder works on the map: one satellite, one or two dates,
+ checks made with pins, and **Test** says what the rules find before you save.
+- Areas sit in ordered groups, and the dock can be resized.
+- **What** starts with nothing picked and lists the analyzers by what they look
+ for.
+- Detect still reads a pass its tile calls fully cloudy, rather than skipping
+ it.
+
+## Proofs, posts and collages
+
+- Saving a proof says what it just joined: other geolocations on the same site,
+ other files the account posted there.
+- A `#date` token carries a proof's date into a post. Templates in Settings →
+ Templates start from a layout, preview on the open post and flag a misspelled
+ token.
+- A point named only by its coordinates reads as the town it is near on the
+ Graph.
+- A collage exports at full resolution with no setting, and its size shows
+ before you save. Collages are listed with a preview.
+
+## Clearer when something goes wrong
+
+- A failure reads as one sentence saying what to do. The full error stays in
+ the log.
+- Starting Azimut a second time opens the one already running.
+- If another program holds port 8477, Azimut takes the next free port, and
+ Settings → Capture extension shows the address to give the extension.
+- A bundle import cut off halfway is cleaned up at the next start.
+- A thumbnail or job asked for while the same one runs is no longer lost.
+- Settings → System shows the licence notice and texts of the bundled ffmpeg.
## Security and privacy
-- A case file opened in a tab, such as an SVG from a received bundle, no longer
- runs its script.
-- Another website can no longer make Azimut fetch tiles or run lookups on your
- keys.
-- A bundle no longer carries the exporting machine's folder paths or a database
- journal.
-- A map site can no longer read or press the extension's panel.
-- A key a provider refuses no longer shows in the error message.
-
-## Fixes
-
-- The Labels map layer is gone: CARTO's tiles now ask for a key and covered the
- map with a watermark. Borders still names places, and Roads names streets.
-- Changing only the case of a name renames it on Windows and macOS, where it
- used to delete a collage or be refused.
-- Two names differing only by case no longer block a bundle export on Linux.
-- A proof, draft or grid with "#" in its name opens and deletes the right one.
-- Renaming a file to the name of one deleted earlier no longer fails halfway.
-- Notes, proofs and drafts are written whole, so an interrupted save keeps the
- previous version.
-- The Wayback map no longer slows down while you pan, and its picker lists every
- release.
-- A video's thumbnail no longer goes missing on import.
-- Geo Report's map links read as site names instead of internal ids.
-- On Windows, moving the workspace or saving settings no longer fails when an
- antivirus briefly holds the file.
-- A tab left open across an update no longer asks for files that are gone.
+- The capture extension acts only for the Azimut it is paired with. Another
+ local page is refused and told which address to set.
+- Its hand-offs open only the posting sites and image search engines Azimut
+ offers.
+- Importing a settings backup made where the extension was never paired no
+ longer drops this machine's pairing.
+- Coordinates typed in a map's search bar or read from a Sheet cell are never
+ sent to the place-name geocoder.
## Install or upgrade
@@ -134,8 +131,8 @@ run `chmod +x` on the file first. The README gives the steps for each platform.
The capture extension changed. Chrome, Edge and Brave update it from Settings →
Capture extension. Firefox updates the signed add-on by itself; for a new
-install, open `azimut-capture-0.3.1.xpi` from this release in `about:addons` →
+install, open `azimut-capture-0.3.2.xpi` from this release in `about:addons` →
gear menu → **Install Add-on From File**.
-Your cases open as they are and older bundles still import. The Inspect merge
-above is the only change to them.
+Your cases open as they are and older bundles still import. The first open
+rebuilds the case's search index so names match without their accents.
diff --git a/docs/SPEC.md b/docs/SPEC.md
index fb398b6..557a405 100644
--- a/docs/SPEC.md
+++ b/docs/SPEC.md
@@ -167,64 +167,21 @@ proof for publication.
| Tool | What it does |
|------|--------------|
-| ✅ **Map engine** | Draws the map on MapLibre GL behind the `lib/map` façade, with the same providers, captures and bearing. |
-| ✅ **Map chrome** | Puts modes in one rail, map layers in their tool panel or popup, imagery in the map corner and position in a status line, each tool declared once. |
-| ✅ **Point menu** | Right-clicking the ground copies that point in every format, looks it up, saves, measures, reads the sky or opens its imagery history from it, opens it in the other map tabs, and links it out. |
-| ✅ **Map windows** | Opens the map in several tabs with the view in the URL, links them and extension panels to one camera, and syncs saved points, grids and sweeps live. |
-| ✅ **Map layers** | Stacks key-less overlays (borders, place names, roads, railways, power lines, sea marks, GPS traces), FIRMS fires and VIIRS night lights, and filters pins by kind and folder. |
-| ✅ **Added map layers** | Draws a KML, KMZ, GeoJSON or GPX file or a public My Maps URL in its own colours and icons, with a legend that filters, cited but never adopted into the case. |
-| ✅ **Added layer rows** | Folds each row to one line with icon acts, drags the rows into the order the map stacks them and refreshes every followed layer at once. |
-| ✅ **Dates on a layer** | Narrows a dated added layer (GeoConfirmed, KML timestamps, GPX waypoints) to a period dragged on a strip of its events over time or picked on a calendar, kept with the legend. |
-| ✅ **GeoConfirmed layer** | Adds one GeoConfirmed conflict over a window of days or its whole history, in its own icons, grouped by faction with each event's sources one click away. |
-| ✅ **Media on the map** | Draws the case's located photos and videos where a relation, a GPS reading or a proof puts them, and plays the stack in the panel beside the imagery. |
-| ✅ **Imagery Wayback** | Browses every Esri World Imagery release, narrowed on request to the ones that changed the point, and dates the pixels apart from the release. |
-| ✅ **Satellite Compare** | Aligns and annotates two dated views, assists matched-product change reading, saves editable sessions and files or exports attributed PNG/GIF outputs. |
-| ✅ **Detect sweep** | Native Sentinel-2 detectors, mask footprints, manual candidates and Keep / Dismiss / Pin review with PNG evidence stamped with its dates and point. |
-| ✅ **Passes over an area** | Picks Detect's Copernicus dates from the passes the drawn areas really have, each with the share its swath reached, and reports what a finished run swept. |
-| ✅ **Cloud & shadow filter** | One click in Difference and Detect on Sentinel-2's scene classification, taking unsure edges, dropping cloud specks and masking shadows cast away from the sun. |
-| ✅ **Difference over any view** | A switch beside Compare's four views, offered on a matched pair only, laying its highlights on A, B or both (the default). |
-| ✅ **Detect** | Map-first tab, resizable dock, shared case areas in ordered groups, live A/B preview with per-area dates, one-off and routine runs grouped in Saved, repeat notices and explicit SAT layer snapshots. |
-| ✅ **Capture scale & north** | Adds a scale bar and true-north needle to app and extension captures when resolution and heading are known. |
-| ✅ **Footprint tracing** | Traces a place's uncertainty as a polygon around its pin, in place of the radius. |
-| ✅ **Extension map tools** | Draws measure, the case's points one position at a time, sun and moon, search grids and case media over third-party maps, calibrated per site by a replayable command. |
-| ✅ **Extension updates** | Updates the unpacked extension in one click, installs a signed self-updating Firefox add-on, and flags a copy out of step with the app. |
-| ✅ **Site hand-offs** | Fills the X or Bluesky composer with a prepared thread and uploads a case picture straight into Lens, Yandex, Bing or TinEye. |
-| ✅ **Home & Guide** | Opens on a case dashboard or a front door when no case is open, and `?` opens the Guide on the current tab. |
-| ✅ **Case to-do lists** | Named lists on Home with editable tasks, checkboxes, progress counts and case-bundle persistence. |
-| ✅ **Compare from the ground** | Right-clicking a point opens Compare on the last two Esri Wayback pictures of it, its last two Copernicus passes, or its last two radar passes of one track. |
-| ✅ **Marks that number and hide** | Stamps numbered markers counting a series per colour, and blur boxes that redraw the picture under them, on a proof's panels and on a comparison's ground alike. |
-| ✅ **A date in one field** | Reads a day, a month, a year, a time or a range from one line of text, or builds one from a calendar with its marks of doubt, and says what it understood. |
-| ✅ **Words that hold still** | One name for a Claim everywhere, a tooltip on every icon, a reason on a layer that cannot be switched on, and recent work first on Home. |
-| ✅ **A picture sent to Reverse Search** | Opens Reverse Search on a Media Library file, from a row's Open in… menu, or on an Inspect frame as it is cropped, saved or not. |
-| ✅ **Add event from anywhere** | One line for an event under the Timeline axis, atop Details and over any tool (Alt+N), with `@` mentions, the tool's view already cited, and a date only the analyst gives. |
-| ✅ **Radar Detect** | Five Sentinel-1 analyzers (vessels, any change, razed buildings, new structures, floods) through the user's own radar layer, calibrated on real scenes, held to one track. |
-| ✅ **Sentinel-1 basemap** | Radar passes as a dated basemap in Satellite, Compare and Detect, named by day, UTC time and direction. |
-| ✅ **All dates** | Lists every dated picture of the point in Compare, oldest first, to set on either side. |
-| ✅ **Copernicus where it is needed** | Detect and Compare say in the middle of the tool what Copernicus still lacks, with the free account, the Sentinel-2 configuration and the Sentinel-1 layer form field by field. |
-| ✅ **A candidate in Compare** | Opens a Detect candidate in Compare on the passes that found it, or against high-resolution imagery for a thing present on one pass. |
-| ✅ **Sizes in Detect** | Right-clicks Detect's map for its point menu, sizes each candidate along its footprint, walks the largest first, and blinks A against B from the review. |
-| ✅ **Analyzers of your own** | Builds a Detect analyzer for one satellite from up to six rules on any band, index, ground class or radar polarisation, proved on checks drawn on the map; five calibrated examples ship. |
-| ✅ **Examine: Inspect and Collage** | Keeps one autosaved work per file with its frames on a strip, lays collages out of any file's frames and images, and merges a case's 0.3.0 sessions on open. |
-| ✅ **One camera for the map tabs** | Satellite, Compare and Detect show the same ground, and the link carries it to other windows; a Detect review keeps its own, and Settings turns it off. |
-| ✅ **Comparisons in Saved work** | A saved comparison stands on the map with the captures, its frame outlined and dated A → B, and reopens in Compare; an export can be kept under it. |
-| ✅ **Dated pins and pictures** | A kept Detect candidate files a claim at its pin, comparisons and pinned evidence carry each picture's date, and exports are named by their pictures' dates. |
-| ✅ **An evolution of one point** | Exports hand-ticked Sentinel-2 passes or Wayback pictures, back to 2015, as one GIF or one sheet on the same ground, empty pictures left out and counted. |
-| ✅ **Signed exports, marks in their colours** | Compare exports close their credits line with the Azimut logo and name unless unticked, and a GIF keeps every mark's colour exact. |
-| ✅ **One turn on every map** | A middle-drag turns any map or Inspect frame about the grabbed point, settling on north, in 15° steps with Ctrl; a middle click or Shift+↑ puts north back. |
-| ✅ **Checked proof points** | A proof point taken from a capture's centre reads greyed until checked; Save and To post show each one on the map first, and one saved for later stays off the case map. |
-| ✅ **Compare and Detect full screen** | Both take the whole screen with their bars and panel, as Satellite does, and any change of tab gives it back. |
-| ✅ **A Timeline that reads at a glance** | A point is an instant, a bracket a date known to the day, month or year, a bar a period, with imagery on its own lane and axis and list read as one. |
-| ✅ **Names in any script** | Search folds case and accents in Latin, Greek and Cyrillic and vowel marks in Arabic and Hebrew, and keeps right-to-left text in its own direction. |
-| ✅ **Subjects corrected safely** | Changes a subject's type without losing a field or a link, and merges two duplicates with a preview, redirects for the absorbed id and an Undo. |
-| ✅ **The Board as an index** | Groups the case by family, people, places and things first, with how many events name each and when, files folded under and Details beside the list. |
-| ✅ **Every date on a clock** | One Clock chip wherever a date is typed: a day or a time reads on its place's zone, UTC, this computer or any zone in the world, and the Timeline spans that zone's day. |
-| ✅ **Dates in posts, better templates** | A `#date` token carries the proof's date into a post where a template asks; templates start from a layout, preview on the open post and flag a misspelled token. |
-| ✅ **A work folder, and Files that acts** | New files and saved work land in the folder being worked in, Files and the sidebar act on a right-click, and Files filters by type or by what is linked to nothing. |
-| ✅ **Links the case proposes** | Proposes the account a post's address names and joins points under 300 m apart as one site, reviewed in one list from the Graph; a dropped proposal does not come back. |
-| ✅ **A Sheet home** | The Sheet tab opens on the recent sheets and the ones the case could start, counted; Close saves and comes back to it; a status chip opens its words. |
-| ✅ **Files to geolocate** | One row per imported picture or video, done once a proof answers it, opened from the Sheet home or the Media Library and kept level by Refresh. |
-| ✅ **My geolocations by point** | One row per point of every proof, POV or not, with its date, source address and description. |
-| ✅ **Where a geolocation sits** | A point named by its coordinates reads as the town it is near on the Graph; a saved proof says which geolocations share its site and what its account posted. |
+| ✅ **Map navigation & captures** | Links map cameras, places case media and uncertainty footprints, and saves attributed captures with scale and north. |
+| ✅ **Map layers** | Stacks infrastructure overlays, FIRMS fires and VIIRS night lights, with case pins filtered by kind and folder. |
+| ✅ **Imported & followed layers** | Imports KML, KMZ, GeoJSON and GPX, follows public My Maps and GeoConfirmed, and filters their legends and dates. |
+| ✅ **Historical imagery & radar** | Browses Esri Wayback releases and dated Sentinel-1 passes, keeping acquisition dates separate from imagery releases. |
+| ✅ **Satellite Compare** | Aligns and annotates dated imagery, highlights comparable changes, saves sessions and exports attributed PNGs, GIFs and evolution sheets. |
+| ✅ **Detect** | Reviews Sentinel-2 and Sentinel-1 detections over shared areas, with pass coverage, cloud masks, custom analyzers and dated evidence. |
+| ✅ **Capture extension** | Adds case map tools to third-party maps, hands media to publishing and reverse search sites, and supports extension updates. |
+| ✅ **Home, Guide & tasks** | Opens recent case work and named task lists from Home, with contextual guidance for each tool. |
+| ✅ **Inspect, Collage & Reverse Search** | Autosaves work per file, arranges extracted frames into collages and sends original or cropped pictures to reverse search. |
+| ✅ **Proof annotations & publishing** | Adds numbered markers and blur boxes, verifies proof points and carries proof dates into previewed post templates. |
+| ✅ **Dates & Timeline** | Shares date entry and clock selection, draws temporal precision explicitly and adds cited events from any tool. |
+| ✅ **Subjects & case analysis** | Corrects and merges subjects, indexes their events, searches across scripts and reviews proposed account and site connections. |
+| ✅ **Geolocation worklists** | Opens recent sheets, tracks imported files awaiting a proof and indexes every proof point with its date, source and coordinates. |
+| ✅ **Files & navigation** | Files work into the active folder, offers contextual actions and filters, and retraces tools and documents with guarded Back and Forward. |
+| ✅ **Command palette** | Ctrl+K or ⌘K searches tools, cases and current-case documents, starts with recently added items and protects unsaved work. |
---
@@ -259,7 +216,6 @@ Each version delivers one complete daily workflow. Firm ideas move here from
| **Panorama** | Stitch a video window / frame set. Auto-stitch already in Collage; still to do: sample a video window directly, seam blending. |
| **Proof annotation** | Grow the Geo Proof toolbox: dashed strokes; a document-level free layer so shapes cross panels and reach the margins; callout / zoom insets. |
| **Detached tool windows** | The rule the map already follows, applied to the rest: a read-and-work surface (Board, Graph, Timeline) opens as many tabs as wanted and the tab it left stays live; a document editor opens one window per document and is greyed out where it was. Cross-tool handoffs route to wherever the tool now lives. |
-| **Command palette** | Ctrl+K reaches a tool, a case or an artifact. |
Edit Provenance rests on three facts about Adobe renders, kept here so the tool
can be rebuilt from the spec alone:
diff --git a/docs/UI.md b/docs/UI.md
index d9c02ff..2eae9f2 100644
--- a/docs/UI.md
+++ b/docs/UI.md
@@ -43,6 +43,23 @@ which is the one affordance that needs no label and costs no seat, and it is whe
app opens (`#overview`). Its sidebar starts closed too: the page is read rather than
worked in, and its whole subject is the case the sidebar would be listing again.
+**The browser's Back and Forward walk the work** (`lib/backButton.js`). Each change of
+tool is a step, and so is each place the analyst goes to inside one: a folder in Files,
+a sheet opened from the Sheet home, a proof, a draft or a note. The address carries it
+(`#files?folder=Sources%2FTelegram`, `#proof?proof=convoy`). A change that only renames
+a place, such as a save naming a document, a rename or a case switch, rewrites the step
+it is on. A document opened from another tool is one step with the switch that brought
+it, so one Back returns to where the press was made. Tools stay loaded, so Back to a
+tool finds it as it was left.
+
+**Back never drops work.** Back away from a proof or a post with unsaved changes asks
+first, and **Keep editing** leaves the address on the document; opening another one
+from its list asks the same. Back on an open dialog closes that dialog, as Escape
+would, and goes nowhere else. Leaving Azimut with unsaved work in a proof, a post, a
+comparison or a sheet whose edits could not be written is a question the browser asks.
+A step made in another case changes the tool and nothing inside it, since Back does not
+switch cases.
+
## Home
Two tabs, chosen by who is looking. **Overview** is for somebody who has been here
@@ -145,6 +162,20 @@ before; **Guide** is for somebody who has not.
Rules:
+- **Go to** opens from the topbar or `Ctrl+K` (`⌘K` on macOS). It starts with
+ recently added documents, then searches tools, workspace cases and documents
+ in the current case. Arrow keys select a result, Enter opens it and Escape
+ returns focus. Changing case through `openCase` asks before discarding unsaved
+ work; document handoffs retain their existing save and confirmation paths.
+ Reads start only when the palette opens; document search uses bounded catalog
+ queries and case search returns at most eight matches. Results from a closed
+ palette, an earlier query or a previous case are discarded.
+ Results stay visible while the next search runs; Enter waits for that search,
+ and new words select the best match again. The palette hangs from the top of
+ the window, so the field stays put while the list grows and shrinks, and the
+ part of each name a search matched is drawn bold.
+ Case names use the same accent and word normalization as other searches;
+ document results rank name matches before incidental matches.
- Use at most two levels: workspace → tab.
- `uiState.tool` is authoritative. The active workspace is derived from it, so
cross-tool handoffs do not need workspace logic. Each workspace remembers its
@@ -1776,7 +1807,7 @@ Satellite or Detect. The rows Satellite offers for its own rails are left out
rather than shown dead.
**Save** writes the editable version-2 session under `.compare/` and
-updates its rendered media preview in My work (PNG, or GIF for blink). The preview
+updates its rendered media preview in the case (PNG, or GIF for blink). The preview
records the date of each picture, one Esri or Wayback only estimated marked `~` on
its Time tab, where **Date a change** offers a claim that something changed between
them. A preview used by a derived proof is preserved when a later save creates new pixels.
diff --git a/extension/manifest.json b/extension/manifest.json
index 075418a..7f92608 100644
--- a/extension/manifest.json
+++ b/extension/manifest.json
@@ -1,7 +1,7 @@
{
"manifest_version": 3,
"name": "Azimut Capture",
- "version": "0.3.1",
+ "version": "0.3.2",
"description": "File into Azimut: screenshot the map you are looking at (coordinates from the URL), save any other page as a bookmark, fill a social composer with a thread the app prepared, or open a reverse-image engine with a picture from the case.",
"permissions": ["activeTab", "scripting", "storage", "notifications"],
"host_permissions": [
diff --git a/frontend/e2e/back-forward.spec.js b/frontend/e2e/back-forward.spec.js
new file mode 100644
index 0000000..b9efb7f
--- /dev/null
+++ b/frontend/e2e/back-forward.spec.js
@@ -0,0 +1,338 @@
+import { test, expect } from '@playwright/test';
+import { CASE_ID, installAppFixture } from './app.fixture.js';
+
+/**
+ * The browser's own Back and Forward, pressed for real.
+ *
+ * They walk the tools, and inside a tool the places the analyst went to: a folder in
+ * Files, a sheet from the Sheet home, a proof, a draft, a note. And they never cost
+ * work: a document with unsaved changes asks before Back leaves it, and stays put when
+ * the analyst keeps editing.
+ */
+
+const tab = (page, name) => page.locator('.tabstrip').getByRole('button', { name, exact: true });
+const hashOf = (page) => page.evaluate(() => location.hash);
+
+test('Back and Forward walk the tools the analyst opened', async ({ page }) => {
+ const fixture = await installAppFixture(page);
+ await page.goto('/#files');
+ await expect(tab(page, 'Files')).toHaveAttribute('aria-current', 'page');
+
+ await page.locator('.rail').getByRole('button', { name: 'Compose' }).click();
+ await expect(tab(page, 'Geo Proof')).toHaveAttribute('aria-current', 'page');
+ await tab(page, 'Notebook').click();
+ await expect(tab(page, 'Notebook')).toHaveAttribute('aria-current', 'page');
+
+ await page.goBack();
+ await expect(tab(page, 'Geo Proof')).toHaveAttribute('aria-current', 'page');
+ await page.goBack();
+ await expect(tab(page, 'Files')).toHaveAttribute('aria-current', 'page');
+ await page.goForward();
+ await expect(tab(page, 'Geo Proof')).toHaveAttribute('aria-current', 'page');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('Back retraces the folders opened in Files', async ({ page }) => {
+ const fixture = await installAppFixture(page, {
+ cases: [{
+ id: CASE_ID, name: 'Browser Test', scratch: false, entities: [], links: [],
+ folders: ['Airbase', 'Airbase/North'],
+ }],
+ });
+ await page.route(`**/api/cases/${CASE_ID}`, (route) =>
+ route.fulfill({ json: { id: CASE_ID, name: 'Browser Test', scratch: false, folders: ['Airbase', 'Airbase/North'] } })
+ );
+ await page.goto('/#files');
+ const grid = page.locator('.grid-pane');
+ const crumbs = page.locator('.crumbs');
+
+ await grid.locator('.tile.folder', { hasText: 'Airbase' }).dblclick();
+ await expect(crumbs).toContainText('Airbase');
+ await grid.locator('.tile.folder', { hasText: 'North' }).dblclick();
+ await expect(crumbs).toContainText('North');
+ expect(await hashOf(page)).toBe('#files?folder=Airbase%2FNorth');
+
+ await page.goBack();
+ await expect(crumbs).not.toContainText('North');
+ await expect(grid.locator('.tile.folder', { hasText: 'North' })).toBeVisible();
+ await page.goBack();
+ await expect(grid.locator('.tile.folder', { hasText: 'Airbase' })).toBeVisible();
+ await page.goForward();
+ await expect(grid.locator('.tile.folder', { hasText: 'North' })).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('Back goes from a sheet to the Sheet home, and Forward opens it again', async ({ page }) => {
+ const fixture = await installAppFixture(page, {
+ sheets: [['Candidates', ['Subject', 'Status'], [['Quai sud', 'To check']]]],
+ });
+ await page.goto('/#sheet');
+ await page.locator('.home .sheet').first().click();
+ const grid = page.getByRole('grid', { name: 'Sheet rows' });
+ await expect(grid).toBeVisible();
+
+ await page.goBack();
+ await expect(grid).toBeHidden();
+ await expect(page.locator('.home .sheet').first()).toBeVisible();
+ await page.goForward();
+ await expect(grid).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
+
+const PROOFS = { 'proof-a': 'Convoy at the gate', 'proof-b': 'Smoke over the depot' };
+
+async function withProofs(page, options = {}) {
+ const fixture = await installAppFixture(page, {
+ ...options,
+ lookupEntities: Object.fromEntries(
+ Object.keys(PROOFS).map((name) => [`proofs/.meta/${name}.json`, { id: `${name}-entity` }])
+ ),
+ });
+ await page.route(`**/api/cases/${CASE_ID}/proofs`, (route) => {
+ if (route.request().method() !== 'GET') return route.fallback();
+ return route.fulfill({
+ json: Object.entries(PROOFS).map(([name, title]) => ({
+ name, title, spec_path: `proofs/.meta/${name}.json`, updated_at: '2026-10-01T10:00:00Z',
+ })),
+ });
+ });
+ await page.route(`**/api/cases/${CASE_ID}/proofs/*`, (route) => {
+ const name = decodeURIComponent(new URL(route.request().url()).pathname.split('/').pop());
+ if (route.request().method() !== 'GET' || !PROOFS[name]) return route.fallback();
+ return route.fulfill({ json: { title: PROOFS[name], panels: [], pastes: [], shapes: [] } });
+ });
+ return fixture;
+}
+
+async function openProof(page, title) {
+ await page.locator('.tool-header').getByRole('button', { name: 'Open proof' }).click();
+ await page.locator('.open-row', { hasText: title }).click();
+ await expect(page.getByRole('textbox', { name: 'Proof name' })).toHaveValue(title);
+}
+
+test('Back between proofs asks before leaving unsaved changes, and keeps them when asked to', async ({ page }) => {
+ const fixture = await withProofs(page);
+ await page.goto('/#proof');
+ await openProof(page, PROOFS['proof-a']);
+ await openProof(page, PROOFS['proof-b']);
+ expect(await hashOf(page)).toBe('#proof?proof=proof-b');
+
+ const name = page.getByRole('textbox', { name: 'Proof name' });
+ await name.fill('Smoke over the depot, east side');
+ await expect(page.locator('.tool-header .badge', { hasText: 'unsaved' })).toBeVisible();
+
+ await page.goBack();
+ const ask = page.getByRole('alertdialog', { name: 'Leave this proof?' });
+ await expect(ask).toBeVisible();
+ await ask.getByRole('button', { name: 'Keep editing' }).click();
+ await expect(ask).toBeHidden();
+ await expect(name).toHaveValue('Smoke over the depot, east side');
+ await expect.poll(() => hashOf(page)).toBe('#proof?proof=proof-b');
+
+ await page.goBack();
+ await expect(ask).toBeVisible();
+ await ask.getByRole('button', { name: 'Leave without saving' }).click();
+ await expect(name).toHaveValue(PROOFS['proof-a']);
+ await expect.poll(() => hashOf(page)).toBe('#proof?proof=proof-a');
+
+ // A saved proof is left without a word.
+ await page.goForward();
+ await expect(name).toHaveValue(PROOFS['proof-b']);
+ await expect(ask).toBeHidden();
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('opening another proof asks first too, so the list cannot drop an edit', async ({ page }) => {
+ const fixture = await withProofs(page);
+ await page.goto('/#proof');
+ await openProof(page, PROOFS['proof-a']);
+ const name = page.getByRole('textbox', { name: 'Proof name' });
+ await name.fill('Convoy at the north gate');
+
+ await page.locator('.tool-header').getByRole('button', { name: 'Open proof' }).click();
+ await page.locator('.open-row', { hasText: PROOFS['proof-b'] }).click();
+ const ask = page.getByRole('alertdialog', { name: 'Leave this proof?' });
+ await expect(ask).toBeVisible();
+ await ask.getByRole('button', { name: 'Keep editing' }).click();
+ await page.keyboard.press('Escape');
+ await expect(name).toHaveValue('Convoy at the north gate');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('Back on an open dialog closes it and stays on the tool', async ({ page }) => {
+ const fixture = await withProofs(page);
+ await page.goto('/#files');
+ await page.locator('.rail').getByRole('button', { name: 'Compose' }).click();
+ await expect(tab(page, 'Geo Proof')).toHaveAttribute('aria-current', 'page');
+ await page.locator('.tool-header').getByRole('button', { name: 'Open proof' }).click();
+ const row = page.locator('.open-row', { hasText: PROOFS['proof-a'] });
+ await expect(row).toBeVisible();
+
+ await page.goBack();
+ await expect(row).toBeHidden();
+ await expect(tab(page, 'Geo Proof')).toHaveAttribute('aria-current', 'page');
+ await page.goBack();
+ await expect(tab(page, 'Files')).toHaveAttribute('aria-current', 'page');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('leaving Azimut asks while a proof holds unsaved changes, and only then', async ({ page }) => {
+ await withProofs(page);
+ await page.goto('/#proof');
+ await openProof(page, PROOFS['proof-a']);
+ const asked = [];
+ page.on('dialog', (dialog) => {
+ asked.push(dialog.type());
+ dialog.dismiss();
+ });
+
+ await page.close({ runBeforeUnload: true });
+ await expect.poll(() => asked).toEqual([]);
+});
+
+test('leaving Azimut with an edited proof is a question the browser asks', async ({ page }) => {
+ await withProofs(page);
+ await page.goto('/#proof');
+ await openProof(page, PROOFS['proof-a']);
+ await page.getByRole('textbox', { name: 'Proof name' }).fill('Convoy, edited');
+ const asked = [];
+ page.on('dialog', (dialog) => {
+ asked.push(dialog.type());
+ dialog.accept();
+ });
+
+ await page.close({ runBeforeUnload: true });
+ await expect.poll(() => asked).toEqual(['beforeunload']);
+});
+
+const DRAFTS = {
+ 'thread-a': { title: 'Thread A', updated_at: '2026-10-01T10:00:00Z', state: { description: 'Convoy at the gate' } },
+ 'thread-b': { title: 'Thread B', updated_at: '2026-10-01T11:00:00Z', state: { description: 'Smoke over the depot' } },
+};
+
+async function openDraft(page, title) {
+ await page.locator('.tool-header').getByRole('button', { name: 'Open' }).click();
+ await page.locator('.open-row', { hasText: title }).click();
+ await expect(page.getByRole('textbox', { name: 'Post name' })).toHaveValue(title);
+}
+
+test('Back between drafts asks before leaving an edited post', async ({ page }) => {
+ const fixture = await installAppFixture(page, {
+ drafts: DRAFTS,
+ // Found again, as the case would: otherwise the composer reads each as deleted.
+ lookupEntities: Object.fromEntries(Object.keys(DRAFTS).map((name) => [`.drafts/${name}.json`, { id: name }])),
+ });
+ await page.goto('/#post');
+ await openDraft(page, 'Thread A');
+ await openDraft(page, 'Thread B');
+ const description = page.locator('#pc-desc');
+ await description.fill('Smoke over the depot, east side');
+
+ await page.goBack();
+ const ask = page.getByRole('alertdialog', { name: 'Leave this post?' });
+ await expect(ask).toBeVisible();
+ await ask.getByRole('button', { name: 'Keep editing' }).click();
+ await expect(description).toHaveValue('Smoke over the depot, east side');
+ await expect.poll(() => hashOf(page)).toBe('#post?draft=thread-b');
+
+ await page.goBack();
+ await ask.getByRole('button', { name: 'Leave without saving' }).click();
+ await expect(page.getByRole('textbox', { name: 'Post name' })).toHaveValue('Thread A');
+ await expect(description).toHaveValue('Convoy at the gate');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('Back retraces the notes opened in the Notebook', async ({ page }) => {
+ const note = (id, label) => ({
+ id, type: 'note', label, attrs: { path: `notes/${id}.md` },
+ provenance: { by: 'user', at: '2026-10-01T10:00:00Z', status: 'confirmed' },
+ });
+ const fixture = await installAppFixture(page, { catalog: [note('n-convoy', 'Convoy'), note('n-depot', 'Depot')] });
+ await page.route(`**/api/cases/${CASE_ID}/notes/*`, (route) => {
+ const id = new URL(route.request().url()).pathname.split('/').pop();
+ return route.fulfill({ json: { text: `# ${id}\n` } });
+ });
+ await page.goto('/#notebook');
+ const pick = async (label) => {
+ await page.locator('.menu-toggle').click();
+ await page.locator('.menu-note', { hasText: label }).click();
+ };
+ const active = page.locator('.tabs .tab.active');
+
+ await pick('Convoy');
+ await expect(active).toContainText('Convoy');
+ await pick('Depot');
+ await expect(active).toContainText('Depot');
+
+ await page.goBack();
+ await expect(active).toContainText('Convoy');
+ await page.goBack();
+ await expect(active).toContainText('Case Notes');
+ await page.goForward();
+ await expect(active).toContainText('Convoy');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a note opened from Files is one step, and Back lands in the folder it came from', async ({ page }) => {
+ const convoy = {
+ id: 'n-convoy', type: 'note', label: 'Convoy', attrs: { path: 'notes/convoy.md', folder: 'Sources' },
+ provenance: { by: 'user', at: '2026-10-01T10:00:00Z', status: 'confirmed' },
+ };
+ const fixture = await installAppFixture(page, {
+ cases: [{ id: CASE_ID, name: 'Browser Test', scratch: false, entities: [], links: [], folders: ['Sources'] }],
+ catalog: [convoy],
+ });
+ await page.route(`**/api/cases/${CASE_ID}`, (route) =>
+ route.fulfill({ json: { id: CASE_ID, name: 'Browser Test', scratch: false, folders: ['Sources'] } })
+ );
+ await page.route(`**/api/cases/${CASE_ID}/notes/*`, (route) => route.fulfill({ json: { text: '# Convoy\n' } }));
+ // The Notebook already open once, so the note arrives in a tool that is there.
+ await page.goto('/#notebook');
+ await expect(page.locator('.tabs .tab.active')).toContainText('Case Notes');
+ await page.locator('.rail').getByRole('button', { name: 'Sources' }).click();
+ await tab(page, 'Files').click();
+ const grid = page.locator('.grid-pane');
+ await grid.locator('.tile.folder', { hasText: 'Sources' }).dblclick();
+ await grid.locator('.tile', { hasText: 'Convoy' }).dblclick();
+ await expect(tab(page, 'Notebook')).toHaveAttribute('aria-current', 'page');
+ await expect(page.locator('.tabs .tab.active')).toContainText('Convoy');
+
+ await page.goBack();
+ await expect(tab(page, 'Files')).toHaveAttribute('aria-current', 'page');
+ await expect(page.locator('.crumbs')).toContainText('Sources');
+ await page.goBack();
+ await expect(grid.locator('.tile.folder', { hasText: 'Sources' })).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a proof opened from Files is one step, even though it loads after the switch', async ({ page }) => {
+ const proof = {
+ id: 'proof-a-entity', type: 'proof', label: PROOFS['proof-a'],
+ attrs: { spec: 'proofs/.meta/proof-a.json', folder: 'Sources' },
+ provenance: { by: 'user', at: '2026-10-01T10:00:00Z', status: 'confirmed' },
+ };
+ const fixture = await withProofs(page, {
+ cases: [{ id: CASE_ID, name: 'Browser Test', scratch: false, entities: [], links: [], folders: ['Sources'] }],
+ catalog: [proof],
+ chains: { [proof.id]: { entity: proof, sources: [], lost: [], dependents: [], relations: [] } },
+ });
+ await page.route(`**/api/cases/${CASE_ID}`, (route) =>
+ route.fulfill({ json: { id: CASE_ID, name: 'Browser Test', scratch: false, folders: ['Sources'] } })
+ );
+ // The composer already open once, so the proof arrives in a tool that is there.
+ await page.goto('/#proof');
+ await expect(page.locator('.tool-header').getByRole('button', { name: 'Open proof' })).toBeVisible();
+ await page.locator('.rail').getByRole('button', { name: 'Sources' }).click();
+ await tab(page, 'Files').click();
+ const grid = page.locator('.grid-pane');
+ await grid.locator('.tile.folder', { hasText: 'Sources' }).dblclick();
+ await grid.locator('.tile', { hasText: PROOFS['proof-a'] }).dblclick();
+ await page.getByRole('button', { name: 'Open in tool' }).click();
+ await expect(page.getByRole('textbox', { name: 'Proof name' })).toHaveValue(PROOFS['proof-a']);
+ await expect.poll(() => hashOf(page)).toBe('#proof?proof=proof-a');
+
+ await page.goBack();
+ await expect(tab(page, 'Files')).toHaveAttribute('aria-current', 'page');
+ await expect(page.locator('.crumbs')).toContainText('Sources');
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/command-palette.spec.js b/frontend/e2e/command-palette.spec.js
new file mode 100644
index 0000000..69884c1
--- /dev/null
+++ b/frontend/e2e/command-palette.spec.js
@@ -0,0 +1,199 @@
+import { test, expect } from '@playwright/test';
+import { CASE_ID, installAppFixture } from './app.fixture.js';
+import { foldTerms, foldText } from '../src/lib/textFold.js';
+
+const SECOND_CASE = 'browser-airfield';
+const CASES = [
+ { id: CASE_ID, name: 'Harbour', scratch: false, folders: [] },
+ { id: SECOND_CASE, name: 'Airfield', scratch: false, folders: [] },
+];
+
+async function start(page, options = {}, tool = 'media') {
+ const fixture = await installAppFixture(page, options);
+ await page.route('**/api/cases/entity-types', (route) => route.fulfill({ json: [
+ { type: 'proof', label: 'Proof', family: 'document', icon: 'proof', attrs: [] },
+ { type: 'sheet', label: 'Sheet', family: 'document', icon: 'table', attrs: [] },
+ { type: 'note', label: 'Note', family: 'document', icon: 'note', attrs: [] },
+ { type: 'media', label: 'Media', family: 'collected', icon: 'media', attrs: [] },
+ ] }));
+ await page.route(`**/api/cases/${SECOND_CASE}/media/page*`, (route) => route.fulfill({
+ json: { items: [], total: 0, next_cursor: null, facets: {} },
+ }));
+ await page.route('**/api/cases?*', (route) => {
+ const params = new URL(route.request().url()).searchParams;
+ const terms = foldTerms(params.get('q') ?? '');
+ const cases = options.cases ?? [{ id: CASE_ID, name: 'Browser Test', scratch: false }];
+ return route.fulfill({ json: cases.filter((item) => terms.every((term) => foldText(item.name).includes(term))).slice(0, 8) });
+ });
+ await page.goto(`/#${tool}`);
+ if (tool === 'media') {
+ await expect(page.getByPlaceholder('Paste a link (X, Telegram, YouTube…)')).toBeVisible({ timeout: 15_000 });
+ }
+ return fixture;
+}
+
+const dialog = (page) => page.getByRole('dialog', { name: 'Go to', exact: true });
+const search = (page) => dialog(page).getByRole('combobox');
+
+async function find(page, term) {
+ await page.keyboard.press('Control+k');
+ await expect(search(page)).toBeFocused();
+ await search(page).fill(term);
+}
+
+test('Ctrl+K reads only on opening and reaches a tool with the keyboard', async ({ page }) => {
+ const calls = [];
+ page.on('request', (request) => {
+ const url = new URL(request.url());
+ if (url.pathname === '/api/cases' && url.searchParams.get('limit') === '8') calls.push(url);
+ });
+ const fixture = await start(page);
+ expect(calls).toHaveLength(0);
+ await find(page, 'Reverse Search');
+ await expect(dialog(page).getByRole('option', { name: /Reverse Search/ })).toBeVisible();
+ await page.keyboard.press('ArrowDown');
+ await page.keyboard.press('ArrowUp');
+ await page.keyboard.press('Enter');
+ await expect(page.locator('.tabstrip').getByRole('button', { name: 'Reverse Search' })).toHaveAttribute('aria-current', 'page');
+ await expect(dialog(page)).toBeHidden();
+ expect(calls.length).toBeGreaterThan(0);
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('Command+K works in a field, and Escape preserves it and returns focus', async ({ page }) => {
+ const fixture = await start(page);
+ const field = page.getByPlaceholder('Paste a link (X, Telegram, YouTube…)');
+ await field.fill('https://example.test/unfinished');
+ await page.keyboard.press('Meta+k');
+ await expect(search(page)).toBeFocused();
+ await search(page).fill('some query');
+ await page.keyboard.press('Escape');
+ await expect(dialog(page)).toBeHidden();
+ await expect(field).toBeFocused();
+ await expect(field).toHaveValue('https://example.test/unfinished');
+ await page.getByRole('button', { name: 'Go to', exact: true }).click();
+ await expect(search(page)).toHaveValue('');
+ await page.keyboard.press('Escape');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a document result opens its sheet and participates in browser history', async ({ page }) => {
+ const fixture = await start(page, {
+ sheets: [['Geolocation index', ['Subject', 'Status'], [['Quay', 'To check']]]],
+ catalog: [{ id: 'sheet-1', type: 'sheet', label: 'Geolocation index', attrs: { path: 'sheets/index.csv' } }],
+ });
+ await find(page, 'Geolocation index');
+ await dialog(page).getByRole('option', { name: /Geolocation index/ }).click();
+ await expect(page.getByRole('grid', { name: 'Sheet rows' })).toBeVisible({ timeout: 15_000 });
+ await expect(page).toHaveURL(/#sheet\?sheet=sheet-1$/);
+ await page.goBack();
+ await expect(page.locator('.tabstrip').getByRole('button', { name: 'Media', exact: true })).toHaveAttribute('aria-current', 'page');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('a case result changes the case and opens its overview', async ({ page }) => {
+ const fixture = await start(page, { cases: CASES });
+ await page.route(`**/api/cases/${SECOND_CASE}/notes`, (route) => route.fulfill({ json: { text: '' } }));
+ await find(page, 'Airfield');
+ await dialog(page).getByRole('option', { name: /Airfield/ }).click();
+ await expect(page.getByTitle('Switch case')).toContainText('Airfield');
+ await expect(page).toHaveURL(/#overview$/);
+ fixture.expectNoUnexpectedRequests();
+});
+
+async function proofCase(page) {
+ const proofs = { 'proof-a': 'Proof A', 'proof-b': 'Proof B' };
+ const catalog = Object.entries(proofs).map(([name, label]) => ({
+ id: `${name}-entity`, type: 'proof', label, attrs: { spec: `proofs/.meta/${name}.json` },
+ }));
+ const fixture = await start(page, {
+ cases: CASES, catalog,
+ lookupEntities: Object.fromEntries(catalog.map((entity) => [entity.attrs.spec, entity])),
+ });
+ await page.route(`**/api/cases/${CASE_ID}/proofs/*`, (route) => {
+ const name = decodeURIComponent(new URL(route.request().url()).pathname.split('/').pop());
+ if (route.request().method() !== 'GET' || !proofs[name]) return route.fallback();
+ return route.fulfill({ json: { title: proofs[name], panels: [], pastes: [], shapes: [] } });
+ });
+ await find(page, 'Proof A');
+ await dialog(page).getByRole('option', { name: /Proof A/ }).click();
+ const title = page.getByRole('textbox', { name: 'Proof name' });
+ await expect(title).toHaveValue('Proof A', { timeout: 15_000 });
+ await title.fill('Proof A revised');
+ await expect(page.locator('.tool-header .badge', { hasText: 'unsaved' })).toBeVisible();
+ return { fixture, title };
+}
+
+test('opening another proof retains its existing unsaved-work confirmation', async ({ page }) => {
+ const { fixture, title } = await proofCase(page);
+ await find(page, 'Proof B');
+ await dialog(page).getByRole('option', { name: /Proof B/ }).click();
+ const ask = page.getByRole('alertdialog', { name: 'Leave this proof?' });
+ await expect(ask).toBeVisible();
+ await ask.getByRole('button', { name: 'Keep editing' }).click();
+ await expect(title).toHaveValue('Proof A revised');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('changing case asks before discarding a proof, with cancellation keeping the work', async ({ page }) => {
+ const { fixture, title } = await proofCase(page);
+ await find(page, 'Airfield');
+ await dialog(page).getByRole('option', { name: /Airfield/ }).click();
+ const ask = page.getByRole('alertdialog', { name: 'Change case?' });
+ await expect(ask).toBeVisible();
+ await expect(ask.getByRole('button', { name: 'Keep editing' })).toBeFocused();
+ await page.keyboard.press('Control+k');
+ await expect(ask).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(ask).toBeHidden();
+ await expect(dialog(page)).toBeVisible();
+ await page.keyboard.press('Escape');
+ await expect(title).toHaveValue('Proof A revised');
+ await expect(page.getByTitle('Switch case')).toContainText('Harbour');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('the topbar case switcher uses the same unsaved-work guard', async ({ page }) => {
+ const { fixture, title } = await proofCase(page);
+ await page.getByTitle('Switch case').click();
+ await page.locator('.switcher .list').getByRole('button', { name: /Airfield/ }).click();
+ const ask = page.getByRole('alertdialog', { name: 'Change case?' });
+ await expect(ask).toBeVisible();
+ await ask.getByRole('button', { name: 'Keep editing' }).click();
+ await expect(title).toHaveValue('Proof A revised');
+ await expect(page.getByTitle('Switch case')).toContainText('Harbour');
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('accented case searches work in the palette and in the case switcher', async ({ page }) => {
+ const cases = [...CASES, { id: 'study', name: 'Étude du port', scratch: false },
+ ...['One', 'Two', 'Three', 'Four'].map((name) => ({ id: name.toLowerCase(), name, scratch: false }))];
+ const fixture = await start(page, { cases });
+ await find(page, 'port etude');
+ await expect(dialog(page).getByRole('option', { name: /Étude du port/ })).toBeVisible();
+ await page.keyboard.press('Escape');
+ await page.getByTitle('Switch case').click();
+ await page.getByPlaceholder('Find a case…').fill('port etude');
+ await expect(page.locator('.switcher .list').getByRole('button', { name: /Étude du port/ })).toBeVisible();
+ fixture.expectNoUnexpectedRequests();
+});
+
+test('the palette fits a narrow window and keeps Tab inside', async ({ page }) => {
+ await page.setViewportSize({ width: 360, height: 640 });
+ const fixture = await start(page);
+ await find(page, 'reverse');
+ await expect(dialog(page).getByRole('option', { name: /Reverse Search/ })).toBeVisible();
+ await expect(dialog(page).getByRole('option')).toHaveCount(1);
+ const bounds = await dialog(page).boundingBox();
+ expect(bounds.x).toBeGreaterThanOrEqual(0);
+ expect(bounds.x + bounds.width).toBeLessThanOrEqual(360);
+ expect(bounds.y + bounds.height).toBeLessThanOrEqual(640);
+ await search(page).press('Shift+Tab');
+ await expect(dialog(page).getByRole('option', { name: /Reverse Search/ })).toBeFocused();
+ await page.keyboard.press('Shift+Tab');
+ await expect(dialog(page).getByRole('button', { name: 'Close', exact: true })).toBeFocused();
+ await page.keyboard.press('Shift+Tab');
+ await expect(search(page)).toBeFocused();
+ await page.screenshot({ path: `/tmp/azimut-palette-narrow-${test.info().project.name}.png` });
+ fixture.expectNoUnexpectedRequests();
+});
diff --git a/frontend/e2e/compare.spec.js b/frontend/e2e/compare.spec.js
index 395f0f7..a1584dc 100644
--- a/frontend/e2e/compare.spec.js
+++ b/frontend/e2e/compare.spec.js
@@ -90,7 +90,7 @@ test('linked maps keep annotations on the ground through pan, modes and save', a
expect(saved[0].spec.blink.interval).toBe(1600);
expect(saved[0].spec.annotations[0].points[0][0]).toBeCloseTo(2.2945, 2);
expect(saved[0].spec.annotations[0].points[0][1]).toBeCloseTo(48.8584, 2);
- await expect(page.getByText('Comparison and animated preview saved to My work', { exact: true })).toBeVisible();
+ await expect(page.getByText('Comparison and animated preview saved to the case', { exact: true })).toBeVisible();
await page.screenshot({ path: test.info().outputPath('compare.png') });
expect(errors).toEqual([]);
});
diff --git a/frontend/e2e/media-download.spec.js b/frontend/e2e/media-download.spec.js
index 01b186f..93c2952 100644
--- a/frontend/e2e/media-download.spec.js
+++ b/frontend/e2e/media-download.spec.js
@@ -14,7 +14,7 @@ test('explains when a large video must be saved from Telegram', async ({ page })
});
await page.goto('/#media');
- await expect(page.getByRole('heading', { name: 'Media', exact: true })).toBeVisible();
+ await expect(page.getByPlaceholder('Paste a link (X, Telegram, YouTube…)')).toBeVisible();
await page.getByPlaceholder('Paste a link (X, Telegram, YouTube…)').fill(target);
await page.getByRole('button', { name: 'Download', exact: true }).click();
diff --git a/frontend/e2e/paste.spec.js b/frontend/e2e/paste.spec.js
index cd66519..1831d4f 100644
--- a/frontend/e2e/paste.spec.js
+++ b/frontend/e2e/paste.spec.js
@@ -112,7 +112,7 @@ test('takes a copied address as a bookmark', async ({ page }) => {
test('a link in Media is refused, and told where it does work', async ({ page }) => {
const fixture = await installAppFixture(page, { catalog });
await page.goto('/#media');
- await expect(page.getByRole('heading', { name: 'Media', exact: true })).toBeVisible();
+ await expect(page.getByPlaceholder('Paste a link (X, Telegram, YouTube…)')).toBeVisible();
await paste(page, { text: 'https://leak.example.test/thread/1' });
@@ -133,11 +133,11 @@ test('one Ctrl+V opens one dialog, however many tabs have been visited', async (
// ungated listeners would answer one paste four times over.
const fixture = await installAppFixture(page, { catalog });
await page.goto('/#media');
- await expect(page.getByRole('heading', { name: 'Media', exact: true })).toBeVisible();
+ await expect(page.getByPlaceholder('Paste a link (X, Telegram, YouTube…)')).toBeVisible();
// switched by the tabs, not by the hash: a deep link is read once, at mount, and
// the point here is to leave three tools mounted at the same time
await page.getByRole('button', { name: 'Files', exact: true }).click();
- await expect(page.getByRole('heading', { name: 'Files' })).toBeVisible();
+ await expect(page.getByText('Organize your folders', { exact: true })).toBeVisible();
await page.getByRole('navigation').first().getByRole('button', { name: 'Case' }).click();
await page.locator('.tabstrip').getByRole('button', { name: 'Board', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
@@ -177,7 +177,7 @@ test('a paste in Proof stays the composer\'s own', async ({ page }) => {
// the boundary between them is worth a test rather than an argument.
const fixture = await installAppFixture(page, { catalog });
await page.goto('/#media');
- await expect(page.getByRole('heading', { name: 'Media', exact: true })).toBeVisible();
+ await expect(page.getByPlaceholder('Paste a link (X, Telegram, YouTube…)')).toBeVisible();
await page.getByRole('navigation').first().getByRole('button', { name: 'Case' }).click();
await page.locator('.tabstrip').getByRole('button', { name: 'Board', exact: true }).click();
await expect(page.getByRole('heading', { name: 'Board' })).toBeVisible();
diff --git a/frontend/src/App.svelte b/frontend/src/App.svelte
index 8c12d39..b95bebe 100644
--- a/frontend/src/App.svelte
+++ b/frontend/src/App.svelte
@@ -1,4 +1,5 @@
<script>
+ import { onDestroy, untrack } from 'svelte';
import {
uiState,
initSession,
@@ -24,6 +25,7 @@
toolFromHash,
} from './lib/workspaces.js';
import { readSolo, splitHash } from './lib/hash.js';
+ import { caseShown, installBackButton, showTool } from './lib/backButton.js';
import { guideFor } from './lib/guide.js';
import { openGuide } from './lib/navigate.js';
import { leaveFullscreen } from './lib/fullscreen.js';
@@ -40,6 +42,9 @@
import WorkspaceStopped from './components/WorkspaceStopped.svelte';
import NoteBar from './components/NoteBar.svelte';
import MoveDialog from './components/MoveDialog.svelte';
+ import CommandPalette from './components/CommandPalette.svelte';
+ import CaseChangeGuard from './components/CaseChangeGuard.svelte';
+ import { isPaletteKey } from './lib/commandPalette.js';
import { filedToast, workFolder } from './lib/folders.js';
import { isNoteKey } from './lib/noteHere.svelte.js';
import { readStatus, stoppedBecause } from './lib/workspace.js';
@@ -92,13 +97,20 @@
// (#compose, #compose/post) — see lib/workspaces.js
const fromHash = toolFromHash(location.hash, TOOL_IDS);
if (fromHash) uiState.tool = fromHash;
- // The app owns the route; a tool may keep its own state in the query after it
- // (the map writes the view its window is on, lib/map/view.js). So this writes
- // only when the route is not already the open tool — otherwise switching back
- // and forth would wipe what that tool had put there.
+ // The app owns the route; a tool may keep its own place in the query after it
+ // (the map's view, the folder Files is in). Each switch of tool is an entry, so the
+ // browser's Back and Forward walk the tools, and inside them the places the
+ // analyst went to (lib/backButton.js).
+ onDestroy(installBackButton(TOOL_IDS));
+ let firstShow = true;
$effect(() => {
- if (splitHash(location.hash).route === uiState.tool) return;
- history.replaceState(null, '', `#${uiState.tool}`);
+ const tool = uiState.tool;
+ untrack(() => showTool(tool, { first: firstShow, solo }));
+ firstShow = false;
+ });
+ $effect(() => {
+ caseState.current?.id;
+ untrack(caseShown);
});
/**
* A tab opened to hold one tool and nothing else (`lib/hash.js`).
@@ -181,6 +193,12 @@
uiState.noting = !uiState.noting;
}
function onGlobalKey(event) {
+ if (isPaletteKey(event)) {
+ event.preventDefault();
+ if (event.target?.closest?.('[role="alertdialog"]')) return;
+ if (paletteOpen || !event.target?.closest?.('[role="dialog"]')) paletteOpen = !paletteOpen;
+ return;
+ }
if (!isNoteKey(event)) return;
event.preventDefault();
toggleNote();
@@ -192,6 +210,8 @@
uiState.sidebarOpen = open;
}
+ let paletteOpen = $state(false);
+
// Tools mount lazily on first visit, then stay mounted (hidden via CSS) so
// unsaved editor state — a half-composed proof, a collage in progress —
// survives switching tabs to grab another capture or media.
@@ -301,6 +321,10 @@
</div>
<div class="spacer"></div>
<DetectActivity />
+ <button class="btn btn-ghost btn-sm" title="Go to (Ctrl+K / ⌘K)" aria-label="Go to"
+ aria-keyshortcuts="Control+k Meta+k" onclick={() => (paletteOpen = true)}>
+ <Icon name="search" size={16} />
+ </button>
<!-- The one mark that answers "what is this tab I am standing in". It sits beside
the gear rather than in each toolbar so there is one of it, and it opens the
Guide on the section written about the current tool. Silent on the Guide
@@ -435,6 +459,8 @@
<NoteBar />
<MoveDialog />
+<CommandPalette bind:open={paletteOpen} tools={ALL_TOOLS} />
+<CaseChangeGuard />
<Toasts />
{#if workspaceStopped}
diff --git a/frontend/src/components/CaseChangeGuard.render.test.js b/frontend/src/components/CaseChangeGuard.render.test.js
new file mode 100644
index 0000000..a8bf557
--- /dev/null
+++ b/frontend/src/components/CaseChangeGuard.render.test.js
@@ -0,0 +1,111 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const get = vi.fn(async (path) => (path.startsWith('/api/cases/') ? { id: path.split('/').pop() } : []));
+const post = vi.fn(async () => ({ id: 'harbour' }));
+vi.mock('../lib/api.js', () => ({ api: { get, post } }));
+const { caseState, openCase, promoteCase } = await import('../lib/state.svelte.js');
+const { holdsUnsaved } = await import('../lib/backButton.js');
+const { default: CaseChangeGuard } = await import('./CaseChangeGuard.svelte');
+
+let live;
+let stopHolding;
+async function settle() {
+ for (let i = 0; i < 8; i++) await Promise.resolve();
+ flushSync();
+}
+const click = (label) => [...document.querySelectorAll('button')].find((button) => button.textContent === label).click();
+
+beforeEach(() => {
+ get.mockClear();
+ post.mockClear();
+ caseState.current = { id: 'case-a' };
+ live = mount(CaseChangeGuard, { target: document.body });
+});
+afterEach(() => {
+ if (live) unmount(live);
+ stopHolding?.();
+ stopHolding = null;
+ document.body.innerHTML = '';
+});
+
+describe('case changes from any entry point', () => {
+ it('opens directly when the mounted tools hold no unsaved work', async () => {
+ await openCase('case-b');
+ expect(caseState.current.id).toBe('case-b');
+ expect(document.querySelector('[role="alertdialog"]')).toBeNull();
+ });
+
+ it('cancels without reading another case or clearing queued work', async () => {
+ stopHolding = holdsUnsaved('proof', () => true);
+ const opening = openCase('case-b');
+ await settle();
+ expect(document.activeElement.textContent).toBe('Keep editing');
+ click('Keep editing');
+ await opening;
+ expect(get).not.toHaveBeenCalled();
+ expect(caseState.current.id).toBe('case-a');
+ expect(caseState.loading).toBe(false);
+ });
+
+ it('opens after explicit confirmation', async () => {
+ stopHolding = holdsUnsaved('post', () => true);
+ const opening = openCase('case-b');
+ await settle();
+ click('Change case');
+ await opening;
+ expect(caseState.current.id).toBe('case-b');
+ });
+
+ it('supersedes an older question when a newer case is requested', async () => {
+ stopHolding = holdsUnsaved('proof', () => true);
+ const older = openCase('case-b');
+ await settle();
+ const newer = openCase('case-c');
+ await settle();
+ click('Change case');
+ await Promise.all([older, newer]);
+ expect(get).toHaveBeenCalledTimes(1);
+ expect(caseState.current.id).toBe('case-c');
+ });
+
+ it('settles a pending switch on teardown and unregisters the guard', async () => {
+ stopHolding = holdsUnsaved('proof', () => true);
+ const opening = openCase('case-b');
+ await settle();
+ unmount(live);
+ live = null;
+ await opening;
+ expect(caseState.current.id).toBe('case-a');
+ await openCase('case-c');
+ expect(caseState.current.id).toBe('case-c');
+ });
+});
+
+describe('keeping a scratch session as a case', () => {
+ it('asks in its own words before the session moves, and keeps it on Keep editing', async () => {
+ caseState.current = { id: 'scratch_a', scratch: true };
+ stopHolding = holdsUnsaved('post', () => true);
+ const promoting = promoteCase('Harbour');
+ await settle();
+ expect(document.querySelector('[role="alertdialog"]').textContent).toContain('Keep this session as a case?');
+ click('Keep editing');
+ expect(await promoting).toBeNull();
+ expect(post).not.toHaveBeenCalled();
+ expect(caseState.current.id).toBe('scratch_a');
+ });
+
+ it('opens the kept case without asking a second time', async () => {
+ caseState.current = { id: 'scratch_a', scratch: true };
+ stopHolding = holdsUnsaved('post', () => true);
+ const promoting = promoteCase('Harbour');
+ await settle();
+ click('Keep as case');
+ await promoting;
+ await settle();
+ expect(post).toHaveBeenCalledWith('/api/cases/scratch_a/promote', { name: 'Harbour' });
+ expect(document.querySelector('[role="alertdialog"]')).toBeNull();
+ expect(caseState.current.id).toBe('harbour');
+ });
+});
diff --git a/frontend/src/components/CaseChangeGuard.svelte b/frontend/src/components/CaseChangeGuard.svelte
new file mode 100644
index 0000000..68d7340
--- /dev/null
+++ b/frontend/src/components/CaseChangeGuard.svelte
@@ -0,0 +1,31 @@
+<script>
+ import { onDestroy } from 'svelte';
+ import { caseState, registerCaseChangeGuard } from '../lib/state.svelte.js';
+ import { anyUnsaved } from '../lib/backButton.js';
+ import ConfirmDialog from './ConfirmDialog.svelte';
+
+ let pending = $state(null);
+
+ function answer(accepted) {
+ const request = pending;
+ pending = null;
+ request?.resolve(accepted && request.fromId === caseState.current?.id);
+ }
+
+ onDestroy(registerCaseChangeGuard(({ fromId, reason }) => {
+ if (!anyUnsaved()) return true;
+ answer(false);
+ return new Promise((resolve) => { pending = { fromId, promote: reason === 'promote', resolve }; });
+ }));
+ onDestroy(() => answer(false));
+</script>
+
+{#if pending?.promote}
+ <ConfirmDialog title="Keep this session as a case?" message="Unsaved work in this session will be lost."
+ confirmLabel="Keep as case" cancelLabel="Keep editing" icon="folder"
+ onconfirm={() => answer(true)} oncancel={() => answer(false)} />
+{:else if pending}
+ <ConfirmDialog title="Change case?" message="Unsaved work in this case will be lost."
+ confirmLabel="Change case" cancelLabel="Keep editing" icon="folder"
+ onconfirm={() => answer(true)} oncancel={() => answer(false)} />
+{/if}
diff --git a/frontend/src/components/CaseSidebar.svelte b/frontend/src/components/CaseSidebar.svelte
index 7448c03..f49d740 100644
--- a/frontend/src/components/CaseSidebar.svelte
+++ b/frontend/src/components/CaseSidebar.svelte
@@ -54,6 +54,9 @@
let loadedCaseId = null;
const byFolder = $derived(summary?.by_folder ?? {});
+ // A folder opens on its accepted rows, so it counts those; a suggestion filed in it
+ // is counted under Suggestions.
+ const filedByFolder = $derived(summary?.confirmed?.by_folder ?? {});
const suggestedCount = $derived(summary?.by_status?.suggested ?? 0);
async function loadSection(sec, params, { id, mySeq, more = false } = {}) {
@@ -255,7 +258,7 @@
openEntity(entity);
}
- // ── My work: the analyst's own nested folder tree ('/'-separated paths) ────
+ // ── Folders: the analyst's own nested folder tree ('/'-separated paths) ────
let newFolderOpen = $state(false);
let newFolder = $state('');
let expanded = $state({}); // path -> bool (absent = collapsed)
@@ -372,13 +375,12 @@
}
}
- // Remove from My work: just clears the filing. The item stays in its tool.
+ // Move to Unfiled: just clears the filing. The item stays in its tool.
function askRemoveFromMyWork(entity) {
confirmState = {
- title: 'Remove from My work?',
- message: `“${entity.label}” is unfiled. Nothing is deleted.`,
- detail: 'It stays available in the case and its tool. Only your filing here is cleared.',
- confirmLabel: 'Remove from My work',
+ title: 'Move to Unfiled?',
+ message: `“${entity.label}” leaves its folder. Nothing is deleted.`,
+ confirmLabel: 'Move to Unfiled',
tone: 'default',
icon: 'folderMinus',
action: () => assignFolder(entity, ''),
@@ -708,7 +710,7 @@
<SidebarTree
{tree}
- {byFolder}
+ byFolder={filedByFolder}
{expanded}
{folderData}
unfiled={unfiledData}
@@ -830,8 +832,8 @@
<label class="modal-label" for="note-title">Title</label>
<input id="note-title" class="input" placeholder="Note title…" bind:value={noteModal.title} />
- <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
- <FolderSelect bind:value={noteModal.folder} folders={allFolders} emptyLabel="My work (root)" fresh />
+ <span class="modal-label" style="margin-top:10px">Folder</span>
+ <FolderSelect bind:value={noteModal.folder} folders={allFolders} emptyLabel="Unfiled" fresh />
<div class="modal-row">
<div style="flex:1"></div>
@@ -843,7 +845,7 @@
</Modal>
{/if}
-<!-- Confirmation dialog (remove from My work / remove folder) -->
+<!-- Confirmation dialog (move to Unfiled / remove folder) -->
{#if confirmState}
<ConfirmDialog
title={confirmState.title}
diff --git a/frontend/src/components/CaseSidebar.test.js b/frontend/src/components/CaseSidebar.test.js
index d96f6e1..7c7e46f 100644
--- a/frontend/src/components/CaseSidebar.test.js
+++ b/frontend/src/components/CaseSidebar.test.js
@@ -29,6 +29,12 @@ describe('sidebar shell', () => {
);
});
+ it('counts a folder by the accepted rows it opens on', () => {
+ // a suggestion filed in a folder is counted once, under Suggestions
+ expect(shell).toContain('const filedByFolder = $derived(summary?.confirmed?.by_folder ?? {})');
+ expect(shell).toContain('byFolder={filedByFolder}');
+ });
+
it('keeps bounded per-section loading and the stale-response guard', () => {
expect(shell).toContain('const CATALOG_PAGE = 200');
expect(shell).toContain('if (mySeq !== seq) return;');
diff --git a/frontend/src/components/CaseSwitcher.svelte b/frontend/src/components/CaseSwitcher.svelte
index 1a06223..88a60bb 100644
--- a/frontend/src/components/CaseSwitcher.svelte
+++ b/frontend/src/components/CaseSwitcher.svelte
@@ -24,6 +24,7 @@
import { checkCase, repairCase } from '../lib/doctor.js';
import { revealCaseFolder } from '../lib/reveal.js';
import { formatSize } from '../lib/trash.js';
+ import { foldTerms, foldText } from '../lib/textFold.js';
import Icon from './Icon.svelte';
import Modal from './Modal.svelte';
import SearchInput from './SearchInput.svelte';
@@ -301,7 +302,7 @@
// and debounce a server query so it still finds a case in a long list the
// first page didn't hold. Both paths key on the case name.
const matchesSearch = (c) =>
- (c.name ?? c.id ?? '').toLowerCase().includes(search.trim().toLowerCase());
+ foldTerms(search).every((term) => foldText(c.name ?? c.id ?? '').includes(term));
let searchTimer;
$effect(() => {
const q = search;
@@ -322,8 +323,7 @@
busy = true;
try {
if (modal === 'create') {
- await createCase(name);
- toast(`Case “${name}” created`, 'ok');
+ if (await createCase(name)) toast(`Case “${name}” created`, 'ok');
} else if (modal === 'promote') {
await promoteCase(name);
} else if (modal === 'rename') {
@@ -370,7 +370,7 @@
} else {
open = false;
const adopted = await adoptFolder(folder.name);
- toast(`Case “${adopted.name ?? folder.name}” created`, 'ok');
+ if (adopted) toast(`Case “${adopted.name ?? folder.name}” created`, 'ok');
}
} catch (error) {
toast(error.message || 'Could not use this folder', 'danger', 7000);
diff --git a/frontend/src/components/CommandPalette.render.test.js b/frontend/src/components/CommandPalette.render.test.js
new file mode 100644
index 0000000..27db7a1
--- /dev/null
+++ b/frontend/src/components/CommandPalette.render.test.js
@@ -0,0 +1,284 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { flushSync, mount, unmount } from 'svelte';
+
+const get = vi.fn();
+vi.mock('../lib/api.js', () => ({ api: { get } }));
+
+const { caseState, uiState, registerCaseChangeGuard } = await import('../lib/state.svelte.js');
+const { loadEntityTypes } = await import('../lib/entityTypes.svelte.js');
+const { holdsUnsaved } = await import('../lib/backButton.js');
+const { default: CommandPalette } = await import('./CommandPalette.svelte');
+const { default: CaseChangeGuard } = await import('./CaseChangeGuard.svelte');
+
+const NOTE = { id: 'note-a', type: 'note', label: 'Harbour observations', attrs: { folder: 'Harbour' } };
+const SHEET = { id: 'sheet-a', type: 'sheet', label: 'Geolocation index', attrs: { path: 'sheets/index.csv' } };
+const CASES = [{ id: 'case-a', name: 'Harbour' }, { id: 'case-b', name: 'Airfield' }];
+const TOOLS = [{ id: 'media', label: 'Media' }, { id: 'proof', label: 'Geo Proof' }, { id: 'sheet', label: 'Sheet' }];
+
+let live;
+let guardComponent;
+let target;
+const cleanups = [];
+
+async function settle(ms = 0) {
+ flushSync();
+ await vi.advanceTimersByTimeAsync(ms);
+ for (let i = 0; i < 8; i += 1) await Promise.resolve();
+ flushSync();
+}
+
+async function show(open = true) {
+ target = document.createElement('div');
+ document.body.append(target);
+ live = mount(CommandPalette, { target, props: { open, tools: TOOLS } });
+ guardComponent = mount(CaseChangeGuard, { target });
+ await settle();
+}
+
+const input = () => document.querySelector('[role="combobox"]');
+const options = () => [...document.querySelectorAll('[role="option"]')];
+const option = (label) => options().find((node) => node.querySelector('.name').textContent === label);
+
+async function search(text) {
+ input().value = text;
+ input().dispatchEvent(new Event('input', { bubbles: true }));
+ await settle(160);
+}
+
+beforeEach(async () => {
+ vi.useFakeTimers();
+ get.mockReset();
+ get.mockImplementation(async (path) => {
+ if (path === '/api/cases/entity-types') return [
+ { type: 'note', family: 'document', label: 'Note' },
+ { type: 'sheet', family: 'document', label: 'Sheet' },
+ { type: 'media', family: 'collected', label: 'Media' },
+ { type: 'person', family: 'actor', label: 'Person' },
+ ];
+ const url = new URL(path, 'http://localhost');
+ if (url.pathname === '/api/cases') {
+ const query = url.searchParams.get('q')?.toLowerCase() ?? '';
+ return CASES.filter((item) => item.name.toLowerCase().includes(query));
+ }
+ if (url.pathname.endsWith('/catalog/entities')) {
+ const query = url.searchParams.get('q')?.toLowerCase() ?? '';
+ const items = [NOTE, SHEET].filter((item) => item.label.toLowerCase().includes(query));
+ return { items, total: items.length };
+ }
+ if (url.pathname === '/api/cases/case-b') return CASES[1];
+ throw new Error(`Unexpected request: ${path}`);
+ });
+ await loadEntityTypes();
+ get.mockClear();
+ caseState.current = CASES[0];
+ uiState.tool = 'media';
+ uiState.openNotebook = null;
+ uiState.openSheet = null;
+ uiState.toasts = [];
+});
+
+afterEach(() => {
+ cleanups.splice(0).forEach((cleanup) => cleanup());
+ if (live) unmount(live);
+ if (guardComponent) unmount(guardComponent);
+ live = null;
+ target?.remove();
+ document.body.innerHTML = '';
+ vi.useRealTimers();
+});
+
+describe('Go to', () => {
+ it('reads nothing while closed and focuses the search when opened', async () => {
+ await show(false);
+ expect(get).not.toHaveBeenCalled();
+ unmount(live);
+ unmount(guardComponent);
+ await show();
+ expect(document.activeElement).toBe(input());
+ expect(document.querySelector('[aria-label="Recently added"]')).not.toBeNull();
+ expect(option(NOTE.label)).toBeDefined();
+ const urls = get.mock.calls.map(([path]) => new URL(path, 'http://localhost'));
+ const catalog = urls.find((url) => url.pathname.endsWith('/catalog/entities'));
+ expect(catalog.searchParams.get('limit')).toBe('8');
+ expect(catalog.searchParams.get('order')).toBe('-created');
+ expect(catalog.searchParams.get('type')).toBe('note,sheet,media');
+ });
+
+ it('searches documents server-side and opens the chosen note', async () => {
+ await show();
+ await search('Harbour');
+ expect(option(NOTE.label)).toBeDefined();
+ expect(option(SHEET.label)).toBeUndefined();
+ const request = get.mock.calls.find(([path]) => path.includes('/catalog/entities') && path.includes('q=Harbour'));
+ expect(new URL(request[0], 'http://localhost').searchParams.get('limit')).toBe('20');
+ option(NOTE.label).click();
+ await settle();
+ expect(uiState.openNotebook).toEqual({ noteId: NOTE.id });
+ expect(uiState.tool).toBe('notebook');
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
+ });
+
+ it('opens a sheet in Sheet instead of the Board', async () => {
+ await show();
+ option(SHEET.label).click();
+ await settle();
+ expect(uiState.tool).toBe('sheet');
+ expect(uiState.openSheet).toBe(SHEET.id);
+ });
+
+ it('walks results with the arrows and opens with Enter', async () => {
+ await show();
+ await search('proof');
+ input().dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowUp', bubbles: true, cancelable: true }));
+ await settle();
+ expect(options().filter((node) => node.getAttribute('aria-selected') === 'true')).toHaveLength(1);
+ input().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }));
+ await settle();
+ expect(uiState.tool).toBe('proof');
+ });
+
+ it('keeps case changes behind the existing guard', async () => {
+ await show();
+ await search('Airfield');
+ const guard = vi.fn(async () => false);
+ cleanups.push(registerCaseChangeGuard(guard));
+ option('Airfield').click();
+ await settle();
+ expect(guard).toHaveBeenCalledWith({ fromId: 'case-a', toId: 'case-b' });
+ expect(caseState.current.id).toBe('case-a');
+ expect(uiState.tool).toBe('media');
+ expect(get.mock.calls.some(([path]) => path === '/api/cases/case-b')).toBe(false);
+ });
+
+ it('opens a chosen case on its overview', async () => {
+ await show();
+ await search('Airfield');
+ option('Airfield').click();
+ await settle();
+ expect(caseState.current.id).toBe('case-b');
+ expect(uiState.tool).toBe('overview');
+ });
+
+ it('asks before a case change can discard work, with Keep editing selected', async () => {
+ cleanups.push(holdsUnsaved('proof', () => true));
+ await show();
+ await search('Airfield');
+ option('Airfield').click();
+ await settle();
+ const dialog = document.querySelector('[role="alertdialog"]');
+ expect(dialog.textContent).toContain('Unsaved work');
+ expect(document.activeElement.textContent).toBe('Keep editing');
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
+ await settle();
+ expect(document.querySelector('[role="alertdialog"]')).toBeNull();
+ expect(document.querySelector('[role="dialog"]')).not.toBeNull();
+ expect(caseState.current.id).toBe('case-a');
+ expect(get.mock.calls.some(([path]) => path === '/api/cases/case-b')).toBe(false);
+ });
+
+ it('changes case after the unsaved-work confirmation', async () => {
+ cleanups.push(holdsUnsaved('proof', () => true));
+ await show();
+ await search('Airfield');
+ option('Airfield').click();
+ await settle();
+ [...document.querySelectorAll('[role="alertdialog"] button')].find((button) => button.textContent === 'Change case').click();
+ await settle();
+ expect(caseState.current.id).toBe('case-b');
+ expect(uiState.tool).toBe('overview');
+ });
+
+ it('discards a slow result after the query changes', async () => {
+ await show();
+ const normal = get.getMockImplementation();
+ let release;
+ get.mockImplementation((path, options) => path.includes('q=Harbour') && path.includes('/catalog/entities')
+ ? new Promise((resolve) => (release = resolve))
+ : normal(path, options));
+ await search('Harbour');
+ await search('Geolocation');
+ expect(option(SHEET.label)).toBeDefined();
+ release({ items: [NOTE], total: 1 });
+ await settle();
+ expect(option(NOTE.label)).toBeUndefined();
+ expect(option(SHEET.label)).toBeDefined();
+ });
+
+ it('cancels searches on close and returns focus to the invoking control', async () => {
+ const trigger = document.createElement('button');
+ document.body.append(trigger);
+ trigger.focus();
+ await show();
+ const signals = get.mock.calls.map(([, options]) => options.signal);
+ window.dispatchEvent(new KeyboardEvent('keydown', { key: 'Escape' }));
+ await settle();
+ expect(document.querySelector('[role="dialog"]')).toBeNull();
+ expect(signals.every((signal) => signal.aborted)).toBe(true);
+ expect(document.activeElement).toBe(trigger);
+ });
+
+ it('keeps tools usable when a document request fails', async () => {
+ get.mockImplementation(async (path) => {
+ if (path.includes('/catalog/entities')) throw new Error('Offline');
+ return [];
+ });
+ await show();
+ expect(option('Media')).toBeDefined();
+ expect(document.querySelector('[role="status"]').textContent).toContain('Could not load documents.');
+ });
+
+ it('shows truncation only for a search, not for the eight recently added items', async () => {
+ const normal = get.getMockImplementation();
+ get.mockImplementation(async (path, options) => {
+ const response = await normal(path, options);
+ return path.includes('/catalog/entities') ? { ...response, total: 80 } : response;
+ });
+ await show();
+ expect(document.querySelector('[role="status"]').textContent).not.toContain('refine your search');
+ await search('Harbour');
+ expect(document.querySelector('[role="status"]').textContent).toContain('Showing 1 of 80 documents');
+ });
+
+ it('keeps results during a slow search and waits for fresh results on Enter', async () => {
+ await show();
+ const normal = get.getMockImplementation();
+ let release;
+ get.mockImplementation((path, options) => path.includes('q=Geolocation') && path.includes('/catalog/entities')
+ ? new Promise((resolve) => (release = resolve)) : normal(path, options));
+ input().value = 'Geolocation';
+ input().dispatchEvent(new Event('input', { bubbles: true }));
+ await settle(100);
+ expect(option(NOTE.label)).toBeDefined();
+ expect(option(SHEET.label)).toBeDefined();
+ expect(option('Airfield')).toBeDefined();
+ input().dispatchEvent(new KeyboardEvent('keydown', { key: 'Enter', bubbles: true, cancelable: true }));
+ await settle(60);
+ expect(uiState.tool).toBe('media');
+ release({ items: [SHEET], total: 1 });
+ await settle();
+ expect(uiState.tool).toBe('sheet');
+ expect(uiState.openSheet).toBe(SHEET.id);
+ });
+
+ it('starts new words from the best match and marks what they matched', async () => {
+ await show();
+ for (let i = 0; i < 3; i += 1) {
+ input().dispatchEvent(new KeyboardEvent('keydown', { key: 'ArrowDown', bubbles: true, cancelable: true }));
+ }
+ await settle();
+ expect(options().findIndex((node) => node.getAttribute('aria-selected') === 'true')).toBe(3);
+ await search('harbour');
+ expect(options()[0].getAttribute('aria-selected')).toBe('true');
+ expect(option(NOTE.label).querySelector('b').textContent).toBe('Harbour');
+ });
+
+ it('marks scratch sessions separately from named cases', async () => {
+ const normal = get.getMockImplementation();
+ get.mockImplementation((path, options) => new URL(path, 'http://localhost').pathname === '/api/cases'
+ ? Promise.resolve([{ id: 'scratch-a', name: 'Scratch session', scratch: true }]) : normal(path, options));
+ await show();
+ expect(option('Scratch session').textContent).toContain('Scratch');
+ expect(option('Scratch session').querySelector('.detail').textContent).not.toContain('Case');
+ });
+});
diff --git a/frontend/src/components/CommandPalette.svelte b/frontend/src/components/CommandPalette.svelte
new file mode 100644
index 0000000..6d78709
--- /dev/null
+++ b/frontend/src/components/CommandPalette.svelte
@@ -0,0 +1,361 @@
+<script>
+ import { tick, untrack } from 'svelte';
+ import { api } from '../lib/api.js';
+ import { caseState, openCase, toast, uiState } from '../lib/state.svelte.js';
+ import { buildCatalogQuery } from '../lib/catalog.js';
+ import { entityLabel, entityTypes } from '../lib/entityTypes.svelte.js';
+ import { entityIcon, entityKindLabel } from '../lib/entityIcon.js';
+ import { openEntity } from '../lib/navigate.js';
+ import { matchRuns, paletteTools } from '../lib/commandPalette.js';
+ import Icon from './Icon.svelte';
+ import Modal from './Modal.svelte';
+
+ let { open = $bindable(false), tools = [] } = $props();
+ let query = $state('');
+ let documents = $state([]);
+ let documentCase = $state(null);
+ let cases = $state([]);
+ let selected = $state(0);
+ let loading = $state(false);
+ let errors = $state([]);
+ let total = $state(0);
+ let list = $state(null);
+ let loadedCase = $state(null);
+ let loadedQuery = $state('');
+ let openAfterSearch = false;
+ let answered = false;
+
+ const documentTypes = $derived(entityTypes()
+ .filter((entry) => ['document', 'collected'].includes(entry.family))
+ .map((entry) => entry.type));
+ const toolRows = $derived(paletteTools(tools, loadedQuery));
+ const documentRows = $derived(documents.map((entity) => ({
+ kind: 'document', id: entity.id, label: entity.label, caseId: documentCase,
+ detail: [entityKindLabel(entity, entityLabel(entity.type)), entity.attrs?.folder].filter(Boolean).join(' · '),
+ icon: entityIcon(entity), entity,
+ })));
+ const caseRows = $derived(cases.map((item) => ({
+ kind: 'case', id: item.id, label: item.name ?? item.id,
+ detail: [item.scratch ? 'Scratch' : 'Case', item.id === caseState.current?.id ? 'Current' : ''].filter(Boolean).join(' · '), icon: 'folder',
+ })));
+ const groups = $derived(loadedQuery
+ ? [{ label: 'Tools', rows: toolRows }, { label: 'Documents', rows: documentRows }, { label: 'Cases', rows: caseRows }]
+ : [{ label: 'Recently added', rows: documentRows }, { label: 'Tools', rows: toolRows }, { label: 'Cases', rows: caseRows }]);
+ const rows = $derived(groups.flatMap((group) => group.rows));
+
+ $effect(() => {
+ if (open) {
+ query = '';
+ loadedQuery = '';
+ documents = [];
+ cases = [];
+ total = 0;
+ selected = 0;
+ answered = false;
+ }
+ });
+
+ $effect(() => {
+ if (!open) return;
+ const caseId = caseState.current?.id;
+ const text = query.trim();
+ const types = documentTypes;
+ const controller = new AbortController();
+ openAfterSearch = false;
+ if (caseId !== untrack(() => loadedCase)) {
+ documents = [];
+ cases = [];
+ total = 0;
+ }
+ errors = [];
+ loading = true;
+
+ const timer = setTimeout(async () => {
+ const caseQuery = new URLSearchParams({ limit: '8' });
+ if (text) caseQuery.set('q', text);
+ const requests = [api.get(`/api/cases?${caseQuery}`, { signal: controller.signal })];
+ if (caseId && types.length) {
+ requests.push(api.get(buildCatalogQuery(caseId, {
+ types, query: text, limit: text ? 20 : 8, order: text ? 'relevance' : '-created',
+ }), { signal: controller.signal }));
+ }
+ const [caseResult, documentResult] = await Promise.allSettled(requests);
+ if (controller.signal.aborted || !open || caseId !== caseState.current?.id || text !== query.trim()) return;
+ const active = untrack(() => rows[selected]);
+ if (caseResult.status === 'fulfilled') cases = caseResult.value;
+ else { cases = []; errors.push('Could not load cases.'); }
+ if (documentResult?.status === 'fulfilled') {
+ documents = documentResult.value.items ?? [];
+ documentCase = caseId;
+ total = documentResult.value.total ?? documents.length;
+ } else if (documentResult?.status === 'rejected' || (caseId && !types.length)) {
+ documents = [];
+ total = 0;
+ errors.push('Could not load documents.');
+ }
+ // A refreshed answer to the same words keeps the row the analyst was on; the
+ // first answer and new words start from the top, which is what Enter should open.
+ const sameQuery = answered && text === loadedQuery;
+ answered = true;
+ loadedCase = caseId;
+ loadedQuery = text;
+ selected = sameQuery ? Math.max(0, rows.findIndex((row) => row.kind === active?.kind && row.id === active?.id)) : 0;
+ if (!sameQuery && list) list.scrollTop = 0;
+ loading = false;
+ if (openAfterSearch) { openAfterSearch = false; void choose(rows[selected]); }
+ }, text ? 150 : 0);
+
+ return () => {
+ clearTimeout(timer);
+ controller.abort();
+ };
+ });
+
+ function close() {
+ openAfterSearch = false;
+ open = false;
+ }
+
+ async function choose(row) {
+ if (!row) return;
+ if (row.kind === 'document' && row.caseId !== caseState.current?.id) return;
+ try {
+ if (row.kind === 'tool') { close(); uiState.tool = row.id; }
+ else if (row.kind === 'document') { close(); await openEntity(row.entity); }
+ else {
+ if (row.id !== caseState.current?.id) await openCase(row.id);
+ if (caseState.current?.id === row.id) { close(); uiState.tool = 'overview'; }
+ }
+ } catch (error) {
+ toast(error.message || 'Could not open this item.', 'danger');
+ }
+ }
+
+ async function onKeydown(event) {
+ if (event.isComposing) return;
+ if (['ArrowDown', 'ArrowUp'].includes(event.key)) {
+ event.preventDefault();
+ event.stopPropagation();
+ if (!rows.length) return;
+ selected = (selected + (event.key === 'ArrowDown' ? 1 : -1) + rows.length) % rows.length;
+ await tick();
+ list?.querySelector(`#go-to-result-${selected}`)?.scrollIntoView?.({ block: 'nearest' });
+ } else if (event.key === 'Enter') {
+ event.preventDefault();
+ event.stopPropagation();
+ if (loading) openAfterSearch = true;
+ else void choose(rows[selected]);
+ }
+ }
+
+ function focus(node) {
+ queueMicrotask(() => node.isConnected && node.focus());
+ }
+
+</script>
+
+{#if open}
+ <Modal title="Go to" width="640px" align="top" bare onclose={close}>
+ <div class="search" class:busy={loading}>
+ <Icon name="search" size={18} />
+ <input
+ use:focus bind:value={query} onkeydown={onKeydown}
+ placeholder="Search tools, cases and documents…" aria-label="Search tools, cases and documents"
+ role="combobox" aria-autocomplete="list" aria-expanded="true" aria-controls="go-to-results"
+ aria-activedescendant={rows[selected] ? `go-to-result-${selected}` : undefined}
+ autocomplete="off" spellcheck="false"
+ />
+ <button class="esc" type="button" onclick={close} aria-label="Close" title="Close">Esc</button>
+ </div>
+ <div class="results" id="go-to-results" role="listbox" aria-label="Destinations" bind:this={list}>
+ {#each groups as group (group.label)}
+ {#if group.rows.length}
+ <div class="group" role="group" aria-label={group.label}>
+ <h4>{group.label}</h4>
+ {#each group.rows as row (`${row.kind}:${row.id}`)}
+ {@const index = rows.indexOf(row)}
+ <button
+ class="result" class:active={selected === index} id={`go-to-result-${index}`}
+ type="button" role="option" aria-selected={selected === index}
+ onclick={() => choose(row)} onpointermove={() => (selected = index)}
+ >
+ <span class="glyph"><Icon name={row.icon} size={15} /></span>
+ <span class="name" dir="auto">{#each matchRuns(row.label, loadedQuery) as run, i (i)}{#if run.hit}<b>{run.text}</b>{:else}{run.text}{/if}{/each}</span>
+ {#if row.detail}<span class="detail" dir="auto">{row.detail}</span>{/if}
+ <kbd class="enter" aria-hidden="true"><Icon name="enter" size={11} stroke={2.2} /></kbd>
+ </button>
+ {/each}
+ </div>
+ {/if}
+ {/each}
+ </div>
+ <div class="status" role="status">
+ {#if !loading && !rows.length && !errors.length}
+ <p class="none">{loadedQuery ? `No matches for “${loadedQuery}”.` : 'No matches.'}</p>
+ {/if}
+ {#each errors as error}<p class="error"><Icon name="alert" size={13} />{error}</p>{/each}
+ {#if !loading && loadedQuery && total > documents.length}
+ <p>Showing {documents.length} of {total} documents; refine your search.</p>
+ {/if}
+ </div>
+ <footer>
+ <span><kbd>↑</kbd><kbd>↓</kbd> Choose</span>
+ <span><kbd><Icon name="enter" size={11} stroke={2.2} /></kbd> Open</span>
+ {#if loading}<span class="searching">Searching…</span>{/if}
+ </footer>
+ </Modal>
+{/if}
+
+<style>
+ .search {
+ position: relative;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ padding: 0 14px 0 18px;
+ border-bottom: 1px solid var(--border);
+ color: var(--text-3);
+ }
+ .search:focus-within { color: var(--text-2); }
+ .search input {
+ flex: 1;
+ min-width: 0;
+ height: 56px;
+ padding: 0;
+ border: 0;
+ outline: none;
+ background: transparent;
+ color: var(--text-1);
+ font-size: var(--fs-lg);
+ }
+ .search input::placeholder { color: var(--text-3); }
+ /* What used to be a line of text: a sliver of the accent running under the field. */
+ .search.busy::after {
+ content: '';
+ position: absolute;
+ left: 0;
+ bottom: -1px;
+ width: 30%;
+ height: 2px;
+ background: linear-gradient(90deg, transparent, var(--accent), transparent);
+ animation: sweep 0.9s var(--ease) infinite;
+ }
+ @keyframes sweep {
+ from { transform: translateX(-100%); }
+ to { transform: translateX(340%); }
+ }
+ .esc {
+ padding: 3px 7px;
+ border: 1px solid var(--border-strong);
+ border-radius: var(--r-sm);
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .esc:hover { color: var(--text-1); background: var(--bg-3); }
+
+ .results {
+ max-height: min(440px, 56dvh);
+ overflow-y: auto;
+ overscroll-behavior: contain;
+ padding: 0 8px;
+ }
+ .group { padding: 6px 0 4px; }
+ .group + .group { border-top: 1px solid var(--border); }
+ h4 {
+ padding: 8px 10px 6px;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ font-weight: 600;
+ letter-spacing: 0.05em;
+ text-transform: uppercase;
+ }
+ .result {
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ width: 100%;
+ min-height: 40px;
+ padding: 6px 10px;
+ border-radius: var(--r-md);
+ text-align: left;
+ color: var(--text-1);
+ }
+ .result.active { background: var(--bg-3); }
+ .glyph {
+ display: grid;
+ place-items: center;
+ flex: none;
+ width: 28px;
+ height: 28px;
+ border: 1px solid var(--border);
+ border-radius: var(--r-md);
+ background: var(--bg-2);
+ color: var(--text-2);
+ }
+ .result.active .glyph { border-color: transparent; background: var(--accent-soft); color: var(--accent); }
+ .name {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: var(--fs-md);
+ }
+ .name b { font-weight: 700; color: var(--text-1); text-decoration: underline; text-decoration-color: var(--accent); text-underline-offset: 3px; }
+ .detail {
+ flex: none;
+ max-width: 40%;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .result.active .detail { color: var(--text-2); }
+ .enter { visibility: hidden; }
+ .result.active .enter { visibility: visible; }
+
+ .status { color: var(--text-3); font-size: var(--fs-xs); }
+ .status p { padding: 8px 18px; }
+ .status p:first-child { padding-top: 10px; }
+ .status p:last-child { padding-bottom: 10px; }
+ .status .none { padding: 28px 18px; text-align: center; font-size: var(--fs-sm); }
+ .status .error { display: flex; align-items: center; gap: 6px; color: var(--danger); }
+
+ footer {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ padding: 9px 18px;
+ border-top: 1px solid var(--border);
+ background: var(--bg-0);
+ color: var(--text-3);
+ font-size: var(--fs-xs);
+ }
+ .searching { margin-left: auto; }
+ kbd {
+ display: inline-grid;
+ place-items: center;
+ min-width: 18px;
+ height: 18px;
+ margin-right: 3px;
+ padding: 0 4px;
+ border: 1px solid var(--border-strong);
+ border-bottom-width: 2px;
+ border-radius: var(--r-sm);
+ background: var(--bg-2);
+ color: var(--text-2);
+ font: inherit;
+ font-size: 0.68rem;
+ line-height: 1;
+ }
+ @media (max-width: 480px) {
+ .search { padding: 0 10px 0 14px; }
+ .search input { font-size: var(--fs-md); }
+ .detail { max-width: 32%; }
+ footer { gap: 12px; padding: 9px 14px; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .search.busy::after { animation: none; width: 100%; opacity: 0.5; }
+ }
+</style>
diff --git a/frontend/src/components/ConfirmDialog.svelte b/frontend/src/components/ConfirmDialog.svelte
index d895b27..38976fa 100644
--- a/frontend/src/components/ConfirmDialog.svelte
+++ b/frontend/src/components/ConfirmDialog.svelte
@@ -21,6 +21,7 @@
consequences = null,
restorable = '',
confirmLabel = 'Confirm',
+ cancelLabel = 'Cancel',
tone = 'default', // 'danger' | 'default'
icon = tone === 'danger' ? 'trash' : 'folderMinus',
busy = false,
@@ -34,7 +35,7 @@
const self = {};
let cancelBtn = $state(null);
- $effect(() => joinOverlays(self));
+ $effect(() => joinOverlays(self, () => oncancel?.()));
// An alertdialog that leaves the focus behind the veil is unreachable by keyboard, so
// move it in. Cancel and not the confirm button: this dialog exists to be read before
@@ -122,7 +123,7 @@
</div>
{/if}
<div class="actions">
- <button class="btn" bind:this={cancelBtn} onclick={oncancel} disabled={busy}>Cancel</button>
+ <button class="btn" bind:this={cancelBtn} onclick={oncancel} disabled={busy}>{cancelLabel}</button>
<button
class="btn {tone === 'danger' ? 'btn-danger' : 'btn-primary'}"
onclick={onconfirm}
diff --git a/frontend/src/components/EntityDetails.svelte b/frontend/src/components/EntityDetails.svelte
index 52a853b..e14ea30 100644
--- a/frontend/src/components/EntityDetails.svelte
+++ b/frontend/src/components/EntityDetails.svelte
@@ -865,8 +865,8 @@
<label class="modal-label" for="ed-notes">Notes</label>
<textarea id="ed-notes" class="textarea" rows="3" dir="auto" bind:value={infoNotes} placeholder="Add observations, links, context…"></textarea>
- <span class="modal-label">Folder (My work)</span>
- <FolderSelect bind:value={infoFolder} folders={allFolders} emptyLabel="None" />
+ <span class="modal-label">Folder</span>
+ <FolderSelect bind:value={infoFolder} folders={allFolders} emptyLabel="Unfiled" />
{/if}
{#if tab === 'connections'}
diff --git a/frontend/src/components/Icon.svelte b/frontend/src/components/Icon.svelte
index 4e39eeb..c6aae7a 100644
--- a/frontend/src/components/Icon.svelte
+++ b/frontend/src/components/Icon.svelte
@@ -161,6 +161,8 @@
// press means "what is this tab", not "open a document".
help: 'M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18ZM9.1 9.6a2.9 2.9 0 1 1 4.2 2.6c-.8.4-1.3 1-1.3 1.9v.4M12 16.3a.8.8 0 1 0 0 1.6.8.8 0 1 0 0-1.6Z',
keyboard: 'M3 7h18a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V8a1 1 0 0 1 1-1Zm3.5 3.2h.01m3.2 0h.01m3.2 0h.01m3.2 0h.01M8 13.8h8',
+ // The Enter key drawn on a keycap: the arrow every keyboard prints on it.
+ enter: 'M19 5v6a3 3 0 0 1-3 3H5m0 0 4-4m-4 4 4 4',
};
</script>
diff --git a/frontend/src/components/MediaPreview.svelte b/frontend/src/components/MediaPreview.svelte
index fb2e5fb..74adcfa 100644
--- a/frontend/src/components/MediaPreview.svelte
+++ b/frontend/src/components/MediaPreview.svelte
@@ -32,7 +32,7 @@
let large = $state(false);
const self = {};
- $effect(() => (large ? joinOverlays(self) : undefined));
+ $effect(() => (large ? joinOverlays(self, () => (large = false)) : undefined));
function onkeydown(event) {
if (large && event.key === 'Escape' && isTopOverlay(self)) {
event.preventDefault();
diff --git a/frontend/src/components/Modal.svelte b/frontend/src/components/Modal.svelte
index 25a6e3f..cecf77f 100644
--- a/frontend/src/components/Modal.svelte
+++ b/frontend/src/components/Modal.svelte
@@ -3,10 +3,13 @@
import { portal } from '../lib/fullscreen.js';
import { isTopOverlay, joinOverlays } from '../lib/overlayStack.js';
- let { title, onclose, width = '440px', children } = $props();
+ // `align="top"` hangs the dialog from the top so a list that grows and shrinks
+ // under a field does not move the field; `bare` drops the header for a dialog
+ // whose own first row says what it is, and the title stays its accessible name.
+ let { title, onclose, width = '440px', align = 'center', bare = false, children } = $props();
const self = {};
- $effect(() => joinOverlays(self));
+ $effect(() => joinOverlays(self, () => onclose?.()));
let dialogEl = $state(null);
@@ -49,19 +52,22 @@
<div
class="overlay"
+ class:top={align === 'top'}
use:portal
onclick={(e) => e.target === e.currentTarget && onclose?.()}
role="presentation"
>
<div class="modal" style:width role="dialog" aria-modal="true" aria-label={title} tabindex="-1"
bind:this={dialogEl} onkeydown={trap}>
- <header>
- <h3>{title}</h3>
- <button class="btn btn-ghost btn-sm" onclick={onclose} aria-label="Close" title="Close">
- <Icon name="x" size={15} />
- </button>
- </header>
- <div class="content">
+ {#if !bare}
+ <header>
+ <h3>{title}</h3>
+ <button class="btn btn-ghost btn-sm" onclick={onclose} aria-label="Close" title="Close">
+ <Icon name="x" size={15} />
+ </button>
+ </header>
+ {/if}
+ <div class="content" class:bare>
{@render children?.()}
</div>
</div>
@@ -104,4 +110,26 @@
padding: 4px 18px 18px;
overflow: auto;
}
+ .content.bare {
+ display: flex;
+ flex-direction: column;
+ min-height: 0;
+ padding: 0;
+ overflow: hidden;
+ }
+ .overlay.top {
+ align-items: flex-start;
+ padding-top: min(14vh, 120px);
+ }
+ .overlay.top .modal {
+ max-height: calc(100dvh - min(14vh, 120px) - 24px);
+ overflow: hidden;
+ animation: drop 140ms var(--ease);
+ }
+ @keyframes drop {
+ from { opacity: 0; transform: translateY(-6px) scale(0.985); }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .overlay.top .modal { animation: none; }
+ }
</style>
diff --git a/frontend/src/components/NoteBar.svelte b/frontend/src/components/NoteBar.svelte
index 7b9850e..9febffe 100644
--- a/frontend/src/components/NoteBar.svelte
+++ b/frontend/src/components/NoteBar.svelte
@@ -72,7 +72,7 @@
// Over the tool's own overlays too (a file's Details, the lightbox), since that is
// where a file is watched; so it takes its turn in the Escape order like a modal.
const self = {};
- $effect(() => (uiState.noting ? joinOverlays(self) : undefined));
+ $effect(() => (uiState.noting ? joinOverlays(self, close) : undefined));
function onkeydown(event) {
if (event.key !== 'Escape' || event.defaultPrevented || !isTopOverlay(self)) return;
diff --git a/frontend/src/components/PasteDialog.render.test.js b/frontend/src/components/PasteDialog.render.test.js
index 1551a32..3456761 100644
--- a/frontend/src/components/PasteDialog.render.test.js
+++ b/frontend/src/components/PasteDialog.render.test.js
@@ -78,13 +78,13 @@ describe('a pasted image', () => {
it('offers a folder in Files and nowhere else', () => {
const filed = open(resolvePaste('files', payload()), { folders: ['Sources'] });
- expect(labels(filed)).toContain('Folder (in My work)');
+ expect(labels(filed)).toContain('Folder');
unmount(live);
live = null;
document.body.innerHTML = '';
const drawn = open(resolvePaste('graph', payload()));
- expect(labels(drawn)).not.toContain('Folder (in My work)');
+ expect(labels(drawn)).not.toContain('Folder');
});
it('files with no title, since a stamped name is the honest default', () => {
@@ -128,7 +128,7 @@ describe('a pasted link', () => {
it('shows the address and asks what a bookmark needs', () => {
const root = open(resolvePaste('files', payload));
expect(root.querySelector('.target')?.textContent).toContain('leak.example.com/thread/1');
- expect(labels(root)).toEqual(['Title', 'Folder (in My work)', 'Notes']);
+ expect(labels(root)).toEqual(['Title', 'Folder', 'Notes']);
// no source field: the link is the source
expect(root.querySelector('#paste-source')).toBeNull();
});
diff --git a/frontend/src/components/PasteDialog.svelte b/frontend/src/components/PasteDialog.svelte
index ba76451..527a75d 100644
--- a/frontend/src/components/PasteDialog.svelte
+++ b/frontend/src/components/PasteDialog.svelte
@@ -97,8 +97,8 @@
{/if}
{#if asks('folder')}
- <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
- <FolderSelect bind:value={values.folder} {folders} emptyLabel="My work (root)" fresh />
+ <span class="modal-label" style="margin-top:10px">Folder</span>
+ <FolderSelect bind:value={values.folder} {folders} emptyLabel="Unfiled" fresh />
{/if}
{#if asks('source')}
diff --git a/frontend/src/components/ProposalReview.svelte b/frontend/src/components/ProposalReview.svelte
index ced3b82..0a75978 100644
--- a/frontend/src/components/ProposalReview.svelte
+++ b/frontend/src/components/ProposalReview.svelte
@@ -42,7 +42,7 @@
// Escape closes it like every other panel, and only when nothing sits above it.
const self = {};
- $effect(() => (open ? joinOverlays(self) : undefined));
+ $effect(() => (open ? joinOverlays(self, () => (open = false)) : undefined));
function onkeydown(e) {
if (open && e.key === 'Escape' && isTopOverlay(self)) open = false;
}
diff --git a/frontend/src/lib/analysisViews.test.js b/frontend/src/lib/analysisViews.test.js
index 0237bd9..e360a7d 100644
--- a/frontend/src/lib/analysisViews.test.js
+++ b/frontend/src/lib/analysisViews.test.js
@@ -1,3 +1,6 @@
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { join } from 'node:path';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import {
copyName,
@@ -109,6 +112,26 @@ describe('dating a saved reading', () => {
expect(timeAgo('2025-12-24T23:00:00Z', now)).toBe('24 Dec 2025');
});
+ // The UI is English. A date or a number formatted in the browser's own language
+ // read "14 juil. 2026" on a Collage card and "10 000 rows" in a Sheet warning,
+ // amid English words.
+ it('is the only kind of date the UI writes: none follows the system language', () => {
+ const root = fileURLToPath(new URL('..', import.meta.url));
+ const offenders = [];
+ const walk = (dir) => {
+ for (const name of readdirSync(dir)) {
+ const path = join(dir, name);
+ if (statSync(path).isDirectory()) walk(path);
+ else if (/\.(svelte|js)$/.test(name) && !name.endsWith('.test.js')) {
+ const source = readFileSync(path, 'utf8');
+ if (/\.toLocale(Date|Time)?String\((\)|undefined)/.test(source)) offenders.push(path.slice(root.length));
+ }
+ }
+ };
+ walk(root);
+ expect(offenders).toEqual([]);
+ });
+
it('says nothing about a stamp it cannot read', () => {
expect(timeAgo('', now)).toBe('');
expect(timeAgo('not a date', now)).toBe('');
diff --git a/frontend/src/lib/backButton.js b/frontend/src/lib/backButton.js
new file mode 100644
index 0000000..1933ca9
--- /dev/null
+++ b/frontend/src/lib/backButton.js
@@ -0,0 +1,226 @@
+/**
+ * The browser's Back and Forward, across the tools and inside the ones that have
+ * somewhere to be.
+ *
+ * The address reads `#<tool>?<the tool's place>` (lib/hash.js). Changing tool adds
+ * an entry, and so does a move a tool calls a navigation: a folder opened in Files, a
+ * sheet opened from the Sheet home, a proof, a draft or a note opened. Every other
+ * change of place rewrites the entry it is on (a save naming the document, a rename,
+ * a case switch resetting the tool), so Back only walks through places the analyst
+ * chose to go to.
+ *
+ * Going back never costs work. Tools stay mounted, so a tool reached by Back is as it
+ * was left. A tool asked to leave a document with unsaved changes asks first and
+ * answers whether it moved; when it stays, the address is put back on it. Back on an
+ * open dialog closes that dialog, as Escape would, and goes nowhere else. And when Back
+ * would leave Azimut altogether, the browser asks while a tool holds unsaved work.
+ *
+ * An entry remembers the case it was made in. Back into another case's entry changes
+ * the tool and nothing inside it, since switching cases is not something Back does.
+ */
+import { caseState, uiState } from './state.svelte.js';
+import { buildHash, splitHash } from './hash.js';
+import { toolFromHash } from './workspaces.js';
+import { closeTopOverlay } from './overlayStack.js';
+
+/** tool → its place, as address parameters */
+const places = new Map();
+/** tool → (params) => boolean | Promise<boolean>: go there, and say whether it went */
+const returns = new Map();
+/** tool → () => boolean: whether it holds work a page unload would lose */
+const holds = new Map();
+/** tool → how many Back or Forward moves are being applied to it */
+const restoring = new Map();
+/** tool → the place a Back or Forward reached before that tool had loaded */
+const waiting = new Map();
+/** The tool a switch just opened an entry for, with nothing pressed since. The
+ * navigation that follows (a sidebar row opening a proof) is that same move. */
+let fresh = null;
+let pops = 0;
+let toolIds = [];
+
+const caseNow = () => caseState.current?.id ?? null;
+const stamp = () => ({ azimut: 1, case: caseNow() });
+
+/** Parameters with the empty ones dropped, as strings, in the order the tool wrote them. */
+function written(params) {
+ const entries = params instanceof URLSearchParams ? [...params] : Object.entries(params ?? {});
+ return entries
+ .filter(([, value]) => value !== null && value !== undefined && value !== '')
+ .map(([name, value]) => [name, String(value)]);
+}
+
+const sameParams = (a, b) => {
+ const sorted = (params) => JSON.stringify(written(params).sort(([x], [y]) => (x < y ? -1 : x > y ? 1 : 0)));
+ return sorted(a) === sorted(b);
+};
+
+const addressOf = (tool) => buildHash(tool, places.get(tool));
+
+function showing(tool, params) {
+ const here = splitHash(location.hash);
+ return here.route === tool && sameParams(here.params, params);
+}
+
+/**
+ * Where a tool is now. A tool calls it whenever its place changes, from an effect, and
+ * again with `navigate` right where the analyst moves it somewhere (in the same
+ * synchronous block as the change, before that effect runs). Only the navigation adds
+ * an entry; anything else rewrites the current one.
+ */
+export function settlePlace(tool, params, { navigate = false } = {}) {
+ places.set(tool, Object.fromEntries(written(params)));
+ if (uiState.tool !== tool) return;
+ // The switch to this tool has not written its entry yet; it will, from `places`.
+ if (splitHash(location.hash).route !== tool) return;
+ if (showing(tool, params)) return;
+ // A move made while Back or Forward is being applied is that move, not a new one.
+ const step = navigate && !restoring.get(tool);
+ const sameCase = history.state?.azimut && history.state.case === caseNow();
+ if (step && sameCase && fresh !== tool) history.pushState(stamp(), '', addressOf(tool));
+ else history.replaceState(stamp(), '', addressOf(tool));
+ if (step) fresh = null;
+}
+
+/**
+ * The tool on screen changed. A switch is an entry, except the first one (the app
+ * settling on where it opened) and in a tab that is one tool on its own. A Back or a
+ * link that already names the tool leaves the address as it is.
+ */
+export function showTool(tool, { first = false, solo = false } = {}) {
+ if (splitHash(location.hash).route === tool) return;
+ if (first || solo) {
+ history.replaceState(stamp(), '', addressOf(tool));
+ return;
+ }
+ history.pushState(stamp(), '', addressOf(tool));
+ fresh = tool;
+}
+
+/** A case opened, or the first one loaded: the entry on screen now belongs to it. */
+export function caseShown() {
+ history.replaceState(stamp(), '', location.href);
+}
+
+/** How a tool goes back to a place it was at. Returns the way to stop listening. */
+export function onBackForward(tool, apply) {
+ returns.set(tool, apply);
+ if (waiting.has(tool)) {
+ const params = waiting.get(tool);
+ waiting.delete(tool);
+ const pop = pops;
+ // After the tool's own first effects, which would otherwise reset what this sets.
+ queueMicrotask(async () => {
+ const moved = await goBackTo(tool, apply, params);
+ if (pop === pops) settleAddress(tool, moved);
+ });
+ }
+ return () => {
+ if (returns.get(tool) === apply) returns.delete(tool);
+ };
+}
+
+/** Work a page unload would lose. Returns the way to stop declaring it. */
+export function holdsUnsaved(tool, check) {
+ holds.set(tool, check);
+ return () => {
+ if (holds.get(tool) === check) holds.delete(tool);
+ };
+}
+
+export function anyUnsaved() {
+ for (const check of holds.values()) {
+ try {
+ if (check()) return true;
+ } catch {
+ /* a tool that cannot answer holds nothing to ask about */
+ }
+ }
+ return false;
+}
+
+async function goBackTo(tool, apply, params) {
+ restoring.set(tool, (restoring.get(tool) ?? 0) + 1);
+ try {
+ return (await apply(params)) !== false;
+ } catch {
+ return true;
+ } finally {
+ const left = (restoring.get(tool) ?? 1) - 1;
+ if (left) restoring.set(tool, left);
+ else restoring.delete(tool);
+ }
+}
+
+/** The address names where the tool really is. A tool that stayed (it held unsaved
+ * work and the analyst kept it) gets an entry of its own again, so the one Back left
+ * is still there to come back to. */
+function settleAddress(tool, moved) {
+ if (uiState.tool !== tool || !places.has(tool)) return;
+ if (showing(tool, places.get(tool))) return;
+ if (moved) history.replaceState(stamp(), '', addressOf(tool));
+ else history.pushState(stamp(), '', addressOf(tool));
+}
+
+async function onPop(event) {
+ fresh = null;
+ const pop = ++pops;
+ // Back on an open dialog closes it, as Escape would, and the tool stays where it
+ // is: a dialog left open over the next tool would answer for the wrong one. The
+ // entry Back reached stays behind this one, to go to once the dialog is gone. An
+ // address typed or followed from a link (an entry Azimut did not write) closes the
+ // dialog too, and then goes where it says.
+ const ours = Boolean(event.state?.azimut);
+ if (closeTopOverlay() && ours) {
+ const here = places.has(uiState.tool) ? addressOf(uiState.tool) : buildHash(uiState.tool);
+ history.pushState(stamp(), '', here);
+ return;
+ }
+ const tool = toolFromHash(location.hash, toolIds);
+ if (!tool) return;
+ if (uiState.tool !== tool) uiState.tool = tool;
+ const params = Object.fromEntries(splitHash(location.hash).params);
+ const sameCase = ours && event.state.case === caseNow();
+ let moved = true;
+ if (sameCase) {
+ const apply = returns.get(tool);
+ if (!apply) {
+ waiting.set(tool, params);
+ return;
+ }
+ moved = await goBackTo(tool, apply, params);
+ }
+ if (pop === pops) settleAddress(tool, moved);
+}
+
+function onBeforeUnload(event) {
+ if (!anyUnsaved()) return;
+ event.preventDefault();
+ // The older half of the same request, which some browsers still read.
+ event.returnValue = '';
+}
+
+const pressed = () => {
+ fresh = null;
+};
+
+/** Listen for Back, Forward and leaving the page. Returns the way to stop. */
+export function installBackButton(ids) {
+ toolIds = ids;
+ window.addEventListener('popstate', onPop);
+ window.addEventListener('beforeunload', onBeforeUnload);
+ window.addEventListener('pointerdown', pressed, true);
+ window.addEventListener('keydown', pressed, true);
+ return () => {
+ window.removeEventListener('popstate', onPop);
+ window.removeEventListener('beforeunload', onBeforeUnload);
+ window.removeEventListener('pointerdown', pressed, true);
+ window.removeEventListener('keydown', pressed, true);
+ places.clear();
+ returns.clear();
+ holds.clear();
+ restoring.clear();
+ waiting.clear();
+ fresh = null;
+ };
+}
diff --git a/frontend/src/lib/backButton.test.js b/frontend/src/lib/backButton.test.js
new file mode 100644
index 0000000..752a3af
--- /dev/null
+++ b/frontend/src/lib/backButton.test.js
@@ -0,0 +1,276 @@
+// @vitest-environment happy-dom
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+import { caseState, uiState } from './state.svelte.js';
+import { joinOverlays } from './overlayStack.js';
+import {
+ anyUnsaved, caseShown, holdsUnsaved, installBackButton, onBackForward, settlePlace, showTool,
+} from './backButton.js';
+
+const TOOLS = ['overview', 'files', 'sheet', 'proof', 'satellite'];
+let uninstall;
+let push;
+let replace;
+
+/** Where the browser is, the way Back would leave it: an address and the state the
+ * entry was written with. */
+function backTo(hash, state) {
+ history.replaceState(state, '', hash);
+ window.dispatchEvent(new PopStateEvent('popstate', { state }));
+}
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+const entry = (caseId = 'c1') => ({ azimut: 1, case: caseId });
+
+beforeEach(() => {
+ caseState.current = { id: 'c1' };
+ uiState.tool = 'overview';
+ history.replaceState(null, '', '#overview');
+ uninstall = installBackButton(TOOLS);
+ push = vi.spyOn(history, 'pushState');
+ replace = vi.spyOn(history, 'replaceState');
+});
+
+afterEach(() => {
+ uninstall();
+ vi.restoreAllMocks();
+});
+
+describe('changing tool', () => {
+ it('is an entry Back returns to', () => {
+ uiState.tool = 'files';
+ showTool('files');
+ expect(push).toHaveBeenCalledWith(entry(), '', '#files');
+ expect(location.hash).toBe('#files');
+ });
+
+ it('only settles the address when the app opens, or in a tab that is one tool', () => {
+ showTool('files', { first: true });
+ showTool('proof', { solo: true });
+ expect(push).not.toHaveBeenCalled();
+ expect(location.hash).toBe('#proof');
+ });
+
+ it('writes nothing when Back or a link already names the tool', () => {
+ showTool('overview');
+ expect(push).not.toHaveBeenCalled();
+ expect(replace).not.toHaveBeenCalled();
+ });
+
+ it('carries the place the tool was left at', () => {
+ settlePlace('files', { folder: 'Sources/Telegram' });
+ showTool('files');
+ expect(location.hash).toBe('#files?folder=Sources%2FTelegram');
+ });
+});
+
+describe('a place inside a tool', () => {
+ beforeEach(() => {
+ uiState.tool = 'files';
+ history.replaceState(entry(), '', '#files');
+ replace.mockClear();
+ });
+
+ it('is an entry when the analyst goes there, and rewrites the entry otherwise', () => {
+ window.dispatchEvent(new Event('pointerdown'));
+ settlePlace('files', { folder: 'A' }, { navigate: true });
+ expect(push).toHaveBeenCalledTimes(1);
+ settlePlace('files', { folder: 'A renamed' });
+ expect(push).toHaveBeenCalledTimes(1);
+ expect(location.hash).toBe('#files?folder=A+renamed');
+ });
+
+ it('writes nothing when it is already the address', () => {
+ settlePlace('files', { folder: '' });
+ settlePlace('files', {}, { navigate: true });
+ expect(push).not.toHaveBeenCalled();
+ expect(replace).not.toHaveBeenCalled();
+ });
+
+ it('is the same move as the switch that brought the tool, when nothing was pressed between', () => {
+ uiState.tool = 'proof';
+ showTool('proof');
+ settlePlace('proof', { proof: 'convoy' }, { navigate: true });
+ expect(push).toHaveBeenCalledTimes(1);
+ expect(location.hash).toBe('#proof?proof=convoy');
+ });
+
+ it('is its own entry once the analyst pressed something after the switch', () => {
+ uiState.tool = 'proof';
+ showTool('proof');
+ window.dispatchEvent(new Event('pointerdown'));
+ settlePlace('proof', { proof: 'convoy' }, { navigate: true });
+ expect(push).toHaveBeenCalledTimes(2);
+ });
+
+ it('is never written by a tool that is not on screen', () => {
+ settlePlace('sheet', { sheet: 's1' }, { navigate: true });
+ expect(location.hash).toBe('#files');
+ });
+
+ it('never adds an entry across a case switch', () => {
+ caseState.current = { id: 'c2' };
+ window.dispatchEvent(new Event('pointerdown'));
+ settlePlace('files', { folder: 'B' }, { navigate: true });
+ expect(push).not.toHaveBeenCalled();
+ expect(history.state).toEqual(entry('c2'));
+ });
+
+ it('keeps the order the tool wrote, and ignores it when comparing', () => {
+ settlePlace('satellite', { ll: '1,2', z: '5' });
+ uiState.tool = 'satellite';
+ history.replaceState(entry(), '', '#satellite?z=5&ll=1%2C2');
+ replace.mockClear();
+ settlePlace('satellite', { ll: '1,2', z: '5' });
+ expect(replace).not.toHaveBeenCalled();
+ });
+});
+
+describe('Back and Forward', () => {
+ it('brings back the tool and the place it was at', async () => {
+ const apply = vi.fn(() => true);
+ onBackForward('files', apply);
+ backTo('#files?folder=A', entry());
+ await settle();
+ expect(uiState.tool).toBe('files');
+ expect(apply).toHaveBeenCalledWith({ folder: 'A' });
+ });
+
+ it('changes only the tool when the entry belongs to another case', async () => {
+ const apply = vi.fn(() => true);
+ onBackForward('files', apply);
+ backTo('#files?folder=A', entry('other'));
+ await settle();
+ expect(uiState.tool).toBe('files');
+ expect(apply).not.toHaveBeenCalled();
+ });
+
+ it('puts the address back on a tool that stayed, keeping the entry it came from', async () => {
+ uiState.tool = 'proof';
+ settlePlace('proof', { proof: 'edited' });
+ onBackForward('proof', () => false);
+ backTo('#proof?proof=older', entry());
+ await settle();
+ expect(push).toHaveBeenLastCalledWith(entry(), '', '#proof?proof=edited');
+ });
+
+ it('names where the tool landed when it could not go exactly there', async () => {
+ uiState.tool = 'files';
+ onBackForward('files', () => {
+ settlePlace('files', { folder: 'Parent' }, { navigate: true });
+ return true;
+ });
+ backTo('#files?folder=Parent%2FGone', entry());
+ await settle();
+ expect(push).not.toHaveBeenCalled();
+ expect(location.hash).toBe('#files?folder=Parent');
+ });
+
+ it('waits for a tool that has not loaded yet', async () => {
+ backTo('#sheet?sheet=s1', entry());
+ await settle();
+ expect(uiState.tool).toBe('sheet');
+ const apply = vi.fn(() => true);
+ onBackForward('sheet', apply);
+ await settle();
+ expect(apply).toHaveBeenCalledWith({ sheet: 's1' });
+ });
+
+ it('lets a later Back overtake one still waiting on an answer', async () => {
+ uiState.tool = 'proof';
+ settlePlace('proof', { proof: 'current' });
+ let answer;
+ onBackForward('proof', (to) => (to.proof === 'first' ? new Promise((r) => (answer = r)) : true));
+ backTo('#proof?proof=first', entry());
+ await settle();
+ backTo('#proof', entry());
+ await settle();
+ answer(false);
+ await settle();
+ expect(push).not.toHaveBeenCalled();
+ });
+
+ it('ends the switch a move would have joined: a folder opened after Forward is a step', async () => {
+ uiState.tool = 'proof';
+ history.replaceState(entry(), '', '#proof');
+ uiState.tool = 'files';
+ showTool('files');
+ backTo('#proof', entry());
+ backTo('#files', entry());
+ await settle();
+ settlePlace('files', { folder: 'A' }, { navigate: true });
+ expect(push).toHaveBeenCalledTimes(2);
+ });
+});
+
+describe('Back on an open dialog', () => {
+ it('closes the dialog, as Escape would, and keeps the tool where it is', async () => {
+ uiState.tool = 'proof';
+ settlePlace('proof', { proof: 'convoy' });
+ history.replaceState(entry(), '', '#proof?proof=convoy');
+ const apply = vi.fn(() => true);
+ onBackForward('proof', apply);
+ const close = vi.fn();
+ const leave = joinOverlays({}, close);
+ backTo('#files', entry());
+ await settle();
+ leave();
+ expect(close).toHaveBeenCalledTimes(1);
+ expect(uiState.tool).toBe('proof');
+ expect(apply).not.toHaveBeenCalled();
+ expect(push).toHaveBeenLastCalledWith(entry(), '', '#proof?proof=convoy');
+ });
+});
+
+describe('an address typed or followed from a link', () => {
+ it('closes an open dialog and goes where it says', async () => {
+ uiState.tool = 'settings';
+ history.replaceState(entry(), '', '#settings');
+ const close = vi.fn();
+ const leave = joinOverlays({}, close);
+ backTo('#files', null);
+ await settle();
+ leave();
+ expect(close).toHaveBeenCalledTimes(1);
+ expect(uiState.tool).toBe('files');
+ expect(push).not.toHaveBeenCalled();
+ });
+});
+
+describe('a case opened', () => {
+ it('makes the entry on screen belong to it', () => {
+ history.replaceState(entry('c1'), '', '#files');
+ caseState.current = { id: 'c2' };
+ caseShown();
+ expect(history.state).toEqual(entry('c2'));
+ expect(location.hash).toBe('#files');
+ });
+});
+
+describe('leaving Azimut', () => {
+ const unload = () => {
+ const event = new Event('beforeunload', { cancelable: true });
+ window.dispatchEvent(event);
+ return event;
+ };
+
+ it('asks while a tool holds unsaved work', () => {
+ let dirty = true;
+ holdsUnsaved('proof', () => dirty);
+ expect(anyUnsaved()).toBe(true);
+ expect(unload().defaultPrevented).toBe(true);
+ dirty = false;
+ expect(unload().defaultPrevented).toBe(false);
+ });
+
+ it('lets go once the tool stops declaring it', () => {
+ const stop = holdsUnsaved('post', () => true);
+ stop();
+ expect(anyUnsaved()).toBe(false);
+ });
+
+ it('does not let a tool that cannot answer hold the page', () => {
+ holdsUnsaved('sheet', () => {
+ throw new Error('gone');
+ });
+ expect(anyUnsaved()).toBe(false);
+ });
+});
diff --git a/frontend/src/lib/commandPalette.js b/frontend/src/lib/commandPalette.js
new file mode 100644
index 0000000..29862b4
--- /dev/null
+++ b/frontend/src/lib/commandPalette.js
@@ -0,0 +1,65 @@
+import { foldTerms, foldText } from './textFold.js';
+import { workspaceOf } from './workspaces.js';
+
+export function isPaletteKey(event) {
+ return Boolean(
+ (event.ctrlKey || event.metaKey) && !event.altKey && !event.shiftKey &&
+ !event.repeat && !event.isComposing && !event.defaultPrevented &&
+ event.key?.toLowerCase() === 'k'
+ );
+}
+
+/**
+ * `label` cut into runs, each marked with whether a search term matched it.
+ *
+ * Folded one character at a time so a match found in folded text points back at the
+ * characters the analyst sees. Where that per-character fold differs from folding the
+ * whole label (a mark that belongs to its letter), nothing is marked rather than the
+ * wrong letters.
+ */
+export function matchRuns(label, query) {
+ const text = String(label ?? '');
+ const terms = foldTerms(query);
+ if (!terms.length || !text) return [{ text, hit: false }];
+ const chars = [...text];
+ const owner = [];
+ let folded = '';
+ chars.forEach((char, index) => {
+ const part = foldText(char);
+ folded += part;
+ for (let unit = 0; unit < part.length; unit += 1) owner.push(index);
+ });
+ if (folded !== foldText(text)) return [{ text, hit: false }];
+ const hits = new Array(chars.length).fill(false);
+ for (const term of terms) {
+ for (let at = folded.indexOf(term); at !== -1; at = folded.indexOf(term, at + term.length)) {
+ for (let unit = at; unit < at + term.length; unit += 1) hits[owner[unit]] = true;
+ }
+ }
+ const runs = [];
+ chars.forEach((char, index) => {
+ const last = runs[runs.length - 1];
+ if (last && last.hit === hits[index]) last.text += char;
+ else runs.push({ text: char, hit: hits[index] });
+ });
+ return runs;
+}
+
+/** Find tools by their displayed name, workspace or stable id. */
+export function paletteTools(tools, query) {
+ const terms = foldTerms(query);
+ return tools.map(({ id, label }) => {
+ const workspace = workspaceOf(id);
+ return {
+ kind: 'tool', id, label,
+ detail: workspace?.label ?? label,
+ icon: workspace?.icon ?? 'settings',
+ };
+ }).filter((row) => {
+ const text = foldText(`${row.label} ${row.detail} ${row.id}`);
+ return terms.every((term) => text.includes(term));
+ }).sort((a, b) => {
+ const queryText = foldText(query.trim());
+ return Number(foldText(b.label).startsWith(queryText)) - Number(foldText(a.label).startsWith(queryText));
+ });
+}
diff --git a/frontend/src/lib/commandPalette.test.js b/frontend/src/lib/commandPalette.test.js
new file mode 100644
index 0000000..9b055cf
--- /dev/null
+++ b/frontend/src/lib/commandPalette.test.js
@@ -0,0 +1,59 @@
+import { describe, expect, it } from 'vitest';
+import { isPaletteKey, matchRuns, paletteTools } from './commandPalette.js';
+
+describe('the palette shortcut', () => {
+ it('opens with Control or Command, including from a text field', () => {
+ expect(isPaletteKey({ key: 'k', ctrlKey: true, target: { tagName: 'INPUT' } })).toBe(true);
+ expect(isPaletteKey({ key: 'k', metaKey: true })).toBe(true);
+ });
+
+ it('leaves composition, held keys and other shortcuts alone', () => {
+ for (const extra of [{ isComposing: true }, { repeat: true }, { altKey: true }, { shiftKey: true }, { defaultPrevented: true }]) {
+ expect(isPaletteKey({ key: 'k', ctrlKey: true, ...extra })).toBe(false);
+ }
+ expect(isPaletteKey({ key: 'k' })).toBe(false);
+ expect(isPaletteKey({ key: 'n', ctrlKey: true })).toBe(false);
+ });
+});
+
+describe('matched runs', () => {
+ const marked = (runs) => runs.filter((run) => run.hit).map((run) => run.text);
+
+ it('marks every term where the label holds it, whatever the case', () => {
+ expect(matchRuns('Port Sudan quay', 'port QUAY')).toEqual([
+ { text: 'Port', hit: true }, { text: ' Sudan ', hit: false }, { text: 'quay', hit: true },
+ ]);
+ expect(marked(matchRuns('Geo Proof', 'o'))).toEqual(['o', 'oo']);
+ });
+
+ it('points a folded match back at the accented letters', () => {
+ expect(marked(matchRuns('Étude de Straße', 'etude strasse'))).toEqual(['Étude', 'Straße']);
+ });
+
+ it('leaves the label whole without a query or a match', () => {
+ expect(matchRuns('Harbour', ' ')).toEqual([{ text: 'Harbour', hit: false }]);
+ expect(matchRuns('Harbour', 'airfield')).toEqual([{ text: 'Harbour', hit: false }]);
+ expect(matchRuns('', 'a')).toEqual([{ text: '', hit: false }]);
+ });
+});
+
+describe('tool search', () => {
+ const tools = [
+ { id: 'satellite', label: 'Satellite' },
+ { id: 'compare', label: 'Compare' },
+ { id: 'proof', label: 'Geo Proof' },
+ { id: 'settings', label: 'Settings' },
+ ];
+
+ it('finds a workspace as well as an individual tool, with folded text', () => {
+ expect(paletteTools(tools, 'MÁP').map((row) => row.id)).toEqual(['satellite', 'compare']);
+ expect(paletteTools(tools, 'compose proof').map((row) => row.id)).toEqual(['proof']);
+ expect(paletteTools(tools, 'satellite').map((row) => row.label)).toEqual(['Satellite']);
+ });
+
+ it('includes Settings and ranks a named tool before workspace matches', () => {
+ expect(paletteTools(tools, '').map((row) => row.id)).toEqual(tools.map((tool) => tool.id));
+ expect(paletteTools(tools, 'settings')[0]).toMatchObject({ label: 'Settings', icon: 'settings' });
+ expect(paletteTools([{ id: 'proof', label: 'Geo Proof' }, { id: 'notebook', label: 'Compose notes' }], 'compose')[0].id).toBe('notebook');
+ });
+});
diff --git a/frontend/src/lib/entityFilter.js b/frontend/src/lib/entityFilter.js
index 9c0d51c..42654d3 100644
--- a/frontend/src/lib/entityFilter.js
+++ b/frontend/src/lib/entityFilter.js
@@ -104,7 +104,8 @@ export const QUESTIONS = [
id: 'unfiled',
label: 'Unfiled',
hint: 'in none of your folders',
- terms: { unfiled: true },
+ // Accepted rows, as the sidebar's Unfiled lists them: a suggestion is To review.
+ terms: { unfiled: true, status: 'confirmed' },
},
{
id: 'unsourced',
diff --git a/frontend/src/lib/entityFilter.test.js b/frontend/src/lib/entityFilter.test.js
index a1fe32a..58f8d79 100644
--- a/frontend/src/lib/entityFilter.test.js
+++ b/frontend/src/lib/entityFilter.test.js
@@ -80,10 +80,16 @@ describe('the questions every case is asked', () => {
for (const question of QUESTIONS) {
const asked = askQuestion(emptyFilter(), question.id);
expect(isFiltering(asked)).toBe(true);
- expect(chipsOf(asked).length).toBe(1);
+ expect(chipsOf(asked).length).toBe(Object.keys(question.terms).length);
}
});
+ it('asks Unfiled of accepted rows, as the sidebar lists them', () => {
+ const unfiled = askQuestion(emptyFilter(), 'unfiled');
+ expect(toQuery(unfiled)).toMatchObject({ unfiled: true, status: 'confirmed' });
+ expect(chipsOf(unfiled).map((chip) => chip.text)).toEqual(['Unfiled', 'Status: Confirmed']);
+ });
+
it('asks the case for what nothing connects to, which no column reports', () => {
const loose = askQuestion(emptyFilter(), 'loose');
expect(toQuery(loose).unlinked).toBe(true);
diff --git a/frontend/src/lib/guide.js b/frontend/src/lib/guide.js
index e838d97..01ecb6e 100644
--- a/frontend/src/lib/guide.js
+++ b/frontend/src/lib/guide.js
@@ -350,6 +350,7 @@ export const GUIDE = [
{
where: 'Anywhere',
keys: [
+ { combo: 'Ctrl+K / ⌘K', does: 'opens Go to for tools, cases and documents' },
{ combo: 'Ctrl+V', does: 'files a screenshot or a copied address, on Media, Files, Board and Graph' },
{ combo: 'Escape', does: 'closes whatever is open, shallowest first' },
{ combo: 'Ctrl+Enter', does: 'adds the entry line, from any of its fields' },
diff --git a/frontend/src/lib/navigate.js b/frontend/src/lib/navigate.js
index 5987c62..d4ec934 100644
--- a/frontend/src/lib/navigate.js
+++ b/frontend/src/lib/navigate.js
@@ -158,6 +158,11 @@ export function openEntity(entity, resolved = false) {
uiState.tool = 'notebook';
return;
}
+ if (entity.type === 'sheet' && entity.id) {
+ uiState.openSheet = entity.id;
+ uiState.tool = 'sheet';
+ return;
+ }
if (entity.type === 'proof') {
const name = specName(entity.attrs?.spec);
if (name) uiState.openProof = name;
diff --git a/frontend/src/lib/navigate.test.js b/frontend/src/lib/navigate.test.js
index add0d00..8cfb5e4 100644
--- a/frontend/src/lib/navigate.test.js
+++ b/frontend/src/lib/navigate.test.js
@@ -79,6 +79,11 @@ describe('openInReverseSearch', () => {
});
describe('openEntity', () => {
+ it('reopens a sheet by its entity id in Sheet', () => {
+ openEntity({ id: 'sheet-1', type: 'sheet', label: 'Index', attrs: { path: 'sheets/index.csv' } });
+ expect(uiState.tool).toBe('sheet');
+ expect(uiState.openSheet).toBe('sheet-1');
+ });
it('opens a merged place at the survivor coordinates instead of frozen coordinates', async () => {
get.mockResolvedValue({ entity: { id: 'kept', type: 'place', label: 'Kept place', attrs: { lat: 3, lon: 4 } }, merged_from: { id: 'old', label: 'Old place' } });
openEntity({ id: 'old', type: 'place', attrs: { lat: 1, lon: 2 } });
diff --git a/frontend/src/lib/overlayStack.js b/frontend/src/lib/overlayStack.js
index 9140248..179dbde 100644
--- a/frontend/src/lib/overlayStack.js
+++ b/frontend/src/lib/overlayStack.js
@@ -13,14 +13,19 @@
// re-runs itself for good.
const stack = [];
+/** Each overlay's way out, the one Escape takes. */
+const closers = new WeakMap();
+
/**
* Join the stack, and leave it when the caller is torn down.
*
* `self` is any stable object identity; the caller keeps it and passes it back to
- * `isTopOverlay`. Returns the cleanup, so it reads as the body of an `$effect`.
+ * `isTopOverlay`. `close` is what Escape does to it, so the browser's Back can do the
+ * same (lib/backButton.js). Returns the cleanup, so it reads as the body of an `$effect`.
*/
-export function joinOverlays(self) {
+export function joinOverlays(self, close = null) {
stack.push(self);
+ if (close) closers.set(self, close);
return () => {
const at = stack.indexOf(self);
if (at !== -1) stack.splice(at, 1);
@@ -31,3 +36,14 @@ export function joinOverlays(self) {
export function isTopOverlay(self) {
return stack.at(-1) === self;
}
+
+/**
+ * Close the overlay on top, as Escape would. Answers whether one was open: one that
+ * cannot be closed this way still holds the screen, and is left as it is.
+ */
+export function closeTopOverlay() {
+ const top = stack.at(-1);
+ if (!top) return false;
+ closers.get(top)?.();
+ return true;
+}
diff --git a/frontend/src/lib/overlayStack.test.js b/frontend/src/lib/overlayStack.test.js
new file mode 100644
index 0000000..5d19ec5
--- /dev/null
+++ b/frontend/src/lib/overlayStack.test.js
@@ -0,0 +1,38 @@
+import { describe, expect, it, vi } from 'vitest';
+import { closeTopOverlay, isTopOverlay, joinOverlays } from './overlayStack.js';
+
+describe('the overlay on top', () => {
+ it('is the last one opened, and the only one a key press reaches', () => {
+ const below = {};
+ const above = {};
+ const leaveBelow = joinOverlays(below);
+ const leaveAbove = joinOverlays(above);
+ expect(isTopOverlay(above)).toBe(true);
+ expect(isTopOverlay(below)).toBe(false);
+ leaveAbove();
+ expect(isTopOverlay(below)).toBe(true);
+ leaveBelow();
+ });
+
+ it('is closed the way Escape closes it, and only that one', () => {
+ const closeBelow = vi.fn();
+ const closeAbove = vi.fn();
+ const leaveBelow = joinOverlays({}, closeBelow);
+ const leaveAbove = joinOverlays({}, closeAbove);
+ expect(closeTopOverlay()).toBe(true);
+ expect(closeAbove).toHaveBeenCalledTimes(1);
+ expect(closeBelow).not.toHaveBeenCalled();
+ leaveAbove();
+ leaveBelow();
+ });
+
+ it('says nothing was open when nothing is', () => {
+ expect(closeTopOverlay()).toBe(false);
+ });
+
+ it('still holds the screen when it has no way to be closed', () => {
+ const leave = joinOverlays({});
+ expect(closeTopOverlay()).toBe(true);
+ leave();
+ });
+});
diff --git a/frontend/src/lib/overview.js b/frontend/src/lib/overview.js
index c4cc86f..54c58de 100644
--- a/frontend/src/lib/overview.js
+++ b/frontend/src/lib/overview.js
@@ -16,19 +16,14 @@
import { QUESTIONS } from './entityFilter.js';
/**
- * How many entities sit in none of the analyst's folders.
+ * How many accepted entities sit in none of the analyst's folders.
*
- * Derived rather than asked for: `by_folder` counts the rows that *have* a folder, so
- * the rest of the case is the remainder. Clamped at zero, since a summary read while a
- * write lands can briefly count more folders than it counts rows.
+ * Accepted only, as the sidebar's and Files' Unfiled list them: a suggestion is
+ * counted once, under To review. Counted over every row, a case with three
+ * suggestions said 18 here and 15 in the sidebar beside it.
*/
export function unfiledCount(summary) {
- const total = Number(summary?.total ?? 0);
- const filed = Object.values(summary?.by_folder ?? {}).reduce(
- (sum, n) => sum + Number(n || 0),
- 0
- );
- return Math.max(0, total - filed);
+ return Math.max(0, Number(summary?.confirmed?.unfiled ?? 0));
}
/** A Board question by id, carrying its own label, hint and terms. */
diff --git a/frontend/src/lib/overview.test.js b/frontend/src/lib/overview.test.js
index 47ffcd0..2e225d1 100644
--- a/frontend/src/lib/overview.test.js
+++ b/frontend/src/lib/overview.test.js
@@ -46,7 +46,7 @@ describe('what the case is waiting on', () => {
it('reads each count off the payload that already holds it', () => {
const rows = waitingRows({
- summary: summary({ total: 30, by_status: { suggested: 4 }, unlinked: 7, by_folder: { a: 10, b: 8 } }),
+ summary: summary({ total: 30, by_status: { suggested: 4 }, unlinked: 7, confirmed: { unfiled: 12 } }),
timeline: { undated: 2 },
});
expect(Object.fromEntries(rows.map((row) => [row.id, row.count]))).toEqual({
@@ -70,17 +70,14 @@ describe('what the case is waiting on', () => {
});
describe('what sits in none of the folders', () => {
- it('is the case less what the folders hold', () => {
- expect(unfiledCount(summary({ total: 12, by_folder: { work: 5, old: 2 } }))).toBe(5);
+ it('counts accepted rows only, as the sidebar lists them', () => {
+ // three suggestions out of a folder are To review, not Unfiled as well
+ const read = summary({ total: 49, by_folder: { a: 31 }, by_status: { suggested: 3 }, confirmed: { unfiled: 15 } });
+ expect(unfiledCount(read)).toBe(15);
});
- it('is the whole case when no folder exists yet', () => {
- expect(unfiledCount(summary({ total: 12 }))).toBe(12);
- });
-
- it('never goes negative on a summary read mid-write', () => {
- // the two counts are separate scans; a folder count can briefly outrun the total
- expect(unfiledCount(summary({ total: 2, by_folder: { a: 5 } }))).toBe(0);
+ it('is zero before the server says', () => {
+ expect(unfiledCount(summary({ total: 12 }))).toBe(0);
});
it('is zero on nothing at all', () => {
diff --git a/frontend/src/lib/sheet.js b/frontend/src/lib/sheet.js
index 158d0b1..8c225e0 100644
--- a/frontend/src/lib/sheet.js
+++ b/frontend/src/lib/sheet.js
@@ -58,8 +58,8 @@ export function tooBigBy(table, { rows = 0, columns = 0 } = {}) {
if (willRows > MAX_ROWS) {
const room = Math.max(0, MAX_ROWS - (table?.rows?.length ?? 0));
return room
- ? `A sheet holds ${MAX_ROWS.toLocaleString()} rows, so there is room for ${room.toLocaleString()} more.`
- : `This sheet is full at ${MAX_ROWS.toLocaleString()} rows.`;
+ ? `A sheet holds ${MAX_ROWS.toLocaleString('en-US')} rows, so there is room for ${room.toLocaleString('en-US')} more.`
+ : `This sheet is full at ${MAX_ROWS.toLocaleString('en-US')} rows.`;
}
return null;
}
diff --git a/frontend/src/lib/state.svelte.js b/frontend/src/lib/state.svelte.js
index 8ac5fb9..1af6372 100644
--- a/frontend/src/lib/state.svelte.js
+++ b/frontend/src/lib/state.svelte.js
@@ -421,9 +421,10 @@ export async function refreshCaseList({ q } = {}) {
* the files stay in the analyst's half of the case folder.
*/
export async function adoptFolder(name) {
+ if (!(await leaveCurrentCase('create'))) return null;
const adopted = await api.post('/api/workspace/folders/adopt', { name });
await refreshCaseList();
- await openCase(adopted.id);
+ await openCase(adopted.id, { asked: true });
return adopted;
}
@@ -457,32 +458,47 @@ export function registerCaseChangeGuard(guard) {
return () => caseChangeGuards.delete(guard);
}
-async function prepareCaseChange(fromId, toId) {
+async function prepareCaseChange(fromId, toId, reason = null) {
+ const change = reason ? { fromId, toId, reason } : { fromId, toId };
for (const guard of [...caseChangeGuards]) {
- if ((await guard({ fromId, toId })) === false) return false;
+ if ((await guard(change)) === false) return false;
}
return true;
}
-export async function openCase(id) {
+/**
+ * Ask the guards before a server write that ends on another case: a new case, an
+ * adopted folder, a promoted session. Asked after, a "Keep editing" would leave the
+ * write done anyway, and a promoted session would stay open on a folder that moved.
+ */
+async function leaveCurrentCase(reason) {
+ const fromId = caseState.current?.id ?? null;
+ if (!fromId) return true;
+ return (await prepareCaseChange(fromId, null, reason)) && caseState.current?.id === fromId;
+}
+
+/** Open a case. `asked` skips the guards, for a caller that already ran them.
+ * Answers whether the case is now current. */
+export async function openCase(id, { asked = false } = {}) {
const run = ++openingCase;
caseState.loading = true;
try {
const currentId = caseState.current?.id ?? null;
if (
- currentId && currentId !== id &&
+ currentId && currentId !== id && !asked &&
!(await prepareCaseChange(currentId, id))
- ) return;
- if (run !== openingCase) return;
+ ) return false;
+ if (run !== openingCase) return false;
// Everything queued names something in the case being left behind —
// reference viewers point at its media, `openProof` at one of its files.
if (caseState.current?.id !== id) clearCaseHandoffs();
const opened = await api.get(`/api/cases/${id}`);
// Case reads can finish out of order. Only the latest choice may become current,
// or a slow first click can put its case back after a faster second one opened.
- if (run !== openingCase) return;
+ if (run !== openingCase) return false;
caseState.current = opened;
rememberCase(id);
+ return true;
} finally {
if (run === openingCase) caseState.loading = false;
}
@@ -543,10 +559,12 @@ export async function reloadCase() {
caseState.rev++;
}
+/** Create a case and open it. Answers null when the analyst kept the open one. */
export async function createCase(name) {
+ if (!(await leaveCurrentCase('create'))) return null;
const created = await api.post('/api/cases', { name });
await refreshCaseList();
- await openCase(created.id);
+ await openCase(created.id, { asked: true });
return created;
}
@@ -573,12 +591,17 @@ export async function renameCase(id, name) {
if (caseState.current?.id === id) await openCase(id);
}
+/** Keep the open scratch session as a case. Answers null when the analyst kept
+ * editing: the session is then left where it is. */
export async function promoteCase(name) {
- if (!caseState.current?.scratch) return;
- const promoted = await api.post(`/api/cases/${caseState.current.id}/promote`, { name });
+ const scratch = caseState.current;
+ if (!scratch?.scratch) return null;
+ if (!(await leaveCurrentCase('promote'))) return null;
+ const promoted = await api.post(`/api/cases/${scratch.id}/promote`, { name });
await refreshCaseList();
- await openCase(promoted.id);
+ await openCase(promoted.id, { asked: true });
toast(`Promoted to case “${name}”`, 'ok');
+ return promoted;
}
/**
diff --git a/frontend/src/lib/state.test.js b/frontend/src/lib/state.test.js
index d54747d..760eff9 100644
--- a/frontend/src/lib/state.test.js
+++ b/frontend/src/lib/state.test.js
@@ -429,6 +429,57 @@ describe('case request ownership', () => {
unregister();
});
+ // Promoting moves the scratch folder on the server. A guard asked afterwards,
+ // answered "Keep editing", left the app on a session id that no longer existed.
+ it('asks before promoting a session, and moves nothing when it is kept', async () => {
+ const guard = vi.fn().mockResolvedValue(false);
+ const unregister = state.registerCaseChangeGuard(guard);
+ state.caseState.current = { id: 'scratch_a', name: 'Scratch session', scratch: true };
+ api.post.mockReset();
+
+ expect(await state.promoteCase('Harbour')).toBeNull();
+
+ expect(guard).toHaveBeenCalledWith({ fromId: 'scratch_a', toId: null, reason: 'promote' });
+ expect(api.post).not.toHaveBeenCalled();
+ expect(state.caseState.current.id).toBe('scratch_a');
+ unregister();
+ });
+
+ it('promotes once the guards agree, without asking them twice', async () => {
+ const order = [];
+ const guard = vi.fn(async () => { order.push('guard'); return true; });
+ const unregister = state.registerCaseChangeGuard(guard);
+ state.caseState.current = { id: 'scratch_a', name: 'Scratch session', scratch: true };
+ api.post.mockReset();
+ api.post.mockImplementation(async (path) => {
+ order.push(path);
+ return { id: 'harbour' };
+ });
+ api.get.mockImplementation(async (path) =>
+ path === '/api/cases/harbour' ? { id: 'harbour', name: 'Harbour' } : []
+ );
+
+ expect(await state.promoteCase('Harbour')).toEqual({ id: 'harbour' });
+
+ expect(order).toEqual(['guard', '/api/cases/scratch_a/promote']);
+ expect(guard).toHaveBeenCalledTimes(1);
+ expect(state.caseState.current.id).toBe('harbour');
+ unregister();
+ });
+
+ it('creates no case when the analyst keeps the open one', async () => {
+ const unregister = state.registerCaseChangeGuard(async () => false);
+ state.caseState.current = { id: 'case-a', name: 'Case A' };
+ api.post.mockReset();
+
+ expect(await state.createCase('Harbour')).toBeNull();
+ expect(await state.adoptFolder('Harbour')).toBeNull();
+
+ expect(api.post).not.toHaveBeenCalled();
+ expect(state.caseState.current.id).toBe('case-a');
+ unregister();
+ });
+
it('does not let a late refresh reopen the case it started in', async () => {
const refresh = deferred();
api.get.mockReturnValue(refresh.promise);
diff --git a/frontend/src/tools/Collage.svelte b/frontend/src/tools/Collage.svelte
index 71989f9..c7bcf9f 100644
--- a/frontend/src/tools/Collage.svelte
+++ b/frontend/src/tools/Collage.svelte
@@ -14,6 +14,7 @@
import { deletedToast } from '../lib/trash.js';
import { renderCollageThumb } from '../lib/collageThumb.js';
import { foldTerms, foldText } from '../lib/textFold.js';
+ import { timeAgo } from '../lib/analysisViews.js';
import Icon from '../components/Icon.svelte';
import Modal from '../components/Modal.svelte';
import ConfirmDialog from '../components/ConfirmDialog.svelte';
@@ -649,12 +650,6 @@
toast(e.message, 'danger');
}
}
-
- function when(stamp) {
- if (!stamp) return '';
- const d = new Date(stamp);
- return Number.isNaN(d.getTime()) ? '' : d.toLocaleDateString(undefined, { day: 'numeric', month: 'short', year: 'numeric' });
- }
</script>
<svelte:window onkeydown={onWindowKeydown} {onpagehide} />
@@ -669,7 +664,7 @@
{#if collages.length}
<div class={grid ? 'cards' : 'rows'}>
{#each shownCollages as row (row.name)}
- {@const meta = `${row.pieces} piece${row.pieces === 1 ? '' : 's'}${when(row.updated_at) ? ` · ${when(row.updated_at)}` : ''}`}
+ {@const meta = `${row.pieces} piece${row.pieces === 1 ? '' : 's'}${timeAgo(row.updated_at) ? ` · ${timeAgo(row.updated_at)}` : ''}`}
{#if grid}
<div class="card" class:current={row.name === doc.name}>
<button class="card-open" onclick={() => openCollage(row.name)}>
diff --git a/frontend/src/tools/Compare.svelte b/frontend/src/tools/Compare.svelte
index 7fe44ba..2456967 100644
--- a/frontend/src/tools/Compare.svelte
+++ b/frontend/src/tools/Compare.svelte
@@ -101,6 +101,7 @@
import { WAYBACK_ID, releaseYearBefore, waybackId } from '../lib/wayback.js';
import { RADAR_ID, radarId } from '../lib/radar.js';
import { offerNote, pairOffers, withdrawNote } from '../lib/noteHere.svelte.js';
+ import { holdsUnsaved } from '../lib/backButton.js';
import { changeInterval, formatTemporalValue } from '../lib/timeline.js';
import Icon from '../components/Icon.svelte';
import Compass from '../components/Compass.svelte';
@@ -368,6 +369,8 @@
// Panning is looking, not work, so leaving asks nothing; Save still takes it.
let pristineSignature = $state(null);
const discardable = $derived(sessionDirty && pairSignature() !== pristineSignature);
+ // Leaving Azimut with them asks first, as leaving the comparison here does.
+ onDestroy(holdsUnsaved('compare', () => discardable));
let firmsSensors = $state([]);
function changeSide(target, sentinel, wayback, shown, radar) {
@@ -1009,8 +1012,8 @@
toast(`Comparison saved, but its preview could not update: ${previewError.message}`, 'warn', 7000);
} else {
toast(mode === 'blink'
- ? 'Comparison and animated preview saved to My work'
- : 'Comparison and preview saved to My work', 'ok');
+ ? 'Comparison and animated preview saved to the case'
+ : 'Comparison and preview saved to the case', 'ok');
}
if (exportAfterSave) {
exportAfterSave = false;
@@ -2363,7 +2366,7 @@
class="btn btn-primary btn-sm"
onclick={requestSaveSession}
disabled={!both || sessionBusy || !sessionDirty}
- title="Keep this editable comparison in My work"
+ title="Keep this editable comparison in the case"
>
<Icon name="save" size={13} /> {sessionBusy ? 'Saving…' : 'Save'}
</button>
diff --git a/frontend/src/tools/Files.svelte b/frontend/src/tools/Files.svelte
index f0178b6..6d93362 100644
--- a/frontend/src/tools/Files.svelte
+++ b/frontend/src/tools/Files.svelte
@@ -1,6 +1,6 @@
<script>
/**
- * Files — the desktop view of My work. The case sidebar's folder tree, opened
+ * Files — the desktop view of the case's folders. The case sidebar's folder tree, opened
* up into a Finder-style surface: navigate folders, rubber-band-select several
* items at once, and drag the lot into a folder. Reads every saved artifact
* (media, captures, notes, proofs, posts, places, sessions), not just media.
@@ -64,6 +64,7 @@
} from '../lib/trash.js';
import { createPagedList } from '../lib/pagedList.svelte.js';
import { offerNote, withdrawNote } from '../lib/noteHere.svelte.js';
+ import { onBackForward, settlePlace } from '../lib/backButton.js';
import Icon from '../components/Icon.svelte';
import SearchInput from '../components/SearchInput.svelte';
import Modal from '../components/Modal.svelte';
@@ -103,7 +104,7 @@
),
});
const confirmed = $derived(pl.items);
- let summary = $state(null); // { total, by_type, by_status, by_folder }
+ let summary = $state(null); // { total, by_type, by_status, by_folder, confirmed }
const emptyTrashState = () => ({ groups: [], items: 0, size_bytes: 0 });
let trashData = $state(emptyTrashState());
let trashRun = 0;
@@ -150,8 +151,11 @@
const allFolders = $derived(flattenPaths(tree));
const unfiled = $derived(confirmed.filter((e) => !folderOf(e)));
// Counts from the summary, which covers the whole case; the loaded page alone
- // undercounted every folder of a case past its first 200 items.
- const countOf = (node) => (summary?.by_folder ? subtreeCountFrom(node, summary.by_folder) : subtreeCount(node));
+ // undercounted every folder of a case past its first 200 items. Accepted rows only,
+ // as Files lists them: a suggestion waits in the sidebar, under review.
+ const filedCounts = $derived(summary?.confirmed?.by_folder ?? null);
+ const countOf = (node) => (filedCounts ? subtreeCountFrom(node, filedCounts) : subtreeCount(node));
+ const unfiledTotal = $derived(summary?.confirmed?.unfiled ?? unfiled.length);
const working = $derived(caseState.current?.work_folder ?? null);
// ── filters ─────────────────────────────────────────────────────────────────
@@ -162,7 +166,7 @@
let typeFilter = $state(null);
let unlinkedOnly = $state(false);
const filtering = $derived(Boolean(typeFilter || unlinkedOnly));
- const chips = $derived(typeChips(summary));
+ const chips = $derived(typeChips(summary?.confirmed));
const fl = createPagedList({
fetchPage: ({ query: serverQuery, cursor }) =>
api.get(
@@ -236,7 +240,7 @@
}
// Search stays inside the open folder and its subfolders. The root is the
- // one intentional exception: it represents all of My work.
+ // one intentional exception: it represents every file.
let query = $state('');
const searching = $derived(!!query.trim());
const total = $derived(
@@ -381,11 +385,13 @@
showUnfiled = false;
cwd = path;
if (searching && pl.serverMode) pl.reload();
+ settlePlace('files', place(), { navigate: true });
}
function openUnfiled() {
showTrash = false;
showUnfiled = true;
if (searching && pl.serverMode) pl.reload();
+ settlePlace('files', place(), { navigate: true });
}
function openTrash() {
@@ -393,7 +399,29 @@
showUnfiled = false;
cwd = '';
query = '';
- }
+ settlePlace('files', place(), { navigate: true });
+ }
+
+ // Where Files is, in the address: each folder opened is a step Back retraces. A
+ // folder renamed or removed under it only rewrites the step it is on.
+ function place() {
+ if (showTrash) return { view: 'trash' };
+ if (showUnfiled) return { view: 'unfiled' };
+ return { folder: cwd };
+ }
+ $effect(() => settlePlace('files', place()));
+ // A folder renamed or removed since is not there to go back to; its nearest
+ // surviving parent is.
+ onDestroy(onBackForward('files', (to) => {
+ if (to.view === 'trash') openTrash();
+ else if (to.view === 'unfiled') openUnfiled();
+ else {
+ let folder = to.folder ?? '';
+ while (folder && !allFolders.includes(folder)) folder = folder.split('/').slice(0, -1).join('/');
+ openFolder(folder);
+ }
+ return true;
+ }));
// ── selection ────────────────────────────────────────────────────────────────
let selected = $state([]);
@@ -1081,8 +1109,7 @@
<div class="tool">
<div class="tool-header">
- <h2>Files</h2>
- <span class="sub">Organize My work</span>
+ <span class="sub">Organize your folders</span>
<div class="spacer"></div>
{#if showTrash}
{#if trashData.groups.length}
@@ -1093,7 +1120,7 @@
{:else}
<SearchInput
bind:value={query}
- placeholder={cwd ? 'Search this folder…' : 'Search My work…'}
+ placeholder={cwd ? 'Search this folder…' : 'Search all files…'}
width="160px"
/>
{#if view !== 'list'}
@@ -1169,7 +1196,7 @@
>
<Icon name="file" size={14} />
<span class="tname">Unfiled</span>
- <span class="tcount">{unfiled.length}</span>
+ <span class="tcount">{unfiledTotal}</span>
</div>
<div
@@ -1364,7 +1391,7 @@
<span class="lcol-name"><Icon name="file" size={15} /><span class="ltext">Unfiled</span></span>
<span class="lcol-type">—</span>
<span class="lcol-size">—</span>
- <span class="lcol-added">{unfiled.length} item{unfiled.length === 1 ? '' : 's'}</span>
+ <span class="lcol-added">{unfiledTotal} item{unfiledTotal === 1 ? '' : 's'}</span>
</div>
{/if}
{/if}
@@ -1465,7 +1492,7 @@
>
<div class="thumb folder-thumb unfiled"><Icon name="file" size={dense ? 26 : 38} /></div>
<span class="tile-name">Unfiled</span>
- <span class="tile-sub">{unfiled.length} item{unfiled.length === 1 ? '' : 's'}</span>
+ <span class="tile-sub">{unfiledTotal} item{unfiledTotal === 1 ? '' : 's'}</span>
</div>
{/if}
{/if}
@@ -1769,8 +1796,8 @@
<label class="modal-label" for="fnote-title">Title</label>
<input id="fnote-title" class="input" placeholder="Note title…" bind:value={noteModal.title} />
- <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
- <FolderSelect bind:value={noteModal.folder} folders={allFolders} emptyLabel="My work (root)" fresh />
+ <span class="modal-label" style="margin-top:10px">Folder</span>
+ <FolderSelect bind:value={noteModal.folder} folders={allFolders} emptyLabel="Unfiled" fresh />
<div class="modal-row">
<div style="flex:1"></div>
@@ -1791,8 +1818,8 @@
<label class="modal-label" for="fbm-title" style="margin-top:10px">Title</label>
<input id="fbm-title" class="input" placeholder="Bookmark title…" bind:value={bookmarkModal.title} />
- <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
- <FolderSelect bind:value={bookmarkModal.folder} folders={allFolders} emptyLabel="My work (root)" fresh />
+ <span class="modal-label" style="margin-top:10px">Folder</span>
+ <FolderSelect bind:value={bookmarkModal.folder} folders={allFolders} emptyLabel="Unfiled" fresh />
<label class="modal-label" for="fbm-notes" style="margin-top:10px">Notes</label>
<textarea id="fbm-notes" class="textarea" rows="3" placeholder="Why this page matters…" bind:value={bookmarkModal.notes}></textarea>
diff --git a/frontend/src/tools/Files.test.js b/frontend/src/tools/Files.test.js
index e9e1c00..d2e1955 100644
--- a/frontend/src/tools/Files.test.js
+++ b/frontend/src/tools/Files.test.js
@@ -182,7 +182,7 @@ describe('Ctrl+V on the desktop', () => {
});
it('moves a new image out of the work folder when the dialog named another', () => {
- // registration filed it in the work folder; "My work (root)" has to be applied too
+ // registration filed it in the work folder; "Unfiled" has to be applied too
expect(source).toContain("(values.folder ?? '') !== (folderOf(result.entity) ?? '')");
});
@@ -211,12 +211,20 @@ describe('Files offers what is open to the Add event bar', () => {
describe('Files counts folders across the whole case', () => {
it('reads folder counts from the summary, not the loaded page', () => {
- expect(source).toContain('subtreeCountFrom(node, summary.by_folder)');
+ // accepted rows only, as Files lists them: a suggestion is counted under review
+ expect(source).toContain('summary?.confirmed?.by_folder');
+ expect(source).toContain('subtreeCountFrom(node, filedCounts)');
expect(source).toContain('{countOf(node)}');
expect(source).not.toContain('{subtreeCount(node)}');
expect(source).toContain('summary?.by_status?.confirmed ?? confirmed.length');
});
+ it('counts Unfiled across the whole case, not the loaded page', () => {
+ expect(source).toContain('summary?.confirmed?.unfiled ?? unfiled.length');
+ expect(source).toContain('<span class="tcount">{unfiledTotal}</span>');
+ expect(source).not.toContain('{unfiled.length} item');
+ });
+
it('removes a folder through the server, which unfiles items past the first page too', () => {
expect(source).toContain('...removeFolderPrompt(path, allFolders)');
expect(source).toContain('await removeFolder(caseState.current.id, path)');
@@ -300,7 +308,7 @@ describe('Files filters', () => {
it('narrows by type and by what nothing points at, on the server past one page', () => {
expect(source).toContain('types: typeFilter ? [typeFilter] : null');
expect(source).toContain('unlinked: unlinkedOnly');
- expect(source).toContain('const chips = $derived(typeChips(summary))');
+ expect(source).toContain('const chips = $derived(typeChips(summary?.confirmed))');
expect(source).toContain('Nothing linked yet');
});
diff --git a/frontend/src/tools/MediaLibrary.svelte b/frontend/src/tools/MediaLibrary.svelte
index 5111417..fcaca57 100644
--- a/frontend/src/tools/MediaLibrary.svelte
+++ b/frontend/src/tools/MediaLibrary.svelte
@@ -914,7 +914,6 @@
ondrop={onDrop}
>
<div class="tool-header">
- <h2>Media</h2>
<div class="spacer"></div>
<form
class="dl-form"
diff --git a/frontend/src/tools/Notebook.svelte b/frontend/src/tools/Notebook.svelte
index cb3278e..b03e381 100644
--- a/frontend/src/tools/Notebook.svelte
+++ b/frontend/src/tools/Notebook.svelte
@@ -1,8 +1,9 @@
<script>
- import { onDestroy } from 'svelte';
+ import { onDestroy, untrack } from 'svelte';
import { api } from '../lib/api.js';
import { fetchAllEntities } from '../lib/catalog.js';
import { offerNote, withdrawNote } from '../lib/noteHere.svelte.js';
+ import { onBackForward, settlePlace } from '../lib/backButton.js';
import { foldText } from '../lib/textFold.js';
import { caseState, uiState, toast, reloadCase } from '../lib/state.svelte.js';
import { entityReference, markdownHtml, remoteImageUrls } from '../lib/markdown.js';
@@ -188,6 +189,9 @@
({ tabs, activeId } = openNotebookTab(tabs, noteId));
}
+ // A note asked for from elsewhere (a sidebar row, Details) is a step Back retraces,
+ // unless the case just changed under the tab, which starts it over.
+ let requestedIn = null;
$effect(() => {
const caseId = caseState.current?.id ?? null;
if (caseId !== tabsCaseId) {
@@ -197,9 +201,27 @@
tabs = [];
}
}
- if (caseId) openRequestedNote(uiState.openNotebook?.noteId ?? null);
+ if (caseId) {
+ openRequestedNote(uiState.openNotebook?.noteId ?? null);
+ const sameCase = requestedIn === caseId;
+ requestedIn = caseId;
+ untrack(() => settlePlace('notebook', place(), { navigate: sameCase }));
+ }
});
+ // Where the tab is, in the address: the note on screen. Choosing a note is a step
+ // Back retraces; closing a tab or deleting its note only rewrites the step it is on.
+ // Notes write themselves as they are typed, so going back costs nothing.
+ const place = () => ({ note: noteId });
+ $effect(() => settlePlace('notebook', place()));
+ onDestroy(onBackForward('notebook', (to) => {
+ const id = to.note ?? null;
+ // A note deleted since is not there to go back to.
+ if (id && graphEntities.length && !noteEntities.some((entity) => entity.id === id)) return true;
+ selectNote(id);
+ return true;
+ }));
+
$effect(() => {
if (!key || key === loadedKey) return;
const requestedKey = key;
@@ -269,12 +291,14 @@
activeId = tab.id;
uiState.openNotebook = { noteId: tab.noteId };
closeNotesMenu();
+ settlePlace('notebook', place(), { navigate: true });
}
function selectNote(noteId = null) {
openRequestedNote(noteId);
uiState.openNotebook = { noteId };
closeNotesMenu();
+ settlePlace('notebook', place(), { navigate: true });
}
function openNewNote() {
@@ -295,6 +319,7 @@
noteModal = null;
openRequestedNote(note.id);
uiState.openNotebook = { noteId: note.id };
+ settlePlace('notebook', place(), { navigate: true });
} catch (error) {
toast(error.message, 'danger');
} finally {
@@ -326,6 +351,7 @@
activeId = next.activeId;
const active = tabs.find((tab) => tab.id === activeId);
uiState.openNotebook = { noteId: active?.noteId ?? null };
+ settlePlace('notebook', place());
}
async function confirmNoteAction() {
@@ -363,6 +389,7 @@
if (activeId === tab.id) return;
const active = tabs.find((item) => item.id === activeId);
if (active) uiState.openNotebook = { noteId: active.noteId };
+ settlePlace('notebook', place());
}
function saveSoon() {
@@ -882,8 +909,8 @@ flowchart LR
<label class="modal-label" for="notebook-note-title">Title</label>
<input id="notebook-note-title" class="input" placeholder="Note title…" bind:value={noteModal.title} />
- <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
- <FolderSelect bind:value={noteModal.folder} folders={caseState.current?.folders ?? []} emptyLabel="My work (root)" fresh />
+ <span class="modal-label" style="margin-top:10px">Folder</span>
+ <FolderSelect bind:value={noteModal.folder} folders={caseState.current?.folders ?? []} emptyLabel="Unfiled" fresh />
<div class="modal-row">
<div style="flex:1"></div>
diff --git a/frontend/src/tools/Overview.render.test.js b/frontend/src/tools/Overview.render.test.js
index a75d8a5..5daa804 100644
--- a/frontend/src/tools/Overview.render.test.js
+++ b/frontend/src/tools/Overview.render.test.js
@@ -20,6 +20,7 @@ const SUMMARY = {
linked_to: {},
unlinked: 7,
countable: 0,
+ confirmed: { by_type: {}, by_folder: { work: 14 }, unfiled: 12 },
};
const RECENT = [
@@ -211,7 +212,7 @@ describe('with a case open', () => {
it('says a clear case in one line rather than four zeros', async () => {
get.mockImplementation(async (url) => {
if (url.includes('/catalog/summary')) {
- return { ...SUMMARY, total: 18, by_status: {}, by_folder: { work: 18 }, unlinked: 0 };
+ return { ...SUMMARY, total: 18, by_status: {}, by_folder: { work: 18 }, unlinked: 0, confirmed: { unfiled: 0 } };
}
if (url.includes('/timeline')) return { undated: 0 };
if (url.includes('/satellite/media')) return [];
@@ -226,7 +227,7 @@ describe('with a case open', () => {
it('offers a way in rather than a reading of nothing, on a case holding nothing', async () => {
get.mockImplementation(async (url) => {
- if (url.includes('/catalog/summary')) return { ...SUMMARY, total: 0, by_type: {}, by_status: {}, by_folder: {}, unlinked: 0 };
+ if (url.includes('/catalog/summary')) return { ...SUMMARY, total: 0, by_type: {}, by_status: {}, by_folder: {}, unlinked: 0, confirmed: { unfiled: 0 } };
if (url.includes('/timeline')) return { undated: 0 };
if (url.includes('/satellite/media')) return [];
return { items: [], total: 0, next_cursor: null };
@@ -426,4 +427,31 @@ describe('with no case open', () => {
flushSync();
expect(openCase).toHaveBeenCalledWith('case-b');
});
+
+ it('asks for a new case, not a first one, above the cases already there', async () => {
+ caseState.list = [{ id: 'case-a', name: 'Kharkiv strike' }];
+ await open();
+ expect(target.querySelector('label[for="home-case-name"]').textContent).toBe('Name a new case');
+ });
+
+ it('opens a stage from its button, as the rail does', async () => {
+ await open();
+ const stages = [...target.querySelectorAll('button.stage')];
+ expect(stages.map((stage) => stage.textContent.trim())).toEqual(['Sources', 'Examine', 'Map', 'Compose']);
+ stages[2].click();
+ flushSync();
+ expect(uiState.tool).toBe('satellite');
+ });
+
+ it('keeps the typed name when the analyst stays in the open case', async () => {
+ createCase.mockResolvedValueOnce(null);
+ await open();
+ const field = target.querySelector('#home-case-name');
+ field.value = 'Kharkiv strike';
+ field.dispatchEvent(new Event('input', { bubbles: true }));
+ flushSync();
+ [...target.querySelectorAll('button')].find((b) => b.textContent.trim() === 'Create').click();
+ await settle();
+ expect(field.value).toBe('Kharkiv strike');
+ });
});
diff --git a/frontend/src/tools/Overview.svelte b/frontend/src/tools/Overview.svelte
index d72c879..32663d2 100644
--- a/frontend/src/tools/Overview.svelte
+++ b/frontend/src/tools/Overview.svelte
@@ -172,8 +172,7 @@
if (!name || creating) return;
creating = true;
try {
- await createCase(name);
- naming = '';
+ if (await createCase(name)) naming = '';
} catch (error) {
toast(error.message, 'warn', 5000);
} finally {
@@ -376,15 +375,18 @@
<ol class="pipeline">
{#each WORKSPACES as ws, i (ws.id)}
{#if i > 0}<li class="arrow" aria-hidden="true"><Icon name="chevronRight" size={13} /></li>{/if}
- <li class="stage">
- <Icon name={ws.icon} size={17} />
- <span>{ws.label}</span>
+ <!-- Each stage opens its first tool, as the rail does. -->
+ <li>
+ <button class="stage" title="Open {ws.label}" onclick={() => (uiState.tool = ws.tools[0])}>
+ <Icon name={ws.icon} size={17} />
+ <span>{ws.label}</span>
+ </button>
</li>
{/each}
</ol>
<div class="start">
- <label class="label" for="home-case-name">Name your first case</label>
+ <label class="label" for="home-case-name">{others.length ? 'Name a new case' : 'Name your first case'}</label>
<div class="start-row">
<input
id="home-case-name"
@@ -950,9 +952,19 @@
border: 1px solid var(--border);
border-radius: var(--r-md);
background: var(--bg-1);
+ font: inherit;
font-size: var(--fs-sm);
font-weight: 500;
color: var(--text-2);
+ cursor: pointer;
+ }
+ .stage:hover {
+ border-color: var(--border-strong);
+ color: var(--text-1);
+ }
+ .stage:focus-visible {
+ outline: 2px solid var(--accent);
+ outline-offset: 2px;
}
.arrow {
display: flex;
diff --git a/frontend/src/tools/PostComposer.svelte b/frontend/src/tools/PostComposer.svelte
index 1e05ce3..5313aef 100644
--- a/frontend/src/tools/PostComposer.svelte
+++ b/frontend/src/tools/PostComposer.svelte
@@ -1,11 +1,12 @@
<script>
- import { untrack } from 'svelte';
+ import { onDestroy, untrack } from 'svelte';
import { api } from '../lib/api.js';
import { fileUrl } from '../lib/fileUrl.js';
import { fetchAllEntities, lookupEntity, fetchDerivation } from '../lib/catalog.js';
import { caseState, uiState, toast, reloadCase, prefs, updatesState } from '../lib/state.svelte.js';
import { copyText } from '../lib/clipboard.js';
import { templatesState, postDraftState } from '../lib/state.svelte.js';
+ import { holdsUnsaved, onBackForward, settlePlace } from '../lib/backButton.js';
import { createNote } from '../lib/notes.js';
import { openNotebook } from '../lib/navigate.js';
import { deletedToast, RESTORABLE } from '../lib/trash.js';
@@ -257,7 +258,7 @@
if (uiState.tool === 'post' && uiState.openDraft && caseState.current) {
const name = uiState.openDraft;
uiState.openDraft = null;
- loadDraft(name);
+ requestLoadDraft(name);
}
});
@@ -789,6 +790,9 @@
async function performDraftSave(message = 'Draft saved') {
saving = true;
+ // What was sent is what is saved: an edit typed while the save is on its way
+ // still counts as unsaved.
+ const sent = contentState();
try {
const r = await api.post(`/api/cases/${caseState.current.id}/drafts`, {
rename_from: draftName,
@@ -797,6 +801,7 @@
});
draftName = r.name;
postName = r.title;
+ savedKey = contentKey(sent, r.title);
await reloadCase(); // surface the post entity in the sidebar
toast(message, 'ok', 1600);
return true;
@@ -874,6 +879,7 @@
};
});
draftName = name;
+ settlePlace('post', where(), { navigate: true });
postName = doc.title || name;
appliedPostTemplate = null;
// restore geo facts from the coordinates, then honor any manual tweet edits
@@ -890,6 +896,7 @@
tweet1Edited = s.tweet1Edited ?? false;
target = normalizePostTarget(s.target);
openList = null;
+ savedKey = contentKey();
toast('Draft loaded', 'ok', 1400);
} catch (e) {
toast(`Could not load draft: ${e.message}`, 'danger');
@@ -921,7 +928,63 @@
defaultDeclined = false;
discardConfirm = false;
startFromDefaultTemplate();
+ savedKey = contentKey();
+ }
+
+ // ---- what is not saved yet ------------------------------------------------
+ // What a save would keep, to tell work from the composer as it was opened, reset
+ // or last saved. The platform follows Settings on a blank post, an untouched first
+ // tweet is rebuilt from the fields and a numbered name is renumbered once the case's
+ // drafts are known, so none of them counts as work on its own.
+ function contentState() {
+ const state = snapshot();
+ delete state.target;
+ delete state.tweet1;
+ return { ...state, tweet1: tweet1Edited ? tweet1 : null };
+ }
+ function contentKey(state = contentState(), title = postName) {
+ const named = String(title ?? '').trim();
+ return JSON.stringify({ ...state, title: isDefaultName(named, 'draft') ? '' : named });
+ }
+ let savedKey = $state(null);
+ const unsaved = $derived(savedKey !== null && contentKey() !== savedKey);
+ $effect(() => {
+ if (savedKey === null) untrack(() => (savedKey = contentKey()));
+ });
+
+ // Opening another draft, from the list, the sidebar or Back, asks first when this
+ // post has changes not saved, so nothing is dropped without the analyst saying so.
+ let leaving = $state(null); // { answer(ok) }
+ function mayLeave() {
+ if (!unsaved) return Promise.resolve(true);
+ leaving?.answer(false);
+ return new Promise((resolve) => {
+ leaving = {
+ answer: (ok) => {
+ leaving = null;
+ resolve(ok);
+ },
+ };
+ });
}
+ async function requestLoadDraft(name) {
+ if (await mayLeave()) await loadDraft(name);
+ }
+
+ // Where the composer is, in the address: the saved draft open, or none. Opening a
+ // draft is the step Back retraces; a save naming it, a rename or a discard only
+ // rewrite the step it is on.
+ const where = () => ({ draft: draftName });
+ $effect(() => settlePlace('post', where()));
+ onDestroy(onBackForward('post', async (to) => {
+ const target = to.draft ?? null;
+ if (target === draftName) return true;
+ if (!(await mayLeave())) return false;
+ if (target) await loadDraft(target);
+ else resetDraft();
+ return true;
+ }));
+ onDestroy(holdsUnsaved('post', () => unsaved));
const hasContent = $derived(
!!(draftName || description.trim() || coordsText.trim() || date.trim() || mediaPaths.length ||
@@ -939,7 +1002,12 @@
$effect(() => {
if (hasContent || appliedPostTemplate || defaultDeclined) return;
const t = defaultTemplate();
- if (t) untrack(() => applyPostTemplate(t, { quiet: true }));
+ if (t) {
+ untrack(() => {
+ applyPostTemplate(t, { quiet: true });
+ savedKey = contentKey();
+ });
+ }
});
// The live draft, mirrored for Settings → Templates so a layout can be tried on
@@ -1588,8 +1656,8 @@
<label class="modal-label" for="report-note-title">Title</label>
<input id="report-note-title" class="input" placeholder="Report title…" bind:value={reportModal.title} />
- <span class="modal-label" style="margin-top:10px">Folder (in My work)</span>
- <FolderSelect bind:value={reportModal.folder} folders={caseState.current?.folders ?? []} emptyLabel="My work (root)" fresh />
+ <span class="modal-label" style="margin-top:10px">Folder</span>
+ <FolderSelect bind:value={reportModal.folder} folders={caseState.current?.folders ?? []} emptyLabel="Unfiled" fresh />
<div class="modal-row">
<div style="flex:1"></div>
@@ -1609,7 +1677,7 @@
<div class="open-list">
{#each openList as entry (entry.name)}
<div class="open-row-wrap">
- <button class="open-row" onclick={() => loadDraft(entry.name)}>
+ <button class="open-row" onclick={() => requestLoadDraft(entry.name)}>
<div class="open-meta">
<span class="open-title">{entry.title}</span>
<span class="open-sub">{entry.updated_at?.slice(0, 10)}</span>
@@ -1639,6 +1707,19 @@
/>
{/if}
+{#if leaving}
+ <ConfirmDialog
+ title="Leave this post?"
+ message="Its changes are not saved."
+ confirmLabel="Leave without saving"
+ cancelLabel="Keep editing"
+ tone="danger"
+ icon="reset"
+ onconfirm={() => leaving.answer(true)}
+ oncancel={() => leaving.answer(false)}
+ />
+{/if}
+
{#if discardConfirm}
<ConfirmDialog
title="Discard this draft?"
diff --git a/frontend/src/tools/ProofComposer.svelte b/frontend/src/tools/ProofComposer.svelte
index c617163..98027ef 100644
--- a/frontend/src/tools/ProofComposer.svelte
+++ b/frontend/src/tools/ProofComposer.svelte
@@ -1,6 +1,7 @@
<script>
import { onDestroy, onMount, untrack } from 'svelte';
import { offerNote, withdrawNote } from '../lib/noteHere.svelte.js';
+ import { holdsUnsaved, onBackForward, settlePlace } from '../lib/backButton.js';
import { fileUrl } from '../lib/fileUrl.js';
import Konva from 'konva';
import { api } from '../lib/api.js';
@@ -648,10 +649,52 @@
if (uiState.tool === 'proof' && uiState.openProof && caseState.current) {
const name = uiState.openProof;
uiState.openProof = null;
- openProof({ name });
+ requestOpenProof({ name });
}
});
+ // ---- leaving a proof that holds unsaved changes --------------------------
+ // Opening another proof, from the list, the sidebar or Back, asks first when this
+ // one has changes not saved, so nothing is dropped without the analyst saying so.
+ let leaving = $state(null); // { answer(ok) }
+ function mayLeave() {
+ if (!proofStarted || !dirty) return Promise.resolve(true);
+ leaving?.answer(false);
+ return new Promise((resolve) => {
+ leaving = {
+ answer: (ok) => {
+ leaving = null;
+ resolve(ok);
+ },
+ };
+ });
+ }
+ async function requestOpenProof(entry) {
+ if (await mayLeave()) await openProof(entry);
+ }
+
+ // Where the composer is, in the address: the saved proof open, or none. Opening a
+ // proof and starting a new one are the steps Back retraces; a save naming the proof,
+ // a rename or a discard only rewrite the step it is on.
+ const place = () => ({ proof: savedName });
+ $effect(() => settlePlace('proof', place()));
+ onDestroy(onBackForward('proof', async (to) => {
+ const target = to.proof ?? null;
+ if (target === savedName) return true;
+ if (!(await mayLeave())) return false;
+ if (!target) {
+ resetDoc();
+ return true;
+ }
+ try {
+ await openProof({ name: target });
+ } catch (error) {
+ toast(`This proof cannot be opened: ${error.message}`, 'warn');
+ }
+ return true;
+ }));
+ onDestroy(holdsUnsaved('proof', () => proofStarted && dirty));
+
// leaving the curve tool abandons an unfinished draft
$effect(() => {
if (tool !== 'curve' && pathDraft) finishPath(false);
@@ -1022,6 +1065,7 @@
try {
resetDoc();
proofStarted = true;
+ settlePlace('proof', place(), { navigate: true });
if (template) applyTemplate(template, { notify: false });
for (const item of selectedItems) await addPanel(item);
dirty = true;
@@ -3976,12 +4020,12 @@
function selectProofBrowser(entry, confirm = false) {
proofBrowseSelection = entry.name;
- if (confirm) openProof(entry);
+ if (confirm) requestOpenProof(entry);
}
function confirmProofBrowser() {
const entry = proofBrowserEntries.find((item) => item.name === proofBrowseSelection);
- if (entry) openProof(entry);
+ if (entry) requestOpenProof(entry);
}
let deleteEntry = $state(null); // open-list entry pending deletion
@@ -4015,6 +4059,7 @@
// stream in one by one and enable the Save button as they arrive, so a Save
// during the load has to write back over this proof, not file a new one.
savedName = entry.name;
+ settlePlace('proof', place(), { navigate: true });
proof.title = spec.title;
proof.points = editablePoints(spec);
proof.footerCoords = spec.footerCoords === true;
@@ -4123,7 +4168,7 @@
picker || newProofOpen || importOpen || openList !== null || discardConfirm
|| replaceWithNewConfirm || exportPicker || overwritePrompt !== null
|| placeOffer !== null || orphanOffer !== null || deleteEntry !== null
- || sourcePick !== null || pointMap !== null || checking !== null
+ || sourcePick !== null || pointMap !== null || checking !== null || leaving !== null
);
const editableShape = $derived(editableShapes.length === 1 ? editableShapes[0] : null);
const fillableSelection = $derived(editableShapes.some((s) => canFill(s.kind)));
@@ -5131,7 +5176,7 @@
onclose={() => (importOpen = false)}
oncreated={async (created) => {
await reloadCase();
- openProof({ name: created.proof.name });
+ requestOpenProof({ name: created.proof.name });
}}
/>
{/if}
@@ -5162,6 +5207,19 @@
/>
{/if}
+{#if leaving}
+ <ConfirmDialog
+ title="Leave this proof?"
+ message="Its changes are not saved."
+ confirmLabel="Leave without saving"
+ cancelLabel="Keep editing"
+ tone="danger"
+ icon="reset"
+ onconfirm={() => leaving.answer(true)}
+ oncancel={() => leaving.answer(false)}
+ />
+{/if}
+
{#if discardConfirm}
<ConfirmDialog
title="Discard this proof?"
@@ -5376,7 +5434,7 @@
<div class="open-list">
{#each visibleProofs as entry (entry.name)}
<div class="open-row-wrap">
- <button class="open-row" onclick={() => openProof(entry)}>
+ <button class="open-row" onclick={() => requestOpenProof(entry)}>
{#if entry.thumb || entry.png}
<!-- the thumbnail of the export, or the export itself when
it could not be rendered; decoded off the main thread -->
diff --git a/frontend/src/tools/Satellite.svelte b/frontend/src/tools/Satellite.svelte
index 0b33bde..06d496a 100644
--- a/frontend/src/tools/Satellite.svelte
+++ b/frontend/src/tools/Satellite.svelte
@@ -48,6 +48,7 @@
import { COMPARE_SOURCES, comparePair } from '../lib/map/comparePair.js';
import { actionsFor, otherMapTools } from '../lib/map/contextMenu.js';
import { buildHash, readSolo, splitHash } from '../lib/hash.js';
+ import { settlePlace } from '../lib/backButton.js';
import { readView, readWindowLabel, viewParams } from '../lib/map/view.js';
import { createViewLink } from '../lib/map/link.js';
import { shareView } from '../lib/map/sharedView.js';
@@ -797,8 +798,8 @@
/**
* This window's view, kept in its own address.
*
- * `replaceState`, never push: panning a map is not navigating, and a back
- * button holding four hundred camera positions is worse than useless.
+ * Settled, never navigated to: panning a map is not going somewhere, and a
+ * back button holding four hundred camera positions is worse than useless.
*/
$effect(() => {
if (uiState.tool !== 'satellite' || !mapReady) return;
@@ -814,7 +815,7 @@
// without it, the first pan would turn a detached map back into the whole
// app on the next reload.
if (solo) params.solo = '1';
- history.replaceState(null, '', buildHash('satellite', params));
+ settlePlace('satellite', params);
});
/**
diff --git a/frontend/src/tools/Satellite.test.js b/frontend/src/tools/Satellite.test.js
index ad29d98..d299b04 100644
--- a/frontend/src/tools/Satellite.test.js
+++ b/frontend/src/tools/Satellite.test.js
@@ -143,14 +143,14 @@ describe('filing saved work from its details dialog', () => {
it('offers the same folder picker the rest of the app uses, in both dialogs', () => {
expect(captureDialog).toContain("import FolderSelect from '../../components/FolderSelect.svelte'");
expect(captureDialog).toContain('bind:value={folder}');
- expect(captureDialog).toContain('emptyLabel="My work (root)"');
+ expect(captureDialog).toContain('emptyLabel="Unfiled"');
const placeDialog = readFileSync(
new URL('./satellite/PlaceDialog.svelte', import.meta.url),
'utf8'
);
expect(placeDialog).toContain("import FolderSelect from '../../components/FolderSelect.svelte'");
expect(placeDialog).toContain('bind:value={draft.folder}');
- expect(placeDialog).toContain('emptyLabel="My work (root)"');
+ expect(placeDialog).toContain('emptyLabel="Unfiled"');
});
it('opens each dialog on the folder the item is already in', () => {
@@ -680,10 +680,11 @@ describe('a map in more than one window', () => {
});
it('keeps this window\'s view in this window\'s address', () => {
- expect(source).toContain("history.replaceState(null, '', buildHash('satellite', params))");
+ expect(source).toContain("settlePlace('satellite', params);");
// panning is not navigating: a back button full of camera positions is worse
// than no history at all
expect(source).not.toContain('history.pushState');
+ expect(source).not.toContain('navigate: true');
});
it('writes nothing while another tool is open', () => {
diff --git a/frontend/src/tools/Sheet.svelte b/frontend/src/tools/Sheet.svelte
index 584d81a..c935872 100644
--- a/frontend/src/tools/Sheet.svelte
+++ b/frontend/src/tools/Sheet.svelte
@@ -40,12 +40,13 @@
* No rules live in this file. The table, the selection, the clipboard, the cleaning passes
* and the undo stack are all pure modules; what is here is the screen.
*/
- import { tick, untrack } from 'svelte';
+ import { onDestroy, tick, untrack } from 'svelte';
import { api } from '../lib/api.js';
import { closeOnOutsidePointer } from '../lib/dismiss.js';
import { fileUrl } from '../lib/fileUrl.js';
import { CASE_FOLDER_LABEL, destinationLabel, readDestinations } from '../lib/exportDest.js';
import { caseState, reloadCase, toast, uiState } from '../lib/state.svelte.js';
+ import { holdsUnsaved, onBackForward, settlePlace } from '../lib/backButton.js';
import {
DEFAULT_WIDTH,
GUTTER_WIDTH,
@@ -522,20 +523,55 @@
/** Back to the home. Whatever is unsaved is written first, as on any other switch, and
* a grid that still holds what no write kept asks before it is dropped. */
async function goHome() {
- await release(async () => {
+ return release(async () => {
close();
+ settlePlace('sheet', place(), { navigate: true });
await list(caseId);
});
}
/** Write what is pending, then let go of the sheet. A failed or conflicting save leaves
* edits only the grid holds, and leaving drops them as surely as Reload does, so it asks
- * the same way. */
+ * the same way. Answers whether it let go. */
async function release(then) {
await flush();
- if (!unsaved) return then();
- confirming = { kind: 'leave', then };
+ if (!unsaved) {
+ await then();
+ return true;
+ }
+ return new Promise((resolve) => {
+ staying?.();
+ staying = () => resolve(false);
+ confirming = {
+ kind: 'leave',
+ then: async () => {
+ staying = null;
+ await then();
+ resolve(true);
+ },
+ };
+ });
}
+ // The question closed any way but Leave (Cancel, Escape, another question in its
+ // place) is an answer too: the tab stays where it is.
+ let staying = null;
+ $effect(() => {
+ if (confirming?.kind === 'leave' || !staying) return;
+ staying();
+ staying = null;
+ });
+
+ // Where the tab is, in the address: the home, or one sheet. Opening a sheet and
+ // coming home are the steps Back retraces; a sheet deleted under it only rewrites
+ // the step it is on. Back past a sheet whose edits could not be written asks as
+ // leaving it any other way does.
+ const place = () => ({ sheet: openId });
+ $effect(() => settlePlace('sheet', place()));
+ onDestroy(onBackForward('sheet', (to) => {
+ if (to.sheet) return open(to.sheet);
+ return openId ? goHome() : true;
+ }));
+ onDestroy(holdsUnsaved('sheet', () => unsaved));
/** Which sheet this case was last left on. Kept in the browser rather than in the case:
* it is where *this* analyst was reading, not something the case believes, and a bundle
@@ -560,8 +596,8 @@
}
async function open(id) {
- if (id === openId) return;
- await release(() => openNow(id));
+ if (id === openId) return true;
+ return release(() => openNow(id));
}
async function openNow(id) {
@@ -570,6 +606,7 @@
try {
adopt(await api.get(`/api/cases/${caseId}/sheets/${id}`), { reset: true });
openId = id;
+ settlePlace('sheet', place(), { navigate: true });
rememberOpened(caseId, id);
} catch (error) {
toast(error.message || 'This sheet could not be opened.', 'danger');
diff --git a/frontend/src/tools/coordinates/PointPicker.svelte b/frontend/src/tools/coordinates/PointPicker.svelte
index 25a25cd..aadc2c3 100644
--- a/frontend/src/tools/coordinates/PointPicker.svelte
+++ b/frontend/src/tools/coordinates/PointPicker.svelte
@@ -76,7 +76,7 @@
<FolderBrowser
{entries}
{path}
- rootLabel="My work"
+ rootLabel="Saved points"
icon={glyph}
{label}
emptyText="No saved point is filed here."
diff --git a/frontend/src/tools/coordinates/PointPicker.test.js b/frontend/src/tools/coordinates/PointPicker.test.js
index ccc9371..5b1bf5e 100644
--- a/frontend/src/tools/coordinates/PointPicker.test.js
+++ b/frontend/src/tools/coordinates/PointPicker.test.js
@@ -16,7 +16,7 @@ describe('saved-point picker', () => {
expect(picker).toContain("import FolderBrowser from '../../components/FolderBrowser.svelte'");
expect(picker).toContain("import SearchInput from '../../components/SearchInput.svelte'");
expect(picker).toContain('class="btn btn-ghost btn-sm browse-btn"');
- expect(picker).toContain('rootLabel="My work"');
+ expect(picker).toContain('rootLabel="Saved points"');
});
it('lists only what carries a position', () => {
diff --git a/frontend/src/tools/satellite/CaptureDetails.svelte b/frontend/src/tools/satellite/CaptureDetails.svelte
index afbcc7d..d3f8416 100644
--- a/frontend/src/tools/satellite/CaptureDetails.svelte
+++ b/frontend/src/tools/satellite/CaptureDetails.svelte
@@ -53,7 +53,7 @@
id="capture-folder"
bind:value={folder}
{folders}
- emptyLabel="My work (root)"
+ emptyLabel="Unfiled"
/>
<hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />
<div class="sat-info-rows">
diff --git a/frontend/src/tools/satellite/PlaceDialog.svelte b/frontend/src/tools/satellite/PlaceDialog.svelte
index eececd6..030b866 100644
--- a/frontend/src/tools/satellite/PlaceDialog.svelte
+++ b/frontend/src/tools/satellite/PlaceDialog.svelte
@@ -73,7 +73,7 @@
id="place-folder"
bind:value={draft.folder}
{folders}
- emptyLabel="My work (root)"
+ emptyLabel="Unfiled"
/>
<hr style="border:none;border-top:1px solid var(--border);margin:12px 0" />
<div class="sat-info-rows">
diff --git a/frontend/src/tools/satellite/PlaceSearch.render.test.js b/frontend/src/tools/satellite/PlaceSearch.render.test.js
index 66c82ad..de613fc 100644
--- a/frontend/src/tools/satellite/PlaceSearch.render.test.js
+++ b/frontend/src/tools/satellite/PlaceSearch.render.test.js
@@ -94,3 +94,37 @@ describe('Enter with nothing highlighted', () => {
expect(get).not.toHaveBeenCalled();
});
});
+
+describe('a typed coordinate', () => {
+ it('never reaches the geocoder, however long the analyst waits to pick it', async () => {
+ get.mockImplementation(async (path) =>
+ path.startsWith('/api/geo/suggest')
+ ? { coords: { lat: 50.4501, lon: 30.5234 }, cities: [] }
+ : { places: [] }
+ );
+ const { input } = open();
+
+ type(input, '50.4501, 30.5234');
+ // well past the geocoder's debounce, with the Coordinates row still unpicked
+ await vi.advanceTimersByTimeAsync(5000);
+ flushSync();
+
+ expect(get.mock.calls.map(([path]) => path.split('?')[0])).toEqual(['/api/geo/suggest']);
+ expect(target.querySelector('[role="listbox"]').textContent).toContain('Coordinates');
+ });
+
+ it('still asks the geocoder for a place name', async () => {
+ get.mockImplementation(async (path) =>
+ path.startsWith('/api/geo/suggest') ? { coords: null, cities: [] } : { places: [] }
+ );
+ const { input } = open();
+
+ type(input, 'Kyiv centre');
+ await vi.advanceTimersByTimeAsync(5000);
+
+ expect(get.mock.calls.map(([path]) => path.split('?')[0])).toEqual([
+ '/api/geo/suggest',
+ '/api/geo/places',
+ ]);
+ });
+});
diff --git a/frontend/src/tools/satellite/PlaceSearch.svelte b/frontend/src/tools/satellite/PlaceSearch.svelte
index aa06b45..5be4663 100644
--- a/frontend/src/tools/satellite/PlaceSearch.svelte
+++ b/frontend/src/tools/satellite/PlaceSearch.svelte
@@ -54,6 +54,8 @@
// query is dropped rather than shown under a newer one.
let localFor = '';
let remoteFor = '';
+ // The local layer's answer for `localFor`, which the geocoder waits on.
+ let localAnswer = Promise.resolve(null);
const groups = $derived(
buildGroups({
@@ -92,17 +94,22 @@
async function askLocal(query) {
localFor = query;
- try {
- const body = await api.get(`/api/geo/suggest?q=${encodeURIComponent(query)}`);
- if (localFor !== query) return;
- coords = body.coords;
- cities = body.cities ?? [];
- } catch {
- /* the bar still works without suggestions */
- }
+ // the bar still works without suggestions
+ localAnswer = api.get(`/api/geo/suggest?q=${encodeURIComponent(query)}`).catch(() => null);
+ const body = await localAnswer;
+ if (localFor !== query || !body) return;
+ coords = body.coords;
+ cities = body.cities ?? [];
}
async function askRemote(query) {
+ // A coordinate is nobody's place name. The local layer was asked first, so its
+ // reading of the same text decides whether the geocoder hears it at all, however
+ // long the analyst waits before picking the row.
+ if (localFor === query) {
+ const local = await localAnswer;
+ if (local?.coords || localFor !== query) return;
+ }
remoteFor = query;
try {
const body = await api.get(`/api/geo/places?q=${encodeURIComponent(query)}&limit=5`);
diff --git a/frontend/src/tools/satellite/PlaceSearch.test.js b/frontend/src/tools/satellite/PlaceSearch.test.js
index 2ef5162..158c618 100644
--- a/frontend/src/tools/satellite/PlaceSearch.test.js
+++ b/frontend/src/tools/satellite/PlaceSearch.test.js
@@ -45,7 +45,7 @@ describe('what typing costs', () => {
});
it('drops an answer to a query that is no longer what is typed', () => {
- expect(source).toContain('if (localFor !== query) return');
+ expect(source).toContain('if (localFor !== query || !body) return');
expect(source).toContain('if (remoteFor !== query) return');
});
diff --git a/frontend/src/tools/satellite/SavedTree.svelte b/frontend/src/tools/satellite/SavedTree.svelte
index 8eecd58..ea078e1 100644
--- a/frontend/src/tools/satellite/SavedTree.svelte
+++ b/frontend/src/tools/satellite/SavedTree.svelte
@@ -6,7 +6,7 @@
* Two groupings over one set. **Geography** (lib/geoTree.js) is the default:
* a case that sits in one country opens straight on its regions, one that
* spans the world opens on continents. **Folders** (lib/folderView.js) shows
- * the same items through My work, and only there can a row be dragged onto a
+ * the same items through the case folders, and only there can a row be dragged onto a
* folder to file it. Typing filters before grouping, so the counts always
* describe what is on screen, and every branch opens while a search is
* running — a filter that hides its own matches behind chevrons is no filter.
diff --git a/frontend/src/tools/satellite/state/saved.svelte.js b/frontend/src/tools/satellite/state/saved.svelte.js
index 6f369b7..f4f75fe 100644
--- a/frontend/src/tools/satellite/state/saved.svelte.js
+++ b/frontend/src/tools/satellite/state/saved.svelte.js
@@ -207,7 +207,7 @@ export function createSavedState({ api, notify, assignFolder, reloadCase }) {
try {
await assignFolder(caseId, entity, folder);
await reloadCase();
- notify(folder ? `Filed in ${folder}` : 'Removed from My work', 'ok', 1600);
+ notify(folder ? `Filed in ${folder}` : 'Moved to Unfiled', 'ok', 1600);
} catch (e) {
notify(e.message, 'danger');
}
diff --git a/src/azimut/__init__.py b/src/azimut/__init__.py
index 9140976..6890c00 100644
--- a/src/azimut/__init__.py
+++ b/src/azimut/__init__.py
@@ -13,7 +13,7 @@ from PIL import Image as _Image
# The capture extension is versioned separately, on purpose — it carries the
# release that last changed it (tests/test_updates.py). Don't move the two
# together.
-__version__ = "0.3.1"
+__version__ = "0.3.2"
# Cap the pixels Pillow will decode from a file, process-wide. A tiny,
# highly-compressed image can otherwise expand to gigabytes in memory and take
diff --git a/src/azimut/api/cases/catalog.py b/src/azimut/api/cases/catalog.py
index 19b827d..e6b2244 100644
--- a/src/azimut/api/cases/catalog.py
+++ b/src/azimut/api/cases/catalog.py
@@ -73,8 +73,9 @@ def catalog_entities(
coordinates", and ``total`` is how many.
``order`` sorts the whole filtered set rather than the page — ``created`` and
- ``label``, each with a ``-`` prefix for the other direction. Empty is the insertion
- order that has always been the default.
+ ``label``, each with a ``-`` prefix for the other direction; ``relevance`` ranks
+ exact labels, phrase prefixes and word prefixes before other matches. Empty
+ is the insertion order that has always been the default.
``attr`` without ``value`` is not a term — it is the analyst having chosen which
field they are about to ask about, and answering it as "holds nothing" would empty
diff --git a/src/azimut/api/satellite.py b/src/azimut/api/satellite.py
index a1a1b56..cb2bcfd 100644
--- a/src/azimut/api/satellite.py
+++ b/src/azimut/api/satellite.py
@@ -1049,6 +1049,10 @@ def geocode(q: str) -> dict[str, Any]:
query = q.strip()
if not query:
raise HTTPException(status_code=422, detail="empty query")
+ # Already a point (a Sheet cell holding coordinates, say): read here, never sent.
+ parsed = geo.parse_coords(query)
+ if parsed:
+ return {"lat": parsed[0], "lon": parsed[1], "display_name": None, "attribution": None}
result = geo.geocode(query)
if not result:
raise HTTPException(status_code=404, detail="no match for that place name")
@@ -1085,6 +1089,10 @@ def suggest_places(q: str, limit: int = Query(default=5, ge=1, le=10)) -> dict[s
query = q.strip()
if not query:
raise HTTPException(status_code=422, detail="empty query")
+ # A coordinate is nobody's place name, and sending the analyst's point to an
+ # outside geocoder is a leak with nothing to gain: `/geo/suggest` reads it.
+ if geo.parse_coords(query):
+ return {"places": [], "busy": False, "throttled": False, "attribution": None}
found = geo.suggest(query, limit)
if found is None:
return {"places": [], "busy": True, "throttled": geo.throttled(), "attribution": None}
diff --git a/src/azimut/engine/textfold.py b/src/azimut/engine/textfold.py
index 5d706eb..ecb88fd 100644
--- a/src/azimut/engine/textfold.py
+++ b/src/azimut/engine/textfold.py
@@ -50,3 +50,17 @@ def fold_text(text: str) -> str:
base = code
out.append(char)
return unicodedata.normalize("NFC", "".join(out))
+
+
+def search_rank(label: str, query: str) -> int:
+ """Rank exact labels, phrase prefixes, word prefixes, then other matches."""
+ text = fold_text(label)
+ phrase = " ".join(fold_text(query).split())
+ if text == phrase:
+ return 0
+ if text.startswith(phrase):
+ return 1
+ words = text.split()
+ if all(any(word.startswith(term) for word in words) for term in phrase.split()):
+ return 2
+ return 3
diff --git a/src/azimut/repository.py b/src/azimut/repository.py
index 0c1087b..5d81ce6 100644
--- a/src/azimut/repository.py
+++ b/src/azimut/repository.py
@@ -108,7 +108,8 @@ class CaseRepository(Protocol):
Feeds the catalog's badges and its filter menus without shipping entities to
the caller — ``{"total": int, "by_type": {type: n}, "by_status": {status: n},
"by_folder": {path: n}, "by_source": {who: n}, "linked_to": {type: n},
- "unlinked": int}``.
+ "unlinked": int, "confirmed": {"by_type", "by_folder", "unfiled"}}``, the last
+ over accepted rows only, as Files and the sidebar list them.
``linked_to`` counts entities that **have a neighbour** of each type, which is
not how many of that type the case holds: it is what the "linked to" filter
diff --git a/src/azimut/sqlite_backend.py b/src/azimut/sqlite_backend.py
index 26e5c30..19226e8 100644
--- a/src/azimut/sqlite_backend.py
+++ b/src/azimut/sqlite_backend.py
@@ -31,7 +31,7 @@ from typing import TYPE_CHECKING, Any, Callable, Iterator, TypeVar
from .engine import links as link_engine
from .engine import timeline as timeline_engine
-from .engine.textfold import fold_text
+from .engine.textfold import fold_text, search_rank
from . import layout
from .repository import EntityStatus
from .store.cursors import (
@@ -1363,6 +1363,7 @@ class SqliteCase:
the answer each of its groups holds without asking once per group.
"""
orders = {**_PAGE_ORDERS, **_COUNTED_ORDERS}
+ orders["relevance"] = ("azimut_search_rank(label)", "_sort", False)
if order and order not in orders:
raise CaseError(f"'{order}' is not an ordering")
if order in _COUNTED_ORDERS and not types:
@@ -1387,7 +1388,7 @@ class SqliteCase:
if cursor is not None:
seat, raw_key = _page_cursor(cursor)
key: Any = raw_key
- if order in _COUNTED_ORDERS:
+ if order in _COUNTED_ORDERS or order == "relevance":
try:
key = int(raw_key)
except ValueError:
@@ -1408,6 +1409,12 @@ class SqliteCase:
ordering = "rowid"
params.append(limit + 1)
with self._connect() as conn:
+ if order == "relevance":
+ conn.create_function(
+ "azimut_search_rank", 1,
+ lambda label: search_rank(str(label), query or ""),
+ deterministic=True,
+ )
total = int(
conn.execute(
f"SELECT COUNT(*) FROM entities{filter_clause}",
@@ -1572,6 +1579,22 @@ class SqliteCase:
" WHERE folder IS NOT NULL GROUP BY folder"
)
}
+ # The same counts over accepted rows only, which is what Files, the
+ # sidebar and Home's "Unfiled" show: a suggestion waits under review and
+ # is neither filed nor unfiled until somebody accepts it.
+ confirmed_by_type: dict[str, int] = {}
+ confirmed_by_folder: dict[str, int] = {}
+ confirmed_unfiled = 0
+ for r in conn.execute(
+ "SELECT type, folder, COUNT(*) AS n FROM entities"
+ " WHERE prov_status = 'confirmed' GROUP BY type, folder"
+ ):
+ n = int(r["n"])
+ confirmed_by_type[r["type"]] = confirmed_by_type.get(r["type"], 0) + n
+ if r["folder"] is None:
+ confirmed_unfiled += n
+ else:
+ confirmed_by_folder[r["folder"]] = confirmed_by_folder.get(r["folder"], 0) + n
by_source = {
r["prov_by"]: r["n"]
for r in conn.execute(
@@ -1643,6 +1666,11 @@ class SqliteCase:
"unlinked": unlinked,
"countable": countable,
"lacks": lacks,
+ "confirmed": {
+ "by_type": confirmed_by_type,
+ "by_folder": confirmed_by_folder,
+ "unfiled": confirmed_unfiled,
+ },
}
def attr_facets(
diff --git a/src/azimut/workspace.py b/src/azimut/workspace.py
index 925899e..7bcbd2a 100644
--- a/src/azimut/workspace.py
+++ b/src/azimut/workspace.py
@@ -32,6 +32,7 @@ from .caselayout import (
write_readme,
)
from .casestore import CaseStore
+from .engine.textfold import fold_text
from .layout import MAX_CASE_SLUG
from .repository import EntityStatus
@@ -627,6 +628,7 @@ class Case(CaseStore):
cls, *, q: str | None = None, limit: int | None = None, scaffolds: bool = False
) -> list[dict[str, Any]]:
out: list[dict[str, Any]] = []
+ terms = fold_text(q or "").split()
for parent, scratch in ((config.cases_dir(), False), (config.scratch_dir(), True)):
if not parent.is_dir():
continue
@@ -650,6 +652,9 @@ class Case(CaseStore):
if not isinstance(data, dict):
data = {}
health = "needs-attention"
+ name = data.get("name", case.id)
+ if terms and not all(term in fold_text(str(name)) for term in terms):
+ continue
updated_at = data.get("updated_at")
try:
if case._sqlite is not None:
@@ -664,7 +669,7 @@ class Case(CaseStore):
out.append(
{
"id": case.id,
- "name": data.get("name", case.id),
+ "name": name,
"scratch": scratch,
"created_at": data.get("created_at"),
"updated_at": updated_at,
@@ -673,9 +678,6 @@ class Case(CaseStore):
}
)
out.sort(key=lambda c: c.get("updated_at") or "", reverse=True)
- if q:
- needle = q.strip().lower()
- out = [c for c in out if needle in str(c.get("name", "")).lower()]
if limit is not None:
out = out[: max(0, limit)]
return out
diff --git a/tests/fixtures/case-workspace-0.3.1.json b/tests/fixtures/case-workspace-0.3.1.json
index 9b6f2b2..8b1f34c 100644
--- a/tests/fixtures/case-workspace-0.3.1.json
+++ b/tests/fixtures/case-workspace-0.3.1.json
@@ -1731,6 +1731,38 @@
"structure": 1,
"vessel": 1
},
+ "confirmed": {
+ "by_folder": {
+ "Sources/Telegram": 1
+ },
+ "by_type": {
+ "account": 1,
+ "analysis-area": 2,
+ "analysis-follow-up": 1,
+ "analysis-run": 1,
+ "analysis-zones": 1,
+ "bookmark": 1,
+ "capture": 1,
+ "claim": 12,
+ "collage": 1,
+ "compare-session": 1,
+ "equipment-type": 1,
+ "inspect-session": 1,
+ "map-layer": 1,
+ "media": 6,
+ "network": 1,
+ "note": 1,
+ "organization": 2,
+ "person": 1,
+ "place": 2,
+ "post": 1,
+ "proof": 2,
+ "sheet": 2,
+ "structure": 1,
+ "vessel": 1
+ },
+ "unfiled": 44
+ },
"countable": 1,
"lacks": {
"assessment": 6,
diff --git a/tests/test_cases_api.py b/tests/test_cases_api.py
index 647d696..15d6150 100644
--- a/tests/test_cases_api.py
+++ b/tests/test_cases_api.py
@@ -51,6 +51,42 @@ def test_list_cases_respects_limit(client):
assert len(client.get("/api/cases", params={"limit": 2}).json()) == 2
+def test_case_search_folds_accents_and_matches_each_word(client, monkeypatch):
+ for name in ("Étude du port", "Proof geo", "Other work"):
+ client.post("/api/cases", json={"name": name})
+ opened = []
+ original = Case.entity_count
+
+ def count(case):
+ opened.append(case.id)
+ return original(case)
+
+ monkeypatch.setattr(Case, "entity_count", count)
+ hits = client.get("/api/cases", params={"q": " PORT etude "}).json()
+ assert [case["name"] for case in hits] == ["Étude du port"]
+ assert opened == ["Étude du port"]
+ hits = client.get("/api/cases", params={"q": "geo proof"}).json()
+ assert [case["name"] for case in hits] == ["Proof geo"]
+
+
+def test_catalog_relevance_ranks_across_pages_with_folded_names(client):
+ cid = client.post("/api/cases", json={"name": "Harbour"}).json()["id"]
+ case = Case.open(cid)
+ for label in ("Airport", "Notes from Port", "Pórt Sudan", "Port"):
+ case.add_entity("note", label, {}, by="user")
+ params = {"q": "port", "order": "relevance", "limit": 2}
+ first = client.get(f"/api/cases/{cid}/catalog/entities", params=params)
+ assert first.status_code == 200
+ page = first.json()
+ assert page["total"] == 4
+ assert [item["label"] for item in page["items"]] == ["Port", "Pórt Sudan"]
+ second = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={**params, "cursor": page["next_cursor"]}
+ ).json()
+ assert [item["label"] for item in second["items"]] == ["Notes from Port", "Airport"]
+ assert second["next_cursor"] is None
+
+
def test_case_lifecycle(client):
created = client.post("/api/cases", json={"name": "Kharkiv Strike"}).json()
# The folder is the name the analyst typed, the way every other saved thing
@@ -425,6 +461,34 @@ def test_catalog_filters_by_folder(client):
assert client.get(f"/api/cases/{cid}/catalog/summary").json()["by_folder"] == {"Alpha": 1}
+def test_catalog_summary_counts_accepted_rows_apart(client):
+ """Files, the sidebar and Home's Unfiled list accepted rows only, with suggestions
+ under review. Counted over every row, Home said 18 unfiled where the sidebar
+ beside it said 15."""
+ cid = client.post("/api/cases", json={"name": "Review"}).json()["id"]
+ client.post(f"/api/cases/{cid}/folders", json={"name": "Alpha"})
+ for label, folder, status in (
+ ("kept", "Alpha", "confirmed"),
+ ("loose", None, "confirmed"),
+ ("proposed", None, "suggested"),
+ ("proposed here", "Alpha", "suggested"),
+ ):
+ attrs = {"folder": folder} if folder else {}
+ client.post(
+ f"/api/cases/{cid}/entities",
+ json={"type": "person", "label": label, "attrs": attrs, "status": status},
+ )
+
+ summary = client.get(f"/api/cases/{cid}/catalog/summary").json()
+
+ assert summary["by_folder"] == {"Alpha": 2}
+ assert summary["confirmed"] == {"by_type": {"person": 2}, "by_folder": {"Alpha": 1}, "unfiled": 1}
+ sidebar = client.get(
+ f"/api/cases/{cid}/catalog/entities", params={"unfiled": "true", "status": "confirmed"}
+ ).json()
+ assert sidebar["total"] == summary["confirmed"]["unfiled"]
+
+
def test_catalog_searches_notes_and_descendant_folders(client):
cid = client.post("/api/cases", json={"name": "Search"}).json()["id"]
client.post(
diff --git a/tests/test_geo_api.py b/tests/test_geo_api.py
index 89f5ebc..496a672 100644
--- a/tests/test_geo_api.py
+++ b/tests/test_geo_api.py
@@ -94,6 +94,17 @@ def test_geocode_empty_query_is_422(client):
assert response.status_code == 422
+def test_geocode_reads_a_coordinate_without_the_network(client, monkeypatch):
+ """A Sheet cell already holding coordinates is a point, not a place name to send out."""
+ calls = []
+ monkeypatch.setattr(geo.httpx, "get", lambda *a, **k: calls.append(k) or _FakeResponse([]))
+
+ body = client.get("/api/geo/geocode", params={"q": "50.4501, 30.5234"}).json()
+
+ assert body == {"lat": 50.4501, "lon": 30.5234, "display_name": None, "attribution": None}
+ assert calls == []
+
+
def test_geocode_network_failure_is_404(client, monkeypatch):
def boom(*args, **kwargs):
raise OSError("network down")
@@ -505,3 +516,14 @@ def test_places_reports_a_throttled_geocoder_instead_of_an_empty_list(client, mo
def test_places_empty_query_is_422(client):
assert client.get("/api/geo/places", params={"q": " "}).status_code == 422
+
+
+def test_places_never_sends_a_typed_coordinate_to_the_geocoder(client, monkeypatch):
+ """A search bar left alone past its debounce asked Nominatim for "50.4501, 30.5234"."""
+ calls = []
+ monkeypatch.setattr(geo.httpx, "get", lambda *a, **k: calls.append(k) or _FakeResponse([]))
+
+ for typed in ("50.4501, 30.5234", "50°27'00.4\"N 30°31'24.2\"E", "36SYC8418406297"):
+ body = client.get("/api/geo/places", params={"q": typed}).json()
+ assert body == {"places": [], "busy": False, "throttled": False, "attribution": None}
+ assert calls == []
diff --git a/tests/test_updates.py b/tests/test_updates.py
index 8da4175..8b18c0a 100644
--- a/tests/test_updates.py
+++ b/tests/test_updates.py
@@ -138,7 +138,7 @@ def test_update_endpoint_with_check_queries_github(client, monkeypatch):
# The pair below is the contract, and it moves in one direction only: when a
# shipped file really changes, set the manifest to the current __version__ and
# record the new digest here (the failing test prints it).
-EXTENSION_VERSION = "0.3.1"
+EXTENSION_VERSION = "0.3.2"
EXTENSION_PAYLOAD = "39ae74f8fbe3eee32a95f5c73816bb6c6a4dd424a26004a48e527261325227c6"
# The digest itself lives in engine/extinstall.py, because the update button