editor.cljs 167 KB

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