Something went wrong. Try again.
A ebook and PDF reader, annotator, and citation manager.
Something went wrong. Try again.
16 kB 348 lines
at main
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349== Document value policy and creation <document-creation>
=== Pure presets and type identity
Creation presets are ordinary data shared by immediate REPL creation and lazyUI drafts. They do not resolve a type or perform IPC. The caller supplies typeidentity: REPL helpers resolve the current editable name, whereas UI startuploads stable built-in mappings. Keeping that distinction outside the presetspreserves renamed/replacement-type behavior without introducing another key.Transport envelopes retain their existing camelCase keys;metadata and scratch EDN are unchanged.
```clojure;| file: tangled/cljs/candlelight/documents.cljs(ns candlelight.documents (:require [clojure.string :as str]))
(defn preset "Return creation values for a document mode without resolving a type or saving." [mode] (merge {:name (str "Untitled " mode) :content "" :metadata {} :attachments []} (case mode "citation" {:metadata {:title "Untitled citation"}} "clojure-mode" {:name "scratch" :content (pr-str {:source "" :annotations []})} {})))
(defn draft "Add the caller-resolved type and unsaved timestamps to a creation preset." [mode type-id] (assoc (preset mode) :typeId type-id :typeName mode :createdAt "" :modifiedAt ""))
(defn display-name "Apply the shared shell/close fallback using caller-resolved built-in type IDs." [document value citation-type-id clojure-type-id] (if (str/blank? value) (cond (= (:typeId document) clojure-type-id) "scratch" (= (:typeId document) citation-type-id) "Untitled citation" :else (str "Untitled " (:typeName document))) value))```
The shell and close capture share this blank-title policy. It is separate fromcreation: the native rename still enforces its own fallback atomically. The noteeditor's existing blank-input callback uses its narrower note/citation displaylabels; this cleanup does not silently standardize that observable distinction.
=== Immediate native creation
The native adapter owns creation wire conversion, not draft lifecycle. Itaccepts an explicit invocation function for isolated regression checks. A namedcreation still resolves the editable name on every call, rejects missing types,and returns the persisted ID without opening a tab. Creation and attachmentsremain one native transaction; a name lookup is not a transaction boundary forany write. Requiring either namespace performs no IPC.
```clojure;| file: tangled/cljs/candlelight/document_operations.cljs(ns candlelight.document-operations (:require [candlelight.bridge :as bridge]))
(defn require-type-id "Resolve an editable type name, rejecting if absent. Returns an ID Promise." ([type-name] (require-type-id type-name bridge/invoke)) ([type-name invoke!] (-> (invoke! "find_type_id" #js {:name type-name}) (.then (fn [id] (if (nil? id) (throw (ex-info (str "Document type does not exist: " type-name) {:type-name type-name})) id))))))
(defn create-document! "Persist creation values atomically, returning an ID Promise, without UI effects." ([document] (create-document! document bridge/invoke)) ([{:keys [type-id name content metadata attachments] :or {name "" content "" metadata {} attachments []}} invoke!] (invoke! "create_document" (clj->js {:typeId type-id :name name :content content :metadata metadata :attachments attachments}))))
(defn create-named-document! "Resolve an editable type name and immediately persist the supplied values." ([type-name document] (create-named-document! type-name document bridge/invoke)) ([type-name document invoke!] (-> (require-type-id type-name invoke!) (.then (fn [type-id] (create-document! (assoc document :type-id type-id) invoke!))))))```
=== Creation regressions
The tests below lock the stored creation payloads independently of their presetimplementation. In particular, explicit nil values must not become defaults,custom metadata keys must not be renamed, and a replacement type returned byname lookup must be used rather than a cached built-in ID. Draft promotion andretry remain covered by the UI draft regressions. Scratch expectations use thestored `pr-str` expression: CLJS prints commas between map entries, so ahandwritten whitespace-only EDN string is not the same serialized content.Run explicitly after Loom with`clojure -M -m cljs.main -re node -m candlelight.document-creation-test`.
```clojure;| file: tangled/cljs/candlelight/document_creation_test.cljs(ns candlelight.document-creation-test (:require [candlelight :as api] [candlelight.documents :as documents] [candlelight.document-operations :as operations] [cljs.test :refer-macros [async deftest is run-tests]]))
(deftest presets-preserve-existing-defaults (is (= [{:name "Untitled note" :content "" :metadata {} :attachments []} {:name "Untitled citation" :content "" :metadata {:title "Untitled citation"} :attachments []} {:name "scratch" :content (pr-str {:source "" :annotations []}) :metadata {} :attachments []} {:name "Untitled custom" :content "" :metadata {} :attachments []}] (mapv documents/preset ["note" "citation" "clojure-mode" "custom"]))))
(deftest draft-keeps-the-caller-resolved-type (is (= {:name "Untitled citation" :content "" :metadata {:title "Untitled citation"} :attachments [] :typeId 91 :typeName "citation" :createdAt "" :modifiedAt ""} (documents/draft "citation" 91))))
(deftest shared-shell-and-close-names-use-built-in-identity-with-custom-fallback (is (= ["scratch" "Untitled citation" "Untitled Renamed note" "Untitled Custom" "Exact title"] (mapv (fn [[document value]] (documents/display-name document value 91 92)) [[{:typeId 92 :typeName "Renamed scratch"} " "] [{:typeId 91 :typeName "Renamed citation"} nil] [{:typeId 2 :typeName "Renamed note"} ""] [{:typeId 8 :typeName "Custom"} "\n"] [{:typeId 91 :typeName "Citation"} "Exact title"]]))))
(deftest public-creation-arities-preserve-their-values (let [calls (atom [])] (with-redefs [operations/create-named-document! (fn [type-name document] (swap! calls conj [type-name (:name document) (:content document)]) (js/Promise.resolve 42))] (api/create-note!) (api/create-note! "Title") (api/create-note! "Title" "Markdown") (api/create-citation!) (api/create-scratch!)) (is (= [["note" "Untitled note" ""] ["note" "Title" ""] ["note" "Title" "Markdown"] ["citation" "Untitled citation" ""] ["clojure-mode" "scratch" (pr-str {:source "" :annotations []})]] @calls))))
(deftest generic-creation-keeps-existing-wire-defaults (let [payload (atom nil)] (operations/create-document! {:type-id 91} (fn [command args] (reset! payload [command (js->clj args :keywordize-keys true)]) (js/Promise.resolve 42))) (is (= ["create_document" {:typeId 91 :name "" :content "" :metadata {} :attachments []}] @payload))))
(deftest creation-preserves-explicit-nils (let [payload (atom nil)] (operations/create-document! {:type-id 91 :name nil :content nil :metadata nil :attachments nil} (fn [_ args] (reset! payload (js->clj args :keywordize-keys true)) (js/Promise.resolve 42))) (is (= {:typeId 91 :name nil :content nil :metadata nil :attachments nil} @payload))))
(deftest creation-preserves-custom-metadata-and-attachment-bytes (let [payload (atom nil) metadata {:URL "https://example.org/" :DOI "legacy" :customKey ["" "value"]} attachments [{:filename "sample.bin" :data [0 255]}]] (operations/create-document! {:type-id 91 :name "Title" :content "Source" :metadata metadata :attachments attachments} (fn [_ args] (reset! payload (js->clj args :keywordize-keys true)) (js/Promise.resolve 42))) (is (= {:typeId 91 :name "Title" :content "Source" :metadata metadata :attachments attachments} @payload))))
(deftest named-creation-resolves-the-editable-name-before-writing (async done (let [calls (atom [])] (-> (operations/create-named-document! "citation" (documents/preset "citation") (fn [command args] (swap! calls conj [command (js->clj args :keywordize-keys true)]) (js/Promise.resolve (if (= command "find_type_id") 91 42)))) (.then (fn [id] (is (= [42 [["find_type_id" {:name "citation"}] ["create_document" {:typeId 91 :name "Untitled citation" :content "" :metadata {:title "Untitled citation"} :attachments []}]]] [id @calls])))) (.catch (fn [error] (is (nil? error)))) (.finally done)))))
(deftest missing-editable-name-rejects-without-creating (async done (let [calls (atom [])] (-> (operations/create-named-document! "note" (documents/preset "note") (fn [command _] (swap! calls conj command) (js/Promise.resolve nil))) (.then (fn [_] (is false "A renamed type must not fall back to its built-in ID"))) (.catch (fn [error] (is (= [["find_type_id"] {:type-name "note"}] [@calls (ex-data error)])))) (.finally done)))))
(deftest native-creation-failure-propagates (async done (let [failure (js/Error. "Disk unavailable")] (-> (operations/create-named-document! "note" (documents/preset "note") (fn [command _] (if (= command "find_type_id") (js/Promise.resolve 91) (js/Promise.reject failure)))) (.then (fn [_] (is false "Creation must not hide native failure"))) (.catch (fn [error] (is (identical? failure error)))) (.finally done)))))
(defn -main "Run document creation policy and adapter regressions without a native host." [] (run-tests 'candlelight.document-creation-test))```
=== Explicit create-and-link
Inline wiki completion searches all document types, excluding the source document.Existing targets use ID-based links and generic document loading, so their storedtype determines the view. Creating a new target still creates a note.Inline wiki completion creates a persisted, titled note immediately and returnsits ID/name for insertion. It uses the same creation adapter, but does not uselazy draft promotion. The editor owns stale-completion guards and the save/closebarrier tracks the request. If completion changes while creating, the storednote is retained and the app reports that insertion was cancelled.Run `clojure -M -m cljs.main -re node -m candlelight.note-link-test`.
```clojure;| file: tangled/cljs/candlelight/note_link.cljs(ns candlelight.note-link (:require [candlelight.bridge :as bridge] [candlelight.document-operations :as operations] [clojure.string :as str]))
(defn markdown "Format a saved document link, escaping label characters that would break its syntax." [id title] (str "[[" id "|" (str/replace title #"\]|\r|\n" " ") "]]"))
(defn search! "Find link targets across all document types, excluding the source document." ([source-id query] (search! source-id query bridge/invoke)) ([source-id query invoke!] (-> (invoke! "search_documents" #js {:query query}) (.then (fn [matches] (into [] (remove #(= source-id (.-id %))) (array-seq matches)))))))
(defn create! "Explicitly create a titled note for linking. Returns a Promise of a JS id/name object." ([type-id title] (create! type-id title bridge/invoke)) ([type-id title invoke!] (let [title (str/trim title)] (if (or (str/blank? title) (not (and (int? type-id) (pos? type-id)))) (js/Promise.reject (js/Error. "A nonblank title and a valid note type are required")) (-> (js/Promise.resolve nil) (.then (fn [_] (operations/create-document! {:type-id type-id :name title} invoke!))) (.then (fn [id] #js {:id id :name title})))))))```
```clojure;| file: tangled/cljs/candlelight/note_link_test.cljs(ns candlelight.note-link-test (:require [candlelight.note-link :as note-link] [cljs.test :refer-macros [async deftest is run-tests]]))
(deftest link-labels-cannot-close-the-wiki-link-early (is (= "[[42|A B C]]" (note-link/markdown 42 "A] B\r\nC"))))
(deftest completion-search-includes-all-types-and-excludes-only-the-source (async done (let [calls (atom []) matches #js [#js {:id 1 :typeName "note"} #js {:id 2 :typeName "citation"} #js {:id 3 :typeName "clojure-mode"} #js {:id 4 :typeName "Custom"} #js {:id 5 :typeName "note"}]] (-> (note-link/search! 1 "target" (fn [command args] (swap! calls conj [command (js->clj args :keywordize-keys true)]) (js/Promise.resolve matches))) (.then (fn [targets] (is (= [[["search_documents" {:query "target"}]] [2 3 4 5]] [@calls (mapv #(.-id %) targets)])))) (.catch (fn [error] (is (nil? error)))) (.finally done)))))
(deftest completion-search-propagates-native-failure (async done (let [failure (js/Error. "Search unavailable")] (-> (note-link/search! nil "" (fn [_ _] (js/Promise.reject failure))) (.then (fn [_] (is false "Search failure must reject"))) (.catch (fn [error] (is (identical? failure error)))) (.finally done)))))
(deftest explicit-creation-uses-the-trimmed-title-and-empty-note-content (async done (let [calls (atom [])] (-> (note-link/create! 2 " New note " (fn [command args] (swap! calls conj [command (js->clj args :keywordize-keys true)]) (js/Promise.resolve 42))) (.then (fn [note] (is (= [["create_document" {:name "New note" :typeId 2 :content "" :metadata {} :attachments []}]] @calls)) (is (= "[[42|New note]]" (note-link/markdown (.-id note) (.-name note)))))) (.catch (fn [error] (is (nil? error)))) (.finally done)))))
(deftest blank-title-rejects-without-native-creation (async done (let [calls (atom [])] (-> (note-link/create! 2 " " (fn [& args] (swap! calls conj args))) (.then (fn [_] (is false "Blank titles must reject"))) (.catch (fn [_] (is (empty? @calls)))) (.finally done)))))
(deftest invalid-type-ids-reject-without-native-creation (async done (let [calls (atom []) requests (mapv (fn [type-id] (-> (note-link/create! type-id "Title" (fn [& args] (swap! calls conj args) (js/Promise.resolve 42))) (.then (fn [_] (is false "Invalid type must reject"))) (.catch (fn [_] nil)))) [nil 0 -1 1.5 "2"])] (-> (js/Promise.all (into-array requests)) (.then (fn [_] (is (empty? @calls)))) (.catch (fn [error] (is (nil? error)))) (.finally done)))))
(deftest inline-creation-propagates-native-failure (async done (let [failure (js/Error. "Disk unavailable")] (-> (note-link/create! 2 "Title" (fn [_ _] (js/Promise.reject failure))) (.then (fn [_] (is false "Native creation must reject"))) (.catch (fn [error] (is (identical? failure error)))) (.finally done)))))
(defn -main "Run create-and-link note regressions under Node." [] (run-tests 'candlelight.note-link-test))```