editor.cljs 110 KB

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