From d22de0257d85877f8fd07164fe3e17d93845f530 Mon Sep 17 00:00:00 2001 From: Tony Date: Thu, 3 Oct 2024 16:11:53 +0800 Subject: [PATCH] Use absolute path for store --- plugins/store/api-iife.js | 2 +- plugins/store/guest-js/index.ts | 25 ++++++++++++++++-------- plugins/store/src/lib.rs | 2 ++ plugins/store/src/store.rs | 34 ++++++++++++++------------------- 4 files changed, 34 insertions(+), 29 deletions(-) diff --git a/plugins/store/api-iife.js b/plugins/store/api-iife.js index cd3559d3..9b27a2dc 100644 --- a/plugins/store/api-iife.js +++ b/plugins/store/api-iife.js @@ -1 +1 @@ -if("__TAURI__"in window){var __TAURI_PLUGIN_STORE__=function(t){"use strict";var e,a;function r(t,e=!1){return window.__TAURI_INTERNALS__.transformCallback(t,e)}async function s(t,e={},a){return window.__TAURI_INTERNALS__.invoke(t,e,a)}"function"==typeof SuppressedError&&SuppressedError;class i{get rid(){return function(t,e,a,r){if("a"===a&&!r)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===a?r:"a"===a?r.call(t):r?r.value:e.get(t)}(this,e,"f")}constructor(t){e.set(this,void 0),function(t,e,a,r,s){if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");e.set(t,a)}(this,e,t)}async close(){return s("plugin:resources|close",{rid:this.rid})}}async function n(t,e,a){const i={kind:"Any"};return s("plugin:event|listen",{event:t,target:i,handler:r(e)}).then((e=>async()=>async function(t,e){await s("plugin:event|unlisten",{event:t,eventId:e})}(t,e)))}async function o(t,e){return await u.createStore(t,e)}async function c(t){return await u.getStore(t)}e=new WeakMap,function(t){t.WINDOW_RESIZED="tauri://resize",t.WINDOW_MOVED="tauri://move",t.WINDOW_CLOSE_REQUESTED="tauri://close-requested",t.WINDOW_DESTROYED="tauri://destroyed",t.WINDOW_FOCUS="tauri://focus",t.WINDOW_BLUR="tauri://blur",t.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",t.WINDOW_THEME_CHANGED="tauri://theme-changed",t.WINDOW_CREATED="tauri://window-created",t.WEBVIEW_CREATED="tauri://webview-created",t.DRAG_ENTER="tauri://drag-enter",t.DRAG_OVER="tauri://drag-over",t.DRAG_DROP="tauri://drag-drop",t.DRAG_LEAVE="tauri://drag-leave"}(a||(a={}));class u extends i{constructor(t,e){super(t),this.path=e}static async createStore(t,e){const a=await s("plugin:store|create_store",{path:t,...e});return new u(a,t)}static async getStore(t){const e=await s("plugin:store|get_store");return e?new u(e,t):void 0}async set(t,e){await s("plugin:store|set",{rid:this.rid,key:t,value:e})}async get(t){return await s("plugin:store|get",{rid:this.rid,key:t})}async has(t){return await s("plugin:store|has",{rid:this.rid,key:t})}async delete(t){return await s("plugin:store|delete",{rid:this.rid,key:t})}async clear(){await s("plugin:store|clear",{rid:this.rid})}async reset(){await s("plugin:store|reset",{rid:this.rid})}async keys(){return await s("plugin:store|keys",{rid:this.rid})}async values(){return await s("plugin:store|values",{rid:this.rid})}async entries(){return await s("plugin:store|entries",{rid:this.rid})}async length(){return await s("plugin:store|length",{rid:this.rid})}async load(){await s("plugin:store|load",{rid:this.rid})}async save(){await s("plugin:store|save",{rid:this.rid})}async onKeyChange(t,e){return await n("store://change",(a=>{a.payload.path===this.path&&a.payload.key===t&&e(a.payload.value)}))}async onChange(t){return await n("store://change",(e=>{e.payload.path===this.path&&t(e.payload.key,e.payload.value)}))}}return t.LazyStore=class{constructor(t,e){this.path=t,this.options=e}get store(){return this._store||(this._store=c(this.path).then((async t=>t||await o(this.path,this.options)))),this._store}async init(){await this.store}async set(t,e){return(await this.store).set(t,e)}async get(t){return(await this.store).get(t)}async has(t){return(await this.store).has(t)}async delete(t){return(await this.store).delete(t)}async clear(){await(await this.store).clear()}async reset(){await(await this.store).reset()}async keys(){return(await this.store).keys()}async values(){return(await this.store).values()}async entries(){return(await this.store).entries()}async length(){return(await this.store).length()}async load(){await(await this.store).load()}async save(){await(await this.store).save()}async onKeyChange(t,e){return(await this.store).onKeyChange(t,e)}async onChange(t){return(await this.store).onChange(t)}async close(){this._store&&await(await this._store).close()}},t.Store=u,t.createStore=o,t.getStore=c,t}({});Object.defineProperty(window.__TAURI__,"store",{value:__TAURI_PLUGIN_STORE__})} +if("__TAURI__"in window){var __TAURI_PLUGIN_STORE__=function(t){"use strict";var e,r;function a(t,e=!1){return window.__TAURI_INTERNALS__.transformCallback(t,e)}async function s(t,e={},r){return window.__TAURI_INTERNALS__.invoke(t,e,r)}"function"==typeof SuppressedError&&SuppressedError;class i{get rid(){return function(t,e,r,a){if("a"===r&&!a)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!a:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===r?a:"a"===r?a.call(t):a?a.value:e.get(t)}(this,e,"f")}constructor(t){e.set(this,void 0),function(t,e,r,a,s){if("function"==typeof e?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");e.set(t,r)}(this,e,t)}async close(){return s("plugin:resources|close",{rid:this.rid})}}async function n(t,e,r){const i={kind:"Any"};return s("plugin:event|listen",{event:t,target:i,handler:a(e)}).then((e=>async()=>async function(t,e){await s("plugin:event|unlisten",{event:t,eventId:e})}(t,e)))}async function o(t,e){return await u.createStore(t,e)}async function c(t){return await u.getStore(t)}e=new WeakMap,function(t){t.WINDOW_RESIZED="tauri://resize",t.WINDOW_MOVED="tauri://move",t.WINDOW_CLOSE_REQUESTED="tauri://close-requested",t.WINDOW_DESTROYED="tauri://destroyed",t.WINDOW_FOCUS="tauri://focus",t.WINDOW_BLUR="tauri://blur",t.WINDOW_SCALE_FACTOR_CHANGED="tauri://scale-change",t.WINDOW_THEME_CHANGED="tauri://theme-changed",t.WINDOW_CREATED="tauri://window-created",t.WEBVIEW_CREATED="tauri://webview-created",t.DRAG_ENTER="tauri://drag-enter",t.DRAG_OVER="tauri://drag-over",t.DRAG_DROP="tauri://drag-drop",t.DRAG_LEAVE="tauri://drag-leave"}(r||(r={}));class u extends i{constructor(t){super(t)}static async createStore(t,e){const r=await s("plugin:store|create_store",{path:t,...e});return new u(r)}static async getStore(t){const e=await s("plugin:store|get_store",{path:t});return e?new u(e):void 0}async set(t,e){await s("plugin:store|set",{rid:this.rid,key:t,value:e})}async get(t){return await s("plugin:store|get",{rid:this.rid,key:t})}async has(t){return await s("plugin:store|has",{rid:this.rid,key:t})}async delete(t){return await s("plugin:store|delete",{rid:this.rid,key:t})}async clear(){await s("plugin:store|clear",{rid:this.rid})}async reset(){await s("plugin:store|reset",{rid:this.rid})}async keys(){return await s("plugin:store|keys",{rid:this.rid})}async values(){return await s("plugin:store|values",{rid:this.rid})}async entries(){return await s("plugin:store|entries",{rid:this.rid})}async length(){return await s("plugin:store|length",{rid:this.rid})}async load(){await s("plugin:store|load",{rid:this.rid})}async save(){await s("plugin:store|save",{rid:this.rid})}async onKeyChange(t,e){return await n("store://change",(r=>{r.payload.resourceId===this.rid&&r.payload.key===t&&e(r.payload.value)}))}async onChange(t){return await n("store://change",(e=>{e.payload.resourceId===this.rid&&t(e.payload.key,e.payload.value)}))}}return t.LazyStore=class{constructor(t,e){this.path=t,this.options=e}get store(){return this._store||(this._store=c(this.path).then((async t=>t||await o(this.path,this.options)))),this._store}async init(){await this.store}async set(t,e){return(await this.store).set(t,e)}async get(t){return(await this.store).get(t)}async has(t){return(await this.store).has(t)}async delete(t){return(await this.store).delete(t)}async clear(){await(await this.store).clear()}async reset(){await(await this.store).reset()}async keys(){return(await this.store).keys()}async values(){return(await this.store).values()}async entries(){return(await this.store).entries()}async length(){return(await this.store).length()}async load(){await(await this.store).load()}async save(){await(await this.store).save()}async onKeyChange(t,e){return(await this.store).onKeyChange(t,e)}async onChange(t){return(await this.store).onChange(t)}async close(){this._store&&await(await this._store).close()}},t.Store=u,t.createStore=o,t.getStore=c,t}({});Object.defineProperty(window.__TAURI__,"store",{value:__TAURI_PLUGIN_STORE__})} diff --git a/plugins/store/guest-js/index.ts b/plugins/store/guest-js/index.ts index 47f15f34..69e40348 100644 --- a/plugins/store/guest-js/index.ts +++ b/plugins/store/guest-js/index.ts @@ -8,6 +8,7 @@ import { invoke, Resource } from '@tauri-apps/api/core' interface ChangePayload { path: string + resourceId?: number key: string value: T | null } @@ -143,8 +144,8 @@ export class LazyStore implements IStore { */ export class Store extends Resource implements IStore { private constructor( - rid: number, - private readonly path: string + rid: number + // private readonly path: string ) { super(rid) } @@ -159,19 +160,27 @@ export class Store extends Resource implements IStore { path: string, options?: StoreOptions ): Promise { - const resourceId = await invoke('plugin:store|create_store', { + const rid = await invoke('plugin:store|create_store', { path, ...options }) - return new Store(resourceId, path) + return new Store( + rid + // path + ) } /** * @param path: Path of the store in the rust side */ static async getStore(path: string): Promise { - const resourceId = await invoke('plugin:store|get_store') - return resourceId ? new Store(resourceId, path) : undefined + const rid = await invoke('plugin:store|get_store', { path }) + return rid + ? new Store( + rid + // path + ) + : undefined } async set(key: string, value: unknown): Promise { @@ -240,7 +249,7 @@ export class Store extends Resource implements IStore { cb: (value: T | null) => void ): Promise { return await listen>('store://change', (event) => { - if (event.payload.path === this.path && event.payload.key === key) { + if (event.payload.resourceId === this.rid && event.payload.key === key) { cb(event.payload.value) } }) @@ -250,7 +259,7 @@ export class Store extends Resource implements IStore { cb: (key: string, value: T | null) => void ): Promise { return await listen>('store://change', (event) => { - if (event.payload.path === this.path) { + if (event.payload.resourceId === this.rid) { cb(event.payload.key, event.payload.value) } }) diff --git a/plugins/store/src/lib.rs b/plugins/store/src/lib.rs index dbc53d5f..40f72aff 100644 --- a/plugins/store/src/lib.rs +++ b/plugins/store/src/lib.rs @@ -31,8 +31,10 @@ mod error; mod store; #[derive(Serialize, Clone)] +#[serde(rename_all = "camelCase")] struct ChangePayload<'a> { path: &'a Path, + resource_id: Option, key: &'a str, value: &'a JsonValue, } diff --git a/plugins/store/src/store.rs b/plugins/store/src/store.rs index 15c5f4ac..b2c4c23d 100644 --- a/plugins/store/src/store.rs +++ b/plugins/store/src/store.rs @@ -12,7 +12,7 @@ use std::{ sync::{Arc, Mutex}, time::Duration, }; -use tauri::{AppHandle, Emitter, Manager, Resource, ResourceId, Runtime}; +use tauri::{path::BaseDirectory, AppHandle, Emitter, Manager, Resource, ResourceId, Runtime}; use tokio::{ select, sync::mpsc::{unbounded_channel, UnboundedSender}, @@ -59,10 +59,15 @@ impl StoreBuilder { /// }); /// ``` pub fn new, P: AsRef>(manager: &M, path: P) -> Self { + let app = manager.app_handle().clone(); + let path = app + .path() + .resolve(path, BaseDirectory::AppData) + .expect("failed to resolve app dir"); Self { - app: manager.app_handle().clone(), + app, // Since Store.path is only exposed to the user in emit calls we may as well simplify it here already. - path: dunce::simplified(path.as_ref()).to_path_buf(), + path: dunce::simplified(&path).to_path_buf(), defaults: None, serialize_fn: default_serialize, deserialize_fn: default_deserialize, @@ -255,17 +260,10 @@ impl StoreInner { /// Saves the store to disk at the store's `path`. pub fn save(&self) -> crate::Result<()> { - let app_dir = self - .app - .path() - .app_data_dir() - .expect("failed to resolve app dir"); - let store_path = app_dir.join(&self.path); - - create_dir_all(store_path.parent().expect("invalid store path"))?; + create_dir_all(self.path.parent().expect("invalid store path"))?; let bytes = (self.serialize_fn)(&self.cache).map_err(crate::Error::Serialize)?; - let mut f = File::create(&store_path)?; + let mut f = File::create(&self.path)?; f.write_all(&bytes)?; Ok(()) @@ -273,14 +271,7 @@ impl StoreInner { /// Update the store from the on-disk state pub fn load(&mut self) -> crate::Result<()> { - let app_dir = self - .app - .path() - .app_data_dir() - .expect("failed to resolve app dir"); - let store_path = app_dir.join(&self.path); - - let bytes = read(store_path)?; + let bytes = read(&self.path)?; self.cache .extend((self.deserialize_fn)(&bytes).map_err(crate::Error::Deserialize)?); @@ -374,10 +365,13 @@ impl StoreInner { } fn emit_change_event(&self, key: &str, value: &JsonValue) -> crate::Result<()> { + let collection = self.app.state::(); + let stores = collection.stores.lock().unwrap(); self.app.emit( "store://change", ChangePayload { path: &self.path, + resource_id: stores.get(&self.path).copied(), key, value, },