editor.cljs 145 KB

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