editor.cljs 136 KB

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