editor.cljs 139 KB

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