editor.cljs 121 KB

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