editor.cljs 145 KB

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