editor.cljs 110 KB

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