bjomarks-gui/tests/app.bjo

1228 lines
67 KiB
Text
Raw Normal View History

;; This Source Code Form is subject to the terms of the Mozilla Public
;; License, v. 2.0. If a copy of the MPL was not distributed with this
;; file, You can obtain one at http://mozilla.org/MPL/2.0/.
;; bjomarks-gui/tests/app.bjo — the window, driven through its controls.
;;
;; bjo run tests/app.bjo # prints "bjomarks-gui ok"
;;
;; Avalonia runs with no screen, and the app is shown in a window of it. Keys
;; are pressed with Avalonia's headless keyboard, so that they go where real
;; keys go: to the control with the keyboard first, then to the window's
;; keys, as `run-app` hears them. The vault is made in a folder of the temp
;; directory, with the default cost of Argon2id. Titles and archive links
;; are fetched only from a server on the loopback: no site on the internet
;; is asked.
(import (std prelude))
(import (std simpletest))
(import (std interop))
(import (std os))
(import (std uuid))
(import (std net))
(import (std ports))
(import (std inbox))
(import (bjogui view))
(import (bjogui app))
(import (bjomarks bookmark))
(import (bjomarks store))
(import (bjomarks-gui inputs))
(import (bjomarks-gui browser))
(import (bjomarks-gui app))
(import (bjomarks draft))
(import (bjomarks search))
(import (bjomarks duplicates))
(import (bjomarks-gui settings))
(import/class
(Object (: System.Object))
(Control (: Avalonia.Controls.Control))
(Window (: Avalonia.Controls.Window (-> Window)))
(TopLevel (: Avalonia.Controls.TopLevel))
(Visual (: Avalonia.Visual))
(ContentControl (: Avalonia.Controls.ContentControl))
(Layoutable (: Avalonia.Layout.Layoutable))
(InputElement (: Avalonia.Input.InputElement))
(TextBox (: Avalonia.Controls.TextBox))
(Interactive (: Avalonia.Interactivity.Interactive))
(RoutedEvent (: Avalonia.Interactivity.RoutedEvent))
(RoutedEventArgs (: Avalonia.Interactivity.RoutedEventArgs (-> RoutedEvent RoutedEventArgs)))
(Panel (: Avalonia.Controls.Panel))
(Controls (: Avalonia.Controls.Controls))
(Arc (: Avalonia.Controls.Shapes.Arc))
(StyledElement (: Avalonia.StyledElement))
(Classes (: Avalonia.Controls.Classes))
(Routes (: Avalonia.Interactivity.RoutingStrategies))
(KeyEventArgs (: Avalonia.Input.KeyEventArgs))
(KeyCode (: Avalonia.Input.Key))
(KeyModifiers (: Avalonia.Input.KeyModifiers))
(KeyGesture (: Avalonia.Input.KeyGesture (-> KeyCode KeyModifiers KeyGesture)))
(RawMods (: Avalonia.Input.RawInputModifiers))
(PhysicalKey (: Avalonia.Input.PhysicalKey))
(UnixMode (: System.IO.UnixFileMode))
((EventHandler %a) (: System.EventHandler)))
(import/extern
(content! (: Avalonia.Controls.ContentControl.Content (-> ContentControl Object void) #:set))
(show! (: Avalonia.Controls.Window.Show (-> Window void)))
(width! (: Avalonia.Layout.Layoutable.Width (-> Layoutable double void) #:set))
(height! (: Avalonia.Layout.Layoutable.Height (-> Layoutable double void) #:set))
(update-layout! (: Avalonia.Layout.Layoutable.UpdateLayout (-> Layoutable void)))
(top-level-of (: Avalonia.Controls.TopLevel.GetTopLevel (-> Visual TopLevel)))
(focused? (: Avalonia.Input.InputElement.IsFocused (-> InputElement bool) #:get))
(focus-within? (: Avalonia.Input.InputElement.IsKeyboardFocusWithin (-> InputElement bool) #:get))
(box-text (: Avalonia.Controls.TextBox.Text (-> TextBox string) #:get))
(key-press! (: Avalonia.Headless.HeadlessWindowExtensions.KeyPress
(-> TopLevel KeyCode RawMods PhysicalKey string void)))
(key-release! (: Avalonia.Headless.HeadlessWindowExtensions.KeyRelease
(-> TopLevel KeyCode RawMods PhysicalKey string void)))
(type-text! (: Avalonia.Headless.HeadlessWindowExtensions.KeyTextInput (-> TopLevel string void)))
(key-down-event (: Avalonia.Input.InputElement.KeyDownEvent #:get))
(add-handler (: Avalonia.Interactivity.Interactive.AddHandler
(-> Interactive RoutedEvent Delegate Routes bool void)))
(handled! (: Avalonia.Interactivity.RoutedEventArgs.Handled (-> RoutedEventArgs bool void) #:set))
(key-of (: Avalonia.Input.KeyEventArgs.Key (-> KeyEventArgs KeyCode) #:get))
(modifiers-of (: Avalonia.Input.KeyEventArgs.KeyModifiers (-> KeyEventArgs KeyModifiers) #:get))
(gesture-text (: Avalonia.Input.KeyGesture.ToString (-> KeyGesture string)))
(sleep-ms (: System.Threading.Thread.Sleep (-> int void) #:blocking))
(raise-event! (: Avalonia.Interactivity.Interactive.RaiseEvent (-> Interactive RoutedEventArgs void)))
(click-event (: Avalonia.Controls.Button.ClickEvent #:get))
(content-of (: Avalonia.Controls.ContentControl.Content (-> ContentControl Object) #:get))
(children-of (: Avalonia.Controls.Panel.Children (-> Panel Controls) #:get))
(child-at (: Avalonia.Controls.Controls.get_Item (-> Controls int Control)))
(visible? (: Avalonia.Visual.IsVisible (-> Visual bool) #:get))
(opacity-of (: Avalonia.Visual.Opacity (-> Visual double) #:get))
(start-angle-of (: Avalonia.Controls.Shapes.Arc.StartAngle (-> Arc double) #:get))
(classes-of (: Avalonia.StyledElement.Classes (-> StyledElement Classes) #:get))
(has-class? (: Avalonia.Controls.Classes.Contains (-> Classes string bool)))
(render-ticks! (: Avalonia.Headless.AvaloniaHeadlessPlatform.ForceRenderTimerTick (-> int void)))
(set-mode! (: System.IO.File.SetUnixFileMode (-> string UnixMode void))))
;; The window's keys, as `run-app` hears them: what the control with the
;; keyboard did not handle goes to `app-press!`.
(: (-> Window (App Model Msg) void))
(defun (listen-keys! w app)
(add-handler (cast Interactive w) (cast RoutedEvent key-down-event)
(cast Delegate (cast Object (: (as-delegate (: (fun (s e)
(def k (cast KeyEventArgs e))
(when (app-press! app (gesture-text (KeyGesture. (key-of k) (modifiers-of k))))
(handled! e #t)))
(-> Object RoutedEventArgs void)))
(EventHandler RoutedEventArgs))))
Routes.Bubble #f))
;; Presses and lets go of a key, as the keyboard does.
(: (-> TopLevel KeyCode RawMods PhysicalKey void))
(defun (press w code mods physical)
(key-press! w code mods physical "")
(key-release! w code mods physical ""))
(: (-> TopLevel void))
(defun (ctrl-n w) (press w KeyCode.N RawMods.Control PhysicalKey.N))
(: (-> TopLevel void))
(defun (ctrl-p w) (press w KeyCode.P RawMods.Control PhysicalKey.P))
;; Enter closes the dialog it is pressed in, so there is no window to let go
;; of it in.
(: (-> TopLevel void))
(defun (enter w) (key-press! w KeyCode.Enter RawMods.None PhysicalKey.Enter ""))
;; Escape closes the dialog too.
(: (-> TopLevel void))
(defun (escape w) (key-press! w KeyCode.Escape RawMods.None PhysicalKey.Escape ""))
(: (-> Model (Vec string)))
(defun (shown-urls m) (vec-map #(.url &) (visible-bookmarks m)))
(: (-> Model Vault))
(defun (vault-of m)
(match (.vault m)
((Some v) v)
(None (panic! "no vault"))))
;; The labels of the menu items in a view, depth first.
(: (-> (View Msg) (Vec string)))
(defun (menu-labels v)
(def own (if (= (view-kind v) MenuItemKind)
(vec-fold (fun (p acc) (match p ((PropLabel s) (vec-add acc s)) (_ acc))) [] (view-props v))
[]))
(vec-fold (fun (c acc) (vec-append acc (menu-labels c))) own (view-children v)))
;; The texts in a view, depth first.
(: (-> (View Msg) (Vec string)))
(defun (view-texts v)
(def own (if (= (view-kind v) TextKind)
(vec-fold (fun (p acc) (match p ((PropLabel s) (vec-add acc s)) (_ acc))) [] (view-props v))
[]))
(vec-fold (fun (c acc) (vec-append acc (view-texts c))) own (view-children v)))
;; The labels of the buttons in a view, depth first.
(: (-> (View Msg) (Vec string)))
(defun (button-labels v)
(def own (if (= (view-kind v) ButtonKind)
(vec-fold (fun (p acc) (match p ((PropLabel s) (vec-add acc s)) (_ acc))) [] (view-props v))
[]))
(vec-fold (fun (c acc) (vec-append acc (button-labels c))) own (view-children v)))
(: (-> (View Msg) int))
(defun (context-menus v)
(vec-fold (fun (c n) (+ n (context-menus c))) (if (= (view-kind v) ContextKind) 1 0) (view-children v)))
;; ---- A server on the loopback, for the titles and the archive links ------------------
;;
;; The pages of the bookmarks whose titles are fetched are here, so that the
;; test asks no site on the internet. The server also answers as the Wayback
;; Machine's availability API does, at `/wayback/available`.
(: string)
(def wayback-path "/wayback/available?url=")
;; The answer of the API for the page `url`: a snapshot of it, at an http
;; address as the API gives, or none for the pages that end in "/untitled".
(: (-> string string))
(defun (wayback-answer url)
(if (string-ends-with? url "/untitled")
(str "{\"url\": \"" url "\", \"archived_snapshots\": {}}")
(str "{\"url\": \"" url "\", \"archived_snapshots\": {\"closest\": {\"status\": \"200\", "
"\"available\": true, \"url\": \"http://web.archive.org/web/20260101000000/" url "\", "
"\"timestamp\": \"20260101000000\"}}}")))
;; The status and the body for a path.
(: (-> string (Tuple string string)))
(defun (page-for path)
(if (string-starts-with? path wayback-path)
(Tuple "200 OK" (wayback-answer (string-drop path (string-length wayback-path))))
(page-at path)))
(: (-> string (Tuple string string)))
(defun (page-at path)
(match path
("/titled" (Tuple "200 OK" "<html><head><title>A local page</title></head></html>"))
("/later" (Tuple "200 OK" "<html><head><title>Later page</title></head></html>"))
("/untitled" (Tuple "200 OK" "<html><head></head><body>none</body></html>"))
;; Answered after `slow-ms`, as is the API's answer for it.
("/slow" (Tuple "200 OK" "<html><head><title>A slow page</title></head></html>"))
(_ (Tuple "404 Not Found" ""))))
(: long)
(def slow-ms 1500L)
;; "GET /titled HTTP/1.1" gives "/titled".
(: (-> string string))
(defun (path-of head)
(def line (match (string-split-once head "\r\n") ((Some (Tuple l _)) l) (None head)))
(def parts (string-split line " "))
(if (>= (vec-length parts) 2) (vec-ref parts 1) "/"))
(: (-bjo-> InputPort string))
(defbjo (request-path in)
(let go ((seen ""))
(if (string-contains? seen "\r\n\r\n")
(path-of seen)
(match (read-some in)
((Some bs) (go (str seen (bytes->string bs))))
(None (path-of seen))))))
;; One request, one page. The path is added to `asked`.
(: (-bjo-> (Box (Vec string)) InputPort OutputPort void))
(defbjo (answer asked in out)
(def path (request-path in))
(box-set! asked (vec-add (box-ref asked) path))
(when (string-ends-with? path "/slow") (ignore (sync (timeout (milliseconds slow-ms)))))
(def (Tuple status body) (page-for path))
(def bytes (string->bytes body))
(write-bytes! out (string->bytes (str "HTTP/1.1 " status "\r\nContent-Type: text/html; charset=utf-8\r\n"
"Content-Length: " (int->string (array-length bytes)) "\r\n"
"Connection: close\r\n\r\n")))
(write-bytes! out bytes)
(flush-port out)
(close-input-port in)
(close-output-port out))
;; Listens on a port that the system gives, puts it in `port` (-1 when it
;; cannot listen), and answers until `stop` gets a message.
(: (-bjo-> (Box int) (Box (Vec string)) (Inbox int) void))
(defbjo (title-server port asked stop)
(match (tcp-listen "127.0.0.1" 0)
((Err _) (box-set! port -1))
((Ok l)
(with-open ((listening l))
(box-set! port (listener-port l))
(let go ()
(match (sync (choose (wrap (accept-evt l) Some) (wrap (inbox-recv stop) (fun (_) None))))
((Some (Ok (Tuple in out))) (answer asked in out) (go))
((Some (Err _)) unit)
(None unit)))))))
(defun (main)
;; --- the search, on bookmarks that are in no vault ---------------------------------
(: (-> string string (Vec string) Bookmark))
(defun (example url title tags)
(match (make-bookmark url #:title (Some title) #:tags tags)
((Ok b) b)
((Err why) (panic! why))))
(def both (example "https://example.org/banana-bread" "Banana bread" ["mytag" "nice"]))
(def one (example "https://example.org/banana-split" "Banana split" ["nice"]))
(def apple (example "https://example.org/apple" "Apple pie" ["MyTag" "nice"]))
(: (-> string (Vec string)))
(defun (found text)
(vec-map #(.url &) (vec-filter (fun (b) (matches? (parse-query text) b)) [both one apple])))
(expect "tag:mytag tag:nice banana: both tags, and banana"
(found "tag:mytag tag:nice banana") ["https://example.org/banana-bread"])
(expect "one tag" (found "tag:nice banana")
["https://example.org/banana-bread" "https://example.org/banana-split"])
(expect "tags in any case" (found "TAG:mytag") ["https://example.org/banana-bread" "https://example.org/apple"])
(expect "a tag is whole: tag:my is not mytag" (found "tag:my") [])
(expect "a word is looked for in the tags too" (found "nice")
["https://example.org/banana-bread" "https://example.org/banana-split" "https://example.org/apple"])
(expect "tag: with nothing after it is no tag" (.words (parse-query "tag: Banana")) ["banana"])
(expect "the order does not matter" (found "banana tag:nice tag:mytag") ["https://example.org/banana-bread"])
(start-headless!)
(def root (make-temp-directory #:prefix "bjomarks-gui-test-"))
(def shared (folder-storage (path-combine root "shared")))
(def here (path-combine root "laptop"))
(def w (Window.))
(width! (cast Layoutable w) 640.0)
(height! (cast Layoutable w) 520.0)
;; The server of the titles and of the archive links. It starts before the
;; app, which is given its address as the Wayback Machine's.
(def server-port (make-box 0))
(def asked (make-box (: [] (Vec string))))
(def stop (make-inbox 1 DropNewest))
(def server (bjo (title-server server-port asked stop)))
(let go ((tries 0))
(when (and (= (box-ref server-port) 0) (< tries 1000))
(sleep-ms 10)
(go (+ tries 1))))
(def base (str "http://127.0.0.1:" (int->string (box-ref server-port))))
(def titled (str base "/titled"))
(def untitled (str base "/untitled"))
(def slow (str base "/slow"))
(def app (start-app (initial-model shared here #:wayback (str base "/wayback/available")) gui-update view
(fun (c) (content! (cast ContentControl w) (cast Object c)))
#:windows windows #:keys keys))
(show! w)
(listen-keys! w app)
(def top (cast TopLevel w))
(defun (model) (app-model app))
(defun (ctl path) (app-control-at app path))
(defun (settle) (app-run-pending! app) (update-layout! (cast Layoutable w)))
(: (-> (-> bool) bool))
(defun (wait-for done?)
(let go ((tries 0))
(settle)
(cond ((done?) #t)
((> tries 1000) #f)
(else (sleep-ms 10) (go (+ tries 1))))))
(defun (idle?) (and (not (.saving (model))) (not (vault-dirty? (vault-of (model))))))
;; The controls of the main view: the toolbar's grid, and the list, after
;; the line at the bottom and the touch bar.
(defun (search-control) (ctl '(0 2)))
(defun (list-control) (ctl '(3)))
(settle)
;; --- making a vault -----------------------------------------------------------
(expect "an empty folder: the first screen makes a vault" (.start (model)) CreateNew)
;; The two password boxes of the first screen.
(defun (first-box) (cast InputElement (ctl '(4))))
(defun (second-box) (cast InputElement (ctl '(5))))
(expect "the password box has the keyboard when the window opens" (wait-for (fun () (focused? (first-box)))) #t)
(type-text! top "correct horse")
(settle)
(expect "what is typed is the password" (.password (model)) "correct horse")
(app-dispatch! app Unlock)
(expect "the password is asked twice" (.lock-problem (model)) "The two passwords are not the same.")
(press top KeyCode.Enter RawMods.None PhysicalKey.Enter)
(settle)
(expect "Enter in the first box of a new vault goes to the second"
(wait-for (fun () (focused? (second-box)))) #t)
(expect "and makes no vault yet" (.phase (model)) Locked)
(type-text! top "correct horse")
(settle)
(expect "what is typed there is the password again" (.again (model)) "correct horse")
(press top KeyCode.Enter RawMods.None PhysicalKey.Enter)
(settle)
(expect "Enter in the second box makes the vault" (.phase (model)) Unlocking)
(expect "the vault is made in the background" (wait-for (fun () (= (.phase (model)) Open))) #t)
(expect "the search box has the keyboard" (wait-for (fun () (focused? (cast InputElement (search-control))))) #t)
(expect "this device's file is written"
(file-exists? (path-combine root "shared" "devices"
(device-file-name (vault-device (vault-of (model)))))) #t)
;; --- new bookmarks --------------------------------------------------------------
(app-dispatch! app New)
(expect "New opens the dialog" (app-windows app) '("draft"))
(app-dispatch! app (DraftUrl "example.org"))
(app-dispatch! app SaveDraft)
(expect "an address that is not absolute is refused"
(match (.draft (model)) ((Some d) (.problem d)) (None "")) "Not an absolute URL: example.org")
(app-dispatch! app (DraftUrl "https://example.org/rust-async"))
(app-dispatch! app (DraftTitle " Async\n Rust "))
(app-dispatch! app (DraftTags "rust, async"))
(settle)
(def dialog (top-level-of (cast Visual (app-window-control app "draft" '()))))
(enter dialog)
(settle)
(expect "Enter in the dialog saves" (shown-urls (model)) ["https://example.org/rust-async"])
(expect "and closes it" (app-windows app) '())
(expect "the tags are split" (.tags (vec-ref (visible-bookmarks (model)) 0)) ["async" "rust"])
(expect "the title is one line" (.title (vec-ref (visible-bookmarks (model)) 0)) (Some "Async Rust"))
(expect "the change is saved in the background" (wait-for idle?) #t)
(expect "and said so" (.status (model)) "Saved.")
(def revision (vault-revision (vault-of (model))))
;; Two more, the second while the first one's sync may still run.
(defun (add! url title tags)
(app-dispatch! app New)
(app-dispatch! app (DraftUrl url))
(app-dispatch! app (DraftTitle title))
(app-dispatch! app (DraftTags tags))
(app-dispatch! app SaveDraft))
(add! "https://bjolang.org/manual" "The Bjolang manual" "docs")
(add! "https://doc.rust-lang.org/book/" "The Rust Programming Language" "rust docs")
(expect "both are shown" (vec-length (visible-bookmarks (model))) 3)
(expect "and saved" (wait-for idle?) #t)
(expect "with newer revisions" (> (vault-revision (vault-of (model))) revision) #t)
;; --- an address that is here already, typed in the dialog of a new bookmark --------
(: (-> Draft))
(defun (open-draft)
(match (.draft (model))
((Some d) d)
(None (panic! "the dialog is not open"))))
(defun (dialog-top) (top-level-of (cast Visual (app-window-control app "draft" '()))))
(def manuals (vec-filter (fun (b) (= (.url b) "https://bjolang.org/manual")) (vault-bookmarks (vault-of (model)))))
(def manual (if (vec-empty? manuals) (panic! "no manual") (vec-ref manuals 0)))
;; The id of the bookmark that the dialog edits; a new id for none.
(defun (editing-id) (match (.editing (open-draft)) ((Some b) (.id b)) (None (uuid-v4))))
(app-dispatch! app New)
(app-dispatch! app (DraftTitle "Typed first"))
(settle)
;; Typed into the address field, which has the keyboard.
(type-text! (dialog-top) "https://bjolang.org/manua")
(settle)
(expect "an address that no bookmark has is a new bookmark" (.editing (open-draft)) None)
(type-text! (dialog-top) "l")
(settle)
(expect "the address of a bookmark loads that bookmark" (editing-id) (.id manual))
(expect "with its title and tags" (Tuple (.title (open-draft)) (.tags (open-draft))) (Tuple "The Bjolang manual" "docs"))
(expect "and the dialog says so" (.problem (open-draft)) "This address is here already: this is its bookmark.")
(expect "the address is as typed" (.url (open-draft)) "https://bjolang.org/manual")
(type-text! (dialog-top) "/more")
(settle)
(expect "typing on makes it a new bookmark again" (.editing (open-draft)) None)
(expect "with what was typed before" (.title (open-draft)) "Typed first")
(expect "and the tags it had" (.tags (open-draft)) "")
(expect "and no message" (.problem (open-draft)) "")
(app-dispatch! app (DraftUrl " https://bjolang.org/manual "))
(expect "the spaces at the ends do not count" (some? (.editing (open-draft))) #t)
(app-dispatch! app (DraftTags "docs manual"))
(app-dispatch! app (DraftUrl "https://bjolang.org/manual"))
(expect "the edits to the bookmark loaded are kept while its address stays" (.tags (open-draft)) "docs manual")
(app-dispatch! app SaveDraft)
(expect "saving changes that bookmark" (match (vault-find (vault-of (model)) (.id manual)) ((Some b) (.tags b)) (None []))
["docs" "manual"])
(expect "and adds none" (vec-length (vault-bookmarks (vault-of (model)))) 3)
(expect "which is saved" (wait-for idle?) #t)
(app-dispatch! app (Edit (.id manual)))
(app-dispatch! app (DraftUrl "https://example.org/rust-async"))
(expect "a dialog that edits a bookmark does not load another" (editing-id) (.id manual))
(app-dispatch! app CancelDraft)
;; --- the context menu --------------------------------------------------------------
(def main-view (view (model)))
(expect "each bookmark has a menu" (context-menus main-view) 3)
(expect "to open, copy, edit or remove it" (vec-take (menu-labels main-view) 5)
["Open" "Open in private window" "Copy address" "Edit" "Remove"])
(expect "the same for each" (vec-length (menu-labels main-view)) 15)
(expect "the second line starts with the day it was added"
(vec-length (vec-filter (fun (t) (and (> (string-length t) 10)
(= (string-take (string-drop t 4) 1) "-") (= (string-take (string-drop t 7) 1) "-")
(not (string-contains? t "added "))))
(view-texts main-view)))
3)
(expect "with no settings, no Other bookmarks" (vec-contains? (button-labels main-view) "Other bookmarks…") #f)
(def first-url (.url (vec-ref (visible-bookmarks (model)) 0)))
(app-dispatch! app (CopyAddress (.id (vec-ref (visible-bookmarks (model)) 0))))
(expect "Copy address" (.note (model)) (str "Copied " first-url "."))
(app-dispatch! app (OpenedPrivately first-url (Ok (Err "No private window"))))
(expect "no private window: the address is copied"
(.note (model)) "No private window. The address is copied: paste it in a private window.")
(app-dispatch! app (OpenedPrivately first-url (Ok (Err "No private window here."))))
(expect "with one period" (.note (model)) "No private window here. The address is copied: paste it in a private window.")
(app-dispatch! app (OpenedPrivately first-url (Ok (Ok "Opened it"))))
(expect "or the browser opened it" (.note (model)) "Opened it")
;; --- searching and the keys ---------------------------------------------------------
(app-dispatch! app (Search (SearchTyped "")))
(app-dispatch! app (Select 1))
(app-dispatch! app Prev)
(app-dispatch! app Prev)
(expect "Ctrl+P on the first bookmark goes back to the search box"
(wait-for (fun () (focused? (cast InputElement (search-control))))) #t)
(type-text! top "RUST")
(settle)
(expect "what is typed is the search" (.query (model)) "RUST")
(expect "it filters as it is typed, in any case" (shown-urls (model))
["https://doc.rust-lang.org/book/" "https://example.org/rust-async"])
(type-text! top " programming")
(settle)
(expect "each word must match, in the title or the address" (shown-urls (model)) ["https://doc.rust-lang.org/book/"])
(type-text! top " qqq")
(settle)
(expect "nothing matches" (shown-urls (model)) [])
(ctrl-n top)
(settle)
(expect "Ctrl+N with nothing shown does nothing" (.selected (model)) -1)
(app-dispatch! app (Search (SearchTyped "docs")))
(expect "the tags are searched too" (shown-urls (model))
["https://doc.rust-lang.org/book/" "https://bjolang.org/manual"])
(app-dispatch! app (Search (SearchTyped "Bjolang MANUAL")))
(expect "the title and the address are" (shown-urls (model)) ["https://bjolang.org/manual"])
(app-dispatch! app (Search (SearchTyped "language")))
(expect "the title alone matches" (shown-urls (model)) ["https://doc.rust-lang.org/book/"])
(app-dispatch! app (Search (SearchTyped "tag:rust")))
(expect "tag: shows the bookmarks with the tag" (shown-urls (model))
["https://doc.rust-lang.org/book/" "https://example.org/rust-async"])
(app-dispatch! app (Search (SearchTyped "tag:rust tag:DOCS")))
(expect "each tag: must be a tag of the bookmark" (shown-urls (model)) ["https://doc.rust-lang.org/book/"])
(app-dispatch! app (Search (SearchTyped "tag:rust async")))
(expect "and each other word in its title or address" (shown-urls (model)) ["https://example.org/rust-async"])
(app-dispatch! app (Search (SearchTyped "rust")))
(settle)
(expect "the search box shows the search" (box-text (cast TextBox (search-control))) "rust")
(expect "the search box still has the keyboard" (focused? (cast InputElement (search-control))) #t)
(ctrl-n top)
(settle)
(expect "Ctrl+N in the search box goes to the first bookmark" (.selected (model)) 0)
(expect "and gives the list the keyboard" (wait-for (fun () (focus-within? (cast InputElement (list-control))))) #t)
(expect "which the search box has no more" (focused? (cast InputElement (search-control))) #f)
(ctrl-n top)
(settle)
(expect "Ctrl+N in the list goes to the next" (.selected (model)) 1)
(ctrl-n top)
(settle)
(expect "and stops at the last" (.selected (model)) 1)
(ctrl-p top)
(settle)
(expect "Ctrl+P goes to the one before" (.selected (model)) 0)
(ctrl-p top)
(settle)
(expect "and from the first, to the search box" (.selected (model)) -1)
(expect "with the keyboard" (wait-for (fun () (focused? (cast InputElement (search-control))))) #t)
(ctrl-n top)
(settle)
(expect "so that Ctrl+N goes to the first again, not the next" (.selected (model)) 0)
(expect "the list has the keyboard" (wait-for (fun () (focus-within? (cast InputElement (list-control))))) #t)
(press top KeyCode.S RawMods.Control PhysicalKey.S)
(settle)
(expect "Ctrl+S in the list gives the search box the keyboard"
(wait-for (fun () (focused? (cast InputElement (search-control))))) #t)
(expect "with the search as it was" (.query (model)) "rust")
(press top KeyCode.S RawMods.Control PhysicalKey.S)
(settle)
(expect "Ctrl+S in the search box leaves it there" (focused? (cast InputElement (search-control))) #t)
(expect "and types nothing" (.query (model)) "rust")
;; --- editing and removing -------------------------------------------------------------
(def rust-book (vec-ref (visible-bookmarks (model)) 0))
(app-dispatch! app (Edit (.id rust-book)))
(expect "Edit fills the dialog"
(match (.draft (model)) ((Some d) (Tuple (.url d) (.title d) (.tags d))) (None (Tuple "" "" "")))
(Tuple "https://doc.rust-lang.org/book/" "The Rust Programming Language" "docs rust"))
(app-dispatch! app (DraftTags "rust book"))
(app-dispatch! app (DraftArchive "https://web.archive.org/web/2026/https://doc.rust-lang.org/book/"))
(app-dispatch! app SaveDraft)
(def edited (match (vault-find (vault-of (model)) (.id rust-book)) ((Some b) b) (None rust-book)))
(expect "the edit is kept" (.tags edited) ["book" "rust"])
(expect "with its archive link" (.archive edited)
(Some "https://web.archive.org/web/2026/https://doc.rust-lang.org/book/"))
(expect "and saved" (wait-for idle?) #t)
(app-dispatch! app (Edit (.id rust-book)))
(app-dispatch! app (DraftArchive "not a link"))
(app-dispatch! app SaveDraft)
(expect "a bad archive link is refused" (match (.draft (model)) ((Some d) (.problem d)) (None ""))
"The archive link is not an absolute URL: not a link")
(app-dispatch! app CancelDraft)
;; Bound first: `(.archive (match ...))` makes C# that does not compile.
(def after-cancel (match (vault-find (vault-of (model)) (.id rust-book)) ((Some b) b) (None rust-book)))
(expect "Cancel keeps the bookmark as it was" (.archive after-cancel) (.archive edited))
;; --- the keys on the chosen bookmark ----------------------------------------------------
;; The list shows "rust": the book, then rust-async. The book is chosen, and
;; the list has the keyboard.
(app-dispatch! app (Search (SearchTyped "rust")))
(app-dispatch! app (Search SearchNext))
(expect "the list has the keyboard" (wait-for (fun () (focus-within? (cast InputElement (list-control))))) #t)
(expect "and the search box knows it has it no more" (.search-focused (model)) #f)
(press top KeyCode.E RawMods.None PhysicalKey.E)
(settle)
(expect "E alone does nothing" (.draft (model)) None)
(press top KeyCode.E RawMods.Control PhysicalKey.E)
(settle)
(expect "Ctrl+E edits the chosen bookmark"
(match (.draft (model)) ((Some d) (.url d)) (None "")) "https://doc.rust-lang.org/book/")
(escape (top-level-of (cast Visual (app-window-control app "draft" '()))))
(settle)
(expect "Escape closes the dialog" (app-windows app) '())
;; Enter, with BJOMARKS_BROWSER: a script that writes down what it is given.
(def opened (path-combine root "opened.txt"))
(def script (path-combine root "browser.sh"))
(file-write-text script (str "#!/bin/sh\nprintf '%s\\n' \"$1\" >> '" opened "'\n"))
(set-mode! script (cast UnixMode 448))
(set-environment-variable! "BJOMARKS_BROWSER" script)
(app-dispatch! app (Select 0))
(app-dispatch! app (Search (SearchFocus #f)))
(press top KeyCode.O RawMods.None PhysicalKey.O)
(settle)
(expect "O alone does nothing" (file-exists? opened) #f)
(press top KeyCode.Enter RawMods.None PhysicalKey.Enter)
(expect "Enter opens the chosen bookmark in the browser"
(wait-for (fun () (and (file-exists? opened)
(= (file-read-text opened) "https://doc.rust-lang.org/book/\n"))))
#t)
(expect "and says so" (wait-for (fun () (= (.note (model)) "Opened https://doc.rust-lang.org/book/"))) #t)
;; With no BJOMARKS_BROWSER, the system opens it: on Linux, xdg-open. A
;; fake one, first on the PATH, writes down what it is given, so that no
;; browser is started.
(when (linux?)
(def fake-bin (path-combine root "bin"))
(directory-create fake-bin)
(def fake (path-combine fake-bin "xdg-open"))
(def seen (path-combine root "xdg-open.txt"))
(file-write-text fake (str "#!/bin/sh\nprintf '%s\\n' \"$1\" >> '" seen "'\n"))
(set-mode! fake (cast UnixMode 448))
;; A fake host-spawn too, first on the PATH: this test can run in a
;; container that distrobox made, and the real one would open a browser
;; on the host.
(def spawn (path-combine fake-bin "host-spawn"))
(def spawned (path-combine root "host-spawn.txt"))
(file-write-text spawn (str "#!/bin/sh\nprintf '%s\\n' \"$@\" > '" spawned "'\n"))
(set-mode! spawn (cast UnixMode 448))
(set-environment-variable! "BJOMARKS_BROWSER" "")
(set-environment-variable! "PATH" (str fake-bin ":" (option-ref-or (get-environment-variable "PATH") "")))
(expect "BJOMARKS_BROWSER is unset" (get-environment-variable "BJOMARKS_BROWSER") None)
(expect "out of a container, xdg-open is given the address"
(open-in-browser "https://example.org/a?b=c&d" #:host-spawn None)
(Ok "Opened https://example.org/a?b=c&d"))
(expect "it is xdg-open, with the address as it is"
(wait-for (fun () (and (file-exists? seen) (= (file-read-text seen) "https://example.org/a?b=c&d\n"))))
#t)
(expect "in a container, host-spawn is the one on the PATH"
(distrobox-host-spawn)
(if (or (file-exists? "/run/.containerenv") (file-exists? "/.dockerenv")) (Some spawn) None))
(expect "in a distrobox container, host-spawn opens it on the host"
(open-in-browser "https://example.org/x" #:host-spawn (Some spawn))
(Ok "Opened https://example.org/x"))
(expect "with xdg-open there, and the variables of the display, not of the desktop"
(file-read-text spawned)
"-no-pty\n-env\nDISPLAY,WAYLAND_DISPLAY,XDG_SESSION_TYPE\nxdg-open\nhttps://example.org/x\n")
;; Openers that fail.
(def failing-bin (path-combine root "bin-failing"))
(directory-create failing-bin)
(def failing (path-combine failing-bin "xdg-open"))
(file-write-text failing "#!/bin/sh\necho 'xdg-open: no method available' >&2\nexit 3\n")
(set-mode! failing (cast UnixMode 448))
(def path-before (option-ref-or (get-environment-variable "PATH") ""))
(set-environment-variable! "PATH" (str failing-bin ":" path-before))
(expect "an xdg-open that finds no program is said so, not \"Opened\""
(open-in-browser "https://example.org/x" #:host-spawn None)
(Err "Could not open https://example.org/x: xdg-open found no program to open it with."))
(set-environment-variable! "PATH" path-before)
(def broken (path-combine failing-bin "broken.sh"))
(file-write-text broken "#!/bin/sh\nexit 7\n")
(set-mode! broken (cast UnixMode 448))
(set-environment-variable! "BJOMARKS_BROWSER" broken)
(expect "another opener that fails, with its code"
(open-in-browser "https://example.org/x" #:host-spawn None)
(Err "Could not open https://example.org/x: broken.sh ended with code 7."))
(set-environment-variable! "BJOMARKS_BROWSER" ""))
(expect "only http and https are opened" (browser-scheme? "file:///etc/passwd") #f)
;; A private window: the flag of the default browser, after its Exec line.
(expect "the words of a flatpak's Exec line"
(exec-words "/usr/bin/flatpak run --branch=stable --command=firefox --file-forwarding org.mozilla.firefox @@u %u @@")
["/usr/bin/flatpak" "run" "--branch=stable" "--command=firefox" "--file-forwarding" "org.mozilla.firefox"])
(expect "a word in quotes" (exec-words "\"/opt/my browser/chrome\" --flag %U") ["/opt/my browser/chrome" "--flag"])
(expect "Firefox" (private-command "org.mozilla.firefox.desktop" "firefox %u" "https://e.org/")
(Some (Tuple "firefox" ["--private-window" "https://e.org/"])))
(expect "Brave" (private-command "brave-browser.desktop" "/usr/bin/brave-browser-stable %U" "https://e.org/")
(Some (Tuple "/usr/bin/brave-browser-stable" ["--incognito" "https://e.org/"])))
(expect "Edge" (private-flag "microsoft-edge.desktop") (Some "--inprivate"))
(expect "a browser not known" (private-command "org.gnome.Epiphany.desktop" "epiphany %U" "https://e.org/") None)
(expect "only http and https, in a private window too"
(match (open-private-in-browser "file:///etc/passwd" #:host-spawn None) ((Ok _) #t) ((Err _) #f)) #f)
(expect "in any case" (browser-scheme? "HTTPS://example.org/") #t)
(expect "another scheme is refused" (open-in-browser "javascript:alert(1)")
(Err "Only http and https addresses are opened: javascript:alert(1)"))
;; Ctrl+M, in the list and in the search box.
(app-dispatch! app (Search SearchNext))
(expect "the list has the keyboard for Ctrl+M"
(wait-for (fun () (focus-within? (cast InputElement (list-control))))) #t)
(press top KeyCode.M RawMods.Control PhysicalKey.M)
(settle)
(expect "Ctrl+M in the list opens the dialog of a new bookmark"
(match (.draft (model)) ((Some d) (Tuple (.editing d) (.url d))) (None (Tuple (Some rust-book) "closed")))
(Tuple None ""))
(app-dispatch! app CancelDraft)
(settle)
(press top KeyCode.S RawMods.Control PhysicalKey.S)
(expect "Ctrl+S gives the search box the keyboard" (wait-for (fun () (focused? (cast InputElement (search-control))))) #t)
(press top KeyCode.M RawMods.Control PhysicalKey.M)
(settle)
(expect "Ctrl+M in the search box opens it too" (app-windows app) '("draft"))
(expect "and types nothing" (.query (model)) "rust")
(app-dispatch! app CancelDraft)
(settle)
;; --- the help ---------------------------------------------------------------------------
(expect "the toolbar has Help" (vec-contains? (button-labels (view (model))) "Help") #t)
(press top KeyCode.F1 RawMods.None PhysicalKey.F1)
(settle)
(expect "F1 opens the help" (app-windows app) '("help"))
(expect "the help names each key of the window, Escape for the help too"
(vec-filter (fun (g) (not (vec-contains? (view-texts (help-view)) g)))
(list->vec (list-map key-gesture (keys (model)))))
[])
(press top KeyCode.Escape RawMods.None PhysicalKey.Escape)
(settle)
(expect "Escape closes it" (app-windows app) '())
(app-dispatch! app ShowHelp)
(settle)
(expect "the Help button opens it" (app-windows app) '("help"))
(app-dispatch! app HideHelp)
(settle)
(expect "and closing its window closes it" (app-windows app) '())
(expect "a search is typed" (.query (model)) "rust")
(press top KeyCode.Escape RawMods.None PhysicalKey.Escape)
(settle)
(expect "Escape clears it" (Tuple (.query (model)) (box-text (cast TextBox (search-control)))) (Tuple "" ""))
(expect "and leaves the keyboard in the search box" (focused? (cast InputElement (search-control))) #t)
(app-dispatch! app (Search (SearchTyped "rust")))
(settle)
(app-dispatch! app New)
(def dialog-keys (list->vec (list-map key-gesture (keys (model)))))
(app-dispatch! app CancelDraft)
(settle)
(expect "the help names the keys of the dialog too"
(vec-filter (fun (g) (not (vec-contains? (view-texts (help-view)) g))) dialog-keys) [])
;; The list, with the keyboard, for what comes next.
(app-dispatch! app (Search SearchNext))
;; Remove, from the menu of the chosen bookmark, then Ctrl+Z. D is no key.
(expect "the list has the keyboard before the removal"
(wait-for (fun () (focus-within? (cast InputElement (list-control))))) #t)
(app-dispatch! app (Select 0))
(press top KeyCode.D RawMods.None PhysicalKey.D)
(settle)
(expect "D alone does nothing" (vec-length (vault-bookmarks (vault-of (model)))) 3)
(app-dispatch! app (Remove (.id rust-book)))
(settle)
(expect "Remove removes the bookmark" (shown-urls (model)) ["https://example.org/rust-async"])
(expect "with no question" (app-windows app) '())
(expect "and says how to bring it back" (string-contains? (.note (model)) "Ctrl+Z brings it back") #t)
(expect "the next one is chosen in its place" (.selected (model)) 0)
(expect "and has the keyboard"
(wait-for (fun () (focus-within? (cast InputElement (list-control))))) #t)
(expect "the removal is saved" (wait-for idle?) #t)
(press top KeyCode.Z RawMods.Control PhysicalKey.Z)
(settle)
(expect "Ctrl+Z brings it back" (shown-urls (model))
["https://doc.rust-lang.org/book/" "https://example.org/rust-async"])
(expect "as it was" (match (vault-find (vault-of (model)) (.id rust-book)) ((Some b) (.tags b)) (None []))
["book" "rust"])
(expect "and chooses it" (.selected (model)) 0)
(expect "the undo is saved" (wait-for idle?) #t)
(press top KeyCode.Z RawMods.Control PhysicalKey.Z)
(settle)
(expect "Ctrl+Z with nothing removed says so" (.note (model)) "Nothing removed to bring back.")
;; Two removals come back the last first. The first one, removed from the
;; menu, is not the chosen bookmark: the chosen one stays chosen.
(app-dispatch! app (Select 1))
(app-dispatch! app (Remove (.id rust-book)))
(expect "a bookmark before the chosen one is removed" (shown-urls (model)) ["https://example.org/rust-async"])
(expect "and the chosen one stays chosen" (.selected (model)) 0)
(app-dispatch! app (Remove (.id (vec-ref (visible-bookmarks (model)) (.selected (model))))))
(settle)
(expect "the list is empty" (shown-urls (model)) [])
(expect "and the search box has the keyboard"
(wait-for (fun () (focused? (cast InputElement (search-control))))) #t)
;; The key, pressed in the search box: a removal is the last thing done.
(press top KeyCode.Z RawMods.Control PhysicalKey.Z)
(settle)
(expect "Ctrl+Z in the search box, after the removal, brings the last removed back"
(shown-urls (model)) ["https://example.org/rust-async"])
(expect "and chooses it" (.selected (model)) 0)
(expect "the search is as it was" (.query (model)) "rust")
(expect "and so is the box" (box-text (cast TextBox (search-control))) "rust")
(app-dispatch! app (Search (SearchTyped "nowhere")))
(app-dispatch! app Undo)
(expect "one that the search hides comes back too"
(vec-length (vault-bookmarks (vault-of (model)))) 3)
(expect "and the note says the search hides it" (string-contains? (.note (model)) "which the search hides") #t)
(app-dispatch! app (Search (SearchTyped "")))
;; In the search box, the letters are typed.
(app-dispatch! app (Select 0))
(app-dispatch! app (Search SearchNext))
(app-dispatch! app Prev)
(expect "the search box has the keyboard again"
(wait-for (fun () (and (focused? (cast InputElement (search-control))) (.search-focused (model))))) #t)
;; A bookmark is chosen before each key, as typing in the box chooses none.
(app-dispatch! app (Select 0))
(press top KeyCode.E RawMods.None PhysicalKey.E)
(type-text! top "e")
(app-dispatch! app (Select 0))
(press top KeyCode.D RawMods.None PhysicalKey.D)
(type-text! top "d")
(settle)
(expect "E and D in the search box are typed" (.query (model)) "ed")
(expect "and edit nothing" (.draft (model)) None)
(expect "and remove nothing" (vec-length (vault-bookmarks (vault-of (model)))) 3)
(app-dispatch! app (Search (SearchTyped "rust")))
(app-dispatch! app (Remove (.id rust-book)))
(expect "a removal" (shown-urls (model)) ["https://example.org/rust-async"])
(expect "is saved" (wait-for idle?) #t)
;; Typed after the removal: Ctrl+Z in the box undoes the typing.
(app-dispatch! app (Select 0))
(app-dispatch! app Prev)
(expect "the search box has the keyboard once more"
(wait-for (fun () (focused? (cast InputElement (search-control))))) #t)
;; The text was put in the box by a message, which leaves the caret where
;; it was: End moves it after the text.
(press top KeyCode.End RawMods.None PhysicalKey.End)
(type-text! top "-async")
(settle)
(expect "typing after a removal" (.query (model)) "rust-async")
(press top KeyCode.Z RawMods.Control PhysicalKey.Z)
(settle)
(expect "makes Ctrl+Z in the box undo the typing" (.query (model)) "rust")
(expect "and not the removal" (vec-length (vault-bookmarks (vault-of (model)))) 2)
;; --- this device again, and another device ---------------------------------------------
(def kept (vec-map #(.url &) (vault-bookmarks (vault-of (model)))))
(defun (opened-at local)
(def app2 (start-app (initial-model shared local) gui-update view (fun (c) unit) #:windows windows #:keys keys))
app2)
(def again (opened-at here))
(expect "a folder with a vault: the first screen opens it" (.start (app-model again)) OpenExisting)
(app-dispatch! again (Password (PasswordTyped "wrong")))
(app-dispatch! again Unlock)
(expect "a wrong password is said so"
(let go ((tries 0))
(app-run-pending! again)
(cond ((= (.lock-problem (app-model again)) "The password is wrong.") #t)
((> tries 1000) #f)
(else (sleep-ms 10) (go (+ tries 1)))))
#t)
(app-dispatch! again (Password (PasswordTyped "correct horse")))
;; What Enter in the box sends: with a vault there, it opens it.
(app-dispatch! again (Password PasswordEnter))
(expect "the right one opens"
(let go ((tries 0))
(app-run-pending! again)
(cond ((= (.phase (app-model again)) Open) #t)
((> tries 1000) #f)
(else (sleep-ms 10) (go (+ tries 1)))))
#t)
(expect "with the bookmarks as they were saved"
(vec-map #(.url &) (vault-bookmarks (vault-of (app-model again)))) kept)
(def phone (opened-at (path-combine root "phone")))
(expect "another device joins" (.start (app-model phone)) JoinShared)
(app-dispatch! phone (Password (PasswordTyped "correct horse")))
(app-dispatch! phone Unlock)
(expect "and has the bookmarks"
(let go ((tries 0))
(app-run-pending! phone)
(cond ((and (= (.phase (app-model phone)) Open)
(= (vec-map #(.url &) (vault-bookmarks (vault-of (app-model phone)))) kept)) #t)
((> tries 1000) #f)
(else (sleep-ms 10) (go (+ tries 1)))))
#t)
;; --- titles: the button beside the title, in the dialog ------------------------------
;; The pages are on the server above, so that no site on the internet is
;; asked. The laptop's dialog is drawn, so the button is a real one.
(expect "the server listens" (> (box-ref server-port) 0) #t)
(: (-> Model string (Option Bookmark)))
(defun (bookmark-at m url)
(def found (vec-filter (fun (b) (= (.url b) url)) (vault-bookmarks (vault-of m))))
(if (vec-empty? found) None (Some (vec-ref found 0))))
;; The title of the bookmark with this address.
(: (-> Model string string))
(defun (title-at m url)
(match (bookmark-at m url)
((Some b) (match (.title b) ((Some t) t) (None "<no title>")))
(None "<missing>")))
(: (-> Draft))
(defun (draft-now)
(match (.draft (model))
((Some d) d)
(None (panic! "the dialog is not open"))))
;; The button, and the label and the arc in it.
(defun (fetch-control) (app-window-control app "draft" '(3 1)))
(: (-> Panel))
(defun (button-face) (cast Panel (content-of (cast ContentControl (fetch-control)))))
(defun (label-shown) (opacity-of (cast Visual (child-at (children-of (button-face)) 0))))
(defun (spinner) (cast Arc (child-at (children-of (button-face)) 1)))
(defun (spinner-shown?) (visible? (cast Visual (spinner))))
(defun (spinning?) (has-class? (classes-of (cast StyledElement (spinner))) "spinning"))
;; A click, as the button hears one.
(defun (click-fetch!)
(raise-event! (cast Interactive (fetch-control)) (RoutedEventArgs. (cast RoutedEvent click-event)))
(settle))
(app-dispatch! app New)
(app-dispatch! app (DraftUrl titled))
(app-dispatch! app SaveDraft)
(expect "a bookmark is saved with no title" (title-at (model) titled) "<no title>")
(expect "and saved" (wait-for idle?) #t)
(expect "and no title is fetched" (box-ref asked) [])
(app-dispatch! app (Edit (match (bookmark-at (model) titled) ((Some b) (.id b)) (None (panic! "no bookmark")))))
(settle)
(expect "the button shows its label" (label-shown) 1.0)
(expect "and no spinner" (spinner-shown?) #f)
(expect "which does not turn" (spinning?) #f)
(app-dispatch! app (DraftUrl slow))
(settle)
(click-fetch!)
(expect "a click fetches the title" (some? (.fetching (draft-now))) #t)
(expect "the label is hidden" (label-shown) 0.0)
(expect "the spinner is shown" (spinner-shown?) #t)
(expect "and turns" (spinning?) #t)
;; The render loop does not run by itself here: a tick runs it, and the
;; dispatcher then applies what the animation set.
(def angle (start-angle-of (spinner)))
(sleep-ms 200)
(render-ticks! 1)
(settle)
(expect "it moves as time passes" (= (start-angle-of (spinner)) angle) #f)
(click-fetch!)
(expect "the title comes" (wait-for (fun () (= (.title (draft-now)) "A slow page"))) #t)
(expect "into the field" (box-text (cast TextBox (app-window-control app "draft" '(3 0)))) "A slow page")
(expect "the spinner stops" (spinner-shown?) #f)
(expect "and turns no more" (spinning?) #f)
(expect "the label is back" (label-shown) 1.0)
(expect "a second click while it runs fetches nothing more" (box-ref asked) ["/slow"])
(app-dispatch! app (DraftUrl titled))
(click-fetch!)
(expect "another page's title replaces it" (wait-for (fun () (= (.title (draft-now)) "A local page"))) #t)
(app-dispatch! app SaveDraft)
(expect "and is saved with the bookmark" (title-at (model) titled) "A local page")
(app-dispatch! app New)
(app-dispatch! app (DraftUrl untitled))
(settle)
(click-fetch!)
(expect "a page with no title is said so in the dialog"
(wait-for (fun () (= (.problem (draft-now)) "No title: the page has no title."))) #t)
(expect "and the field stays empty" (.title (draft-now)) "")
(expect "and the spinner stops" (spinner-shown?) #f)
(app-dispatch! app (DraftUrl ""))
(click-fetch!)
(expect "with no address, the dialog asks for one" (.problem (draft-now)) "Type the address first.")
(expect "and fetches nothing" (.fetching (draft-now)) None)
;; A result that its dialog no longer waits for is dropped. The fetches
;; still run, and their results come later, and are dropped too.
(app-dispatch! app (DraftUrl slow))
(click-fetch!)
(def typed-over (.fetches (model)))
(app-dispatch! app (DraftTitle "Mine"))
(settle)
(expect "typing a title stops the fetch" (.fetching (draft-now)) None)
(expect "and the spinner" (spinner-shown?) #f)
(app-dispatch! app (DraftTitleFetched typed-over (Ok (Ok "Fetched"))))
(expect "its title does not replace what was typed" (.title (draft-now)) "Mine")
(click-fetch!)
(def closed (.fetches (model)))
(app-dispatch! app CancelDraft)
(app-dispatch! app New)
(app-dispatch! app (DraftTitleFetched closed (Ok (Ok "Fetched"))))
(expect "a fetch of a dialog that was closed does not reach the next" (.title (draft-now)) "")
(app-dispatch! app CancelDraft)
(expect "the server was asked only by the clicks"
(wait-for (fun () (= (box-ref asked) ["/slow" "/titled" "/untitled" "/slow" "/slow"]))) #t)
;; --- archive links: the button beside the archive link, in the dialog ---------------
(defun (archive-control) (app-window-control app "draft" '(7 1)))
(defun (archive-shown) (box-text (cast TextBox (app-window-control app "draft" '(7 0)))))
(defun (archive-spinner-shown?)
(visible? (cast Visual (child-at (children-of (cast Panel (content-of (cast ContentControl (archive-control)))))
1))))
(defun (click-archive!)
(raise-event! (cast Interactive (archive-control)) (RoutedEventArgs. (cast RoutedEvent click-event)))
(settle))
(: (-> string string))
(defun (snapshot-of url) (str "https://web.archive.org/web/20260101000000/" url))
(: (-> (Vec string)))
(defun (lookups) (vec-filter (fun (p) (string-starts-with? p wayback-path)) (box-ref asked)))
(app-dispatch! app New)
(app-dispatch! app (DraftUrl slow))
(settle)
(expect "the archive button shows no spinner" (archive-spinner-shown?) #f)
(click-archive!)
(expect "a click looks up the archive link" (some? (.archiving (draft-now))) #t)
(expect "its spinner is shown" (archive-spinner-shown?) #t)
(expect "and not the title's" (spinner-shown?) #f)
(click-archive!)
(expect "the latest snapshot comes, at https"
(wait-for (fun () (= (.archive (draft-now)) (snapshot-of slow)))) #t)
(expect "into the field" (archive-shown) (snapshot-of slow))
(expect "the archive spinner stops" (archive-spinner-shown?) #f)
(expect "a second click while it runs looks up nothing more" (lookups) [(str wayback-path slow)])
(app-dispatch! app (DraftUrl untitled))
(click-archive!)
(expect "a page with no snapshot is said so in the dialog"
(wait-for (fun () (= (.problem (draft-now)) "No archive: the Wayback Machine has no copy of this page.")))
#t)
(expect "and the field keeps its link" (.archive (draft-now)) (snapshot-of slow))
(app-dispatch! app (DraftUrl ""))
(click-archive!)
(expect "with no address, the dialog asks for one" (.problem (draft-now)) "Type the address first.")
(expect "and looks up nothing" (.archiving (draft-now)) None)
;; A result that the dialog no longer waits for is dropped.
(app-dispatch! app (DraftUrl slow))
(click-archive!)
(def typed-link (.fetches (model)))
(app-dispatch! app (DraftArchive "https://example.org/mine"))
(settle)
(expect "typing an archive link stops the lookup" (.archiving (draft-now)) None)
(expect "and its spinner" (archive-spinner-shown?) #f)
(app-dispatch! app (DraftArchiveFetched typed-link (Ok (Ok "https://example.org/fetched"))))
(expect "its link does not replace what was typed" (.archive (draft-now)) "https://example.org/mine")
(app-dispatch! app CancelDraft)
;; The address of a bookmark loads it: its looked up link is saved with it.
(app-dispatch! app New)
(app-dispatch! app (DraftUrl titled))
(click-archive!)
(expect "the link of a bookmark's page comes"
(wait-for (fun () (= (.archive (draft-now)) (snapshot-of titled)))) #t)
(app-dispatch! app SaveDraft)
(expect "and is saved with the bookmark"
(match (bookmark-at (model) titled) ((Some b) (.archive b)) (None None)) (Some (snapshot-of titled)))
(expect "the API was asked only by the clicks"
(wait-for (fun () (= (lookups) (vec-map (fun (u) (str wayback-path u)) [slow untitled slow titled])))) #t)
(expect "the laptop saves the title" (wait-for idle?) #t)
(app-dispatch! phone SyncTick)
(expect "the phone gets it at its next sync"
(let go ((tries 0))
(app-run-pending! phone)
(cond ((= (title-at (app-model phone) titled) "A local page") #t)
((> tries 1000) #f)
(else (sleep-ms 10) (go (+ tries 1)))))
#t)
;; --- importing Firefox's bookmarks ---------------------------------------------------
;; A made-up backup in Firefox's shape. The picker answers nothing here, as
;; there is no screen: the test sends what it sends when a file is chosen.
(def firefox (path-combine root "firefox.json"))
(file-write-text firefox
(str "{\"type\":\"text/x-moz-place-container\",\"root\":\"placesRoot\",\"title\":\"\",\"children\":["
"{\"type\":\"text/x-moz-place-container\",\"root\":\"bookmarksMenuFolder\",\"title\":\"menu\","
"\"children\":[{\"type\":\"text/x-moz-place-container\",\"title\":\"Reading List\",\"children\":["
"{\"type\":\"text/x-moz-place\",\"title\":\"An article\",\"uri\":\"https://example.net/article\","
"\"tags\":\"Later\",\"dateAdded\":1700000000000000}]},"
"{\"type\":\"text/x-moz-place\",\"title\":\"Recent\",\"uri\":\"place:sort=12\"}]},"
"{\"type\":\"text/x-moz-place-container\",\"root\":\"toolbarFolder\",\"title\":\"toolbar\","
"\"children\":[{\"type\":\"text/x-moz-place\",\"title\":\"Manual\","
"\"uri\":\"https://bjolang.org/manual\",\"dateAdded\":1700000000000000}]}]}"))
(app-dispatch! app ImportAsked)
(settle)
(expect "Import with no file chosen imports nothing" (string-starts-with? (.note (model)) "Imported") #f)
(def before-import (vec-length (vault-bookmarks (vault-of (model)))))
(app-dispatch! app (ImportChosen (Some firefox)))
(expect "the backup is imported in the background"
(wait-for (fun () (string-starts-with? (.note (model)) "Imported"))) #t)
(expect "and the note says what came in"
(.note (model))
(str "Imported 1 bookmark from firefox.json. 1 was here already. "
"1 is not a web address, and left out."))
(expect "one bookmark more" (vec-length (vault-bookmarks (vault-of (model)))) (+ before-import 1))
(def article (bookmark-at (model) "https://example.net/article"))
(expect "with its title" (match article ((Some b) (.title b)) (None None)) (Some "An article"))
(expect "and its folder and its Firefox tag as tags" (match article ((Some b) (.tags b)) (None []))
["later" "reading-list"])
(expect "the bookmark that was here is as it was" (title-at (model) "https://bjolang.org/manual") "The Bjolang manual")
(expect "the import is saved" (wait-for idle?) #t)
(app-dispatch! app (ImportChosen (Some firefox)))
(expect "the same backup again adds nothing"
(wait-for (fun () (= (.note (model))
(str "Imported 0 bookmarks from firefox.json. 2 were here already. "
"1 is not a web address, and left out."))))
#t)
(def html (path-combine root "bookmarks.html"))
(file-write-text html "<!DOCTYPE NETSCAPE-Bookmark-file-1>\n<TITLE>Bookmarks</TITLE>\n")
(app-dispatch! app (ImportChosen (Some html)))
(expect "the HTML export is not read, and the note says which file to choose"
(wait-for (fun () (string-starts-with? (.note (model))
"Could not import bookmarks.html: this is Firefox's HTML export")))
#t)
(app-dispatch! app (ImportChosen (Some (path-combine root "missing.json"))))
(expect "a file that is not there is said so"
(wait-for (fun () (string-starts-with? (.note (model)) "Could not import missing.json: "))) #t)
(ignore (inbox-post! stop 1))
(expect "the server stops" (match (sync/blocking (promise-join server)) ((Ok _) #t) ((Err _) #f)) #t)
;; --- the shared folder, chosen on the first screen --------------------------------------
;; The settings are in the temp directory, not in the user's. The picker
;; answers nothing here: the test sends what it sends for a folder.
(: (-> (App Model Msg) (-> bool) bool))
(defun (pending-until a done?)
(let go ((tries 0))
(app-run-pending! a)
(cond ((done?) #t)
((> tries 1000) #f)
(else (sleep-ms 10) (go (+ tries 1))))))
(def config (path-combine root "config"))
(def shared-folder (path-combine root "shared"))
(expect "no folder is saved at first" (read-shared-folder config) None)
(expect "with no settings folder, the first screen has no Change button"
(button-labels (view (initial-model shared (path-combine root "tablet")))) ["Join"])
;; A device with no vault yet.
(def tablet (start-app (initial-model shared (path-combine root "tablet") #:settings config) gui-update view
(fun (c) unit) #:windows windows #:keys keys))
(defun (tablet-model) (app-model tablet))
(: (-> (View Msg) (Vec string)))
(defun (dropdown-items v)
(def own (if (= (view-kind v) DropdownKind)
(vec-fold (fun (p acc) (match p ((PropItems s) (vec-append acc s)) (_ acc))) [] (view-props v))
[]))
(vec-fold (fun (c acc) (vec-append acc (dropdown-items c))) own (view-children v)))
(expect "with no settings folder, no list of folders"
(dropdown-items (view (initial-model shared (path-combine root "tablet")))) [])
(expect "with one, a list of the folders, by their names, and Add new"
(dropdown-items (view (tablet-model))) ["shared" "Add new…"])
(expect "with one folder, no Remove from list" (button-labels (view (tablet-model))) ["Join"])
(expect "a folder with a vault, and a device with none: join" (.start (tablet-model)) JoinShared)
(def elsewhere (path-combine root "elsewhere"))
(directory-create elsewhere)
(app-dispatch! tablet (FolderChosen (Some elsewhere)))
(expect "an empty folder: make a vault there" (.start (tablet-model)) CreateNew)
(expect "the folder is shown" (storage-label (.storage (tablet-model))) elsewhere)
(expect "and saved in the settings"
(pending-until tablet (fun () (= (read-shared-folder config) (Some elsewhere)))) #t)
(expect "the list has both, the first one too" (.vaults (tablet-model)) [shared-folder elsewhere])
(expect "and is saved" (pending-until tablet (fun () (= (read-vaults config) [shared-folder elsewhere]))) #t)
(expect "with two, the list" (dropdown-items (view (tablet-model))) ["shared" "elsewhere" "Add new…"])
(expect "and Remove from list" (button-labels (view (tablet-model))) ["Remove from list" "Create"])
(app-dispatch! tablet (ChooseVault 0))
(expect "the first of the list: join" (Tuple (.start (tablet-model)) (storage-label (.storage (tablet-model))))
(Tuple JoinShared shared-folder))
(expect "the one in use is saved" (pending-until tablet (fun () (= (read-shared-folder config) (Some shared-folder))))
#t)
(app-dispatch! tablet (FolderChosen (Some elsewhere)))
(expect "a folder of the list, chosen again, is not added again" (.vaults (tablet-model)) [shared-folder elsewhere])
(app-dispatch! tablet ForgetVault)
(expect "Remove from list: the folder is out of it, and the first left is in use"
(Tuple (.vaults (tablet-model)) (storage-label (.storage (tablet-model))))
(Tuple [shared-folder] shared-folder))
(expect "which is saved" (pending-until tablet (fun () (= (read-vaults config) [shared-folder]))) #t)
(expect "its files stay" (directory-exists? elsewhere) #t)
(app-dispatch! tablet ForgetVault)
(expect "the last one stays" (.vaults (tablet-model)) [shared-folder])
(app-dispatch! tablet (FolderChosen (Some shared-folder)))
(expect "the folder with the vault again: join" (.start (tablet-model)) JoinShared)
(expect "saved again" (pending-until tablet (fun () (= (read-shared-folder config) (Some shared-folder)))) #t)
(app-dispatch! tablet (FolderChosen None))
(expect "a picker that was cancelled changes nothing" (storage-label (.storage (tablet-model))) shared-folder)
(save-shared-folder! config "/somewhere")
(file-write-text (path-combine config "settings.json") "{\"later\":[1,2],\"shared\":\"/old\"}")
(save-shared-folder! config "/new")
(expect "the fields that this version does not know are kept"
(file-read-text (path-combine config "settings.json")) "{\"later\":[1,2],\"shared\":\"/new\"}")
(expect "and the file is not left half written" (file-exists? (path-combine config "settings.json.new")) #f)
(expect "settings of an earlier version: their one folder" (read-vaults config) ["/new"])
(save-vaults! config ["/a" "/b"] "/b")
(expect "the list is saved" (Tuple (read-vaults config) (read-shared-folder config)) (Tuple ["/a" "/b"] (Some "/b")))
(expect "the other fields are kept"
(string-contains? (file-read-text (path-combine config "settings.json")) "\"later\":[1,2]") #t)
;; With a root, each shared folder has a device folder of its own: an
;; empty folder is a new vault, not this device's vault again.
(def roots (path-combine root "roots"))
(def phone (start-app (initial-model shared "" #:settings config #:root (Some roots)) gui-update view
(fun (c) unit) #:windows windows #:keys keys))
(def phone-local (.local (app-model phone)))
(expect "the device folder is in the root" (string-starts-with? phone-local roots) #t)
(expect "a folder with a vault: join" (.start (app-model phone)) JoinShared)
(def empty-folder (path-combine root "empty"))
(directory-create empty-folder)
(app-dispatch! phone (FolderChosen (Some empty-folder)))
(expect "another folder, another device folder" (= (.local (app-model phone)) phone-local) #f)
(expect "an empty folder: a new vault" (.start (app-model phone)) CreateNew)
(app-dispatch! phone (FolderChosen (Some shared-folder)))
(expect "the first folder, its device folder again" (.local (app-model phone)) phone-local)
;; This device's vault, in a new empty folder: it opens from this device's
;; own files, and writes its files there.
(def laptop-bookmarks (vec-map #(.url &) (vault-bookmarks (vault-of (model)))))
(def moved (path-combine root "moved"))
(directory-create moved)
(def laptop (start-app (initial-model shared here #:settings config) gui-update view
(fun (c) unit) #:windows windows #:keys keys))
(app-dispatch! laptop (FolderChosen (Some moved)))
(expect "a device with a vault opens it, in whatever folder" (.start (app-model laptop)) OpenExisting)
(app-dispatch! laptop (Password (PasswordTyped "correct horse")))
(app-dispatch! laptop Unlock)
(expect "it opens in the new folder" (pending-until laptop (fun () (= (.phase (app-model laptop)) Open))) #t)
(expect "with its bookmarks"
(vec-map #(.url &) (vault-bookmarks (vault-of (app-model laptop)))) laptop-bookmarks)
(expect "and writes the vault's files there"
(and (file-exists? (path-combine moved "keys.bin"))
(file-exists? (path-combine moved "devices"
(device-file-name (vault-device (vault-of (app-model laptop)))))))
#t)
;; Another device, not yet synced, bookmarked a page of the laptop with a
;; title of its own: after a sync, a window asks which title to keep.
(def page (vec-ref laptop-bookmarks 0))
(def other (match (join-vault (folder-storage moved) (path-combine root "other") "correct horse")
((Ok (Tuple v _)) v)
((Err _) (panic! "the other device did not join"))))
(match (vault-add other page #:title (Some "Another title") #:tags ["other"])
((Ok (Tuple v _)) (ignore (vault-sync v)))
((Err why) (panic! why)))
(defun (laptop-idle?) (and (not (.saving (app-model laptop))) (not (vault-dirty? (vault-of (app-model laptop))))))
(app-dispatch! laptop SyncTick)
(expect "the laptop syncs" (pending-until laptop laptop-idle?) #t)
(expect "a page bookmarked twice" (vec-map duplicate-url (.duplicates (app-model laptop))) [page])
(expect "the question shows" (list-map window-key (windows (app-model laptop))) '("duplicate"))
(expect "with a button for each title, and Not now"
(vec-length (button-labels (window-content (list-ref (windows (app-model laptop)) 0)))) 3)
(app-dispatch! laptop (Later page))
(expect "Not now closes it" (windows (app-model laptop)) '())
(app-dispatch! laptop (ChooseTitle page "Another title"))
(expect "a title is chosen" (pending-until laptop laptop-idle?) #t)
(def kept (vec-filter (fun (b) (= (.url b) page)) (vault-bookmarks (vault-of (app-model laptop)))))
(expect "one bookmark of it, with the title chosen and the tags of both"
(Tuple (vec-length kept) (.title (vec-ref kept 0)) (vec-contains? (.tags (vec-ref kept 0)) "other"))
(Tuple 1 (Some "Another title") #t))
(expect "no question" (vec-length (.duplicates (app-model laptop))) 0)
;; Other bookmarks: the vault is synced and closed, and the first screen
;; shows, to open it again or choose another folder.
(expect "with settings, Other bookmarks" (vec-contains? (button-labels (view (app-model laptop))) "Other bookmarks…")
#t)
(app-dispatch! laptop (Search (SearchTyped "something")))
(app-dispatch! laptop SwitchVault)
(expect "it closes" (pending-until laptop (fun () (= (.phase (app-model laptop)) Locked))) #t)
(expect "with nothing of it kept"
(Tuple (.vault (app-model laptop)) (.query (app-model laptop)) (.start (app-model laptop)))
(Tuple None "" OpenExisting))
(expect "the folder is in the list" (vec-contains? (.vaults (app-model laptop)) moved) #t)
(app-dispatch! laptop (Password (PasswordTyped "correct horse")))
(app-dispatch! laptop Unlock)
(expect "and it opens again" (pending-until laptop (fun () (= (.phase (app-model laptop)) Open))) #t)
(directory-delete-tree root)
(println "bjomarks-gui ok"))