editor.cljs 168 KB

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