editor.cljs 161 KB

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