editor.cljs 160 KB

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