editor.cljs 160 KB

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