editor.cljs 121 KB

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