editor.cljs 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057
  1. (ns frontend.handler.editor
  2. (:require [frontend.state :as state]
  3. [frontend.handler.common :as common-handler]
  4. [frontend.handler.route :as route-handler]
  5. [frontend.handler.git :as git-handler]
  6. [frontend.handler.ui :as ui-handler]
  7. [frontend.handler.repo :as repo-handler]
  8. [frontend.handler.file :as file-handler]
  9. [frontend.handler.notification :as notification]
  10. [frontend.handler.draw :as draw]
  11. [frontend.handler.expand :as expand]
  12. [frontend.format.mldoc :as mldoc]
  13. [frontend.format :as format]
  14. [frontend.format.block :as block]
  15. [frontend.image :as image]
  16. [cljs-time.core :as t]
  17. [cljs-time.coerce :as tc]
  18. [frontend.db :as db]
  19. [goog.object :as gobj]
  20. [goog.dom :as gdom]
  21. [goog.dom.classes :as gdom-classes]
  22. [clojure.string :as string]
  23. [frontend.util :as util :refer-macros [profile]]
  24. [frontend.config :as config]
  25. [dommy.core :as dom]
  26. [frontend.utf8 :as utf8]
  27. [frontend.fs :as fs]
  28. [promesa.core :as p]
  29. [dommy.core :as d]
  30. [frontend.diff :as diff]
  31. [frontend.search :as search]
  32. [frontend.handler.image :as image-handler]
  33. [frontend.commands :as commands
  34. :refer [*show-commands
  35. *slash-caret-pos
  36. *angle-bracket-caret-pos
  37. *show-block-commands]]
  38. [frontend.extensions.html-parser :as html-parser]
  39. [medley.core :as medley]
  40. [frontend.text :as text]
  41. [frontend.date :as date]
  42. [frontend.handler.repeated :as repeated]
  43. [clojure.core.async :as async]
  44. [lambdaisland.glogi :as log]))
  45. ;; FIXME: should support multiple images concurrently uploading
  46. (defonce *image-uploading? (atom false))
  47. (defonce *image-uploading-process (atom 0))
  48. (defonce *selected-text (atom nil))
  49. (defn modified-time-tx
  50. [page file]
  51. (let [modified-at (tc/to-long (t/now))]
  52. [[:db/add (:db/id page) :page/last-modified-at modified-at]
  53. [:db/add (:db/id file) :file/last-modified-at modified-at]]))
  54. (defn- get-selection-and-format
  55. []
  56. (when-let [block (state/get-edit-block)]
  57. (when-let [id (:block/uuid block)]
  58. (when-let [edit-id (state/get-edit-input-id)]
  59. (when-let [input (gdom/getElement edit-id)]
  60. {:selection-start (gobj/get input "selectionStart")
  61. :selection-end (gobj/get input "selectionEnd")
  62. :format (:block/format block)
  63. :value (gobj/get input "value")
  64. :block block
  65. :edit-id edit-id
  66. :input input})))))
  67. (defn- format-text!
  68. [pattern-fn]
  69. (when-let [m (get-selection-and-format)]
  70. (let [{:keys [selection-start selection-end format value block edit-id input]} m
  71. empty-selection? (= selection-start selection-end)
  72. pattern (pattern-fn format)
  73. new-value (str
  74. (subs value 0 selection-start)
  75. pattern
  76. (subs value selection-start selection-end)
  77. pattern
  78. (subs value selection-end))]
  79. (state/set-edit-content! edit-id new-value)
  80. (when empty-selection?
  81. (util/cursor-move-back input (count pattern))))))
  82. (defn bold-format! []
  83. (format-text! config/get-bold))
  84. (defn italics-format! []
  85. (format-text! config/get-italic))
  86. (defn highlight-format! []
  87. (format-text! config/get-highlight))
  88. (defn html-link-format! []
  89. (when-let [m (get-selection-and-format)]
  90. (let [{:keys [selection-start selection-end format value block edit-id input]} m
  91. cur-pos (:pos (util/get-caret-pos input))
  92. empty-selection? (= selection-start selection-end)
  93. selection (subs value selection-start selection-end)
  94. selection-link? (and selection (or (util/starts-with? selection "http://")
  95. (util/starts-with? selection "https://")))
  96. [content forward-pos] (cond
  97. empty-selection?
  98. (config/get-empty-link-and-forward-pos format)
  99. selection-link?
  100. (config/with-default-link format selection)
  101. :else
  102. (config/with-default-label format selection))
  103. new-value (str
  104. (subs value 0 selection-start)
  105. content
  106. (subs value selection-end))
  107. cur-pos (or selection-start cur-pos)]
  108. (state/set-edit-content! edit-id new-value)
  109. (util/move-cursor-to input (+ cur-pos forward-pos)))))
  110. (defn focus-on-block!
  111. [block-id]
  112. (when block-id
  113. (route-handler/redirect! {:to :page
  114. :path-params {:name (str block-id)}})))
  115. (defn open-block-in-sidebar!
  116. [block-id]
  117. (when block-id
  118. (when-let [block (db/pull [:block/uuid block-id])]
  119. (state/sidebar-add-block!
  120. (state/get-current-repo)
  121. (:db/id block)
  122. :block
  123. block))))
  124. (defn reset-cursor-range!
  125. [node]
  126. (when node
  127. (state/set-cursor-range! (util/caret-range node))))
  128. (defn restore-cursor-pos!
  129. ([id markup]
  130. (restore-cursor-pos! id markup false))
  131. ([id markup dummy?]
  132. (when-let [node (gdom/getElement (str id))]
  133. (when-let [cursor-range (state/get-cursor-range)]
  134. (when-let [range (string/trim cursor-range)]
  135. (let [pos (diff/find-position markup range)]
  136. (util/set-caret-pos! node pos)))))))
  137. (defn block-content-join-newlines
  138. [prefix value postfix]
  139. (str
  140. (if (or (= "" prefix)
  141. (= "\n" (last prefix)))
  142. ""
  143. "\n")
  144. (string/trim value)
  145. (if (= "\n" (first postfix))
  146. ""
  147. "\n")))
  148. (defn new-file-content
  149. [{:block/keys [content meta dummy?] :as block} file-content value]
  150. (let [utf8-content (utf8/encode file-content)
  151. prefix (utf8/substring utf8-content 0 (:start-pos meta))
  152. postfix (let [end-pos (if dummy?
  153. (:start-pos meta)
  154. (:end-pos meta))]
  155. (utf8/substring utf8-content end-pos))
  156. value (block-content-join-newlines prefix value postfix)]
  157. [(str prefix value postfix)
  158. value]))
  159. (defn get-block-new-value
  160. [{:block/keys [content meta dummy?] :as block} file-content value]
  161. (let [utf8-content (utf8/encode file-content)
  162. prefix (utf8/substring utf8-content 0 (:start-pos meta))
  163. postfix (let [end-pos (if dummy?
  164. (:start-pos meta)
  165. (:end-pos meta))]
  166. (utf8/substring utf8-content end-pos))]
  167. (block-content-join-newlines prefix value postfix)))
  168. (defn new-file-content-indent-outdent
  169. [{:block/keys [content meta dummy?] :as block} file-content value block-with-children-content last-child-end-pos indent-left?]
  170. (let [utf8-content (utf8/encode file-content)
  171. prefix (utf8/substring utf8-content 0 (:start-pos meta))
  172. last-child-end-pos (if (some? indent-left?) last-child-end-pos nil)
  173. end-pos (or
  174. last-child-end-pos
  175. (if dummy?
  176. (:start-pos meta)
  177. (:end-pos meta)))
  178. postfix (utf8/substring utf8-content end-pos)
  179. block-children-value (block-content-join-newlines prefix block-with-children-content postfix)]
  180. (str prefix block-children-value postfix)))
  181. (defn- with-block-meta
  182. [repo block]
  183. (if (:block/dummy? block)
  184. (if-let [page-id (:db/id (:block/page block))]
  185. (let [page-name (:page/name (db/entity repo page-id))
  186. end-pos (db/get-block-page-end-pos repo page-name)]
  187. (assoc block :block/meta {:start-pos end-pos
  188. :end-pos end-pos}))
  189. block)
  190. (if-let [meta (:block/meta (db/entity repo [:block/uuid (:block/uuid block)]))]
  191. (assoc block :block/meta meta)
  192. block)))
  193. (defn highlight-block!
  194. [block-uuid]
  195. (let [blocks (array-seq (js/document.getElementsByClassName (str block-uuid)))]
  196. (doseq [block blocks]
  197. (dom/add-class! block "block-highlight"))))
  198. (defn unhighlight-block!
  199. []
  200. (let [blocks (some->> (array-seq (js/document.getElementsByClassName "block-highlight"))
  201. (repeat 2)
  202. (apply concat))]
  203. (doseq [block blocks]
  204. (gdom-classes/remove block "block-highlight"))))
  205. (defn rebuild-blocks-meta
  206. [start-pos blocks]
  207. (let [last-start-pos (atom start-pos)]
  208. (mapv
  209. (fn [{:block/keys [uuid meta] :as block}]
  210. (let [old-start-pos (:start-pos meta)
  211. old-end-pos (:end-pos meta)
  212. new-end-pos (if old-end-pos
  213. (+ @last-start-pos (- old-end-pos old-start-pos)))
  214. new-meta {:start-pos @last-start-pos
  215. :end-pos new-end-pos}]
  216. (reset! last-start-pos new-end-pos)
  217. {:block/uuid uuid
  218. :block/meta new-meta}))
  219. blocks)))
  220. (defn rebuild-after-blocks
  221. [repo file before-end-pos new-end-pos]
  222. (let [file-id (:db/id file)
  223. after-blocks (db/get-file-after-blocks-meta repo file-id before-end-pos)]
  224. (rebuild-blocks-meta new-end-pos after-blocks)))
  225. (defn rebuild-after-blocks-indent-outdent
  226. [repo file block before-end-pos new-end-pos indent-left?]
  227. (let [file-id (:db/id file)
  228. after-blocks (db/get-file-after-blocks-meta repo file-id before-end-pos true)
  229. last-start-pos (atom new-end-pos)
  230. block-level (:block/level block)
  231. next-leq-level? (atom false)
  232. format (:block/format block)
  233. block-and-children-content (atom (:block/content block))
  234. last-child-end-pos (atom before-end-pos)
  235. after-blocks (mapv
  236. (fn [{:block/keys [uuid meta level content] :as block}]
  237. (let [old-start-pos (:start-pos meta)
  238. old-end-pos (:end-pos meta)]
  239. (when (<= level block-level)
  240. (reset! next-leq-level? true))
  241. (let [[new-content offset] (cond
  242. (and (not @next-leq-level?) (true? indent-left?))
  243. [(subs content 1) -1]
  244. (and (not @next-leq-level?) (false? indent-left?))
  245. [(str (config/get-block-pattern format) content) 1]
  246. :else
  247. [nil 0])
  248. new-end-pos (if old-end-pos
  249. (+ @last-start-pos
  250. (- old-end-pos old-start-pos)
  251. offset))
  252. new-meta {:start-pos @last-start-pos
  253. :end-pos new-end-pos}]
  254. (reset! last-start-pos new-end-pos)
  255. (when-not @next-leq-level?
  256. (do
  257. (reset! block-and-children-content (str @block-and-children-content new-content))
  258. (reset! last-child-end-pos old-end-pos)))
  259. (cond->
  260. {:block/uuid uuid
  261. :block/meta new-meta}
  262. (and (some? indent-left?) (not @next-leq-level?))
  263. (assoc :block/level (if indent-left? (dec level) (inc level)))
  264. (and new-content (not @next-leq-level?))
  265. (assoc :block/content new-content)))))
  266. after-blocks)]
  267. [after-blocks @block-and-children-content @last-child-end-pos]))
  268. (defn compute-retract-refs
  269. "Computes old references to be retracted."
  270. [eid {:block/keys [ref-pages ref-blocks]} old-ref-pages old-ref-blocks]
  271. (let [ref-pages-id (map #(:db/id (db/get-page (:page/name %))) ref-pages)
  272. retracted-pages (reduce (fn [done current]
  273. (if (some #(= (:db/id current) %) ref-pages-id)
  274. done
  275. (conj done (:db/id current))))
  276. [] old-ref-pages)
  277. ref-blocks-id (map #(:db/id (db/get-page (str (last %)))) ref-blocks)
  278. retracted-blocks (reduce (fn [done current]
  279. (if (some #(= (:db/id current) %) ref-blocks-id)
  280. done
  281. (conj done (:db/id current))))
  282. [] old-ref-blocks)]
  283. ;; removes retracted pages and blocks
  284. (into
  285. (mapv (fn [ref] [:db/retract eid :block/ref-pages ref]) retracted-pages)
  286. (mapv (fn [ref] [:db/retract eid :block/ref-blocks ref]) retracted-blocks))))
  287. (defn- rebuild-block-content
  288. "We'll create an empty heading if the first parsed ast element is not a paragraph, definition list or some hiccup."
  289. [content format]
  290. (let [content-without-level-spaces (text/remove-level-spaces content format)
  291. first-block (-> content-without-level-spaces
  292. (format/to-edn format)
  293. ffirst)]
  294. (if (or (block/heading-block? first-block)
  295. (block/paragraph-block? first-block)
  296. (block/hiccup-block? first-block)
  297. (block/definition-list-block? first-block))
  298. content
  299. (text/append-newline-after-level-spaces content format))))
  300. (defn- get-edit-input-id-with-block-id
  301. [block-id]
  302. (when-let [first-block (util/get-first-block-by-id block-id)]
  303. (string/replace (gobj/get first-block "id")
  304. "ls-block"
  305. "edit-block")))
  306. ;; id: block dom id, "ls-block-counter-uuid"
  307. (defn edit-block!
  308. ([block pos format id]
  309. (edit-block! block pos format id nil))
  310. ([block pos format id {:keys [custom-content custom-properties tail-len]
  311. :or {tail-len 0}}]
  312. (when-not config/publishing?
  313. (when-let [block-id (:block/uuid block)]
  314. (let [edit-input-id (if (uuid? id)
  315. (get-edit-input-id-with-block-id id)
  316. (str (subs id 0 (- (count id) 36)) block-id))
  317. block (or
  318. block
  319. (db/pull [:block/uuid block-id])
  320. ;; dummy?
  321. {:block/uuid block-id
  322. :block/content ""})
  323. {:block/keys [content properties]} block
  324. content (or custom-content content)
  325. content (string/trim (text/remove-level-spaces content format))
  326. properties (or custom-properties properties)
  327. content (if (and (seq properties) (text/properties-hidden? properties))
  328. (text/remove-properties! content)
  329. content)
  330. content-length (count content)
  331. text-range (cond
  332. (and (> tail-len 0) (>= (count content) tail-len))
  333. (subs content 0 (- (count content) tail-len))
  334. (or (= :max pos) (<= content-length pos))
  335. content
  336. :else
  337. (subs content 0 pos))]
  338. (state/set-editing! edit-input-id content block text-range))))))
  339. (defn edit-last-block-for-new-page!
  340. [last-block pos]
  341. (when-let [first-block (util/get-first-block-by-id (:block/uuid last-block))]
  342. (edit-block!
  343. last-block
  344. pos
  345. (:block/format last-block)
  346. (string/replace (gobj/get first-block "id")
  347. "ls-block"
  348. "edit-block"))))
  349. (defn- with-time-properties
  350. [block properties]
  351. (if (and (state/enable-block-time?)
  352. (not (:block/pre-block? block)))
  353. (let [time (util/time-ms)
  354. props (into {} (:block/properties block))]
  355. (merge properties
  356. (if-let [created-at (get props "created_at")]
  357. {"created_at" created-at
  358. "last_modified_at" time}
  359. {"created_at" time
  360. "last_modified_at" time})))
  361. properties))
  362. (defn- block-text-with-time
  363. [block format value]
  364. (let [value (text/remove-level-spaces value (keyword format))
  365. properties (with-time-properties block {})]
  366. (text/re-construct-block-properties value properties)))
  367. (defn save-block-if-changed!
  368. ([block value]
  369. (save-block-if-changed! block value nil))
  370. ([{:block/keys [uuid content meta file page dummy? format repo pre-block? content ref-pages ref-blocks] :as block}
  371. value
  372. {:keys [indent-left? custom-properties remove-properties rebuild-content?]
  373. :or {rebuild-content? true
  374. custom-properties nil
  375. remove-properties nil}}]
  376. (let [value value
  377. repo (or repo (state/get-current-repo))
  378. e (db/entity repo [:block/uuid uuid])
  379. block (assoc (with-block-meta repo block)
  380. ;; (into {} ...) to fix the old data
  381. :block/properties (into {} (:block/properties e)))
  382. format (or format (state/get-preferred-format))
  383. page (db/entity repo (:db/id page))
  384. ;; page properties
  385. [old-properties new-properties] (when pre-block?
  386. [(:page/properties (db/entity (:db/id page)))
  387. (mldoc/parse-properties value format)])
  388. page-tags (when-let [tags (:tags new-properties)]
  389. (util/->tags tags))
  390. page-alias (when-let [alias (:alias new-properties)]
  391. (map
  392. (fn [alias]
  393. {:page/name (string/lower-case alias)})
  394. (remove #{(:page/name page)} alias)))
  395. permalink-changed? (when (and pre-block? (:permalink old-properties))
  396. (not= (:permalink old-properties)
  397. (:permalink new-properties)))
  398. value (if permalink-changed?
  399. (db/add-properties! format value {:old_permalink (:permalink old-properties)})
  400. value)
  401. new-properties (if permalink-changed?
  402. (assoc new-properties :old_permalink (:permalink old-properties))
  403. new-properties)
  404. text-properties (text/extract-properties value)
  405. properties (->> custom-properties
  406. (with-time-properties block)
  407. (merge text-properties))
  408. properties (if (and (seq properties) (seq remove-properties))
  409. (medley/remove-keys (fn [k] (contains? (set remove-properties) k)) properties)
  410. properties)
  411. value (text/re-construct-block-properties value properties)]
  412. (cond
  413. (not= (string/trim content) (string/trim value)) ; block content changed
  414. (let [file (db/entity repo (:db/id file))]
  415. (cond
  416. ;; Page was referenced but no related file
  417. ;; TODO: replace with handler.page/create!
  418. (and page (not file))
  419. (let [format (name format)
  420. title (string/capitalize (:page/name page))
  421. journal-page? (date/valid-journal-title? title)
  422. path (str
  423. (if journal-page?
  424. config/default-journals-directory
  425. (config/get-pages-directory))
  426. "/"
  427. (if journal-page?
  428. (date/journal-title->default title)
  429. (-> (:page/name page)
  430. (util/page-name-sanity))) "."
  431. (if (= format "markdown") "md" format))
  432. file-path (str "/" path)
  433. dir (util/get-repo-dir repo)]
  434. (p/let [exists? (fs/file-exists? dir file-path)]
  435. (if exists?
  436. (notification/show!
  437. [:p.content
  438. (util/format "File %s already exists!" file-path)]
  439. :error)
  440. ;; create the file
  441. (let [value (block-text-with-time nil format value)
  442. content (str (util/default-content-with-title format
  443. (or (:page/original-name page)
  444. (:page/name page)))
  445. value)]
  446. (p/let [_ (fs/create-if-not-exists repo dir file-path content)
  447. _ (git-handler/git-add repo path)]
  448. (file-handler/reset-file! repo path content)
  449. (ui-handler/re-render-root!)
  450. ;; Continue to edit the last block
  451. (let [blocks (db/get-page-blocks repo (:page/name page))
  452. last-block (last blocks)]
  453. (edit-last-block-for-new-page! last-block :max)))))))
  454. (and file page)
  455. (let [file (db/entity repo (:db/id file))
  456. file-path (:file/path file)
  457. format (format/get-format file-path)
  458. file-content (db/get-file repo file-path)
  459. value (get-block-new-value block file-content value)
  460. value (if rebuild-content?
  461. (rebuild-block-content value format)
  462. value)
  463. block (assoc block :block/content value)
  464. {:keys [blocks pages start-pos end-pos]} (if pre-block?
  465. (let [new-end-pos (utf8/length (utf8/encode value))]
  466. {:blocks [(assoc-in block [:block/meta :end-pos] new-end-pos)]
  467. :pages []
  468. :start-pos 0
  469. :end-pos new-end-pos})
  470. (block/parse-block block format))
  471. block-retracted-attrs (when-not pre-block?
  472. (when-let [id (:db/id block)]
  473. [[:db/retract id :block/priority]
  474. [:db/retract id :block/deadline]
  475. [:db/retract id :block/deadline-ast]
  476. [:db/retract id :block/scheduled]
  477. [:db/retract id :block/scheduled-ast]
  478. [:db/retract id :block/marker]
  479. [:db/retract id :block/tags]
  480. [:db/retract id :block/repeated?]]))
  481. [after-blocks block-children-content new-end-pos] (rebuild-after-blocks-indent-outdent repo file block (:end-pos (:block/meta block)) end-pos indent-left?)
  482. retract-refs (compute-retract-refs (:db/id e) (first blocks) ref-pages ref-blocks)
  483. page-id (:db/id page)
  484. modified-time (let [modified-at (tc/to-long (t/now))]
  485. [[:db/add page-id :page/last-modified-at modified-at]
  486. [:db/add (:db/id file) :file/last-modified-at modified-at]])
  487. page-properties (when pre-block?
  488. (if (seq new-properties)
  489. [[:db/retract page-id :page/properties]
  490. {:db/id page-id
  491. :page/properties new-properties}]
  492. [[:db/retract page-id :page/properties]]))
  493. pages (if (seq page-tags)
  494. (let [tag-pages (map
  495. (fn [page]
  496. {:page/original-name page
  497. :page/name page})
  498. (map :tag/name page-tags))]
  499. (concat pages tag-pages))
  500. pages)
  501. pages (remove
  502. (fn [page]
  503. (string/blank? (:page/name page)))
  504. pages)
  505. page-tags (when (and pre-block? (seq page-tags))
  506. (if (seq page-tags)
  507. [[:db/retract page-id :page/tags]
  508. {:db/id page-id
  509. :page/tags page-tags}]
  510. [[:db/retract page-id :page/tags]]))
  511. page-alias (when (and pre-block? (seq page-alias))
  512. (if (seq page-alias)
  513. [[:db/retract page-id :page/alias]
  514. {:db/id page-id
  515. :page/alias page-alias}]
  516. [[:db/retract page-id :page/alias]]))]
  517. (profile
  518. "Save block: "
  519. (repo-handler/transact-react-and-alter-file!
  520. repo
  521. (concat
  522. pages
  523. block-retracted-attrs
  524. (mapv (fn [b] {:block/uuid (:block/uuid b)}) blocks)
  525. blocks
  526. retract-refs
  527. page-properties
  528. page-tags
  529. page-alias
  530. after-blocks
  531. modified-time)
  532. {:key :block/change
  533. :data (map (fn [block] (assoc block :block/page page)) blocks)}
  534. (let [new-content (new-file-content-indent-outdent block file-content value block-children-content new-end-pos indent-left?)]
  535. [[file-path new-content]])))
  536. (when (or (seq retract-refs) pre-block?)
  537. (ui-handler/re-render-root!))
  538. (repo-handler/push-if-auto-enabled! repo))
  539. :else
  540. nil))
  541. (seq (state/get-changed-files))
  542. (repo-handler/push-if-auto-enabled! repo)
  543. :else
  544. nil))))
  545. (defn insert-new-block-aux!
  546. [{:block/keys [uuid content meta file dummy? level repo page format properties collapsed?] :as block}
  547. value
  548. {:keys [create-new-block? ok-handler with-level? new-level current-page blocks-container-id]}]
  549. (let [value (or value "")
  550. block-page? (and current-page (util/uuid-string? current-page))
  551. block-self? (= uuid (and block-page? (medley/uuid current-page)))
  552. input (gdom/getElement (state/get-edit-input-id))
  553. pos (if new-level
  554. (dec (count value))
  555. (util/get-input-pos input))
  556. repo (or repo (state/get-current-repo))
  557. block-has-children? (seq (:block/children block))
  558. fst-block-text (subs value 0 pos)
  559. snd-block-text (string/triml (subs value pos))
  560. fst-block-text (string/trim (if with-level? fst-block-text (block/with-levels fst-block-text format block)))
  561. edit-self? (and block-has-children? (zero? pos))
  562. snd-block-text-level (cond
  563. new-level
  564. new-level
  565. (or block-self?
  566. (and block-has-children?
  567. (not (zero? pos))))
  568. (inc level)
  569. :else
  570. level)
  571. snd-block-text (if (and snd-block-text
  572. (re-find (re-pattern (util/format "^[%s]+\\s+" (config/get-block-pattern format))) snd-block-text))
  573. snd-block-text
  574. (rebuild-block-content
  575. (str (config/default-empty-block format snd-block-text-level) " " snd-block-text)
  576. format))
  577. block (with-block-meta repo block)
  578. original-id (:block/uuid block)
  579. format (:block/format block)
  580. page (db/entity repo (:db/id page))
  581. file (db/entity repo (:db/id file))
  582. insert-block (fn [block file-path file-content]
  583. (let [value (if create-new-block?
  584. (str fst-block-text "\n" snd-block-text)
  585. value)
  586. text-properties (text/extract-properties fst-block-text)
  587. properties (with-time-properties block text-properties)
  588. value (text/re-construct-block-properties value properties)
  589. value (rebuild-block-content value format)
  590. [new-content value] (new-file-content block file-content value)
  591. parse-result (block/parse-block (assoc block :block/content value) format)
  592. id-conflict? (some #(= original-id (:block/uuid %)) (next (:blocks parse-result)))
  593. {:keys [blocks pages start-pos end-pos]}
  594. (if id-conflict?
  595. (let [new-value (string/replace
  596. value
  597. (re-pattern (str "(?i):(custom_)?id: " original-id))
  598. "")]
  599. (block/parse-block (assoc block :block/content new-value) format))
  600. parse-result)
  601. after-blocks (rebuild-after-blocks repo file (:end-pos meta) end-pos)
  602. files [[file-path new-content]]
  603. transact-fn (fn []
  604. (repo-handler/transact-react-and-alter-file!
  605. repo
  606. (concat
  607. pages
  608. (mapv (fn [b] {:block/uuid (:block/uuid b)}) blocks)
  609. blocks
  610. after-blocks)
  611. {:key :block/insert
  612. :data (map (fn [block] (assoc block :block/page page)) blocks)}
  613. files)
  614. (state/set-editor-op! nil))]
  615. ;; Replace with batch transactions
  616. (state/add-tx! transact-fn)
  617. (let [blocks (remove (fn [block]
  618. (nil? (:block/content block))) blocks)
  619. page-blocks-atom (db/get-page-blocks-cache-atom repo (:db/id page))
  620. first-block-id (:block/uuid (first blocks))
  621. [before-part after-part] (and page-blocks-atom
  622. (split-with
  623. #(not= first-block-id (:block/uuid %))
  624. @page-blocks-atom))
  625. after-part (rest after-part)
  626. blocks-container-id (and blocks-container-id
  627. (util/uuid-string? blocks-container-id)
  628. (medley/uuid blocks-container-id))]
  629. ; WORKAROUND: The block won't refresh itself even if the content is empty.
  630. (when edit-self?
  631. (gobj/set input "value" ""))
  632. (when ok-handler
  633. (ok-handler
  634. (if edit-self? (first blocks) (last blocks))))
  635. ;; update page blocks cache if exists
  636. (when page-blocks-atom
  637. (reset! page-blocks-atom (->> (concat before-part blocks after-part)
  638. (remove nil?))))
  639. ;; update block children cache if exists
  640. (when blocks-container-id
  641. (let [blocks-atom (db/get-block-blocks-cache-atom repo blocks-container-id)
  642. [before-part after-part] (and blocks-atom
  643. (split-with
  644. #(not= first-block-id (:block/uuid %))
  645. @blocks-atom))
  646. after-part (rest after-part)]
  647. (and blocks-atom
  648. (reset! blocks-atom (->> (concat before-part blocks after-part)
  649. (remove nil?)))))))))]
  650. (cond
  651. (and (not file) page)
  652. ;; TODO: replace with handler.page/create!
  653. (let [format (name format)
  654. title (string/capitalize (:page/name page))
  655. journal-page? (date/valid-journal-title? title)
  656. path (str
  657. (if journal-page?
  658. config/default-journals-directory
  659. (config/get-pages-directory))
  660. "/"
  661. (if journal-page?
  662. (date/journal-title->default title)
  663. (-> (:page/name page)
  664. (util/page-name-sanity)))
  665. "."
  666. (if (= format "markdown") "md" format))
  667. file-path (str "/" path)
  668. dir (util/get-repo-dir repo)]
  669. (p/let [exists? (fs/file-exists? dir file-path)]
  670. (if exists?
  671. (do (notification/show!
  672. [:p.content
  673. (util/format "File %s already exists!"
  674. file-path)]
  675. :error)
  676. (state/set-editor-op! nil))
  677. ;; create the file
  678. (let [content (util/default-content-with-title format (or
  679. (:page/original-name page)
  680. (:page/name page)))]
  681. (p/let [_ (fs/create-if-not-exists repo dir file-path content)
  682. _ (git-handler/git-add repo path)]
  683. (let [value (block-text-with-time nil format value)]
  684. (file-handler/reset-file! repo path
  685. (str content
  686. value
  687. "\n"
  688. snd-block-text)))
  689. (ui-handler/re-render-root!)
  690. ;; Continue to edit the last block
  691. (let [blocks (db/get-page-blocks repo (:page/name page))
  692. last-block (last blocks)]
  693. (edit-last-block-for-new-page! last-block 0))
  694. (state/set-editor-op! nil))))))
  695. file
  696. (let [file-path (:file/path file)
  697. file-content (db/get-file repo file-path)]
  698. (insert-block block file-path file-content))
  699. :else
  700. nil)))
  701. (defn clear-when-saved!
  702. []
  703. (state/set-editor-show-input! nil)
  704. (state/set-editor-show-date-picker! false)
  705. (state/set-editor-show-page-search! false)
  706. (state/set-editor-show-block-search! false)
  707. (state/set-editor-show-template-search! false)
  708. (commands/restore-state true))
  709. (defn get-state
  710. [state]
  711. (let [[{:keys [on-hide block block-id block-parent-id dummy? format sidebar?]} id config] (:rum/args state)
  712. node (gdom/getElement id)
  713. value (gobj/get node "value")
  714. pos (gobj/get node "selectionStart")]
  715. {:config config
  716. :on-hide on-hide
  717. :dummy? dummy?
  718. :sidebar? sidebar?
  719. :format format
  720. :id id
  721. :block block
  722. :block-id block-id
  723. :block-parent-id block-parent-id
  724. :node node
  725. :value value
  726. :pos pos}))
  727. (defn- with-timetracking-properties
  728. [block value]
  729. (let [new-marker (first (re-find format/bare-marker-pattern (or value "")))
  730. new-marker (if new-marker (string/lower-case (string/trim new-marker)))]
  731. (if (and
  732. new-marker
  733. (not= new-marker (string/lower-case (or (:block/marker block) "")))
  734. (state/enable-timetracking?))
  735. {new-marker (util/time-ms)}
  736. {})))
  737. (defn insert-new-block!
  738. [state]
  739. (when (and (not config/publishing?)
  740. ;; skip this operation if it's inserting
  741. (not= :insert (state/get-editor-op)))
  742. (state/set-editor-op! :insert)
  743. (let [{:keys [block value format id config]} (get-state state)
  744. block-id (:block/uuid block)
  745. block (or (db/pull [:block/uuid block-id])
  746. block)
  747. collapsed? (:block/collapsed? block)
  748. repo (or (:block/repo block) (state/get-current-repo))
  749. last-child (and collapsed?
  750. (last (db/get-block-and-children-no-cache repo (:block/uuid block))))
  751. last-child (when (not= (:block/uuid last-child)
  752. (:block/uuid block))
  753. last-child)
  754. new-block (or last-child block)
  755. new-value (if last-child (:block/content last-child) value)
  756. properties (with-timetracking-properties new-block new-value)]
  757. ;; save the current block and insert a new block
  758. (insert-new-block-aux!
  759. (assoc new-block :block/properties properties)
  760. new-value
  761. {:create-new-block? true
  762. :ok-handler
  763. (fn [last-block]
  764. (let [last-id (:block/uuid last-block)]
  765. (edit-block! last-block 0 format id)
  766. (clear-when-saved!)))
  767. :with-level? (if last-child true false)
  768. :new-level (and last-child (:block/level block))
  769. :blocks-container-id (:id config)
  770. :current-page (state/get-current-page)}))))
  771. (defn insert-new-block-without-save-previous!
  772. [config last-block]
  773. (let [format (:block/format last-block)
  774. id (:id config)
  775. new-level (if (util/uuid-string? id)
  776. (inc (:block/level (db/entity [:block/uuid (medley/uuid id)])))
  777. 2)]
  778. (insert-new-block-aux!
  779. last-block
  780. (:block/content last-block)
  781. {:create-new-block? true
  782. :ok-handler
  783. (fn [last-block]
  784. (js/setTimeout #(edit-last-block-for-new-page! last-block :max) 50))
  785. :with-level? true
  786. :new-level new-level
  787. :blocks-container-id (:id config)
  788. :current-page (state/get-current-page)})))
  789. (defn update-timestamps-content!
  790. [{:block/keys [repeated? scheduled-ast deadline-ast marker]} content]
  791. (if repeated?
  792. (let [content (some->> (filter repeated/repeated? [scheduled-ast deadline-ast])
  793. (map (fn [ts]
  794. [(repeated/timestamp->text ts)
  795. (repeated/next-timestamp-text ts)]))
  796. (reduce (fn [content [old new]]
  797. (string/replace content old new))
  798. content))]
  799. (when content
  800. (str (string/trimr content)
  801. "\n"
  802. (util/format "- %s -> DONE [%s]"
  803. marker
  804. (date/get-local-date-time-string)))))
  805. content))
  806. (defn- with-marker-time
  807. [block marker]
  808. (if (state/enable-timetracking?)
  809. (let [marker (string/lower-case marker)]
  810. {marker (util/time-ms)})
  811. {}))
  812. (defn check
  813. [{:block/keys [uuid marker content meta file dummy? repeated?] :as block}]
  814. (let [new-content (string/replace-first content marker "DONE")
  815. new-content (if repeated?
  816. (update-timestamps-content! block content)
  817. new-content)]
  818. (save-block-if-changed! block new-content
  819. {:custom-properties (with-marker-time block "DONE")})))
  820. (defn uncheck
  821. [{:block/keys [uuid marker content meta file dummy?] :as block}]
  822. (let [marker (if (= :now (state/get-preferred-workflow))
  823. "LATER"
  824. "TODO")
  825. new-content (string/replace-first content "DONE" marker)]
  826. (save-block-if-changed! block new-content
  827. {:custom-properties (with-marker-time block marker)})))
  828. (defn cycle-todo!
  829. []
  830. (when-let [block (state/get-edit-block)]
  831. (let [edit-input-id (state/get-edit-input-id)
  832. current-input (gdom/getElement edit-input-id)
  833. content (state/get-edit-content)
  834. [new-content marker] (cond
  835. (util/starts-with? content "TODO")
  836. [(string/replace-first content "TODO" "DOING") "DOING"]
  837. (util/starts-with? content "DOING")
  838. [(string/replace-first content "DOING" "DONE") "DONE"]
  839. (util/starts-with? content "LATER")
  840. [(string/replace-first content "LATER" "NOW") "NOW"]
  841. (util/starts-with? content "NOW")
  842. [(string/replace-first content "NOW" "DONE") "DONE"]
  843. (util/starts-with? content "DONE")
  844. [(string/replace-first content "DONE" "") nil]
  845. :else
  846. (let [marker (if (= :now (state/get-preferred-workflow))
  847. "LATER"
  848. "TODO")]
  849. [(str marker " " (string/triml content)) marker]))
  850. new-content (string/triml new-content)]
  851. (let [new-pos (commands/compute-pos-delta-when-change-marker
  852. current-input content new-content marker (util/get-input-pos current-input))]
  853. (state/set-edit-content! edit-input-id new-content)
  854. (util/set-caret-pos! current-input new-pos)))))
  855. (defn set-marker
  856. [{:block/keys [uuid marker content meta file dummy? properties] :as block} new-marker]
  857. (let [new-content (string/replace-first content marker new-marker)]
  858. (save-block-if-changed! block new-content
  859. (with-marker-time block marker))))
  860. (defn set-priority
  861. [{:block/keys [uuid marker priority content meta file dummy?] :as block} new-priority]
  862. (let [new-content (string/replace-first content
  863. (util/format "[#%s]" priority)
  864. (util/format "[#%s]" new-priority))]
  865. (save-block-if-changed! block new-content)))
  866. (defn- get-prev-block-non-collapsed
  867. [block]
  868. (let [id (gobj/get block "id")
  869. prefix (re-find #"ls-block-[\d]+" id)]
  870. (when-let [blocks (d/by-class "ls-block")]
  871. (when-let [index (.indexOf blocks block)]
  872. (loop [idx (dec index)]
  873. (when (>= idx 0)
  874. (let [block (nth blocks idx)
  875. collapsed? (= "none" (d/style block "display"))
  876. prefix-match? (util/starts-with? (gobj/get block "id") prefix)]
  877. (if (or collapsed?
  878. ;; might be embed blocks
  879. (not prefix-match?))
  880. (recur (dec idx))
  881. block))))))))
  882. (defn- get-next-block-non-collapsed
  883. [block]
  884. (let [id (gobj/get block "id")
  885. prefix (re-find #"ls-block-[\d]+" id)]
  886. (when-let [blocks (d/by-class "ls-block")]
  887. (when-let [index (.indexOf blocks block)]
  888. (loop [idx (inc index)]
  889. (when (>= (count blocks) idx)
  890. (when-let [block (util/nth-safe blocks idx)]
  891. (let [collapsed? (= "none" (d/style block "display"))
  892. prefix-match? (util/starts-with? (gobj/get block "id") prefix)]
  893. (if (or collapsed?
  894. ;; might be embed blocks
  895. (not prefix-match?))
  896. (recur (inc idx))
  897. block)))))))))
  898. (defn delete-block-aux!
  899. [{:block/keys [uuid meta content file repo ref-pages ref-blocks] :as block} dummy?]
  900. (when-not dummy?
  901. (let [repo (or repo (state/get-current-repo))
  902. block (db/pull repo '[*] [:block/uuid uuid])]
  903. (when block
  904. (let [file-path (:file/path (db/entity repo (:db/id file)))
  905. file-content (db/get-file repo file-path)
  906. after-blocks (rebuild-after-blocks repo file (:end-pos meta) (:start-pos meta))
  907. new-content (utf8/delete! file-content (:start-pos meta) (:end-pos meta))]
  908. (repo-handler/transact-react-and-alter-file!
  909. repo
  910. (concat
  911. [[:db.fn/retractEntity [:block/uuid uuid]]]
  912. after-blocks)
  913. {:key :block/change
  914. :data [block]}
  915. [[file-path new-content]])
  916. (when (or (seq ref-pages) (seq ref-blocks))
  917. (ui-handler/re-render-root!)))))))
  918. (defn delete-block!
  919. [state repo e]
  920. (let [{:keys [id block-id block-parent-id dummy? value pos format]} (get-state state)]
  921. (when (and block-id
  922. (not= :block/delete (state/get-editor-op)))
  923. (state/set-editor-op! :block/delete)
  924. (let [page-id (:db/id (:block/page (db/entity [:block/uuid block-id])))
  925. page-blocks-count (and page-id (db/get-page-blocks-count repo page-id))
  926. page (and page-id (db/entity page-id))]
  927. (if (> page-blocks-count 1)
  928. (do
  929. (util/stop e)
  930. ;; delete block, edit previous block
  931. (let [block (db/pull [:block/uuid block-id])
  932. block-parent (gdom/getElement block-parent-id)
  933. sibling-block (get-prev-block-non-collapsed block-parent)]
  934. (delete-block-aux! block dummy?)
  935. (when (and repo sibling-block)
  936. (when-let [sibling-block-id (d/attr sibling-block "blockid")]
  937. (when-let [block (db/pull repo '[*] [:block/uuid (uuid sibling-block-id)])]
  938. (let [original-content (util/trim-safe (:block/content block))
  939. new-value (str original-content " " (string/triml value))
  940. tail-len (count (string/triml value))
  941. pos (max
  942. (if original-content
  943. (utf8/length (utf8/encode (text/remove-level-spaces original-content format)))
  944. 0)
  945. 0)]
  946. (edit-block! block pos format id
  947. {:custom-content new-value
  948. :tail-len tail-len})))))))))
  949. (state/set-editor-op! nil))))
  950. (defn delete-blocks!
  951. [repo block-uuids]
  952. (when (seq block-uuids)
  953. (let [current-page (state/get-current-page)
  954. top-block-id (and current-page
  955. (util/uuid-string? current-page)
  956. (medley/uuid current-page))
  957. top-block? (and top-block-id
  958. (= top-block-id (first block-uuids)))]
  959. (let [blocks (db/pull-many repo '[*] (mapv (fn [id]
  960. [:block/uuid id])
  961. block-uuids))
  962. page (db/entity repo (:db/id (:block/page (first blocks))))
  963. first-block (first blocks)
  964. last-block (last blocks)
  965. file (db/entity repo (:db/id (:block/file first-block)))
  966. file-path (:file/path file)
  967. file-content (db/get-file repo file-path)
  968. start-pos (:start-pos (:block/meta first-block))
  969. end-pos (:end-pos (:block/meta last-block))
  970. after-blocks (rebuild-after-blocks repo file end-pos start-pos)
  971. new-content (utf8/delete! file-content start-pos end-pos)
  972. retract-blocks-tx (mapv
  973. (fn [uuid]
  974. [:db.fn/retractEntity [:block/uuid uuid]])
  975. block-uuids)
  976. tx-data (concat
  977. retract-blocks-tx
  978. after-blocks
  979. [{:file/path file-path}])]
  980. (repo-handler/transact-react-and-alter-file!
  981. repo
  982. tx-data
  983. {:key :block/change
  984. :data blocks}
  985. [[file-path new-content]])
  986. (when top-block?
  987. (route-handler/redirect! {:to :page
  988. :path-params {:name (:page/name page)}})
  989. (ui-handler/re-render-root!))
  990. (repo-handler/push-if-auto-enabled! repo)))))
  991. (defn remove-block-property!
  992. [block-id key]
  993. (let [block-id (if (string? block-id) (uuid block-id) block-id)
  994. key (string/lower-case (str key))]
  995. (when-let [block (db/pull [:block/uuid block-id])]
  996. (let [{:block/keys [content properties]} block]
  997. (when (get properties key)
  998. (save-block-if-changed! block content
  999. {:remove-properties [key]}))))))
  1000. (defn set-block-property!
  1001. [block-id key value]
  1002. (let [block-id (if (string? block-id) (uuid block-id) block-id)
  1003. key (string/lower-case (str key))
  1004. value (str value)]
  1005. (when-let [block (db/pull [:block/uuid block-id])]
  1006. (when-not (:block/pre-block? block)
  1007. (let [{:block/keys [content properties]} block]
  1008. (cond
  1009. (and (get properties key)
  1010. (= (string/trim (get properties key)) value))
  1011. nil
  1012. :else
  1013. (save-block-if-changed! block content
  1014. {:custom-properties {key value}
  1015. :rebuild-content? false})))))))
  1016. (defn set-block-timestamp!
  1017. [block-id key value]
  1018. (let [key (string/lower-case key)
  1019. scheduled? (= key "scheduled")
  1020. deadline? (= key "deadline")
  1021. block-id (if (string? block-id) (uuid block-id) block-id)
  1022. key (string/lower-case (str key))
  1023. value (str value)]
  1024. (when-let [block (db/pull [:block/uuid block-id])]
  1025. (let [{:block/keys [content scheduled deadline format]} block
  1026. content (or (when-let [edit-content (state/get-edit-content)]
  1027. (block/with-levels edit-content format block))
  1028. content)
  1029. new-line (str (string/upper-case key) ": " value)
  1030. new-content (cond
  1031. ;; update
  1032. (or
  1033. (and deadline deadline?)
  1034. (and scheduled scheduled?))
  1035. (let [lines (string/split-lines content)
  1036. body (map (fn [line]
  1037. (if (string/starts-with? (string/lower-case line) key)
  1038. new-line
  1039. line))
  1040. (rest lines))]
  1041. (->> (cons (first lines) body)
  1042. (string/join "\n")))
  1043. ;; insert
  1044. (or deadline? scheduled?)
  1045. (let [[title body] (if (string/includes? content "\n")
  1046. (util/split-first "\n" content)
  1047. [content ""])]
  1048. (str title "\n"
  1049. new-line
  1050. "\n" (util/trim-only-newlines body)))
  1051. :else
  1052. content)]
  1053. (when (not= content new-content)
  1054. (if-let [input-id (state/get-edit-input-id)]
  1055. (state/set-edit-content! input-id new-content)
  1056. (save-block-if-changed! block new-content)))))))
  1057. (defn copy-block-ref!
  1058. ([block-id] (copy-block-ref! block-id #(str %)))
  1059. ([block-id tap-clipboard]
  1060. (let [block (db/entity [:block/uuid block-id])]
  1061. (when-not (:block/pre-block? block)
  1062. (set-block-property! block-id "id" (str block-id))))
  1063. (util/copy-to-clipboard! (tap-clipboard block-id))))
  1064. (defn clear-selection!
  1065. [_e]
  1066. (when (state/in-selection-mode?)
  1067. (doseq [block (state/get-selection-blocks)]
  1068. (dom/remove-class! block "selected")
  1069. (dom/remove-class! block "noselect"))
  1070. (state/clear-selection!)))
  1071. (defn clear-selection-blocks!
  1072. []
  1073. (when (state/in-selection-mode?)
  1074. (doseq [block (state/get-selection-blocks)]
  1075. (dom/remove-class! block "selected")
  1076. (dom/remove-class! block "noselect"))
  1077. (state/clear-selection-blocks!)))
  1078. (defn exit-editing-and-set-selected-blocks!
  1079. [blocks]
  1080. (util/clear-selection!)
  1081. (state/clear-edit!)
  1082. (state/set-selection-blocks! blocks))
  1083. (defn select-all-blocks!
  1084. []
  1085. (when-let [current-input-id (state/get-edit-input-id)]
  1086. (let [input (gdom/getElement current-input-id)
  1087. blocks-container (util/rec-get-blocks-container input)
  1088. blocks (dom/by-class blocks-container "ls-block")]
  1089. (doseq [block blocks]
  1090. (dom/add-class! block "selected noselect"))
  1091. (exit-editing-and-set-selected-blocks! blocks))))
  1092. (defn- get-selected-blocks-with-children
  1093. []
  1094. (when-let [blocks (seq (get @state/state :selection/blocks))]
  1095. (mapcat (fn [block]
  1096. (cons block
  1097. (array-seq (dom/by-class block "ls-block"))))
  1098. blocks)))
  1099. (defn copy-selection-blocks
  1100. []
  1101. (when-let [blocks (seq (get-selected-blocks-with-children))]
  1102. (let [repo (dom/attr (first blocks) "repo")
  1103. ids (->> (distinct (map #(when-let [id (dom/attr % "blockid")]
  1104. (uuid id)) blocks))
  1105. (remove nil?))
  1106. up? (state/selection-up?)
  1107. content (some->> (db/get-blocks-contents repo ids)
  1108. (map :block/content))
  1109. content (if (false? up?) (reverse content) content)
  1110. content (string/join "" content)]
  1111. (when-not (string/blank? content)
  1112. (common-handler/copy-to-clipboard-without-id-property! content)))))
  1113. (defn cut-selection-blocks
  1114. []
  1115. (copy-selection-blocks)
  1116. (when-let [blocks (seq (get-selected-blocks-with-children))]
  1117. (let [repo (dom/attr (first blocks) "repo")
  1118. ids (distinct (map #(uuid (dom/attr % "blockid")) blocks))]
  1119. (delete-blocks! repo ids))))
  1120. (defn- get-nearest-page
  1121. []
  1122. (when-let [block (state/get-edit-block)]
  1123. (when-let [id (:block/uuid block)]
  1124. (when-let [edit-id (state/get-edit-input-id)]
  1125. (when-let [input (gdom/getElement edit-id)]
  1126. (when-let [pos (util/get-input-pos input)]
  1127. (let [value (gobj/get input "value")
  1128. page-pattern #"\[\[([^\]]+)]]"
  1129. block-pattern #"\(\(([^\)]+)\)\)"
  1130. page-matches (util/re-pos page-pattern value)
  1131. block-matches (util/re-pos block-pattern value)
  1132. matches (->> (concat page-matches block-matches)
  1133. (remove nil?))
  1134. [_ page] (first (sort-by
  1135. (fn [[start-pos content]]
  1136. (let [end-pos (+ start-pos (count content))]
  1137. (cond
  1138. (< pos start-pos)
  1139. (- pos start-pos)
  1140. (> pos end-pos)
  1141. (- end-pos pos)
  1142. :else
  1143. 0)))
  1144. >
  1145. matches))]
  1146. (when page
  1147. (subs page 2 (- (count page) 2))))))))))
  1148. (defn follow-link-under-cursor!
  1149. []
  1150. (when-let [page (get-nearest-page)]
  1151. (let [page-name (string/lower-case page)]
  1152. (state/clear-edit!)
  1153. (route-handler/redirect! {:to :page
  1154. :path-params {:name page-name}}))))
  1155. (defn open-link-in-sidebar!
  1156. []
  1157. (when-let [page (get-nearest-page)]
  1158. (let [page-name (string/lower-case page)
  1159. block? (util/uuid-string? page-name)]
  1160. (when-let [page (db/get-page page-name)]
  1161. (if block?
  1162. (state/sidebar-add-block!
  1163. (state/get-current-repo)
  1164. (:db/id page)
  1165. :block
  1166. page)
  1167. (state/sidebar-add-block!
  1168. (state/get-current-repo)
  1169. (:db/id page)
  1170. :page
  1171. {:page page}))))))
  1172. (defn zoom-in! []
  1173. (if-let [block (state/get-edit-block)]
  1174. (when-let [id (:block/uuid block)]
  1175. (route-handler/redirect! {:to :page
  1176. :path-params {:name (str id)}}))
  1177. (js/window.history.forward)))
  1178. (defn zoom-out! []
  1179. (let [page (state/get-current-page)
  1180. block-id (and
  1181. (string? page)
  1182. (util/uuid-string? page)
  1183. (medley/uuid page))]
  1184. (if block-id
  1185. (let [repo (state/get-current-repo)
  1186. block-parent (db/get-block-parent repo block-id)]
  1187. (if-let [id (:block/uuid block-parent)]
  1188. (route-handler/redirect! {:to :page
  1189. :path-params {:name (str id)}})
  1190. (let [page-id (-> (db/entity [:block/uuid block-id])
  1191. :block/page
  1192. :db/id)]
  1193. (when-let [page-name (:page/name (db/entity repo page-id))]
  1194. (route-handler/redirect! {:to :page
  1195. :path-params {:name page-name}})))))
  1196. (js/window.history.back))))
  1197. (defn cut-block!
  1198. [block-id]
  1199. (when-let [block (db/pull [:block/uuid block-id])]
  1200. (let [content (:block/content block)]
  1201. (common-handler/copy-to-clipboard-without-id-property! content)
  1202. (delete-block-aux! block false))))
  1203. (defonce select-start-block-state (atom nil))
  1204. (defn clear-last-selected-block!
  1205. []
  1206. (let [first-block (state/pop-selection-block!)]
  1207. (dom/remove-class! first-block "selected")
  1208. (dom/remove-class! first-block "noselect")))
  1209. (defn input-start-or-end?
  1210. ([input]
  1211. (input-start-or-end? input nil))
  1212. ([input up?]
  1213. (let [value (gobj/get input "value")
  1214. start (gobj/get input "selectionStart")
  1215. end (gobj/get input "selectionEnd")]
  1216. (if (nil? up?)
  1217. (or (= start 0) (= end (count value)))
  1218. (or (and (= start 0) up?)
  1219. (and (= end (count value)) (not up?)))))))
  1220. (defn highlight-selection-area!
  1221. [end-block]
  1222. (when-let [start-block (:selection/start-block @state/state)]
  1223. (clear-selection-blocks!)
  1224. (let [blocks (util/get-nodes-between-two-nodes start-block end-block "ls-block")]
  1225. (doseq [block blocks]
  1226. (dom/add-class! block "selected noselect"))
  1227. (exit-editing-and-set-selected-blocks! blocks))))
  1228. (defn on-select-block
  1229. [state e up?]
  1230. (when (and
  1231. (gobj/get e "shiftKey")
  1232. (not (gobj/get e "altKey"))
  1233. (or (state/in-selection-mode?)
  1234. (when-let [input-id (state/get-edit-input-id)]
  1235. (when-let [input (gdom/getElement input-id)]
  1236. (input-start-or-end? input up?)))))
  1237. (state/clear-edit!)
  1238. (let [{:keys [id block-id block block-parent-id dummy? value pos format] :as block-state} @select-start-block-state
  1239. element (gdom/getElement block-parent-id)
  1240. selected-blocks (state/get-selection-blocks)
  1241. selected-blocks-count (count selected-blocks)
  1242. first-block (first selected-blocks)
  1243. selection-up? (state/selection-up?)]
  1244. (when block-id
  1245. (util/stop e)
  1246. (when-let [element (if-not (state/in-selection-mode?)
  1247. element
  1248. (let [f (if up? util/get-prev-block util/get-next-block)]
  1249. (f first-block)))]
  1250. (if (and (not (nil? selection-up?)) (not= up? selection-up?))
  1251. (cond
  1252. (>= selected-blocks-count 2) ; back to the start block
  1253. (do
  1254. (when (= 2 selected-blocks-count) (state/set-selection-up! nil))
  1255. (clear-last-selected-block!))
  1256. :else
  1257. nil)
  1258. (do
  1259. (util/clear-selection!)
  1260. (state/clear-edit!)
  1261. (state/conj-selection-block! element up?))))))))
  1262. (defn save-block-aux!
  1263. [block value format]
  1264. (let [value (text/remove-level-spaces value format true)
  1265. new-value (block/with-levels value format block)
  1266. properties (with-timetracking-properties block value)]
  1267. ;; FIXME: somehow frontend.components.editor's will-unmount event will loop forever
  1268. ;; maybe we shouldn't save the block/file in "will-unmount" event?
  1269. (save-block-if-changed! block new-value
  1270. {:custom-properties properties})))
  1271. (defn save-block!
  1272. [{:keys [format block id repo dummy?] :as state} value]
  1273. (when (or (:db/id (db/entity repo [:block/uuid (:block/uuid block)]))
  1274. dummy?)
  1275. (save-block-aux! block value format)))
  1276. (defn save-current-block-when-idle!
  1277. []
  1278. (when-let [repo (state/get-current-repo)]
  1279. (when (and (state/input-idle? repo)
  1280. (not (state/get-editor-show-page-search?))
  1281. (not (state/get-editor-show-page-search-hashtag?))
  1282. (not (state/get-editor-show-block-search?)))
  1283. (state/set-editor-op! :auto-save)
  1284. (try
  1285. (let [input-id (state/get-edit-input-id)
  1286. block (state/get-edit-block)
  1287. db-block (when-let [block-id (:block/uuid block)]
  1288. (db/pull [:block/uuid block-id]))
  1289. elem (and input-id (gdom/getElement input-id))
  1290. db-content (:block/content db-block)
  1291. db-content-without-heading (and db-content
  1292. (util/safe-subs db-content (:block/level db-block)))
  1293. value (and elem (gobj/get elem "value"))]
  1294. (when (and block value db-content-without-heading
  1295. (or
  1296. (not= (string/trim db-content-without-heading)
  1297. (string/trim value))))
  1298. (let [cur-pos (util/get-input-pos elem)]
  1299. (save-block-aux! db-block value (:block/format db-block))
  1300. ;; Restore the cursor after saving the block
  1301. (when (and elem cur-pos)
  1302. (util/set-caret-pos! elem cur-pos)))))
  1303. (catch js/Error error
  1304. (log/error :save-block-failed error)))
  1305. (state/set-editor-op! nil))))
  1306. (defn on-up-down
  1307. [state e up?]
  1308. (let [{:keys [id block-id block block-parent-id dummy? value pos format] :as block-state} (get-state state)]
  1309. (if (gobj/get e "shiftKey")
  1310. (reset! select-start-block-state block-state)
  1311. (let [element (gdom/getElement id)
  1312. line-height (util/get-textarea-line-height element)]
  1313. (when (and block-id
  1314. (or (and up? (util/textarea-cursor-first-row? element line-height))
  1315. (and (not up?) (util/textarea-cursor-end-row? element line-height))))
  1316. (util/stop e)
  1317. (let [f (if up? get-prev-block-non-collapsed get-next-block-non-collapsed)
  1318. sibling-block (f (gdom/getElement block-parent-id))]
  1319. (when sibling-block
  1320. (when-let [sibling-block-id (d/attr sibling-block "blockid")]
  1321. (let [state (get-state state)
  1322. content (:block/content block)
  1323. value (:value state)]
  1324. (when (not= (-> content
  1325. (text/remove-level-spaces format)
  1326. text/remove-properties!
  1327. string/trim)
  1328. (string/trim value))
  1329. (save-block! state (:value state))))
  1330. (let [block (db/pull (state/get-current-repo) '[*] [:block/uuid (uuid sibling-block-id)])]
  1331. (edit-block! block pos format id))))))))))
  1332. (defn insert-command!
  1333. [id command-output format {:keys [restore?]
  1334. :or {restore? true}
  1335. :as option}]
  1336. (cond
  1337. ;; replace string
  1338. (string? command-output)
  1339. (commands/insert! id command-output option)
  1340. ;; steps
  1341. (vector? command-output)
  1342. (commands/handle-steps command-output format)
  1343. (fn? command-output)
  1344. (let [s (command-output)]
  1345. (commands/insert! id s option))
  1346. :else
  1347. nil)
  1348. (when restore?
  1349. (let [restore-slash-caret-pos? (if (and
  1350. (seq? command-output)
  1351. (= :editor/click-hidden-file-input
  1352. (ffirst command-output)))
  1353. false
  1354. true)]
  1355. (commands/restore-state restore-slash-caret-pos?))))
  1356. (defn- get-image-link
  1357. [format url file-name]
  1358. (case (keyword format)
  1359. :markdown (util/format "![%s](%s)" file-name url)
  1360. :org (util/format "[[%s][%s]]" url file-name)
  1361. nil))
  1362. (defn upload-image
  1363. [id files format uploading? drop?]
  1364. (image/upload
  1365. files
  1366. (fn [file file-name file-type]
  1367. (image-handler/request-presigned-url
  1368. file file-name file-type
  1369. uploading?
  1370. (fn [signed-url]
  1371. (insert-command! id
  1372. (get-image-link format signed-url file-name)
  1373. format
  1374. {:last-pattern (if drop? "" commands/slash)
  1375. :restore? true})
  1376. (reset! *image-uploading-process 0))
  1377. (fn [e]
  1378. (let [process (* (/ (gobj/get e "loaded")
  1379. (gobj/get e "total"))
  1380. 100)]
  1381. (reset! *image-uploading-process process)))))))
  1382. ;; Editor should track some useful information, like editor modes.
  1383. ;; For example:
  1384. ;; 1. Which file format is it, markdown or org mode?
  1385. ;; 2. Is it in the properties area? Then we can enable the ":" autopair
  1386. (def autopair-map
  1387. {"[" "]"
  1388. "{" "}"
  1389. "(" ")"
  1390. "`" "`"
  1391. "~" "~"
  1392. "*" "*"
  1393. ;; "_" "_"
  1394. ;; ":" ":" ; TODO: only properties editing and org mode tag
  1395. ;; "^" "^"
  1396. })
  1397. (def reversed-autopair-map
  1398. (zipmap (vals autopair-map)
  1399. (keys autopair-map)))
  1400. (def delete-map
  1401. (assoc autopair-map
  1402. "$" "$"
  1403. ":" ":"))
  1404. (def reversed-delete-map
  1405. (zipmap (vals delete-map)
  1406. (keys delete-map)))
  1407. (defn autopair
  1408. [input-id prefix format {:keys [restore?]
  1409. :or {restore? true}
  1410. :as option}]
  1411. (let [value (get autopair-map prefix)
  1412. selected (util/get-selected-text)
  1413. postfix (str selected value)
  1414. value (str prefix postfix)
  1415. input (gdom/getElement input-id)]
  1416. (when value
  1417. (when-not (string/blank? selected) (reset! *selected-text selected))
  1418. (let [[prefix pos] (commands/simple-replace! input-id value selected
  1419. {:backward-pos (count postfix)
  1420. :check-fn (fn [new-value prefix-pos]
  1421. (when (>= prefix-pos 0)
  1422. [(subs new-value prefix-pos (+ prefix-pos 2))
  1423. (+ prefix-pos 2)]))})]
  1424. (case prefix
  1425. "[["
  1426. (do
  1427. (commands/handle-step [:editor/search-page])
  1428. (reset! commands/*slash-caret-pos (util/get-caret-pos input)))
  1429. "(("
  1430. (do
  1431. (commands/handle-step [:editor/search-block :reference])
  1432. (reset! commands/*slash-caret-pos (util/get-caret-pos input)))
  1433. nil)))))
  1434. (defn surround-by?
  1435. [input before after]
  1436. (when input
  1437. (let [value (gobj/get input "value")
  1438. pos (util/get-input-pos input)
  1439. start-pos (if (= :start before) 0 (- pos (count before)))
  1440. end-pos (if (= :end after) (count value) (+ pos (count after)))]
  1441. (when (>= (count value) end-pos)
  1442. (= (cond
  1443. (and (= :end after) (= :start before))
  1444. ""
  1445. (= :end after)
  1446. before
  1447. (= :start before)
  1448. after
  1449. :else
  1450. (str before after))
  1451. (subs value start-pos end-pos))))))
  1452. (defn get-matched-pages
  1453. [q]
  1454. (let [block (state/get-edit-block)
  1455. editing-page (and block
  1456. (when-let [page-id (:db/id (:block/page block))]
  1457. (:page/name (db/entity page-id))))]
  1458. (let [pages (search/page-search q 20)]
  1459. (if editing-page
  1460. ;; To prevent self references
  1461. (remove (fn [p] (= (string/lower-case p) editing-page)) pages)
  1462. pages))))
  1463. (defn get-matched-blocks
  1464. [q]
  1465. ;; remove current block
  1466. (let [current-block (state/get-edit-block)]
  1467. (remove
  1468. (fn [h]
  1469. (= (:block/uuid current-block)
  1470. (:block/uuid h)))
  1471. (search/search q 10))))
  1472. (defn get-matched-templates
  1473. [q]
  1474. (search/template-search q))
  1475. (defn get-matched-commands
  1476. [input]
  1477. (try
  1478. (let [edit-content (gobj/get input "value")
  1479. pos (util/get-input-pos input)
  1480. last-slash-caret-pos (:pos @*slash-caret-pos)
  1481. last-command (and last-slash-caret-pos (subs edit-content last-slash-caret-pos pos))]
  1482. (when (> pos 0)
  1483. (or
  1484. (and (= \/ (util/nth-safe edit-content (dec pos)))
  1485. @commands/*initial-commands)
  1486. (and last-command
  1487. (commands/get-matched-commands last-command)))))
  1488. (catch js/Error e
  1489. nil)))
  1490. (defn get-matched-block-commands
  1491. [input]
  1492. (try
  1493. (let [edit-content (gobj/get input "value")
  1494. pos (util/get-input-pos input)
  1495. last-command (subs edit-content
  1496. (:pos @*angle-bracket-caret-pos)
  1497. pos)]
  1498. (when (> pos 0)
  1499. (or
  1500. (and (= \< (util/nth-safe edit-content (dec pos)))
  1501. (commands/block-commands-map))
  1502. (and last-command
  1503. (commands/get-matched-commands
  1504. last-command
  1505. (commands/block-commands-map))))))
  1506. (catch js/Error e
  1507. nil)))
  1508. (defn in-auto-complete?
  1509. [input]
  1510. (or @*show-commands
  1511. @*show-block-commands
  1512. (state/get-editor-show-input)
  1513. (state/get-editor-show-page-search?)
  1514. (state/get-editor-show-block-search?)
  1515. (state/get-editor-show-template-search?)
  1516. (state/get-editor-show-date-picker?)))
  1517. (defn get-previous-input-char
  1518. [input]
  1519. (when-let [pos (util/get-input-pos input)]
  1520. (let [value (gobj/get input "value")]
  1521. (when (and (>= (count value) pos)
  1522. (>= pos 1))
  1523. (util/nth-safe value (- pos 1))))))
  1524. (defn get-previous-input-chars
  1525. [input length]
  1526. (when-let [pos (util/get-input-pos input)]
  1527. (let [value (gobj/get input "value")]
  1528. (when (and (>= (count value) pos)
  1529. (>= pos 1))
  1530. (subs value (- pos length) pos)))))
  1531. (defn get-current-input-char
  1532. [input]
  1533. (when-let [pos (util/get-input-pos input)]
  1534. (let [value (gobj/get input "value")]
  1535. (when (and (>= (count value) (inc pos))
  1536. (>= pos 1))
  1537. (util/nth-safe value pos)))))
  1538. (defn- get-previous-block-level
  1539. [current-id]
  1540. (when-let [input (gdom/getElement current-id)]
  1541. (when-let [prev-block (util/get-prev-block input)]
  1542. (util/parse-int (d/attr prev-block "level")))))
  1543. ;; If it's an indent/outdent action followed by an "Enter", only adjust after inserting a block was finished. Maybe we should use a channel to serialize all the events.
  1544. (defn adjust-block-level!
  1545. ([state direction]
  1546. (adjust-block-level! state direction 100))
  1547. ([state direction retry-limit]
  1548. (if (= :insert (state/get-editor-op))
  1549. (if (> retry-limit 0)
  1550. (js/setTimeout #(adjust-block-level! state direction (dec retry-limit)) 20)
  1551. (log/error :editor/indent-outdent-retry-max-limit {:direction direction}))
  1552. (do
  1553. (state/set-editor-op! :indent-outdent)
  1554. (let [{:keys [block block-parent-id value config]} (get-state state)
  1555. start-level (:start-level config)
  1556. format (:block/format block)
  1557. level (:block/level block)
  1558. previous-level (or (get-previous-block-level block-parent-id) 1)
  1559. [add? remove?] (case direction
  1560. :left [false true]
  1561. :right [true false]
  1562. [(<= level previous-level)
  1563. (and (> level previous-level)
  1564. (> level 2))])
  1565. final-level (cond
  1566. add? (inc level)
  1567. remove? (if (> level 2)
  1568. (dec level)
  1569. level)
  1570. :else level)
  1571. new-value (block/with-levels value format (assoc block :block/level final-level))]
  1572. (when (and
  1573. (not (and (= direction :left)
  1574. (get config :id)
  1575. (util/uuid-string? (get config :id))
  1576. (<= final-level start-level)))
  1577. (<= (- final-level previous-level) 1))
  1578. (save-block-if-changed! block new-value
  1579. {:indent-left? (= direction :left)})))
  1580. (state/set-editor-op! nil)))))
  1581. (defn adjust-blocks-level!
  1582. [blocks direction])
  1583. (defn append-paste-doc!
  1584. [format event]
  1585. (let [[html text] (util/get-clipboard-as-html event)]
  1586. (when-not (util/starts-with? (string/trim text) "http")
  1587. (let [doc-text (html-parser/parse format html)]
  1588. (when-not (string/blank? doc-text)
  1589. (util/stop event)
  1590. (state/append-current-edit-content! doc-text))))))
  1591. (defn- block-and-children-content
  1592. [block-children]
  1593. (-> (map :block/content block-children)
  1594. string/join))
  1595. (defn move-up-down
  1596. [e up?]
  1597. (when-let [block-id (:block/uuid (state/get-edit-block))]
  1598. (let [block-parent-id (state/get-editing-block-dom-id)
  1599. block (db/entity [:block/uuid block-id])
  1600. meta (:block/meta block)
  1601. page (:block/page block)
  1602. block-dom-node (gdom/getElement block-parent-id)
  1603. prev-block (get-prev-block-non-collapsed block-dom-node)
  1604. next-block (get-next-block-non-collapsed block-dom-node)
  1605. repo (state/get-current-repo)
  1606. move-upwards-to-parent? (and up? prev-block (< (d/attr prev-block "level") (:block/level block)))
  1607. move-down-to-higher-level? (and (not up?) next-block (< (d/attr next-block "level") (:block/level block)))]
  1608. (when-let [sibling-block (cond
  1609. move-upwards-to-parent?
  1610. prev-block
  1611. move-down-to-higher-level?
  1612. next-block
  1613. :else
  1614. (let [f (if up? util/get-prev-block-with-same-level util/get-next-block-with-same-level)]
  1615. (f block-dom-node)))]
  1616. (when-let [sibling-block-id (d/attr sibling-block "blockid")]
  1617. (when-let [sibling-block (db/pull-block (medley/uuid sibling-block-id))]
  1618. (let [sibling-meta (:block/meta sibling-block)
  1619. hc1 (db/get-block-and-children-no-cache repo (:block/uuid block))
  1620. hc2 (if (or move-upwards-to-parent? move-down-to-higher-level?)
  1621. [sibling-block]
  1622. (db/get-block-and-children-no-cache repo (:block/uuid sibling-block)))]
  1623. ;; Same page and next to the other
  1624. (when (and
  1625. (= (:db/id (:block/page block))
  1626. (:db/id (:block/page sibling-block)))
  1627. (or
  1628. (and up? (= (:end-pos (:block/meta (last hc2))) (:start-pos (:block/meta (first hc1)))))
  1629. (and (not up?) (= (:end-pos (:block/meta (last hc1))) (:start-pos (:block/meta (first hc2)))))))
  1630. (let [hc1-content (block-and-children-content hc1)
  1631. hc2-content (block-and-children-content hc2)
  1632. file (db/get-block-file (:block/uuid block))
  1633. file-path (:file/path file)
  1634. old-file-content (db/get-file file-path)
  1635. [start-pos end-pos new-content blocks] (if up?
  1636. [(:start-pos sibling-meta)
  1637. (get-in (last hc1) [:block/meta :end-pos])
  1638. (str hc1-content hc2-content)
  1639. (concat hc1 hc2)]
  1640. [(:start-pos meta)
  1641. (get-in (last hc2) [:block/meta :end-pos])
  1642. (str hc2-content hc1-content)
  1643. (concat hc2 hc1)])]
  1644. (when (and start-pos end-pos)
  1645. (let [new-file-content (utf8/insert! old-file-content start-pos end-pos new-content)
  1646. modified-time (modified-time-tx page file)
  1647. blocks-meta (rebuild-blocks-meta start-pos blocks)]
  1648. (profile
  1649. (str "Move block " (if up? "up: " "down: "))
  1650. (repo-handler/transact-react-and-alter-file!
  1651. repo
  1652. (concat
  1653. blocks-meta
  1654. modified-time)
  1655. {:key :block/change
  1656. :data (map (fn [block] (assoc block :block/page page)) blocks)}
  1657. [[file-path new-file-content]])))))))))))))
  1658. (defn expand!
  1659. []
  1660. (when-let [current-block (state/get-edit-block)]
  1661. (expand/expand! current-block)
  1662. (state/set-collapsed-state! (:block/uuid current-block)
  1663. false)))
  1664. (defn collapse!
  1665. []
  1666. (when-let [current-block (state/get-edit-block)]
  1667. (expand/collapse! current-block)
  1668. (state/set-collapsed-state! (:block/uuid current-block)
  1669. true)))
  1670. (defn cycle-collapse!
  1671. [_state e]
  1672. (when (and
  1673. ;; not input, t
  1674. (nil? (state/get-edit-input-id))
  1675. (not (state/get-editor-show-input))
  1676. (string/blank? (:search/q @state/state)))
  1677. (util/stop e)
  1678. (expand/cycle!)))
  1679. (defn on-tab
  1680. [direction]
  1681. (fn [state e]
  1682. (when-let [repo (state/get-current-repo)]
  1683. (let [blocks (seq (state/get-selection-blocks))]
  1684. (cond
  1685. (seq blocks)
  1686. (let [ids (map (fn [block] (when-let [id (dom/attr block "blockid")]
  1687. (medley/uuid id))) blocks)
  1688. ids (->> (mapcat #(let [children (vec (db/get-block-children-ids repo %))]
  1689. (cons % children)) ids)
  1690. (distinct))
  1691. blocks (db/pull-many '[*] (map (fn [id] [:block/uuid id]) ids))
  1692. block (first blocks)
  1693. format (:block/format block)
  1694. start-pos (get-in block [:block/meta :start-pos])
  1695. old-end-pos (get-in (last blocks) [:block/meta :end-pos])
  1696. pattern (config/get-block-pattern format)
  1697. last-start-pos (atom start-pos)
  1698. blocks (doall
  1699. (map (fn [block]
  1700. (let [content (:block/content block)
  1701. level (:block/level block)
  1702. content' (if (= :left direction)
  1703. (subs content 1)
  1704. (str pattern content))
  1705. end-pos (+ @last-start-pos (utf8/length (utf8/encode content')))
  1706. block (assoc block
  1707. :block/content content'
  1708. :block/level (if (= direction :left)
  1709. (dec level)
  1710. (inc level))
  1711. :block/meta (merge
  1712. (:block/meta block)
  1713. {:start-pos @last-start-pos
  1714. :end-pos end-pos}))]
  1715. (reset! last-start-pos end-pos)
  1716. block))
  1717. blocks))
  1718. file-id (:db/id (:block/file block))
  1719. file (db/entity file-id)
  1720. page (:block/page block)
  1721. after-blocks (rebuild-after-blocks repo file old-end-pos @last-start-pos)
  1722. ;; _ (prn {:blocks (map (fn [h] (select-keys h [:block/content :block/meta])) blocks)
  1723. ;; :after-blocks after-blocks
  1724. ;; :last-start-pos @last-start-pos})
  1725. file-path (:file/path file)
  1726. file-content (db/get-file file-path)
  1727. new-content (utf8/insert! file-content start-pos old-end-pos (apply str (map :block/content blocks)))
  1728. modified-time (modified-time-tx page file)]
  1729. (profile
  1730. "Indent/outdent: "
  1731. (repo-handler/transact-react-and-alter-file!
  1732. repo
  1733. (concat
  1734. blocks
  1735. after-blocks
  1736. modified-time)
  1737. {:key :block/change
  1738. :data (map (fn [block] (assoc block :block/page page)) blocks)}
  1739. [[file-path new-content]])))
  1740. (gdom/getElement "date-time-picker")
  1741. nil
  1742. :else
  1743. (cycle-collapse! state e))))))
  1744. (defn bulk-make-todos
  1745. [state e]
  1746. (when-let [repo (state/get-current-repo)]
  1747. (let [blocks (seq (state/get-selection-blocks))]
  1748. (if (seq blocks)
  1749. (let [ids (map (fn [block] (when-let [id (dom/attr block "blockid")]
  1750. (medley/uuid id))) blocks)
  1751. ids (->> (mapcat #(let [children (vec (db/get-block-children-ids repo %))]
  1752. (cons % children)) ids)
  1753. (distinct))
  1754. blocks (db/pull-many '[*] (map (fn [id] [:block/uuid id]) ids))
  1755. block (first blocks)
  1756. format (:block/format block)
  1757. start-pos (get-in block [:block/meta :start-pos])
  1758. old-end-pos (get-in (last blocks) [:block/meta :end-pos])
  1759. pattern (config/get-block-pattern format)
  1760. last-start-pos (atom start-pos)
  1761. blocks (doall
  1762. (map (fn [block]
  1763. (let [content (:block/content block)
  1764. [prefix content] (if-let [col (util/split-first " " content)]
  1765. col
  1766. [content ""])
  1767. level (:block/level block)
  1768. new-marker (state/get-preferred-todo)
  1769. content' (string/replace-first content
  1770. format/marker-pattern
  1771. (str new-marker " "))
  1772. content' (str prefix " " content')
  1773. end-pos (+ @last-start-pos (utf8/length (utf8/encode content')))
  1774. block (assoc block
  1775. :block/marker new-marker
  1776. :block/content content'
  1777. :block/meta (merge
  1778. (:block/meta block)
  1779. {:start-pos @last-start-pos
  1780. :end-pos end-pos}))]
  1781. (reset! last-start-pos end-pos)
  1782. block))
  1783. blocks))
  1784. file-id (:db/id (:block/file block))
  1785. file (db/entity file-id)
  1786. page (:block/page block)
  1787. after-blocks (rebuild-after-blocks repo file old-end-pos @last-start-pos)
  1788. file-path (:file/path file)
  1789. file-content (db/get-file file-path)
  1790. new-content (utf8/insert! file-content start-pos old-end-pos (apply str (map :block/content blocks)))
  1791. modified-time (modified-time-tx page file)]
  1792. (profile
  1793. "Indent/outdent: "
  1794. (repo-handler/transact-react-and-alter-file!
  1795. repo
  1796. (concat
  1797. blocks
  1798. after-blocks
  1799. modified-time)
  1800. {:key :block/change
  1801. :data (map (fn [block] (assoc block :block/page page)) blocks)}
  1802. [[file-path new-content]])))
  1803. (cycle-collapse! state e)))))
  1804. (defn- get-link
  1805. [format link label]
  1806. (let [link (or link "")
  1807. label (or label "")]
  1808. (case (keyword format)
  1809. :markdown (util/format "[%s](%s)" label link)
  1810. :org (util/format "[[%s][%s]]" link label)
  1811. nil)))
  1812. (defn handle-command-input
  1813. [command id format m pos]
  1814. (case command
  1815. :link
  1816. (let [{:keys [link label]} m]
  1817. (if (and (string/blank? link)
  1818. (string/blank? label))
  1819. nil
  1820. (insert-command! id
  1821. (get-link format link label)
  1822. format
  1823. {:last-pattern (str commands/slash "link")})))
  1824. :draw
  1825. (when-not (string/blank? (:title m))
  1826. (let [file (draw/title->file-name (:title m))
  1827. value (util/format
  1828. "[[%s]]\n<iframe class=\"draw-iframe\" src=\"/draw?file=%s\" width=\"100%\" height=\"400\" frameborder=\"0\" allowfullscreen></iframe>"
  1829. file
  1830. file)]
  1831. (insert-command! id
  1832. value
  1833. format
  1834. {:last-pattern (str commands/slash "draw ")})
  1835. (draw/create-draw-with-default-content
  1836. file
  1837. (fn []
  1838. (let [input (gdom/getElement "download")]
  1839. (.click input))))))
  1840. nil)
  1841. (state/set-editor-show-input! nil)
  1842. (when-let [saved-cursor (get @state/state :editor/last-saved-cursor)]
  1843. (when-let [input (gdom/getElement id)]
  1844. (.focus input)
  1845. (util/move-cursor-to input saved-cursor))))
  1846. (defn set-block-as-a-heading!
  1847. [block-id value]
  1848. (set-block-property! block-id "heading" value))
  1849. ;; Should preserve the cursor too.
  1850. (defn open-last-block!
  1851. [journal?]
  1852. (let [edit-id (state/get-edit-input-id)
  1853. last-pos (state/get-edit-pos)
  1854. block-id (when edit-id (subs edit-id (- (count edit-id) 36)))]
  1855. (let [last-edit-block (first (array-seq (js/document.getElementsByClassName block-id)))
  1856. first-block (first (array-seq (js/document.getElementsByClassName "ls-block")))
  1857. node (or last-edit-block
  1858. (and (not journal?) first-block))]
  1859. (when node
  1860. (let [block-id (and node (d/attr node "blockid"))
  1861. edit-block-id (string/replace (gobj/get node "id") "ls-block" "edit-block")
  1862. block-id (medley/uuid block-id)]
  1863. (when-let [block (db/entity [:block/uuid block-id])]
  1864. (edit-block! block
  1865. (or (and last-edit-block last-pos)
  1866. :max)
  1867. (:block/format block)
  1868. edit-block-id)))))))
  1869. (defn get-search-q
  1870. []
  1871. (when-let [id (state/get-edit-input-id)]
  1872. (when-let [input (gdom/getElement id)]
  1873. (let [current-pos (:pos (util/get-caret-pos input))
  1874. pos (:editor/last-saved-cursor @state/state)
  1875. edit-content (state/sub [:editor/content id])]
  1876. (or
  1877. @*selected-text
  1878. (util/safe-subs edit-content pos current-pos))))))
  1879. (defn close-autocomplete-if-outside
  1880. [input]
  1881. (when (or (state/get-editor-show-page-search?)
  1882. (state/get-editor-show-page-search-hashtag?)
  1883. (state/get-editor-show-block-search?))
  1884. (when-let [q (get-search-q)]
  1885. (let [value (gobj/get input "value")
  1886. pos (:editor/last-saved-cursor @state/state)
  1887. current-pos (:pos (util/get-caret-pos input))]
  1888. (when (or (< current-pos pos)
  1889. (string/includes? q "]")
  1890. (string/includes? q ")"))
  1891. (state/set-editor-show-block-search! false)
  1892. (state/set-editor-show-page-search! false)
  1893. (state/set-editor-show-page-search-hashtag! false))))))
  1894. (defn periodically-save!
  1895. []
  1896. (js/setInterval save-current-block-when-idle! 3000))
  1897. (defn get-current-input-value
  1898. []
  1899. (let [edit-input-id (state/get-edit-input-id)
  1900. input (and edit-input-id (gdom/getElement edit-input-id))]
  1901. (when input
  1902. (gobj/get input "value"))))