editor.cljs 116 KB

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