editor.cljs 137 KB

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