editor.cljs 157 KB

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