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