editor.cljs 164 KB

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