editor.cljs 154 KB

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