editor.cljs 161 KB

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