editor.cljs 135 KB

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