editor.cljs 127 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272
  1. (ns frontend.handler.editor
  2. (:require [cljs.core.match :refer [match]]
  3. [clojure.set :as set]
  4. [clojure.string :as string]
  5. [clojure.walk :as w]
  6. [clojure.zip :as zip]
  7. [dommy.core :as dom]
  8. [frontend.commands :as commands
  9. :refer [*angle-bracket-caret-pos *show-block-commands *show-commands *slash-caret-pos]]
  10. [frontend.config :as config]
  11. [frontend.date :as date]
  12. [frontend.db :as db]
  13. [frontend.db-schema :as db-schema]
  14. [frontend.db.model :as db-model]
  15. [frontend.db.utils :as db-utils]
  16. [frontend.diff :as diff]
  17. [frontend.extensions.html-parser :as html-parser]
  18. [frontend.format.block :as block]
  19. [frontend.format.mldoc :as mldoc]
  20. [frontend.fs :as fs]
  21. [frontend.util.clock :as clock]
  22. [frontend.handler.block :as block-handler]
  23. [frontend.handler.common :as common-handler]
  24. [frontend.handler.image :as image-handler]
  25. [frontend.handler.notification :as notification]
  26. [frontend.handler.repeated :as repeated]
  27. [frontend.handler.repo :as repo-handler]
  28. [frontend.handler.route :as route-handler]
  29. [frontend.handler.ui :as ui-handler]
  30. [frontend.handler.export :as export]
  31. [frontend.util.drawer :as drawer]
  32. [frontend.image :as image]
  33. [frontend.modules.outliner.core :as outliner-core]
  34. [frontend.modules.outliner.tree :as tree]
  35. [frontend.search :as search]
  36. [frontend.state :as state]
  37. [frontend.template :as template]
  38. [frontend.text :as text]
  39. [frontend.utf8 :as utf8]
  40. [frontend.util :as util :refer [profile]]
  41. [frontend.util.cursor :as cursor]
  42. [frontend.util.marker :as marker]
  43. [frontend.util.property :as property]
  44. [frontend.util.thingatpt :as thingatpt]
  45. [goog.dom :as gdom]
  46. [goog.dom.classes :as gdom-classes]
  47. [goog.object :as gobj]
  48. [lambdaisland.glogi :as log]
  49. [medley.core :as medley]
  50. [promesa.core :as p]
  51. ["/frontend/utils" :as utils]
  52. [frontend.mobile.util :as mobile]))
  53. ;; FIXME: should support multiple images concurrently uploading
  54. (defonce *asset-uploading? (atom false))
  55. (defonce *asset-uploading-process (atom 0))
  56. (defonce *selected-text (atom nil))
  57. (defn- get-selection-and-format
  58. []
  59. (when-let [block (state/get-edit-block)]
  60. (when-let [id (:block/uuid block)]
  61. (when-let [edit-id (state/get-edit-input-id)]
  62. (when-let [input (gdom/getElement edit-id)]
  63. {:selection-start (gobj/get input "selectionStart")
  64. :selection-end (gobj/get input "selectionEnd")
  65. :format (:block/format block)
  66. :value (gobj/get input "value")
  67. :block block
  68. :edit-id edit-id
  69. :input input})))))
  70. (defn- format-text!
  71. [pattern-fn]
  72. (when-let [m (get-selection-and-format)]
  73. (let [{:keys [selection-start selection-end format value block edit-id input]} m
  74. empty-selection? (= selection-start selection-end)
  75. pattern (pattern-fn format)
  76. pattern-count (count pattern)
  77. pattern-prefix (subs value (max 0 (- selection-start pattern-count)) selection-start)
  78. pattern-suffix (subs value selection-end (min (count value) (+ selection-end pattern-count)))
  79. already-wrapped? (= pattern pattern-prefix pattern-suffix)
  80. prefix (if already-wrapped?
  81. (subs value 0 (- selection-start pattern-count))
  82. (subs value 0 selection-start))
  83. postfix (if already-wrapped?
  84. (subs value (+ selection-end pattern-count))
  85. (subs value selection-end))
  86. inner-value (cond-> (subs value selection-start selection-end)
  87. (not already-wrapped?) (#(str pattern % pattern)))
  88. new-value (str prefix inner-value postfix)]
  89. (state/set-edit-content! edit-id new-value)
  90. (cond
  91. already-wrapped? (cursor/set-selection-to input (- selection-start pattern-count) (- selection-end pattern-count))
  92. empty-selection? (cursor/move-cursor-to input (+ selection-end pattern-count))
  93. :else (cursor/set-selection-to input (+ selection-start pattern-count) (+ selection-end pattern-count))))))
  94. (defn bold-format! []
  95. (format-text! config/get-bold))
  96. (defn italics-format! []
  97. (format-text! config/get-italic))
  98. (defn highlight-format! [state]
  99. (when-let [block (state/get-edit-block)]
  100. (let [format (:block/format block)]
  101. (format-text! #(config/get-highlight format)))))
  102. (defn strike-through-format! []
  103. (format-text! config/get-strike-through))
  104. (defn html-link-format! []
  105. (when-let [m (get-selection-and-format)]
  106. (let [{:keys [selection-start selection-end format value block edit-id input]} m
  107. cur-pos (cursor/pos input)
  108. empty-selection? (= selection-start selection-end)
  109. selection (subs value selection-start selection-end)
  110. selection-link? (and selection (or (util/starts-with? selection "http://")
  111. (util/starts-with? selection "https://")))
  112. [content forward-pos] (cond
  113. empty-selection?
  114. (config/get-empty-link-and-forward-pos format)
  115. selection-link?
  116. (config/with-default-link format selection)
  117. :else
  118. (config/with-default-label format selection))
  119. new-value (str
  120. (subs value 0 selection-start)
  121. content
  122. (subs value selection-end))
  123. cur-pos (or selection-start cur-pos)]
  124. (state/set-edit-content! edit-id new-value)
  125. (cursor/move-cursor-to input (+ cur-pos forward-pos)))))
  126. (defn open-block-in-sidebar!
  127. [block-id]
  128. (when block-id
  129. (when-let [block (db/pull [:block/uuid block-id])]
  130. (state/sidebar-add-block!
  131. (state/get-current-repo)
  132. (:db/id block)
  133. :block
  134. block))))
  135. (defn reset-cursor-range!
  136. [node]
  137. (when node
  138. (state/set-cursor-range! (util/caret-range node))))
  139. (defn restore-cursor-pos!
  140. [id markup]
  141. (when-let [node (gdom/getElement (str id))]
  142. (when-let [cursor-range (state/get-cursor-range)]
  143. (when-let [range cursor-range]
  144. (let [pos (diff/find-position markup range)]
  145. (cursor/move-cursor-to node pos))))))
  146. (defn highlight-block!
  147. [block-uuid]
  148. (let [blocks (array-seq (js/document.getElementsByClassName (str block-uuid)))]
  149. (doseq [block blocks]
  150. (dom/add-class! block "block-highlight"))))
  151. (defn unhighlight-blocks!
  152. []
  153. (let [blocks (some->> (array-seq (js/document.getElementsByClassName "block-highlight"))
  154. (repeat 2)
  155. (apply concat))]
  156. (doseq [block blocks]
  157. (gdom-classes/remove block "block-highlight"))))
  158. ;; FIXME: children' :block/path-ref-pages
  159. (defn compute-retract-refs
  160. "Computes old references to be retracted."
  161. [eid {:block/keys [refs]} old-refs]
  162. ;; TODO:
  163. )
  164. (defn- get-edit-input-id-with-block-id
  165. [block-id]
  166. (when-let [first-block (util/get-first-block-by-id block-id)]
  167. (string/replace (gobj/get first-block "id")
  168. "ls-block"
  169. "edit-block")))
  170. (defn clear-selection!
  171. []
  172. (util/select-unhighlight! (dom/by-class "selected"))
  173. (state/clear-selection!))
  174. (defn- text-range-by-lst-fst-line [content [direction pos]]
  175. (case direction
  176. :up
  177. (let [last-new-line (or (string/last-index-of content \newline) -1)
  178. end (+ last-new-line pos 1)]
  179. (subs content 0 end))
  180. :down
  181. (-> (string/split-lines content)
  182. first
  183. (or "")
  184. (subs 0 pos))))
  185. ;; id: block dom id, "ls-block-counter-uuid"
  186. (defn edit-block!
  187. ([block pos format id]
  188. (edit-block! block pos format id nil))
  189. ([block pos format id {:keys [custom-content tail-len move-cursor?]
  190. :or {tail-len 0
  191. move-cursor? true}}]
  192. (when-not config/publishing?
  193. (when-let [block-id (:block/uuid block)]
  194. (let [block (or (db/pull [:block/uuid block-id]) block)
  195. edit-input-id (if (uuid? id)
  196. (get-edit-input-id-with-block-id id)
  197. (-> (str (subs id 0 (- (count id) 36)) block-id)
  198. (string/replace "ls-block" "edit-block")))
  199. content (or custom-content (:block/content block) "")
  200. content-length (count content)
  201. text-range (cond
  202. (vector? pos)
  203. (text-range-by-lst-fst-line content pos)
  204. (and (> tail-len 0) (>= (count content) tail-len))
  205. (subs content 0 (- (count content) tail-len))
  206. (or (= :max pos) (<= content-length pos))
  207. content
  208. :else
  209. (subs content 0 pos))
  210. content (-> (property/remove-built-in-properties (:block/format block)
  211. content)
  212. (drawer/remove-logbook))]
  213. (clear-selection!)
  214. (state/set-editing! edit-input-id content block text-range move-cursor?))))))
  215. (defn edit-last-block-for-new-page!
  216. [last-block pos]
  217. (when-let [first-block (util/get-first-block-by-id (:block/uuid last-block))]
  218. (edit-block!
  219. last-block
  220. pos
  221. (:block/format last-block)
  222. (string/replace (gobj/get first-block "id")
  223. "ls-block"
  224. "edit-block"))))
  225. (defn- another-block-with-same-id-exists?
  226. [current-id block-id]
  227. (and (string? block-id)
  228. (util/uuid-string? block-id)
  229. (not= current-id (cljs.core/uuid block-id))
  230. (db/entity [:block/uuid (cljs.core/uuid block-id)])))
  231. (defn- attach-page-properties-if-exists!
  232. [block]
  233. (if (and (:block/pre-block? block)
  234. (seq (:block/properties block)))
  235. (let [page-properties (:block/properties block)
  236. str->page (fn [n] (block/page-name->map n true))
  237. refs (->> page-properties
  238. (filter (fn [[_ v]] (coll? v)))
  239. (vals)
  240. (apply concat)
  241. (set)
  242. (map str->page)
  243. (concat (:block/refs block))
  244. (util/distinct-by :block/name))
  245. {:keys [tags alias]} page-properties
  246. page-tx (let [id (:db/id (:block/page block))
  247. retract-attributes (when id
  248. (mapv (fn [attribute]
  249. [:db/retract id attribute])
  250. [:block/properties :block/tags :block/alias]))
  251. tx (cond-> {:db/id id
  252. :block/properties page-properties}
  253. (seq tags)
  254. (assoc :block/tags (map str->page tags))
  255. (seq alias)
  256. (assoc :block/alias (map str->page alias)))]
  257. (conj retract-attributes tx))]
  258. (assoc block
  259. :block/refs refs
  260. :db/other-tx page-tx))
  261. block))
  262. (defn- remove-non-existed-refs!
  263. [refs]
  264. (remove (fn [x] (and (vector? x)
  265. (= :block/uuid (first x))
  266. (nil? (db/entity x)))) refs))
  267. (defn- with-marker-time
  268. [content block format new-marker old-marker]
  269. (if (and (state/enable-timetracking?) new-marker)
  270. (try
  271. (let [logbook-exists? (and (:block/body block) (drawer/get-logbook (:block/body block)))
  272. new-marker (string/trim (string/lower-case (name new-marker)))
  273. old-marker (when old-marker (string/trim (string/lower-case (name old-marker))))
  274. new-content (cond
  275. (or (and (nil? old-marker) (or (= new-marker "doing")
  276. (= new-marker "now")))
  277. (and (= old-marker "todo") (= new-marker "doing"))
  278. (and (= old-marker "later") (= new-marker "now"))
  279. (and (= old-marker new-marker "now") (not logbook-exists?))
  280. (and (= old-marker new-marker "doing") (not logbook-exists?)))
  281. (clock/clock-in format content)
  282. (or
  283. (and (= old-marker "doing") (= new-marker "todo"))
  284. (and (= old-marker "now") (= new-marker "later"))
  285. (and (contains? #{"now" "doing"} old-marker)
  286. (= new-marker "done")))
  287. (clock/clock-out format content)
  288. :else
  289. content)]
  290. new-content)
  291. (catch js/Error _e
  292. content))
  293. content))
  294. (defn- with-timetracking
  295. [block value]
  296. (if (and (state/enable-timetracking?)
  297. (not= (:block/content block) value))
  298. (let [new-marker (first (util/safe-re-find marker/bare-marker-pattern (or value "")))
  299. new-value (with-marker-time value block (:block/format block)
  300. new-marker
  301. (:block/marker block))]
  302. new-value)
  303. value))
  304. (defn wrap-parse-block
  305. [{:block/keys [content format parent left page uuid pre-block? level] :as block}]
  306. (let [block (or (and (:db/id block) (db/pull (:db/id block))) block)
  307. properties (:block/properties block)
  308. real-content (:block/content block)
  309. content (if (and (seq properties) real-content (not= real-content content))
  310. (property/with-built-in-properties properties content format)
  311. content)
  312. content (with-timetracking block content)
  313. first-block? (= left page)
  314. ast (mldoc/->edn (string/trim content) (mldoc/default-config format))
  315. first-elem-type (first (ffirst ast))
  316. first-elem-meta (second (ffirst ast))
  317. properties? (contains? #{"Property_Drawer" "Properties"} first-elem-type)
  318. markdown-heading? (and (= format :markdown)
  319. (= "Heading" first-elem-type)
  320. (nil? (:size first-elem-meta)))
  321. block-with-title? (mldoc/block-with-title? first-elem-type)
  322. content (string/triml content)
  323. content (string/replace content (util/format "((%s))" (str uuid)) "")
  324. [content content'] (cond
  325. (and first-block? properties?)
  326. [content content]
  327. markdown-heading?
  328. [content content]
  329. :else
  330. (let [content' (str (config/get-block-pattern format) (if block-with-title? " " "\n") content)]
  331. [content content']))
  332. block (assoc block
  333. :block/content content'
  334. :block/format format)
  335. block (apply dissoc block (remove #{:block/pre-block?} db-schema/retract-attributes))
  336. block (block/parse-block block)
  337. block (if (and first-block? (:block/pre-block? block))
  338. block
  339. (dissoc block :block/pre-block?))
  340. block (update block :block/refs remove-non-existed-refs!)
  341. block (attach-page-properties-if-exists! block)
  342. new-properties (merge
  343. (select-keys properties (property/built-in-properties))
  344. (:block/properties block))]
  345. (-> block
  346. (dissoc :block/top?
  347. :block/bottom?)
  348. (assoc :block/content content
  349. :block/properties new-properties)
  350. (merge (if level {:block/level level} {})))))
  351. (defn- save-block-inner!
  352. [repo block value {:keys [refresh?]
  353. :or {refresh? true}}]
  354. (let [block (assoc block :block/content value)
  355. block (apply dissoc block db-schema/retract-attributes)]
  356. (profile
  357. "Save block: "
  358. (let [block (wrap-parse-block block)]
  359. (-> (outliner-core/block block)
  360. (outliner-core/save-node))
  361. (when refresh?
  362. (let [opts {:key :block/change
  363. :data [block]}]
  364. (db/refresh! repo opts)))
  365. ;; page title changed
  366. (when-let [title (get-in block [:block/properties :title])]
  367. (when-let [old-title (:block/name (db/entity (:db/id (:block/page block))))]
  368. (when (and (:block/pre-block? block)
  369. (not (string/blank? title))
  370. (not= (string/lower-case title) old-title))
  371. (state/pub-event! [:page/title-property-changed old-title title]))))))
  372. (repo-handler/push-if-auto-enabled! repo)))
  373. (defn save-block-if-changed!
  374. ([block value]
  375. (save-block-if-changed! block value nil))
  376. ([block value
  377. {:keys [force?]
  378. :as opts}]
  379. (let [{:block/keys [uuid file page format repo content properties]} block
  380. repo (or repo (state/get-current-repo))
  381. e (db/entity repo [:block/uuid uuid])
  382. format (or format (state/get-preferred-format))
  383. page (db/entity repo (:db/id page))
  384. block-id (when (map? properties) (get properties :id))
  385. content (-> (property/remove-built-in-properties format content)
  386. (drawer/remove-logbook))]
  387. (cond
  388. (another-block-with-same-id-exists? uuid block-id)
  389. (notification/show!
  390. [:p.content
  391. (util/format "Block with the id % already exists!" block-id)]
  392. :error)
  393. force?
  394. (save-block-inner! repo block value opts)
  395. :else
  396. (let [content-changed? (not= (string/trim content) (string/trim value))]
  397. (when (and content-changed? page)
  398. (save-block-inner! repo block value opts)))))))
  399. (defn- compute-fst-snd-block-text
  400. [value pos]
  401. (when (string? value)
  402. (let [fst-block-text (subs value 0 pos)
  403. snd-block-text (string/triml (subs value pos))]
  404. [fst-block-text snd-block-text])))
  405. (defn outliner-insert-block!
  406. [config current-block new-block sibling?]
  407. (let [ref-top-block? (and (:ref? config)
  408. (not (:ref-child? config)))
  409. skip-save-current-block? (:skip-save-current-block? config)
  410. [current-node new-node]
  411. (mapv outliner-core/block [current-block new-block])
  412. has-children? (db/has-children? (state/get-current-repo)
  413. (tree/-get-id current-node))
  414. sibling? (cond
  415. ref-top-block?
  416. false
  417. (boolean? sibling?)
  418. sibling?
  419. (:collapsed (:block/properties current-block))
  420. true
  421. :else
  422. (not has-children?))]
  423. (let [*blocks (atom [current-node])]
  424. (when-not skip-save-current-block?
  425. (outliner-core/save-node current-node))
  426. (outliner-core/insert-node new-node current-node sibling? {:blocks-atom *blocks
  427. :skip-transact? false})
  428. {:blocks @*blocks
  429. :sibling? sibling?})))
  430. (defn- block-self-alone-when-insert?
  431. [config uuid]
  432. (let [current-page (state/get-current-page)
  433. block-id (or
  434. (and (:id config)
  435. (util/uuid-string? (:id config))
  436. (:id config))
  437. (and current-page
  438. (util/uuid-string? current-page)
  439. current-page))]
  440. (= uuid (and block-id (medley/uuid block-id)))))
  441. ;; FIXME: painful
  442. (defn update-cache-for-block-insert!
  443. "Currently, this only affects current editor container to improve the performance."
  444. [repo config {:block/keys [page uuid] :as block} blocks]
  445. (let [blocks (map :data blocks)
  446. [first-block last-block right-block] blocks
  447. child? (= (first (:block/parent last-block))
  448. (:block/uuid first-block))
  449. blocks-container-id (when-let [id (:id config)]
  450. (and (util/uuid-string? id) (medley/uuid id)))]
  451. (let [new-last-block (let [first-block-uuid (:block/uuid (db/entity (:db/id first-block)))
  452. first-block-id {:db/id (:db/id first-block)}]
  453. (assoc last-block
  454. :block/left first-block-id
  455. :block/parent (if child?
  456. first-block-id
  457. ;; sibling
  458. (:block/parent first-block))))
  459. blocks [first-block new-last-block]
  460. blocks-atom (if blocks-container-id
  461. (db/get-block-blocks-cache-atom repo blocks-container-id)
  462. (db/get-page-blocks-cache-atom repo (:db/id page)))
  463. [before-part after-part] (and blocks-atom
  464. (split-with
  465. #(not= uuid (:block/uuid %))
  466. @blocks-atom))
  467. after-part (rest after-part)
  468. blocks (concat before-part blocks after-part)
  469. blocks (if right-block
  470. (map (fn [block]
  471. (if (= (:block/uuid right-block) (:block/uuid block))
  472. (assoc block :block/left (:block/left right-block))
  473. block)) blocks)
  474. blocks)]
  475. (when blocks-atom
  476. (reset! blocks-atom blocks)))))
  477. (defn insert-new-block-before-block-aux!
  478. [config
  479. {:block/keys [uuid content repo format page]
  480. db-id :db/id
  481. :as block}
  482. value
  483. {:keys [ok-handler]
  484. :as opts}]
  485. (let [input (gdom/getElement (state/get-edit-input-id))
  486. pos (cursor/pos input)
  487. repo (or repo (state/get-current-repo))
  488. [fst-block-text snd-block-text] (compute-fst-snd-block-text value pos)
  489. current-block (assoc block :block/content snd-block-text)
  490. current-block (apply dissoc current-block db-schema/retract-attributes)
  491. current-block (wrap-parse-block current-block)
  492. new-m {:block/uuid (db/new-block-id)
  493. :block/content fst-block-text}
  494. prev-block (-> (merge (select-keys block [:block/parent :block/left :block/format
  495. :block/page :block/file :block/journal?]) new-m)
  496. (wrap-parse-block))
  497. left-block (db/pull (:db/id (:block/left block)))
  498. _ (outliner-core/save-node (outliner-core/block current-block))
  499. sibling? (not= (:db/id left-block) (:db/id (:block/parent block)))
  500. {:keys [sibling? blocks]} (profile
  501. "outliner insert block"
  502. (outliner-insert-block! config left-block prev-block sibling?))]
  503. (db/refresh! repo {:key :block/insert :data [prev-block left-block current-block]})
  504. (profile "ok handler" (ok-handler prev-block))))
  505. (defn insert-new-block-aux!
  506. [config
  507. {:block/keys [uuid content repo format page]
  508. db-id :db/id
  509. :as block}
  510. value
  511. {:keys [ok-handler]
  512. :as opts}]
  513. (let [block-self? (block-self-alone-when-insert? config uuid)
  514. input (gdom/getElement (state/get-edit-input-id))
  515. pos (cursor/pos input)
  516. repo (or repo (state/get-current-repo))
  517. [fst-block-text snd-block-text] (compute-fst-snd-block-text value pos)
  518. current-block (assoc block :block/content fst-block-text)
  519. current-block (apply dissoc current-block db-schema/retract-attributes)
  520. current-block (wrap-parse-block current-block)
  521. zooming? (when-let [id (:id config)]
  522. (and (string? id) (util/uuid-string? id)))
  523. new-m {:block/uuid (db/new-block-id)
  524. :block/content snd-block-text}
  525. next-block (-> (merge (select-keys block [:block/parent :block/left :block/format
  526. :block/page :block/file :block/journal?]) new-m)
  527. (wrap-parse-block))
  528. sibling? (when block-self? false)
  529. {:keys [sibling? blocks]} (profile
  530. "outliner insert block"
  531. (outliner-insert-block! config current-block next-block sibling?))
  532. refresh-fn (fn []
  533. (let [opts {:key :block/insert
  534. :data [current-block next-block]}]
  535. (db/refresh! repo opts)))]
  536. (do
  537. (if (or (:ref? config)
  538. (not sibling?)
  539. zooming?)
  540. (refresh-fn)
  541. (do
  542. (profile "update cache " (update-cache-for-block-insert! repo config block blocks))
  543. (state/add-tx! refresh-fn)))
  544. ;; WORKAROUND: The block won't refresh itself even if the content is empty.
  545. (when block-self?
  546. (gobj/set input "value" ""))
  547. (profile "ok handler" (ok-handler next-block)))))
  548. (defn clear-when-saved!
  549. []
  550. (state/set-editor-show-input! nil)
  551. (state/set-editor-show-zotero! false)
  552. (state/set-editor-show-date-picker! false)
  553. (state/set-editor-show-page-search! false)
  554. (state/set-editor-show-block-search! false)
  555. (state/set-editor-show-template-search! false)
  556. (commands/restore-state true))
  557. (defn get-state
  558. []
  559. (let [[{:keys [on-hide block block-id block-parent-id format sidebar?]} id config] (state/get-editor-args)
  560. node (gdom/getElement id)]
  561. (when node
  562. (let [value (gobj/get node "value")
  563. pos (gobj/get node "selectionStart")]
  564. {:config config
  565. :on-hide on-hide
  566. :sidebar? sidebar?
  567. :format format
  568. :id id
  569. :block (or (db/pull [:block/uuid (:block/uuid block)]) block)
  570. :block-id block-id
  571. :block-parent-id block-parent-id
  572. :node node
  573. :value value
  574. :pos pos}))))
  575. (defn insert-new-block!
  576. ([state]
  577. (insert-new-block! state nil))
  578. ([state block-value]
  579. (when (and (not config/publishing?)
  580. (not= :insert (state/get-editor-op)))
  581. (state/set-editor-op! :insert)
  582. (when-let [state (get-state)]
  583. (let [{:keys [block value format id config]} state
  584. value (if (string? block-value) block-value value)
  585. block-id (:block/uuid block)
  586. block (or (db/pull [:block/uuid block-id])
  587. block)
  588. repo (or (:block/repo block) (state/get-current-repo))
  589. block-self? (block-self-alone-when-insert? config block-id)
  590. input (gdom/getElement (state/get-edit-input-id))
  591. pos (cursor/pos input)
  592. repo (or repo (state/get-current-repo))
  593. [fst-block-text snd-block-text] (compute-fst-snd-block-text value pos)
  594. insert-fn (match (mapv boolean [block-self? (seq fst-block-text) (seq snd-block-text)])
  595. [true _ _] insert-new-block-aux!
  596. [_ false true] insert-new-block-before-block-aux!
  597. [_ _ _] insert-new-block-aux!)]
  598. (insert-fn config block value
  599. {:ok-handler
  600. (fn [last-block]
  601. (edit-block! last-block 0 format id)
  602. (clear-when-saved!))}))))
  603. (state/set-editor-op! nil)))
  604. (defn api-insert-new-block!
  605. [content {:keys [page block-uuid sibling? before? properties custom-uuid re-render-root?]
  606. :or {sibling? false
  607. before? false
  608. re-render-root? true}}]
  609. (when (or page block-uuid)
  610. (let [before? (if page false before?)
  611. sibling? (if before? true (if page false sibling?))
  612. block (if page
  613. (db/entity [:block/name (string/lower-case page)])
  614. (db/entity [:block/uuid block-uuid]))]
  615. (when block
  616. (let [repo (state/get-current-repo)
  617. last-block (when (not sibling?)
  618. (let [children (:block/_parent block)
  619. blocks (db/sort-by-left children block)
  620. last-block-id (:db/id (last blocks))]
  621. (when last-block-id
  622. (db/pull last-block-id))))
  623. format (or
  624. (:block/format block)
  625. (db/get-page-format (:db/id block))
  626. (state/get-preferred-format))
  627. content (if (seq properties)
  628. (property/insert-properties format content properties)
  629. content)
  630. new-block (-> (select-keys block [:block/page :block/file :block/journal?
  631. :block/journal-day])
  632. (assoc :block/content content
  633. :block/format format))
  634. new-block (assoc new-block :block/page
  635. (if page
  636. (:db/id block)
  637. (:db/id (:block/page new-block))))
  638. new-block (-> new-block
  639. (wrap-parse-block)
  640. (assoc :block/uuid (or custom-uuid (db/new-block-id))))
  641. new-block (if-let [db-id (:db/id (:block/file block))]
  642. (assoc new-block :block/file db-id)
  643. new-block)]
  644. (let [[block-m sibling?] (cond
  645. before?
  646. (let [block (db/pull (:db/id (:block/left block)))
  647. sibling? (if (:block/name block) false sibling?)]
  648. [block sibling?])
  649. sibling?
  650. [(db/pull (:db/id block)) sibling?]
  651. last-block
  652. [last-block true]
  653. block
  654. [(db/pull (:db/id block)) sibling?]
  655. ;; FIXME: assert
  656. :else
  657. nil)]
  658. (when block-m
  659. (outliner-insert-block! {:skip-save-current-block? true} block-m new-block sibling?)
  660. (when re-render-root? (ui-handler/re-render-root!))
  661. new-block)))))))
  662. (defn insert-first-page-block-if-not-exists!
  663. [page-name]
  664. (when (string? page-name)
  665. (when-let [page (db/entity [:block/name (string/lower-case page-name)])]
  666. (when (db/page-empty? (state/get-current-repo) (:db/id page))
  667. (api-insert-new-block! "" {:page page-name})))))
  668. (defn properties-block
  669. [properties format page]
  670. (let [content (property/insert-properties format "" properties)
  671. refs (block/get-page-refs-from-properties properties)]
  672. {:block/pre-block? true
  673. :block/uuid (db/new-block-id)
  674. :block/properties properties
  675. :block/properties-order (keys properties)
  676. :block/refs refs
  677. :block/left page
  678. :block/format format
  679. :block/content content
  680. :block/parent page
  681. :block/unordered true
  682. :block/page page}))
  683. (defn default-properties-block
  684. ([title format page]
  685. (default-properties-block title format page {}))
  686. ([title format page properties]
  687. (let [p (common-handler/get-page-default-properties title)
  688. ps (merge p properties)
  689. content (property/insert-properties format "" ps)
  690. refs (block/get-page-refs-from-properties properties)]
  691. {:block/pre-block? true
  692. :block/uuid (db/new-block-id)
  693. :block/properties ps
  694. :block/properties-order (keys ps)
  695. :block/refs refs
  696. :block/left page
  697. :block/format format
  698. :block/content content
  699. :block/parent page
  700. :block/unordered true
  701. :block/page page})))
  702. (defn add-default-title-property-if-needed!
  703. [page-name]
  704. (when (string? page-name)
  705. (when-let [page (db/entity [:block/name (string/lower-case page-name)])]
  706. (when (db/page-empty? (state/get-current-repo) (:db/id page))
  707. (let [title (or (:block/original-name page)
  708. (:block/name page))
  709. format (db/get-page-format page)
  710. create-title-property? (util/create-title-property? title)]
  711. (when create-title-property?
  712. (let [default-properties (default-properties-block title format (:db/id page))
  713. new-empty-block (-> (dissoc default-properties :block/pre-block? :block/uuid :block/left :block/properties)
  714. (assoc :block/uuid (db/new-block-id)
  715. :block/content ""
  716. :block/left [:block/uuid (:block/uuid default-properties)]))]
  717. (db/transact! [default-properties new-empty-block])
  718. true)))))))
  719. (defn update-timestamps-content!
  720. [{:block/keys [repeated? marker format] :as block} content]
  721. (if repeated?
  722. (let [scheduled-ast (block-handler/get-scheduled-ast block)
  723. deadline-ast (block-handler/get-deadline-ast block)
  724. content (some->> (filter repeated/repeated? [scheduled-ast deadline-ast])
  725. (map (fn [ts]
  726. [(repeated/timestamp->text ts)
  727. (repeated/next-timestamp-text ts)]))
  728. (reduce (fn [content [old new]]
  729. (string/replace content old new))
  730. content))
  731. content (string/replace-first content "DOING" "TODO")
  732. content (clock/clock-out format content)
  733. content (drawer/insert-drawer
  734. format content "logbook"
  735. (util/format (str (if (= :org format) "-" "*")
  736. " State \"DONE\" from \"%s\" [%s]")
  737. marker
  738. (date/get-date-time-string-3)))]
  739. content)
  740. content))
  741. (defn check
  742. [{:block/keys [uuid marker content format repeated?] :as block}]
  743. (let [new-content (string/replace-first content marker "DONE")
  744. new-content (if repeated?
  745. (update-timestamps-content! block content)
  746. new-content)]
  747. (save-block-if-changed! block new-content)))
  748. (defn uncheck
  749. [{:block/keys [uuid marker content format] :as block}]
  750. (let [marker (if (= :now (state/get-preferred-workflow))
  751. "LATER"
  752. "TODO")
  753. new-content (string/replace-first content "DONE" marker)]
  754. (save-block-if-changed! block new-content)))
  755. (defn cycle-todo!
  756. []
  757. (when-let [block (state/get-edit-block)]
  758. (let [edit-input-id (state/get-edit-input-id)
  759. current-input (gdom/getElement edit-input-id)
  760. content (state/get-edit-content)
  761. format (or (db/get-page-format (state/get-current-page))
  762. (state/get-preferred-format))
  763. [new-content marker] (marker/cycle-marker content format (state/get-preferred-workflow))
  764. new-content (string/triml new-content)]
  765. (let [new-pos (commands/compute-pos-delta-when-change-marker
  766. current-input content new-content marker (cursor/pos current-input))]
  767. (state/set-edit-content! edit-input-id new-content)
  768. (cursor/move-cursor-to current-input new-pos)))))
  769. (defn set-marker
  770. [{:block/keys [uuid marker content format properties] :as block} new-marker]
  771. (let [new-content (string/replace-first content (re-pattern (str "^" marker)) new-marker)]
  772. (save-block-if-changed! block new-content)))
  773. (defn set-priority
  774. [{:block/keys [uuid marker priority content] :as block} new-priority]
  775. (let [new-content (string/replace-first content
  776. (util/format "[#%s]" priority)
  777. (util/format "[#%s]" new-priority))]
  778. (save-block-if-changed! block new-content)))
  779. (defn delete-block-aux!
  780. [{:block/keys [uuid content repo refs] :as block} children?]
  781. (let [repo (or repo (state/get-current-repo))
  782. block (db/pull repo '[*] [:block/uuid uuid])]
  783. (when block
  784. (->
  785. (outliner-core/block block)
  786. (outliner-core/delete-node children?))
  787. (db/refresh! repo {:key :block/change :data [block]}))))
  788. (defn- move-to-prev-block
  789. [repo sibling-block format id value]
  790. (when (and repo sibling-block)
  791. (when-let [sibling-block-id (dom/attr sibling-block "blockid")]
  792. (when-let [block (db/pull repo '[*] [:block/uuid (uuid sibling-block-id)])]
  793. (let [original-content (util/trim-safe (:block/content block))
  794. value' (-> (property/remove-built-in-properties format original-content)
  795. (drawer/remove-logbook))
  796. new-value (str value' " " (string/triml value))
  797. tail-len (count (string/triml value))
  798. pos (max
  799. (if original-content
  800. (utf8/length (utf8/encode original-content))
  801. 0)
  802. 0)]
  803. (edit-block! block pos format id
  804. {:custom-content new-value
  805. :tail-len tail-len
  806. :move-cursor? false}))))))
  807. (defn delete-block!
  808. ([repo e]
  809. (delete-block! repo e true))
  810. ([repo e delete-children?]
  811. (state/set-editor-op! :delete)
  812. (let [{:keys [id block-id block-parent-id value format]} (get-state)]
  813. (when block-id
  814. (let [page-id (:db/id (:block/page (db/entity [:block/uuid block-id])))
  815. page-blocks-count (and page-id (db/get-page-blocks-count repo page-id))]
  816. (when (> page-blocks-count 1)
  817. (let [block (db/entity [:block/uuid block-id])
  818. has-children? (seq (:block/_parent block))
  819. block (db/pull (:db/id block))
  820. left (tree/-get-left (outliner-core/block block))
  821. left-has-children? (and left
  822. (when-let [block-id (:block/uuid (:data left))]
  823. (let [block (db/entity [:block/uuid block-id])]
  824. (seq (:block/_parent block)))))]
  825. (when-not (and has-children? left-has-children?)
  826. (when block-parent-id
  827. (let [block-parent (gdom/getElement block-parent-id)
  828. sibling-block (util/get-prev-block-non-collapsed block-parent)]
  829. (delete-block-aux! block delete-children?)
  830. (move-to-prev-block repo sibling-block format id value)))))))))
  831. (state/set-editor-op! nil)))
  832. (defn- get-end-block-parent
  833. [end-block blocks]
  834. (if-let [parent (let [id (:db/id (:block/parent end-block))]
  835. (some (fn [block] (when (= (:db/id block) id) block)) blocks))]
  836. (recur parent blocks)
  837. end-block))
  838. (defn- get-top-level-end-node
  839. [blocks]
  840. (let [end-block (last blocks)
  841. end-block-parent (get-end-block-parent end-block blocks)]
  842. (outliner-core/block end-block-parent)))
  843. (defn- reorder-blocks
  844. [blocks]
  845. (if (<= (count blocks) 1)
  846. blocks
  847. (let [[f s & others] blocks]
  848. (if (or
  849. (= (:block/left s) {:db/id (:db/id f)})
  850. (let [parents (db/get-block-parents (state/get-current-repo)
  851. (:block/uuid f)
  852. 100)]
  853. (some #(= (:block/left s) {:db/id (:db/id %)})
  854. parents)))
  855. blocks
  856. (reverse blocks)))))
  857. (defn delete-blocks!
  858. [repo dom-blocks]
  859. (let [block-uuids (distinct (map #(uuid (dom/attr % "blockid")) dom-blocks))]
  860. (when (seq block-uuids)
  861. (let [uuid->dom-block (zipmap block-uuids dom-blocks)
  862. lookup-refs (map (fn [id] [:block/uuid id]) block-uuids)
  863. blocks (db/pull-many repo '[*] lookup-refs)
  864. blocks (reorder-blocks blocks)
  865. start-node (outliner-core/block (first blocks))
  866. end-node (get-top-level-end-node blocks)
  867. block (first blocks)
  868. block-parent (get uuid->dom-block (:block/uuid block))
  869. sibling-block (when block-parent (util/get-prev-block-non-collapsed block-parent))]
  870. (if (= start-node end-node)
  871. (delete-block-aux! (first blocks) true)
  872. (when (outliner-core/delete-nodes start-node end-node lookup-refs)
  873. (let [opts {:key :block/change
  874. :data blocks}]
  875. (db/refresh! repo opts)
  876. (ui-handler/re-render-root!))))
  877. (when sibling-block
  878. (move-to-prev-block repo sibling-block
  879. (:block/format block)
  880. (dom/attr sibling-block "id")
  881. ""))))))
  882. (defn- block-property-aux!
  883. [block-id key value]
  884. (let [block-id (if (string? block-id) (uuid block-id) block-id)
  885. repo (state/get-current-repo)]
  886. (when repo
  887. (when-let [block (db/entity [:block/uuid block-id])]
  888. (let [format (:block/format block)
  889. content (:block/content block)
  890. properties (:block/properties block)
  891. properties (if (nil? value)
  892. (dissoc properties key)
  893. (assoc properties key value))
  894. content (if (nil? value)
  895. (property/remove-property format key content)
  896. (property/insert-property format content key value))
  897. content (property/remove-empty-properties content)
  898. block (outliner-core/block {:block/uuid block-id
  899. :block/properties properties
  900. :block/content content})
  901. input-pos (or (state/get-edit-pos) :max)]
  902. (outliner-core/save-node block)
  903. (db/refresh! (state/get-current-repo)
  904. {:key :block/change
  905. :data [(db/pull [:block/uuid block-id])]})
  906. ;; update editing input content
  907. (when-let [editing-block (state/get-edit-block)]
  908. (when (= (:block/uuid editing-block) block-id)
  909. (edit-block! editing-block
  910. input-pos
  911. format
  912. (state/get-edit-input-id)))))))))
  913. (defn remove-block-property!
  914. [block-id key]
  915. (let [key (keyword key)]
  916. (block-property-aux! block-id key nil)))
  917. (defn set-block-property!
  918. [block-id key value]
  919. (let [key (keyword key)]
  920. (block-property-aux! block-id key value)))
  921. (defn set-block-query-properties!
  922. [block-id all-properties key add?]
  923. (when-let [block (db/entity [:block/uuid block-id])]
  924. (let [query-properties (-> (get-in block [:block/properties :query-properties] "")
  925. (common-handler/safe-read-string "Failed to parse query properties"))
  926. query-properties (if (seq query-properties)
  927. query-properties
  928. all-properties)
  929. query-properties (if add?
  930. (distinct (conj query-properties key))
  931. (remove #{key} query-properties))
  932. query-properties (vec query-properties)]
  933. (if (seq query-properties)
  934. (set-block-property! block-id :query-properties (str query-properties))
  935. (remove-block-property! block-id :query-properties)))))
  936. (defn set-block-timestamp!
  937. [block-id key value]
  938. (let [key (string/lower-case key)
  939. block-id (if (string? block-id) (uuid block-id) block-id)
  940. key (string/lower-case (str key))
  941. value (str value)]
  942. (when-let [block (db/pull [:block/uuid block-id])]
  943. (let [{:block/keys [content scheduled deadline format]} block
  944. content (or (state/get-edit-content) content)
  945. new-content (-> (text/remove-timestamp content key)
  946. (text/add-timestamp key value))]
  947. (when (not= content new-content)
  948. (if-let [input-id (state/get-edit-input-id)]
  949. (state/set-edit-content! input-id new-content)
  950. (save-block-if-changed! block new-content)))))))
  951. (defn copy-block-ref!
  952. ([block-id] (copy-block-ref! block-id #(str %)))
  953. ([block-id tap-clipboard]
  954. (let [block (db/entity [:block/uuid block-id])]
  955. (when-not (:block/pre-block? block)
  956. (set-block-property! block-id "id" (str block-id))))
  957. (util/copy-to-clipboard! (tap-clipboard block-id))))
  958. (defn select-block!
  959. [block-uuid]
  960. (when-let [block (-> (str block-uuid)
  961. (js/document.getElementsByClassName)
  962. first)]
  963. (state/exit-editing-and-set-selected-blocks! [block])))
  964. (defn- get-selected-blocks-with-children
  965. []
  966. (when-let [blocks (seq (state/get-selection-blocks))]
  967. (->> (mapcat (fn [block]
  968. (cons block
  969. (array-seq (dom/by-class block "ls-block"))))
  970. blocks)
  971. distinct)))
  972. (defn- blocks-with-level
  973. [blocks]
  974. (let [level-blocks (mapv #(assoc % :level 1) blocks)
  975. level-blocks-map (into {} (mapv (fn [b] [(:db/id b) b]) level-blocks))
  976. [level-blocks-map _]
  977. (reduce (fn [[r state] [id block]]
  978. (if-let [parent-level (get-in state [(:db/id (:block/parent block)) :level])]
  979. [(conj r [id (assoc block :level (inc parent-level))])
  980. (assoc-in state [(:db/id block) :level] (inc parent-level))]
  981. [(conj r [id block])
  982. state]))
  983. [{} level-blocks-map] level-blocks-map)]
  984. level-blocks-map))
  985. (defn- blocks-vec->tree
  986. [blocks]
  987. (let [loc (reduce (fn [loc {:keys [level] :as block}]
  988. (let [loc*
  989. (loop [loc (zip/vector-zip (zip/root loc))
  990. level level]
  991. (if (> level 1)
  992. (if-let [down (zip/rightmost (zip/down loc))]
  993. (let [down-node (zip/node down)]
  994. (if (or (and (vector? down-node)
  995. (>= (:level (first down-node)) (:level block)))
  996. (>= (:level down-node) (:level block)))
  997. down
  998. (recur down (dec level))))
  999. loc)
  1000. loc))
  1001. loc**
  1002. (if (vector? (zip/node loc*))
  1003. (zip/append-child loc* block)
  1004. (-> loc*
  1005. zip/up
  1006. (zip/append-child [block])))]
  1007. loc**)) (zip/vector-zip []) blocks)]
  1008. (clojure.walk/postwalk (fn [e] (if (map? e) (dissoc e :level) e)) (zip/root loc))))
  1009. (defn- compose-copied-blocks-contents-&-block-tree
  1010. [repo block-ids]
  1011. (let [blocks (db-utils/pull-many repo '[*] (mapv (fn [id] [:block/uuid id]) block-ids))
  1012. blocks* (flatten
  1013. (mapv (fn [b] (if (:collapsed (:block/properties b))
  1014. (vec (tree/sort-blocks (db/get-block-children repo (:block/uuid b)) b))
  1015. [b])) blocks))
  1016. block-ids* (mapv :block/uuid blocks*)
  1017. unordered? (:block/unordered (first blocks*))
  1018. format (:block/format (first blocks*))
  1019. level-blocks-map (blocks-with-level blocks*)
  1020. level-blocks-uuid-map (into {} (mapv (fn [b] [(:block/uuid b) b]) (vals level-blocks-map)))
  1021. level-blocks (mapv (fn [uuid] (get level-blocks-uuid-map uuid)) block-ids*)
  1022. tree (blocks-vec->tree level-blocks)
  1023. top-level-block-uuids (mapv :block/uuid (filterv #(not (vector? %)) tree))
  1024. exported-md-contents (export/export-blocks-as-markdown
  1025. repo top-level-block-uuids
  1026. (state/get-export-block-text-indent-style)
  1027. (into [] (state/get-export-block-text-remove-options)))]
  1028. [exported-md-contents tree]))
  1029. (defn copy-selection-blocks
  1030. []
  1031. (when-let [blocks (seq (get-selected-blocks-with-children))]
  1032. (let [repo (state/get-current-repo)
  1033. ids (->> (distinct (map #(when-let [id (dom/attr % "blockid")]
  1034. (uuid id)) blocks))
  1035. (remove nil?))
  1036. [content tree] (compose-copied-blocks-contents-&-block-tree repo ids)
  1037. block (db/pull [:block/uuid (first ids)])]
  1038. (common-handler/copy-to-clipboard-without-id-property! (:block/format block) content)
  1039. (state/set-copied-blocks content tree)
  1040. (notification/show! "Copied!" :success))))
  1041. (defn get-selected-toplevel-block-uuids
  1042. []
  1043. (when-let [blocks (seq (get-selected-blocks-with-children))]
  1044. (let [repo (state/get-current-repo)
  1045. block-ids (->> (distinct (map #(when-let [id (dom/attr % "blockid")]
  1046. (uuid id)) blocks))
  1047. (remove nil?))
  1048. blocks (db-utils/pull-many repo '[*] (mapv (fn [id] [:block/uuid id]) block-ids))
  1049. blocks* (flatten
  1050. (mapv (fn [b] (if (:collapsed (:block/properties b))
  1051. (vec (tree/sort-blocks (db/get-block-children repo (:block/uuid b)) b))
  1052. [b])) blocks))
  1053. block-ids* (mapv :block/uuid blocks*)
  1054. unordered? (:block/unordered (first blocks*))
  1055. format (:block/format (first blocks*))
  1056. level-blocks-map (blocks-with-level blocks*)
  1057. level-blocks-uuid-map (into {} (mapv (fn [b] [(:block/uuid b) b]) (vals level-blocks-map)))
  1058. level-blocks (mapv (fn [uuid] (get level-blocks-uuid-map uuid)) block-ids*)
  1059. tree (blocks-vec->tree level-blocks)
  1060. top-level-block-uuids (mapv :block/uuid (filterv #(not (vector? %)) tree))]
  1061. top-level-block-uuids)))
  1062. (defn cut-selection-blocks
  1063. [copy?]
  1064. (when copy? (copy-selection-blocks))
  1065. (when-let [blocks (seq (get-selected-blocks-with-children))]
  1066. ;; remove embeds, references and queries
  1067. (let [blocks (remove (fn [block]
  1068. (or (= "true" (dom/attr block "data-transclude"))
  1069. (= "true" (dom/attr block "data-query")))) blocks)]
  1070. (when (seq blocks)
  1071. (let [repo (state/get-current-repo)]
  1072. (delete-blocks! repo blocks))))))
  1073. (defn- get-nearest-page
  1074. []
  1075. (when-let [block (state/get-edit-block)]
  1076. (when-let [id (:block/uuid block)]
  1077. (when-let [edit-id (state/get-edit-input-id)]
  1078. (when-let [input (gdom/getElement edit-id)]
  1079. (when-let [pos (cursor/pos input)]
  1080. (let [value (gobj/get input "value")
  1081. page-pattern #"\[\[([^\]]+)]]"
  1082. block-pattern #"\(\(([^\)]+)\)\)"
  1083. page-matches (util/re-pos page-pattern value)
  1084. block-matches (util/re-pos block-pattern value)
  1085. matches (->> (concat page-matches block-matches)
  1086. (remove nil?))
  1087. [_ page] (first (sort-by
  1088. (fn [[start-pos content]]
  1089. (let [end-pos (+ start-pos (count content))]
  1090. (cond
  1091. (< pos start-pos)
  1092. (- pos start-pos)
  1093. (> pos end-pos)
  1094. (- end-pos pos)
  1095. :else
  1096. 0)))
  1097. >
  1098. matches))]
  1099. (when page
  1100. (subs page 2 (- (count page) 2))))))))))
  1101. (defn follow-link-under-cursor!
  1102. []
  1103. (when-let [page (get-nearest-page)]
  1104. (when-not (string/blank? page)
  1105. (let [page-name (string/lower-case page)]
  1106. (state/clear-edit!)
  1107. (insert-first-page-block-if-not-exists! page-name)
  1108. (route-handler/redirect! {:to :page
  1109. :path-params {:name page-name}})))))
  1110. (defn open-link-in-sidebar!
  1111. []
  1112. (when-let [page (get-nearest-page)]
  1113. (let [page-name (string/lower-case page)
  1114. block? (util/uuid-string? page-name)]
  1115. (when-let [page (db/get-page page-name)]
  1116. (if block?
  1117. (state/sidebar-add-block!
  1118. (state/get-current-repo)
  1119. (:db/id page)
  1120. :block
  1121. page)
  1122. (state/sidebar-add-block!
  1123. (state/get-current-repo)
  1124. (:db/id page)
  1125. :page
  1126. {:page page}))))))
  1127. (defn zoom-in! []
  1128. (if (state/editing?)
  1129. (when-let [id (some-> (state/get-edit-block)
  1130. :block/uuid
  1131. ((fn [id] [:block/uuid id]))
  1132. db/entity
  1133. :block/uuid)]
  1134. (let [pos (state/get-edit-pos)]
  1135. (route-handler/redirect! {:to :page
  1136. :path-params {:name (str id)}})
  1137. (edit-block! {:block/uuid id} pos nil id)))
  1138. (js/window.history.forward)))
  1139. (defn zoom-out!
  1140. []
  1141. (if (state/editing?)
  1142. (let [page (state/get-current-page)
  1143. block-id (and
  1144. (string? page)
  1145. (util/uuid-string? page)
  1146. (medley/uuid page))]
  1147. (when block-id
  1148. (let [block-parent (db/get-block-parent block-id)]
  1149. (if-let [id (and
  1150. (nil? (:block/name block-parent))
  1151. (:block/uuid block-parent))]
  1152. (do
  1153. (route-handler/redirect! {:to :page
  1154. :path-params {:name (str id)}})
  1155. (edit-block! {:block/uuid block-id} :max nil block-id))
  1156. (let [page-id (some-> (db/entity [:block/uuid block-id])
  1157. :block/page
  1158. :db/id)]
  1159. (when-let [page-name (:block/name (db/entity page-id))]
  1160. (route-handler/redirect! {:to :page
  1161. :path-params {:name page-name}})
  1162. (edit-block! {:block/uuid block-id} :max nil block-id)))))))
  1163. (js/window.history.back)))
  1164. (defn cut-block!
  1165. [block-id]
  1166. (when-let [block (db/pull [:block/uuid block-id])]
  1167. (let [content (:block/content block)]
  1168. (common-handler/copy-to-clipboard-without-id-property! (:block/format block) content)
  1169. (delete-block-aux! block true))))
  1170. (defn clear-last-selected-block!
  1171. []
  1172. (let [block (state/drop-last-selection-block!)]
  1173. (util/select-unhighlight! [block])))
  1174. (defn input-start-or-end?
  1175. ([input]
  1176. (input-start-or-end? input nil))
  1177. ([input up?]
  1178. (let [value (gobj/get input "value")
  1179. start (gobj/get input "selectionStart")
  1180. end (gobj/get input "selectionEnd")]
  1181. (if (nil? up?)
  1182. (or (= start 0) (= end (count value)))
  1183. (or (and (= start 0) up?)
  1184. (and (= end (count value)) (not up?)))))))
  1185. (defn highlight-selection-area!
  1186. [end-block]
  1187. (when-let [start-block (state/get-selection-start-block)]
  1188. (let [blocks (util/get-nodes-between-two-nodes start-block end-block "ls-block")
  1189. direction (util/get-direction-between-two-nodes start-block end-block "ls-block")
  1190. blocks (if (= :up direction)
  1191. (reverse blocks)
  1192. blocks)]
  1193. (state/exit-editing-and-set-selected-blocks! blocks direction))))
  1194. (defn on-select-block
  1195. [direction]
  1196. (fn [e]
  1197. (cond
  1198. ;; when editing, quit editing and select current block
  1199. (state/editing?)
  1200. (state/exit-editing-and-set-selected-blocks! [(gdom/getElement (state/get-editing-block-dom-id))])
  1201. ;; when selection and one block selected, select next block
  1202. (and (state/selection?) (== 1 (count (state/get-selection-blocks))))
  1203. (let [f (if (= :up direction) util/get-prev-block-non-collapsed util/get-next-block-non-collapsed-skip)
  1204. element (f (first (state/get-selection-blocks)))]
  1205. (when element
  1206. (state/conj-selection-block! element direction)))
  1207. ;; if same direction, keep conj on same direction
  1208. (and (state/selection?) (= direction (state/get-selection-direction)))
  1209. (let [f (if (= :up direction) util/get-prev-block-non-collapsed util/get-next-block-non-collapsed-skip)
  1210. first-last (if (= :up direction) first last)
  1211. element (f (first-last (state/get-selection-blocks)))]
  1212. (when element
  1213. (state/conj-selection-block! element direction)))
  1214. ;; if different direction, keep clear until one left
  1215. (state/selection?)
  1216. (clear-last-selected-block!))))
  1217. (defn save-block-aux!
  1218. [block value format opts]
  1219. (let [value (string/trim value)]
  1220. ;; FIXME: somehow frontend.components.editor's will-unmount event will loop forever
  1221. ;; maybe we shouldn't save the block/file in "will-unmount" event?
  1222. (save-block-if-changed! block value
  1223. (merge
  1224. {:init-properties (:block/properties block)}
  1225. opts))))
  1226. (defn save-block!
  1227. ([repo block-or-uuid content]
  1228. (let [block (if (or (uuid? block-or-uuid)
  1229. (string? block-or-uuid))
  1230. (db-model/query-block-by-uuid block-or-uuid) block-or-uuid)
  1231. format (:block/format block)]
  1232. (save-block! {:block block :repo repo :format format} content)))
  1233. ([{:keys [format block repo] :as state} value]
  1234. (when (:db/id (db/entity repo [:block/uuid (:block/uuid block)]))
  1235. (save-block-aux! block value format {}))))
  1236. (defn save-current-block!
  1237. ([]
  1238. (save-current-block! {}))
  1239. ([{:keys [force?] :as opts}]
  1240. ;; non English input method
  1241. (when-not (state/editor-in-composition?)
  1242. (when-let [repo (state/get-current-repo)]
  1243. (when (and (not @commands/*show-commands)
  1244. (not @commands/*show-block-commands)
  1245. (not (state/get-editor-show-page-search?))
  1246. (not (state/get-editor-show-page-search-hashtag?))
  1247. (not (state/get-editor-show-block-search?))
  1248. (not (state/get-editor-show-date-picker?))
  1249. (not (state/get-editor-show-template-search?))
  1250. (not (state/get-editor-show-input)))
  1251. (try
  1252. (let [input-id (state/get-edit-input-id)
  1253. block (state/get-edit-block)
  1254. db-block (when-let [block-id (:block/uuid block)]
  1255. (db/pull [:block/uuid block-id]))
  1256. elem (and input-id (gdom/getElement input-id))
  1257. db-content (:block/content db-block)
  1258. db-content-without-heading (and db-content
  1259. (util/safe-subs db-content (:block/level db-block)))
  1260. value (and elem (gobj/get elem "value"))]
  1261. (cond
  1262. force?
  1263. (save-block-aux! db-block value (:block/format db-block) opts)
  1264. (and block value db-content-without-heading
  1265. (or
  1266. (not= (string/trim db-content-without-heading)
  1267. (string/trim value))))
  1268. (save-block-aux! db-block value (:block/format db-block) opts)))
  1269. (catch js/Error error
  1270. (log/error :save-block-failed error))))))))
  1271. (defn- clean-content!
  1272. [format content]
  1273. (->> (text/remove-level-spaces content format)
  1274. (drawer/remove-logbook)
  1275. (property/remove-properties format)
  1276. string/trim))
  1277. (defn insert-command!
  1278. [id command-output format {:keys [restore?]
  1279. :or {restore? true}
  1280. :as option}]
  1281. (cond
  1282. ;; replace string
  1283. (string? command-output)
  1284. (commands/insert! id command-output option)
  1285. ;; steps
  1286. (vector? command-output)
  1287. (commands/handle-steps command-output format)
  1288. (fn? command-output)
  1289. (let [s (command-output)]
  1290. (commands/insert! id s option))
  1291. :else
  1292. nil)
  1293. (when restore?
  1294. (let [restore-slash-caret-pos? (if (and
  1295. (seq? command-output)
  1296. (= :editor/click-hidden-file-input
  1297. (ffirst command-output)))
  1298. false
  1299. true)]
  1300. (commands/restore-state restore-slash-caret-pos?))))
  1301. (defn- get-asset-file-link
  1302. [format url file-name image?]
  1303. (let [pdf? (and url (string/ends-with? url ".pdf"))]
  1304. (case (keyword format)
  1305. :markdown (util/format (str (when (or image? pdf?) "!") "[%s](%s)") file-name url)
  1306. :org (if image?
  1307. (util/format "[[%s]]" url)
  1308. (util/format "[[%s][%s]]" url file-name))
  1309. nil)))
  1310. (defn- get-asset-link
  1311. [url]
  1312. (str "/" url))
  1313. (defn ensure-assets-dir!
  1314. [repo]
  1315. (let [repo-dir (config/get-repo-dir repo)
  1316. assets-dir "assets"]
  1317. (p/then
  1318. (fs/mkdir-if-not-exists (str repo-dir "/" assets-dir))
  1319. (fn [] [repo-dir assets-dir]))))
  1320. (defn save-assets!
  1321. ([{block-id :block/uuid} repo files]
  1322. (p/let [[repo-dir assets-dir] (ensure-assets-dir! repo)]
  1323. (save-assets! repo repo-dir assets-dir files
  1324. (fn [index file-base]
  1325. ;; TODO: maybe there're other chars we need to handle?
  1326. (let [file-base (-> file-base
  1327. (string/replace " " "_")
  1328. (string/replace "%" "_")
  1329. (string/replace "/" "_"))
  1330. file-name (str file-base "_" (.now js/Date) "_" index)]
  1331. (string/replace file-name #"_+" "_"))))))
  1332. ([repo dir path files gen-filename]
  1333. (p/all
  1334. (for [[index ^js file] (map-indexed vector files)]
  1335. (do
  1336. ;; WARN file name maybe fully qualified path when paste file
  1337. (let [file-name (util/node-path.basename (.-name file))
  1338. [file-base ext] (if file-name
  1339. (let [last-dot-index (string/last-index-of file-name ".")]
  1340. [(subs file-name 0 last-dot-index)
  1341. (subs file-name last-dot-index)])
  1342. ["" ""])
  1343. filename (str (gen-filename index file-base) ext)
  1344. filename (str path "/" filename)]
  1345. ;(js/console.debug "Write asset #" dir filename file)
  1346. (if (util/electron?)
  1347. (let [from (.-path file)]
  1348. (p/then (js/window.apis.copyFileToAssets dir filename from)
  1349. #(p/resolved [filename (if (string? %) (js/File. #js[] %) file) (.join util/node-path dir filename)])))
  1350. (p/then (fs/write-file! repo dir filename (.stream file) nil)
  1351. #(p/resolved [filename file])))))))))
  1352. (defonce *assets-url-cache (atom {}))
  1353. (defn make-asset-url
  1354. [path] ;; path start with "/assets" or compatible for "../assets"
  1355. (let [repo-dir (config/get-repo-dir (state/get-current-repo))
  1356. path (string/replace path "../" "/")]
  1357. (cond
  1358. (util/electron?)
  1359. (str "assets://" repo-dir path)
  1360. (mobile/is-native-platform?)
  1361. (mobile/convert-file-src
  1362. (str "file://" repo-dir path))
  1363. :else
  1364. (let [handle-path (str "handle" repo-dir path)
  1365. cached-url (get @*assets-url-cache (keyword handle-path))]
  1366. (if cached-url
  1367. (p/resolved cached-url)
  1368. (p/let [handle (frontend.idb/get-item handle-path)
  1369. file (and handle (.getFile handle))]
  1370. (when file
  1371. (p/let [url (js/URL.createObjectURL file)]
  1372. (swap! *assets-url-cache assoc (keyword handle-path) url)
  1373. url))))))))
  1374. (defn delete-asset-of-block!
  1375. [{:keys [repo href title full-text block-id local? delete-local?] :as opts}]
  1376. (let [block (db-model/query-block-by-uuid block-id)
  1377. _ (or block (throw (str block-id " not exists")))
  1378. format (:block/format block)
  1379. text (:block/content block)
  1380. content (string/replace text full-text "")]
  1381. (save-block! repo block content)
  1382. (when (and local? delete-local?)
  1383. ;; FIXME: should be relative to current block page path
  1384. (when-let [href (if (util/electron?) href (second (re-find #"\((.+)\)$" full-text)))]
  1385. (fs/unlink! repo
  1386. (config/get-repo-path
  1387. repo (-> href
  1388. (string/replace #"^../" "/")
  1389. (string/replace #"^assets://" ""))) nil)))))
  1390. ;; assets/journals_2021_02_03_1612350230540_0.png
  1391. (defn resolve-relative-path
  1392. [file-path]
  1393. (if-let [current-file (or (some-> (state/get-edit-block)
  1394. :block/file
  1395. :db/id
  1396. (db/entity)
  1397. :file/path)
  1398. ;; fix dummy file path of page
  1399. (and (util/electron?)
  1400. (util/node-path.join
  1401. (config/get-repo-dir (state/get-current-repo))
  1402. (config/get-pages-directory) "_.md")))]
  1403. (util/get-relative-path current-file file-path)
  1404. file-path))
  1405. (defn upload-asset
  1406. [id ^js files format uploading? drop-or-paste?]
  1407. (let [repo (state/get-current-repo)
  1408. block (state/get-edit-block)]
  1409. (if (config/local-db? repo)
  1410. (-> (save-assets! block repo (js->clj files))
  1411. (p/then
  1412. (fn [res]
  1413. (when-let [[asset-file-name file full-file-path] (and (seq res) (first res))]
  1414. (let [image? (util/ext-of-image? asset-file-name)]
  1415. (insert-command!
  1416. id
  1417. (get-asset-file-link format (resolve-relative-path (or full-file-path asset-file-name))
  1418. (if file (.-name file) (if image? "image" "asset"))
  1419. image?)
  1420. format
  1421. {:last-pattern (if drop-or-paste? "" commands/slash)
  1422. :restore? true})))))
  1423. (p/finally
  1424. (fn []
  1425. (reset! uploading? false)
  1426. (reset! *asset-uploading? false)
  1427. (reset! *asset-uploading-process 0))))
  1428. (image/upload
  1429. files
  1430. (fn [file file-name file-type]
  1431. (image-handler/request-presigned-url
  1432. file file-name file-type
  1433. uploading?
  1434. (fn [signed-url]
  1435. (insert-command! id
  1436. (get-asset-file-link format signed-url file-name true)
  1437. format
  1438. {:last-pattern (if drop-or-paste? "" commands/slash)
  1439. :restore? true})
  1440. (reset! *asset-uploading? false)
  1441. (reset! *asset-uploading-process 0))
  1442. (fn [e]
  1443. (let [process (* (/ (gobj/get e "loaded")
  1444. (gobj/get e "total"))
  1445. 100)]
  1446. (reset! *asset-uploading? false)
  1447. (reset! *asset-uploading-process process)))))))))
  1448. ;; Editor should track some useful information, like editor modes.
  1449. ;; For example:
  1450. ;; 1. Which file format is it, markdown or org mode?
  1451. ;; 2. Is it in the properties area? Then we can enable the ":" autopair
  1452. (def autopair-map
  1453. {"[" "]"
  1454. "{" "}"
  1455. "(" ")"
  1456. "`" "`"
  1457. "~" "~"
  1458. "*" "*"
  1459. "_" "_"
  1460. "^" "^"
  1461. "=" "="
  1462. ;; ":" ":" ; TODO: only properties editing and org mode tag
  1463. })
  1464. (def reversed-autopair-map
  1465. (zipmap (vals autopair-map)
  1466. (keys autopair-map)))
  1467. (defonce autopair-when-selected
  1468. #{"^" "_" "="})
  1469. (def delete-map
  1470. (assoc autopair-map
  1471. "$" "$"
  1472. ":" ":"))
  1473. (def reversed-delete-map
  1474. (zipmap (vals delete-map)
  1475. (keys delete-map)))
  1476. (defn autopair
  1477. [input-id prefix format {:keys [restore?]
  1478. :or {restore? true}
  1479. :as option}]
  1480. (let [value (get autopair-map prefix)
  1481. selected (util/get-selected-text)
  1482. postfix (str selected value)
  1483. value (str prefix postfix)
  1484. input (gdom/getElement input-id)]
  1485. (when value
  1486. (when-not (string/blank? selected) (reset! *selected-text selected))
  1487. (let [[prefix pos] (commands/simple-replace! input-id value selected
  1488. {:backward-pos (count postfix)
  1489. :check-fn (fn [new-value prefix-pos]
  1490. (when (>= prefix-pos 0)
  1491. [(subs new-value prefix-pos (+ prefix-pos 2))
  1492. (+ prefix-pos 2)]))})]
  1493. (case prefix
  1494. "[["
  1495. (do
  1496. (commands/handle-step [:editor/search-page])
  1497. (reset! commands/*slash-caret-pos (cursor/get-caret-pos input)))
  1498. "(("
  1499. (do
  1500. (commands/handle-step [:editor/search-block :reference])
  1501. (reset! commands/*slash-caret-pos (cursor/get-caret-pos input)))
  1502. nil)))))
  1503. (defn surround-by?
  1504. [input before after]
  1505. (when input
  1506. (let [value (gobj/get input "value")
  1507. pos (cursor/pos input)
  1508. start-pos (if (= :start before) 0 (- pos (count before)))
  1509. end-pos (if (= :end after) (count value) (+ pos (count after)))]
  1510. (when (>= (count value) end-pos)
  1511. (= (cond
  1512. (and (= :end after) (= :start before))
  1513. ""
  1514. (= :end after)
  1515. before
  1516. (= :start before)
  1517. after
  1518. :else
  1519. (str before after))
  1520. (subs value start-pos end-pos))))))
  1521. (defn get-matched-pages
  1522. [q]
  1523. (let [block (state/get-edit-block)
  1524. editing-page (and block
  1525. (when-let [page-id (:db/id (:block/page block))]
  1526. (:block/name (db/entity page-id))))]
  1527. (let [pages (search/page-search q 20)]
  1528. (if editing-page
  1529. ;; To prevent self references
  1530. (remove (fn [p] (= (string/lower-case p) editing-page)) pages)
  1531. pages))))
  1532. (defn get-matched-blocks
  1533. [q block-id]
  1534. ;; remove current block
  1535. (let [current-block (state/get-edit-block)
  1536. block-parents (set (->> (db/get-block-parents (state/get-current-repo)
  1537. block-id
  1538. 99)
  1539. (map (comp str :block/uuid))))
  1540. current-and-parents (set/union #{(str (:block/uuid current-block))} block-parents)]
  1541. (p/let [result (search/block-search (state/get-current-repo) q {:limit 20})]
  1542. (remove
  1543. (fn [h]
  1544. (contains? current-and-parents (:block/uuid h)))
  1545. result))))
  1546. (defn get-matched-templates
  1547. [q]
  1548. (search/template-search q))
  1549. (defn get-matched-commands
  1550. [input]
  1551. (try
  1552. (let [edit-content (or (gobj/get input "value") "")
  1553. pos (cursor/pos input)
  1554. last-slash-caret-pos (:pos @*slash-caret-pos)
  1555. last-command (and last-slash-caret-pos (subs edit-content last-slash-caret-pos pos))]
  1556. (when (> pos 0)
  1557. (or
  1558. (and (= \/ (util/nth-safe edit-content (dec pos)))
  1559. @commands/*initial-commands)
  1560. (and last-command
  1561. (commands/get-matched-commands last-command)))))
  1562. (catch js/Error e
  1563. (js/console.error e)
  1564. nil)))
  1565. (defn get-matched-block-commands
  1566. [input]
  1567. (try
  1568. (let [edit-content (gobj/get input "value")
  1569. pos (cursor/pos input)
  1570. last-command (subs edit-content
  1571. (:pos @*angle-bracket-caret-pos)
  1572. pos)]
  1573. (when (> pos 0)
  1574. (or
  1575. (and (= \< (util/nth-safe edit-content (dec pos)))
  1576. (commands/block-commands-map))
  1577. (and last-command
  1578. (commands/get-matched-commands
  1579. last-command
  1580. (commands/block-commands-map))))))
  1581. (catch js/Error e
  1582. nil)))
  1583. (defn auto-complete?
  1584. []
  1585. (or @*show-commands
  1586. @*show-block-commands
  1587. @*asset-uploading?
  1588. (state/get-editor-show-input)
  1589. (state/get-editor-show-page-search?)
  1590. (state/get-editor-show-block-search?)
  1591. (state/get-editor-show-template-search?)
  1592. (state/get-editor-show-date-picker?)))
  1593. (defn get-previous-input-char
  1594. [input]
  1595. (when-let [pos (cursor/pos input)]
  1596. (let [value (gobj/get input "value")]
  1597. (when (and (>= (count value) pos)
  1598. (>= pos 1))
  1599. (util/nth-safe value (- pos 1))))))
  1600. (defn get-previous-input-chars
  1601. [input length]
  1602. (when-let [pos (cursor/pos input)]
  1603. (let [value (gobj/get input "value")]
  1604. (when (and (>= (count value) pos)
  1605. (>= pos 1))
  1606. (subs value (- pos length) pos)))))
  1607. (defn get-current-input-char
  1608. [input]
  1609. (when-let [pos (cursor/pos input)]
  1610. (let [value (gobj/get input "value")]
  1611. (when (and (>= (count value) (inc pos))
  1612. (>= pos 1))
  1613. (util/nth-safe value pos)))))
  1614. (defn append-paste-doc!
  1615. [format event]
  1616. (let [[html text] (util/get-clipboard-as-html event)]
  1617. (when-not (util/starts-with? (string/trim text) "http")
  1618. (let [doc-text (html-parser/parse format html)]
  1619. (when-not (string/blank? doc-text)
  1620. (util/stop event)
  1621. (state/append-current-edit-content! doc-text))))))
  1622. (defn- block-and-children-content
  1623. [block-children]
  1624. (-> (map :block/content block-children)
  1625. string/join))
  1626. (defn move-up-down
  1627. [up?]
  1628. (fn [e]
  1629. (when-let [block-id (:block/uuid (state/get-edit-block))]
  1630. (when-let [block (db/pull [:block/uuid block-id])]
  1631. (outliner-core/move-node (outliner-core/block block) up?)
  1632. (when-let [repo (state/get-current-repo)]
  1633. (let [opts {:key :block/change
  1634. :data [block]}]
  1635. (db/refresh! repo opts)))
  1636. (when-let [block-node (util/get-first-block-by-id block-id)]
  1637. (.scrollIntoView block-node #js {:behavior "smooth" :block "nearest"})
  1638. (when-let [input-id (state/get-edit-input-id)]
  1639. (when-let [input (gdom/getElement input-id)]
  1640. (.focus input))))))))
  1641. ;; selections
  1642. (defn on-tab
  1643. "direction = :left|:right, only indent or outdent when blocks are siblings"
  1644. [direction]
  1645. (when-let [repo (state/get-current-repo)]
  1646. (let [blocks-dom-nodes (state/get-selection-blocks)
  1647. blocks (seq blocks-dom-nodes)]
  1648. (cond
  1649. (seq blocks)
  1650. (do
  1651. (let [lookup-refs (->> (map (fn [block] (when-let [id (dom/attr block "blockid")]
  1652. [:block/uuid (medley/uuid id)])) blocks)
  1653. (remove nil?))
  1654. blocks (db/pull-many repo '[*] lookup-refs)
  1655. blocks (reorder-blocks blocks)
  1656. end-node (get-top-level-end-node blocks)
  1657. end-node-parent (tree/-get-parent end-node)
  1658. top-level-nodes (->> (filter #(= (get-in end-node-parent [:data :db/id])
  1659. (get-in % [:block/parent :db/id])) blocks)
  1660. (map outliner-core/block))]
  1661. (outliner-core/indent-outdent-nodes top-level-nodes (= direction :right))
  1662. (let [opts {:key :block/change
  1663. :data blocks}]
  1664. (db/refresh! repo opts)
  1665. (let [blocks (doall
  1666. (map
  1667. (fn [block]
  1668. (when-let [id (gobj/get block "id")]
  1669. (when-let [block (gdom/getElement id)]
  1670. (dom/add-class! block "selected noselect")
  1671. block)))
  1672. blocks-dom-nodes))]
  1673. (state/set-selection-blocks! blocks)))))))))
  1674. (defn- get-link
  1675. [format link label]
  1676. (let [link (or link "")
  1677. label (or label "")]
  1678. (case (keyword format)
  1679. :markdown (util/format "[%s](%s)" label link)
  1680. :org (util/format "[[%s][%s]]" link label)
  1681. nil)))
  1682. (defn- get-image-link
  1683. [format link label]
  1684. (let [link (or link "")
  1685. label (or label "")]
  1686. (case (keyword format)
  1687. :markdown (util/format "![%s](%s)" label link)
  1688. :org (util/format "[[%s]]"))))
  1689. (defn handle-command-input
  1690. [command id format m pos]
  1691. (case command
  1692. :link
  1693. (let [{:keys [link label]} m]
  1694. (if (and (string/blank? link)
  1695. (string/blank? label))
  1696. nil
  1697. (insert-command! id
  1698. (get-link format link label)
  1699. format
  1700. {:last-pattern (str commands/slash "link")})))
  1701. :image-link
  1702. (let [{:keys [link label]} m]
  1703. (if (and (string/blank? link)
  1704. (string/blank? label))
  1705. nil
  1706. (insert-command! id
  1707. (get-image-link format link label)
  1708. format
  1709. {:last-pattern (str commands/slash "link")})))
  1710. nil)
  1711. (state/set-editor-show-input! nil)
  1712. (when-let [saved-cursor (get @state/state :editor/last-saved-cursor)]
  1713. (when-let [input (gdom/getElement id)]
  1714. (.focus input)
  1715. (cursor/move-cursor-to input saved-cursor))))
  1716. (defn get-search-q
  1717. []
  1718. (when-let [id (state/get-edit-input-id)]
  1719. (when-let [input (gdom/getElement id)]
  1720. (let [current-pos (cursor/pos input)
  1721. pos (:editor/last-saved-cursor @state/state)
  1722. edit-content (or (state/sub [:editor/content id]) "")]
  1723. (or
  1724. @*selected-text
  1725. (util/safe-subs edit-content pos current-pos))))))
  1726. (defn close-autocomplete-if-outside
  1727. [input]
  1728. (when (and input
  1729. (or (state/get-editor-show-page-search?)
  1730. (state/get-editor-show-page-search-hashtag?)
  1731. (state/get-editor-show-block-search?)))
  1732. (when-let [q (get-search-q)]
  1733. (let [value (gobj/get input "value")
  1734. pos (:editor/last-saved-cursor @state/state)
  1735. current-pos (cursor/pos input)
  1736. between (util/safe-subs value (min pos current-pos) (max pos current-pos))]
  1737. (when (and between
  1738. (or
  1739. (string/includes? between "[")
  1740. (string/includes? between "]")
  1741. (string/includes? between "(")
  1742. (string/includes? between ")")))
  1743. (state/set-editor-show-block-search! false)
  1744. (state/set-editor-show-page-search! false)
  1745. (state/set-editor-show-page-search-hashtag! false))))))
  1746. (defn save!
  1747. []
  1748. (when-let [repo (state/get-current-repo)]
  1749. (save-current-block!)
  1750. (when (string/starts-with? repo "https://") ; git repo
  1751. (repo-handler/auto-push!))))
  1752. (defn resize-image!
  1753. [block-id metadata full_text size]
  1754. (let [new-meta (merge metadata size)
  1755. image-part (first (string/split full_text #"\{"))
  1756. new-full-text (str image-part (pr-str new-meta))
  1757. block (db/pull [:block/uuid block-id])
  1758. value (:block/content block)
  1759. new-value (string/replace value full_text new-full-text)]
  1760. (save-block-aux! block new-value (:block/format block) {})))
  1761. (defn- mark-last-input-time!
  1762. [repo]
  1763. (when repo
  1764. (state/set-editor-last-input-time! repo (util/time-ms))
  1765. (db/clear-repo-persistent-job! repo)))
  1766. (defonce *auto-save-timeout (atom nil))
  1767. (defn edit-box-on-change!
  1768. [e block id]
  1769. (let [value (util/evalue e)
  1770. repo (or (:block/repo block)
  1771. (state/get-current-repo))]
  1772. (state/set-edit-content! id value false)
  1773. (when @*auto-save-timeout
  1774. (js/clearTimeout @*auto-save-timeout))
  1775. (mark-last-input-time! repo)
  1776. (when-not
  1777. (and
  1778. (= (:db/id (:block/parent block))
  1779. (:db/id (:block/page block))) ; don't auto-save for page's properties block
  1780. (get-in block [:block/properties :title]))
  1781. (reset! *auto-save-timeout
  1782. (js/setTimeout
  1783. (fn []
  1784. (when (state/input-idle? repo)
  1785. (state/set-editor-op! :auto-save)
  1786. (save-current-block! {})
  1787. (state/set-editor-op! nil)))
  1788. 500)))))
  1789. (defn handle-last-input []
  1790. (let [input (state/get-input)
  1791. pos (cursor/pos input)
  1792. last-input-char (util/nth-safe (.-value input) (dec pos))]
  1793. (case last-input-char
  1794. "/"
  1795. ;; TODO: is it cross-browser compatible?
  1796. ;; (not= (gobj/get native-e "inputType") "insertFromPaste")
  1797. (when (seq (get-matched-commands input))
  1798. (reset! commands/*slash-caret-pos (cursor/get-caret-pos input))
  1799. (reset! commands/*show-commands true))
  1800. "<"
  1801. (when (seq (get-matched-block-commands input))
  1802. (reset! commands/*angle-bracket-caret-pos (cursor/get-caret-pos input))
  1803. (reset! commands/*show-block-commands true))
  1804. nil)))
  1805. (defn block-on-chosen-handler
  1806. [input id q format]
  1807. (fn [chosen _click?]
  1808. (state/set-editor-show-block-search! false)
  1809. (let [uuid-string (str (:block/uuid chosen))]
  1810. ;; block reference
  1811. (insert-command! id
  1812. (util/format "((%s))" uuid-string)
  1813. format
  1814. {:last-pattern (str "((" (if @*selected-text "" q))
  1815. :end-pattern "))"
  1816. :postfix-fn (fn [s] (util/replace-first "))" s ""))
  1817. :forward-pos 3})
  1818. ;; Save it so it'll be parsed correctly in the future
  1819. (set-block-property! (:block/uuid chosen)
  1820. :id
  1821. uuid-string)
  1822. (when-let [input (gdom/getElement id)]
  1823. (.focus input)))))
  1824. (defn block-non-exist-handler
  1825. [input]
  1826. (fn []
  1827. (state/set-editor-show-block-search! false)
  1828. (cursor/move-cursor-forward input 2)))
  1829. (defn get-block-tree-insert-pos-after-target
  1830. "return [target-block sibling? delete-editing-block? editing-block]"
  1831. ([target-block-id sibling?]
  1832. (get-block-tree-insert-pos-after-target target-block-id sibling? nil))
  1833. ([target-block-id sibling? editing-block]
  1834. (when-let [target-block (db/pull target-block-id)]
  1835. [target-block sibling? false (or editing-block target-block)])))
  1836. (defn- get-block-tree-insert-pos-at-point
  1837. "return [target-block sibling? delete-editing-block? editing-block]"
  1838. []
  1839. (when-let [editing-block (db/pull (:db/id (state/get-edit-block)))]
  1840. (let [input (gdom/getElement (state/get-edit-input-id))
  1841. pos (cursor/pos input)
  1842. value (:value (get-state))
  1843. [fst-block-text snd-block-text] (compute-fst-snd-block-text value pos)
  1844. parent (:db/id (:block/parent editing-block))
  1845. parent-block (db/pull parent)
  1846. left (:db/id (:block/left editing-block))
  1847. left-block (db/pull left)
  1848. [_ _ config] (state/get-editor-args)
  1849. block-id (:block/uuid editing-block)
  1850. block-self? (block-self-alone-when-insert? config block-id)
  1851. has-children? (db/has-children? (state/get-current-repo)
  1852. (:block/uuid editing-block))
  1853. collapsed? (:collapsed (:block/properties editing-block))]
  1854. (conj (match (mapv boolean [(seq fst-block-text) (seq snd-block-text)
  1855. block-self? has-children? (= parent left) collapsed?])
  1856. ;; when zoom at editing-block
  1857. [_ _ true _ _ _]
  1858. [editing-block false false]
  1859. ;; insert after editing-block
  1860. [true _ false true _ false]
  1861. [editing-block false false]
  1862. [true _ false true _ true]
  1863. [editing-block true false]
  1864. [true _ false false _ _]
  1865. [editing-block true false]
  1866. [false false false true _ false]
  1867. [editing-block false false]
  1868. [false false false true _ true]
  1869. [editing-block true false]
  1870. [false false false false _ _]
  1871. [editing-block true true]
  1872. ;; insert before editing-block
  1873. [false true false _ true _]
  1874. [parent-block false false]
  1875. [false true false _ false _]
  1876. [left-block true false])
  1877. editing-block))))
  1878. (defn- paste-block-tree-at-point-edit-aux
  1879. [uuid file page exclude-properties format content-update-fn]
  1880. (fn [block]
  1881. (outliner-core/block
  1882. (let [[new-content new-title]
  1883. (if content-update-fn
  1884. (let [new-content (content-update-fn (:block/content block))
  1885. new-title (or (->> (mldoc/->edn
  1886. (str (case format
  1887. :markdown "- "
  1888. :org "* ")
  1889. (if (seq (:block/title block)) "" "\n")
  1890. new-content)
  1891. (mldoc/default-config format))
  1892. (ffirst)
  1893. (second)
  1894. (:title))
  1895. (:block/title block))]
  1896. [new-content new-title])
  1897. [(:block/content block) (:block/title block)])
  1898. new-content
  1899. (->> new-content
  1900. (property/remove-property format "id")
  1901. (property/remove-property format "custom_id"))
  1902. m (merge (dissoc block
  1903. :block/pre-block?
  1904. :block/uuid
  1905. :db/id
  1906. :block/left
  1907. :block/parent
  1908. :block/file)
  1909. {:block/uuid uuid
  1910. :block/page (select-keys page [:db/id])
  1911. :block/format format
  1912. :block/properties (apply dissoc (:block/properties block)
  1913. (concat [:id :custom_id :custom-id]
  1914. exclude-properties))
  1915. :block/meta (dissoc (:block/meta block) :start-pos :end-pos)
  1916. :block/content new-content
  1917. :block/title new-title
  1918. :block/path-refs (->> (cons (:db/id page) (:block/path-refs block))
  1919. (remove nil?))})]
  1920. (if file
  1921. (assoc m :block/file (select-keys file [:db/id]))
  1922. m)))))
  1923. (defn paste-block-vec-tree-at-target
  1924. [tree exclude-properties {:keys [content-update-fn
  1925. get-pos-fn
  1926. page-block]
  1927. :as opts}]
  1928. (let [repo (state/get-current-repo)
  1929. page (or page-block
  1930. (:block/page (db/entity (:db/id (state/get-edit-block)))))
  1931. file (:block/file page)
  1932. [target-block sibling? delete-editing-block? editing-block]
  1933. ((or get-pos-fn get-block-tree-insert-pos-at-point))]
  1934. (when target-block
  1935. (let [target-block (outliner-core/block target-block)
  1936. format (or (:block/format target-block) (state/get-preferred-format))
  1937. new-block-uuids (atom #{})
  1938. metadata-replaced-blocks
  1939. (zip/root
  1940. (loop [loc (zip/vector-zip tree)]
  1941. (if (zip/end? loc)
  1942. loc
  1943. (if (vector? (zip/node loc))
  1944. (recur (zip/next loc))
  1945. (let [uuid (random-uuid)]
  1946. (swap! new-block-uuids (fn [acc uuid] (conj acc uuid)) uuid)
  1947. (recur (zip/next (zip/edit
  1948. loc
  1949. (paste-block-tree-at-point-edit-aux
  1950. uuid file page exclude-properties format content-update-fn)))))))))
  1951. _ (when editing-block
  1952. (let [editing-block (outliner-core/block editing-block)]
  1953. (outliner-core/save-node editing-block)))
  1954. _ (outliner-core/insert-nodes metadata-replaced-blocks target-block sibling?)
  1955. _ (when (and delete-editing-block? editing-block)
  1956. (when-let [id (:db/id editing-block)]
  1957. (outliner-core/delete-node (outliner-core/block (db/pull id)) true)))
  1958. new-blocks (db/pull-many repo '[*] (map (fn [id] [:block/uuid id]) @new-block-uuids))]
  1959. (db/refresh! repo {:key :block/insert :data new-blocks})
  1960. (last metadata-replaced-blocks)))))
  1961. (defn- tree->vec-tree
  1962. "tree:
  1963. [
  1964. {
  1965. :content 'this is a block',
  1966. :properties {\"key\" \"value\" \"key2\" \"value2\"},
  1967. :children [
  1968. { :content 'this is child block' }
  1969. ]
  1970. },
  1971. {
  1972. :content 'this is sibling block'
  1973. }
  1974. ]"
  1975. [tree]
  1976. (into []
  1977. (mapcat
  1978. (fn [e]
  1979. (let [e* (select-keys e [:content :properties])
  1980. children (:children e)]
  1981. (if (seq children)
  1982. [e* (tree->vec-tree (:children e))]
  1983. [e*])))
  1984. tree)))
  1985. (defn- vec-tree->vec-block-tree
  1986. [tree format]
  1987. (let [loc (zip/vector-zip tree)]
  1988. (loop [loc loc]
  1989. (if (zip/end? loc)
  1990. (zip/root loc)
  1991. (let [node (zip/node loc)]
  1992. (if (vector? node)
  1993. (recur (zip/next loc))
  1994. (let [content (:content node)
  1995. props (into [] (:properties node))
  1996. content* (str (if (= :markdown format) "- " "* ")
  1997. (property/insert-properties format content props))
  1998. ast (mldoc/->edn content* (mldoc/default-config format))
  1999. blocks (block/extract-blocks ast content* true format)
  2000. fst-block (first blocks)]
  2001. (assert fst-block "fst-block shouldn't be nil")
  2002. (recur (zip/next (zip/replace loc fst-block))))))))))
  2003. (defn paste-block-tree-after-target
  2004. [target-block-id sibling? tree format]
  2005. (let [vec-tree (tree->vec-tree tree)
  2006. block-tree (vec-tree->vec-block-tree vec-tree format)
  2007. target-block (db/pull target-block-id)
  2008. page-block (if (:block/name target-block) target-block
  2009. (db/entity (:db/id (:block/page (db/pull target-block-id)))))
  2010. ;; sibling? = false, when target-block is a page-block
  2011. sibling? (if (= target-block-id (:db/id page-block))
  2012. false
  2013. sibling?)]
  2014. (paste-block-vec-tree-at-target
  2015. block-tree []
  2016. {:get-pos-fn #(get-block-tree-insert-pos-after-target target-block-id sibling?)
  2017. :page-block page-block})))
  2018. (defn insert-template!
  2019. ([element-id db-id]
  2020. (insert-template! element-id db-id {}))
  2021. ([element-id db-id opts]
  2022. (when-let [db-id (if (integer? db-id)
  2023. db-id
  2024. (:db/id (db-model/get-template-by-name (name db-id))))]
  2025. (let [repo (state/get-current-repo)
  2026. block (db/entity db-id)
  2027. format (:block/format block)
  2028. block-uuid (:block/uuid block)
  2029. template-including-parent? (not (false? (:template-including-parent (:block/properties block))))
  2030. blocks (if template-including-parent? (db/get-block-and-children repo block-uuid) (db/get-block-children repo block-uuid))
  2031. level-blocks (vals (blocks-with-level blocks))
  2032. grouped-blocks (group-by #(= db-id (:db/id %)) level-blocks)
  2033. root-block (or (first (get grouped-blocks true)) (assoc (db/pull db-id) :level 1))
  2034. blocks-exclude-root (get grouped-blocks false)
  2035. sorted-blocks (tree/sort-blocks blocks-exclude-root root-block)
  2036. result-blocks (if template-including-parent? sorted-blocks (drop 1 sorted-blocks))
  2037. tree (blocks-vec->tree result-blocks)]
  2038. (when element-id
  2039. (insert-command! element-id "" format {}))
  2040. (let [opts (merge
  2041. {:content-update-fn (fn [content]
  2042. (->> content
  2043. (property/remove-property format "template")
  2044. (property/remove-property format "template-including-parent")
  2045. template/resolve-dynamic-template!))}
  2046. opts)
  2047. last-block (paste-block-vec-tree-at-target tree [:id :template :template-including-parent] opts)]
  2048. (clear-when-saved!)
  2049. (db/refresh! repo {:key :block/insert :data [(db/pull db-id)]})
  2050. (let [block (if (tree/satisfied-inode? last-block)
  2051. (:data last-block)
  2052. (:data (last (flatten last-block))))]
  2053. (edit-block! block :max (:block/format block) (:block/uuid block))))))))
  2054. (defn template-on-chosen-handler
  2055. [element-id]
  2056. (fn [[_template db-id] _click?]
  2057. (insert-template! element-id db-id)))
  2058. (defn parent-is-page?
  2059. [{{:block/keys [parent page]} :data :as node}]
  2060. {:pre [(tree/satisfied-inode? node)]}
  2061. (= parent page))
  2062. (defn outdent-on-enter
  2063. [node]
  2064. (when-not (parent-is-page? node)
  2065. (let [parent-node (tree/-get-parent node)]
  2066. (outliner-core/move-subtree node parent-node true)))
  2067. (let [repo (state/get-current-repo)]
  2068. (db/refresh! repo {:key :block/change :data [(:data node)]})))
  2069. (defn- last-top-level-child?
  2070. [{:keys [id config]} current-node]
  2071. (when id
  2072. (when-let [entity (if (util/uuid-string? (str id))
  2073. (db/entity [:block/uuid (uuid id)])
  2074. (db/entity [:block/name (string/lower-case id)]))]
  2075. (= (:block/uuid entity) (tree/-get-parent-id current-node)))))
  2076. (defn- keydown-new-block
  2077. [state]
  2078. (when-not (auto-complete?)
  2079. (let [{:keys [block config]} (get-state)]
  2080. (when block
  2081. (let [content (state/get-edit-content)
  2082. current-node (outliner-core/block block)
  2083. has-right? (-> (tree/-get-right current-node)
  2084. (tree/satisfied-inode?))]
  2085. (if (and
  2086. (string/blank? content)
  2087. (not has-right?)
  2088. (not (last-top-level-child? config current-node)))
  2089. (outdent-on-enter current-node)
  2090. (profile
  2091. "Insert block"
  2092. (insert-new-block! state))))))))
  2093. (defn- keydown-new-line
  2094. []
  2095. (when-not (auto-complete?)
  2096. (let [^js input (state/get-input)
  2097. selected-start (gobj/get input "selectionStart")
  2098. selected-end (gobj/get input "selectionEnd")
  2099. value (.-value input)
  2100. s1 (subs value 0 selected-start)
  2101. s2 (subs value selected-end)]
  2102. (state/set-edit-content! (state/get-edit-input-id)
  2103. (str s1 "\n" s2))
  2104. (cursor/move-cursor-to input (inc selected-start)))))
  2105. (defn keydown-new-block-handler [state e]
  2106. (if (state/doc-mode-enter-for-new-line?)
  2107. (keydown-new-line)
  2108. (do
  2109. (.preventDefault e)
  2110. (keydown-new-block state))))
  2111. (defn keydown-new-line-handler [state e]
  2112. (if (state/doc-mode-enter-for-new-line?)
  2113. (keydown-new-block state)
  2114. (do
  2115. (.preventDefault e)
  2116. (keydown-new-line))))
  2117. (defn- select-first-last
  2118. "Select first or last block in viewpoint"
  2119. [direction]
  2120. (let [f (case direction :up last :down first)
  2121. block (->> (util/get-blocks-noncollapse)
  2122. (f))]
  2123. (when block
  2124. (.scrollIntoView block #js {:behavior "smooth" :block "center"})
  2125. (state/exit-editing-and-set-selected-blocks! [block]))))
  2126. (defn- select-up-down [direction]
  2127. (let [selected (first (state/get-selection-blocks))
  2128. f (case direction
  2129. :up util/get-prev-block-non-collapsed
  2130. :down util/get-next-block-non-collapsed)
  2131. sibling-block (f selected)]
  2132. (when (and sibling-block (dom/attr sibling-block "blockid"))
  2133. (.scrollIntoView sibling-block #js {:behavior "smooth" :block "center"})
  2134. (state/exit-editing-and-set-selected-blocks! [sibling-block]))))
  2135. (defn- move-cross-boundrary-up-down
  2136. [direction]
  2137. (let [input (state/get-input)
  2138. line-pos (util/get-first-or-last-line-pos input)
  2139. repo (state/get-current-repo)
  2140. f (case direction
  2141. :up util/get-prev-block-non-collapsed
  2142. :down util/get-next-block-non-collapsed)
  2143. sibling-block (f (gdom/getElement (state/get-editing-block-dom-id)))
  2144. {:block/keys [uuid content format]} (state/get-edit-block)]
  2145. (when sibling-block
  2146. (when-let [sibling-block-id (dom/attr sibling-block "blockid")]
  2147. (let [value (state/get-edit-content)]
  2148. (when (not= (clean-content! format content)
  2149. (string/trim value))
  2150. (save-block! repo uuid value)))
  2151. (let [new-id (string/replace (gobj/get sibling-block "id") "ls-block" "edit-block")
  2152. new-uuid (cljs.core/uuid sibling-block-id)
  2153. block (db/pull repo '[*] [:block/uuid new-uuid])]
  2154. (edit-block! block
  2155. [direction line-pos]
  2156. format
  2157. new-id))))))
  2158. (defn keydown-up-down-handler
  2159. [direction]
  2160. (let [input (state/get-input)
  2161. selected-start (.-selectionStart input)
  2162. selected-end (.-selectionEnd input)
  2163. up? (= direction :up)
  2164. down? (= direction :down)]
  2165. (cond
  2166. (not= selected-start selected-end)
  2167. (if up?
  2168. (cursor/move-cursor-to input selected-start)
  2169. (cursor/move-cursor-to input selected-end))
  2170. (or (and up? (cursor/textarea-cursor-first-row? input))
  2171. (and down? (cursor/textarea-cursor-last-row? input)))
  2172. (move-cross-boundrary-up-down direction)
  2173. :else
  2174. (if up?
  2175. (cursor/move-cursor-up input)
  2176. (cursor/move-cursor-down input)))))
  2177. (defn- move-to-block-when-cross-boundrary
  2178. [direction]
  2179. (let [up? (= :left direction)
  2180. pos (if up? :max 0)
  2181. {:block/keys [format uuid] :as block} (state/get-edit-block)
  2182. id (state/get-edit-input-id)
  2183. repo (state/get-current-repo)]
  2184. (let [f (if up? util/get-prev-block-non-collapsed util/get-next-block-non-collapsed)
  2185. sibling-block (f (gdom/getElement (state/get-editing-block-dom-id)))]
  2186. (when sibling-block
  2187. (when-let [sibling-block-id (dom/attr sibling-block "blockid")]
  2188. (let [content (:block/content block)
  2189. value (state/get-edit-content)]
  2190. (when (not= (clean-content! format content)
  2191. (string/trim value))
  2192. (save-block! repo uuid value)))
  2193. (let [block (db/pull repo '[*] [:block/uuid (cljs.core/uuid sibling-block-id)])]
  2194. (edit-block! block pos format id)))))))
  2195. (defn keydown-arrow-handler
  2196. [direction]
  2197. (let [input (state/get-input)
  2198. element js/document.activeElement
  2199. selected-start (.-selectionStart input)
  2200. selected-end (.-selectionEnd input)
  2201. left? (= direction :left)
  2202. right? (= direction :right)]
  2203. (when (= input element)
  2204. (cond
  2205. (not= selected-start selected-end)
  2206. (if left?
  2207. (cursor/move-cursor-to input selected-start)
  2208. (cursor/move-cursor-to input selected-end))
  2209. (or (and left? (cursor/start? input))
  2210. (and right? (cursor/end? input)))
  2211. (move-to-block-when-cross-boundrary direction)
  2212. :else
  2213. (if left?
  2214. (cursor/move-cursor-backward input)
  2215. (cursor/move-cursor-forward input))))))
  2216. (defn- delete-and-update [^js input start end]
  2217. (.setRangeText input "" start end)
  2218. (state/set-edit-content! (state/get-edit-input-id) (.-value input)))
  2219. (defn- delete-concat [current-block]
  2220. (let [input-id (state/get-edit-input-id)
  2221. ^js input (state/get-input)
  2222. current-pos (cursor/pos input)
  2223. value (gobj/get input "value")
  2224. repo (state/get-current-repo)
  2225. right (outliner-core/get-right-node (outliner-core/block current-block))
  2226. current-block-has-children? (db/has-children? repo (:block/uuid current-block))
  2227. collapsed? (:collapsed (:block/properties current-block))
  2228. first-child (:data (tree/-get-down (outliner-core/block current-block)))
  2229. next-block (if (or collapsed? (not current-block-has-children?))
  2230. (:data right)
  2231. first-child)]
  2232. (cond
  2233. (and collapsed? right (db/has-children? repo (tree/-get-id right)))
  2234. nil
  2235. (and (not collapsed?) first-child (db/has-children? repo (:block/uuid first-child)))
  2236. nil
  2237. :else
  2238. (do
  2239. (delete-block-aux! next-block false)
  2240. (state/set-edit-content! input-id (str value "" (:block/content next-block)))
  2241. (cursor/move-cursor-to input current-pos)))))
  2242. (defn keydown-delete-handler
  2243. [e]
  2244. (let [^js input (state/get-input)
  2245. current-pos (cursor/pos input)
  2246. value (gobj/get input "value")
  2247. end? (= current-pos (count value))
  2248. current-block (state/get-edit-block)
  2249. selected-start (gobj/get input "selectionStart")
  2250. selected-end (gobj/get input "selectionEnd")]
  2251. (when current-block
  2252. (cond
  2253. (not= selected-start selected-end)
  2254. (delete-and-update input selected-start selected-end)
  2255. (and end? current-block)
  2256. (delete-concat current-block)
  2257. :else
  2258. (delete-and-update input current-pos (inc current-pos))))))
  2259. (defn keydown-backspace-handler
  2260. [cut? e]
  2261. (let [^js input (state/get-input)
  2262. id (state/get-edit-input-id)
  2263. current-pos (cursor/pos input)
  2264. value (gobj/get input "value")
  2265. deleted (and (> current-pos 0)
  2266. (util/nth-safe value (dec current-pos)))
  2267. selected-start (gobj/get input "selectionStart")
  2268. selected-end (gobj/get input "selectionEnd")
  2269. block-id (:block/uuid (state/get-edit-block))
  2270. page (state/get-current-page)
  2271. repo (state/get-current-repo)]
  2272. (mark-last-input-time! repo)
  2273. (cond
  2274. (not= selected-start selected-end)
  2275. (do
  2276. (util/stop e)
  2277. (when cut?
  2278. (js/document.execCommand "copy"))
  2279. (delete-and-update input selected-start selected-end))
  2280. (and (zero? current-pos)
  2281. ;; not the top block in a block page
  2282. (not (and page
  2283. (util/uuid-string? page)
  2284. (= (medley/uuid page) block-id))))
  2285. (do
  2286. (util/stop e)
  2287. (delete-block! repo e false))
  2288. (and (> current-pos 1)
  2289. (= (util/nth-safe value (dec current-pos)) commands/slash))
  2290. (do
  2291. (util/stop e)
  2292. (reset! *slash-caret-pos nil)
  2293. (reset! *show-commands false)
  2294. (delete-and-update input (dec current-pos) current-pos))
  2295. (and (> current-pos 1)
  2296. (= (util/nth-safe value (dec current-pos)) commands/angle-bracket))
  2297. (do
  2298. (util/stop e)
  2299. (reset! *angle-bracket-caret-pos nil)
  2300. (reset! *show-block-commands false)
  2301. (delete-and-update input (dec current-pos) current-pos))
  2302. ;; pair
  2303. (and
  2304. deleted
  2305. (contains?
  2306. (set (keys delete-map))
  2307. deleted)
  2308. (>= (count value) (inc current-pos))
  2309. (= (util/nth-safe value current-pos)
  2310. (get delete-map deleted)))
  2311. (do
  2312. (util/stop e)
  2313. (commands/delete-pair! id)
  2314. (cond
  2315. (and (= deleted "[") (state/get-editor-show-page-search?))
  2316. (state/set-editor-show-page-search! false)
  2317. (and (= deleted "(") (state/get-editor-show-block-search?))
  2318. (state/set-editor-show-block-search! false)
  2319. :else
  2320. nil))
  2321. ;; deleting hashtag
  2322. (and (= deleted "#") (state/get-editor-show-page-search-hashtag?))
  2323. (do
  2324. (state/set-editor-show-page-search-hashtag! false)
  2325. (delete-and-update input (dec current-pos) current-pos))
  2326. ;; just delete
  2327. :else
  2328. (do
  2329. (util/stop e)
  2330. (delete-and-update input (dec current-pos) current-pos)))))
  2331. (defn indent-outdent
  2332. [indent?]
  2333. (state/set-editor-op! :indent-outdent)
  2334. (let [{:keys [block]} (get-state)]
  2335. (when block
  2336. (let [current-node (outliner-core/block block)]
  2337. (outliner-core/indent-outdent-nodes [current-node] indent?)
  2338. (let [repo (state/get-current-repo)]
  2339. (db/refresh! repo
  2340. {:key :block/change :data [(:data current-node)]}))))
  2341. (state/set-editor-op! :nil)))
  2342. (defn keydown-tab-handler
  2343. [direction]
  2344. (fn [e]
  2345. (cond
  2346. (state/editing?)
  2347. (let [input (state/get-input)
  2348. pos (cursor/pos input)]
  2349. (when (and (not (state/get-editor-show-input))
  2350. (not (state/get-editor-show-date-picker?))
  2351. (not (state/get-editor-show-template-search?)))
  2352. (util/stop e)
  2353. (indent-outdent (not (= :left direction)))
  2354. (and input pos
  2355. (when-let [input (state/get-input)]
  2356. (cursor/move-cursor-to input pos)))))
  2357. (state/selection?)
  2358. (do
  2359. (util/stop e)
  2360. (on-tab direction))
  2361. :else nil)))
  2362. (defn keydown-not-matched-handler
  2363. [format]
  2364. (fn [e key-code]
  2365. (let [input-id (state/get-edit-input-id)
  2366. input (state/get-input)
  2367. key (gobj/get e "key")
  2368. value (gobj/get input "value")
  2369. ctrlKey (gobj/get e "ctrlKey")
  2370. metaKey (gobj/get e "metaKey")
  2371. pos (cursor/pos input)]
  2372. (cond
  2373. (or ctrlKey metaKey)
  2374. nil
  2375. (and (= key "#")
  2376. (and
  2377. (> pos 0)
  2378. (= "#" (util/nth-safe value (dec pos)))))
  2379. (state/set-editor-show-page-search-hashtag! false)
  2380. (and
  2381. (contains? (set/difference (set (keys reversed-autopair-map))
  2382. #{"`"})
  2383. key)
  2384. (= (get-current-input-char input) key))
  2385. (do
  2386. (util/stop e)
  2387. (cursor/move-cursor-forward input))
  2388. (and (autopair-when-selected key) (string/blank? (util/get-selected-text)))
  2389. nil
  2390. (contains? (set (keys autopair-map)) key)
  2391. (do
  2392. (util/stop e)
  2393. (autopair input-id key format nil)
  2394. (cond
  2395. (surround-by? input "[[" "]]")
  2396. (do
  2397. (commands/handle-step [:editor/search-page])
  2398. (reset! commands/*slash-caret-pos (cursor/get-caret-pos input)))
  2399. (surround-by? input "((" "))")
  2400. (do
  2401. (commands/handle-step [:editor/search-block :reference])
  2402. (reset! commands/*slash-caret-pos (cursor/get-caret-pos input)))
  2403. :else
  2404. nil))
  2405. (or
  2406. (surround-by? input "#" " ")
  2407. (surround-by? input "#" :end)
  2408. (= key "#"))
  2409. (do
  2410. (commands/handle-step [:editor/search-page-hashtag])
  2411. (state/set-last-pos! (cursor/pos input))
  2412. (reset! commands/*slash-caret-pos (cursor/get-caret-pos input)))
  2413. (let [sym "$"]
  2414. (and (= key sym)
  2415. (>= (count value) 1)
  2416. (> pos 0)
  2417. (= (nth value (dec pos)) sym)
  2418. (if (> (count value) pos)
  2419. (not= (nth value pos) sym)
  2420. true)))
  2421. (commands/simple-insert! input-id "$$" {:backward-pos 2})
  2422. (let [sym "^"]
  2423. (and (= key sym)
  2424. (>= (count value) 1)
  2425. (> pos 0)
  2426. (= (nth value (dec pos)) sym)
  2427. (if (> (count value) pos)
  2428. (not= (nth value pos) sym)
  2429. true)))
  2430. (commands/simple-insert! input-id "^^" {:backward-pos 2})
  2431. :else
  2432. nil))))
  2433. ;; key up
  2434. (defn keyup-handler
  2435. [state input input-id search-timeout]
  2436. (fn [e key-code]
  2437. (let [k (gobj/get e "key")
  2438. format (:format (get-state))
  2439. current-pos (cursor/pos input)
  2440. value (gobj/get input "value")
  2441. c (util/nth-safe value (dec current-pos))]
  2442. (when-not (state/get-editor-show-input)
  2443. (when (and (= "【" c (util/nth-safe value (dec (dec current-pos))))
  2444. (> current-pos 0))
  2445. (commands/handle-step [:editor/input "[[]]" {:last-pattern "【【"
  2446. :backward-pos 2}])
  2447. (commands/handle-step [:editor/search-page])
  2448. (reset! commands/*slash-caret-pos (cursor/get-caret-pos input)))
  2449. (when (and (= "(" c (util/nth-safe value (dec (dec current-pos))))
  2450. (> current-pos 0))
  2451. (commands/handle-step [:editor/input "(())" {:last-pattern "(("
  2452. :backward-pos 2}])
  2453. (commands/handle-step [:editor/search-block :reference])
  2454. (reset! commands/*slash-caret-pos (cursor/get-caret-pos input)))
  2455. (when (and (= "〈" c)
  2456. (= "《" (util/nth-safe value (dec (dec current-pos))))
  2457. (> current-pos 0))
  2458. (commands/handle-step [:editor/input "<" {:last-pattern "《〈"
  2459. :backward-pos 0}])
  2460. (reset! commands/*angle-bracket-caret-pos (cursor/get-caret-pos input))
  2461. (reset! commands/*show-block-commands true))
  2462. (when (= c " ")
  2463. (when (or (= (util/nth-safe value (dec (dec current-pos))) "#")
  2464. (not (state/get-editor-show-page-search?))
  2465. (and (state/get-editor-show-page-search?)
  2466. (not= (util/nth-safe value current-pos) "]")))
  2467. (state/set-editor-show-page-search-hashtag! false)))
  2468. (when (and @*show-commands (not= key-code 191)) ; not /
  2469. (let [matched-commands (get-matched-commands input)]
  2470. (if (seq matched-commands)
  2471. (do
  2472. (reset! *show-commands true)
  2473. (reset! commands/*matched-commands matched-commands))
  2474. (reset! *show-commands false))))
  2475. (when (and @*show-block-commands (not= key-code 188)) ; not <
  2476. (let [matched-block-commands (get-matched-block-commands input)]
  2477. (if (seq matched-block-commands)
  2478. (cond
  2479. (= key-code 9) ;tab
  2480. (when @*show-block-commands
  2481. (util/stop e)
  2482. (insert-command! input-id
  2483. (last (first matched-block-commands))
  2484. format
  2485. {:last-pattern commands/angle-bracket}))
  2486. :else
  2487. (reset! commands/*matched-block-commands matched-block-commands))
  2488. (reset! *show-block-commands false))))
  2489. (when (nil? @search-timeout)
  2490. (close-autocomplete-if-outside input))))))
  2491. (defn editor-on-click!
  2492. [id]
  2493. (fn [_e]
  2494. (let [input (gdom/getElement id)]
  2495. (close-autocomplete-if-outside input))))
  2496. (defn editor-on-change!
  2497. [block id search-timeout]
  2498. (fn [e]
  2499. (if (state/sub :editor/show-block-search?)
  2500. (let [blocks-count (or (db/blocks-count) 0)
  2501. timeout (if (> blocks-count 2000) 300 100)]
  2502. (when @search-timeout
  2503. (js/clearTimeout @search-timeout))
  2504. (reset! search-timeout
  2505. (js/setTimeout
  2506. #(edit-box-on-change! e block id)
  2507. timeout)))
  2508. (edit-box-on-change! e block id))))
  2509. (defn- get-current-page-format
  2510. []
  2511. (when-let [page (state/get-current-page)]
  2512. (db/get-page-format page)))
  2513. (defn blocks->tree-by-level
  2514. [blocks]
  2515. (let [min-level (apply min (mapv :block/level blocks))
  2516. prefix-level (if (> min-level 1) (- min-level 1) 0)]
  2517. (->> blocks
  2518. (mapv #(assoc % :level (- (:block/level %) prefix-level)))
  2519. (blocks-vec->tree))))
  2520. (defn- paste-text-parseable
  2521. [format text]
  2522. (let [tree (->>
  2523. (block/extract-blocks
  2524. (mldoc/->edn text (mldoc/default-config format)) text true format))
  2525. min-level (apply min (mapv :block/level tree))
  2526. prefix-level (if (> min-level 1) (- min-level 1) 0)
  2527. tree* (->> tree
  2528. (mapv #(assoc % :level (- (:block/level %) prefix-level)))
  2529. (blocks-vec->tree))]
  2530. (paste-block-vec-tree-at-target tree* [] nil)))
  2531. (defn- paste-segmented-text
  2532. [format text]
  2533. (let [paragraphs (string/split text #"(?:\r?\n){2,}")
  2534. updated-paragraphs
  2535. (string/join "\n"
  2536. (mapv (fn [p] (->> (string/trim p)
  2537. ((fn [p]
  2538. (if (util/safe-re-find (if (= format :org)
  2539. #"\s*\*+\s+"
  2540. #"\s*-\s+") p)
  2541. p
  2542. (str (if (= format :org) "* " "- ") p))))))
  2543. paragraphs))]
  2544. (paste-text-parseable format updated-paragraphs)))
  2545. (defn- paste-text
  2546. [text e]
  2547. (let [repo (state/get-current-repo)
  2548. page (or (db/entity [:block/name (state/get-current-page)])
  2549. (db/entity [:block/original-name (state/get-current-page)])
  2550. (:block/page (db/entity (:db/id (state/get-edit-block)))))
  2551. copied-blocks (state/get-copied-blocks)
  2552. copied-block-tree (:copy/block-tree copied-blocks)]
  2553. (if (and
  2554. (:copy/content copied-blocks)
  2555. (not (string/blank? text))
  2556. (= (string/replace (string/trim text) "\r" "")
  2557. (string/replace (string/trim (:copy/content copied-blocks)) "\r" "")))
  2558. (do
  2559. ;; copy from logseq internally
  2560. (paste-block-vec-tree-at-target copied-block-tree [] nil)
  2561. (util/stop e))
  2562. (do
  2563. ;; from external
  2564. (let [format (or (db/get-page-format (state/get-current-page)) :markdown)]
  2565. (match [format
  2566. (nil? (util/safe-re-find #"(?m)^\s*(?:[-+*]|#+)\s+" text))
  2567. (nil? (util/safe-re-find #"(?m)^\s*\*+\s+" text))
  2568. (nil? (util/safe-re-find #"(?:\r?\n){2,}" text))]
  2569. [:markdown false _ _]
  2570. (do
  2571. (paste-text-parseable format text)
  2572. (util/stop e))
  2573. [:org _ false _]
  2574. (do
  2575. (paste-text-parseable format text)
  2576. (util/stop e))
  2577. [:markdown true _ false]
  2578. (do
  2579. (paste-segmented-text format text)
  2580. (util/stop e))
  2581. [:markdown true _ true]
  2582. (do)
  2583. [:org _ true false]
  2584. (do
  2585. (paste-segmented-text format text)
  2586. (util/stop e))
  2587. [:org _ true true]
  2588. (do)))))))
  2589. (defn editor-on-paste!
  2590. [id]
  2591. (fn [e]
  2592. (state/set-state! :editor/on-paste? true)
  2593. (if-let [handled
  2594. (let [pick-one-allowed-item
  2595. (fn [items]
  2596. (if (util/electron?)
  2597. (let [existed-file-path (js/window.apis.getFilePathFromClipboard)
  2598. existed-file-path (if (and
  2599. (string? existed-file-path)
  2600. (not util/mac?)
  2601. (not util/win32?)) ; FIXME: linux
  2602. (when (util/safe-re-find #"^(/[^/ ]*)+/?$" existed-file-path)
  2603. existed-file-path)
  2604. existed-file-path)
  2605. has-file-path? (not (string/blank? existed-file-path))
  2606. has-image? (js/window.apis.isClipboardHasImage)]
  2607. (when (or has-image? has-file-path?)
  2608. [:asset (js/File. #js[] (if has-file-path? existed-file-path "image.png"))]))
  2609. (when (and items (.-length items))
  2610. (let [files (. (js/Array.from items) (filter #(= (.-kind %) "file")))
  2611. it (gobj/get files 0) ;;; TODO: support multiple files
  2612. mime (and it (.-type it))]
  2613. (cond
  2614. (contains? #{"image/jpeg" "image/png" "image/jpg" "image/gif"} mime) [:asset (. it getAsFile)])))))
  2615. clipboard-data (gobj/get e "clipboardData")
  2616. items (or (.-items clipboard-data)
  2617. (.-files clipboard-data))
  2618. picked (pick-one-allowed-item items)]
  2619. (when-let [file (second picked)]
  2620. (when-let [block (state/get-edit-block)]
  2621. (upload-asset id #js[file] (:block/format block) *asset-uploading? true))))]
  2622. (util/stop e)
  2623. (paste-text (.getData (gobj/get e "clipboardData") "text") e))))
  2624. (defn- cut-blocks-and-clear-selections!
  2625. [copy?]
  2626. (cut-selection-blocks copy?)
  2627. (clear-selection!))
  2628. (defn shortcut-copy-selection
  2629. [e]
  2630. (copy-selection-blocks))
  2631. (defn shortcut-cut-selection
  2632. [e]
  2633. (util/stop e)
  2634. (cut-blocks-and-clear-selections! true))
  2635. (defn shortcut-delete-selection
  2636. [e]
  2637. (util/stop e)
  2638. (cut-blocks-and-clear-selections! false))
  2639. ;; credits to @pengx17
  2640. (defn- copy-current-block-ref
  2641. []
  2642. (when-let [current-block (state/get-edit-block)]
  2643. (when-let [block-id (:block/uuid current-block)]
  2644. (copy-block-ref! block-id #(str "((" % "))"))
  2645. (notification/show!
  2646. [:div
  2647. [:span.mb-1.5 "Block ref copied!"]
  2648. [:div [:code.whitespace-nowrap (str "((" block-id "))")]]]
  2649. :success true
  2650. ;; use uuid to make sure there is only one toast a time
  2651. (str "copied-block-ref:" block-id)))))
  2652. (defn shortcut-copy
  2653. "shortcut copy action:
  2654. * when in selection mode, copy selected blocks
  2655. * when in edit mode but no text selected, copy current block ref
  2656. * when in edit mode with text selected, copy selected text as normal"
  2657. [e]
  2658. (when-not (auto-complete?)
  2659. (cond
  2660. (state/selection?)
  2661. (shortcut-copy-selection e)
  2662. (state/editing?)
  2663. (let [input (state/get-input)
  2664. selected-start (.-selectionStart input)
  2665. selected-end (.-selectionEnd input)]
  2666. (if (= selected-start selected-end)
  2667. (copy-current-block-ref)
  2668. (js/document.execCommand "copy")))
  2669. :else
  2670. (js/document.execCommand "copy"))))
  2671. (defn shortcut-cut
  2672. "shortcut cut action:
  2673. * when in selection mode, cut selected blocks
  2674. * when in edit mode with text selected, cut selected text
  2675. * otherwise same as delete shortcut"
  2676. [e]
  2677. (cond
  2678. (state/selection?)
  2679. (shortcut-cut-selection e)
  2680. (state/editing?)
  2681. (keydown-backspace-handler true e)))
  2682. (defn delete-selection
  2683. [e]
  2684. (when (state/selection?)
  2685. (shortcut-delete-selection e)))
  2686. (defn editor-delete
  2687. [_state e]
  2688. (when (state/editing?)
  2689. (keydown-delete-handler e)))
  2690. (defn editor-backspace
  2691. [_state e]
  2692. (when (state/editing?)
  2693. (keydown-backspace-handler false e)))
  2694. (defn shortcut-up-down [direction]
  2695. (fn [e]
  2696. (when-not (auto-complete?)
  2697. (util/stop e)
  2698. (cond
  2699. (state/editing?)
  2700. (keydown-up-down-handler direction)
  2701. (and (state/selection?) (== 1 (count (state/get-selection-blocks))))
  2702. (select-up-down direction)
  2703. :else
  2704. (select-first-last direction)))))
  2705. (defn open-selected-block!
  2706. [direction e]
  2707. (when-let [block-id (some-> (state/get-selection-blocks)
  2708. first
  2709. (dom/attr "blockid")
  2710. medley/uuid)]
  2711. (util/stop e)
  2712. (let [block {:block/uuid block-id}
  2713. block-id (-> (state/get-selection-blocks)
  2714. first
  2715. (gobj/get "id")
  2716. (string/replace "ls-block" "edit-block"))
  2717. left? (= direction :left)]
  2718. (edit-block! block
  2719. (if left? 0 :max)
  2720. (:block/format block)
  2721. block-id))))
  2722. (defn shortcut-left-right [direction]
  2723. (fn [e]
  2724. (when-not (auto-complete?)
  2725. (util/stop e)
  2726. (cond
  2727. (state/editing?)
  2728. (keydown-arrow-handler direction)
  2729. (and (state/selection?) (== 1 (count (state/get-selection-blocks))))
  2730. (open-selected-block! direction e)
  2731. :else
  2732. nil))))
  2733. (defn clear-block-content! []
  2734. (save-current-block! {:force? true})
  2735. (state/set-edit-content! (state/get-edit-input-id) ""))
  2736. (defn kill-line-before! []
  2737. (save-current-block! {:force? true})
  2738. (util/kill-line-before! (state/get-input)))
  2739. (defn kill-line-after! []
  2740. (save-current-block! {:force? true})
  2741. (util/kill-line-after! (state/get-input)))
  2742. (defn beginning-of-block []
  2743. (cursor/move-cursor-to (state/get-input) 0))
  2744. (defn end-of-block []
  2745. (cursor/move-cursor-to-end (state/get-input)))
  2746. (defn cursor-forward-word []
  2747. (cursor/move-cursor-forward-by-word (state/get-input)))
  2748. (defn cursor-backward-word []
  2749. (cursor/move-cursor-backward-by-word (state/get-input)))
  2750. (defn backward-kill-word []
  2751. (let [input (state/get-input)]
  2752. (save-current-block! {:force? true})
  2753. (util/backward-kill-word input)
  2754. (state/set-edit-content! (state/get-edit-input-id) (.-value input))))
  2755. (defn forward-kill-word []
  2756. (let [input (state/get-input)]
  2757. (save-current-block! {:force? true})
  2758. (util/forward-kill-word input)
  2759. (state/set-edit-content! (state/get-edit-input-id) (.-value input))))
  2760. (defn all-blocks-with-level
  2761. "Return all blocks associated with correct level
  2762. if :collapse? true, return without any collapsed children
  2763. for example:
  2764. - a
  2765. - b (collapsed)
  2766. - c
  2767. - d
  2768. - e
  2769. return:
  2770. blocks
  2771. [{:block a :level 1}
  2772. {:block b :level 2}
  2773. {:block e :level 2}]"
  2774. [{:keys [collapse?] :or {collapse? false}}]
  2775. (when-let [page (or (state/get-current-page)
  2776. (date/today))]
  2777. (->>
  2778. (-> page
  2779. (db/get-page-blocks-no-cache)
  2780. (tree/blocks->vec-tree page))
  2781. (#(if collapse?
  2782. (w/postwalk
  2783. (fn [x]
  2784. (if (and (map? x) (-> x :block/properties :collapsed))
  2785. (assoc x :block/children []) x)) %) %))
  2786. (mapcat (fn [x] (tree-seq map? :block/children x)))
  2787. (map (fn [x] (dissoc x :block/children))))))
  2788. (defn collapsable? [block-id]
  2789. (if-let [block (db-model/get-block-by-uuid block-id)]
  2790. (and
  2791. (nil? (-> block :block/properties :collapsed))
  2792. (or (not-empty (:block/body block))
  2793. (db-model/has-children? block-id)))
  2794. false))
  2795. (defn collapse-block! [block-id]
  2796. (when (collapsable? block-id)
  2797. (set-block-property! block-id :collapsed true)))
  2798. (defn expand-block! [block-id]
  2799. (remove-block-property! block-id :collapsed))
  2800. (defn expand!
  2801. [e]
  2802. (util/stop e)
  2803. (cond
  2804. (state/editing?)
  2805. (when-let [block-id (:block/uuid (state/get-edit-block))]
  2806. (expand-block! block-id))
  2807. (state/selection?)
  2808. (do
  2809. (->> (get-selected-blocks-with-children)
  2810. (map (fn [dom]
  2811. (-> (dom/attr dom "blockid")
  2812. medley/uuid
  2813. expand-block!)))
  2814. doall)
  2815. (clear-selection!))
  2816. :else
  2817. ;; expand one level
  2818. (let [blocks-with-level (all-blocks-with-level {})
  2819. max-level (or (apply max (map :block/level blocks-with-level)) 99)]
  2820. (loop [level 1]
  2821. (if (> level max-level)
  2822. nil
  2823. (let [blocks-to-expand (->> blocks-with-level
  2824. (filter (fn [b] (= (:block/level b) level)))
  2825. (filter (fn [{:block/keys [properties]}]
  2826. (contains? properties :collapsed))))]
  2827. (if (empty? blocks-to-expand)
  2828. (recur (inc level))
  2829. (doseq [{:block/keys [uuid]} blocks-to-expand]
  2830. (expand-block! uuid)))))))))
  2831. (defn collapse!
  2832. [e]
  2833. (util/stop e)
  2834. (cond
  2835. (state/editing?)
  2836. (when-let [block-id (:block/uuid (state/get-edit-block))]
  2837. (collapse-block! block-id))
  2838. (state/selection?)
  2839. (do
  2840. (->> (get-selected-blocks-with-children)
  2841. (map (fn [dom]
  2842. (-> (dom/attr dom "blockid")
  2843. medley/uuid
  2844. collapse-block!)))
  2845. doall)
  2846. (clear-selection!))
  2847. :else
  2848. ;; collapse by one level from outside
  2849. (let [blocks-with-level
  2850. (all-blocks-with-level {:collapse? true})
  2851. max-level (or (apply max (map :block/level blocks-with-level)) 99)]
  2852. (loop [level max-level]
  2853. (if (zero? level)
  2854. nil
  2855. (let [blocks-to-collapse
  2856. (->> blocks-with-level
  2857. (filter (fn [b] (= (:block/level b) level)))
  2858. (filter (fn [b] (collapsable? (:block/uuid b)))))]
  2859. (if (empty? blocks-to-collapse)
  2860. (recur (dec level))
  2861. (doseq [{:block/keys [uuid]} blocks-to-collapse]
  2862. (collapse-block! uuid)))))))))
  2863. (defn- collapse-all!
  2864. []
  2865. (let [blocks-to-collapse
  2866. (->> (all-blocks-with-level {:collapse? true})
  2867. (filter (fn [b] (collapsable? (:block/uuid b)))))]
  2868. (when (seq blocks-to-collapse)
  2869. (doseq [{:block/keys [uuid]} blocks-to-collapse]
  2870. (collapse-block! uuid)))))
  2871. (defn- expand-all!
  2872. []
  2873. (->> (all-blocks-with-level {})
  2874. (filter (fn [b] (-> b :block/properties :collapsed)))
  2875. (map (comp expand-block! :block/uuid))
  2876. doall))
  2877. (defn toggle-open! []
  2878. (let [all-collapsed?
  2879. (->> (all-blocks-with-level {:collapse? true})
  2880. (filter (fn [b] (collapsable? (:block/uuid b))))
  2881. (empty?))]
  2882. (if all-collapsed?
  2883. (expand-all!)
  2884. (collapse-all!))))
  2885. (defn select-all-blocks!
  2886. []
  2887. (if-let [current-input-id (state/get-edit-input-id)]
  2888. (let [input (gdom/getElement current-input-id)
  2889. blocks-container (util/rec-get-blocks-container input)
  2890. blocks (dom/by-class blocks-container "ls-block")]
  2891. (state/exit-editing-and-set-selected-blocks! blocks))
  2892. (->> (all-blocks-with-level {:collapse? true})
  2893. (map (comp gdom/getElementByClass str :block/uuid))
  2894. state/exit-editing-and-set-selected-blocks!)))
  2895. (defn escape-editing
  2896. ([]
  2897. (escape-editing true))
  2898. ([select?]
  2899. (when (state/editing?)
  2900. (if select?
  2901. (->> (:block/uuid (state/get-edit-block))
  2902. select-block!)
  2903. (state/clear-edit!)))))
  2904. (defn replace-block-reference-with-content-at-point
  2905. []
  2906. (when-let [{:keys [content start end]} (thingatpt/block-ref-at-point)]
  2907. (let [block-ref-id (subs content 2 (- (count content) 2))]
  2908. (when-let [block (db/pull [:block/uuid (uuid block-ref-id)])]
  2909. (let [block-content (:block/content block)
  2910. format (or (:block/format block) :markdown)
  2911. block-content-without-prop (-> (property/remove-properties format block-content)
  2912. (drawer/remove-logbook))]
  2913. (when-let [input (state/get-input)]
  2914. (when-let [current-block-content (gobj/get input "value")]
  2915. (let [block-content* (str (subs current-block-content 0 start)
  2916. block-content-without-prop
  2917. (subs current-block-content end))]
  2918. (state/set-block-content-and-last-pos! input block-content* 1)))))))))
  2919. (defn paste-text-in-one-block-at-point
  2920. []
  2921. (utils/getClipText
  2922. (fn [clipboard-data]
  2923. (when-let [_ (state/get-input)]
  2924. (state/append-current-edit-content! clipboard-data)))
  2925. (fn [error]
  2926. (js/console.error error))))
  2927. (defn copy-current-ref
  2928. [block-id]
  2929. (when block-id
  2930. (util/copy-to-clipboard! (util/format "((%s))" (str block-id)))))
  2931. (defn delete-current-ref!
  2932. [block ref-id]
  2933. (when (and block ref-id)
  2934. (let [match (re-pattern (str "\\s?" (util/format "\\(\\(%s\\)\\)" (str ref-id))))
  2935. content (string/replace-first (:block/content block) match "")]
  2936. (save-block! (state/get-current-repo)
  2937. (:block/uuid block)
  2938. content))))
  2939. (defn replace-ref-with-text!
  2940. [block ref-id]
  2941. (when (and block ref-id)
  2942. (let [match (util/format "((%s))" (str ref-id))
  2943. ref-block (db/entity [:block/uuid ref-id])
  2944. block-ref-content (->> (or (:block/content ref-block)
  2945. "")
  2946. (property/remove-built-in-properties (:block/format ref-block))
  2947. (drawer/remove-logbook))
  2948. content (string/replace-first (:block/content block) match
  2949. block-ref-content)]
  2950. (save-block! (state/get-current-repo)
  2951. (:block/uuid block)
  2952. content))))
  2953. (defn replace-ref-with-embed!
  2954. [block ref-id]
  2955. (when (and block ref-id)
  2956. (let [match (util/format "((%s))" (str ref-id))
  2957. content (string/replace-first (:block/content block) match
  2958. (util/format "{{embed ((%s))}}"
  2959. (str ref-id)))]
  2960. (save-block! (state/get-current-repo)
  2961. (:block/uuid block)
  2962. content))))