events.cljs 43 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998
  1. (ns frontend.handler.events
  2. "System-component-like ns that defines named events and listens on a
  3. core.async channel to handle them. Any part of the system can dispatch
  4. one of these events using state/pub-event!"
  5. (:refer-clojure :exclude [run!])
  6. (:require ["@capacitor/filesystem" :refer [Directory Filesystem]]
  7. ["@sentry/react" :as Sentry]
  8. [cljs-bean.core :as bean]
  9. [clojure.core.async :as async]
  10. [clojure.core.async.interop :refer [p->c]]
  11. [clojure.set :as set]
  12. [clojure.string :as string]
  13. [frontend.commands :as commands]
  14. [frontend.components.class :as class-component]
  15. [frontend.components.cmdk :as cmdk]
  16. [frontend.components.diff :as diff]
  17. [frontend.components.encryption :as encryption]
  18. [frontend.components.file-sync :as file-sync]
  19. [frontend.components.git :as git-component]
  20. [frontend.components.plugins :as plugin]
  21. [frontend.components.shell :as shell]
  22. [frontend.components.whiteboard :as whiteboard]
  23. [frontend.components.user.login :as login]
  24. [frontend.components.repo :as repo]
  25. [frontend.components.db-based.page :as db-page]
  26. [frontend.config :as config]
  27. [frontend.context.i18n :refer [t]]
  28. [frontend.db :as db]
  29. [frontend.db.conn :as conn]
  30. [frontend.db.model :as db-model]
  31. [frontend.db.persist :as db-persist]
  32. [frontend.extensions.srs :as srs]
  33. [frontend.fs :as fs]
  34. [frontend.fs.capacitor-fs :as capacitor-fs]
  35. [frontend.fs.nfs :as nfs]
  36. [frontend.fs.sync :as sync]
  37. [frontend.fs.watcher-handler :as fs-watcher]
  38. [frontend.handler.common :as common-handler]
  39. [frontend.handler.editor :as editor-handler]
  40. [frontend.handler.file :as file-handler]
  41. [frontend.handler.file-sync :as file-sync-handler]
  42. [frontend.handler.notification :as notification]
  43. [frontend.handler.page :as page-handler]
  44. [frontend.handler.common.page :as page-common-handler]
  45. [frontend.handler.plugin :as plugin-handler]
  46. [frontend.handler.repo :as repo-handler]
  47. [frontend.handler.repo-config :as repo-config-handler]
  48. [frontend.handler.route :as route-handler]
  49. [frontend.handler.search :as search-handler]
  50. [frontend.handler.shell :as shell-handler]
  51. [frontend.handler.ui :as ui-handler]
  52. [frontend.handler.user :as user-handler]
  53. [frontend.handler.property.util :as pu]
  54. [frontend.handler.db-based.property.util :as db-pu]
  55. [frontend.handler.file-based.property.util :as property-util]
  56. [frontend.handler.property :as property-handler]
  57. [frontend.handler.web.nfs :as nfs-handler]
  58. [frontend.handler.code :as code-handler]
  59. [frontend.mobile.core :as mobile]
  60. [frontend.mobile.graph-picker :as graph-picker]
  61. [frontend.mobile.util :as mobile-util]
  62. [frontend.modules.instrumentation.posthog :as posthog]
  63. [frontend.modules.instrumentation.sentry :as sentry-event]
  64. [frontend.modules.shortcut.core :as st]
  65. [frontend.quick-capture :as quick-capture]
  66. [frontend.search :as search]
  67. [frontend.state :as state]
  68. [frontend.ui :as ui]
  69. [frontend.util :as util]
  70. [frontend.util.persist-var :as persist-var]
  71. [goog.dom :as gdom]
  72. [logseq.db.frontend.schema :as db-schema]
  73. [logseq.common.config :as common-config]
  74. [promesa.core :as p]
  75. [lambdaisland.glogi :as log]
  76. [rum.core :as rum]
  77. [frontend.rum :as r]
  78. [frontend.persist-db.browser :as db-browser]
  79. [frontend.db.rtc.debug-ui :as rtc-debug-ui]
  80. [frontend.modules.outliner.pipeline :as pipeline]
  81. [electron.ipc :as ipc]
  82. [frontend.date :as date]
  83. [logseq.db :as ldb]))
  84. ;; TODO: should we move all events here?
  85. (defmulti handle first)
  86. (defn file-sync-restart! []
  87. (async/go (async/<! (p->c (persist-var/load-vars)))
  88. (async/<! (sync/<sync-stop))
  89. (some-> (sync/<sync-start) async/<!)))
  90. (defn- file-sync-stop! []
  91. (async/go (async/<! (p->c (persist-var/load-vars)))
  92. (async/<! (sync/<sync-stop))))
  93. (defn- enable-beta-features!
  94. []
  95. (when-not (false? (state/enable-sync?)) ; user turns it off
  96. (file-sync-handler/set-sync-enabled! true)))
  97. (defmethod handle :user/fetch-info-and-graphs [[_]]
  98. (state/set-state! [:ui/loading? :login] false)
  99. (async/go
  100. (let [result (async/<! (sync/<user-info sync/remoteapi))]
  101. (cond
  102. (instance? ExceptionInfo result)
  103. nil
  104. (map? result)
  105. (do
  106. (state/set-user-info! result)
  107. (when-let [uid (user-handler/user-uuid)]
  108. (sentry-event/set-user! uid))
  109. (let [status (if (user-handler/alpha-or-beta-user?) :welcome :unavailable)]
  110. (when (and (= status :welcome) (user-handler/logged-in?))
  111. (enable-beta-features!)
  112. (async/<! (file-sync-handler/load-session-graphs))
  113. (p/let [repos (repo-handler/refresh-repos!)]
  114. (when-let [repo (state/get-current-repo)]
  115. (when (some #(and (= (:url %) repo)
  116. (vector? (:sync-meta %))
  117. (util/uuid-string? (first (:sync-meta %)))
  118. (util/uuid-string? (second (:sync-meta %)))) repos)
  119. (sync/<sync-start)))))
  120. (ui-handler/re-render-root!)
  121. (file-sync/maybe-onboarding-show status)))))))
  122. (defmethod handle :user/logout [[_]]
  123. (file-sync-handler/reset-session-graphs)
  124. (sync/remove-all-pwd!)
  125. (file-sync-handler/reset-user-state!)
  126. (login/sign-out!))
  127. (defmethod handle :user/login [[_ host-ui?]]
  128. (if (or host-ui? (not util/electron?))
  129. (js/window.open config/LOGIN-URL)
  130. (login/open-login-modal!)))
  131. (defmethod handle :graph/added [[_ repo {:keys [empty-graph?]}]]
  132. (db/set-key-value repo :ast/version db-schema/ast-version)
  133. (search-handler/rebuild-indices!)
  134. (plugin-handler/hook-plugin-app :graph-after-indexed {:repo repo :empty-graph? empty-graph?})
  135. (when (state/setups-picker?)
  136. (if empty-graph?
  137. (route-handler/redirect! {:to :import :query-params {:from "picker"}})
  138. (route-handler/redirect-to-home!)))
  139. (when-let [dir-name (and (not (config/db-based-graph? repo)) (config/get-repo-dir repo))]
  140. (fs/watch-dir! dir-name))
  141. (file-sync-restart!))
  142. (defmethod handle :init/commands [_]
  143. (page-handler/init-commands!))
  144. (defmethod handle :graph/unlinked [repo current-repo]
  145. (when (= (:url repo) current-repo)
  146. (file-sync-restart!)))
  147. ;; FIXME(andelf): awful multi-arty function.
  148. ;; Should use a `-impl` function instead of the awful `skip-ios-check?` param with nested callback.
  149. (defn- graph-switch
  150. ([graph]
  151. (graph-switch graph false))
  152. ([graph skip-ios-check?]
  153. (let [db-based? (config/db-based-graph? graph)]
  154. (if (and (mobile-util/native-ios?) (not skip-ios-check?))
  155. (state/pub-event! [:validate-appId graph-switch graph])
  156. (do
  157. (state/set-current-repo! graph)
  158. (page-handler/init-commands!)
  159. ;; load config
  160. (repo-config-handler/restore-repo-config! graph)
  161. (when-not (= :draw (state/get-current-route))
  162. (route-handler/redirect-to-home!))
  163. (srs/update-cards-due-count!)
  164. (state/pub-event! [:graph/ready graph])
  165. (when-not db-based?
  166. (file-sync-restart!))
  167. (when-let [dir-name (and (not db-based?) (config/get-repo-dir graph))]
  168. (fs/watch-dir! dir-name)))))))
  169. ;; Parameters for the `persist-db` function, to show the notification messages
  170. (defn- graph-switch-on-persisted
  171. "graph: the target graph to switch to"
  172. [graph _opts]
  173. (p/do!
  174. (repo-handler/restore-and-setup-repo! graph)
  175. (graph-switch graph)
  176. state/set-state! :sync-graph/init? false))
  177. (defmethod handle :graph/switch [[_ graph opts]]
  178. (state/set-state! :db/async-queries #{})
  179. (reset! r/*key->atom {})
  180. (let [^js sqlite @db-browser/*worker]
  181. (p/let [writes-finished? (when sqlite (.file-writes-finished? sqlite (state/get-current-repo)))
  182. request-finished? (ldb/request-finished?)]
  183. (if (or (not request-finished?) (not writes-finished?)) ; TODO: test (:sync-graph/init? @state/state)
  184. (do
  185. (log/info :graph/switch (cond->
  186. {:request-finished? request-finished?
  187. :file-writes-finished? writes-finished?}
  188. (false? request-finished?)
  189. (assoc :unfinished-requests? @ldb/*request-id->response)))
  190. (notification/show!
  191. "Please wait seconds until all changes are saved for the current graph."
  192. :warning))
  193. (graph-switch-on-persisted graph opts)))))
  194. (defmethod handle :graph/pull-down-remote-graph [[_ graph dir-name]]
  195. (if (mobile-util/native-ios?)
  196. (when-let [graph-name (or dir-name (:GraphName graph))]
  197. (let [graph-name (util/safe-sanitize-file-name graph-name)]
  198. (if (string/blank? graph-name)
  199. (notification/show! "Illegal graph folder name.")
  200. ;; Create graph directory under Logseq document folder (local)
  201. (when-let [root (state/get-local-container-root-url)]
  202. (let [graph-path (graph-picker/validate-graph-dirname root graph-name)]
  203. (->
  204. (p/let [exists? (fs/dir-exists? graph-path)]
  205. (let [overwrite? (if exists?
  206. (js/confirm (str "There's already a directory with the name \"" graph-name "\", do you want to overwrite it? Make sure to backup it first if you're not sure about it."))
  207. true)]
  208. (if overwrite?
  209. (p/let [_ (fs/mkdir-if-not-exists graph-path)]
  210. (nfs-handler/ls-dir-files-with-path!
  211. graph-path
  212. {:ok-handler (fn []
  213. (file-sync-handler/init-remote-graph graph-path graph)
  214. (js/setTimeout (fn [] (repo-handler/refresh-repos!)) 200))}))
  215. (let [graph-name (-> (js/prompt "Please specify a new directory name to download the graph:")
  216. str
  217. string/trim)]
  218. (when-not (string/blank? graph-name)
  219. (state/pub-event! [:graph/pull-down-remote-graph graph graph-name]))))))
  220. (p/catch (fn [^js e]
  221. (notification/show! (str e) :error)
  222. (js/console.error e)))))))))
  223. (state/set-modal!
  224. (file-sync/pick-dest-to-sync-panel graph)
  225. {:center? true})))
  226. (defmethod handle :graph/pick-page-histories [[_ graph-uuid page-name]]
  227. (state/set-modal!
  228. (file-sync/pick-page-histories-panel graph-uuid page-name)
  229. {:id :page-histories :label "modal-page-histories"}))
  230. (defmethod handle :graph/open-new-window [[_ev target-repo]]
  231. (p/let [current-repo (state/get-current-repo)]
  232. (ui-handler/open-new-window-or-tab! current-repo target-repo)))
  233. (defmethod handle :graph/migrated [[_ _repo]]
  234. (js/alert "Graph migrated."))
  235. (defn get-local-repo
  236. []
  237. (when-let [repo (state/get-current-repo)]
  238. (when (config/local-file-based-graph? repo)
  239. repo)))
  240. (defn ask-permission
  241. [repo]
  242. (when
  243. (and (not (util/electron?))
  244. (not (mobile-util/native-platform?)))
  245. (fn [close-fn]
  246. [:div
  247. ;; TODO: fn translation with args
  248. [:p
  249. "Grant native filesystem permission for directory: "
  250. [:b (config/get-local-dir repo)]]
  251. (ui/button
  252. (t :settings-permission/start-granting)
  253. :class "ui__modal-enter"
  254. :on-click (fn []
  255. (nfs/check-directory-permission! repo)
  256. (close-fn)))])))
  257. (defmethod handle :modal/nfs-ask-permission []
  258. (when-let [repo (get-local-repo)]
  259. (state/set-modal! (ask-permission repo))))
  260. (defonce *query-properties (atom {}))
  261. (rum/defc query-properties-settings-inner < rum/reactive
  262. {:will-unmount (fn [state]
  263. (reset! *query-properties {})
  264. state)}
  265. [block shown-properties all-properties]
  266. (let [query-properties (rum/react *query-properties)]
  267. [:div.p-4
  268. [:div.font-bold (t :query/config-property-settings)]
  269. [:div.flex
  270. {:title "Refresh list of columns"
  271. :on-click
  272. (fn []
  273. (reset! *query-properties {})
  274. (property-handler/remove-block-property! (state/get-current-repo) (:block/uuid block) :query-properties))}
  275. (ui/icon "refresh")]
  276. (for [property all-properties]
  277. (let [property-value (get query-properties property)
  278. shown? (if (nil? property-value)
  279. (contains? shown-properties property)
  280. property-value)]
  281. [:div.flex.flex-row.m-2.justify-between.align-items
  282. [:div (if (uuid? property) (db-pu/get-property-name property) (name property))]
  283. [:div.mt-1 (ui/toggle shown?
  284. (fn []
  285. (let [value (not shown?)]
  286. (swap! *query-properties assoc property value)
  287. (editor-handler/set-block-query-properties!
  288. (:block/uuid block)
  289. all-properties
  290. property
  291. value)))
  292. true)]]))]))
  293. (defn query-properties-settings
  294. [block shown-properties all-properties]
  295. (fn [_close-fn]
  296. (query-properties-settings-inner block shown-properties all-properties)))
  297. (defmethod handle :modal/set-query-properties [[_ block all-properties]]
  298. (let [properties (:block/properties block)
  299. query-properties (pu/lookup properties :query-properties)
  300. block-properties (if (config/db-based-graph? (state/get-current-repo))
  301. query-properties
  302. (some-> query-properties
  303. (common-handler/safe-read-string "Parsing query properties failed")))
  304. shown-properties (if (seq block-properties)
  305. (set block-properties)
  306. (set all-properties))
  307. shown-properties (set/intersection (set all-properties) shown-properties)]
  308. (state/set-modal! (query-properties-settings block shown-properties all-properties)
  309. {:center? true})))
  310. (defmethod handle :modal/show-cards [_]
  311. (state/set-modal! srs/global-cards {:id :srs
  312. :label "flashcards__cp"}))
  313. (defmethod handle :modal/show-instruction [_]
  314. (state/set-modal! capacitor-fs/instruction {:id :instruction
  315. :label "instruction__cp"}))
  316. (defmethod handle :modal/show-themes-modal [_]
  317. (plugin/open-select-theme!))
  318. (rum/defc modal-output
  319. [content]
  320. content)
  321. (defmethod handle :modal/show [[_ content]]
  322. (state/set-modal! #(modal-output content)))
  323. (defmethod handle :modal/set-git-username-and-email [[_ _content]]
  324. (state/set-modal! git-component/set-git-username-and-email))
  325. (defmethod handle :page/create [[_ page-name opts]]
  326. (if (= page-name (date/today))
  327. (page-handler/create-today-journal!)
  328. (page-handler/<create! page-name opts)))
  329. (defmethod handle :page/deleted [[_ repo page-name file-path tx-meta]]
  330. (page-common-handler/after-page-deleted! repo page-name file-path tx-meta))
  331. (defmethod handle :page/renamed [[_ repo data]]
  332. (page-common-handler/after-page-renamed! repo data))
  333. (defmethod handle :page/create-today-journal [[_ _repo]]
  334. (p/let [_ (page-handler/create-today-journal!)]
  335. (ui-handler/re-render-root!)))
  336. (defmethod handle :file/not-matched-from-disk [[_ path disk-content db-content]]
  337. (when-let [repo (state/get-current-repo)]
  338. (let [^js sqlite @db-browser/*worker]
  339. (p/let [writes-finished? (when sqlite (.file-writes-finished? sqlite (state/get-current-repo)))
  340. request-finished? (ldb/request-finished?)]
  341. (prn :debug :writes-finished? writes-finished?
  342. :request-finished? request-finished?)
  343. (when (and request-finished? writes-finished? disk-content db-content
  344. (not= (util/trim-safe disk-content) (util/trim-safe db-content)))
  345. (state/set-modal! #(diff/local-file repo path disk-content db-content)
  346. {:label "diff__cp"}))))))
  347. (defmethod handle :modal/display-file-version [[_ path content hash]]
  348. (state/set-modal! #(git-component/file-specific-version path hash content)))
  349. ;; Hook on a graph is ready to be shown to the user.
  350. ;; It's different from :graph/restored, as :graph/restored is for window reloaded
  351. ;; FIXME: config may not be loaded when the graph is ready.
  352. (defmethod handle :graph/ready
  353. [[_ repo]]
  354. (when (config/local-file-based-graph? repo)
  355. (p/let [dir (config/get-repo-dir repo)
  356. dir-exists? (fs/dir-exists? dir)]
  357. (when (and (not dir-exists?)
  358. (not util/nfs?))
  359. (state/pub-event! [:graph/dir-gone dir]))))
  360. (p/let [loaded-homepage-files (when-not (config/db-based-graph? repo)
  361. (fs-watcher/preload-graph-homepage-files!))
  362. ;; re-render-root is async and delegated to rum, so we need to wait for main ui to refresh
  363. _ (js/setTimeout #(mobile/mobile-postinit) 1000)
  364. ;; FIXME: an ugly implementation for redirecting to page on new window is restored
  365. _ (repo-handler/graph-ready! repo)
  366. _ (when-not (config/db-based-graph? repo)
  367. (fs-watcher/load-graph-files! repo loaded-homepage-files))]))
  368. (defmethod handle :notification/show [[_ {:keys [content status clear?]}]]
  369. (notification/show! content status clear?))
  370. (defmethod handle :command/run [_]
  371. (when (util/electron?)
  372. (state/set-modal! shell/shell)))
  373. (defmethod handle :go/search [_]
  374. (state/set-modal! cmdk/cmdk-modal
  375. {:fullscreen? true
  376. :close-btn? false
  377. :panel? false
  378. :label "ls-modal-search"}))
  379. (defmethod handle :go/plugins [_]
  380. (plugin/open-plugins-modal!))
  381. (defmethod handle :go/plugins-waiting-lists [_]
  382. (plugin/open-waiting-updates-modal!))
  383. (defmethod handle :go/plugins-from-file [[_ plugins]]
  384. (plugin/open-plugins-from-file-modal! plugins))
  385. (defmethod handle :go/plugins-settings [[_ pid nav? title]]
  386. (if pid
  387. (do
  388. (state/set-state! :plugin/focused-settings pid)
  389. (state/set-state! :plugin/navs-settings? (not (false? nav?)))
  390. (plugin/open-focused-settings-modal! title))
  391. (state/close-sub-modal! "ls-focused-settings-modal")))
  392. (defmethod handle :go/proxy-settings [[_ agent-opts]]
  393. (state/set-sub-modal!
  394. (fn [_] (plugin/user-proxy-settings-panel agent-opts))
  395. {:id :https-proxy-panel :center? true}))
  396. (defmethod handle :redirect-to-home [_]
  397. (page-handler/create-today-journal!))
  398. (defmethod handle :instrument [[_ {:keys [type payload] :as opts}]]
  399. (when-not (empty? (dissoc opts :type :payload))
  400. (js/console.error "instrument data-map should only contains [:type :payload]"))
  401. (posthog/capture type payload))
  402. (defmethod handle :capture-error [[_ {:keys [error payload]}]]
  403. (let [[user-uuid graph-uuid tx-id] @sync/graphs-txid
  404. payload (assoc payload
  405. :user-id user-uuid
  406. :graph-id graph-uuid
  407. :tx-id tx-id)]
  408. (Sentry/captureException error
  409. (bean/->js {:tags payload}))))
  410. (defmethod handle :exec-plugin-cmd [[_ {:keys [pid cmd action]}]]
  411. (commands/exec-plugin-simple-command! pid cmd action))
  412. (defmethod handle :shortcut-handler-refreshed [[_]]
  413. (when-not @st/*pending-inited?
  414. (reset! st/*pending-inited? true)
  415. (st/consume-pending-shortcuts!)))
  416. (defmethod handle :mobile/keyboard-will-show [[_ keyboard-height]]
  417. (let [main-node (util/app-scroll-container-node)]
  418. (state/set-state! :mobile/show-tabbar? false)
  419. (state/set-state! :mobile/show-toolbar? true)
  420. (state/set-state! :mobile/show-action-bar? false)
  421. (when (= (state/sub :editor/record-status) "RECORDING")
  422. (state/set-state! :mobile/show-recording-bar? true))
  423. (when (mobile-util/native-ios?)
  424. (reset! util/keyboard-height keyboard-height)
  425. (set! (.. main-node -style -marginBottom) (str keyboard-height "px"))
  426. (when-let [^js html (js/document.querySelector ":root")]
  427. (.setProperty (.-style html) "--ls-native-kb-height" (str keyboard-height "px"))
  428. (.add (.-classList html) "has-mobile-keyboard"))
  429. (when-let [left-sidebar-node (gdom/getElement "left-sidebar")]
  430. (set! (.. left-sidebar-node -style -bottom) (str keyboard-height "px")))
  431. (when-let [right-sidebar-node (gdom/getElementByClass "sidebar-item-list")]
  432. (set! (.. right-sidebar-node -style -paddingBottom) (str (+ 150 keyboard-height) "px")))
  433. (when-let [card-preview-el (js/document.querySelector ".cards-review")]
  434. (set! (.. card-preview-el -style -marginBottom) (str keyboard-height "px")))
  435. (when-let [card-preview-el (js/document.querySelector ".encryption-password")]
  436. (set! (.. card-preview-el -style -marginBottom) (str keyboard-height "px")))
  437. (js/setTimeout (fn []
  438. (when-let [toolbar (.querySelector main-node "#mobile-editor-toolbar")]
  439. (set! (.. toolbar -style -bottom) (str keyboard-height "px"))))
  440. 100))))
  441. (defmethod handle :mobile/keyboard-will-hide [[_]]
  442. (let [main-node (util/app-scroll-container-node)]
  443. (state/set-state! :mobile/show-toolbar? false)
  444. (state/set-state! :mobile/show-tabbar? true)
  445. (when (= (state/sub :editor/record-status) "RECORDING")
  446. (state/set-state! :mobile/show-recording-bar? false))
  447. (when (mobile-util/native-ios?)
  448. (when-let [^js html (js/document.querySelector ":root")]
  449. (.removeProperty (.-style html) "--ls-native-kb-height")
  450. (.remove (.-classList html) "has-mobile-keyboard"))
  451. (when-let [card-preview-el (js/document.querySelector ".cards-review")]
  452. (set! (.. card-preview-el -style -marginBottom) "0px"))
  453. (when-let [card-preview-el (js/document.querySelector ".encryption-password")]
  454. (set! (.. card-preview-el -style -marginBottom) "0px"))
  455. (set! (.. main-node -style -marginBottom) "0px")
  456. (when-let [left-sidebar-node (gdom/getElement "left-sidebar")]
  457. (set! (.. left-sidebar-node -style -bottom) "0px"))
  458. (when-let [right-sidebar-node (gdom/getElementByClass "sidebar-item-list")]
  459. (set! (.. right-sidebar-node -style -paddingBottom) "150px"))
  460. (when-let [toolbar (.querySelector main-node "#mobile-editor-toolbar")]
  461. (set! (.. toolbar -style -bottom) 0)))))
  462. (defn- get-ios-app-id
  463. [repo-url]
  464. (when repo-url
  465. (let [app-id (-> (first (string/split repo-url "/Documents"))
  466. (string/split "/")
  467. last)]
  468. app-id)))
  469. (defmethod handle :validate-appId [[_ graph-switch-f graph]]
  470. (when-let [deprecated-repo (or graph (state/get-current-repo))]
  471. (if (mobile-util/in-iCloud-container-path? deprecated-repo)
  472. ;; Installation is not changed for iCloud
  473. (when graph-switch-f
  474. (graph-switch-f graph true)
  475. (state/pub-event! [:graph/ready (state/get-current-repo)]))
  476. ;; Installation is changed for App Documents directory
  477. (p/let [deprecated-app-id (get-ios-app-id deprecated-repo)
  478. current-document-url (.getUri Filesystem #js {:path ""
  479. :directory (.-Documents Directory)})
  480. current-app-id (-> (js->clj current-document-url :keywordize-keys true)
  481. get-ios-app-id)]
  482. (if (= deprecated-app-id current-app-id)
  483. (when graph-switch-f (graph-switch-f graph true))
  484. (do
  485. (notification/show! [:div "Migrating from previous App installation..."]
  486. :warning
  487. true)
  488. (prn ::migrate-app-id :from deprecated-app-id :to current-app-id)
  489. (file-sync-stop!)
  490. (.unwatch mobile-util/fs-watcher)
  491. (let [current-repo (string/replace deprecated-repo deprecated-app-id current-app-id)
  492. current-repo-dir (config/get-repo-dir current-repo)]
  493. (try
  494. ;; replace app-id part of repo url
  495. (reset! conn/conns
  496. (update-keys @conn/conns
  497. (fn [key]
  498. (if (string/includes? key deprecated-app-id)
  499. (string/replace key deprecated-app-id current-app-id)
  500. key))))
  501. (db-persist/rename-graph! deprecated-repo current-repo)
  502. (search/remove-db! deprecated-repo)
  503. (state/add-repo! {:url current-repo :nfs? true})
  504. (state/delete-repo! {:url deprecated-repo})
  505. (catch :default e
  506. (js/console.error e)))
  507. (state/set-current-repo! current-repo)
  508. (repo-config-handler/restore-repo-config! current-repo)
  509. (when graph-switch-f (graph-switch-f current-repo true))
  510. (.watch mobile-util/fs-watcher #js {:path current-repo-dir})
  511. (file-sync-restart!))))
  512. (state/pub-event! [:graph/ready (state/get-current-repo)])))))
  513. (defmethod handle :plugin/consume-updates [[_ id prev-pending? updated?]]
  514. (let [downloading? (:plugin/updates-downloading? @state/state)
  515. auto-checking? (plugin-handler/get-auto-checking?)]
  516. (when-let [coming (and (not downloading?)
  517. (get-in @state/state [:plugin/updates-coming id]))]
  518. (let [error-code (:error-code coming)
  519. error-code (if (= error-code (str :no-new-version)) nil error-code)
  520. title (:title coming)]
  521. (when (and prev-pending? (not auto-checking?))
  522. (if-not error-code
  523. (plugin/set-updates-sub-content! (str title "...") 0)
  524. (notification/show!
  525. (str "[Checked]<" title "> " error-code) :error)))))
  526. (if (and updated? downloading?)
  527. ;; try to start consume downloading item
  528. (if-let [next-coming (state/get-next-selected-coming-update)]
  529. (plugin-handler/check-or-update-marketplace-plugin!
  530. (assoc next-coming :only-check false :error-code nil)
  531. (fn [^js e] (js/console.error "[Download Err]" next-coming e)))
  532. (plugin-handler/close-updates-downloading))
  533. ;; try to start consume pending item
  534. (if-let [next-pending (second (first (:plugin/updates-pending @state/state)))]
  535. (do
  536. (println "Updates: take next pending - " (:id next-pending))
  537. (js/setTimeout
  538. #(plugin-handler/check-or-update-marketplace-plugin!
  539. (assoc next-pending :only-check true :auto-check auto-checking? :error-code nil)
  540. (fn [^js e]
  541. (notification/show! (.toString e) :error)
  542. (js/console.error "[Check Err]" next-pending e))) 500))
  543. ;; try to open waiting updates list
  544. (do (when (and prev-pending? (not auto-checking?)
  545. (seq (state/all-available-coming-updates)))
  546. (plugin/open-waiting-updates-modal!))
  547. (plugin-handler/set-auto-checking! false))))))
  548. (defmethod handle :plugin/hook-db-tx [[_ {:keys [blocks tx-data] :as payload}]]
  549. (when-let [payload (and (seq blocks)
  550. (merge payload {:tx-data (map #(into [] %) tx-data)}))]
  551. (plugin-handler/hook-plugin-db :changed payload)
  552. (plugin-handler/hook-plugin-block-changes payload)))
  553. (defmethod handle :plugin/loader-perf-tip [[_ {:keys [^js o _s _e]}]]
  554. (when-let [opts (.-options o)]
  555. (notification/show!
  556. (plugin/perf-tip-content (.-id o) (.-name opts) (.-url opts))
  557. :warning false (.-id o))))
  558. (defmethod handle :mobile-file-watcher/changed [[_ ^js event]]
  559. (let [type (.-event event)
  560. payload (js->clj event :keywordize-keys true)]
  561. (fs-watcher/handle-changed! type payload)
  562. (when (file-sync-handler/enable-sync?)
  563. (sync/file-watch-handler type payload))))
  564. (defmethod handle :rebuild-slash-commands-list [[_]]
  565. (page-handler/rebuild-slash-commands-list!))
  566. (defmethod handle :shortcut/refresh [[_]]
  567. (st/refresh!))
  568. (defn- refresh-cb []
  569. (page-handler/create-today-journal!)
  570. (file-sync-restart!))
  571. (defmethod handle :graph/ask-for-re-fresh [_]
  572. (handle
  573. [:modal/show
  574. [:div {:style {:max-width 700}}
  575. [:p (t :sync-from-local-changes-detected)]
  576. (ui/button
  577. (t :yes)
  578. :autoFocus "on"
  579. :class "ui__modal-enter"
  580. :on-click (fn []
  581. (state/close-modal!)
  582. (nfs-handler/refresh! (state/get-current-repo) refresh-cb)))]]))
  583. (defmethod handle :sync/create-remote-graph [[_ current-repo]]
  584. (let [graph-name (js/decodeURI (util/node-path.basename current-repo))]
  585. (async/go
  586. (async/<! (sync/<sync-stop))
  587. (state/set-state! [:ui/loading? :graph/create-remote?] true)
  588. (when-let [GraphUUID (get (async/<! (file-sync-handler/create-graph graph-name)) 2)]
  589. (async/<! (sync/<sync-start))
  590. (state/set-state! [:ui/loading? :graph/create-remote?] false)
  591. ;; update existing repo
  592. (state/set-repos! (map (fn [r]
  593. (if (= (:url r) current-repo)
  594. (assoc r
  595. :GraphUUID GraphUUID
  596. :GraphName graph-name
  597. :remote? true)
  598. r))
  599. (state/get-repos)))))))
  600. (defmethod handle :modal/remote-encryption-input-pw-dialog [[_ repo-url remote-graph-info type opts]]
  601. (state/set-modal!
  602. (encryption/input-password
  603. repo-url nil (merge
  604. (assoc remote-graph-info
  605. :type (or type :create-pwd-remote)
  606. :repo repo-url)
  607. opts))
  608. {:center? true :close-btn? false :close-backdrop? false}))
  609. (defmethod handle :journal/insert-template [[_ page-name]]
  610. (let [page-name (util/page-name-sanity-lc page-name)]
  611. (when-let [page (db/pull [:block/name page-name])]
  612. (when (db/page-empty? (state/get-current-repo) page-name)
  613. (when-let [template (state/get-default-journal-template)]
  614. (editor-handler/insert-template!
  615. nil
  616. template
  617. {:target page}))))))
  618. (defmethod handle :editor/set-org-mode-heading [[_ block heading]]
  619. (when-let [id (:block/uuid block)]
  620. (editor-handler/set-heading! id heading)))
  621. (defmethod handle :file-sync-graph/restore-file [[_ graph page-entity content]]
  622. (when (db/get-db graph)
  623. (let [file (:block/file page-entity)]
  624. (when-let [path (:file/path file)]
  625. (when (and (not= content (:file/content file))
  626. (:file/content file))
  627. (sync/add-new-version-file graph path (:file/content file)))
  628. (p/let [_ (file-handler/alter-file graph
  629. path
  630. content
  631. {:re-render-root? true
  632. :skip-compare? true})]
  633. (state/close-modal!)
  634. (route-handler/redirect! {:to :page
  635. :path-params {:name (:block/name page-entity)}}))))))
  636. (defmethod handle :whiteboard/onboarding [[_ opts]]
  637. (state/set-modal!
  638. (fn [close-fn] (whiteboard/onboarding-welcome close-fn))
  639. (merge {:close-btn? false
  640. :center? true
  641. :close-backdrop? false} opts)))
  642. (defmethod handle :file-sync/onboarding-tip [[_ type opts]]
  643. (let [type (keyword type)]
  644. (state/set-modal!
  645. (file-sync/make-onboarding-panel type)
  646. (merge {:close-btn? false
  647. :center? true
  648. :close-backdrop? (not= type :welcome)} opts))))
  649. (defmethod handle :file-sync/maybe-onboarding-show [[_ type]]
  650. (file-sync/maybe-onboarding-show type))
  651. (defmethod handle :file-sync/storage-exceed-limit [[_]]
  652. (notification/show! "file sync storage exceed limit" :warning false)
  653. (file-sync-stop!))
  654. (defmethod handle :file-sync/graph-count-exceed-limit [[_]]
  655. (notification/show! "file sync graph count exceed limit" :warning false)
  656. (file-sync-stop!))
  657. (defmethod handle :graph/restored [[_ _graph]]
  658. (mobile/init!)
  659. (when-not (mobile-util/native-ios?)
  660. (state/pub-event! [:graph/ready (state/get-current-repo)])))
  661. (defmethod handle :whiteboard-link [[_ shapes]]
  662. (route-handler/go-to-search! :whiteboard/link)
  663. (state/set-state! :whiteboard/linked-shapes shapes))
  664. (defmethod handle :whiteboard-go-to-link [[_ link]]
  665. (route-handler/redirect! {:to :whiteboard
  666. :path-params {:name link}}))
  667. (defmethod handle :graph/dir-gone [[_ dir]]
  668. (state/pub-event! [:notification/show
  669. {:content (str "The directory " dir " has been renamed or deleted, the editor will be disabled for this graph, you can unlink the graph.")
  670. :status :error
  671. :clear? false}])
  672. (state/update-state! :file/unlinked-dirs (fn [dirs] (conj dirs dir))))
  673. (defmethod handle :graph/dir-back [[_ repo dir]]
  674. (when (contains? (:file/unlinked-dirs @state/state) dir)
  675. (notification/clear-all!)
  676. (state/pub-event! [:notification/show
  677. {:content (str "The directory " dir " has been back, you can edit your graph now.")
  678. :status :success
  679. :clear? true}])
  680. (state/update-state! :file/unlinked-dirs (fn [dirs] (disj dirs dir)))
  681. (when (= dir (config/get-repo-dir repo))
  682. (fs/watch-dir! dir))))
  683. (defmethod handle :ui/notify-skipped-downloading-files [[_ paths]]
  684. (notification/show!
  685. [:div
  686. [:div.mb-4
  687. [:div.font-semibold.mb-4.text-xl "It seems that some of your filenames are in the outdated format."]
  688. [:p
  689. "The files below that have reserved characters can't be saved on this device."]
  690. [:div.overflow-y-auto.max-h-96
  691. [:ol.my-2
  692. (for [path paths]
  693. [:li path])]]
  694. [:div
  695. [:p
  696. "Check " [:a {:href "https://docs.logseq.com/#/page/logseq%20file%20and%20folder%20naming%20rules"
  697. :target "_blank"}
  698. "Logseq file and folder naming rules"]
  699. " for more details."]
  700. [:p
  701. (util/format "To solve this problem, we suggest you quit Logseq and update the filename format (on Settings > Advanced > Filename format > click EDIT button)%s to avoid more potential bugs."
  702. (if (and util/mac? (not (mobile-util/native-ios?)))
  703. ""
  704. " in other devices"))]]]]
  705. :warning
  706. false))
  707. (defmethod handle :graph/setup-a-repo [[_ opts]]
  708. (let [opts' (merge {:picked-root-fn #(state/close-modal!)
  709. :native-icloud? (not (string/blank? (state/get-icloud-container-root-url)))
  710. :logged? (user-handler/logged-in?)} opts)]
  711. (if (mobile-util/native-ios?)
  712. (state/set-modal!
  713. #(graph-picker/graph-picker-cp opts')
  714. {:label "graph-setup"})
  715. (page-handler/ls-dir-files! st/refresh! opts'))))
  716. (defmethod handle :graph/new-db-graph [[_ _opts]]
  717. (state/set-modal!
  718. repo/new-db-graph
  719. {:id :new-db-graph
  720. :label "graph-setup"}))
  721. (defmethod handle :search/transact-data [[_ repo data]]
  722. (let [file-based? (config/local-file-based-graph? repo)
  723. data' (cond-> data
  724. file-based?
  725. ;; remove built-in properties from content
  726. (update :blocks-to-add
  727. (fn [blocks]
  728. (map #(update % :content
  729. (fn [content]
  730. (property-util/remove-built-in-properties (get % :format :markdown) content)))
  731. blocks))))]
  732. (search/transact-blocks! repo data')))
  733. (defmethod handle :class/configure [[_ page]]
  734. (state/set-modal!
  735. #(vector :<>
  736. (class-component/configure page {})
  737. (db-page/page-properties page {:configure? true}))
  738. {:id :page-configure
  739. :label "page-configure"
  740. :container-overflow-visible? true}))
  741. (defmethod handle :file/alter [[_ repo path content]]
  742. (p/let [_ (file-handler/alter-file repo path content {:from-disk? true})]
  743. (ui-handler/re-render-root!)))
  744. (defmethod handle :ui/re-render-root [[_]]
  745. (ui-handler/re-render-root!))
  746. (rum/defcs file-id-conflict-item <
  747. (rum/local false ::resolved?)
  748. [state repo file data]
  749. (let [resolved? (::resolved? state)
  750. id (last (:assertion data))]
  751. [:li {:key file}
  752. [:div
  753. [:a {:on-click #(js/window.apis.openPath file)} file]
  754. (if @resolved?
  755. [:div.flex.flex-row.items-center
  756. (ui/icon "circle-check" {:style {:font-size 20}})
  757. [:div.ml-1 "Resolved"]]
  758. [:div
  759. [:p
  760. (str "It seems that another whiteboard file already has the ID \"" id
  761. "\". You can fix it by changing the ID in this file with another UUID.")]
  762. [:p
  763. "Or, let me"
  764. (ui/button "Fix"
  765. :on-click (fn []
  766. (let [dir (config/get-repo-dir repo)]
  767. (p/let [content (fs/read-file dir file)]
  768. (let [new-content (string/replace content (str id) (str (random-uuid)))]
  769. (p/let [_ (fs/write-file! repo
  770. dir
  771. file
  772. new-content
  773. {})]
  774. (reset! resolved? true))))))
  775. :class "inline mx-1")
  776. "it."]])]]))
  777. (defmethod handle :file/parse-and-load-error [[_ repo parse-errors]]
  778. (state/pub-event! [:notification/show
  779. {:content
  780. [:div
  781. [:h2.title "Oops. These files failed to import to your graph:"]
  782. [:ol.my-2
  783. (for [[file error] parse-errors]
  784. (let [data (ex-data error)]
  785. (cond
  786. (and (common-config/whiteboard? file)
  787. (= :transact/upsert (:error data))
  788. (uuid? (last (:assertion data))))
  789. (rum/with-key (file-id-conflict-item repo file data) file)
  790. :else
  791. (do
  792. (state/pub-event! [:capture-error {:error error
  793. :payload {:type :file/parse-and-load-error}}])
  794. [:li.my-1 {:key file}
  795. [:a {:on-click #(js/window.apis.openPath file)} file]
  796. [:p (.-message error)]]))))]
  797. [:p "Don't forget to re-index your graph when all the conflicts are resolved."]]
  798. :status :error}]))
  799. (defmethod handle :run/cli-command [[_ command content]]
  800. (when (and command (not (string/blank? content)))
  801. (shell-handler/run-cli-command-wrapper! command content)))
  802. (defmethod handle :editor/quick-capture [[_ args]]
  803. (quick-capture/quick-capture args))
  804. (defmethod handle :modal/keymap [[_]]
  805. (state/open-settings! :keymap))
  806. (defmethod handle :editor/toggle-own-number-list [[_ blocks]]
  807. (let [batch? (sequential? blocks)
  808. blocks (cond->> blocks
  809. batch?
  810. (map #(cond-> % (or (uuid? %) (string? %)) (db-model/get-block-by-uuid))))]
  811. (if (and batch? (> (count blocks) 1))
  812. (editor-handler/toggle-blocks-as-own-order-list! blocks)
  813. (when-let [block (cond-> blocks batch? (first))]
  814. (if (editor-handler/own-order-number-list? block)
  815. (editor-handler/remove-block-own-order-list-type! block)
  816. (editor-handler/make-block-as-own-order-list! block))))))
  817. (defmethod handle :editor/remove-own-number-list [[_ block]]
  818. (when (some-> block (editor-handler/own-order-number-list?))
  819. (editor-handler/remove-block-own-order-list-type! block)))
  820. (defmethod handle :editor/save-code-editor [_]
  821. (code-handler/save-code-editor!))
  822. (defmethod handle :editor/toggle-children-number-list [[_ block]]
  823. (when-let [blocks (and block (db-model/get-block-immediate-children (state/get-current-repo) (:block/uuid block)))]
  824. (editor-handler/toggle-blocks-as-own-order-list! blocks)))
  825. (defmethod handle :editor/new-property [[_]]
  826. (p/do!
  827. (when-let [edit-block (state/get-edit-block)]
  828. (when-let [block-id (:block/uuid edit-block)]
  829. (let [block (db/entity [:block/uuid block-id])
  830. collapsed? (or (get-in @state/state [:ui/collapsed-blocks (state/get-current-repo) block-id])
  831. (:block/collapsed? block))]
  832. (when collapsed?
  833. (editor-handler/set-blocks-collapsed! [block-id] false)))))
  834. (editor-handler/save-current-block!)
  835. (property-handler/editing-new-property!)))
  836. (rum/defc multi-tabs-dialog
  837. []
  838. (let [word (if (util/electron?) "window" "tab")]
  839. [:div.flex.p-4.flex-col.gap-4.h-64
  840. [:span.warning.text-lg
  841. (util/format "Logseq doesn't support multiple %ss access to the same graph yet, please close this %s or switch to another graph."
  842. word word)]
  843. [:div.text-lg
  844. [:p "Switch to another repo: "]
  845. (repo/repos-dropdown {:on-click (fn [e]
  846. (util/stop e)
  847. (state/set-state! :error/multiple-tabs-access-opfs? false)
  848. (state/close-modal!))})]]))
  849. (defmethod handle :show/multiple-tabs-error-dialog [_]
  850. (state/set-state! :error/multiple-tabs-access-opfs? true)
  851. (state/set-modal! multi-tabs-dialog {:container-overflow-visible? true}))
  852. (defmethod handle :rtc/sync-state [[_ state]]
  853. (swap! rtc-debug-ui/debug-state (fn [old] (merge old state))))
  854. ;; db-worker -> UI
  855. (defmethod handle :db/sync-changes [[_ data]]
  856. (let [repo (state/get-current-repo)]
  857. (pipeline/invoke-hooks data)
  858. (when (util/electron?)
  859. (ipc/ipc :db-transact repo (pr-str (:tx-data data)) (pr-str (:tx-meta data))))
  860. nil))
  861. (defn run!
  862. []
  863. (let [chan (state/get-events-chan)]
  864. (async/go-loop []
  865. (let [[payload d] (async/<! chan)]
  866. (->
  867. (try
  868. (p/resolved (handle payload))
  869. (catch :default error
  870. (p/rejected error)))
  871. (p/then (fn [result]
  872. (p/resolve! d result)))
  873. (p/catch (fn [error]
  874. (let [type :handle-system-events/failed]
  875. (state/pub-event! [:capture-error {:error error
  876. :payload {:type type
  877. :payload payload}}])
  878. (p/reject! d error))))))
  879. (recur))
  880. chan))
  881. (comment
  882. (let [{:keys [deprecated-app-id current-app-id]} {:deprecated-app-id "AFDADF9A-7466-4ED8-B74F-AAAA0D4565B9", :current-app-id "7563518E-0EFD-4AD2-8577-10CFFD6E4596"}]
  883. (def deprecated-app-id deprecated-app-id)
  884. (def current-app-id current-app-id))
  885. (def deprecated-repo (state/get-current-repo))
  886. (def new-repo (string/replace deprecated-repo deprecated-app-id current-app-id))
  887. (update-file-path deprecated-repo new-repo deprecated-app-id current-app-id))