editor.cljs 124 KB

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