From 8bb3823c5fa8f736e0c29ef492ed43b201e99eca Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Mon, 8 Jan 2018 08:03:59 +0000 Subject: [PATCH 01/85] First sketch of a Indexed DB API wrpper. --- examples/minimal/Cargo.toml | 2 + examples/minimal/src/main.rs | 80 +++- src/lib.rs | 22 ++ src/webapi/event.rs | 83 ++++ src/webapi/indexeddb.rs | 686 +++++++++++++++++++++++++++++++++ src/webapi/mod.rs | 1 + src/webapi/window.rs | 11 + src/webapi/window_or_worker.rs | 1 + 8 files changed, 882 insertions(+), 4 deletions(-) create mode 100644 src/webapi/indexeddb.rs diff --git a/examples/minimal/Cargo.toml b/examples/minimal/Cargo.toml index a6db8ae6..375d5f63 100644 --- a/examples/minimal/Cargo.toml +++ b/examples/minimal/Cargo.toml @@ -5,3 +5,5 @@ authors = ["Jan Bujak "] [dependencies] stdweb = { path = "../.." } +serde="*" +serde_derive="*" \ No newline at end of file diff --git a/examples/minimal/src/main.rs b/examples/minimal/src/main.rs index 365964df..10f376cd 100644 --- a/examples/minimal/src/main.rs +++ b/examples/minimal/src/main.rs @@ -1,13 +1,85 @@ #[macro_use] extern crate stdweb; +#[macro_use] +extern crate serde_derive; + +extern crate serde; + +use std::collections::HashMap; + +use stdweb::Value; + +use stdweb::web::{ + window, + IEventTarget, + EventTarget +}; + +use stdweb::web::event::{ConcreteEvent, IEvent}; + +use stdweb::web::event::{ + IDBSuccessEvent, + IDBVersionChangeEvent, + IDBCompleteEvent +}; + +use stdweb::web::indexeddb::{ + IDBOpenDBRequest, + IDBDatabase, + IDBRequest, + DBRequest +}; + +use stdweb::unstable::TryInto; + +#[derive(Serialize, Deserialize)] +struct Customer { + ssn: String, + name: String, + age: i32, + email: String +} + +js_serializable!( Customer ); +js_deserializable!( Customer ); + fn main() { stdweb::initialize(); - let message = "Hello, 世界!"; - js! { - alert( @{message} ); - } + let request = window().indexed_db().open("db", None); + + request.add_event_listener( |event: IDBVersionChangeEvent| { + let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); + let db: IDBDatabase = db_request.result().try_into().unwrap(); + + let mut store_options = HashMap::new(); + store_options.insert("keyPath", "ssn"); + let object_store = db.create_object_store("customers", Value::from(store_options)); + + let mut name_options = HashMap::new(); + name_options.insert("unique", false); + object_store.create_index("name", "name", Value::from(name_options)); + + let mut email_options = HashMap::new(); + email_options.insert("unique", true); + object_store.create_index("email", "email", Value::from(email_options)); + + object_store.transaction().add_event_listener( move |event: IDBCompleteEvent| { + + let customers = vec![ + Customer{ ssn: "444-44-4444".to_string(), name: "Bill".to_string(), age: 35, email: "bill@company.com".to_string() }, + Customer{ ssn: "555-55-5555".to_string(), name: "Donna".to_string(), age: 32, email: "donna@home.org".to_string() } + ]; + + let customer_object_store = db.transaction("customers", "readwrite").object_store("customers"); + for customer in &customers { + customer_object_store.add(customer.try_into().unwrap(), None); + } + }); + + }); + stdweb::event_loop(); } diff --git a/src/lib.rs b/src/lib.rs index fd3e3fd7..9c766996 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -117,6 +117,25 @@ pub mod serde { /// A module with bindings to the Web APIs. pub mod web { + + /// This is a module + pub mod indexeddb { + pub use webapi::indexeddb::{ + IDBOpenDBRequest, + IDBDatabase, + IDBRequest, + DBRequest, + IDBIndex, + IDBObjectStore, + IDBTransaction, + IDBFactory, + IDBObjectStoreIndexSharedMethods, + IDBCursorDirection, + IDBRequestReadyState, + IDBCursor + }; + } + pub use webapi::window::{ Window, window @@ -201,6 +220,9 @@ pub mod web { ProgressErrorEvent, InputEvent, ReadyStateChange, + IDBSuccessEvent, + IDBVersionChangeEvent, + IDBCompleteEvent }; } } diff --git a/src/webapi/event.rs b/src/webapi/event.rs index 616d6876..c44d1823 100644 --- a/src/webapi/event.rs +++ b/src/webapi/event.rs @@ -1121,6 +1121,89 @@ impl ConcreteEvent for ReadyStateChange { const EVENT_TYPE: &'static str = "readystatechange"; } +/// The `IDBSuccessEvent` handler is fired when a and Indexed DB request succeed. +/// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/Events/success) +pub struct IDBSuccessEvent( Reference ); + +reference_boilerplate! { + IDBSuccessEvent, + instanceof Event + convertible to Event +} + +impl IEvent for IDBSuccessEvent {} + +impl ConcreteEvent for IDBSuccessEvent { + const EVENT_TYPE: &'static str = "success"; +} + +/// This event is fired if a new verion of a database has been requested. +/// +/// [(JavaScript docs)](https://www.w3.org/TR/IndexedDB/#events) +pub struct IDBVersionChangeEvent( Reference ); + +reference_boilerplate! { + IDBVersionChangeEvent, + instanceof Event + convertible to Event +} + +impl IEvent for IDBVersionChangeEvent {} + +impl ConcreteEvent for IDBVersionChangeEvent { + const EVENT_TYPE: &'static str = "upgradeneeded"; +} + +impl IDBVersionChangeEvent { + // readonly attribute unsigned long long oldVersion; + /// Returns the previous version of the database. + pub fn old_version( &self ) -> u64 { + js! ( + return @{self.as_ref()}.oldVersion; + ).try_into().unwrap() + } + + // readonly attribute unsigned long long? newVersion; + /// Returns the new version of the database, or null if the database is being deleted. + pub fn new_version( &self ) -> Option { + js! ( + return @{self.as_ref()}.newVersion; + ).try_into().unwrap() + } + +} + +/// +pub struct IDBCompleteEvent( Reference ); + +reference_boilerplate! { + IDBCompleteEvent, + instanceof Event + convertible to Event +} + +impl IEvent for IDBCompleteEvent {} + +impl ConcreteEvent for IDBCompleteEvent { + const EVENT_TYPE: &'static str = "complete"; +} + +/// +pub struct IDBErrorEvent( Reference ); + +reference_boilerplate! { + IDBErrorEvent, + instanceof Event + convertible to Event +} + +impl IEvent for IDBErrorEvent {} + +impl ConcreteEvent for IDBErrorEvent { + const EVENT_TYPE: &'static str = "error"; +} + #[cfg(all(test, feature = "web_test"))] mod tests { use super::*; diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs new file mode 100644 index 00000000..b6dcdeec --- /dev/null +++ b/src/webapi/indexeddb.rs @@ -0,0 +1,686 @@ +use webcore::value::Value; +use webcore::value::Reference; +use webcore::try_from::TryInto; +use webapi::event_target::IEventTarget; +use webapi::event::{ConcreteEvent, IEvent}; + +/// +#[derive(Debug)] +pub enum IDBRequestReadyState { + /// + Pending, + /// + Done +} + +/// This is a trait +pub trait IDBRequest : IEventTarget { + + //readonly attribute any result; + /// This is a trait method + fn result( &self ) -> Value { + js! ( + return @{self.as_ref()}.result; + ) + } + + /*fn error(&self) -> DOMException { + +}*/ + + //readonly attribute (IDBObjectStore or IDBIndex or IDBCursor)? source; + + //readonly attribute IDBTransaction? transaction; + /// + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/transaction) + fn transaction( &self ) -> Option { + let transaction : Value = js! ( + return @{self.as_ref()}.transaction; + ); + match transaction { + Undefined => None, + Null => None, + _ => Some(transaction.try_into().unwrap()) + } + } + + //readonly attribute IDBRequestReadyState readyState; + /// + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/readyState) + fn ready_state( &self ) -> IDBRequestReadyState { + let ready_state : String = js! ( + return @{self.as_ref()}.readyState; + ).try_into().unwrap(); + + if ready_state.eq("pending") { + return IDBRequestReadyState::Pending; + } else if ready_state.eq("done") { + return IDBRequestReadyState::Done; + } else { + panic!("Got {} as an IDBRequestReadyState.", ready_state); + } + + } + + // Event handlers: + //attribute EventHandler onsuccess; + //attribute EventHandler onerror; + +} + +/// This is a struct +pub struct DBRequest( Reference ); + +impl IEventTarget for DBRequest {} +impl IDBRequest for DBRequest {} + +reference_boilerplate! { + DBRequest, + instanceof IDBRequest +} + +/// Provides access to the results of requests to open or delete databases. +/// Receives `IDBBlockedEvent` and `IDBVersionChangeEvent` as well as events received by `IDBRequest`. +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest) +pub struct IDBOpenDBRequest( Reference ); + +impl IEventTarget for IDBOpenDBRequest {} +impl IDBRequest for IDBOpenDBRequest {} + + +reference_boilerplate! { + IDBOpenDBRequest, + instanceof IDBOpenDBRequest +} + +/// The `IDBFactory` interface of the IndexedDB API lets applications asynchronously access the indexed databases. The object that implements the interface is `window.indexedDB`. +/// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory) +pub struct IDBFactory( Reference ); + +impl IDBFactory { + + /// Requests opening a connection to a database. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/open) + pub fn open>>( &self, name: &str, version: T) -> IDBOpenDBRequest { + match version.into() { + None => js! ( + return @{self.as_ref()}.open(@{name}); + ).try_into().unwrap(), + Some(version) => js! ( + return @{self.as_ref()}.open(@{name}, @{version}); + ).try_into().unwrap() + } + } + + + + /// Requests the deletion of a database. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/deleteDatabase) + pub fn delete_database( &self, name: &str) -> IDBOpenDBRequest { + js! ( + return @{self.as_ref()}.deleteDatabase(@{name}); + ).try_into().unwrap() + } + + /// Compares two values as keys to determine equality and ordering for `IndexedDB` operations. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/cmp) + pub fn cmp( &self, first: Value, second: Value) -> i16 { + js!( + return @{self.as_ref()}.cmp(@{first.as_ref()}, @{second.as_ref()}); + ).try_into().unwrap() + } + +} + +reference_boilerplate! { + IDBFactory, + instanceof IDBFactory +} + +/// +#[derive(Debug)] +pub enum IDBCursorDirection { + /// + Next, + /// + NextUnique, + /// + Prev, + /// + PrevUnique +} + +fn cursor_direction_to_string( direction: IDBCursorDirection) -> String { + match direction { + Next => "next".to_string(), + NextUnique => "nextunique".to_string(), + Prev => "prev".to_string(), + PrevUnique => "prevunique".to_string() + } +} + +fn string_to_cursor_direction( direction: &str) -> IDBCursorDirection { + if direction.eq("next") { + return IDBCursorDirection::Next; + } else if direction.eq("nextunique") { + return IDBCursorDirection::NextUnique; + } else if direction.eq("prev") { + return IDBCursorDirection::Prev; + } else if direction.eq("prevunique") { + return IDBCursorDirection::PrevUnique; + } else { + unreachable!("Unknown index direction \"{}\".", direction); + } +} + +/// +pub struct IDBCursor( Reference ); + +impl IDBCursor { + //readonly attribute (IDBObjectStore or IDBIndex) source; + + //readonly attribute IDBCursorDirection direction; + // /// + // /// + // /// + // pub fn direction( &self ) -> IDBCursorDirection { + // string_to_cursor_direction(js! ( return @{self.as_ref()}.direction; ).try_into().unwrap()) + //} + + // Todo, not sure what I'm doing with these two + //readonly attribute any key; + //readonly attribute any primaryKey; + + //void advance([EnforceRange] unsigned long count); + /// + /// + /// + pub fn advance( &self, count: u32) { + js! { @{self.as_ref()}.advance(@{count}); } + } + + //void continue(optional any key); + /// + /// + /// + pub fn advance_to_match>>( &self, key: K) { + match key.into() { + None => js! { @{self.as_ref()}.continue(); }, + Some(key) => js! { @{self.as_ref()}.continue(@{key.as_ref()}); } + }; + } + + //void continuePrimaryKey(any key, any primaryKey); + + //[NewObject] IDBRequest update(any value); + /// + /// + /// + pub fn update( &self, value: Value) -> DBRequest { + js! ( return @{self}.update(@{value.as_ref()}); ).try_into().unwrap() + } + + //[NewObject] IDBRequest delete(); + /// + /// + /// + pub fn delete( &self ) -> DBRequest { + js!( return @{self}.delete(); ).try_into().unwrap() + } +} + +reference_boilerplate! { + IDBCursor, + instanceof IDBCursor +} + +/// This trait contains mothods that are Identicle in both IDBIndex IDBObjectStore +pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { + + // attribute DOMString name; + /// Returns the name of this object store. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/name) + fn name( &self ) -> String { + js! ( + return @{self.as_ref()}.name; + ).try_into().unwrap() + } + + /// Returns the name of this object store. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/name) + fn set_name( &self, name: &str) { + js! { + @{self.as_ref()}.name = @{name}; + }; + } + + // [NewObject] IDBRequest get(any query); + /// This is for retrieving specific records from an object store. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/get) + fn get( &self, query: Value) -> DBRequest { + js! ( + return @{self.as_ref()}.get(@{query.as_ref()}); + ).try_into().unwrap() + } + + // [NewObject] IDBRequest getKey(any query); + /// This is for retrieving specific records from an object store. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getKey) + fn get_key( &self, query: Value) -> DBRequest { + js! ( + return @{self.as_ref()}.getKey(@{query.as_ref()}); + ).try_into().unwrap() + } + + // [NewObject] IDBRequest getAll(optional any query, optional [EnforceRange] unsigned long count); + /// + /// + /// + fn get_all>, C: Into>>( &self, query: Q, count: C) -> DBRequest { + match query.into() { + None => js! ( return @{self.as_ref()}.getAll(); ), + Some(query) => { + match count.into() { + None => js! ( return @{self.as_ref()}.getAll(@{query.as_ref()}); ), + Some(count) => js! ( return @{self.as_ref()}.getAll(@{query.as_ref()}, @{count}); ) + } + } + }.try_into().unwrap() + } + + + // [NewObject] IDBRequest getAllKeys(optional any query, optional [EnforceRange] unsigned long count); + /// + /// + /// + fn get_all_keys>, C: Into>>( &self, query: Q, count: C) -> DBRequest { + match query.into() { + None => js! ( return @{self.as_ref()}.getAllKeys(); ), + Some(query) => { + match count.into() { + None => js! ( return @{self.as_ref()}.getAllKeys(@{query.as_ref()}); ), + Some(count) => js! ( return @{self.as_ref()}.getAllKeys(@{query.as_ref()}, @{count}); ) + } + } + }.try_into().unwrap() + } + + // [NewObject] IDBRequest count(optional any query); + /// + /// + /// + fn count>>( &self, query: Q) -> DBRequest { + match query.into() { + None => js! ( + return @{self.as_ref()}.count(); + ), + Some(query) => js! ( + return @{self.as_ref()}.count(@{query.as_ref()}); + ) + }.try_into().unwrap() + } + + // [NewObject] IDBRequest openCursor(optional any query, optional IDBCursorDirection direction = "next"); + /// + /// + /// + fn open_cursor>, D: Into>>( &self, query: Q, direction: D) -> DBRequest { + match query.into() { + None => js! ( return @{self.as_ref()}.openCursor(); ), + Some(query) => { + match direction.into() { + None => js! ( return @{self.as_ref()}.openCursor(@{query.as_ref()}); ), + Some(direction) => js! ( return @{self.as_ref()}.openCursor(@{query.as_ref()}, @{cursor_direction_to_string(direction)}); ) + } + } + }.try_into().unwrap() + } + + // [NewObject] IDBRequest openKeyCursor(optional any query, optional IDBCursorDirection direction = "next"); + /// + /// + /// + fn open_key_cursor>, D: Into>>( &self, query: Q, direction: D) -> DBRequest { + match query.into() { + None => js! ( return @{self.as_ref()}.openKeyCursor(); ), + Some(query) => { + match direction.into() { + None => js! ( return @{self.as_ref()}.openKeyCursor(@{query.as_ref()}); ), + Some(direction) => js! ( return @{self.as_ref()}.openKeyCursor(@{query.as_ref()}, @{cursor_direction_to_string(direction)}); ) + } + } + }.try_into().unwrap() + } + +} + +/// Provides asynchronous access to an index in a database. +/// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex) +pub struct IDBIndex( Reference ); + +impl IDBObjectStoreIndexSharedMethods for IDBIndex {} + +impl IDBIndex { + //attribute DOMString name; + // Implemented in trait. + + //[SameObject] readonly attribute IDBObjectStore objectStore; + //readonly attribute any keyPath; + + //readonly attribute boolean multiEntry; + /// Affects how the index behaves when the result of evaluating the index's key path yields an array. If `true`, there is one record in the index for each item in an array of keys. If `false`, then there is one record for each key that is an array. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/multiEntry) + pub fn multi_entry( &self ) -> bool { + js! ( + return @{self.as_ref()}.multiEntry; + ).try_into().unwrap() + } + + //readonly attribute boolean unique; + /// If `true`, this index does not allow duplicate values for a key. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/unique) + pub fn unique( &self ) -> bool { + js! ( + return @{self.as_ref()}.unique; + ).try_into().unwrap() + } + + // The rest of this is implemented in the trait + //[NewObject] IDBRequest get(any query); + //[NewObject] IDBRequest getKey(any query); + //[NewObject] IDBRequest getAll(optional any query, optional [EnforceRange] unsigned long count); + //[NewObject] IDBRequest getAllKeys(optional any query, optional [EnforceRange] unsigned long count); + //[NewObject] IDBRequest count(optional any query); + //[NewObject] IDBRequest openCursor(optional any query, optional IDBCursorDirection direction = "next"); + //[NewObject] IDBRequest openKeyCursor(optional any query, optional IDBCursorDirection direction = "next"); +} + +reference_boilerplate! { + IDBIndex, + instanceof IDBIndex +} + +/// The `IDBObjectStore` interface of the IndexedDB API represents an object store in a database +/// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore) +pub struct IDBObjectStore( Reference ); + +impl IDBObjectStoreIndexSharedMethods for IDBObjectStore {} + +impl IDBObjectStore { + + + // readonly attribute any keyPath; + // Todo, how am I wrapping this. + + // readonly attribute DOMStringList indexNames; + // TODO: how am I wrapping this + + // [SameObject] readonly attribute IDBTransaction transaction; + /// The `IDBTransaction` object to which this object store belongs. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/transaction) + pub fn transaction( &self ) -> IDBTransaction { + js! ( + return @{self.as_ref()}.transaction; + ).try_into().unwrap() + } + + // readonly attribute boolean autoIncrement; + /// Returns the value of the auto increment flag for this object store. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/autoIncrement) + fn auto_increment( &self ) -> bool { + js! ( + return @{self.as_ref()}.autoIncrement; + ).try_into().unwrap() + } + + // [NewObject] IDBRequest put(any value, optional any key); + /// Updates a given record in a database, or inserts a new record if the given item does not already exist. + /// The key is only needed if + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put) + pub fn put>>( &self, value: Value, key: T) -> DBRequest { + match key.into() { + None => js! ( + return @{self.as_ref()}.put(@{value.as_ref()}); + ), + Some(key) => js! ( + return @{self.as_ref()}.put(@{value.as_ref()}, @{key.as_ref()}); + ) + }.try_into().unwrap() + } + + // [NewObject] IDBRequest add(any value, optional any key); + /// Returns an `IDBRequest` object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add) + pub fn add>>( &self, value: Value, key: T) -> DBRequest { + match key.into() { + None => js! ( + return @{self.as_ref()}.add(@{value.as_ref()}); + ), + Some(key) => js! ( + return @{self.as_ref()}.add(@{value.as_ref()}, @{key.as_ref()}); + ) + }.try_into().unwrap() + } + + // [NewObject] IDBRequest delete(any query); + /// returns an `IDBRequest` object, and, in a separate thread, deletes the specified record or records. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete) + pub fn delete( &self, query: Value) -> DBRequest { + js! ( + return @{self.as_ref()}.delete(@{query.as_ref()}); + ).try_into().unwrap() + } + + // [NewObject] IDBRequest clear(); + /// Returns an IDBRequest object, and clears this object store in a separate thread + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/clear) + pub fn clear( &self ) -> DBRequest { + js! ( + return @{self.as_ref()}.clear(); + ).try_into().unwrap() + } + + // IDBIndex index(DOMString name); + /// opens a named index in the current object store + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/index) + pub fn index( &self, name: &str) -> IDBIndex { + js! ( + return @{self.as_ref()}.index(@{name}); + ).try_into().unwrap() + } + + // [NewObject] IDBIndex createIndex(DOMString name, (DOMString or sequence) keyPath, optional IDBIndexParameters options); + /// Creates and returns a new `IDBIndex` object in the connected database. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex) + pub fn create_index( &self, name: &str, key_path: &str, options: Value) -> IDBIndex { // TODO, how am I doing the optinal options? + js! ( + return @{self.as_ref()}.createIndex(@{name}, @{key_path}, @{options.as_ref()}); + ).try_into().unwrap() + } + + // void deleteIndex(DOMString name); + /// Destroys the index with the specified name in the connected database, used during a version upgrade. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/deleteIndex) + fn delete_index( &self, name: &str) { + js! { + return @{self.as_ref()}.deleteIndex(@{name}); + } + } +} + +reference_boilerplate! { + IDBObjectStore, + instanceof IDBObjectStore +} + +/* dictionary IDBIndexParameters { + boolean unique = false; + boolean multiEntry = false; +};*/ + + +pub enum IDBTransactionMode { + ReadOnly, + Readwrite, + VersionChange +} + +/// The `IDBTransaction` interface of the IndexedDB API provides a static, asynchronous transaction on a database using event handlers. +/// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction) +pub struct IDBTransaction( Reference ); + +impl IEventTarget for IDBTransaction {} + +impl IDBTransaction { + // readonly attribute DOMStringList objectStoreNames; + // Todo, how am I wrapping DOMStringList + + // readonly attribute IDBTransactionMode mode; + // Todo, should I use an enum or a string + + // [SameObject] readonly attribute IDBDatabase db; + /// Returns the database connection with which this transaction is associated. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/db) + pub fn db( &self ) -> IDBDatabase { + js! ( + return @{self}.db(); + ).try_into().unwrap() + } + + // readonly attribute DOMException error; + + // IDBObjectStore objectStore(DOMString name); + /// This is a method + pub fn object_store( &self, name: &str) -> IDBObjectStore { + js! ( + return @{self.as_ref()}.objectStore(@{name}); + ).try_into().unwrap() + } + + // void abort(); + // Todo, do I need to implement this or do I get it for free from IEventTarget + // /// + // /// + // /// [(JavaScript docs)] + + // Event handlers: + // attribute EventHandler onabort; + // attribute EventHandler oncomplete; + // attribute EventHandler onerror; +} + +reference_boilerplate! { + IDBTransaction, + instanceof IDBTransaction +} + +/// The `IDBDatabase` interface of the IndexedDB API provides a connection to a database. +/// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase) +pub struct IDBDatabase( Reference ); + +impl IEventTarget for IDBDatabase {} + +impl IDBDatabase { + + // readonly attribute DOMString name; + /// Returns the the name of the connected database. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/name) + pub fn name( &self ) -> String { + js! ( + return @{self.as_ref()}.name; + ).try_into().unwrap() + } + + // readonly attribute unsigned long long version; + /// Returns the version of the connected database. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/version) + pub fn version( &self ) -> u64 { + js! ( + return @{self.as_ref()}.version; + ).try_into().unwrap() + } + + // readonly attribute DOMStringList objectStoreNames; + // TODO: how should I expose DomStringList + + // [NewObject] IDBTransaction transaction((DOMString or sequence) storeNames, optional IDBTransactionMode mode = "readonly"); + /// Immediately returns a transaction object (`IDBTransaction`) containing the `IDBTransaction.object_store` method, which you can use to access your object store. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/transaction) + pub fn transaction( &self, store_name: &str, mode: &str) -> IDBTransaction { + js! ( + //return @{self.as_ref()}.transaction(@{store_name}, @{mode}); + return @{self.as_ref()}.transaction("customers", "readwrite"); + ).try_into().unwrap() + } + + //void close(); + /// Returns immediately and closes the connection in a separate thread. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/close) + pub fn close( &self ) { + js! { + @{self.as_ref()}.close(); + } + } + + // [NewObject] IDBObjectStore createObjectStore(DOMString name, optional IDBObjectStoreParameters options); + /// Creates and returns a new object store or index. TODO: why does this say index + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/createObjectStore) + pub fn create_object_store( &self, name: &str, options: Value) -> IDBObjectStore { + js! ( + return @{self.as_ref()}.createObjectStore(@{name}, @{options.as_ref()}); + ).try_into().unwrap() + } + + // void deleteObjectStore(DOMString name); + /// Destroys the object store with the given name. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/deleteObjectStore) + pub fn delete_object_store( &self, name: &str ) { + js! { + @{self.as_ref()}.deleteObjectStore(@{name}); + } + } + + // Event handlers: + // attribute EventHandler onabort; + // attribute EventHandler onclose; + // attribute EventHandler onerror; + // attribute EventHandler onversionchange; + +} + +reference_boilerplate! { + IDBDatabase, + instanceof IDBDatabase +} diff --git a/src/webapi/mod.rs b/src/webapi/mod.rs index 8b62513d..66744f42 100644 --- a/src/webapi/mod.rs +++ b/src/webapi/mod.rs @@ -24,3 +24,4 @@ pub mod array_buffer; pub mod typed_array; /// A module containing XMLHttpRequest and its ReadyState pub mod xml_http_request; +pub mod indexeddb; diff --git a/src/webapi/window.rs b/src/webapi/window.rs index 0616d19a..84efbd18 100644 --- a/src/webapi/window.rs +++ b/src/webapi/window.rs @@ -5,6 +5,9 @@ use webapi::storage::Storage; use webapi::location::Location; use webcore::once::Once; use webcore::value::Value; +use webcore::try_from::TryInto; +use webapi::indexeddb::IDBFactory; + /// A handle to a pending animation frame request. #[derive(Debug)] @@ -126,4 +129,12 @@ impl Window { }; RequestAnimationFrameHandle(values) } + + /// This is a method + pub fn indexed_db( &self ) -> IDBFactory { + js! ( + return window.indexedDB; + ).try_into().unwrap() + } + } diff --git a/src/webapi/window_or_worker.rs b/src/webapi/window_or_worker.rs index e98d8787..3380240b 100644 --- a/src/webapi/window_or_worker.rs +++ b/src/webapi/window_or_worker.rs @@ -24,4 +24,5 @@ pub trait IWindowOrWorker: AsRef< Reference > { }, $3 );\ ", self.as_ref().as_raw(), funcall_adapter::< F > as extern fn( *mut F ), callback, timeout ); } + } From 61b3a1887602c70296305772db3d85053c710b04 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Sun, 20 May 2018 20:52:57 +0100 Subject: [PATCH 02/85] start of indexeddb example --- examples/Cargo.toml | 2 +- examples/indexeddb/Cargo.toml | 9 ++ examples/indexeddb/src/main.rs | 184 +++++++++++++++++++++++++++ examples/indexeddb/static/index.html | 60 +++++++++ examples/indexeddb/static/style.css | 35 +++++ src/lib.rs | 3 +- src/webapi/indexeddb.rs | 2 + 7 files changed, 293 insertions(+), 2 deletions(-) create mode 100644 examples/indexeddb/Cargo.toml create mode 100644 examples/indexeddb/src/main.rs create mode 100644 examples/indexeddb/static/index.html create mode 100644 examples/indexeddb/static/style.css diff --git a/examples/Cargo.toml b/examples/Cargo.toml index 9d91ec5b..87e3a2b1 100644 --- a/examples/Cargo.toml +++ b/examples/Cargo.toml @@ -1,2 +1,2 @@ [workspace] -members = ["canvas", "echo", "hasher", "minimal", "todomvc", "webgl"] +members = ["canvas", "echo", "hasher", "minimal", "todomvc", "webgl", "indexeddb"] diff --git a/examples/indexeddb/Cargo.toml b/examples/indexeddb/Cargo.toml new file mode 100644 index 00000000..be6e5e61 --- /dev/null +++ b/examples/indexeddb/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "indexeddb_example" +version = "0.1.0" +authors = ["Joe Jones "] + +[dependencies] +stdweb = { path = "../.." } +serde="*" +serde_derive="*" diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs new file mode 100644 index 00000000..63d3169f --- /dev/null +++ b/examples/indexeddb/src/main.rs @@ -0,0 +1,184 @@ +#[macro_use] +extern crate stdweb; + +#[macro_use] +extern crate serde_derive; + +extern crate serde; + +use std::collections::HashMap; +use std::cell::RefCell; + +use stdweb::Value; + +use stdweb::traits::*; +use stdweb::web::{ + HtmlElement, + Element, + window, + document, + IEventTarget, + EventTarget +}; + +use stdweb::web::event::{ConcreteEvent, IEvent}; + +use stdweb::web::event::{ + IDBSuccessEvent, + IDBVersionChangeEvent, + IDBCompleteEvent, + IDBErrorEvent +}; + +use stdweb::web::indexeddb::{ + IDBOpenDBRequest, + IDBDatabase, + IDBRequest, + DBRequest, + IDBObjectStore, + IDBObjectStoreIndexSharedMethods +}; + +use stdweb::unstable::TryInto; + +#[derive(Serialize, Deserialize)] +struct Note { + title: String, + body: String +} + +js_serializable!( Note ); +js_deserializable!( Note ); + +fn main() { + stdweb::initialize(); + + let title_input = document().query_selector("#title").unwrap().unwrap(); + let body_input = document().query_selector("#body").unwrap().unwrap(); + let form = document().query_selector("form").unwrap().unwrap(); + let submit_btn = document().query_selector("form button"); + + let db: RefCell> = RefCell::new(None); + + // Open our database; it is created if it doesn't already exist + // (see onupgradeneeded below) + let request = window().indexed_db().open("notes", 1); + + // onerror handler signifies that the database didn't open successfully + request.add_event_listener( |event: IDBErrorEvent| { + js!( + console.log("Database failed to open"); + ); + }); + + // onsuccess handler signifies that the database opened successfully + request.add_event_listener( |event: IDBSuccessEvent| { + js!( + console.log("Database opened succesfully"); + ); + + let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); + // Store the opened database object in the db variable. This is used a lot below + let db_ : IDBDatabase = db_request.result().try_into().unwrap(); + + //db.replace(Some(db_)); + // Run the displayData() function to display the notes already in the IDB + display_data(db_); + }); + + request.add_event_listener( |event: IDBVersionChangeEvent| { + let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); + let db: IDBDatabase = db_request.result().try_into().unwrap(); + + // Create an objectStore to store our notes in (basically like a single table) + // including a auto-incrementing key + let mut store_options = HashMap::new(); + store_options.insert("keyPath", "id"); + store_options.insert("autoIncrement", "true"); + let object_store = db.create_object_store("notes", Value::from(store_options)); + + // Define what data items the objectStore will contain + let mut title_options = HashMap::new(); + title_options.insert("unique", false); + object_store.create_index("title", "title", Value::from(title_options)); + + let mut body_options = HashMap::new(); + body_options.insert("unique", false); + object_store.create_index("body", "body", Value::from(body_options)); + + js!( + console.log("Database setup complete"); + ); + + }); + + // Define the displayData() function + fn display_data(db: IDBDatabase) { + let list = document().query_selector("ul").unwrap().unwrap(); + + // Here we empty the contents of the list element each time the display is updated + // If you ddn't do this, you'd get duplicates listed each time a new note is added + while list.first_child().is_some() { + list.remove_child(&list.first_child().unwrap()); + } + + // Open our object store and then get a cursor - which iterates through all the + // different data items in the store + let object_store = db.transaction("notes", "readonly").object_store("notes"); + + object_store.open_cursor(None, None) + .add_event_listener( |e: IDBSuccessEvent| { + + // Get a reference to the cursor + + let cursor = e.target(); + + //.result; +/* + // If there is still another data item to iterate through, keep running this code + if(cursor) { + // Create a list item, h3, and p to put each data item inside when displaying it + // structure the HTML fragment, and append it inside the list + let listItem = document.createElement('li'); + let h3 = document.createElement('h3'); + let para = document.createElement('p'); + + listItem.appendChild(h3); + listItem.appendChild(para); + list.appendChild(listItem); + + // Put the data from the cursor inside the h3 and para + h3.textContent = cursor.value.title; + para.textContent = cursor.value.body; + + // Store the ID of the data item inside an attribute on the listItem, so we know + // which item it corresponds to. This will be useful later when we want to delete items + listItem.setAttribute('data-note-id', cursor.value.id); + + // Create a button and place it inside each listItem + let deleteBtn = document.createElement('button'); + listItem.appendChild(deleteBtn); + deleteBtn.textContent = 'Delete'; + + // Set an event handler so that when the button is clicked, the deleteItem() + // function is run + deleteBtn.onclick = deleteItem; + + // Iterate to the next item in the cursor + cursor.continue(); + } else { + // Again, if list item is empty, display a 'No notes stored' message + if(!list.firstChild) { + let listItem = document.createElement('li'); + listItem.textContent = 'No notes stored.' + list.appendChild(listItem); + } + // if there are no more cursor items to iterate through, say so + console.log('Notes all displayed'); + } +*/ + }); + + + } +} diff --git a/examples/indexeddb/static/index.html b/examples/indexeddb/static/index.html new file mode 100644 index 00000000..d7d18dc6 --- /dev/null +++ b/examples/indexeddb/static/index.html @@ -0,0 +1,60 @@ + + + + + IndexedDB demo + + + + + +
+

IndexedDB notes demo

+
+ +
+
+

Notes

+
    + +
+
+
+

Enter a new note

+
+
+ + +
+
+ + +
+
+ +
+
+
+
+ +
+

Copyright nobody. Use the code as you like.

+
+ + diff --git a/examples/indexeddb/static/style.css b/examples/indexeddb/static/style.css new file mode 100644 index 00000000..4893c292 --- /dev/null +++ b/examples/indexeddb/static/style.css @@ -0,0 +1,35 @@ +html { + font-family: sans-serif; +} + +body { + margin: 0 auto; + max-width: 800px; +} + +header, footer { + background-color: green; + color: white; + line-height: 100px; + padding: 0 20px; +} + +.new-note, .note-display { + padding: 20px; +} + +.new-note { + background: #ddd; +} + +h1 { + margin: 0; +} + +ul { + list-style-type: none; +} + +div { + margin-bottom: 10px; +} diff --git a/src/lib.rs b/src/lib.rs index 739affa3..56712ec6 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -383,7 +383,8 @@ pub mod web { pub use webapi::events::indexeddb:: { IDBSuccessEvent, IDBVersionChangeEvent, - IDBCompleteEvent + IDBCompleteEvent, + IDBErrorEvent }; } } diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 9dc220b5..db949b4f 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -99,6 +99,8 @@ impl IDBFactory { /// Requests opening a connection to a database. /// + /// version can be None. + /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/open) pub fn open>>( &self, name: &str, version: T) -> IDBOpenDBRequest { match version.into() { From 4c7c2edf91494fc879c9256e3c729026aa3f7329 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Mon, 21 May 2018 21:20:48 +0100 Subject: [PATCH 03/85] Saving here before I have to change IDBCursor --- examples/indexeddb/src/main.rs | 47 ++++++++++++++++++---------------- src/webapi/indexeddb.rs | 1 + 2 files changed, 26 insertions(+), 22 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 63d3169f..fde0a3af 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -35,6 +35,7 @@ use stdweb::web::indexeddb::{ IDBDatabase, IDBRequest, DBRequest, + IDBCursor, IDBObjectStore, IDBObjectStoreIndexSharedMethods }; @@ -127,30 +128,31 @@ fn main() { let object_store = db.transaction("notes", "readonly").object_store("notes"); object_store.open_cursor(None, None) - .add_event_listener( |e: IDBSuccessEvent| { - + .add_event_listener( move |e: IDBSuccessEvent| { + // Get a reference to the cursor - - let cursor = e.target(); - - //.result; -/* - // If there is still another data item to iterate through, keep running this code - if(cursor) { - // Create a list item, h3, and p to put each data item inside when displaying it - // structure the HTML fragment, and append it inside the list - let listItem = document.createElement('li'); - let h3 = document.createElement('h3'); - let para = document.createElement('p'); - - listItem.appendChild(h3); - listItem.appendChild(para); - list.appendChild(listItem); + let db_request: DBRequest = e.target().unwrap().try_into().unwrap(); + let cursor: IDBCursor = db_request.result().try_into().unwrap(); - // Put the data from the cursor inside the h3 and para - h3.textContent = cursor.value.title; - para.textContent = cursor.value.body; + // Todo there is the posibility that we don't have a cursor, how do we handle it. + // If there is still another data item to iterate through, keep running this code + if true { + + // Create a list item, h3, and p to put each data item inside when displaying it + // structure the HTML fragment, and append it inside the list + let listItem = document().create_element("li").unwrap(); + let h3 = document().create_element("h3").unwrap(); + let para = document().create_element("p").unwrap(); + + listItem.append_child(&h3); + listItem.append_child(¶); + list.append_child(&listItem); + + // Put the data from the cursor inside the h3 and para + // h3.textContent = cursor.value.title; + //para.textContent = cursor.value.body; + /* // Store the ID of the data item inside an attribute on the listItem, so we know // which item it corresponds to. This will be useful later when we want to delete items listItem.setAttribute('data-note-id', cursor.value.id); @@ -175,8 +177,9 @@ fn main() { } // if there are no more cursor items to iterate through, say so console.log('Notes all displayed'); - } */ + } + }); diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index db949b4f..4a765267 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -72,6 +72,7 @@ pub trait IDBRequest : IEventTarget { /// This is a struct #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBRequest")] +#[reference(subclass_of(EventTarget))] pub struct DBRequest( Reference ); impl IEventTarget for DBRequest {} From b8b968eabbbc61f6373b7542cd55b77c812a4fde Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Mon, 21 May 2018 23:10:20 +0100 Subject: [PATCH 04/85] finished display_data --- examples/indexeddb/src/main.rs | 118 ++++++++++++++++++++++----------- src/lib.rs | 4 +- src/webapi/indexeddb.rs | 42 +++++++++--- 3 files changed, 114 insertions(+), 50 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index fde0a3af..d840acc5 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -27,7 +27,8 @@ use stdweb::web::event::{ IDBSuccessEvent, IDBVersionChangeEvent, IDBCompleteEvent, - IDBErrorEvent + IDBErrorEvent, + SubmitEvent }; use stdweb::web::indexeddb::{ @@ -37,15 +38,18 @@ use stdweb::web::indexeddb::{ DBRequest, IDBCursor, IDBObjectStore, - IDBObjectStoreIndexSharedMethods + IDBObjectStoreIndexSharedMethods, + IDBCursorWithValue, + IDBCursorSharedMethods }; use stdweb::unstable::TryInto; #[derive(Serialize, Deserialize)] struct Note { - title: String, - body: String + id: u32, + title: String, + body: String } js_serializable!( Note ); @@ -53,10 +57,7 @@ js_deserializable!( Note ); fn main() { stdweb::initialize(); - - let title_input = document().query_selector("#title").unwrap().unwrap(); - let body_input = document().query_selector("#body").unwrap().unwrap(); - let form = document().query_selector("form").unwrap().unwrap(); + let submit_btn = document().query_selector("form button"); let db: RefCell> = RefCell::new(None); @@ -113,6 +114,44 @@ fn main() { }); + let form = document().query_selector("form").unwrap().unwrap(); + form.add_event_listener( |e: SubmitEvent | { + // prevent default - we don't want the form to submit in the conventional way + e.prevent_default(); + + // grab the values entered into the form fields and store them in an object ready for being inserted into the DB + let title_input = document().query_selector("#title").unwrap().unwrap(); + let body_input = document().query_selector("#body").unwrap().unwrap(); + let newItem = Note{ id: 0, title: title_input.text_content().unwrap(), body: body_input.text_content().unwrap() }; + + // open a read/write db transaction, ready for adding the data + //let transaction = db.transaction("notes", "readwrite"); + /* + // call an object store that's already been added to the database + let objectStore = transaction.objectStore('notes'); + + // Make a request to add our newItem object to the object store + var request = objectStore.add(newItem); + request.onsuccess = function() { + // Clear the form, ready for adding the next entry + titleInput.value = ''; + bodyInput.value = ''; + }; + + // Report on the success of the transaction completing, when everything is done + transaction.oncomplete = function() { + console.log('Transaction completed: database modification finished.'); + + // update the display of data to show the newly added item, by running displayData() again. + displayData(); + }; + + transaction.onerror = function() { + console.log('Transaction not opened due to error'); + }; +*/ + }); + // Define the displayData() function fn display_data(db: IDBDatabase) { let list = document().query_selector("ul").unwrap().unwrap(); @@ -132,7 +171,7 @@ fn main() { // Get a reference to the cursor let db_request: DBRequest = e.target().unwrap().try_into().unwrap(); - let cursor: IDBCursor = db_request.result().try_into().unwrap(); + let cursor: IDBCursorWithValue = db_request.result().try_into().unwrap(); // Todo there is the posibility that we don't have a cursor, how do we handle it. @@ -148,40 +187,43 @@ fn main() { listItem.append_child(&h3); listItem.append_child(¶); list.append_child(&listItem); + + let note: Note = cursor.value().try_into().unwrap(); // Put the data from the cursor inside the h3 and para - // h3.textContent = cursor.value.title; - //para.textContent = cursor.value.body; - /* - // Store the ID of the data item inside an attribute on the listItem, so we know - // which item it corresponds to. This will be useful later when we want to delete items - listItem.setAttribute('data-note-id', cursor.value.id); + h3.set_text_content(¬e.title); + para.set_text_content(¬e.body); + + // Store the ID of the data item inside an attribute on the listItem, so we know + // which item it corresponds to. This will be useful later when we want to delete items + listItem.set_attribute("data-note-id", &format!("{}", note.id)); // Create a button and place it inside each listItem - let deleteBtn = document.createElement('button'); - listItem.appendChild(deleteBtn); - deleteBtn.textContent = 'Delete'; - - // Set an event handler so that when the button is clicked, the deleteItem() - // function is run - deleteBtn.onclick = deleteItem; - - // Iterate to the next item in the cursor - cursor.continue(); - } else { - // Again, if list item is empty, display a 'No notes stored' message - if(!list.firstChild) { - let listItem = document.createElement('li'); - listItem.textContent = 'No notes stored.' - list.appendChild(listItem); + let deleteBtn = document().create_element("button").unwrap(); + listItem.append_child(&deleteBtn); + deleteBtn.set_text_content("Delete"); + + // Set an event handler so that when the button is clicked, the deleteItem() + // function is run + // deleteBtn.onclick = deleteItem; + + // Iterate to the next item in the cursor + cursor.advance(1); // Todo this was continue + + } else { + // Again, if list item is empty, display a 'No notes stored' message + if(list.first_child().is_none()) { + let listItem = document().create_element("li").unwrap(); + listItem.set_text_content("No notes stored."); + list.append_child(&listItem); + } + // if there are no more cursor items to iterate through, say so + console!(log, "Notes all displayed"); + } - // if there are no more cursor items to iterate through, say so - console.log('Notes all displayed'); -*/ - } - - }); + + }); + - } } diff --git a/src/lib.rs b/src/lib.rs index 56712ec6..154c3374 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -218,7 +218,9 @@ pub mod web { IDBObjectStoreIndexSharedMethods, IDBCursorDirection, IDBRequestReadyState, - IDBCursor + IDBCursorSharedMethods, + IDBCursor, + IDBCursorWithValue }; } diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 4a765267..f2e5c1da 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -173,11 +173,7 @@ fn string_to_cursor_direction( direction: &str) -> IDBCursorDirection { } /// -#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "IDBCursor")] -pub struct IDBCursor( Reference ); - -impl IDBCursor { +pub trait IDBCursorSharedMethods: AsRef< Reference > { //readonly attribute (IDBObjectStore or IDBIndex) source; //readonly attribute IDBCursorDirection direction; @@ -196,7 +192,7 @@ impl IDBCursor { /// /// /// - pub fn advance( &self, count: u32) { + fn advance( &self, count: u32) { js! { @{self.as_ref()}.advance(@{count}); } } @@ -204,7 +200,7 @@ impl IDBCursor { /// /// /// - pub fn advance_to_match>>( &self, key: K) { + fn advance_to_match>>( &self, key: K) { match key.into() { None => js! { @{self.as_ref()}.continue(); }, Some(key) => js! { @{self.as_ref()}.continue(@{key.as_ref()}); } @@ -217,16 +213,40 @@ impl IDBCursor { /// /// /// - pub fn update( &self, value: Value) -> DBRequest { - js! ( return @{self}.update(@{value.as_ref()}); ).try_into().unwrap() + fn update( &self, value: Value) -> DBRequest { + js! ( return @{self.as_ref()}.update(@{value.as_ref()}); ).try_into().unwrap() } //[NewObject] IDBRequest delete(); /// /// /// - pub fn delete( &self ) -> DBRequest { - js!( return @{self}.delete(); ).try_into().unwrap() + fn delete( &self ) -> DBRequest { + js!( return @{self.as_ref()}.delete(); ).try_into().unwrap() + } +} + +/// +#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] +#[reference(instance_of = "IDBCursor")] +pub struct IDBCursor( Reference ); + +impl IDBCursorSharedMethods for IDBCursor {} + +/// +#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] +#[reference(instance_of = "IDBCursorWithValue")] +pub struct IDBCursorWithValue( Reference ); + +impl IDBCursorSharedMethods for IDBCursorWithValue {} + +impl IDBCursorWithValue { + + /// + pub fn value( &self ) -> Value { + js! ( + return @{self}.value + ).try_into().unwrap() } } From 1a0f826cf9ee96050346d259f549cbba2aa34013 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Thu, 24 May 2018 08:31:47 +0100 Subject: [PATCH 05/85] made this compile --- examples/indexeddb/src/main.rs | 239 ++++++++++++++++++--------------- 1 file changed, 131 insertions(+), 108 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index d840acc5..5490b012 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -21,6 +21,8 @@ use stdweb::web::{ EventTarget }; +use stdweb::web::html_element::InputElement; + use stdweb::web::event::{ConcreteEvent, IEvent}; use stdweb::web::event::{ @@ -55,12 +57,89 @@ struct Note { js_serializable!( Note ); js_deserializable!( Note ); +thread_local!(static DB: RefCell> = RefCell::new(None)); + +fn display_data_inner(db: &IDBDatabase) { + let list = document().query_selector("ul").unwrap().unwrap(); + + // Here we empty the contents of the list element each time the display is updated + // If you ddn't do this, you'd get duplicates listed each time a new note is added + while list.first_child().is_some() { + list.remove_child(&list.first_child().unwrap()); + } + + // Open our object store and then get a cursor - which iterates through all the + // different data items in the store + let object_store = db.transaction("notes", "readonly").object_store("notes"); + + object_store.open_cursor(None, None) + .add_event_listener( move |e: IDBSuccessEvent| { + + // Get a reference to the cursor + let db_request: DBRequest = e.target().unwrap().try_into().unwrap(); + let cursor: IDBCursorWithValue = db_request.result().try_into().unwrap(); + + // Todo there is the posibility that we don't have a cursor, how do we handle it. + + // If there is still another data item to iterate through, keep running this code + if true { + + // Create a list item, h3, and p to put each data item inside when displaying it + // structure the HTML fragment, and append it inside the list + let listItem = document().create_element("li").unwrap(); + let h3 = document().create_element("h3").unwrap(); + let para = document().create_element("p").unwrap(); + + listItem.append_child(&h3); + listItem.append_child(¶); + list.append_child(&listItem); + + let note: Note = cursor.value().try_into().unwrap(); + + // Put the data from the cursor inside the h3 and para + h3.set_text_content(¬e.title); + para.set_text_content(¬e.body); + + // Store the ID of the data item inside an attribute on the listItem, so we know + // which item it corresponds to. This will be useful later when we want to delete items + listItem.set_attribute("data-note-id", &format!("{}", note.id)); + + // Create a button and place it inside each listItem + let deleteBtn = document().create_element("button").unwrap(); + listItem.append_child(&deleteBtn); + deleteBtn.set_text_content("Delete"); + + // Set an event handler so that when the button is clicked, the deleteItem() + // function is run + // deleteBtn.onclick = deleteItem; + + // Iterate to the next item in the cursor + cursor.advance(1); // Todo this was continue + + } else { + // Again, if list item is empty, display a 'No notes stored' message + if(list.first_child().is_none()) { + let listItem = document().create_element("li").unwrap(); + listItem.set_text_content("No notes stored."); + list.append_child(&listItem); + } + // if there are no more cursor items to iterate through, say so + console!(log, "Notes all displayed"); + }});} + +fn display_data() { + DB.with(|db_cell| { + if let Some(ref db) = *db_cell.borrow_mut() { + display_data_inner(db); + }}) +} + fn main() { stdweb::initialize(); let submit_btn = document().query_selector("form button"); - let db: RefCell> = RefCell::new(None); + // Open our database; it is created if it doesn't already exist // (see onupgradeneeded below) @@ -74,37 +153,39 @@ fn main() { }); // onsuccess handler signifies that the database opened successfully - request.add_event_listener( |event: IDBSuccessEvent| { + request.add_event_listener( move |event: IDBSuccessEvent| { js!( console.log("Database opened succesfully"); - ); + ); let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); // Store the opened database object in the db variable. This is used a lot below - let db_ : IDBDatabase = db_request.result().try_into().unwrap(); + let db : IDBDatabase = db_request.result().try_into().unwrap(); - //db.replace(Some(db_)); + DB.with(|db_cell| { + db_cell.replace(Some(db)); + }); // Run the displayData() function to display the notes already in the IDB - display_data(db_); + display_data(); }); request.add_event_listener( |event: IDBVersionChangeEvent| { let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); - let db: IDBDatabase = db_request.result().try_into().unwrap(); + let db_: IDBDatabase = db_request.result().try_into().unwrap(); // Create an objectStore to store our notes in (basically like a single table) // including a auto-incrementing key let mut store_options = HashMap::new(); store_options.insert("keyPath", "id"); store_options.insert("autoIncrement", "true"); - let object_store = db.create_object_store("notes", Value::from(store_options)); + let object_store = db_.create_object_store("notes", Value::from(store_options)); // Define what data items the objectStore will contain let mut title_options = HashMap::new(); title_options.insert("unique", false); object_store.create_index("title", "title", Value::from(title_options)); - - let mut body_options = HashMap::new(); + + let mut body_options = HashMap::new(); body_options.insert("unique", false); object_store.create_index("body", "body", Value::from(body_options)); @@ -115,115 +196,57 @@ fn main() { }); let form = document().query_selector("form").unwrap().unwrap(); - form.add_event_listener( |e: SubmitEvent | { + form.add_event_listener( move |e: SubmitEvent | { // prevent default - we don't want the form to submit in the conventional way e.prevent_default(); // grab the values entered into the form fields and store them in an object ready for being inserted into the DB - let title_input = document().query_selector("#title").unwrap().unwrap(); - let body_input = document().query_selector("#body").unwrap().unwrap(); + let title_input: InputElement = document().query_selector("#title").unwrap().unwrap().try_into().unwrap(); + let body_input: InputElement = document().query_selector("#body").unwrap().unwrap().try_into().unwrap(); let newItem = Note{ id: 0, title: title_input.text_content().unwrap(), body: body_input.text_content().unwrap() }; + + DB.with(|db_cell| { + if let Some(ref db) = *db_cell.borrow_mut() { + // open a read/write db transaction, ready for adding the data + let transaction = db.transaction("notes", "readwrite"); - // open a read/write db transaction, ready for adding the data - //let transaction = db.transaction("notes", "readwrite"); - /* - // call an object store that's already been added to the database - let objectStore = transaction.objectStore('notes'); - - // Make a request to add our newItem object to the object store - var request = objectStore.add(newItem); - request.onsuccess = function() { - // Clear the form, ready for adding the next entry - titleInput.value = ''; - bodyInput.value = ''; - }; - - // Report on the success of the transaction completing, when everything is done - transaction.oncomplete = function() { - console.log('Transaction completed: database modification finished.'); - - // update the display of data to show the newly added item, by running displayData() again. - displayData(); - }; + // call an object store that's already been added to the database + let objectStore = transaction.object_store("notes"); - transaction.onerror = function() { - console.log('Transaction not opened due to error'); - }; -*/ - }); - - // Define the displayData() function - fn display_data(db: IDBDatabase) { - let list = document().query_selector("ul").unwrap().unwrap(); + // Make a request to add our newItem object to the object store + let request = objectStore.add(newItem.try_into().unwrap(), None); + + request.add_event_listener( move |e: IDBSuccessEvent| { + // Clear the form, ready for adding the next entry + title_input.set_raw_value(""); + body_input.set_raw_value(""); + }); - // Here we empty the contents of the list element each time the display is updated - // If you ddn't do this, you'd get duplicates listed each time a new note is added - while list.first_child().is_some() { - list.remove_child(&list.first_child().unwrap()); - } - - // Open our object store and then get a cursor - which iterates through all the - // different data items in the store - let object_store = db.transaction("notes", "readonly").object_store("notes"); + // Report on the success of the transaction completing, when everything is done + transaction.add_event_listener( |e: IDBCompleteEvent| { + console!(log, "Transaction completed: database modification finished."); + + // update the display of data to show the newly added item, by running displayData() again. + display_data(); + }); - object_store.open_cursor(None, None) - .add_event_listener( move |e: IDBSuccessEvent| { + transaction.add_event_listener( |e: IDBErrorEvent| { + console!(log, "Transaction not opened due to error"); + }); + + + + }}); + + + + + + - // Get a reference to the cursor - let db_request: DBRequest = e.target().unwrap().try_into().unwrap(); - let cursor: IDBCursorWithValue = db_request.result().try_into().unwrap(); - // Todo there is the posibility that we don't have a cursor, how do we handle it. - - // If there is still another data item to iterate through, keep running this code - if true { - - // Create a list item, h3, and p to put each data item inside when displaying it - // structure the HTML fragment, and append it inside the list - let listItem = document().create_element("li").unwrap(); - let h3 = document().create_element("h3").unwrap(); - let para = document().create_element("p").unwrap(); - - listItem.append_child(&h3); - listItem.append_child(¶); - list.append_child(&listItem); - let note: Note = cursor.value().try_into().unwrap(); - - // Put the data from the cursor inside the h3 and para - h3.set_text_content(¬e.title); - para.set_text_content(¬e.body); - - // Store the ID of the data item inside an attribute on the listItem, so we know - // which item it corresponds to. This will be useful later when we want to delete items - listItem.set_attribute("data-note-id", &format!("{}", note.id)); - - // Create a button and place it inside each listItem - let deleteBtn = document().create_element("button").unwrap(); - listItem.append_child(&deleteBtn); - deleteBtn.set_text_content("Delete"); - - // Set an event handler so that when the button is clicked, the deleteItem() - // function is run - // deleteBtn.onclick = deleteItem; - - // Iterate to the next item in the cursor - cursor.advance(1); // Todo this was continue - - } else { - // Again, if list item is empty, display a 'No notes stored' message - if(list.first_child().is_none()) { - let listItem = document().create_element("li").unwrap(); - listItem.set_text_content("No notes stored."); - list.append_child(&listItem); - } - // if there are no more cursor items to iterate through, say so - console!(log, "Notes all displayed"); - - } - - }); - - } + }); + } From 52e54082db6a71bb4a2580c9890e9d65fbaef486 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Thu, 24 May 2018 22:23:39 +0100 Subject: [PATCH 06/85] Adding and displaying. --- examples/indexeddb/src/main.rs | 41 +++++++++++++++++++++------------- src/webapi/indexeddb.rs | 11 ++++++++- 2 files changed, 35 insertions(+), 17 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 5490b012..cd16ee7c 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -49,7 +49,7 @@ use stdweb::unstable::TryInto; #[derive(Serialize, Deserialize)] struct Note { - id: u32, + //id: u32, title: String, body: String } @@ -60,30 +60,31 @@ js_deserializable!( Note ); thread_local!(static DB: RefCell> = RefCell::new(None)); fn display_data_inner(db: &IDBDatabase) { + console!(log, "a"); let list = document().query_selector("ul").unwrap().unwrap(); - + console!(log, "b"); // Here we empty the contents of the list element each time the display is updated // If you ddn't do this, you'd get duplicates listed each time a new note is added while list.first_child().is_some() { list.remove_child(&list.first_child().unwrap()); } - + console!(log, "c"); // Open our object store and then get a cursor - which iterates through all the // different data items in the store let object_store = db.transaction("notes", "readonly").object_store("notes"); - + console!(log, "5"); object_store.open_cursor(None, None) .add_event_listener( move |e: IDBSuccessEvent| { - + console!(log, "6"); // Get a reference to the cursor let db_request: DBRequest = e.target().unwrap().try_into().unwrap(); - let cursor: IDBCursorWithValue = db_request.result().try_into().unwrap(); - - // Todo there is the posibility that we don't have a cursor, how do we handle it. - + console!(log, "7"); + //let cursor: IDBCursorWithValue = db_request.result().try_into().unwrap(); + let maybe_cursor: Result = db_request.result().try_into(); + // If there is still another data item to iterate through, keep running this code - if true { - + if let Ok(cursor) = maybe_cursor { + console!(log, "8"); // Create a list item, h3, and p to put each data item inside when displaying it // structure the HTML fragment, and append it inside the list let listItem = document().create_element("li").unwrap(); @@ -102,8 +103,11 @@ fn display_data_inner(db: &IDBDatabase) { // Store the ID of the data item inside an attribute on the listItem, so we know // which item it corresponds to. This will be useful later when we want to delete items - listItem.set_attribute("data-note-id", &format!("{}", note.id)); - + console!(log, "9"); + let id: u32 = cursor.key().try_into().unwrap(); + console!(log, "10"); + listItem.set_attribute("data-note-id", &format!("{}", id)); + console!(log, "11"); // Create a button and place it inside each listItem let deleteBtn = document().create_element("button").unwrap(); listItem.append_child(&deleteBtn); @@ -125,12 +129,15 @@ fn display_data_inner(db: &IDBDatabase) { } // if there are no more cursor items to iterate through, say so console!(log, "Notes all displayed"); - }});} + } + });} fn display_data() { DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { + console!(log, "3"); display_data_inner(db); + console!(log, "4"); }}) } @@ -166,7 +173,9 @@ fn main() { db_cell.replace(Some(db)); }); // Run the displayData() function to display the notes already in the IDB + console!(log, "1"); display_data(); + console!(log, "2"); }); request.add_event_listener( |event: IDBVersionChangeEvent| { @@ -176,7 +185,7 @@ fn main() { // Create an objectStore to store our notes in (basically like a single table) // including a auto-incrementing key let mut store_options = HashMap::new(); - store_options.insert("keyPath", "id"); + //store_options.insert("keyPath", "id"); store_options.insert("autoIncrement", "true"); let object_store = db_.create_object_store("notes", Value::from(store_options)); @@ -203,7 +212,7 @@ fn main() { // grab the values entered into the form fields and store them in an object ready for being inserted into the DB let title_input: InputElement = document().query_selector("#title").unwrap().unwrap().try_into().unwrap(); let body_input: InputElement = document().query_selector("#body").unwrap().unwrap().try_into().unwrap(); - let newItem = Note{ id: 0, title: title_input.text_content().unwrap(), body: body_input.text_content().unwrap() }; + let newItem = Note{ title: title_input.raw_value(), body: body_input.raw_value() }; DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index f2e5c1da..00a30d03 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -186,6 +186,14 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { // Todo, not sure what I'm doing with these two //readonly attribute any key; + /// + fn key( &self ) -> Value { + js!( + console.log( "This is a dert", @{self.as_ref()}.key); + return @{self.as_ref()}.key; ) + .try_into().unwrap() + } + //readonly attribute any primaryKey; //void advance([EnforceRange] unsigned long count); @@ -584,6 +592,7 @@ impl IDBTransaction { /// This is a method pub fn object_store( &self, name: &str) -> IDBObjectStore { js! ( + console.log("Here we are in Weerdert land ", @{self.as_ref()}, @{name}); return @{self.as_ref()}.objectStore(@{name}); ).try_into().unwrap() } @@ -641,7 +650,7 @@ impl IDBDatabase { pub fn transaction( &self, store_name: &str, mode: &str) -> IDBTransaction { js! ( //return @{self.as_ref()}.transaction(@{store_name}, @{mode}); - return @{self.as_ref()}.transaction("customers", "readwrite"); + return @{self.as_ref()}.transaction(@{store_name}, @{mode}); ).try_into().unwrap() } From 2f47e9cfafbd5ab673896032be30090ae3aa6b5e Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Sun, 27 May 2018 22:59:56 +0100 Subject: [PATCH 07/85] Last function needed for the demo, not working yet. --- examples/indexeddb/src/main.rs | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index cd16ee7c..28b87bc0 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -141,6 +141,34 @@ fn display_data() { }}) } +// Define the deleteItem() function +fn delete_item( e: ClickEvent ) { + // retrieve the name of the task we want to delete. We need + // to convert it to a number before trying it use it with IDB; IDB key + // values are type-sensitive. + let noteId = Number(e.target.parentNode.getAttribute('data-note-id')); + + // open a database transaction and delete the task, finding it using the id we retrieved above + let transaction = db.transaction(['notes'], 'readwrite'); + let objectStore = transaction.objectStore('notes'); + let request = objectStore.delete(noteId); + + // report that the data item has been deleted + transaction.oncomplete = function() { + // delete the parent of the button + // which is the list item, so it is no longer displayed + e.target.parentNode.parentNode.removeChild(e.target.parentNode); + console.log('Note ' + noteId + ' deleted.'); + + // Again, if list item is empty, display a 'No notes stored' message + if(!list.firstChild) { + let listItem = document.createElement('li'); + listItem.textContent = 'No notes stored.'; + list.appendChild(listItem); + } + } +} + fn main() { stdweb::initialize(); From 25c02ad823c79cc25e24deff5a549482bd102cba Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 28 May 2018 23:27:20 +0000 Subject: [PATCH 08/85] It's working. --- examples/indexeddb/src/main.rs | 62 ++++++++++++++++++++++------------ 1 file changed, 40 insertions(+), 22 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 28b87bc0..ae156d06 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -8,6 +8,7 @@ extern crate serde; use std::collections::HashMap; use std::cell::RefCell; +use std::str::FromStr; use stdweb::Value; @@ -18,7 +19,8 @@ use stdweb::web::{ window, document, IEventTarget, - EventTarget + EventTarget, + Node }; use stdweb::web::html_element::InputElement; @@ -30,7 +32,8 @@ use stdweb::web::event::{ IDBVersionChangeEvent, IDBCompleteEvent, IDBErrorEvent, - SubmitEvent + SubmitEvent, + ClickEvent }; use stdweb::web::indexeddb::{ @@ -115,7 +118,7 @@ fn display_data_inner(db: &IDBDatabase) { // Set an event handler so that when the button is clicked, the deleteItem() // function is run - // deleteBtn.onclick = deleteItem; + deleteBtn.add_event_listener( delete_item ); // Iterate to the next item in the cursor cursor.advance(1); // Todo this was continue @@ -146,27 +149,42 @@ fn delete_item( e: ClickEvent ) { // retrieve the name of the task we want to delete. We need // to convert it to a number before trying it use it with IDB; IDB key // values are type-sensitive. - let noteId = Number(e.target.parentNode.getAttribute('data-note-id')); + let button: Element = e.target().unwrap().try_into().unwrap(); + let note: Element = button.parent_node().unwrap().try_into().unwrap(); + let noteId = note.get_attribute("data-note-id").unwrap().parse::().unwrap(); // open a database transaction and delete the task, finding it using the id we retrieved above - let transaction = db.transaction(['notes'], 'readwrite'); - let objectStore = transaction.objectStore('notes'); - let request = objectStore.delete(noteId); - - // report that the data item has been deleted - transaction.oncomplete = function() { - // delete the parent of the button - // which is the list item, so it is no longer displayed - e.target.parentNode.parentNode.removeChild(e.target.parentNode); - console.log('Note ' + noteId + ' deleted.'); - - // Again, if list item is empty, display a 'No notes stored' message - if(!list.firstChild) { - let listItem = document.createElement('li'); - listItem.textContent = 'No notes stored.'; - list.appendChild(listItem); - } - } + DB.with(|db_cell| { + if let Some(ref db) = *db_cell.borrow_mut() { + let transaction = db.transaction("notes", "readwrite"); + let objectStore = transaction.object_store("notes"); + let request = objectStore.delete(noteId.try_into().unwrap()); + + // report that the data item has been deleted + console!(log, 20); + js!{ + @{transaction.as_ref()}.oncomplete = function(e) { + console.log(e); + }; + + }; + transaction.add_event_listener( move |e: IDBCompleteEvent| { + console!(log, 21); + // delete the parent of the button + // which is the list item, so it is no longer displayed + //let node: Node = e.target().unwrap().try_into().unwrap(); + note.parent_node().unwrap().remove_child(¬e); + console!(log, "Note ", noteId, "deleted."); + + // Again, if list item is empty, display a 'No notes stored' message + let list = document().query_selector("ul").unwrap().unwrap(); + if(!list.first_child().is_some()) { + let listItem = document().create_element("li").unwrap(); + listItem.set_text_content("No notes stored."); + list.append_child(&listItem); + } + }); + }}); } fn main() { From ec4b8e55bfbf2d99ce3fc5c2c30ebcde17118855 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 28 May 2018 23:37:30 +0000 Subject: [PATCH 09/85] Tidy up all the console.logs I added. --- examples/indexeddb/src/main.rs | 24 +----------------------- src/webapi/indexeddb.rs | 2 -- 2 files changed, 1 insertion(+), 25 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index ae156d06..7daa953d 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -63,31 +63,24 @@ js_deserializable!( Note ); thread_local!(static DB: RefCell> = RefCell::new(None)); fn display_data_inner(db: &IDBDatabase) { - console!(log, "a"); let list = document().query_selector("ul").unwrap().unwrap(); - console!(log, "b"); // Here we empty the contents of the list element each time the display is updated // If you ddn't do this, you'd get duplicates listed each time a new note is added while list.first_child().is_some() { list.remove_child(&list.first_child().unwrap()); } - console!(log, "c"); // Open our object store and then get a cursor - which iterates through all the // different data items in the store let object_store = db.transaction("notes", "readonly").object_store("notes"); - console!(log, "5"); object_store.open_cursor(None, None) .add_event_listener( move |e: IDBSuccessEvent| { - console!(log, "6"); // Get a reference to the cursor let db_request: DBRequest = e.target().unwrap().try_into().unwrap(); - console!(log, "7"); //let cursor: IDBCursorWithValue = db_request.result().try_into().unwrap(); let maybe_cursor: Result = db_request.result().try_into(); - + // If there is still another data item to iterate through, keep running this code if let Ok(cursor) = maybe_cursor { - console!(log, "8"); // Create a list item, h3, and p to put each data item inside when displaying it // structure the HTML fragment, and append it inside the list let listItem = document().create_element("li").unwrap(); @@ -106,11 +99,8 @@ fn display_data_inner(db: &IDBDatabase) { // Store the ID of the data item inside an attribute on the listItem, so we know // which item it corresponds to. This will be useful later when we want to delete items - console!(log, "9"); let id: u32 = cursor.key().try_into().unwrap(); - console!(log, "10"); listItem.set_attribute("data-note-id", &format!("{}", id)); - console!(log, "11"); // Create a button and place it inside each listItem let deleteBtn = document().create_element("button").unwrap(); listItem.append_child(&deleteBtn); @@ -138,9 +128,7 @@ fn display_data_inner(db: &IDBDatabase) { fn display_data() { DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { - console!(log, "3"); display_data_inner(db); - console!(log, "4"); }}) } @@ -161,15 +149,7 @@ fn delete_item( e: ClickEvent ) { let request = objectStore.delete(noteId.try_into().unwrap()); // report that the data item has been deleted - console!(log, 20); - js!{ - @{transaction.as_ref()}.oncomplete = function(e) { - console.log(e); - }; - - }; transaction.add_event_listener( move |e: IDBCompleteEvent| { - console!(log, 21); // delete the parent of the button // which is the list item, so it is no longer displayed //let node: Node = e.target().unwrap().try_into().unwrap(); @@ -219,9 +199,7 @@ fn main() { db_cell.replace(Some(db)); }); // Run the displayData() function to display the notes already in the IDB - console!(log, "1"); display_data(); - console!(log, "2"); }); request.add_event_listener( |event: IDBVersionChangeEvent| { diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 00a30d03..a5fec8dc 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -189,7 +189,6 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { /// fn key( &self ) -> Value { js!( - console.log( "This is a dert", @{self.as_ref()}.key); return @{self.as_ref()}.key; ) .try_into().unwrap() } @@ -592,7 +591,6 @@ impl IDBTransaction { /// This is a method pub fn object_store( &self, name: &str) -> IDBObjectStore { js! ( - console.log("Here we are in Weerdert land ", @{self.as_ref()}, @{name}); return @{self.as_ref()}.objectStore(@{name}); ).try_into().unwrap() } From 66fd193e5a7a40eac3242f0f9b995a120d21d1bd Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 28 May 2018 23:59:09 +0000 Subject: [PATCH 10/85] Get rid of all the warings in the example code. --- examples/indexeddb/src/main.rs | 100 +++++++++++++-------------------- 1 file changed, 38 insertions(+), 62 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 7daa953d..fca7a544 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -8,24 +8,20 @@ extern crate serde; use std::collections::HashMap; use std::cell::RefCell; -use std::str::FromStr; use stdweb::Value; use stdweb::traits::*; use stdweb::web::{ - HtmlElement, Element, window, document, IEventTarget, - EventTarget, - Node }; use stdweb::web::html_element::InputElement; -use stdweb::web::event::{ConcreteEvent, IEvent}; +use stdweb::web::event::IEvent; use stdweb::web::event::{ IDBSuccessEvent, @@ -41,8 +37,6 @@ use stdweb::web::indexeddb::{ IDBDatabase, IDBRequest, DBRequest, - IDBCursor, - IDBObjectStore, IDBObjectStoreIndexSharedMethods, IDBCursorWithValue, IDBCursorSharedMethods @@ -67,7 +61,7 @@ fn display_data_inner(db: &IDBDatabase) { // Here we empty the contents of the list element each time the display is updated // If you ddn't do this, you'd get duplicates listed each time a new note is added while list.first_child().is_some() { - list.remove_child(&list.first_child().unwrap()); + list.remove_child(&list.first_child().unwrap()).unwrap(); } // Open our object store and then get a cursor - which iterates through all the // different data items in the store @@ -83,13 +77,13 @@ fn display_data_inner(db: &IDBDatabase) { if let Ok(cursor) = maybe_cursor { // Create a list item, h3, and p to put each data item inside when displaying it // structure the HTML fragment, and append it inside the list - let listItem = document().create_element("li").unwrap(); + let list_item = document().create_element("li").unwrap(); let h3 = document().create_element("h3").unwrap(); let para = document().create_element("p").unwrap(); - listItem.append_child(&h3); - listItem.append_child(¶); - list.append_child(&listItem); + list_item.append_child(&h3); + list_item.append_child(¶); + list.append_child(&list_item); let note: Note = cursor.value().try_into().unwrap(); @@ -97,28 +91,28 @@ fn display_data_inner(db: &IDBDatabase) { h3.set_text_content(¬e.title); para.set_text_content(¬e.body); - // Store the ID of the data item inside an attribute on the listItem, so we know + // Store the ID of the data item inside an attribute on the list_item, so we know // which item it corresponds to. This will be useful later when we want to delete items let id: u32 = cursor.key().try_into().unwrap(); - listItem.set_attribute("data-note-id", &format!("{}", id)); - // Create a button and place it inside each listItem - let deleteBtn = document().create_element("button").unwrap(); - listItem.append_child(&deleteBtn); - deleteBtn.set_text_content("Delete"); + list_item.set_attribute("data-note-id", &format!("{}", id)).unwrap(); + // Create a button and place it inside each list_item + let delete_btn = document().create_element("button").unwrap(); + list_item.append_child(&delete_btn); + delete_btn.set_text_content("Delete"); // Set an event handler so that when the button is clicked, the deleteItem() // function is run - deleteBtn.add_event_listener( delete_item ); + delete_btn.add_event_listener( delete_item ); // Iterate to the next item in the cursor cursor.advance(1); // Todo this was continue } else { // Again, if list item is empty, display a 'No notes stored' message - if(list.first_child().is_none()) { - let listItem = document().create_element("li").unwrap(); - listItem.set_text_content("No notes stored."); - list.append_child(&listItem); + if list.first_child().is_none() { + let list_item = document().create_element("li").unwrap(); + list_item.set_text_content("No notes stored."); + list.append_child(&list_item); } // if there are no more cursor items to iterate through, say so console!(log, "Notes all displayed"); @@ -139,29 +133,29 @@ fn delete_item( e: ClickEvent ) { // values are type-sensitive. let button: Element = e.target().unwrap().try_into().unwrap(); let note: Element = button.parent_node().unwrap().try_into().unwrap(); - let noteId = note.get_attribute("data-note-id").unwrap().parse::().unwrap(); + let note_id = note.get_attribute("data-note-id").unwrap().parse::().unwrap(); // open a database transaction and delete the task, finding it using the id we retrieved above DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { let transaction = db.transaction("notes", "readwrite"); - let objectStore = transaction.object_store("notes"); - let request = objectStore.delete(noteId.try_into().unwrap()); + let object_store = transaction.object_store("notes"); + object_store.delete(note_id.try_into().unwrap()); // report that the data item has been deleted - transaction.add_event_listener( move |e: IDBCompleteEvent| { + transaction.add_event_listener( move |_e: IDBCompleteEvent| { // delete the parent of the button // which is the list item, so it is no longer displayed //let node: Node = e.target().unwrap().try_into().unwrap(); - note.parent_node().unwrap().remove_child(¬e); - console!(log, "Note ", noteId, "deleted."); + note.parent_node().unwrap().remove_child(¬e).unwrap(); + console!(log, "Note ", note_id, "deleted."); // Again, if list item is empty, display a 'No notes stored' message let list = document().query_selector("ul").unwrap().unwrap(); - if(!list.first_child().is_some()) { - let listItem = document().create_element("li").unwrap(); - listItem.set_text_content("No notes stored."); - list.append_child(&listItem); + if ! list.first_child().is_some() { + let list_item = document().create_element("li").unwrap(); + list_item.set_text_content("No notes stored."); + list.append_child(&list_item); } }); }}); @@ -170,16 +164,12 @@ fn delete_item( e: ClickEvent ) { fn main() { stdweb::initialize(); - let submit_btn = document().query_selector("form button"); - - - // Open our database; it is created if it doesn't already exist // (see onupgradeneeded below) let request = window().indexed_db().open("notes", 1); // onerror handler signifies that the database didn't open successfully - request.add_event_listener( |event: IDBErrorEvent| { + request.add_event_listener( | _e: IDBErrorEvent| { js!( console.log("Database failed to open"); ); @@ -206,14 +196,14 @@ fn main() { let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); let db_: IDBDatabase = db_request.result().try_into().unwrap(); - // Create an objectStore to store our notes in (basically like a single table) + // Create an object_store to store our notes in (basically like a single table) // including a auto-incrementing key let mut store_options = HashMap::new(); //store_options.insert("keyPath", "id"); store_options.insert("autoIncrement", "true"); let object_store = db_.create_object_store("notes", Value::from(store_options)); - // Define what data items the objectStore will contain + // Define what data items the object_store will contain let mut title_options = HashMap::new(); title_options.insert("unique", false); object_store.create_index("title", "title", Value::from(title_options)); @@ -236,7 +226,7 @@ fn main() { // grab the values entered into the form fields and store them in an object ready for being inserted into the DB let title_input: InputElement = document().query_selector("#title").unwrap().unwrap().try_into().unwrap(); let body_input: InputElement = document().query_selector("#body").unwrap().unwrap().try_into().unwrap(); - let newItem = Note{ title: title_input.raw_value(), body: body_input.raw_value() }; + let new_item = Note{ title: title_input.raw_value(), body: body_input.raw_value() }; DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { @@ -244,42 +234,28 @@ fn main() { let transaction = db.transaction("notes", "readwrite"); // call an object store that's already been added to the database - let objectStore = transaction.object_store("notes"); + let object_store = transaction.object_store("notes"); - // Make a request to add our newItem object to the object store - let request = objectStore.add(newItem.try_into().unwrap(), None); + // Make a request to add our new_item object to the object store + let request = object_store.add(new_item.try_into().unwrap(), None); - request.add_event_listener( move |e: IDBSuccessEvent| { + request.add_event_listener( move |_e: IDBSuccessEvent| { // Clear the form, ready for adding the next entry title_input.set_raw_value(""); body_input.set_raw_value(""); }); // Report on the success of the transaction completing, when everything is done - transaction.add_event_listener( |e: IDBCompleteEvent| { + transaction.add_event_listener( |_e: IDBCompleteEvent| { console!(log, "Transaction completed: database modification finished."); // update the display of data to show the newly added item, by running displayData() again. display_data(); }); - transaction.add_event_listener( |e: IDBErrorEvent| { + transaction.add_event_listener( |_e: IDBErrorEvent| { console!(log, "Transaction not opened due to error"); }); - - - - }}); - - - - - - - - - - + }}); }); - } From 9af4a54e75341cf10bedea0944610159a294c656 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Tue, 29 May 2018 21:50:30 +0000 Subject: [PATCH 11/85] Get rid of most the warnings and add a little more documentation. --- src/webapi/indexeddb.rs | 28 ++++++++++++++++------------ 1 file changed, 16 insertions(+), 12 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index a5fec8dc..9196b03b 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -3,12 +3,14 @@ use webcore::value::Reference; use webcore::try_from::TryInto; use webapi::event_target::{IEventTarget, EventTarget}; +/// Used to represent the state of an IDBRequest. /// +/// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/readyState) #[derive(Debug)] pub enum IDBRequestReadyState { - /// + /// The request is pending. Pending, - /// + /// The request is done. Done } @@ -38,8 +40,8 @@ pub trait IDBRequest : IEventTarget { return @{self.as_ref()}.transaction; ); match transaction { - Undefined => None, - Null => None, + Value::Undefined => None, + Value::Null => None, _ => Some(transaction.try_into().unwrap()) } } @@ -136,25 +138,27 @@ impl IDBFactory { } +/// The IDBCursorDirection enum indicates the direction in which a cursor is traversing the data. /// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/direction) #[derive(Debug)] pub enum IDBCursorDirection { - /// + /// This direction causes the cursor to be opened at the start of the source. Next, - /// + /// This direction causes the cursor to be opened at the start of the source. For every key with duplicate values, only the first record is yielded. NextUnique, - /// + /// This direction causes the cursor to be opened at the end of the source. Prev, - /// + /// This direction causes the cursor to be opened at the end of the source. For every key with duplicate values, only the first record is yielded. PrevUnique } fn cursor_direction_to_string( direction: IDBCursorDirection) -> String { match direction { - Next => "next".to_string(), - NextUnique => "nextunique".to_string(), - Prev => "prev".to_string(), - PrevUnique => "prevunique".to_string() + IDBCursorDirection::Next => "next".to_string(), + IDBCursorDirection::NextUnique => "nextunique".to_string(), + IDBCursorDirection::Prev => "prev".to_string(), + IDBCursorDirection::PrevUnique => "prevunique".to_string() } } From 70926f934df1f648be1967f5381ad3aabfa45253 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Tue, 29 May 2018 22:17:58 +0000 Subject: [PATCH 12/85] remove changes I made to minimal example. --- examples/minimal/Cargo.toml | 2 - examples/minimal/src/main.rs | 80 ++---------------------------------- 2 files changed, 4 insertions(+), 78 deletions(-) diff --git a/examples/minimal/Cargo.toml b/examples/minimal/Cargo.toml index 375d5f63..a6db8ae6 100644 --- a/examples/minimal/Cargo.toml +++ b/examples/minimal/Cargo.toml @@ -5,5 +5,3 @@ authors = ["Jan Bujak "] [dependencies] stdweb = { path = "../.." } -serde="*" -serde_derive="*" \ No newline at end of file diff --git a/examples/minimal/src/main.rs b/examples/minimal/src/main.rs index 10f376cd..365964df 100644 --- a/examples/minimal/src/main.rs +++ b/examples/minimal/src/main.rs @@ -1,85 +1,13 @@ #[macro_use] extern crate stdweb; -#[macro_use] -extern crate serde_derive; - -extern crate serde; - -use std::collections::HashMap; - -use stdweb::Value; - -use stdweb::web::{ - window, - IEventTarget, - EventTarget -}; - -use stdweb::web::event::{ConcreteEvent, IEvent}; - -use stdweb::web::event::{ - IDBSuccessEvent, - IDBVersionChangeEvent, - IDBCompleteEvent -}; - -use stdweb::web::indexeddb::{ - IDBOpenDBRequest, - IDBDatabase, - IDBRequest, - DBRequest -}; - -use stdweb::unstable::TryInto; - -#[derive(Serialize, Deserialize)] -struct Customer { - ssn: String, - name: String, - age: i32, - email: String -} - -js_serializable!( Customer ); -js_deserializable!( Customer ); - fn main() { stdweb::initialize(); - let request = window().indexed_db().open("db", None); - - request.add_event_listener( |event: IDBVersionChangeEvent| { - let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); - let db: IDBDatabase = db_request.result().try_into().unwrap(); - - let mut store_options = HashMap::new(); - store_options.insert("keyPath", "ssn"); - let object_store = db.create_object_store("customers", Value::from(store_options)); - - let mut name_options = HashMap::new(); - name_options.insert("unique", false); - object_store.create_index("name", "name", Value::from(name_options)); - - let mut email_options = HashMap::new(); - email_options.insert("unique", true); - object_store.create_index("email", "email", Value::from(email_options)); - - object_store.transaction().add_event_listener( move |event: IDBCompleteEvent| { - - let customers = vec![ - Customer{ ssn: "444-44-4444".to_string(), name: "Bill".to_string(), age: 35, email: "bill@company.com".to_string() }, - Customer{ ssn: "555-55-5555".to_string(), name: "Donna".to_string(), age: 32, email: "donna@home.org".to_string() } - ]; - - let customer_object_store = db.transaction("customers", "readwrite").object_store("customers"); + let message = "Hello, 世界!"; + js! { + alert( @{message} ); + } - for customer in &customers { - customer_object_store.add(customer.try_into().unwrap(), None); - } - }); - - }); - stdweb::event_loop(); } From 38a39e29c370c35266111c23ed47d0460616ccca Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Wed, 30 May 2018 22:29:53 +0000 Subject: [PATCH 13/85] Get rid of pointless white spae change. --- src/webapi/window_or_worker.rs | 1 - 1 file changed, 1 deletion(-) diff --git a/src/webapi/window_or_worker.rs b/src/webapi/window_or_worker.rs index 1889210a..cc265b6c 100644 --- a/src/webapi/window_or_worker.rs +++ b/src/webapi/window_or_worker.rs @@ -29,5 +29,4 @@ pub trait IWindowOrWorker: ReferenceType { }, $3 );\ ", self.as_ref().as_raw(), funcall_adapter::< F > as extern fn( *mut F ), callback, timeout ); } - } From 9c339b94154798d64849ce17f3bbf08a81499e3d Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Thu, 31 May 2018 22:20:15 +0000 Subject: [PATCH 14/85] Work on IDBRequest. --- examples/indexeddb/src/main.rs | 4 +- src/lib.rs | 2 +- src/webapi/indexeddb.rs | 130 +++++++++++++++++++++------------ 3 files changed, 88 insertions(+), 48 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index fca7a544..365b563f 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -36,7 +36,7 @@ use stdweb::web::indexeddb::{ IDBOpenDBRequest, IDBDatabase, IDBRequest, - DBRequest, + IDBRequestSharedMethods, IDBObjectStoreIndexSharedMethods, IDBCursorWithValue, IDBCursorSharedMethods @@ -69,7 +69,7 @@ fn display_data_inner(db: &IDBDatabase) { object_store.open_cursor(None, None) .add_event_listener( move |e: IDBSuccessEvent| { // Get a reference to the cursor - let db_request: DBRequest = e.target().unwrap().try_into().unwrap(); + let db_request: IDBRequest = e.target().unwrap().try_into().unwrap(); //let cursor: IDBCursorWithValue = db_request.result().try_into().unwrap(); let maybe_cursor: Result = db_request.result().try_into(); diff --git a/src/lib.rs b/src/lib.rs index 63443603..7e26e636 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -209,8 +209,8 @@ pub mod web { pub use webapi::indexeddb::{ IDBOpenDBRequest, IDBDatabase, + IDBRequestSharedMethods, IDBRequest, - DBRequest, IDBIndex, IDBObjectStore, IDBTransaction, diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 9196b03b..aa772c32 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -2,6 +2,7 @@ use webcore::value::Value; use webcore::value::Reference; use webcore::try_from::TryInto; use webapi::event_target::{IEventTarget, EventTarget}; +use webapi::dom_exception::InvalidStateError; /// Used to represent the state of an IDBRequest. /// @@ -14,25 +15,62 @@ pub enum IDBRequestReadyState { Done } -/// This is a trait -pub trait IDBRequest : IEventTarget { - - //readonly attribute any result; - /// This is a trait method +/// Represents the different types the source arrtibute of an IDBRequest +/// can take. +#[derive(Debug)] +pub enum IDBRequestSource { + /// Indicates no source exists, such as when calling `indexedDB.open` + None, + Store(IDBObjectStore), + Index(IDBIndex), + Cursor(IDBCursor) +} + +/// IDBRequestSharedMethode represents the methode that are shared between +/// IDBOpenDBRequest and IDBRequest. +pub trait IDBRequestSharedMethods : IEventTarget { + + /// + /// + /// fn result( &self ) -> Value { - js! ( - return @{self.as_ref()}.result; - ) + js!( return @{self.as_ref()}.result; ) } + //fn result( &self ) -> Result { + // js_try!( return @{self.as_ref()}.result; ).unwrap() + //} /*fn error(&self) -> DOMException { }*/ - //readonly attribute (IDBObjectStore or IDBIndex or IDBCursor)? source; + /// Returns the source of the request. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/source) + fn source( &self ) -> IDBRequestSource { + let t: i32 = js!{ + if (@{self.as_ref()}.source instanceof IDBObjectStore) { + return 0; + } else if (@{self.as_ref()}.source instanceof IDBIndex) { + return 1; + } else if (@{self.as_ref()}.source instanceof IDBCursor) { + return 2; + } else { + return 3; + } + }.try_into().unwrap(); + match t { + 0 => IDBRequestSource::Store(js!(return @{self.as_ref()}.source;).try_into().unwrap()), + 1 => IDBRequestSource::Index(js!(return @{self.as_ref()}.source;).try_into().unwrap()), + 2 => IDBRequestSource::Cursor(js!(return @{self.as_ref()}.source;).try_into().unwrap()), + 3 => IDBRequestSource::None, + _ => panic!() + } + } - //readonly attribute IDBTransaction? transaction; - /// + /// The `transaction` read-only property of the `IDBRequest` interface + /// returns the transaction for the request, that is, the transaction + /// the request is being made inside. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/transaction) fn transaction( &self ) -> Option { @@ -46,8 +84,8 @@ pub trait IDBRequest : IEventTarget { } } - //readonly attribute IDBRequestReadyState readyState; - /// + /// The `ready_state` read-only property of the `IDBRequest` interface + /// returns the state of the request. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/readyState) fn ready_state( &self ) -> IDBRequestReadyState { @@ -61,24 +99,23 @@ pub trait IDBRequest : IEventTarget { return IDBRequestReadyState::Done; } else { panic!("Got {} as an IDBRequestReadyState.", ready_state); - } - + } } - // Event handlers: - //attribute EventHandler onsuccess; - //attribute EventHandler onerror; - } -/// This is a struct +/// The `IDBReques`t interface of the IndexedDB API provides access to results +/// of asynchronous requests to databases and database objects using event +/// handlers. Events that are received are IDBSuccessEvent and IDBErrorEvent. +/// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBRequest")] #[reference(subclass_of(EventTarget))] -pub struct DBRequest( Reference ); +pub struct IDBRequest( Reference ); -impl IEventTarget for DBRequest {} -impl IDBRequest for DBRequest {} +impl IEventTarget for IDBRequest {} +impl IDBRequestSharedMethods for IDBRequest {} /// Provides access to the results of requests to open or delete databases. /// Receives `IDBBlockedEvent` and `IDBVersionChangeEvent` as well as events received by `IDBRequest`. @@ -89,7 +126,7 @@ impl IDBRequest for DBRequest {} pub struct IDBOpenDBRequest( Reference ); impl IEventTarget for IDBOpenDBRequest {} -impl IDBRequest for IDBOpenDBRequest {} +impl IDBRequestSharedMethods for IDBOpenDBRequest {} /// The `IDBFactory` interface of the IndexedDB API lets applications asynchronously access the indexed databases. The object that implements the interface is `window.indexedDB`. /// @@ -176,17 +213,20 @@ fn string_to_cursor_direction( direction: &str) -> IDBCursorDirection { } } -/// +/// This trait implements all the methods that are shared between +/// pub trait IDBCursorSharedMethods: AsRef< Reference > { //readonly attribute (IDBObjectStore or IDBIndex) source; - //readonly attribute IDBCursorDirection direction; - // /// - // /// - // /// - // pub fn direction( &self ) -> IDBCursorDirection { - // string_to_cursor_direction(js! ( return @{self.as_ref()}.direction; ).try_into().unwrap()) - //} + /// The `direction` read-only property of the `IDBCursor` interface is + /// an enum that represents the direction of traversal of the + /// cursor (set using `IDBObjectStore.openCursor` for example). + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/direction) + fn direction( &self ) -> IDBCursorDirection { + let direction: String = js! ( return @{self.as_ref()}.direction; ).try_into().unwrap(); + return string_to_cursor_direction(&direction); + } // Todo, not sure what I'm doing with these two //readonly attribute any key; @@ -224,7 +264,7 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { /// /// /// - fn update( &self, value: Value) -> DBRequest { + fn update( &self, value: Value) -> IDBRequest { js! ( return @{self.as_ref()}.update(@{value.as_ref()}); ).try_into().unwrap() } @@ -232,7 +272,7 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { /// /// /// - fn delete( &self ) -> DBRequest { + fn delete( &self ) -> IDBRequest { js!( return @{self.as_ref()}.delete(); ).try_into().unwrap() } } @@ -287,7 +327,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// This is for retrieving specific records from an object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/get) - fn get( &self, query: Value) -> DBRequest { + fn get( &self, query: Value) -> IDBRequest { js! ( return @{self.as_ref()}.get(@{query.as_ref()}); ).try_into().unwrap() @@ -297,7 +337,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// This is for retrieving specific records from an object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getKey) - fn get_key( &self, query: Value) -> DBRequest { + fn get_key( &self, query: Value) -> IDBRequest { js! ( return @{self.as_ref()}.getKey(@{query.as_ref()}); ).try_into().unwrap() @@ -307,7 +347,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// /// /// - fn get_all>, C: Into>>( &self, query: Q, count: C) -> DBRequest { + fn get_all>, C: Into>>( &self, query: Q, count: C) -> IDBRequest { match query.into() { None => js! ( return @{self.as_ref()}.getAll(); ), Some(query) => { @@ -324,7 +364,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// /// /// - fn get_all_keys>, C: Into>>( &self, query: Q, count: C) -> DBRequest { + fn get_all_keys>, C: Into>>( &self, query: Q, count: C) -> IDBRequest { match query.into() { None => js! ( return @{self.as_ref()}.getAllKeys(); ), Some(query) => { @@ -340,7 +380,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// /// /// - fn count>>( &self, query: Q) -> DBRequest { + fn count>>( &self, query: Q) -> IDBRequest { match query.into() { None => js! ( return @{self.as_ref()}.count(); @@ -355,7 +395,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// /// /// - fn open_cursor>, D: Into>>( &self, query: Q, direction: D) -> DBRequest { + fn open_cursor>, D: Into>>( &self, query: Q, direction: D) -> IDBRequest { match query.into() { None => js! ( return @{self.as_ref()}.openCursor(); ), Some(query) => { @@ -371,7 +411,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// /// /// - fn open_key_cursor>, D: Into>>( &self, query: Q, direction: D) -> DBRequest { + fn open_key_cursor>, D: Into>>( &self, query: Q, direction: D) -> IDBRequest { match query.into() { None => js! ( return @{self.as_ref()}.openKeyCursor(); ), Some(query) => { @@ -474,7 +514,7 @@ impl IDBObjectStore { /// The key is only needed if /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put) - pub fn put>>( &self, value: Value, key: T) -> DBRequest { + pub fn put>>( &self, value: Value, key: T) -> IDBRequest { match key.into() { None => js! ( return @{self.as_ref()}.put(@{value.as_ref()}); @@ -489,7 +529,7 @@ impl IDBObjectStore { /// Returns an `IDBRequest` object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add) - pub fn add>>( &self, value: Value, key: T) -> DBRequest { + pub fn add>>( &self, value: Value, key: T) -> IDBRequest { match key.into() { None => js! ( return @{self.as_ref()}.add(@{value.as_ref()}); @@ -504,7 +544,7 @@ impl IDBObjectStore { /// returns an `IDBRequest` object, and, in a separate thread, deletes the specified record or records. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete) - pub fn delete( &self, query: Value) -> DBRequest { + pub fn delete( &self, query: Value) -> IDBRequest { js! ( return @{self.as_ref()}.delete(@{query.as_ref()}); ).try_into().unwrap() @@ -514,7 +554,7 @@ impl IDBObjectStore { /// Returns an IDBRequest object, and clears this object store in a separate thread /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/clear) - pub fn clear( &self ) -> DBRequest { + pub fn clear( &self ) -> IDBRequest { js! ( return @{self.as_ref()}.clear(); ).try_into().unwrap() From a3da60633ba82d22667930a4f118e978eca0b86c Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 25 Jun 2018 18:59:32 +0000 Subject: [PATCH 15/85] Finished with IDBRequest. --- examples/indexeddb/src/main.rs | 6 +++--- src/webapi/indexeddb.rs | 23 ++++++++++++----------- 2 files changed, 15 insertions(+), 14 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 365b563f..8084ead5 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -71,7 +71,7 @@ fn display_data_inner(db: &IDBDatabase) { // Get a reference to the cursor let db_request: IDBRequest = e.target().unwrap().try_into().unwrap(); //let cursor: IDBCursorWithValue = db_request.result().try_into().unwrap(); - let maybe_cursor: Result = db_request.result().try_into(); + let maybe_cursor: Result = db_request.result().unwrap().try_into(); // If there is still another data item to iterate through, keep running this code if let Ok(cursor) = maybe_cursor { @@ -183,7 +183,7 @@ fn main() { let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); // Store the opened database object in the db variable. This is used a lot below - let db : IDBDatabase = db_request.result().try_into().unwrap(); + let db : IDBDatabase = db_request.result().unwrap().try_into().unwrap(); DB.with(|db_cell| { db_cell.replace(Some(db)); @@ -194,7 +194,7 @@ fn main() { request.add_event_listener( |event: IDBVersionChangeEvent| { let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); - let db_: IDBDatabase = db_request.result().try_into().unwrap(); + let db_: IDBDatabase = db_request.result().unwrap().try_into().unwrap(); // Create an object_store to store our notes in (basically like a single table) // including a auto-incrementing key diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index aa772c32..c7383ff7 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -2,7 +2,7 @@ use webcore::value::Value; use webcore::value::Reference; use webcore::try_from::TryInto; use webapi::event_target::{IEventTarget, EventTarget}; -use webapi::dom_exception::InvalidStateError; +use webapi::dom_exception::{DomException, InvalidStateError}; /// Used to represent the state of an IDBRequest. /// @@ -30,19 +30,20 @@ pub enum IDBRequestSource { /// IDBOpenDBRequest and IDBRequest. pub trait IDBRequestSharedMethods : IEventTarget { + /// The result read-only property of the `IDBRequest` interface returns the result of the request, + /// or if the request failed InvalidStateError. /// + /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/result) + fn result( &self ) -> Result { + js_try!( return @{self.as_ref()}.result; ).unwrap() + } + + /// Returns the error in the event of an unsuccessful request. /// - /// - fn result( &self ) -> Value { - js!( return @{self.as_ref()}.result; ) + /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/error) + fn error(&self) -> Option { + js!( @{self.as_ref()}.error;).try_into().unwrap() } - //fn result( &self ) -> Result { - // js_try!( return @{self.as_ref()}.result; ).unwrap() - //} - - /*fn error(&self) -> DOMException { - -}*/ /// Returns the source of the request. /// From e78d890a2cd2b8706daba336ce4ac4129bd8638f Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 25 Jun 2018 19:27:35 +0000 Subject: [PATCH 16/85] Finished with IDBOpenDBRequest. --- examples/indexeddb/src/main.rs | 2 +- src/webapi/indexeddb.rs | 11 +++++++++++ 2 files changed, 12 insertions(+), 1 deletion(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 8084ead5..c2f1a2c2 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -183,7 +183,7 @@ fn main() { let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); // Store the opened database object in the db variable. This is used a lot below - let db : IDBDatabase = db_request.result().unwrap().try_into().unwrap(); + let db : IDBDatabase = db_request.database_result().unwrap(); DB.with(|db_cell| { db_cell.replace(Some(db)); diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index c7383ff7..d63e7faf 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -129,6 +129,17 @@ pub struct IDBOpenDBRequest( Reference ); impl IEventTarget for IDBOpenDBRequest {} impl IDBRequestSharedMethods for IDBOpenDBRequest {} +impl IDBOpenDBRequest { + + /// Returns the value property as an `IDBDatabase`, or an `InvalidStateError`. + pub fn database_result(&self) -> Result { + match self.result() { + Ok(value) => Ok(value.try_into().unwrap()), + Err(error) => Err(error) + } + } +} + /// The `IDBFactory` interface of the IndexedDB API lets applications asynchronously access the indexed databases. The object that implements the interface is `window.indexedDB`. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory) From 0dca1a062b7447a05250e02298d2f2287fd04341 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 25 Jun 2018 22:31:35 +0000 Subject: [PATCH 17/85] working on the advance method in IDBCursorSharedMethods. --- src/webapi/dom_exception.rs | 11 +++++++ src/webapi/indexeddb.rs | 64 +++++++++++++++++++++++++++++++------ 2 files changed, 65 insertions(+), 10 deletions(-) diff --git a/src/webapi/dom_exception.rs b/src/webapi/dom_exception.rs index 70cee7cc..8b65a831 100644 --- a/src/webapi/dom_exception.rs +++ b/src/webapi/dom_exception.rs @@ -143,6 +143,17 @@ impl IDomException for InvalidPointerId {} error_boilerplate! { InvalidPointerId, name = "InvalidPointerId" } +/// The cursor is currently being iterated or has iterated past its end. +#[derive(Clone, Debug, ReferenceType)] +#[reference(subclass_of(Error, DomException))] +pub struct TransactionInactiveError( Reference ); + +impl IError for TransactionInactiveError {} +impl IDomException for TransactionInactiveError {} + +error_boilerplate! { TransactionInactiveError, name = "TransactionInactiveError" } + + #[cfg(all(test, feature = "web_test"))] mod test { use super::*; diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index d63e7faf..e8d702e4 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -1,8 +1,8 @@ use webcore::value::Value; use webcore::value::Reference; -use webcore::try_from::TryInto; +use webcore::try_from::{TryFrom, TryInto}; use webapi::event_target::{IEventTarget, EventTarget}; -use webapi::dom_exception::{DomException, InvalidStateError}; +use webapi::dom_exception::{DomException, InvalidStateError, TypeError, TransactionInactiveError}; /// Used to represent the state of an IDBRequest. /// @@ -225,10 +225,42 @@ fn string_to_cursor_direction( direction: &str) -> IDBCursorDirection { } } +/// This enum is used to represent the vlaue of the soure property of +/// a `IDBCursor`. +#[derive(Debug)] +pub enum IDBCursorSource { + Store(IDBObjectStore), + Index(IDBIndex) +} + +error_enum_boilerplate! { + /// An enum of the exceptions that IDBCursorSharedMethods.advance() may throw + AdvanceError, + /// This IDBCursor's transaction is inactive. + TransactionInactiveError, + /// The value passed into the count parameter was zero or a negative number. + TypeError, + /// The cursor is currently being iterated or has iterated past its end. + InvalidStateError +} + /// This trait implements all the methods that are shared between -/// +/// `IDBCursor` and `IDBCursorWithValue`. pub trait IDBCursorSharedMethods: AsRef< Reference > { - //readonly attribute (IDBObjectStore or IDBIndex) source; + + /// The source read-only property of the `IDBCursor` interface returns + /// the `IDBObjectStore` or `IDBIndex` that the cursor is iterating over. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/source) + fn source( &self ) -> IDBCursorSource { + if js!( return @{self.as_ref()}.source instanceof IDBObjectStore; ).try_into().unwrap() { + IDBCursorSource::Store(js!( return @{self.as_ref()}.source ).try_into().unwrap()) + } else if js!( return @{self.as_ref()}.source instanceof IDBIndex;).try_into().unwrap() { + IDBCursorSource::Index(js!( return @{self.as_ref()}.source ).try_into().unwrap()) + } else { + panic!() + } + } /// The `direction` read-only property of the `IDBCursor` interface is /// an enum that represents the direction of traversal of the @@ -240,25 +272,37 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { return string_to_cursor_direction(&direction); } - // Todo, not sure what I'm doing with these two - //readonly attribute any key; + /// The `key` read-only property of the `IDBCursor` interface returns the key + /// for the record at the cursor's position. If the cursor is outside its range, + /// this is set to undefined. The cursor's key can be any data type. /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/key) fn key( &self ) -> Value { js!( return @{self.as_ref()}.key; ) .try_into().unwrap() } - //readonly attribute any primaryKey; + /// The `primary_key` read-only property of the `IDBCursor` interface returns + /// the cursor's current effective key. If the cursor is currently being + /// iterated or has iterated outside its range, this is set to undefined. + ///The cursor's primary key can be any data type. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/primaryKey) + fn primary_key( &self ) -> Value { + js!( + return @{self.as_ref()}.primaryKey; ) + .try_into().unwrap() + } - //void advance([EnforceRange] unsigned long count); /// /// /// - fn advance( &self, count: u32) { - js! { @{self.as_ref()}.advance(@{count}); } + fn advance( &self, count: u32) -> Result<(), AdvanceError> { + js_try!( @{self.as_ref()}.advance(@{count}); ).unwrap() } + //void continue(optional any key); /// /// From 5390ff0bf3fb4675419905139a4d43915e995744 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Tue, 26 Jun 2018 22:11:46 +0000 Subject: [PATCH 18/85] Finished with IDBCursor and IDBCursorWithValue. --- src/webapi/dom_exception.rs | 29 ++++++++++ src/webapi/indexeddb.rs | 112 ++++++++++++++++++++++++++++-------- 2 files changed, 118 insertions(+), 23 deletions(-) diff --git a/src/webapi/dom_exception.rs b/src/webapi/dom_exception.rs index 8b65a831..1c9e442a 100644 --- a/src/webapi/dom_exception.rs +++ b/src/webapi/dom_exception.rs @@ -153,6 +153,35 @@ impl IDomException for TransactionInactiveError {} error_boilerplate! { TransactionInactiveError, name = "TransactionInactiveError" } +/// The key was not valid in the context it was used. +#[derive(Clone, Debug, ReferenceType)] +#[reference(subclass_of(Error, DomException))] +pub struct DataError( Reference ); + +impl IError for DataError {} +impl IDomException for DataError {} + +error_boilerplate! { DataError, name = "DataError" } + +/// The transaction mode is read only. +#[derive(Clone, Debug, ReferenceType)] +#[reference(subclass_of(Error, DomException))] +pub struct ReadOnlyError( Reference ); + +impl IError for ReadOnlyError {} +impl IDomException for ReadOnlyError {} + +error_boilerplate! { ReadOnlyError, name = "ReadOnlyError" } + +/// The data being stored could not be cloned by the internal structured cloning algorithm. +#[derive(Clone, Debug, ReferenceType)] +#[reference(subclass_of(Error, DomException))] +pub struct DataCloneError( Reference ); + +impl IError for DataCloneError {} +impl IDomException for DataCloneError {} + +error_boilerplate! { DataCloneError, name = "DataCloneError" } #[cfg(all(test, feature = "web_test"))] mod test { diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index e8d702e4..8fff4d76 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -1,8 +1,9 @@ + use webcore::value::Value; use webcore::value::Reference; use webcore::try_from::{TryFrom, TryInto}; use webapi::event_target::{IEventTarget, EventTarget}; -use webapi::dom_exception::{DomException, InvalidStateError, TypeError, TransactionInactiveError}; +use webapi::dom_exception::{DomException, InvalidStateError, TypeError, TransactionInactiveError, DataError, InvalidAccessError, ReadOnlyError, DataCloneError}; /// Used to represent the state of an IDBRequest. /// @@ -233,17 +234,57 @@ pub enum IDBCursorSource { Index(IDBIndex) } +// Todo, rename this error_enum_boilerplate! { /// An enum of the exceptions that IDBCursorSharedMethods.advance() may throw AdvanceError, /// This IDBCursor's transaction is inactive. TransactionInactiveError, - /// The value passed into the count parameter was zero or a negative number. + /// The value passed into the parameter was zero or a negative number. TypeError, /// The cursor is currently being iterated or has iterated past its end. InvalidStateError } +error_enum_boilerplate! { + ContinuePrimaryKeyError, + /// This IDBCursor's transaction is inactive. + TransactionInactiveError, + /// The key parameter may have any of the following conditions: + /// * The key is not a valid key. + /// * The key is less than or equal to this cursor's position and the cursor's direction is next or nextunique. + /// * The key is greater than or equal to this cursor's position and this cursor's direction is prev or prevunique. + DataError, + /// The cursor is currently being iterated or has iterated past its end. + InvalidStateError, + /// The cursor's direction is not prev or next. + InvalidAccessError +} + +error_enum_boilerplate! { + UpdateError, + /// This IDBCursor's transaction is inactive. + TransactionInactiveError, + /// The transaction mode is read only. + ReadOnlyError, + /// The cursor was created using IDBIndex.openKeyCursor, is currently being iterated, or has iterated past its end. + InvalidStateError, + /// The underlying object store uses in-line keys and the property in the value at the object store's key path does not match the key in this cursor's position. + DataError, + ///The data being stored could not be cloned by the internal structured cloning algorithm. + DataCloneError +} + +error_enum_boilerplate! { + DeleteError, + /// This IDBCursor's transaction is inactive. + TransactionInactiveError, + /// The transaction mode is read-only. + ReadOnlyError, + /// The cursor was created using IDBindex.openKeyCursor, is currently being iterated, or has iterated past its end. + InvalidStateError +} + /// This trait implements all the methods that are shared between /// `IDBCursor` and `IDBCursorWithValue`. pub trait IDBCursorSharedMethods: AsRef< Reference > { @@ -295,52 +336,75 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { .try_into().unwrap() } - /// - /// + /// The advance() method of the IDBCursor interface sets the number of times + /// a cursor should move its position forward. /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/advance) fn advance( &self, count: u32) -> Result<(), AdvanceError> { js_try!( @{self.as_ref()}.advance(@{count}); ).unwrap() } - - - //void continue(optional any key); - /// + + /// The next() method of the IDBCursor interface advances the cursor to the + /// next position along its direction, to the item whose key matches the optional + /// key parameter. If no key (None) is specified, the cursor advances to the immediate + /// next position, based on its direction. /// + /// This function stands in for continue in the javascript interface. Continue + /// is a keyword in rust and so needed to be renamed. /// - fn advance_to_match>>( &self, key: K) { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/continue) + fn next>>( &self, key: K) -> Result<(), AdvanceError> { match key.into() { - None => js! { @{self.as_ref()}.continue(); }, - Some(key) => js! { @{self.as_ref()}.continue(@{key.as_ref()}); } - }; + None => js_try!( @{self.as_ref()}.continue(); ).unwrap(), + Some(key) => js_try! ( @{self.as_ref()}.continue(@{key.as_ref()}); ).unwrap() + } } - - //void continuePrimaryKey(any key, any primaryKey); - //[NewObject] IDBRequest update(any value); - /// - /// + /// The continuePrimaryKey() method of the IDBCursor interface advances + /// the cursor to the to the item whose key matches the key parameter as + /// well as whose primary key matches the primary key parameter. /// - fn update( &self, value: Value) -> IDBRequest { - js! ( return @{self.as_ref()}.update(@{value.as_ref()}); ).try_into().unwrap() + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/continuePrimaryKey) + fn continue_primary_key( &self, key: Value, primary_key: Value) -> Result<(), ContinuePrimaryKeyError> { + js_try!( @{self.as_ref()}.continuePrimaryKey(@{key}, @{primary_key}); ).unwrap() } - //[NewObject] IDBRequest delete(); - /// + /// The update() method of the IDBCursor interface returns an IDBRequest + /// object, and, in a separate thread, updates the value at the current + /// position of the cursor in the object store. If the cursor points to + /// a record that has just been deleted, a new record is created. /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/update) + fn update( &self, value: Value) -> Result { + js_try!( return @{self.as_ref()}.update(@{value.as_ref()}); ).unwrap() + } + + /// The delete() method of the IDBCursor interface returns an IDBRequest + /// object, and, in a separate thread, deletes the record at the cursor's + /// position, without changing the cursor's position. Once the record is + /// deleted, the cursor's value is set to null. /// - fn delete( &self ) -> IDBRequest { - js!( return @{self.as_ref()}.delete(); ).try_into().unwrap() + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete) + fn delete( &self ) -> Result { + js_try!( return @{self.as_ref()}.delete(); ).unwrap() } } +/// The IDBCursor interface of the IndexedDB API represents a cursor for +/// traversing or iterating over multiple records in a database. /// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBCursor")] pub struct IDBCursor( Reference ); impl IDBCursorSharedMethods for IDBCursor {} +/// The IDBCursorWithValue interface of the IndexedDB API represents a cursor +/// for traversing or iterating over multiple records in a database. It is +/// the same as the IDBCursor, except that it includes the value property. /// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursorWithValue) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBCursorWithValue")] pub struct IDBCursorWithValue( Reference ); @@ -349,7 +413,9 @@ impl IDBCursorSharedMethods for IDBCursorWithValue {} impl IDBCursorWithValue { + /// Returns the value of the current cursor. /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursorWithValue/value) pub fn value( &self ) -> Value { js! ( return @{self}.value From bea659a3d451f7b0aaa5be15b9fd0a3fc2d73aa7 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 16 Jul 2018 21:36:46 +0000 Subject: [PATCH 19/85] Not finished with create_index or delete index. --- examples/indexeddb/src/main.rs | 4 +- src/webapi/dom_exception.rs | 20 ++ src/webapi/indexeddb.rs | 358 +++++++++++++++++++++++---------- 3 files changed, 269 insertions(+), 113 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index c2f1a2c2..58e99392 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -66,7 +66,7 @@ fn display_data_inner(db: &IDBDatabase) { // Open our object store and then get a cursor - which iterates through all the // different data items in the store let object_store = db.transaction("notes", "readonly").object_store("notes"); - object_store.open_cursor(None, None) + object_store.open_cursor(None, None).unwrap() .add_event_listener( move |e: IDBSuccessEvent| { // Get a reference to the cursor let db_request: IDBRequest = e.target().unwrap().try_into().unwrap(); @@ -237,7 +237,7 @@ fn main() { let object_store = transaction.object_store("notes"); // Make a request to add our new_item object to the object store - let request = object_store.add(new_item.try_into().unwrap(), None); + let request = object_store.add(new_item.try_into().unwrap(), None).unwrap(); request.add_event_listener( move |_e: IDBSuccessEvent| { // Clear the form, ready for adding the next entry diff --git a/src/webapi/dom_exception.rs b/src/webapi/dom_exception.rs index 1c9e442a..85ef08ad 100644 --- a/src/webapi/dom_exception.rs +++ b/src/webapi/dom_exception.rs @@ -183,6 +183,26 @@ impl IDomException for DataCloneError {} error_boilerplate! { DataCloneError, name = "DataCloneError" } +/// An index or an object store already has this name +#[derive(Clone, Debug, ReferenceType)] +#[reference(subclass_of(Error, DomException))] +pub struct ConstraintError( Reference ); + +impl IError for ConstraintError {} +impl IDomException for ConstraintError {} + +error_boilerplate! { ConstraintError, name = "ConstraintError" } +/* +/// There is no index with the given name (case-sensitive) in the database. +#[derive(Clone, Debug, ReferenceType)] +#[reference(subclass_of(Error, DomException))] +pub struct NotFoundError( Reference ); + +impl IError for NotFoundError {} +impl IDomException for NotFoundError {} + +error_boilerplate! { NotFoundError, name = "NotFoundError" } +*/ #[cfg(all(test, feature = "web_test"))] mod test { use super::*; diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 8fff4d76..835d223f 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -3,7 +3,7 @@ use webcore::value::Value; use webcore::value::Reference; use webcore::try_from::{TryFrom, TryInto}; use webapi::event_target::{IEventTarget, EventTarget}; -use webapi::dom_exception::{DomException, InvalidStateError, TypeError, TransactionInactiveError, DataError, InvalidAccessError, ReadOnlyError, DataCloneError}; +use webapi::dom_exception::{DomException, InvalidStateError, TypeError, TransactionInactiveError, DataError, InvalidAccessError, ReadOnlyError, DataCloneError, ConstraintError, NotFoundError}; /// Used to represent the state of an IDBRequest. /// @@ -275,6 +275,22 @@ error_enum_boilerplate! { DataCloneError } +error_enum_boilerplate! { + UpdateWithConstraintError, + /// This IDBCursor's transaction is inactive. + TransactionInactiveError, + /// The transaction mode is read only. + ReadOnlyError, + /// The cursor was created using IDBIndex.openKeyCursor, is currently being iterated, or has iterated past its end. + InvalidStateError, + /// The underlying object store uses in-line keys and the property in the value at the object store's key path does not match the key in this cursor's position. + DataError, + ///The data being stored could not be cloned by the internal structured cloning algorithm. + DataCloneError, + /// An operation failed because the primary key constraint was violated (due to an already existing record with the same primary key value). + ConstraintError +} + error_enum_boilerplate! { DeleteError, /// This IDBCursor's transaction is inactive. @@ -285,6 +301,23 @@ error_enum_boilerplate! { InvalidStateError } +// Todo this is fpr IDBObjectStore::delete +error_enum_boilerplate! { + Delete2Error, + + TransactionInactiveError, // This object store's transaction is inactive. + ReadOnlyError, // The object store's transaction mode is read-only. + InvalidStateError, // The object store has been deleted. + DataError // The key is not a valid key or a key range. +} + +error_enum_boilerplate! { + ClearError, + + ReadOnlyError, // The transaction associated with this operation is in read-only mode. + TransactionInactiveError // This IDBObjectStore's transaction is inactive. +} + /// This trait implements all the methods that are shared between /// `IDBCursor` and `IDBCursorWithValue`. pub trait IDBCursorSharedMethods: AsRef< Reference > { @@ -423,11 +456,96 @@ impl IDBCursorWithValue { } } +/// The IDBKeyRange interface of the IndexedDB API represents a continuous interval +/// over some data type that is used for keys. Records can be retrieved from +/// IDBObjectStore and IDBIndex objects using keys or a range of keys. You can limit +/// the range using lower and upper bounds. For example, you can iterate over all +/// values of a key in the value range A–Z. +/// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange) +#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] +#[reference(instance_of = "IDBKeyRange")] +pub struct IDBKeyRange( Reference ); + +impl IDBKeyRange { + + /// Lower bound of the key range. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/lower) + pub fn lower( &self ) -> Value { + js!( return @{self}.lower; ).try_into().unwrap() + } + + /// Upper bound of the key range. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/upper) + pub fn upper( &self ) -> Value { + js!( return @{self}.upper; ).try_into().unwrap() + } + + /// Returns false if the lower-bound value is included in the key range. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/lowerOpen) + pub fn lower_open( &self ) -> bool { + js!( return @{self}.lowerOpen; ).try_into().unwrap() + } + + /// Returns false if the upper-bound value is included in the key range. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/upperOpen) + pub fn upper_open( &self ) -> bool { + js!( return @{self}.upperOpen; ).try_into().unwrap() + } +} + +#[derive(Debug)] +pub enum IDBKeyOrKeyRange { + None, + Value(Value), + Range(IDBKeyRange) +} + +error_enum_boilerplate! { + SetNameError, + + /// The index, or its object store, has been deleted; or the current transaction + /// is not an upgrade transaction. You can only rename indexes during upgrade + /// transactions; that is, when the mode is "versionchange". + InvalidStateError, + + /// The current transaction is not active. + TransactionInactiveError, + + /// An index is already using the specified name + ConstraintError +} + +// Todo, this needs renamed as it is used places other than the count method +error_enum_boilerplate! { + IDBCountError, + + /// This IDBIndex's transaction is inactive. + TransactionInactiveError, + + /// The key or key range provided contains an invalid key. + DataError, + + /// The IDBIndex has been deleted or removed. + InvalidStateError +} + +error_enum_boilerplate! { + IndexError, + + InvalidStateError, // The source object store has been deleted, or the transaction for the object store has finished. + NotFoundError // There is no index with the given name (case-sensitive) in the database. + +} + /// This trait contains mothods that are Identicle in both IDBIndex IDBObjectStore pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { - // attribute DOMString name; - /// Returns the name of this object store. + /// Returns the name of this index or object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/name) fn name( &self ) -> String { @@ -436,113 +554,150 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { ).try_into().unwrap() } - /// Returns the name of this object store. + /// Returns the name of this index or object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/name) - fn set_name( &self, name: &str) { - js! { - @{self.as_ref()}.name = @{name}; - }; + fn set_name( &self, name: &str) -> Result<(), SetNameError> { + js_try! ( @{self.as_ref()}.name = @{name}; ).unwrap() } - // [NewObject] IDBRequest get(any query); - /// This is for retrieving specific records from an object store. + /// The key_path read-only property of the IDBObjectStore interface returns the + /// key path of this object store. Or in the case of an IDBIndex, the current + /// object store. + fn key_path( &self ) -> Value { + js!( return @{self.as_ref()}.keyPath; ).try_into().unwrap() + } + + /// This is for retrieving specific records from an object store or index. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/get) - fn get( &self, query: Value) -> IDBRequest { - js! ( - return @{self.as_ref()}.get(@{query.as_ref()}); - ).try_into().unwrap() + fn get>( &self, query: Q) -> Result { + match query.into() { + IDBKeyOrKeyRange::None => js_try! ( + return @{self.as_ref()}.get(); + ), + IDBKeyOrKeyRange::Value(value) => js_try! ( + return @{self.as_ref()}.get(@{value.as_ref()}); + ), + IDBKeyOrKeyRange::Range(range) => js_try! ( + return @{self.as_ref()}.get(@{range.as_ref()}); + ) + }.unwrap() } - - // [NewObject] IDBRequest getKey(any query); + + // Todo, I think this description is wrong. /// This is for retrieving specific records from an object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getKey) - fn get_key( &self, query: Value) -> IDBRequest { - js! ( - return @{self.as_ref()}.getKey(@{query.as_ref()}); - ).try_into().unwrap() + fn get_key>( &self, query: Q) -> Result { + match query.into() { + IDBKeyOrKeyRange::None => js_try! ( + return @{self.as_ref()}.getKey(); + ), + IDBKeyOrKeyRange::Value(value) => js_try! ( + return @{self.as_ref()}.getKey(@{value.as_ref()}); + ), + IDBKeyOrKeyRange::Range(range) => js_try! ( + return @{self.as_ref()}.getKey(@{range.as_ref()}); + ) + }.unwrap() } - // [NewObject] IDBRequest getAll(optional any query, optional [EnforceRange] unsigned long count); - /// - /// + /// The get_ll() method retrieves all objects that are inside the index or + /// object store. /// - fn get_all>, C: Into>>( &self, query: Q, count: C) -> IDBRequest { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/getAll) + fn get_all, C: Into>>( &self, query: Q, count: C) -> Result { match query.into() { - None => js! ( return @{self.as_ref()}.getAll(); ), - Some(query) => { + IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAll(); ), + IDBKeyOrKeyRange::Value(value) => { match count.into() { - None => js! ( return @{self.as_ref()}.getAll(@{query.as_ref()}); ), - Some(count) => js! ( return @{self.as_ref()}.getAll(@{query.as_ref()}, @{count}); ) + None => js_try! ( return @{self.as_ref()}.getAll(@{value.as_ref()}); ), + Some(count) => js_try! ( return @{self.as_ref()}.getAll(@{value.as_ref()}, @{count}); ) + } + }, + IDBKeyOrKeyRange::Range(range) => { + match count.into() { + None => js_try! ( return @{self.as_ref()}.getAll(@{range.as_ref()}); ), + Some(count) => js_try! ( return @{self.as_ref()}.getAll(@{range.as_ref()}, @{count}); ) } } - }.try_into().unwrap() + }.unwrap() } - - // [NewObject] IDBRequest getAllKeys(optional any query, optional [EnforceRange] unsigned long count); + // Todo, acording to the mozilla documentation the IDBIndex version does not + // Throw DataError. + /// The get_all_keys() method returns an IDBRequest object retrieves record keys + /// for all objects matching the specified parameter or all objects if no + /// parameters are given. /// - /// - /// - fn get_all_keys>, C: Into>>( &self, query: Q, count: C) -> IDBRequest { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys) + fn get_all_keys, C: Into>>( &self, query: Q, count: C) -> Result { match query.into() { - None => js! ( return @{self.as_ref()}.getAllKeys(); ), - Some(query) => { + IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAllKeys(); ), + IDBKeyOrKeyRange::Value(value) => { + match count.into() { + None => js_try! ( return @{self.as_ref()}.getAllKeys(@{value.as_ref()}); ), + Some(count) => js_try! ( return @{self.as_ref()}.getAllKeys(@{value.as_ref()}, @{count}); ) + } + }, + IDBKeyOrKeyRange::Range(range) => { match count.into() { - None => js! ( return @{self.as_ref()}.getAllKeys(@{query.as_ref()}); ), - Some(count) => js! ( return @{self.as_ref()}.getAllKeys(@{query.as_ref()}, @{count}); ) + None => js_try! ( return @{self.as_ref()}.getAllKeys(@{range.as_ref()}); ), + Some(count) => js_try! ( return @{self.as_ref()}.getAllKeys(@{range.as_ref()}, @{count}); ) } } - }.try_into().unwrap() + }.unwrap() } - // [NewObject] IDBRequest count(optional any query); + /// Returns an IDBRequest object, and, in a separate thread, returns the total number of records that match the provided key or IDBKeyRange /// - /// - /// - fn count>>( &self, query: Q) -> IDBRequest { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/count) + fn count>( &self, query: Q) -> Result { match query.into() { - None => js! ( + IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.count(); ), - Some(query) => js! ( - return @{self.as_ref()}.count(@{query.as_ref()}); + IDBKeyOrKeyRange::Value(value) => js_try! ( + return @{self.as_ref()}.count(@{value.as_ref()}); + ), + IDBKeyOrKeyRange::Range(range) => js_try! ( + return @{self.as_ref()}.count(@{range.as_ref()}); ) - }.try_into().unwrap() + }.unwrap() } - // [NewObject] IDBRequest openCursor(optional any query, optional IDBCursorDirection direction = "next"); - /// + /// The open_cursor() method returns an IDBRequest object, and, in a separate + /// thread, creates a cursor over the specified key range. /// - /// - fn open_cursor>, D: Into>>( &self, query: Q, direction: D) -> IDBRequest { - match query.into() { - None => js! ( return @{self.as_ref()}.openCursor(); ), - Some(query) => { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openCursor) + fn open_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { + match range.into() { + None => js_try! ( return @{self.as_ref()}.openCursor(); ), + Some(range) => { match direction.into() { - None => js! ( return @{self.as_ref()}.openCursor(@{query.as_ref()}); ), - Some(direction) => js! ( return @{self.as_ref()}.openCursor(@{query.as_ref()}, @{cursor_direction_to_string(direction)}); ) + None => js_try! ( return @{self.as_ref()}.openCursor(@{range.as_ref()}); ), + Some(direction) => js_try! ( return @{self.as_ref()}.openCursor(@{range.as_ref()}, @{cursor_direction_to_string(direction)}); ) } } - }.try_into().unwrap() + }.unwrap() } - // [NewObject] IDBRequest openKeyCursor(optional any query, optional IDBCursorDirection direction = "next"); - /// - /// - /// - fn open_key_cursor>, D: Into>>( &self, query: Q, direction: D) -> IDBRequest { - match query.into() { - None => js! ( return @{self.as_ref()}.openKeyCursor(); ), - Some(query) => { + /// The open_key_cursor() method returns an IDBRequest object, and, in a + /// separate thread, creates a cursor over the specified key range, as arranged + /// by this index. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openKeyCursor) + fn open_key_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { + match range.into() { + None => js_try! ( return @{self.as_ref()}.openKeyCursor(); ), + Some(range) => { match direction.into() { - None => js! ( return @{self.as_ref()}.openKeyCursor(@{query.as_ref()}); ), - Some(direction) => js! ( return @{self.as_ref()}.openKeyCursor(@{query.as_ref()}, @{cursor_direction_to_string(direction)}); ) + None => js_try! ( return @{self.as_ref()}.openKeyCursor(@{range.as_ref()}); ), + Some(direction) => js_try! ( return @{self.as_ref()}.openKeyCursor(@{range.as_ref()}, @{cursor_direction_to_string(direction)}); ) } } - }.try_into().unwrap() + }.unwrap() } } @@ -557,13 +712,14 @@ pub struct IDBIndex( Reference ); impl IDBObjectStoreIndexSharedMethods for IDBIndex {} impl IDBIndex { - //attribute DOMString name; - // Implemented in trait. - //[SameObject] readonly attribute IDBObjectStore objectStore; - //readonly attribute any keyPath; + /// The object_store property of the IDBIndex interface returns the name of the object store referenced by the current index. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/objectStore) + pub fn object_store( &self ) -> IDBObjectStore { + js! ( return @{self.as_ref()}.objectStore ).try_into().unwrap() + } - //readonly attribute boolean multiEntry; /// Affects how the index behaves when the result of evaluating the index's key path yields an array. If `true`, there is one record in the index for each item in an array of keys. If `false`, then there is one record for each key that is an array. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/multiEntry) @@ -573,7 +729,6 @@ impl IDBIndex { ).try_into().unwrap() } - //readonly attribute boolean unique; /// If `true`, this index does not allow duplicate values for a key. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/unique) @@ -583,14 +738,6 @@ impl IDBIndex { ).try_into().unwrap() } - // The rest of this is implemented in the trait - //[NewObject] IDBRequest get(any query); - //[NewObject] IDBRequest getKey(any query); - //[NewObject] IDBRequest getAll(optional any query, optional [EnforceRange] unsigned long count); - //[NewObject] IDBRequest getAllKeys(optional any query, optional [EnforceRange] unsigned long count); - //[NewObject] IDBRequest count(optional any query); - //[NewObject] IDBRequest openCursor(optional any query, optional IDBCursorDirection direction = "next"); - //[NewObject] IDBRequest openKeyCursor(optional any query, optional IDBCursorDirection direction = "next"); } /// The `IDBObjectStore` interface of the IndexedDB API represents an object store in a database @@ -603,15 +750,10 @@ pub struct IDBObjectStore( Reference ); impl IDBObjectStoreIndexSharedMethods for IDBObjectStore {} impl IDBObjectStore { - - - // readonly attribute any keyPath; - // Todo, how am I wrapping this. - + // readonly attribute DOMStringList indexNames; // TODO: how am I wrapping this - // [SameObject] readonly attribute IDBTransaction transaction; /// The `IDBTransaction` object to which this object store belongs. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/transaction) @@ -621,7 +763,6 @@ impl IDBObjectStore { ).try_into().unwrap() } - // readonly attribute boolean autoIncrement; /// Returns the value of the auto increment flag for this object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/autoIncrement) @@ -631,65 +772,60 @@ impl IDBObjectStore { ).try_into().unwrap() } - // [NewObject] IDBRequest put(any value, optional any key); /// Updates a given record in a database, or inserts a new record if the given item does not already exist. /// The key is only needed if /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put) - pub fn put>>( &self, value: Value, key: T) -> IDBRequest { + pub fn put>>( &self, value: Value, key: T) -> Result { match key.into() { - None => js! ( + None => js_try! ( return @{self.as_ref()}.put(@{value.as_ref()}); ), - Some(key) => js! ( + Some(key) => js_try! ( return @{self.as_ref()}.put(@{value.as_ref()}, @{key.as_ref()}); ) - }.try_into().unwrap() + }.unwrap() } - // [NewObject] IDBRequest add(any value, optional any key); /// Returns an `IDBRequest` object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add) - pub fn add>>( &self, value: Value, key: T) -> IDBRequest { + pub fn add>>( &self, value: Value, key: T) -> Result { match key.into() { - None => js! ( + None => js_try! ( return @{self.as_ref()}.add(@{value.as_ref()}); ), - Some(key) => js! ( + Some(key) => js_try! ( return @{self.as_ref()}.add(@{value.as_ref()}, @{key.as_ref()}); ) - }.try_into().unwrap() + }.unwrap() } - // [NewObject] IDBRequest delete(any query); /// returns an `IDBRequest` object, and, in a separate thread, deletes the specified record or records. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete) - pub fn delete( &self, query: Value) -> IDBRequest { - js! ( + pub fn delete( &self, query: Value) -> Result { + js_try! ( return @{self.as_ref()}.delete(@{query.as_ref()}); - ).try_into().unwrap() + ).unwrap() } - // [NewObject] IDBRequest clear(); /// Returns an IDBRequest object, and clears this object store in a separate thread /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/clear) - pub fn clear( &self ) -> IDBRequest { - js! ( + pub fn clear( &self ) -> Result { + js_try! ( return @{self.as_ref()}.clear(); - ).try_into().unwrap() + ).unwrap() } - // IDBIndex index(DOMString name); /// opens a named index in the current object store /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/index) - pub fn index( &self, name: &str) -> IDBIndex { - js! ( + pub fn index( &self, name: &str) -> Result { + js_try! ( return @{self.as_ref()}.index(@{name}); - ).try_into().unwrap() + ).unwrap() } // [NewObject] IDBIndex createIndex(DOMString name, (DOMString or sequence) keyPath, optional IDBIndexParameters options); From c45baaa235b0050738650392e399bc68c731f3d1 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Mon, 16 Jul 2018 22:19:32 +0000 Subject: [PATCH 20/85] Finished with IDBKeyRange --- src/webapi/indexeddb.rs | 48 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 835d223f..1f2e7be1 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -469,6 +469,46 @@ pub struct IDBKeyRange( Reference ); impl IDBKeyRange { + // Static construction methods: + + /// The only() method of the IDBKeyRange interface creates a new key range + /// containing a single value. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/only) + pub fn only( value: Value ) -> Result { + js_try! ( return IDBKeyRange.only(@{value}); ).unwrap() + } + + /// The lower_bound() method of the IDBKeyRange interface creates a new key range + /// with only a lower bound. if open is false it includes the lower endpoint + /// value and is closed. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/lowerBound) + pub fn lower_bound( lower: Value, open: bool ) -> Result { + js_try! ( return IDBKeyRange.lowerBound(@{lower}, @{open}); ).unwrap() + } + + /// The upper_bound() method of the IDBKeyRange interface creates a new key range + /// with only an apper bound. if open is false it includes the upper endpoint + /// value and is closed. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/upperBound) + pub fn upper_bound( upper: Value, open: bool ) -> Result { + js_try! ( return IDBKeyRange.upperBound(@{upper}, @{open}); ).unwrap() + } + + /// The bound() method of the IDBKeyRange interface creates a new key range + /// with the specified upper and lower bounds. The bounds can be open (that + /// is, the bounds exclude the endpoint values) or closed (that is, the bounds + /// include the endpoint values). + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/bound) + pub fn bound (lower: Value, upper: Value, lower_open: bool, upper_open: bool) -> Result { + js_try! ( + return IDBKeyRange.boundound(@{lower}, @{upper}, @{lower_open}, @{upper_open}); + ).unwrap() + } + /// Lower bound of the key range. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/lower) @@ -496,6 +536,14 @@ impl IDBKeyRange { pub fn upper_open( &self ) -> bool { js!( return @{self}.upperOpen; ).try_into().unwrap() } + + /// The includes() method of the IDBKeyRange interface returns a boolean + /// indicating whether a specified key is inside the key range. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/includes) + pub fn includes( &self, value: Value ) -> Result { + js_try! ( return @{self}.includes(@{value}); ).unwrap() + } } #[derive(Debug)] From 6054f0fcfe9b35ddf17e9c0326f6eab9bb59d6a7 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Tue, 17 Jul 2018 21:04:26 +0000 Subject: [PATCH 21/85] Some more of IDBTransaction. --- examples/indexeddb/src/main.rs | 6 +-- src/webapi/indexeddb.rs | 82 ++++++++++++++++++++++++---------- 2 files changed, 62 insertions(+), 26 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 58e99392..0a00ec6e 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -65,7 +65,7 @@ fn display_data_inner(db: &IDBDatabase) { } // Open our object store and then get a cursor - which iterates through all the // different data items in the store - let object_store = db.transaction("notes", "readonly").object_store("notes"); + let object_store = db.transaction("notes", "readonly").object_store("notes").unwrap(); object_store.open_cursor(None, None).unwrap() .add_event_listener( move |e: IDBSuccessEvent| { // Get a reference to the cursor @@ -139,7 +139,7 @@ fn delete_item( e: ClickEvent ) { DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { let transaction = db.transaction("notes", "readwrite"); - let object_store = transaction.object_store("notes"); + let object_store = transaction.object_store("notes").unwrap(); object_store.delete(note_id.try_into().unwrap()); // report that the data item has been deleted @@ -234,7 +234,7 @@ fn main() { let transaction = db.transaction("notes", "readwrite"); // call an object store that's already been added to the database - let object_store = transaction.object_store("notes"); + let object_store = transaction.object_store("notes").unwrap(); // Make a request to add our new_item object to the object store let request = object_store.add(new_item.try_into().unwrap(), None).unwrap(); diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 1f2e7be1..fa105ced 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -902,13 +902,43 @@ impl IDBObjectStore { boolean multiEntry = false; };*/ - +#[derive(Debug)] pub enum IDBTransactionMode { ReadOnly, - Readwrite, + ReadWrite, VersionChange } +fn transaction_mode_to_string( mode: IDBTransactionMode ) -> String { + match mode { + IDBTransactionMode::ReadOnly => "readonly".to_string(), + IDBTransactionMode::ReadWrite => "readwrite".to_string(), + IDBTransactionMode::VersionChange => "versionchange".to_string() + } +} + +fn string_to_transaction_mode( mode: &str ) -> IDBTransactionMode { + if mode.eq("readonly") { + return IDBTransactionMode::ReadOnly; + } else if mode.eq("readwrite") { + return IDBTransactionMode::ReadWrite; + } else if mode.eq("versionchange") { + return IDBTransactionMode::VersionChange; + } else { + unreachable!("Unknown transaction mode \"{}\".", mode); + } +} + +error_enum_boilerplate! { + IDBObjectStoreError, + + /// The requested object store is not in this transaction's scope. + NotFoundError, + /// The request was made on a source object that has been deleted or removed, or + /// if the transaction has finished. + InvalidStateError +} + /// The `IDBTransaction` interface of the IndexedDB API provides a static, asynchronous transaction on a database using event handlers. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction) @@ -922,10 +952,17 @@ impl IDBTransaction { // readonly attribute DOMStringList objectStoreNames; // Todo, how am I wrapping DOMStringList - // readonly attribute IDBTransactionMode mode; - // Todo, should I use an enum or a string + /// The mode read-only property of the `IDBTransaction` interface returns the + /// current mode for accessing the data in the object stores in the scope of the + /// transaction (i.e. is the mode to be read-only, or do you want to write to + /// the object stores?) The default value is readonly. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/mode + pub fn mode( &self ) -> IDBTransactionMode { + let mode: String = js!( return @{self}.mode; ).try_into().unwrap(); + string_to_transaction_mode(&mode) + } - // [SameObject] readonly attribute IDBDatabase db; /// Returns the database connection with which this transaction is associated. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/db) @@ -934,27 +971,28 @@ impl IDBTransaction { return @{self}.db(); ).try_into().unwrap() } - + + // Todo // readonly attribute DOMException error; - // IDBObjectStore objectStore(DOMString name); - /// This is a method - pub fn object_store( &self, name: &str) -> IDBObjectStore { - js! ( + /// The object_store() method of the IDBTransaction interface returns an object + /// store that has already been added to the scope of this transaction. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/objectStore) + pub fn object_store( &self, name: &str) -> Result { + js_try! ( return @{self.as_ref()}.objectStore(@{name}); - ).try_into().unwrap() + ).unwrap() } - // void abort(); - // Todo, do I need to implement this or do I get it for free from IEventTarget - // /// - // /// - // /// [(JavaScript docs)] - - // Event handlers: - // attribute EventHandler onabort; - // attribute EventHandler oncomplete; - // attribute EventHandler onerror; + /// The abort() method of the IDBTransaction interface rolls back all the + /// changes to objects in the database associated with this transaction. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/abort) + pub fn abort( &self ) -> Result<(), InvalidStateError> { + js_try! ( @{self}.abort(); ).unwrap() + } + } /// The `IDBDatabase` interface of the IndexedDB API provides a connection to a database. @@ -968,7 +1006,6 @@ impl IEventTarget for IDBDatabase {} impl IDBDatabase { - // readonly attribute DOMString name; /// Returns the the name of the connected database. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/name) @@ -978,7 +1015,6 @@ impl IDBDatabase { ).try_into().unwrap() } - // readonly attribute unsigned long long version; /// Returns the version of the connected database. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/version) From 5511d2ebd26d3b79be8425ea12badb96946ae7c0 Mon Sep 17 00:00:00 2001 From: Ubuntu Date: Wed, 25 Jul 2018 18:31:39 +0000 Subject: [PATCH 22/85] Still got a couple more interfaces to finish. --- examples/indexeddb/src/main.rs | 2 +- src/webapi/indexeddb.rs | 33 ++++++++++++++++++++++++++------- 2 files changed, 27 insertions(+), 8 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 0a00ec6e..698b3ba1 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -201,7 +201,7 @@ fn main() { let mut store_options = HashMap::new(); //store_options.insert("keyPath", "id"); store_options.insert("autoIncrement", "true"); - let object_store = db_.create_object_store("notes", Value::from(store_options)); + let object_store = db_.create_object_store("notes", true, Value::from(store_options)).unwrap(); // Define what data items the object_store will contain let mut title_options = HashMap::new(); diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index fa105ced..fb043347 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -995,6 +995,26 @@ impl IDBTransaction { } +error_enum_boilerplate! { + IDBCreateObjectStoreError, + + /// Occurs if the method was not called from a versionchange transaction + /// callback. For older WebKit browsers, you must call first. + InvalidStateError, + + /// Occurs if a request is made on a source database that doesn't exist (e.g. + /// has been deleted or removed.) + TransactionInactiveError, + + /// An object store with the given name (based on case-sensitive comparison) + /// already exists in the connected database. + ConstraintError, + + /// If autoIncrement is set to true and keyPath is either an empty string or an + /// array containing an empty string. + InvalidAccessError +} + /// The `IDBDatabase` interface of the IndexedDB API provides a connection to a database. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase) @@ -1038,7 +1058,6 @@ impl IDBDatabase { ).try_into().unwrap() } - //void close(); /// Returns immediately and closes the connection in a separate thread. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/close) @@ -1048,14 +1067,14 @@ impl IDBDatabase { } } - // [NewObject] IDBObjectStore createObjectStore(DOMString name, optional IDBObjectStoreParameters options); - /// Creates and returns a new object store or index. TODO: why does this say index + /// Creates and returns a new object store or index. TODO: why does this say + /// index? /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/createObjectStore) - pub fn create_object_store( &self, name: &str, options: Value) -> IDBObjectStore { - js! ( - return @{self.as_ref()}.createObjectStore(@{name}, @{options.as_ref()}); - ).try_into().unwrap() + pub fn create_object_store( &self, name: &str, auto_increment: bool, options: Value) -> Result { + js_try! ( + return @{self.as_ref()}.createObjectStore(@{name}, { autoIncrememt: @{auto_increment}, keyPath: @{options.as_ref()} } ); + ).unwrap() } // void deleteObjectStore(DOMString name); From bcfbe69a30e79b35bcd1d2ec34c46d4893039073 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Wed, 25 Jul 2018 21:40:18 +0100 Subject: [PATCH 23/85] A little more work on IDBDatabase. --- src/webapi/indexeddb.rs | 34 ++++++++++++++++++++++------------ 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index fb043347..7b671130 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -1015,6 +1015,21 @@ error_enum_boilerplate! { InvalidAccessError } +error_enum_boilerplate! { + IDBDeleteObjectStoreError, + + /// Occurs if the method was not called from a versionchange transaction callback. + /// For older WebKit browsers, you must call first. + InvalidStateError, + + /// Occurs if a request is made on a source database that doesn't exist (e.g. has + /// been deleted or removed.) + TransactionInactiveError, + + /// You are trying to delete an object store that does not exist. Names are case sensitive. + NotFoundError +} + /// The `IDBDatabase` interface of the IndexedDB API provides a connection to a database. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase) @@ -1048,6 +1063,7 @@ impl IDBDatabase { // TODO: how should I expose DomStringList // [NewObject] IDBTransaction transaction((DOMString or sequence) storeNames, optional IDBTransactionMode mode = "readonly"); + // Todo, this can be a string or an array of strings, how to handle this /// Immediately returns a transaction object (`IDBTransaction`) containing the `IDBTransaction.object_store` method, which you can use to access your object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/transaction) @@ -1071,26 +1087,20 @@ impl IDBDatabase { /// index? /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/createObjectStore) - pub fn create_object_store( &self, name: &str, auto_increment: bool, options: Value) -> Result { + pub fn create_object_store( &self, name: &str, auto_increment: bool, key_path: Value) -> Result { + // Todo, there's a question around how to handle the key path js_try! ( - return @{self.as_ref()}.createObjectStore(@{name}, { autoIncrememt: @{auto_increment}, keyPath: @{options.as_ref()} } ); + return @{self.as_ref()}.createObjectStore(@{name}, { autoIncrememt: @{auto_increment}, key_path: @{key_path.as_ref()} } ); ).unwrap() } - // void deleteObjectStore(DOMString name); /// Destroys the object store with the given name. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/deleteObjectStore) - pub fn delete_object_store( &self, name: &str ) { - js! { + pub fn delete_object_store( &self, name: &str ) -> Result<(), IDBDeleteObjectStoreError> { + js_try! ( @{self.as_ref()}.deleteObjectStore(@{name}); - } + ).unwrap() } - // Event handlers: - // attribute EventHandler onabort; - // attribute EventHandler onclose; - // attribute EventHandler onerror; - // attribute EventHandler onversionchange; - } From 2b0434af889f82db0938ea4db3d1c86a59470820 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Wed, 25 Jul 2018 22:29:17 +0100 Subject: [PATCH 24/85] Sort out the error enum names and reformat a bit. --- src/webapi/indexeddb.rs | 98 +++++++++++++++++++++-------------------- 1 file changed, 51 insertions(+), 47 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 7b671130..5c74183c 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -1,4 +1,3 @@ - use webcore::value::Value; use webcore::value::Reference; use webcore::try_from::{TryFrom, TryInto}; @@ -234,10 +233,10 @@ pub enum IDBCursorSource { Index(IDBIndex) } -// Todo, rename this error_enum_boilerplate! { - /// An enum of the exceptions that IDBCursorSharedMethods.advance() may throw - AdvanceError, + /// An enum of the exceptions that IDBCursorSharedMethods.advance() + /// and IDBCursorSharedMethods.next may throw. + IDBAdvanceError, /// This IDBCursor's transaction is inactive. TransactionInactiveError, /// The value passed into the parameter was zero or a negative number. @@ -247,7 +246,7 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - ContinuePrimaryKeyError, + IDBContinuePrimaryKeyError, /// This IDBCursor's transaction is inactive. TransactionInactiveError, /// The key parameter may have any of the following conditions: @@ -262,7 +261,7 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - UpdateError, + IDBUpdateError, /// This IDBCursor's transaction is inactive. TransactionInactiveError, /// The transaction mode is read only. @@ -276,7 +275,7 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - UpdateWithConstraintError, + IDBAddError, /// This IDBCursor's transaction is inactive. TransactionInactiveError, /// The transaction mode is read only. @@ -292,7 +291,7 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - DeleteError, + IDBCursorDeleteError, /// This IDBCursor's transaction is inactive. TransactionInactiveError, /// The transaction mode is read-only. @@ -301,21 +300,12 @@ error_enum_boilerplate! { InvalidStateError } -// Todo this is fpr IDBObjectStore::delete -error_enum_boilerplate! { - Delete2Error, - - TransactionInactiveError, // This object store's transaction is inactive. - ReadOnlyError, // The object store's transaction mode is read-only. - InvalidStateError, // The object store has been deleted. - DataError // The key is not a valid key or a key range. -} - error_enum_boilerplate! { - ClearError, - - ReadOnlyError, // The transaction associated with this operation is in read-only mode. - TransactionInactiveError // This IDBObjectStore's transaction is inactive. + IDBClearError, + /// The transaction associated with this operation is in read-only mode. + ReadOnlyError, + /// This IDBObjectStore's transaction is inactive. + TransactionInactiveError } /// This trait implements all the methods that are shared between @@ -373,7 +363,7 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { /// a cursor should move its position forward. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/advance) - fn advance( &self, count: u32) -> Result<(), AdvanceError> { + fn advance( &self, count: u32) -> Result<(), IDBAdvanceError> { js_try!( @{self.as_ref()}.advance(@{count}); ).unwrap() } @@ -386,7 +376,7 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { /// is a keyword in rust and so needed to be renamed. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/continue) - fn next>>( &self, key: K) -> Result<(), AdvanceError> { + fn next>>( &self, key: K) -> Result<(), IDBAdvanceError> { match key.into() { None => js_try!( @{self.as_ref()}.continue(); ).unwrap(), Some(key) => js_try! ( @{self.as_ref()}.continue(@{key.as_ref()}); ).unwrap() @@ -398,7 +388,7 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { /// well as whose primary key matches the primary key parameter. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/continuePrimaryKey) - fn continue_primary_key( &self, key: Value, primary_key: Value) -> Result<(), ContinuePrimaryKeyError> { + fn continue_primary_key( &self, key: Value, primary_key: Value) -> Result<(), IDBContinuePrimaryKeyError> { js_try!( @{self.as_ref()}.continuePrimaryKey(@{key}, @{primary_key}); ).unwrap() } @@ -408,7 +398,7 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { /// a record that has just been deleted, a new record is created. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/update) - fn update( &self, value: Value) -> Result { + fn update( &self, value: Value) -> Result { js_try!( return @{self.as_ref()}.update(@{value.as_ref()}); ).unwrap() } @@ -418,7 +408,7 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { /// deleted, the cursor's value is set to null. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete) - fn delete( &self ) -> Result { + fn delete( &self ) -> Result { js_try!( return @{self.as_ref()}.delete(); ).unwrap() } } @@ -554,7 +544,7 @@ pub enum IDBKeyOrKeyRange { } error_enum_boilerplate! { - SetNameError, + IDBSetNameError, /// The index, or its object store, has been deleted; or the current transaction /// is not an upgrade transaction. You can only rename indexes during upgrade @@ -568,9 +558,10 @@ error_enum_boilerplate! { ConstraintError } -// Todo, this needs renamed as it is used places other than the count method error_enum_boilerplate! { - IDBCountError, + /// This Error is raised by various methods ised to query object stores + /// and indexes. + IDBQueryError, /// This IDBIndex's transaction is inactive. TransactionInactiveError, @@ -583,10 +574,11 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - IndexError, - - InvalidStateError, // The source object store has been deleted, or the transaction for the object store has finished. - NotFoundError // There is no index with the given name (case-sensitive) in the database. + IDBIndexError, + /// The source object store has been deleted, or the transaction for the object store has finished. + InvalidStateError, + /// There is no index with the given name (case-sensitive) in the database. + NotFoundError } @@ -605,7 +597,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// Returns the name of this index or object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/name) - fn set_name( &self, name: &str) -> Result<(), SetNameError> { + fn set_name( &self, name: &str) -> Result<(), IDBSetNameError> { js_try! ( @{self.as_ref()}.name = @{name}; ).unwrap() } @@ -619,7 +611,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// This is for retrieving specific records from an object store or index. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/get) - fn get>( &self, query: Q) -> Result { + fn get>( &self, query: Q) -> Result { match query.into() { IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.get(); @@ -637,7 +629,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// This is for retrieving specific records from an object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getKey) - fn get_key>( &self, query: Q) -> Result { + fn get_key>( &self, query: Q) -> Result { match query.into() { IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getKey(); @@ -655,7 +647,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/getAll) - fn get_all, C: Into>>( &self, query: Q, count: C) -> Result { + fn get_all, C: Into>>( &self, query: Q, count: C) -> Result { match query.into() { IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAll(); ), IDBKeyOrKeyRange::Value(value) => { @@ -680,7 +672,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// parameters are given. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys) - fn get_all_keys, C: Into>>( &self, query: Q, count: C) -> Result { + fn get_all_keys, C: Into>>( &self, query: Q, count: C) -> Result { match query.into() { IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAllKeys(); ), IDBKeyOrKeyRange::Value(value) => { @@ -701,7 +693,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// Returns an IDBRequest object, and, in a separate thread, returns the total number of records that match the provided key or IDBKeyRange /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/count) - fn count>( &self, query: Q) -> Result { + fn count>( &self, query: Q) -> Result { match query.into() { IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.count(); @@ -719,7 +711,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// thread, creates a cursor over the specified key range. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openCursor) - fn open_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { + fn open_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { match range.into() { None => js_try! ( return @{self.as_ref()}.openCursor(); ), Some(range) => { @@ -736,7 +728,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// by this index. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openKeyCursor) - fn open_key_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { + fn open_key_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { match range.into() { None => js_try! ( return @{self.as_ref()}.openKeyCursor(); ), Some(range) => { @@ -788,6 +780,18 @@ impl IDBIndex { } +error_enum_boilerplate! { + IDBObjectStoreDeleteError, + /// This object store's transaction is inactive. + TransactionInactiveError, + /// The object store's transaction mode is read-only. + ReadOnlyError, + /// The object store has been deleted. + InvalidStateError, + /// The key is not a valid key or a key range. + DataError +} + /// The `IDBObjectStore` interface of the IndexedDB API represents an object store in a database /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore) @@ -824,7 +828,7 @@ impl IDBObjectStore { /// The key is only needed if /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put) - pub fn put>>( &self, value: Value, key: T) -> Result { + pub fn put>>( &self, value: Value, key: T) -> Result { match key.into() { None => js_try! ( return @{self.as_ref()}.put(@{value.as_ref()}); @@ -838,7 +842,7 @@ impl IDBObjectStore { /// Returns an `IDBRequest` object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add) - pub fn add>>( &self, value: Value, key: T) -> Result { + pub fn add>>( &self, value: Value, key: T) -> Result { match key.into() { None => js_try! ( return @{self.as_ref()}.add(@{value.as_ref()}); @@ -852,7 +856,7 @@ impl IDBObjectStore { /// returns an `IDBRequest` object, and, in a separate thread, deletes the specified record or records. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete) - pub fn delete( &self, query: Value) -> Result { + pub fn delete( &self, query: Value) -> Result { js_try! ( return @{self.as_ref()}.delete(@{query.as_ref()}); ).unwrap() @@ -861,7 +865,7 @@ impl IDBObjectStore { /// Returns an IDBRequest object, and clears this object store in a separate thread /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/clear) - pub fn clear( &self ) -> Result { + pub fn clear( &self ) -> Result { js_try! ( return @{self.as_ref()}.clear(); ).unwrap() @@ -870,7 +874,7 @@ impl IDBObjectStore { /// opens a named index in the current object store /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/index) - pub fn index( &self, name: &str) -> Result { + pub fn index( &self, name: &str) -> Result { js_try! ( return @{self.as_ref()}.index(@{name}); ).unwrap() From 71ddbd96f9603eef921b1da6304efe5ec2cb8183 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Sun, 29 Jul 2018 22:46:11 +0100 Subject: [PATCH 25/85] An implementaiotn of DOMStringList --- src/lib.rs | 2 ++ src/webapi/dom_string_list.rs | 53 +++++++++++++++++++++++++++++++++++ src/webapi/indexeddb.rs | 24 ++++++++++++---- src/webapi/mod.rs | 1 + 4 files changed, 74 insertions(+), 6 deletions(-) create mode 100644 src/webapi/dom_string_list.rs diff --git a/src/lib.rs b/src/lib.rs index 2587ddbe..8cf53168 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -237,6 +237,8 @@ pub mod web { }; } + pub use webapi::dom_string_list::DOMStringList; + pub use webapi::window::{ Window, window diff --git a/src/webapi/dom_string_list.rs b/src/webapi/dom_string_list.rs new file mode 100644 index 00000000..65060c48 --- /dev/null +++ b/src/webapi/dom_string_list.rs @@ -0,0 +1,53 @@ +use webcore::value::Reference; +use webcore::try_from::TryInto; + +/// The `DOMStringList` interface is a non-fashionable retro way of representing a list of strings. +/// +/// [(JavaScript docs)](https://html.spec.whatwg.org/multipage/common-dom-interfaces.html#the-domstringlist-interface) +#[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] +#[reference(instance_of = "DOMStringList")] +pub struct DOMStringList( Reference ); + +impl DOMStringList { + + /// Returns the number of strings in the `DOMStringList`. + pub fn length( &self ) -> u32 { + js!( return @{self}.length; ).try_into().unwrap() + } + + /// Returns the string with index `index`. + pub fn item( &self, index: u32) -> Option { + js!( return @{self}.item(@{index}); ).try_into().unwrap() + } + + /// Returns true if the DOMStringList contains `string`, and false otherwise. + pub fn contains( &self, string: &str) -> bool { + js! ( return @{self}.container(@{string}); ).try_into().unwrap() + } + +} + +impl IntoIterator for DOMStringList { + type Item = String; + type IntoIter = DOMStringListIterator; + + fn into_iter(self) -> Self::IntoIter { + DOMStringListIterator { dom_string_list: self, index: 0 } + } +} + +#[derive(Debug)] +pub struct DOMStringListIterator { + dom_string_list: DOMStringList, + index: u32 +} + +impl Iterator for DOMStringListIterator { + type Item = String; + + fn next(&mut self) -> Option { + let result = self.dom_string_list.item(self.index); + self.index += 1; + result + } +} diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 5c74183c..cf111acf 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -3,6 +3,7 @@ use webcore::value::Reference; use webcore::try_from::{TryFrom, TryInto}; use webapi::event_target::{IEventTarget, EventTarget}; use webapi::dom_exception::{DomException, InvalidStateError, TypeError, TransactionInactiveError, DataError, InvalidAccessError, ReadOnlyError, DataCloneError, ConstraintError, NotFoundError}; +use webapi::dom_string_list::DOMStringList; /// Used to represent the state of an IDBRequest. /// @@ -803,8 +804,13 @@ impl IDBObjectStoreIndexSharedMethods for IDBObjectStore {} impl IDBObjectStore { - // readonly attribute DOMStringList indexNames; - // TODO: how am I wrapping this + /// The index_names read-only property of the `IDBObjectStore` interface returns a list of th + /// names of indexes on objects in this object store. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/indexNames) + pub fn index_names( &self ) -> DOMStringList { + js! ( return @{self}.indexNames ).try_into().unwrap() + } /// The `IDBTransaction` object to which this object store belongs. /// @@ -818,7 +824,7 @@ impl IDBObjectStore { /// Returns the value of the auto increment flag for this object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/autoIncrement) - fn auto_increment( &self ) -> bool { + pub fn auto_increment( &self ) -> bool { js! ( return @{self.as_ref()}.autoIncrement; ).try_into().unwrap() @@ -894,7 +900,7 @@ impl IDBObjectStore { /// Destroys the index with the specified name in the connected database, used during a version upgrade. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/deleteIndex) - fn delete_index( &self, name: &str) { + pub fn delete_index( &self, name: &str) { js! { return @{self.as_ref()}.deleteIndex(@{name}); } @@ -953,8 +959,14 @@ pub struct IDBTransaction( Reference ); impl IEventTarget for IDBTransaction {} impl IDBTransaction { - // readonly attribute DOMStringList objectStoreNames; - // Todo, how am I wrapping DOMStringList + + /// The object_store_names read-only property of the IDBTransaction interface returns + /// a DOMStringList of names of IDBObjectStore objects. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/objectStoreNames) + pub fn object_store_names( &self ) -> DOMStringList { + js! ( return @{self}.objectStoreNames ).try_into().unwrap() + } /// The mode read-only property of the `IDBTransaction` interface returns the /// current mode for accessing the data in the object stores in the scope of the diff --git a/src/webapi/mod.rs b/src/webapi/mod.rs index 3d7cc171..6151da00 100644 --- a/src/webapi/mod.rs +++ b/src/webapi/mod.rs @@ -26,6 +26,7 @@ pub mod typed_array; /// A module containing XMLHttpRequest and its ReadyState pub mod xml_http_request; pub mod indexeddb; +pub mod dom_string_list; pub mod history; pub mod web_socket; pub mod rendering_context; From e38012e91fdebf71e503f9282a71d2cfad1730e2 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Mon, 30 Jul 2018 22:09:16 +0100 Subject: [PATCH 26/85] More bits and bobs. --- src/webapi/indexeddb.rs | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index cf111acf..68e27c71 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -626,8 +626,8 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { }.unwrap() } - // Todo, I think this description is wrong. - /// This is for retrieving specific records from an object store. + /// Returns an IDBRequest object, and, in a separate thread retrieves and + /// returns the record key for the object matching the specified parameter. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getKey) fn get_key>( &self, query: Q) -> Result { @@ -896,7 +896,6 @@ impl IDBObjectStore { ).try_into().unwrap() } - // void deleteIndex(DOMString name); /// Destroys the index with the specified name in the connected database, used during a version upgrade. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/deleteIndex) @@ -988,8 +987,13 @@ impl IDBTransaction { ).try_into().unwrap() } - // Todo - // readonly attribute DOMException error; + /// The IDBTransaction.error property of the IDBTransaction interface returns + /// one of several types of error when there is an unsuccessful transaction. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/error) + pub fn error( &self ) -> Option { + js!( return @{self}.error; ).try_into().unwrap() + } /// The object_store() method of the IDBTransaction interface returns an object /// store that has already been added to the scope of this transaction. @@ -1075,8 +1079,14 @@ impl IDBDatabase { ).try_into().unwrap() } - // readonly attribute DOMStringList objectStoreNames; - // TODO: how should I expose DomStringList + /// The objectStoreNames read-only property of the IDBDatabase interface is a + /// DOMStringList containing a list of the names of the object stores currently + /// in the connected database. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/objectStoreNames) + pub fn object_store_names( &self ) -> DOMStringList { + js! ( return @{self}.objectStoreNames ).try_into().unwrap() + } // [NewObject] IDBTransaction transaction((DOMString or sequence) storeNames, optional IDBTransactionMode mode = "readonly"); // Todo, this can be a string or an array of strings, how to handle this From 0da29637e7704be3a0a8be7c99833155ac3953d4 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Wed, 1 Aug 2018 20:47:57 +0100 Subject: [PATCH 27/85] This ain't working. --- examples/indexeddb/src/main.rs | 2 +- src/webapi/indexeddb.rs | 17 +++++++++++++---- 2 files changed, 14 insertions(+), 5 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 698b3ba1..35bc7554 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -65,7 +65,7 @@ fn display_data_inner(db: &IDBDatabase) { } // Open our object store and then get a cursor - which iterates through all the // different data items in the store - let object_store = db.transaction("notes", "readonly").object_store("notes").unwrap(); + let object_store = db.transaction(vec!["notes"], "readonly").object_store("notes").unwrap(); object_store.open_cursor(None, None).unwrap() .add_event_listener( move |e: IDBSuccessEvent| { // Get a reference to the cursor diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 68e27c71..771af1a3 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -1,5 +1,5 @@ -use webcore::value::Value; -use webcore::value::Reference; +use webcore::value::{Value, Reference}; +use webcore::array::Array; use webcore::try_from::{TryFrom, TryInto}; use webapi::event_target::{IEventTarget, EventTarget}; use webapi::dom_exception::{DomException, InvalidStateError, TypeError, TransactionInactiveError, DataError, InvalidAccessError, ReadOnlyError, DataCloneError, ConstraintError, NotFoundError}; @@ -1050,6 +1050,14 @@ error_enum_boilerplate! { NotFoundError } +fn string_iterator_to_value>(i: T) -> Value { + let v: Value = js!( return []); + for item in i { + js!{ @{v.as_ref()}.push(@{item}); } + } + v +} + /// The `IDBDatabase` interface of the IndexedDB API provides a connection to a database. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase) @@ -1093,10 +1101,11 @@ impl IDBDatabase { /// Immediately returns a transaction object (`IDBTransaction`) containing the `IDBTransaction.object_store` method, which you can use to access your object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/transaction) - pub fn transaction( &self, store_name: &str, mode: &str) -> IDBTransaction { + pub fn transaction>( &self, store_names: T, mode: &str) -> IDBTransaction { + let v = string_iterator_to_value(store_names); js! ( //return @{self.as_ref()}.transaction(@{store_name}, @{mode}); - return @{self.as_ref()}.transaction(@{store_name}, @{mode}); + return @{self.as_ref()}.transaction(@{v}, @{mode}); ).try_into().unwrap() } From 94d097fb8f3cd5f6657832488eeaba6b001bb651 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Wed, 1 Aug 2018 21:25:42 +0100 Subject: [PATCH 28/85] Sort out transaction. --- examples/indexeddb/src/main.rs | 9 ++++---- src/lib.rs | 1 + src/webapi/indexeddb.rs | 40 +++++++++++++++++----------------- 3 files changed, 26 insertions(+), 24 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 35bc7554..689932af 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -39,7 +39,8 @@ use stdweb::web::indexeddb::{ IDBRequestSharedMethods, IDBObjectStoreIndexSharedMethods, IDBCursorWithValue, - IDBCursorSharedMethods + IDBCursorSharedMethods, + IDBTransactionMode }; use stdweb::unstable::TryInto; @@ -65,7 +66,7 @@ fn display_data_inner(db: &IDBDatabase) { } // Open our object store and then get a cursor - which iterates through all the // different data items in the store - let object_store = db.transaction(vec!["notes"], "readonly").object_store("notes").unwrap(); + let object_store = db.transaction(vec!["notes"], IDBTransactionMode::ReadOnly).object_store("notes").unwrap(); object_store.open_cursor(None, None).unwrap() .add_event_listener( move |e: IDBSuccessEvent| { // Get a reference to the cursor @@ -138,7 +139,7 @@ fn delete_item( e: ClickEvent ) { // open a database transaction and delete the task, finding it using the id we retrieved above DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { - let transaction = db.transaction("notes", "readwrite"); + let transaction = db.transaction(vec!["notes"], IDBTransactionMode::ReadWrite); let object_store = transaction.object_store("notes").unwrap(); object_store.delete(note_id.try_into().unwrap()); @@ -231,7 +232,7 @@ fn main() { DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { // open a read/write db transaction, ready for adding the data - let transaction = db.transaction("notes", "readwrite"); + let transaction = db.transaction(vec!["notes"], IDBTransactionMode::ReadWrite); // call an object store that's already been added to the database let object_store = transaction.object_store("notes").unwrap(); diff --git a/src/lib.rs b/src/lib.rs index 8cf53168..1e97fc7c 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -227,6 +227,7 @@ pub mod web { IDBIndex, IDBObjectStore, IDBTransaction, + IDBTransactionMode, IDBFactory, IDBObjectStoreIndexSharedMethods, IDBCursorDirection, diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 771af1a3..4302bdb5 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -1,5 +1,4 @@ use webcore::value::{Value, Reference}; -use webcore::array::Array; use webcore::try_from::{TryFrom, TryInto}; use webapi::event_target::{IEventTarget, EventTarget}; use webapi::dom_exception::{DomException, InvalidStateError, TypeError, TransactionInactiveError, DataError, InvalidAccessError, ReadOnlyError, DataCloneError, ConstraintError, NotFoundError}; @@ -666,7 +665,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { }.unwrap() } - // Todo, acording to the mozilla documentation the IDBIndex version does not + // Acording to the mozilla documentation the IDBIndex version does not // Throw DataError. /// The get_all_keys() method returns an IDBRequest object retrieves record keys /// for all objects matching the specified parameter or all objects if no @@ -911,11 +910,22 @@ impl IDBObjectStore { boolean multiEntry = false; };*/ +/// An IDBTransactionMode object defining the mode for isolating access to +/// data in the current object stores. +/// +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/mode) #[derive(Debug)] pub enum IDBTransactionMode { - ReadOnly, - ReadWrite, - VersionChange + /// Allows data to be read but not changed. + ReadOnly, + /// Allows reading and writing of data in existing data stores to be changed. + ReadWrite, + /// Allows any operation to be performed, including ones that delete and + /// create object stores and indexes. This mode is for updating the version + /// number of transactions that were started using IDBDatabase.set_version(). + /// Transactions of this mode cannot run concurrently with other transactions. + /// Transactions in this mode are known as "upgrade transactions." + VersionChange } fn transaction_mode_to_string( mode: IDBTransactionMode ) -> String { @@ -1050,14 +1060,6 @@ error_enum_boilerplate! { NotFoundError } -fn string_iterator_to_value>(i: T) -> Value { - let v: Value = js!( return []); - for item in i { - js!{ @{v.as_ref()}.push(@{item}); } - } - v -} - /// The `IDBDatabase` interface of the IndexedDB API provides a connection to a database. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase) @@ -1096,16 +1098,14 @@ impl IDBDatabase { js! ( return @{self}.objectStoreNames ).try_into().unwrap() } - // [NewObject] IDBTransaction transaction((DOMString or sequence) storeNames, optional IDBTransactionMode mode = "readonly"); - // Todo, this can be a string or an array of strings, how to handle this - /// Immediately returns a transaction object (`IDBTransaction`) containing the `IDBTransaction.object_store` method, which you can use to access your object store. + /// Immediately returns a transaction object (`IDBTransaction`) containing + /// the `IDBTransaction.object_store` method, which you can use to access + /// your object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/transaction) - pub fn transaction>( &self, store_names: T, mode: &str) -> IDBTransaction { - let v = string_iterator_to_value(store_names); + pub fn transaction( &self, store_names: Vec<&str>, mode: IDBTransactionMode) -> IDBTransaction { js! ( - //return @{self.as_ref()}.transaction(@{store_name}, @{mode}); - return @{self.as_ref()}.transaction(@{v}, @{mode}); + return @{self.as_ref()}.transaction(@{store_names}, @{transaction_mode_to_string(mode)}); ).try_into().unwrap() } From b453bc10324fa6188836d9655f8a40580f8f3cde Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Wed, 1 Aug 2018 22:00:34 +0100 Subject: [PATCH 29/85] Add a little more documentation. --- src/webapi/indexeddb.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 4302bdb5..52ab862f 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -888,6 +888,9 @@ impl IDBObjectStore { // [NewObject] IDBIndex createIndex(DOMString name, (DOMString or sequence) keyPath, optional IDBIndexParameters options); /// Creates and returns a new `IDBIndex` object in the connected database. /// + /// Note that this method must be called only from a VersionChange + /// transaction mode callback. + /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex) pub fn create_index( &self, name: &str, key_path: &str, options: Value) -> IDBIndex { // TODO, how am I doing the optinal options? js! ( From 5d29d4a2ce7d904fefe10b54471ef3b0836637ea Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Mon, 6 Aug 2018 20:26:40 +0100 Subject: [PATCH 30/85] Think I've fixed this. --- examples/indexeddb/src/main.rs | 6 +----- src/lib.rs | 3 ++- src/webapi/indexeddb.rs | 10 +++++----- 3 files changed, 8 insertions(+), 11 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 689932af..6e8ea1cd 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -198,11 +198,7 @@ fn main() { let db_: IDBDatabase = db_request.result().unwrap().try_into().unwrap(); // Create an object_store to store our notes in (basically like a single table) - // including a auto-incrementing key - let mut store_options = HashMap::new(); - //store_options.insert("keyPath", "id"); - store_options.insert("autoIncrement", "true"); - let object_store = db_.create_object_store("notes", true, Value::from(store_options)).unwrap(); + let object_store = db_.create_object_store("notes", true, "").unwrap(); // Define what data items the object_store will contain let mut title_options = HashMap::new(); diff --git a/src/lib.rs b/src/lib.rs index 1e97fc7c..e932102b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -234,7 +234,8 @@ pub mod web { IDBRequestReadyState, IDBCursorSharedMethods, IDBCursor, - IDBCursorWithValue + IDBCursorWithValue, + IDBAddError }; } diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 52ab862f..f9737ad4 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -274,7 +274,9 @@ error_enum_boilerplate! { DataCloneError } +/// error_enum_boilerplate! { + /// IDBAddError, /// This IDBCursor's transaction is inactive. TransactionInactiveError, @@ -1121,14 +1123,12 @@ impl IDBDatabase { } } - /// Creates and returns a new object store or index. TODO: why does this say - /// index? + /// Creates and returns a new object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/createObjectStore) - pub fn create_object_store( &self, name: &str, auto_increment: bool, key_path: Value) -> Result { - // Todo, there's a question around how to handle the key path + pub fn create_object_store( &self, name: &str, auto_increment: bool, key_path: &str) -> Result { js_try! ( - return @{self.as_ref()}.createObjectStore(@{name}, { autoIncrememt: @{auto_increment}, key_path: @{key_path.as_ref()} } ); + return @{self.as_ref()}.createObjectStore(@{name}, { autoIncrement: @{auto_increment}, key_path: @{key_path} } ); ).unwrap() } From ff22c06842dd6a263f50ba878287e9ad0eacf193 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Mon, 24 Sep 2018 20:41:28 +0100 Subject: [PATCH 31/85] Make it compile again. --- src/webapi/dom_exception.rs | 21 +++++---------------- src/webapi/indexeddb.rs | 3 ++- 2 files changed, 7 insertions(+), 17 deletions(-) diff --git a/src/webapi/dom_exception.rs b/src/webapi/dom_exception.rs index d1ee0003..294c0e8d 100644 --- a/src/webapi/dom_exception.rs +++ b/src/webapi/dom_exception.rs @@ -151,7 +151,7 @@ pub struct TransactionInactiveError( Reference ); impl IError for TransactionInactiveError {} impl IDomException for TransactionInactiveError {} -error_boilerplate! { TransactionInactiveError, name = "TransactionInactiveError" } +error_boilerplate! { TransactionInactiveError, dom_exception = "TransactionInactiveError" } /// The key was not valid in the context it was used. #[derive(Clone, Debug, ReferenceType)] @@ -161,7 +161,7 @@ pub struct DataError( Reference ); impl IError for DataError {} impl IDomException for DataError {} -error_boilerplate! { DataError, name = "DataError" } +error_boilerplate! { DataError, dom_exception = "DataError" } /// The transaction mode is read only. #[derive(Clone, Debug, ReferenceType)] @@ -171,7 +171,7 @@ pub struct ReadOnlyError( Reference ); impl IError for ReadOnlyError {} impl IDomException for ReadOnlyError {} -error_boilerplate! { ReadOnlyError, name = "ReadOnlyError" } +error_boilerplate! { ReadOnlyError, dom_exception = "ReadOnlyError" } /// The data being stored could not be cloned by the internal structured cloning algorithm. #[derive(Clone, Debug, ReferenceType)] @@ -181,7 +181,7 @@ pub struct DataCloneError( Reference ); impl IError for DataCloneError {} impl IDomException for DataCloneError {} -error_boilerplate! { DataCloneError, name = "DataCloneError" } +error_boilerplate! { DataCloneError, dom_exception = "DataCloneError" } /// An index or an object store already has this name #[derive(Clone, Debug, ReferenceType)] @@ -191,18 +191,7 @@ pub struct ConstraintError( Reference ); impl IError for ConstraintError {} impl IDomException for ConstraintError {} -error_boilerplate! { ConstraintError, name = "ConstraintError" } -/* -/// There is no index with the given name (case-sensitive) in the database. -#[derive(Clone, Debug, ReferenceType)] -#[reference(subclass_of(Error, DomException))] -pub struct NotFoundError( Reference ); - -impl IError for NotFoundError {} -impl IDomException for NotFoundError {} - -error_boilerplate! { NotFoundError, name = "NotFoundError" } -*/ +error_boilerplate! { ConstraintError, dom_exception = "ConstraintError" } /// Used to indicate that the operation was aborted. // https://heycam.github.io/webidl/#aborterror diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index f9737ad4..575d2f76 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -1,7 +1,8 @@ use webcore::value::{Value, Reference}; use webcore::try_from::{TryFrom, TryInto}; use webapi::event_target::{IEventTarget, EventTarget}; -use webapi::dom_exception::{DomException, InvalidStateError, TypeError, TransactionInactiveError, DataError, InvalidAccessError, ReadOnlyError, DataCloneError, ConstraintError, NotFoundError}; +use webapi::dom_exception::{DomException, InvalidStateError, TransactionInactiveError, DataError, InvalidAccessError, ReadOnlyError, DataCloneError, ConstraintError, NotFoundError}; +use webapi::error::TypeError; use webapi::dom_string_list::DOMStringList; /// Used to represent the state of an IDBRequest. From 04cf8bf8c7bc6ce59e09b3a619d95eda04c987d9 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Mon, 24 Sep 2018 20:49:53 +0100 Subject: [PATCH 32/85] Get rid of warnings. --- examples/indexeddb/src/main.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 6e8ea1cd..1d821892 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -106,7 +106,7 @@ fn display_data_inner(db: &IDBDatabase) { delete_btn.add_event_listener( delete_item ); // Iterate to the next item in the cursor - cursor.advance(1); // Todo this was continue + cursor.advance(1).unwrap(); // Todo this was continue } else { // Again, if list item is empty, display a 'No notes stored' message @@ -141,7 +141,7 @@ fn delete_item( e: ClickEvent ) { if let Some(ref db) = *db_cell.borrow_mut() { let transaction = db.transaction(vec!["notes"], IDBTransactionMode::ReadWrite); let object_store = transaction.object_store("notes").unwrap(); - object_store.delete(note_id.try_into().unwrap()); + object_store.delete(note_id.try_into().unwrap()).unwrap(); // report that the data item has been deleted transaction.add_event_listener( move |_e: IDBCompleteEvent| { From c7990fe8a35d0af47c03f859dc45e961f95d7d55 Mon Sep 17 00:00:00 2001 From: Joe Jones Date: Sun, 18 Nov 2018 10:58:27 +0000 Subject: [PATCH 33/85] Little tidy up. --- src/lib.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index f8caffb3..638cb5bf 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -217,7 +217,6 @@ pub mod serde { /// A module with bindings to the Web APIs. pub mod web { - #[cfg(feature = "futures-support")] pub use webapi::timer_future::{ Wait, @@ -227,7 +226,7 @@ pub mod web { }; - /// This is a module + /// A module containing the IndexedDB API pub mod indexeddb { pub use webapi::indexeddb::{ IDBOpenDBRequest, From 788e8a8b0d0b330731b0183d424155a91094c4c9 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:19:25 -0700 Subject: [PATCH 34/85] Remove dead code in example --- examples/indexeddb/src/main.rs | 3 --- 1 file changed, 3 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 1d821892..9a341299 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -47,7 +47,6 @@ use stdweb::unstable::TryInto; #[derive(Serialize, Deserialize)] struct Note { - //id: u32, title: String, body: String } @@ -71,7 +70,6 @@ fn display_data_inner(db: &IDBDatabase) { .add_event_listener( move |e: IDBSuccessEvent| { // Get a reference to the cursor let db_request: IDBRequest = e.target().unwrap().try_into().unwrap(); - //let cursor: IDBCursorWithValue = db_request.result().try_into().unwrap(); let maybe_cursor: Result = db_request.result().unwrap().try_into(); // If there is still another data item to iterate through, keep running this code @@ -147,7 +145,6 @@ fn delete_item( e: ClickEvent ) { transaction.add_event_listener( move |_e: IDBCompleteEvent| { // delete the parent of the button // which is the list item, so it is no longer displayed - //let node: Node = e.target().unwrap().try_into().unwrap(); note.parent_node().unwrap().remove_child(¬e).unwrap(); console!(log, "Note ", note_id, "deleted."); From d87b81aca90a862a07f851c1a46a253023d2c0f2 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:20:02 -0700 Subject: [PATCH 35/85] Remove unnecessary From 5fa10bd7e206fb546779d9aacf36107f5b2e1152 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:24:16 -0700 Subject: [PATCH 36/85] Replace IDB -> Db --- examples/indexeddb/src/main.rs | 66 ++-- src/lib.rs | 40 +-- src/webapi/events/indexeddb.rs | 28 +- src/webapi/indexeddb.rs | 626 ++++++++++++++++----------------- src/webapi/window.rs | 4 +- 5 files changed, 382 insertions(+), 382 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 9a341299..cdd43ce6 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -24,23 +24,23 @@ use stdweb::web::html_element::InputElement; use stdweb::web::event::IEvent; use stdweb::web::event::{ - IDBSuccessEvent, - IDBVersionChangeEvent, - IDBCompleteEvent, - IDBErrorEvent, + DbSuccessEvent, + DbVersionChangeEvent, + DbCompleteEvent, + DbErrorEvent, SubmitEvent, ClickEvent }; use stdweb::web::indexeddb::{ - IDBOpenDBRequest, - IDBDatabase, - IDBRequest, - IDBRequestSharedMethods, - IDBObjectStoreIndexSharedMethods, - IDBCursorWithValue, - IDBCursorSharedMethods, - IDBTransactionMode + DbOpenDBRequest, + DbDatabase, + DbRequest, + DbRequestSharedMethods, + DbObjectStoreIndexSharedMethods, + DbCursorWithValue, + DbCursorSharedMethods, + DbTransactionMode }; use stdweb::unstable::TryInto; @@ -54,9 +54,9 @@ struct Note { js_serializable!( Note ); js_deserializable!( Note ); -thread_local!(static DB: RefCell> = RefCell::new(None)); +thread_local!(static DB: RefCell> = RefCell::new(None)); -fn display_data_inner(db: &IDBDatabase) { +fn display_data_inner(db: &DbDatabase) { let list = document().query_selector("ul").unwrap().unwrap(); // Here we empty the contents of the list element each time the display is updated // If you ddn't do this, you'd get duplicates listed each time a new note is added @@ -65,12 +65,12 @@ fn display_data_inner(db: &IDBDatabase) { } // Open our object store and then get a cursor - which iterates through all the // different data items in the store - let object_store = db.transaction(vec!["notes"], IDBTransactionMode::ReadOnly).object_store("notes").unwrap(); + let object_store = db.transaction(vec!["notes"], DbTransactionMode::ReadOnly).object_store("notes").unwrap(); object_store.open_cursor(None, None).unwrap() - .add_event_listener( move |e: IDBSuccessEvent| { + .add_event_listener( move |e: DbSuccessEvent| { // Get a reference to the cursor - let db_request: IDBRequest = e.target().unwrap().try_into().unwrap(); - let maybe_cursor: Result = db_request.result().unwrap().try_into(); + let db_request: DbRequest = e.target().unwrap().try_into().unwrap(); + let maybe_cursor: Result = db_request.result().unwrap().try_into(); // If there is still another data item to iterate through, keep running this code if let Ok(cursor) = maybe_cursor { @@ -128,7 +128,7 @@ fn display_data() { // Define the deleteItem() function fn delete_item( e: ClickEvent ) { // retrieve the name of the task we want to delete. We need - // to convert it to a number before trying it use it with IDB; IDB key + // to convert it to a number before trying it use it with Db; Db key // values are type-sensitive. let button: Element = e.target().unwrap().try_into().unwrap(); let note: Element = button.parent_node().unwrap().try_into().unwrap(); @@ -137,12 +137,12 @@ fn delete_item( e: ClickEvent ) { // open a database transaction and delete the task, finding it using the id we retrieved above DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { - let transaction = db.transaction(vec!["notes"], IDBTransactionMode::ReadWrite); + let transaction = db.transaction(vec!["notes"], DbTransactionMode::ReadWrite); let object_store = transaction.object_store("notes").unwrap(); object_store.delete(note_id.try_into().unwrap()).unwrap(); // report that the data item has been deleted - transaction.add_event_listener( move |_e: IDBCompleteEvent| { + transaction.add_event_listener( move |_e: DbCompleteEvent| { // delete the parent of the button // which is the list item, so it is no longer displayed note.parent_node().unwrap().remove_child(¬e).unwrap(); @@ -167,32 +167,32 @@ fn main() { let request = window().indexed_db().open("notes", 1); // onerror handler signifies that the database didn't open successfully - request.add_event_listener( | _e: IDBErrorEvent| { + request.add_event_listener( | _e: DbErrorEvent| { js!( console.log("Database failed to open"); ); }); // onsuccess handler signifies that the database opened successfully - request.add_event_listener( move |event: IDBSuccessEvent| { + request.add_event_listener( move |event: DbSuccessEvent| { js!( console.log("Database opened succesfully"); ); - let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); + let db_request: DbOpenDBRequest = event.target().unwrap().try_into().unwrap(); // Store the opened database object in the db variable. This is used a lot below - let db : IDBDatabase = db_request.database_result().unwrap(); + let db : DbDatabase = db_request.database_result().unwrap(); DB.with(|db_cell| { db_cell.replace(Some(db)); }); - // Run the displayData() function to display the notes already in the IDB + // Run the displayData() function to display the notes already in the Db display_data(); }); - request.add_event_listener( |event: IDBVersionChangeEvent| { - let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); - let db_: IDBDatabase = db_request.result().unwrap().try_into().unwrap(); + request.add_event_listener( |event: DbVersionChangeEvent| { + let db_request: DbOpenDBRequest = event.target().unwrap().try_into().unwrap(); + let db_: DbDatabase = db_request.result().unwrap().try_into().unwrap(); // Create an object_store to store our notes in (basically like a single table) let object_store = db_.create_object_store("notes", true, "").unwrap(); @@ -225,7 +225,7 @@ fn main() { DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { // open a read/write db transaction, ready for adding the data - let transaction = db.transaction(vec!["notes"], IDBTransactionMode::ReadWrite); + let transaction = db.transaction(vec!["notes"], DbTransactionMode::ReadWrite); // call an object store that's already been added to the database let object_store = transaction.object_store("notes").unwrap(); @@ -233,21 +233,21 @@ fn main() { // Make a request to add our new_item object to the object store let request = object_store.add(new_item.try_into().unwrap(), None).unwrap(); - request.add_event_listener( move |_e: IDBSuccessEvent| { + request.add_event_listener( move |_e: DbSuccessEvent| { // Clear the form, ready for adding the next entry title_input.set_raw_value(""); body_input.set_raw_value(""); }); // Report on the success of the transaction completing, when everything is done - transaction.add_event_listener( |_e: IDBCompleteEvent| { + transaction.add_event_listener( |_e: DbCompleteEvent| { console!(log, "Transaction completed: database modification finished."); // update the display of data to show the newly added item, by running displayData() again. display_data(); }); - transaction.add_event_listener( |_e: IDBErrorEvent| { + transaction.add_event_listener( |_e: DbErrorEvent| { console!(log, "Transaction not opened due to error"); }); }}); diff --git a/src/lib.rs b/src/lib.rs index 37404e0d..da4f6110 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -226,22 +226,22 @@ pub mod web { /// A module containing the IndexedDB API pub mod indexeddb { pub use webapi::indexeddb::{ - IDBOpenDBRequest, - IDBDatabase, - IDBRequestSharedMethods, - IDBRequest, - IDBIndex, - IDBObjectStore, - IDBTransaction, - IDBTransactionMode, - IDBFactory, - IDBObjectStoreIndexSharedMethods, - IDBCursorDirection, - IDBRequestReadyState, - IDBCursorSharedMethods, - IDBCursor, - IDBCursorWithValue, - IDBAddError + DbOpenDBRequest, + DbDatabase, + DbRequestSharedMethods, + DbRequest, + DbIndex, + DbObjectStore, + DbTransaction, + DbTransactionMode, + DbFactory, + DbObjectStoreIndexSharedMethods, + DbCursorDirection, + DbRequestReadyState, + DbCursorSharedMethods, + DbCursor, + DbCursorWithValue, + DbAddError }; } @@ -444,10 +444,10 @@ pub mod web { }; pub use webapi::events::indexeddb:: { - IDBSuccessEvent, - IDBVersionChangeEvent, - IDBCompleteEvent, - IDBErrorEvent + DbSuccessEvent, + DbVersionChangeEvent, + DbCompleteEvent, + DbErrorEvent }; pub use webapi::events::gamepad::{ diff --git a/src/webapi/events/indexeddb.rs b/src/webapi/events/indexeddb.rs index 66aa0dfc..30321208 100644 --- a/src/webapi/events/indexeddb.rs +++ b/src/webapi/events/indexeddb.rs @@ -4,17 +4,17 @@ use webcore::try_from::TryInto; //use webapi::event_target::{IEventTarget, EventTarget}; //use webapi::node::{INode, Node}; -/// The `IDBSuccessEvent` handler is fired when a and Indexed DB request succeed. +/// The `DbSuccessEvent` handler is fired when a and Indexed DB request succeed. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/Events/success) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "Event")] #[reference(subclass_of(Event))] -pub struct IDBSuccessEvent( Reference ); +pub struct DbSuccessEvent( Reference ); -impl IEvent for IDBSuccessEvent {} +impl IEvent for DbSuccessEvent {} -impl ConcreteEvent for IDBSuccessEvent { +impl ConcreteEvent for DbSuccessEvent { const EVENT_TYPE: &'static str = "success"; } @@ -24,15 +24,15 @@ impl ConcreteEvent for IDBSuccessEvent { #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "Event")] #[reference(subclass_of(Event))] -pub struct IDBVersionChangeEvent( Reference ); +pub struct DbVersionChangeEvent( Reference ); -impl IEvent for IDBVersionChangeEvent {} +impl IEvent for DbVersionChangeEvent {} -impl ConcreteEvent for IDBVersionChangeEvent { +impl ConcreteEvent for DbVersionChangeEvent { const EVENT_TYPE: &'static str = "upgradeneeded"; } -impl IDBVersionChangeEvent { +impl DbVersionChangeEvent { // readonly attribute unsigned long long oldVersion; /// Returns the previous version of the database. pub fn old_version( &self ) -> u64 { @@ -55,11 +55,11 @@ impl IDBVersionChangeEvent { #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "Event")] #[reference(subclass_of(Event))] -pub struct IDBCompleteEvent( Reference ); +pub struct DbCompleteEvent( Reference ); -impl IEvent for IDBCompleteEvent {} +impl IEvent for DbCompleteEvent {} -impl ConcreteEvent for IDBCompleteEvent { +impl ConcreteEvent for DbCompleteEvent { const EVENT_TYPE: &'static str = "complete"; } @@ -67,10 +67,10 @@ impl ConcreteEvent for IDBCompleteEvent { #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "Event")] #[reference(subclass_of(Event))] -pub struct IDBErrorEvent( Reference ); +pub struct DbErrorEvent( Reference ); -impl IEvent for IDBErrorEvent {} +impl IEvent for DbErrorEvent {} -impl ConcreteEvent for IDBErrorEvent { +impl ConcreteEvent for DbErrorEvent { const EVENT_TYPE: &'static str = "error"; } diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 575d2f76..1a91dbc8 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -5,77 +5,77 @@ use webapi::dom_exception::{DomException, InvalidStateError, TransactionInactive use webapi::error::TypeError; use webapi::dom_string_list::DOMStringList; -/// Used to represent the state of an IDBRequest. +/// Used to represent the state of an DbRequest. /// -/// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/readyState) +/// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/readyState) #[derive(Debug)] -pub enum IDBRequestReadyState { +pub enum DbRequestReadyState { /// The request is pending. Pending, /// The request is done. Done } -/// Represents the different types the source arrtibute of an IDBRequest +/// Represents the different types the source arrtibute of an DbRequest /// can take. #[derive(Debug)] -pub enum IDBRequestSource { +pub enum DbRequestSource { /// Indicates no source exists, such as when calling `indexedDB.open` None, - Store(IDBObjectStore), - Index(IDBIndex), - Cursor(IDBCursor) + Store(DbObjectStore), + Index(DbIndex), + Cursor(DbCursor) } -/// IDBRequestSharedMethode represents the methode that are shared between -/// IDBOpenDBRequest and IDBRequest. -pub trait IDBRequestSharedMethods : IEventTarget { +/// DbRequestSharedMethode represents the methode that are shared between +/// DbOpenDBRequest and DbRequest. +pub trait DbRequestSharedMethods : IEventTarget { - /// The result read-only property of the `IDBRequest` interface returns the result of the request, + /// The result read-only property of the `DbRequest` interface returns the result of the request, /// or if the request failed InvalidStateError. /// - /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/result) + /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/result) fn result( &self ) -> Result { js_try!( return @{self.as_ref()}.result; ).unwrap() } /// Returns the error in the event of an unsuccessful request. /// - /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/error) + /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/error) fn error(&self) -> Option { js!( @{self.as_ref()}.error;).try_into().unwrap() } /// Returns the source of the request. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/source) - fn source( &self ) -> IDBRequestSource { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/source) + fn source( &self ) -> DbRequestSource { let t: i32 = js!{ - if (@{self.as_ref()}.source instanceof IDBObjectStore) { + if (@{self.as_ref()}.source instanceof DbObjectStore) { return 0; - } else if (@{self.as_ref()}.source instanceof IDBIndex) { + } else if (@{self.as_ref()}.source instanceof DbIndex) { return 1; - } else if (@{self.as_ref()}.source instanceof IDBCursor) { + } else if (@{self.as_ref()}.source instanceof DbCursor) { return 2; } else { return 3; } }.try_into().unwrap(); match t { - 0 => IDBRequestSource::Store(js!(return @{self.as_ref()}.source;).try_into().unwrap()), - 1 => IDBRequestSource::Index(js!(return @{self.as_ref()}.source;).try_into().unwrap()), - 2 => IDBRequestSource::Cursor(js!(return @{self.as_ref()}.source;).try_into().unwrap()), - 3 => IDBRequestSource::None, + 0 => DbRequestSource::Store(js!(return @{self.as_ref()}.source;).try_into().unwrap()), + 1 => DbRequestSource::Index(js!(return @{self.as_ref()}.source;).try_into().unwrap()), + 2 => DbRequestSource::Cursor(js!(return @{self.as_ref()}.source;).try_into().unwrap()), + 3 => DbRequestSource::None, _ => panic!() } } - /// The `transaction` read-only property of the `IDBRequest` interface + /// The `transaction` read-only property of the `DbRequest` interface /// returns the transaction for the request, that is, the transaction /// the request is being made inside. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/transaction) - fn transaction( &self ) -> Option { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/transaction) + fn transaction( &self ) -> Option { let transaction : Value = js! ( return @{self.as_ref()}.transaction; ); @@ -86,54 +86,54 @@ pub trait IDBRequestSharedMethods : IEventTarget { } } - /// The `ready_state` read-only property of the `IDBRequest` interface + /// The `ready_state` read-only property of the `DbRequest` interface /// returns the state of the request. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/readyState) - fn ready_state( &self ) -> IDBRequestReadyState { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/readyState) + fn ready_state( &self ) -> DbRequestReadyState { let ready_state : String = js! ( return @{self.as_ref()}.readyState; ).try_into().unwrap(); if ready_state.eq("pending") { - return IDBRequestReadyState::Pending; + return DbRequestReadyState::Pending; } else if ready_state.eq("done") { - return IDBRequestReadyState::Done; + return DbRequestReadyState::Done; } else { - panic!("Got {} as an IDBRequestReadyState.", ready_state); + panic!("Got {} as an DbRequestReadyState.", ready_state); } } } -/// The `IDBReques`t interface of the IndexedDB API provides access to results +/// The `DbReques`t interface of the IndexedDB API provides access to results /// of asynchronous requests to databases and database objects using event -/// handlers. Events that are received are IDBSuccessEvent and IDBErrorEvent. +/// handlers. Events that are received are DbSuccessEvent and DbErrorEvent. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "IDBRequest")] +#[reference(instance_of = "DbRequest")] #[reference(subclass_of(EventTarget))] -pub struct IDBRequest( Reference ); +pub struct DbRequest( Reference ); -impl IEventTarget for IDBRequest {} -impl IDBRequestSharedMethods for IDBRequest {} +impl IEventTarget for DbRequest {} +impl DbRequestSharedMethods for DbRequest {} /// Provides access to the results of requests to open or delete databases. -/// Receives `IDBBlockedEvent` and `IDBVersionChangeEvent` as well as events received by `IDBRequest`. -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest) +/// Receives `DbBlockedEvent` and `DbVersionChangeEvent` as well as events received by `DbRequest`. +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbOpenDBRequest) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "IDBOpenDBRequest")] +#[reference(instance_of = "DbOpenDBRequest")] #[reference(subclass_of(EventTarget))] -pub struct IDBOpenDBRequest( Reference ); +pub struct DbOpenDBRequest( Reference ); -impl IEventTarget for IDBOpenDBRequest {} -impl IDBRequestSharedMethods for IDBOpenDBRequest {} +impl IEventTarget for DbOpenDBRequest {} +impl DbRequestSharedMethods for DbOpenDBRequest {} -impl IDBOpenDBRequest { +impl DbOpenDBRequest { - /// Returns the value property as an `IDBDatabase`, or an `InvalidStateError`. - pub fn database_result(&self) -> Result { + /// Returns the value property as an `DbDatabase`, or an `InvalidStateError`. + pub fn database_result(&self) -> Result { match self.result() { Ok(value) => Ok(value.try_into().unwrap()), Err(error) => Err(error) @@ -141,21 +141,21 @@ impl IDBOpenDBRequest { } } -/// The `IDBFactory` interface of the IndexedDB API lets applications asynchronously access the indexed databases. The object that implements the interface is `window.indexedDB`. +/// The `DbFactory` interface of the IndexedDB API lets applications asynchronously access the indexed databases. The object that implements the interface is `window.indexedDB`. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbFactory) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "IDBFactory")] -pub struct IDBFactory( Reference ); +#[reference(instance_of = "DbFactory")] +pub struct DbFactory( Reference ); -impl IDBFactory { +impl DbFactory { /// Requests opening a connection to a database. /// /// version can be None. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/open) - pub fn open>>( &self, name: &str, version: T) -> IDBOpenDBRequest { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbFactory/open) + pub fn open>>( &self, name: &str, version: T) -> DbOpenDBRequest { match version.into() { None => js! ( return @{self.as_ref()}.open(@{name}); @@ -170,8 +170,8 @@ impl IDBFactory { /// Requests the deletion of a database. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/deleteDatabase) - pub fn delete_database( &self, name: &str) -> IDBOpenDBRequest { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbFactory/deleteDatabase) + pub fn delete_database( &self, name: &str) -> DbOpenDBRequest { js! ( return @{self.as_ref()}.deleteDatabase(@{name}); ).try_into().unwrap() @@ -179,7 +179,7 @@ impl IDBFactory { /// Compares two values as keys to determine equality and ordering for `IndexedDB` operations. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/cmp) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbFactory/cmp) pub fn cmp( &self, first: Value, second: Value) -> i16 { js!( return @{self.as_ref()}.cmp(@{first.as_ref()}, @{second.as_ref()}); @@ -188,11 +188,11 @@ impl IDBFactory { } -/// The IDBCursorDirection enum indicates the direction in which a cursor is traversing the data. +/// The DbCursorDirection enum indicates the direction in which a cursor is traversing the data. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/direction) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/direction) #[derive(Debug)] -pub enum IDBCursorDirection { +pub enum DbCursorDirection { /// This direction causes the cursor to be opened at the start of the source. Next, /// This direction causes the cursor to be opened at the start of the source. For every key with duplicate values, only the first record is yielded. @@ -203,42 +203,42 @@ pub enum IDBCursorDirection { PrevUnique } -fn cursor_direction_to_string( direction: IDBCursorDirection) -> String { +fn cursor_direction_to_string( direction: DbCursorDirection) -> String { match direction { - IDBCursorDirection::Next => "next".to_string(), - IDBCursorDirection::NextUnique => "nextunique".to_string(), - IDBCursorDirection::Prev => "prev".to_string(), - IDBCursorDirection::PrevUnique => "prevunique".to_string() + DbCursorDirection::Next => "next".to_string(), + DbCursorDirection::NextUnique => "nextunique".to_string(), + DbCursorDirection::Prev => "prev".to_string(), + DbCursorDirection::PrevUnique => "prevunique".to_string() } } -fn string_to_cursor_direction( direction: &str) -> IDBCursorDirection { +fn string_to_cursor_direction( direction: &str) -> DbCursorDirection { if direction.eq("next") { - return IDBCursorDirection::Next; + return DbCursorDirection::Next; } else if direction.eq("nextunique") { - return IDBCursorDirection::NextUnique; + return DbCursorDirection::NextUnique; } else if direction.eq("prev") { - return IDBCursorDirection::Prev; + return DbCursorDirection::Prev; } else if direction.eq("prevunique") { - return IDBCursorDirection::PrevUnique; + return DbCursorDirection::PrevUnique; } else { unreachable!("Unknown index direction \"{}\".", direction); } } /// This enum is used to represent the vlaue of the soure property of -/// a `IDBCursor`. +/// a `DbCursor`. #[derive(Debug)] -pub enum IDBCursorSource { - Store(IDBObjectStore), - Index(IDBIndex) +pub enum DbCursorSource { + Store(DbObjectStore), + Index(DbIndex) } error_enum_boilerplate! { - /// An enum of the exceptions that IDBCursorSharedMethods.advance() - /// and IDBCursorSharedMethods.next may throw. - IDBAdvanceError, - /// This IDBCursor's transaction is inactive. + /// An enum of the exceptions that DbCursorSharedMethods.advance() + /// and DbCursorSharedMethods.next may throw. + DbAdvanceError, + /// This DbCursor's transaction is inactive. TransactionInactiveError, /// The value passed into the parameter was zero or a negative number. TypeError, @@ -247,8 +247,8 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - IDBContinuePrimaryKeyError, - /// This IDBCursor's transaction is inactive. + DbContinuePrimaryKeyError, + /// This DbCursor's transaction is inactive. TransactionInactiveError, /// The key parameter may have any of the following conditions: /// * The key is not a valid key. @@ -262,12 +262,12 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - IDBUpdateError, - /// This IDBCursor's transaction is inactive. + DbUpdateError, + /// This DbCursor's transaction is inactive. TransactionInactiveError, /// The transaction mode is read only. ReadOnlyError, - /// The cursor was created using IDBIndex.openKeyCursor, is currently being iterated, or has iterated past its end. + /// The cursor was created using DbIndex.openKeyCursor, is currently being iterated, or has iterated past its end. InvalidStateError, /// The underlying object store uses in-line keys and the property in the value at the object store's key path does not match the key in this cursor's position. DataError, @@ -278,12 +278,12 @@ error_enum_boilerplate! { /// error_enum_boilerplate! { /// - IDBAddError, - /// This IDBCursor's transaction is inactive. + DbAddError, + /// This DbCursor's transaction is inactive. TransactionInactiveError, /// The transaction mode is read only. ReadOnlyError, - /// The cursor was created using IDBIndex.openKeyCursor, is currently being iterated, or has iterated past its end. + /// The cursor was created using DbIndex.openKeyCursor, is currently being iterated, or has iterated past its end. InvalidStateError, /// The underlying object store uses in-line keys and the property in the value at the object store's key path does not match the key in this cursor's position. DataError, @@ -294,83 +294,83 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - IDBCursorDeleteError, - /// This IDBCursor's transaction is inactive. + DbCursorDeleteError, + /// This DbCursor's transaction is inactive. TransactionInactiveError, /// The transaction mode is read-only. ReadOnlyError, - /// The cursor was created using IDBindex.openKeyCursor, is currently being iterated, or has iterated past its end. + /// The cursor was created using Dbindex.openKeyCursor, is currently being iterated, or has iterated past its end. InvalidStateError } error_enum_boilerplate! { - IDBClearError, + DbClearError, /// The transaction associated with this operation is in read-only mode. ReadOnlyError, - /// This IDBObjectStore's transaction is inactive. + /// This DbObjectStore's transaction is inactive. TransactionInactiveError } /// This trait implements all the methods that are shared between -/// `IDBCursor` and `IDBCursorWithValue`. -pub trait IDBCursorSharedMethods: AsRef< Reference > { +/// `DbCursor` and `DbCursorWithValue`. +pub trait DbCursorSharedMethods: AsRef< Reference > { - /// The source read-only property of the `IDBCursor` interface returns - /// the `IDBObjectStore` or `IDBIndex` that the cursor is iterating over. - /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/source) - fn source( &self ) -> IDBCursorSource { - if js!( return @{self.as_ref()}.source instanceof IDBObjectStore; ).try_into().unwrap() { - IDBCursorSource::Store(js!( return @{self.as_ref()}.source ).try_into().unwrap()) - } else if js!( return @{self.as_ref()}.source instanceof IDBIndex;).try_into().unwrap() { - IDBCursorSource::Index(js!( return @{self.as_ref()}.source ).try_into().unwrap()) + /// The source read-only property of the `DbCursor` interface returns + /// the `DbObjectStore` or `DbIndex` that the cursor is iterating over. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/source) + fn source( &self ) -> DbCursorSource { + if js!( return @{self.as_ref()}.source instanceof DbObjectStore; ).try_into().unwrap() { + DbCursorSource::Store(js!( return @{self.as_ref()}.source ).try_into().unwrap()) + } else if js!( return @{self.as_ref()}.source instanceof DbIndex;).try_into().unwrap() { + DbCursorSource::Index(js!( return @{self.as_ref()}.source ).try_into().unwrap()) } else { panic!() } } - /// The `direction` read-only property of the `IDBCursor` interface is + /// The `direction` read-only property of the `DbCursor` interface is /// an enum that represents the direction of traversal of the - /// cursor (set using `IDBObjectStore.openCursor` for example). + /// cursor (set using `DbObjectStore.openCursor` for example). /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/direction) - fn direction( &self ) -> IDBCursorDirection { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/direction) + fn direction( &self ) -> DbCursorDirection { let direction: String = js! ( return @{self.as_ref()}.direction; ).try_into().unwrap(); return string_to_cursor_direction(&direction); } - /// The `key` read-only property of the `IDBCursor` interface returns the key + /// The `key` read-only property of the `DbCursor` interface returns the key /// for the record at the cursor's position. If the cursor is outside its range, /// this is set to undefined. The cursor's key can be any data type. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/key) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/key) fn key( &self ) -> Value { js!( return @{self.as_ref()}.key; ) .try_into().unwrap() } - /// The `primary_key` read-only property of the `IDBCursor` interface returns + /// The `primary_key` read-only property of the `DbCursor` interface returns /// the cursor's current effective key. If the cursor is currently being /// iterated or has iterated outside its range, this is set to undefined. ///The cursor's primary key can be any data type. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/primaryKey) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/primaryKey) fn primary_key( &self ) -> Value { js!( return @{self.as_ref()}.primaryKey; ) .try_into().unwrap() } - /// The advance() method of the IDBCursor interface sets the number of times + /// The advance() method of the DbCursor interface sets the number of times /// a cursor should move its position forward. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/advance) - fn advance( &self, count: u32) -> Result<(), IDBAdvanceError> { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/advance) + fn advance( &self, count: u32) -> Result<(), DbAdvanceError> { js_try!( @{self.as_ref()}.advance(@{count}); ).unwrap() } - /// The next() method of the IDBCursor interface advances the cursor to the + /// The next() method of the DbCursor interface advances the cursor to the /// next position along its direction, to the item whose key matches the optional /// key parameter. If no key (None) is specified, the cursor advances to the immediate /// next position, based on its direction. @@ -378,70 +378,70 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { /// This function stands in for continue in the javascript interface. Continue /// is a keyword in rust and so needed to be renamed. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/continue) - fn next>>( &self, key: K) -> Result<(), IDBAdvanceError> { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/continue) + fn next>>( &self, key: K) -> Result<(), DbAdvanceError> { match key.into() { None => js_try!( @{self.as_ref()}.continue(); ).unwrap(), Some(key) => js_try! ( @{self.as_ref()}.continue(@{key.as_ref()}); ).unwrap() } } - /// The continuePrimaryKey() method of the IDBCursor interface advances + /// The continuePrimaryKey() method of the DbCursor interface advances /// the cursor to the to the item whose key matches the key parameter as /// well as whose primary key matches the primary key parameter. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/continuePrimaryKey) - fn continue_primary_key( &self, key: Value, primary_key: Value) -> Result<(), IDBContinuePrimaryKeyError> { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/continuePrimaryKey) + fn continue_primary_key( &self, key: Value, primary_key: Value) -> Result<(), DbContinuePrimaryKeyError> { js_try!( @{self.as_ref()}.continuePrimaryKey(@{key}, @{primary_key}); ).unwrap() } - /// The update() method of the IDBCursor interface returns an IDBRequest + /// The update() method of the DbCursor interface returns an DbRequest /// object, and, in a separate thread, updates the value at the current /// position of the cursor in the object store. If the cursor points to /// a record that has just been deleted, a new record is created. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/update) - fn update( &self, value: Value) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/update) + fn update( &self, value: Value) -> Result { js_try!( return @{self.as_ref()}.update(@{value.as_ref()}); ).unwrap() } - /// The delete() method of the IDBCursor interface returns an IDBRequest + /// The delete() method of the DbCursor interface returns an DbRequest /// object, and, in a separate thread, deletes the record at the cursor's /// position, without changing the cursor's position. Once the record is /// deleted, the cursor's value is set to null. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete) - fn delete( &self ) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/delete) + fn delete( &self ) -> Result { js_try!( return @{self.as_ref()}.delete(); ).unwrap() } } -/// The IDBCursor interface of the IndexedDB API represents a cursor for +/// The DbCursor interface of the IndexedDB API represents a cursor for /// traversing or iterating over multiple records in a database. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "IDBCursor")] -pub struct IDBCursor( Reference ); +#[reference(instance_of = "DbCursor")] +pub struct DbCursor( Reference ); -impl IDBCursorSharedMethods for IDBCursor {} +impl DbCursorSharedMethods for DbCursor {} -/// The IDBCursorWithValue interface of the IndexedDB API represents a cursor +/// The DbCursorWithValue interface of the IndexedDB API represents a cursor /// for traversing or iterating over multiple records in a database. It is -/// the same as the IDBCursor, except that it includes the value property. +/// the same as the DbCursor, except that it includes the value property. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursorWithValue) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursorWithValue) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "IDBCursorWithValue")] -pub struct IDBCursorWithValue( Reference ); +#[reference(instance_of = "DbCursorWithValue")] +pub struct DbCursorWithValue( Reference ); -impl IDBCursorSharedMethods for IDBCursorWithValue {} +impl DbCursorSharedMethods for DbCursorWithValue {} -impl IDBCursorWithValue { +impl DbCursorWithValue { /// Returns the value of the current cursor. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursorWithValue/value) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursorWithValue/value) pub fn value( &self ) -> Value { js! ( return @{self}.value @@ -449,105 +449,105 @@ impl IDBCursorWithValue { } } -/// The IDBKeyRange interface of the IndexedDB API represents a continuous interval +/// The DbKeyRange interface of the IndexedDB API represents a continuous interval /// over some data type that is used for keys. Records can be retrieved from -/// IDBObjectStore and IDBIndex objects using keys or a range of keys. You can limit +/// DbObjectStore and DbIndex objects using keys or a range of keys. You can limit /// the range using lower and upper bounds. For example, you can iterate over all /// values of a key in the value range A–Z. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "IDBKeyRange")] -pub struct IDBKeyRange( Reference ); +#[reference(instance_of = "DbKeyRange")] +pub struct DbKeyRange( Reference ); -impl IDBKeyRange { +impl DbKeyRange { // Static construction methods: - /// The only() method of the IDBKeyRange interface creates a new key range + /// The only() method of the DbKeyRange interface creates a new key range /// containing a single value. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/only) - pub fn only( value: Value ) -> Result { - js_try! ( return IDBKeyRange.only(@{value}); ).unwrap() + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/only) + pub fn only( value: Value ) -> Result { + js_try! ( return DbKeyRange.only(@{value}); ).unwrap() } - /// The lower_bound() method of the IDBKeyRange interface creates a new key range + /// The lower_bound() method of the DbKeyRange interface creates a new key range /// with only a lower bound. if open is false it includes the lower endpoint /// value and is closed. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/lowerBound) - pub fn lower_bound( lower: Value, open: bool ) -> Result { - js_try! ( return IDBKeyRange.lowerBound(@{lower}, @{open}); ).unwrap() + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/lowerBound) + pub fn lower_bound( lower: Value, open: bool ) -> Result { + js_try! ( return DbKeyRange.lowerBound(@{lower}, @{open}); ).unwrap() } - /// The upper_bound() method of the IDBKeyRange interface creates a new key range + /// The upper_bound() method of the DbKeyRange interface creates a new key range /// with only an apper bound. if open is false it includes the upper endpoint /// value and is closed. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/upperBound) - pub fn upper_bound( upper: Value, open: bool ) -> Result { - js_try! ( return IDBKeyRange.upperBound(@{upper}, @{open}); ).unwrap() + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/upperBound) + pub fn upper_bound( upper: Value, open: bool ) -> Result { + js_try! ( return DbKeyRange.upperBound(@{upper}, @{open}); ).unwrap() } - /// The bound() method of the IDBKeyRange interface creates a new key range + /// The bound() method of the DbKeyRange interface creates a new key range /// with the specified upper and lower bounds. The bounds can be open (that /// is, the bounds exclude the endpoint values) or closed (that is, the bounds /// include the endpoint values). /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/bound) - pub fn bound (lower: Value, upper: Value, lower_open: bool, upper_open: bool) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/bound) + pub fn bound (lower: Value, upper: Value, lower_open: bool, upper_open: bool) -> Result { js_try! ( - return IDBKeyRange.boundound(@{lower}, @{upper}, @{lower_open}, @{upper_open}); + return DbKeyRange.boundound(@{lower}, @{upper}, @{lower_open}, @{upper_open}); ).unwrap() } /// Lower bound of the key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/lower) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/lower) pub fn lower( &self ) -> Value { js!( return @{self}.lower; ).try_into().unwrap() } /// Upper bound of the key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/upper) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/upper) pub fn upper( &self ) -> Value { js!( return @{self}.upper; ).try_into().unwrap() } /// Returns false if the lower-bound value is included in the key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/lowerOpen) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/lowerOpen) pub fn lower_open( &self ) -> bool { js!( return @{self}.lowerOpen; ).try_into().unwrap() } /// Returns false if the upper-bound value is included in the key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/upperOpen) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/upperOpen) pub fn upper_open( &self ) -> bool { js!( return @{self}.upperOpen; ).try_into().unwrap() } - /// The includes() method of the IDBKeyRange interface returns a boolean + /// The includes() method of the DbKeyRange interface returns a boolean /// indicating whether a specified key is inside the key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/includes) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/includes) pub fn includes( &self, value: Value ) -> Result { js_try! ( return @{self}.includes(@{value}); ).unwrap() } } #[derive(Debug)] -pub enum IDBKeyOrKeyRange { +pub enum DbKeyOrKeyRange { None, Value(Value), - Range(IDBKeyRange) + Range(DbKeyRange) } error_enum_boilerplate! { - IDBSetNameError, + DbSetNameError, /// The index, or its object store, has been deleted; or the current transaction /// is not an upgrade transaction. You can only rename indexes during upgrade @@ -564,20 +564,20 @@ error_enum_boilerplate! { error_enum_boilerplate! { /// This Error is raised by various methods ised to query object stores /// and indexes. - IDBQueryError, + DbQueryError, - /// This IDBIndex's transaction is inactive. + /// This DbIndex's transaction is inactive. TransactionInactiveError, /// The key or key range provided contains an invalid key. DataError, - /// The IDBIndex has been deleted or removed. + /// The DbIndex has been deleted or removed. InvalidStateError } error_enum_boilerplate! { - IDBIndexError, + DbIndexError, /// The source object store has been deleted, or the transaction for the object store has finished. InvalidStateError, /// There is no index with the given name (case-sensitive) in the database. @@ -585,12 +585,12 @@ error_enum_boilerplate! { } -/// This trait contains mothods that are Identicle in both IDBIndex IDBObjectStore -pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { +/// This trait contains mothods that are Identicle in both DbIndex DbObjectStore +pub trait DbObjectStoreIndexSharedMethods: AsRef< Reference > { /// Returns the name of this index or object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/name) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/name) fn name( &self ) -> String { js! ( return @{self.as_ref()}.name; @@ -599,13 +599,13 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// Returns the name of this index or object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/name) - fn set_name( &self, name: &str) -> Result<(), IDBSetNameError> { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/name) + fn set_name( &self, name: &str) -> Result<(), DbSetNameError> { js_try! ( @{self.as_ref()}.name = @{name}; ).unwrap() } - /// The key_path read-only property of the IDBObjectStore interface returns the - /// key path of this object store. Or in the case of an IDBIndex, the current + /// The key_path read-only property of the DbObjectStore interface returns the + /// key path of this object store. Or in the case of an DbIndex, the current /// object store. fn key_path( &self ) -> Value { js!( return @{self.as_ref()}.keyPath; ).try_into().unwrap() @@ -613,34 +613,34 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// This is for retrieving specific records from an object store or index. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/get) - fn get>( &self, query: Q) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/get) + fn get>( &self, query: Q) -> Result { match query.into() { - IDBKeyOrKeyRange::None => js_try! ( + DbKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.get(); ), - IDBKeyOrKeyRange::Value(value) => js_try! ( + DbKeyOrKeyRange::Value(value) => js_try! ( return @{self.as_ref()}.get(@{value.as_ref()}); ), - IDBKeyOrKeyRange::Range(range) => js_try! ( + DbKeyOrKeyRange::Range(range) => js_try! ( return @{self.as_ref()}.get(@{range.as_ref()}); ) }.unwrap() } - /// Returns an IDBRequest object, and, in a separate thread retrieves and + /// Returns an DbRequest object, and, in a separate thread retrieves and /// returns the record key for the object matching the specified parameter. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getKey) - fn get_key>( &self, query: Q) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/getKey) + fn get_key>( &self, query: Q) -> Result { match query.into() { - IDBKeyOrKeyRange::None => js_try! ( + DbKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getKey(); ), - IDBKeyOrKeyRange::Value(value) => js_try! ( + DbKeyOrKeyRange::Value(value) => js_try! ( return @{self.as_ref()}.getKey(@{value.as_ref()}); ), - IDBKeyOrKeyRange::Range(range) => js_try! ( + DbKeyOrKeyRange::Range(range) => js_try! ( return @{self.as_ref()}.getKey(@{range.as_ref()}); ) }.unwrap() @@ -649,17 +649,17 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// The get_ll() method retrieves all objects that are inside the index or /// object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/getAll) - fn get_all, C: Into>>( &self, query: Q, count: C) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/getAll) + fn get_all, C: Into>>( &self, query: Q, count: C) -> Result { match query.into() { - IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAll(); ), - IDBKeyOrKeyRange::Value(value) => { + DbKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAll(); ), + DbKeyOrKeyRange::Value(value) => { match count.into() { None => js_try! ( return @{self.as_ref()}.getAll(@{value.as_ref()}); ), Some(count) => js_try! ( return @{self.as_ref()}.getAll(@{value.as_ref()}, @{count}); ) } }, - IDBKeyOrKeyRange::Range(range) => { + DbKeyOrKeyRange::Range(range) => { match count.into() { None => js_try! ( return @{self.as_ref()}.getAll(@{range.as_ref()}); ), Some(count) => js_try! ( return @{self.as_ref()}.getAll(@{range.as_ref()}, @{count}); ) @@ -668,23 +668,23 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { }.unwrap() } - // Acording to the mozilla documentation the IDBIndex version does not + // Acording to the mozilla documentation the DbIndex version does not // Throw DataError. - /// The get_all_keys() method returns an IDBRequest object retrieves record keys + /// The get_all_keys() method returns an DbRequest object retrieves record keys /// for all objects matching the specified parameter or all objects if no /// parameters are given. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys) - fn get_all_keys, C: Into>>( &self, query: Q, count: C) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/getAllKeys) + fn get_all_keys, C: Into>>( &self, query: Q, count: C) -> Result { match query.into() { - IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAllKeys(); ), - IDBKeyOrKeyRange::Value(value) => { + DbKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAllKeys(); ), + DbKeyOrKeyRange::Value(value) => { match count.into() { None => js_try! ( return @{self.as_ref()}.getAllKeys(@{value.as_ref()}); ), Some(count) => js_try! ( return @{self.as_ref()}.getAllKeys(@{value.as_ref()}, @{count}); ) } }, - IDBKeyOrKeyRange::Range(range) => { + DbKeyOrKeyRange::Range(range) => { match count.into() { None => js_try! ( return @{self.as_ref()}.getAllKeys(@{range.as_ref()}); ), Some(count) => js_try! ( return @{self.as_ref()}.getAllKeys(@{range.as_ref()}, @{count}); ) @@ -693,28 +693,28 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { }.unwrap() } - /// Returns an IDBRequest object, and, in a separate thread, returns the total number of records that match the provided key or IDBKeyRange + /// Returns an DbRequest object, and, in a separate thread, returns the total number of records that match the provided key or DbKeyRange /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/count) - fn count>( &self, query: Q) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/count) + fn count>( &self, query: Q) -> Result { match query.into() { - IDBKeyOrKeyRange::None => js_try! ( + DbKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.count(); ), - IDBKeyOrKeyRange::Value(value) => js_try! ( + DbKeyOrKeyRange::Value(value) => js_try! ( return @{self.as_ref()}.count(@{value.as_ref()}); ), - IDBKeyOrKeyRange::Range(range) => js_try! ( + DbKeyOrKeyRange::Range(range) => js_try! ( return @{self.as_ref()}.count(@{range.as_ref()}); ) }.unwrap() } - /// The open_cursor() method returns an IDBRequest object, and, in a separate + /// The open_cursor() method returns an DbRequest object, and, in a separate /// thread, creates a cursor over the specified key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openCursor) - fn open_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/openCursor) + fn open_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { match range.into() { None => js_try! ( return @{self.as_ref()}.openCursor(); ), Some(range) => { @@ -726,12 +726,12 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { }.unwrap() } - /// The open_key_cursor() method returns an IDBRequest object, and, in a + /// The open_key_cursor() method returns an DbRequest object, and, in a /// separate thread, creates a cursor over the specified key range, as arranged /// by this index. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openKeyCursor) - fn open_key_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/openKeyCursor) + fn open_key_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { match range.into() { None => js_try! ( return @{self.as_ref()}.openKeyCursor(); ), Some(range) => { @@ -747,25 +747,25 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// Provides asynchronous access to an index in a database. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "IDBIndex")] -pub struct IDBIndex( Reference ); +#[reference(instance_of = "DbIndex")] +pub struct DbIndex( Reference ); -impl IDBObjectStoreIndexSharedMethods for IDBIndex {} +impl DbObjectStoreIndexSharedMethods for DbIndex {} -impl IDBIndex { +impl DbIndex { - /// The object_store property of the IDBIndex interface returns the name of the object store referenced by the current index. + /// The object_store property of the DbIndex interface returns the name of the object store referenced by the current index. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/objectStore) - pub fn object_store( &self ) -> IDBObjectStore { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/objectStore) + pub fn object_store( &self ) -> DbObjectStore { js! ( return @{self.as_ref()}.objectStore ).try_into().unwrap() } /// Affects how the index behaves when the result of evaluating the index's key path yields an array. If `true`, there is one record in the index for each item in an array of keys. If `false`, then there is one record for each key that is an array. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/multiEntry) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/multiEntry) pub fn multi_entry( &self ) -> bool { js! ( return @{self.as_ref()}.multiEntry; @@ -774,7 +774,7 @@ impl IDBIndex { /// If `true`, this index does not allow duplicate values for a key. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/unique) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/unique) pub fn unique( &self ) -> bool { js! ( return @{self.as_ref()}.unique; @@ -784,7 +784,7 @@ impl IDBIndex { } error_enum_boilerplate! { - IDBObjectStoreDeleteError, + DbObjectStoreDeleteError, /// This object store's transaction is inactive. TransactionInactiveError, /// The object store's transaction mode is read-only. @@ -795,29 +795,29 @@ error_enum_boilerplate! { DataError } -/// The `IDBObjectStore` interface of the IndexedDB API represents an object store in a database +/// The `DbObjectStore` interface of the IndexedDB API represents an object store in a database /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "IDBObjectStore")] -pub struct IDBObjectStore( Reference ); +#[reference(instance_of = "DbObjectStore")] +pub struct DbObjectStore( Reference ); -impl IDBObjectStoreIndexSharedMethods for IDBObjectStore {} +impl DbObjectStoreIndexSharedMethods for DbObjectStore {} -impl IDBObjectStore { +impl DbObjectStore { - /// The index_names read-only property of the `IDBObjectStore` interface returns a list of th + /// The index_names read-only property of the `DbObjectStore` interface returns a list of th /// names of indexes on objects in this object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/indexNames) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/indexNames) pub fn index_names( &self ) -> DOMStringList { js! ( return @{self}.indexNames ).try_into().unwrap() } - /// The `IDBTransaction` object to which this object store belongs. + /// The `DbTransaction` object to which this object store belongs. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/transaction) - pub fn transaction( &self ) -> IDBTransaction { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/transaction) + pub fn transaction( &self ) -> DbTransaction { js! ( return @{self.as_ref()}.transaction; ).try_into().unwrap() @@ -825,7 +825,7 @@ impl IDBObjectStore { /// Returns the value of the auto increment flag for this object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/autoIncrement) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/autoIncrement) pub fn auto_increment( &self ) -> bool { js! ( return @{self.as_ref()}.autoIncrement; @@ -835,8 +835,8 @@ impl IDBObjectStore { /// Updates a given record in a database, or inserts a new record if the given item does not already exist. /// The key is only needed if /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put) - pub fn put>>( &self, value: Value, key: T) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/put) + pub fn put>>( &self, value: Value, key: T) -> Result { match key.into() { None => js_try! ( return @{self.as_ref()}.put(@{value.as_ref()}); @@ -847,10 +847,10 @@ impl IDBObjectStore { }.unwrap() } - /// Returns an `IDBRequest` object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store. + /// Returns an `DbRequest` object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add) - pub fn add>>( &self, value: Value, key: T) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/add) + pub fn add>>( &self, value: Value, key: T) -> Result { match key.into() { None => js_try! ( return @{self.as_ref()}.add(@{value.as_ref()}); @@ -861,19 +861,19 @@ impl IDBObjectStore { }.unwrap() } - /// returns an `IDBRequest` object, and, in a separate thread, deletes the specified record or records. + /// returns an `DbRequest` object, and, in a separate thread, deletes the specified record or records. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete) - pub fn delete( &self, query: Value) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/delete) + pub fn delete( &self, query: Value) -> Result { js_try! ( return @{self.as_ref()}.delete(@{query.as_ref()}); ).unwrap() } - /// Returns an IDBRequest object, and clears this object store in a separate thread + /// Returns an DbRequest object, and clears this object store in a separate thread /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/clear) - pub fn clear( &self ) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/clear) + pub fn clear( &self ) -> Result { js_try! ( return @{self.as_ref()}.clear(); ).unwrap() @@ -881,21 +881,21 @@ impl IDBObjectStore { /// opens a named index in the current object store /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/index) - pub fn index( &self, name: &str) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/index) + pub fn index( &self, name: &str) -> Result { js_try! ( return @{self.as_ref()}.index(@{name}); ).unwrap() } - // [NewObject] IDBIndex createIndex(DOMString name, (DOMString or sequence) keyPath, optional IDBIndexParameters options); - /// Creates and returns a new `IDBIndex` object in the connected database. + // [NewObject] DbIndex createIndex(DOMString name, (DOMString or sequence) keyPath, optional DbIndexParameters options); + /// Creates and returns a new `DbIndex` object in the connected database. /// /// Note that this method must be called only from a VersionChange /// transaction mode callback. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex) - pub fn create_index( &self, name: &str, key_path: &str, options: Value) -> IDBIndex { // TODO, how am I doing the optinal options? + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/createIndex) + pub fn create_index( &self, name: &str, key_path: &str, options: Value) -> DbIndex { // TODO, how am I doing the optinal options? js! ( return @{self.as_ref()}.createIndex(@{name}, @{key_path}, @{options.as_ref()}); ).try_into().unwrap() @@ -903,7 +903,7 @@ impl IDBObjectStore { /// Destroys the index with the specified name in the connected database, used during a version upgrade. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/deleteIndex) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/deleteIndex) pub fn delete_index( &self, name: &str) { js! { return @{self.as_ref()}.deleteIndex(@{name}); @@ -911,51 +911,51 @@ impl IDBObjectStore { } } -/* dictionary IDBIndexParameters { +/* dictionary DbIndexParameters { boolean unique = false; boolean multiEntry = false; };*/ -/// An IDBTransactionMode object defining the mode for isolating access to +/// An DbTransactionMode object defining the mode for isolating access to /// data in the current object stores. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/mode) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/mode) #[derive(Debug)] -pub enum IDBTransactionMode { +pub enum DbTransactionMode { /// Allows data to be read but not changed. ReadOnly, /// Allows reading and writing of data in existing data stores to be changed. ReadWrite, /// Allows any operation to be performed, including ones that delete and /// create object stores and indexes. This mode is for updating the version - /// number of transactions that were started using IDBDatabase.set_version(). + /// number of transactions that were started using DbDatabase.set_version(). /// Transactions of this mode cannot run concurrently with other transactions. /// Transactions in this mode are known as "upgrade transactions." VersionChange } -fn transaction_mode_to_string( mode: IDBTransactionMode ) -> String { +fn transaction_mode_to_string( mode: DbTransactionMode ) -> String { match mode { - IDBTransactionMode::ReadOnly => "readonly".to_string(), - IDBTransactionMode::ReadWrite => "readwrite".to_string(), - IDBTransactionMode::VersionChange => "versionchange".to_string() + DbTransactionMode::ReadOnly => "readonly".to_string(), + DbTransactionMode::ReadWrite => "readwrite".to_string(), + DbTransactionMode::VersionChange => "versionchange".to_string() } } -fn string_to_transaction_mode( mode: &str ) -> IDBTransactionMode { +fn string_to_transaction_mode( mode: &str ) -> DbTransactionMode { if mode.eq("readonly") { - return IDBTransactionMode::ReadOnly; + return DbTransactionMode::ReadOnly; } else if mode.eq("readwrite") { - return IDBTransactionMode::ReadWrite; + return DbTransactionMode::ReadWrite; } else if mode.eq("versionchange") { - return IDBTransactionMode::VersionChange; + return DbTransactionMode::VersionChange; } else { unreachable!("Unknown transaction mode \"{}\".", mode); } } error_enum_boilerplate! { - IDBObjectStoreError, + DbObjectStoreError, /// The requested object store is not in this transaction's scope. NotFoundError, @@ -964,67 +964,67 @@ error_enum_boilerplate! { InvalidStateError } -/// The `IDBTransaction` interface of the IndexedDB API provides a static, asynchronous transaction on a database using event handlers. +/// The `DbTransaction` interface of the IndexedDB API provides a static, asynchronous transaction on a database using event handlers. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "IDBTransaction")] -pub struct IDBTransaction( Reference ); +#[reference(instance_of = "DbTransaction")] +pub struct DbTransaction( Reference ); -impl IEventTarget for IDBTransaction {} +impl IEventTarget for DbTransaction {} -impl IDBTransaction { +impl DbTransaction { - /// The object_store_names read-only property of the IDBTransaction interface returns - /// a DOMStringList of names of IDBObjectStore objects. + /// The object_store_names read-only property of the DbTransaction interface returns + /// a DOMStringList of names of DbObjectStore objects. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/objectStoreNames) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/objectStoreNames) pub fn object_store_names( &self ) -> DOMStringList { js! ( return @{self}.objectStoreNames ).try_into().unwrap() } - /// The mode read-only property of the `IDBTransaction` interface returns the + /// The mode read-only property of the `DbTransaction` interface returns the /// current mode for accessing the data in the object stores in the scope of the /// transaction (i.e. is the mode to be read-only, or do you want to write to /// the object stores?) The default value is readonly. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/mode - pub fn mode( &self ) -> IDBTransactionMode { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/mode + pub fn mode( &self ) -> DbTransactionMode { let mode: String = js!( return @{self}.mode; ).try_into().unwrap(); string_to_transaction_mode(&mode) } /// Returns the database connection with which this transaction is associated. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/db) - pub fn db( &self ) -> IDBDatabase { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/db) + pub fn db( &self ) -> DbDatabase { js! ( return @{self}.db(); ).try_into().unwrap() } - /// The IDBTransaction.error property of the IDBTransaction interface returns + /// The DbTransaction.error property of the DbTransaction interface returns /// one of several types of error when there is an unsuccessful transaction. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/error) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/error) pub fn error( &self ) -> Option { js!( return @{self}.error; ).try_into().unwrap() } - /// The object_store() method of the IDBTransaction interface returns an object + /// The object_store() method of the DbTransaction interface returns an object /// store that has already been added to the scope of this transaction. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/objectStore) - pub fn object_store( &self, name: &str) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/objectStore) + pub fn object_store( &self, name: &str) -> Result { js_try! ( return @{self.as_ref()}.objectStore(@{name}); ).unwrap() } - /// The abort() method of the IDBTransaction interface rolls back all the + /// The abort() method of the DbTransaction interface rolls back all the /// changes to objects in the database associated with this transaction. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/abort) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/abort) pub fn abort( &self ) -> Result<(), InvalidStateError> { js_try! ( @{self}.abort(); ).unwrap() } @@ -1032,7 +1032,7 @@ impl IDBTransaction { } error_enum_boilerplate! { - IDBCreateObjectStoreError, + DbCreateObjectStoreError, /// Occurs if the method was not called from a versionchange transaction /// callback. For older WebKit browsers, you must call first. @@ -1052,7 +1052,7 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - IDBDeleteObjectStoreError, + DbDeleteObjectStoreError, /// Occurs if the method was not called from a versionchange transaction callback. /// For older WebKit browsers, you must call first. @@ -1066,20 +1066,20 @@ error_enum_boilerplate! { NotFoundError } -/// The `IDBDatabase` interface of the IndexedDB API provides a connection to a database. +/// The `DbDatabase` interface of the IndexedDB API provides a connection to a database. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "IDBDatabase")] -pub struct IDBDatabase( Reference ); +#[reference(instance_of = "DbDatabase")] +pub struct DbDatabase( Reference ); -impl IEventTarget for IDBDatabase {} +impl IEventTarget for DbDatabase {} -impl IDBDatabase { +impl DbDatabase { /// Returns the the name of the connected database. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/name) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/name) pub fn name( &self ) -> String { js! ( return @{self.as_ref()}.name; @@ -1088,28 +1088,28 @@ impl IDBDatabase { /// Returns the version of the connected database. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/version) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/version) pub fn version( &self ) -> u64 { js! ( return @{self.as_ref()}.version; ).try_into().unwrap() } - /// The objectStoreNames read-only property of the IDBDatabase interface is a + /// The objectStoreNames read-only property of the DbDatabase interface is a /// DOMStringList containing a list of the names of the object stores currently /// in the connected database. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/objectStoreNames) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/objectStoreNames) pub fn object_store_names( &self ) -> DOMStringList { js! ( return @{self}.objectStoreNames ).try_into().unwrap() } - /// Immediately returns a transaction object (`IDBTransaction`) containing - /// the `IDBTransaction.object_store` method, which you can use to access + /// Immediately returns a transaction object (`DbTransaction`) containing + /// the `DbTransaction.object_store` method, which you can use to access /// your object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/transaction) - pub fn transaction( &self, store_names: Vec<&str>, mode: IDBTransactionMode) -> IDBTransaction { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/transaction) + pub fn transaction( &self, store_names: Vec<&str>, mode: DbTransactionMode) -> DbTransaction { js! ( return @{self.as_ref()}.transaction(@{store_names}, @{transaction_mode_to_string(mode)}); ).try_into().unwrap() @@ -1117,7 +1117,7 @@ impl IDBDatabase { /// Returns immediately and closes the connection in a separate thread. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/close) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/close) pub fn close( &self ) { js! { @{self.as_ref()}.close(); @@ -1126,8 +1126,8 @@ impl IDBDatabase { /// Creates and returns a new object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/createObjectStore) - pub fn create_object_store( &self, name: &str, auto_increment: bool, key_path: &str) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/createObjectStore) + pub fn create_object_store( &self, name: &str, auto_increment: bool, key_path: &str) -> Result { js_try! ( return @{self.as_ref()}.createObjectStore(@{name}, { autoIncrement: @{auto_increment}, key_path: @{key_path} } ); ).unwrap() @@ -1135,8 +1135,8 @@ impl IDBDatabase { /// Destroys the object store with the given name. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/deleteObjectStore) - pub fn delete_object_store( &self, name: &str ) -> Result<(), IDBDeleteObjectStoreError> { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/deleteObjectStore) + pub fn delete_object_store( &self, name: &str ) -> Result<(), DbDeleteObjectStoreError> { js_try! ( @{self.as_ref()}.deleteObjectStore(@{name}); ).unwrap() diff --git a/src/webapi/window.rs b/src/webapi/window.rs index 80d443cc..2445caf6 100644 --- a/src/webapi/window.rs +++ b/src/webapi/window.rs @@ -8,7 +8,7 @@ use webapi::history::History; use webapi::selection::Selection; use webcore::once::Once; use webcore::value::Value; -use webapi::indexeddb::IDBFactory; +use webapi::indexeddb::DbFactory; /// A handle to a pending animation frame request. @@ -136,7 +136,7 @@ impl Window { } /// This is a method - pub fn indexed_db( &self ) -> IDBFactory { + pub fn indexed_db( &self ) -> DbFactory { js! ( return window.indexedDB; ).try_into().unwrap() From cc1d178620b307d817e67a2a58d300ca5117193e Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:26:19 -0700 Subject: [PATCH 37/85] Fix revert reference instance_of IDB --- src/webapi/indexeddb.rs | 20 ++++++++++---------- 1 file changed, 10 insertions(+), 10 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 1a91dbc8..bee2ae97 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -112,7 +112,7 @@ pub trait DbRequestSharedMethods : IEventTarget { /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "DbRequest")] +#[reference(instance_of = "IDBRequest")] #[reference(subclass_of(EventTarget))] pub struct DbRequest( Reference ); @@ -123,7 +123,7 @@ impl DbRequestSharedMethods for DbRequest {} /// Receives `DbBlockedEvent` and `DbVersionChangeEvent` as well as events received by `DbRequest`. /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbOpenDBRequest) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "DbOpenDBRequest")] +#[reference(instance_of = "IDBOpenDBRequest")] #[reference(subclass_of(EventTarget))] pub struct DbOpenDBRequest( Reference ); @@ -145,7 +145,7 @@ impl DbOpenDBRequest { /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbFactory) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "DbFactory")] +#[reference(instance_of = "IDBFactory")] pub struct DbFactory( Reference ); impl DbFactory { @@ -421,7 +421,7 @@ pub trait DbCursorSharedMethods: AsRef< Reference > { /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "DbCursor")] +#[reference(instance_of = "IDBCursor")] pub struct DbCursor( Reference ); impl DbCursorSharedMethods for DbCursor {} @@ -432,7 +432,7 @@ impl DbCursorSharedMethods for DbCursor {} /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursorWithValue) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "DbCursorWithValue")] +#[reference(instance_of = "IDBCursorWithValue")] pub struct DbCursorWithValue( Reference ); impl DbCursorSharedMethods for DbCursorWithValue {} @@ -457,7 +457,7 @@ impl DbCursorWithValue { /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "DbKeyRange")] +#[reference(instance_of = "IDBKeyRange")] pub struct DbKeyRange( Reference ); impl DbKeyRange { @@ -749,7 +749,7 @@ pub trait DbObjectStoreIndexSharedMethods: AsRef< Reference > { /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "DbIndex")] +#[reference(instance_of = "IDBIndex")] pub struct DbIndex( Reference ); impl DbObjectStoreIndexSharedMethods for DbIndex {} @@ -799,7 +799,7 @@ error_enum_boilerplate! { /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "DbObjectStore")] +#[reference(instance_of = "IDBObjectStore")] pub struct DbObjectStore( Reference ); impl DbObjectStoreIndexSharedMethods for DbObjectStore {} @@ -968,7 +968,7 @@ error_enum_boilerplate! { /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "DbTransaction")] +#[reference(instance_of = "IDBTransaction")] pub struct DbTransaction( Reference ); impl IEventTarget for DbTransaction {} @@ -1070,7 +1070,7 @@ error_enum_boilerplate! { /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] -#[reference(instance_of = "DbDatabase")] +#[reference(instance_of = "IDBDatabase")] pub struct DbDatabase( Reference ); impl IEventTarget for DbDatabase {} From fddd754a0e1bd337a639fb4fb2d911e5d9a9dbf0 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:30:11 -0700 Subject: [PATCH 38/85] Add comment links to WebIDL errors --- src/webapi/dom_exception.rs | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/webapi/dom_exception.rs b/src/webapi/dom_exception.rs index 294c0e8d..f9524ef0 100644 --- a/src/webapi/dom_exception.rs +++ b/src/webapi/dom_exception.rs @@ -144,6 +144,7 @@ impl IDomException for InvalidPointerId {} error_boilerplate! { InvalidPointerId, dom_exception = "InvalidPointerId" } /// The cursor is currently being iterated or has iterated past its end. +// https://heycam.github.io/webidl/#transactioninactiveerror #[derive(Clone, Debug, ReferenceType)] #[reference(subclass_of(Error, DomException))] pub struct TransactionInactiveError( Reference ); @@ -154,6 +155,7 @@ impl IDomException for TransactionInactiveError {} error_boilerplate! { TransactionInactiveError, dom_exception = "TransactionInactiveError" } /// The key was not valid in the context it was used. +// https://heycam.github.io/webidl/#dataerror #[derive(Clone, Debug, ReferenceType)] #[reference(subclass_of(Error, DomException))] pub struct DataError( Reference ); @@ -164,6 +166,7 @@ impl IDomException for DataError {} error_boilerplate! { DataError, dom_exception = "DataError" } /// The transaction mode is read only. +// https://heycam.github.io/webidl/#readonlyerror #[derive(Clone, Debug, ReferenceType)] #[reference(subclass_of(Error, DomException))] pub struct ReadOnlyError( Reference ); @@ -174,6 +177,7 @@ impl IDomException for ReadOnlyError {} error_boilerplate! { ReadOnlyError, dom_exception = "ReadOnlyError" } /// The data being stored could not be cloned by the internal structured cloning algorithm. +// https://heycam.github.io/webidl/#datacloneerror #[derive(Clone, Debug, ReferenceType)] #[reference(subclass_of(Error, DomException))] pub struct DataCloneError( Reference ); @@ -184,6 +188,7 @@ impl IDomException for DataCloneError {} error_boilerplate! { DataCloneError, dom_exception = "DataCloneError" } /// An index or an object store already has this name +// https://heycam.github.io/webidl/#constrainterror #[derive(Clone, Debug, ReferenceType)] #[reference(subclass_of(Error, DomException))] pub struct ConstraintError( Reference ); From d7dacbd84de03d05a229f6af0c0442f958029906 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:30:58 -0700 Subject: [PATCH 39/85] Remove more dead code comments --- src/webapi/events/indexeddb.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/webapi/events/indexeddb.rs b/src/webapi/events/indexeddb.rs index 30321208..ebf50e73 100644 --- a/src/webapi/events/indexeddb.rs +++ b/src/webapi/events/indexeddb.rs @@ -1,8 +1,6 @@ use webcore::value::Reference; use webapi::event::{IEvent, Event, ConcreteEvent}; use webcore::try_from::TryInto; -//use webapi::event_target::{IEventTarget, EventTarget}; -//use webapi::node::{INode, Node}; /// The `DbSuccessEvent` handler is fired when a and Indexed DB request succeed. /// From 48da190358730603b0d206ebca8e0d8a7db68fd8 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:31:33 -0700 Subject: [PATCH 40/85] Remove IDL comments --- src/webapi/events/indexeddb.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/webapi/events/indexeddb.rs b/src/webapi/events/indexeddb.rs index ebf50e73..9c8ebb21 100644 --- a/src/webapi/events/indexeddb.rs +++ b/src/webapi/events/indexeddb.rs @@ -31,7 +31,6 @@ impl ConcreteEvent for DbVersionChangeEvent { } impl DbVersionChangeEvent { - // readonly attribute unsigned long long oldVersion; /// Returns the previous version of the database. pub fn old_version( &self ) -> u64 { js! ( @@ -39,7 +38,6 @@ impl DbVersionChangeEvent { ).try_into().unwrap() } - // readonly attribute unsigned long long? newVersion; /// Returns the new version of the database, or null if the database is being deleted. pub fn new_version( &self ) -> Option { js! ( From 21abe13ad46807537fabae68bfa2e8180e8d9af9 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:36:50 -0700 Subject: [PATCH 41/85] Add documentation for oncomplete/onerror handlers --- src/webapi/events/indexeddb.rs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/webapi/events/indexeddb.rs b/src/webapi/events/indexeddb.rs index 9c8ebb21..5593d378 100644 --- a/src/webapi/events/indexeddb.rs +++ b/src/webapi/events/indexeddb.rs @@ -47,7 +47,8 @@ impl DbVersionChangeEvent { } -/// +/// This event is fired when a transaction completes successfully. +/// https://www.w3.org/TR/IndexedDB/#transaction #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "Event")] #[reference(subclass_of(Event))] @@ -59,7 +60,8 @@ impl ConcreteEvent for DbCompleteEvent { const EVENT_TYPE: &'static str = "complete"; } -/// +/// This event is fired when a transaction errors. +/// https://www.w3.org/TR/IndexedDB/#transaction #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "Event")] #[reference(subclass_of(Event))] From c975d4aafc5ff3f0e2c150fe2aa780503b347198 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:39:18 -0700 Subject: [PATCH 42/85] Remove the None variant of DbRequestSource --- src/webapi/indexeddb.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index bee2ae97..baad752a 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -21,7 +21,6 @@ pub enum DbRequestReadyState { #[derive(Debug)] pub enum DbRequestSource { /// Indicates no source exists, such as when calling `indexedDB.open` - None, Store(DbObjectStore), Index(DbIndex), Cursor(DbCursor) @@ -58,14 +57,13 @@ pub trait DbRequestSharedMethods : IEventTarget { } else if (@{self.as_ref()}.source instanceof DbCursor) { return 2; } else { - return 3; + panic!() } }.try_into().unwrap(); match t { 0 => DbRequestSource::Store(js!(return @{self.as_ref()}.source;).try_into().unwrap()), 1 => DbRequestSource::Index(js!(return @{self.as_ref()}.source;).try_into().unwrap()), 2 => DbRequestSource::Cursor(js!(return @{self.as_ref()}.source;).try_into().unwrap()), - 3 => DbRequestSource::None, _ => panic!() } } From 220776cd2189aa997fbbdd1749cbeceffd3bdf67 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:41:50 -0700 Subject: [PATCH 43/85] Revert IDB -> Db change back to Db -> IDB, broke links --- examples/indexeddb/src/main.rs | 66 ++-- src/lib.rs | 40 +-- src/webapi/events/indexeddb.rs | 28 +- src/webapi/indexeddb.rs | 604 ++++++++++++++++----------------- src/webapi/window.rs | 4 +- 5 files changed, 371 insertions(+), 371 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index cdd43ce6..9a341299 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -24,23 +24,23 @@ use stdweb::web::html_element::InputElement; use stdweb::web::event::IEvent; use stdweb::web::event::{ - DbSuccessEvent, - DbVersionChangeEvent, - DbCompleteEvent, - DbErrorEvent, + IDBSuccessEvent, + IDBVersionChangeEvent, + IDBCompleteEvent, + IDBErrorEvent, SubmitEvent, ClickEvent }; use stdweb::web::indexeddb::{ - DbOpenDBRequest, - DbDatabase, - DbRequest, - DbRequestSharedMethods, - DbObjectStoreIndexSharedMethods, - DbCursorWithValue, - DbCursorSharedMethods, - DbTransactionMode + IDBOpenDBRequest, + IDBDatabase, + IDBRequest, + IDBRequestSharedMethods, + IDBObjectStoreIndexSharedMethods, + IDBCursorWithValue, + IDBCursorSharedMethods, + IDBTransactionMode }; use stdweb::unstable::TryInto; @@ -54,9 +54,9 @@ struct Note { js_serializable!( Note ); js_deserializable!( Note ); -thread_local!(static DB: RefCell> = RefCell::new(None)); +thread_local!(static DB: RefCell> = RefCell::new(None)); -fn display_data_inner(db: &DbDatabase) { +fn display_data_inner(db: &IDBDatabase) { let list = document().query_selector("ul").unwrap().unwrap(); // Here we empty the contents of the list element each time the display is updated // If you ddn't do this, you'd get duplicates listed each time a new note is added @@ -65,12 +65,12 @@ fn display_data_inner(db: &DbDatabase) { } // Open our object store and then get a cursor - which iterates through all the // different data items in the store - let object_store = db.transaction(vec!["notes"], DbTransactionMode::ReadOnly).object_store("notes").unwrap(); + let object_store = db.transaction(vec!["notes"], IDBTransactionMode::ReadOnly).object_store("notes").unwrap(); object_store.open_cursor(None, None).unwrap() - .add_event_listener( move |e: DbSuccessEvent| { + .add_event_listener( move |e: IDBSuccessEvent| { // Get a reference to the cursor - let db_request: DbRequest = e.target().unwrap().try_into().unwrap(); - let maybe_cursor: Result = db_request.result().unwrap().try_into(); + let db_request: IDBRequest = e.target().unwrap().try_into().unwrap(); + let maybe_cursor: Result = db_request.result().unwrap().try_into(); // If there is still another data item to iterate through, keep running this code if let Ok(cursor) = maybe_cursor { @@ -128,7 +128,7 @@ fn display_data() { // Define the deleteItem() function fn delete_item( e: ClickEvent ) { // retrieve the name of the task we want to delete. We need - // to convert it to a number before trying it use it with Db; Db key + // to convert it to a number before trying it use it with IDB; IDB key // values are type-sensitive. let button: Element = e.target().unwrap().try_into().unwrap(); let note: Element = button.parent_node().unwrap().try_into().unwrap(); @@ -137,12 +137,12 @@ fn delete_item( e: ClickEvent ) { // open a database transaction and delete the task, finding it using the id we retrieved above DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { - let transaction = db.transaction(vec!["notes"], DbTransactionMode::ReadWrite); + let transaction = db.transaction(vec!["notes"], IDBTransactionMode::ReadWrite); let object_store = transaction.object_store("notes").unwrap(); object_store.delete(note_id.try_into().unwrap()).unwrap(); // report that the data item has been deleted - transaction.add_event_listener( move |_e: DbCompleteEvent| { + transaction.add_event_listener( move |_e: IDBCompleteEvent| { // delete the parent of the button // which is the list item, so it is no longer displayed note.parent_node().unwrap().remove_child(¬e).unwrap(); @@ -167,32 +167,32 @@ fn main() { let request = window().indexed_db().open("notes", 1); // onerror handler signifies that the database didn't open successfully - request.add_event_listener( | _e: DbErrorEvent| { + request.add_event_listener( | _e: IDBErrorEvent| { js!( console.log("Database failed to open"); ); }); // onsuccess handler signifies that the database opened successfully - request.add_event_listener( move |event: DbSuccessEvent| { + request.add_event_listener( move |event: IDBSuccessEvent| { js!( console.log("Database opened succesfully"); ); - let db_request: DbOpenDBRequest = event.target().unwrap().try_into().unwrap(); + let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); // Store the opened database object in the db variable. This is used a lot below - let db : DbDatabase = db_request.database_result().unwrap(); + let db : IDBDatabase = db_request.database_result().unwrap(); DB.with(|db_cell| { db_cell.replace(Some(db)); }); - // Run the displayData() function to display the notes already in the Db + // Run the displayData() function to display the notes already in the IDB display_data(); }); - request.add_event_listener( |event: DbVersionChangeEvent| { - let db_request: DbOpenDBRequest = event.target().unwrap().try_into().unwrap(); - let db_: DbDatabase = db_request.result().unwrap().try_into().unwrap(); + request.add_event_listener( |event: IDBVersionChangeEvent| { + let db_request: IDBOpenDBRequest = event.target().unwrap().try_into().unwrap(); + let db_: IDBDatabase = db_request.result().unwrap().try_into().unwrap(); // Create an object_store to store our notes in (basically like a single table) let object_store = db_.create_object_store("notes", true, "").unwrap(); @@ -225,7 +225,7 @@ fn main() { DB.with(|db_cell| { if let Some(ref db) = *db_cell.borrow_mut() { // open a read/write db transaction, ready for adding the data - let transaction = db.transaction(vec!["notes"], DbTransactionMode::ReadWrite); + let transaction = db.transaction(vec!["notes"], IDBTransactionMode::ReadWrite); // call an object store that's already been added to the database let object_store = transaction.object_store("notes").unwrap(); @@ -233,21 +233,21 @@ fn main() { // Make a request to add our new_item object to the object store let request = object_store.add(new_item.try_into().unwrap(), None).unwrap(); - request.add_event_listener( move |_e: DbSuccessEvent| { + request.add_event_listener( move |_e: IDBSuccessEvent| { // Clear the form, ready for adding the next entry title_input.set_raw_value(""); body_input.set_raw_value(""); }); // Report on the success of the transaction completing, when everything is done - transaction.add_event_listener( |_e: DbCompleteEvent| { + transaction.add_event_listener( |_e: IDBCompleteEvent| { console!(log, "Transaction completed: database modification finished."); // update the display of data to show the newly added item, by running displayData() again. display_data(); }); - transaction.add_event_listener( |_e: DbErrorEvent| { + transaction.add_event_listener( |_e: IDBErrorEvent| { console!(log, "Transaction not opened due to error"); }); }}); diff --git a/src/lib.rs b/src/lib.rs index da4f6110..37404e0d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -226,22 +226,22 @@ pub mod web { /// A module containing the IndexedDB API pub mod indexeddb { pub use webapi::indexeddb::{ - DbOpenDBRequest, - DbDatabase, - DbRequestSharedMethods, - DbRequest, - DbIndex, - DbObjectStore, - DbTransaction, - DbTransactionMode, - DbFactory, - DbObjectStoreIndexSharedMethods, - DbCursorDirection, - DbRequestReadyState, - DbCursorSharedMethods, - DbCursor, - DbCursorWithValue, - DbAddError + IDBOpenDBRequest, + IDBDatabase, + IDBRequestSharedMethods, + IDBRequest, + IDBIndex, + IDBObjectStore, + IDBTransaction, + IDBTransactionMode, + IDBFactory, + IDBObjectStoreIndexSharedMethods, + IDBCursorDirection, + IDBRequestReadyState, + IDBCursorSharedMethods, + IDBCursor, + IDBCursorWithValue, + IDBAddError }; } @@ -444,10 +444,10 @@ pub mod web { }; pub use webapi::events::indexeddb:: { - DbSuccessEvent, - DbVersionChangeEvent, - DbCompleteEvent, - DbErrorEvent + IDBSuccessEvent, + IDBVersionChangeEvent, + IDBCompleteEvent, + IDBErrorEvent }; pub use webapi::events::gamepad::{ diff --git a/src/webapi/events/indexeddb.rs b/src/webapi/events/indexeddb.rs index 5593d378..74fa1aea 100644 --- a/src/webapi/events/indexeddb.rs +++ b/src/webapi/events/indexeddb.rs @@ -2,17 +2,17 @@ use webcore::value::Reference; use webapi::event::{IEvent, Event, ConcreteEvent}; use webcore::try_from::TryInto; -/// The `DbSuccessEvent` handler is fired when a and Indexed DB request succeed. +/// The `IDBSuccessEvent` handler is fired when a and Indexed DB request succeed. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/Events/success) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "Event")] #[reference(subclass_of(Event))] -pub struct DbSuccessEvent( Reference ); +pub struct IDBSuccessEvent( Reference ); -impl IEvent for DbSuccessEvent {} +impl IEvent for IDBSuccessEvent {} -impl ConcreteEvent for DbSuccessEvent { +impl ConcreteEvent for IDBSuccessEvent { const EVENT_TYPE: &'static str = "success"; } @@ -22,15 +22,15 @@ impl ConcreteEvent for DbSuccessEvent { #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "Event")] #[reference(subclass_of(Event))] -pub struct DbVersionChangeEvent( Reference ); +pub struct IDBVersionChangeEvent( Reference ); -impl IEvent for DbVersionChangeEvent {} +impl IEvent for IDBVersionChangeEvent {} -impl ConcreteEvent for DbVersionChangeEvent { +impl ConcreteEvent for IDBVersionChangeEvent { const EVENT_TYPE: &'static str = "upgradeneeded"; } -impl DbVersionChangeEvent { +impl IDBVersionChangeEvent { /// Returns the previous version of the database. pub fn old_version( &self ) -> u64 { js! ( @@ -52,11 +52,11 @@ impl DbVersionChangeEvent { #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "Event")] #[reference(subclass_of(Event))] -pub struct DbCompleteEvent( Reference ); +pub struct IDBCompleteEvent( Reference ); -impl IEvent for DbCompleteEvent {} +impl IEvent for IDBCompleteEvent {} -impl ConcreteEvent for DbCompleteEvent { +impl ConcreteEvent for IDBCompleteEvent { const EVENT_TYPE: &'static str = "complete"; } @@ -65,10 +65,10 @@ impl ConcreteEvent for DbCompleteEvent { #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "Event")] #[reference(subclass_of(Event))] -pub struct DbErrorEvent( Reference ); +pub struct IDBErrorEvent( Reference ); -impl IEvent for DbErrorEvent {} +impl IEvent for IDBErrorEvent {} -impl ConcreteEvent for DbErrorEvent { +impl ConcreteEvent for IDBErrorEvent { const EVENT_TYPE: &'static str = "error"; } diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index baad752a..262e7644 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -5,75 +5,75 @@ use webapi::dom_exception::{DomException, InvalidStateError, TransactionInactive use webapi::error::TypeError; use webapi::dom_string_list::DOMStringList; -/// Used to represent the state of an DbRequest. +/// Used to represent the state of an IDBRequest. /// -/// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/readyState) +/// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/readyState) #[derive(Debug)] -pub enum DbRequestReadyState { +pub enum IDBRequestReadyState { /// The request is pending. Pending, /// The request is done. Done } -/// Represents the different types the source arrtibute of an DbRequest +/// Represents the different types the source arrtibute of an IDBRequest /// can take. #[derive(Debug)] -pub enum DbRequestSource { +pub enum IDBRequestSource { /// Indicates no source exists, such as when calling `indexedDB.open` - Store(DbObjectStore), - Index(DbIndex), - Cursor(DbCursor) + Store(IDBObjectStore), + Index(IDBIndex), + Cursor(IDBCursor) } -/// DbRequestSharedMethode represents the methode that are shared between -/// DbOpenDBRequest and DbRequest. -pub trait DbRequestSharedMethods : IEventTarget { +/// IDBRequestSharedMethode represents the methode that are shared between +/// IDBOpenDBRequest and IDBRequest. +pub trait IDBRequestSharedMethods : IEventTarget { - /// The result read-only property of the `DbRequest` interface returns the result of the request, + /// The result read-only property of the `IDBRequest` interface returns the result of the request, /// or if the request failed InvalidStateError. /// - /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/result) + /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/result) fn result( &self ) -> Result { js_try!( return @{self.as_ref()}.result; ).unwrap() } /// Returns the error in the event of an unsuccessful request. /// - /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/error) + /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/error) fn error(&self) -> Option { js!( @{self.as_ref()}.error;).try_into().unwrap() } /// Returns the source of the request. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/source) - fn source( &self ) -> DbRequestSource { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/source) + fn source( &self ) -> IDBRequestSource { let t: i32 = js!{ - if (@{self.as_ref()}.source instanceof DbObjectStore) { + if (@{self.as_ref()}.source instanceof IDBObjectStore) { return 0; - } else if (@{self.as_ref()}.source instanceof DbIndex) { + } else if (@{self.as_ref()}.source instanceof IDBIndex) { return 1; - } else if (@{self.as_ref()}.source instanceof DbCursor) { + } else if (@{self.as_ref()}.source instanceof IDBCursor) { return 2; } else { panic!() } }.try_into().unwrap(); match t { - 0 => DbRequestSource::Store(js!(return @{self.as_ref()}.source;).try_into().unwrap()), - 1 => DbRequestSource::Index(js!(return @{self.as_ref()}.source;).try_into().unwrap()), - 2 => DbRequestSource::Cursor(js!(return @{self.as_ref()}.source;).try_into().unwrap()), + 0 => IDBRequestSource::Store(js!(return @{self.as_ref()}.source;).try_into().unwrap()), + 1 => IDBRequestSource::Index(js!(return @{self.as_ref()}.source;).try_into().unwrap()), + 2 => IDBRequestSource::Cursor(js!(return @{self.as_ref()}.source;).try_into().unwrap()), _ => panic!() } } - /// The `transaction` read-only property of the `DbRequest` interface + /// The `transaction` read-only property of the `IDBRequest` interface /// returns the transaction for the request, that is, the transaction /// the request is being made inside. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/transaction) - fn transaction( &self ) -> Option { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/transaction) + fn transaction( &self ) -> Option { let transaction : Value = js! ( return @{self.as_ref()}.transaction; ); @@ -84,54 +84,54 @@ pub trait DbRequestSharedMethods : IEventTarget { } } - /// The `ready_state` read-only property of the `DbRequest` interface + /// The `ready_state` read-only property of the `IDBRequest` interface /// returns the state of the request. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest/readyState) - fn ready_state( &self ) -> DbRequestReadyState { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/readyState) + fn ready_state( &self ) -> IDBRequestReadyState { let ready_state : String = js! ( return @{self.as_ref()}.readyState; ).try_into().unwrap(); if ready_state.eq("pending") { - return DbRequestReadyState::Pending; + return IDBRequestReadyState::Pending; } else if ready_state.eq("done") { - return DbRequestReadyState::Done; + return IDBRequestReadyState::Done; } else { - panic!("Got {} as an DbRequestReadyState.", ready_state); + panic!("Got {} as an IDBRequestReadyState.", ready_state); } } } -/// The `DbReques`t interface of the IndexedDB API provides access to results +/// The `IDBReques`t interface of the IndexedDB API provides access to results /// of asynchronous requests to databases and database objects using event -/// handlers. Events that are received are DbSuccessEvent and DbErrorEvent. +/// handlers. Events that are received are IDBSuccessEvent and IDBErrorEvent. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbRequest) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBRequest")] #[reference(subclass_of(EventTarget))] -pub struct DbRequest( Reference ); +pub struct IDBRequest( Reference ); -impl IEventTarget for DbRequest {} -impl DbRequestSharedMethods for DbRequest {} +impl IEventTarget for IDBRequest {} +impl IDBRequestSharedMethods for IDBRequest {} /// Provides access to the results of requests to open or delete databases. -/// Receives `DbBlockedEvent` and `DbVersionChangeEvent` as well as events received by `DbRequest`. -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbOpenDBRequest) +/// Receives `IDBBlockedEvent` and `IDBVersionChangeEvent` as well as events received by `IDBRequest`. +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBOpenDBRequest) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBOpenDBRequest")] #[reference(subclass_of(EventTarget))] -pub struct DbOpenDBRequest( Reference ); +pub struct IDBOpenDBRequest( Reference ); -impl IEventTarget for DbOpenDBRequest {} -impl DbRequestSharedMethods for DbOpenDBRequest {} +impl IEventTarget for IDBOpenDBRequest {} +impl IDBRequestSharedMethods for IDBOpenDBRequest {} -impl DbOpenDBRequest { +impl IDBOpenDBRequest { - /// Returns the value property as an `DbDatabase`, or an `InvalidStateError`. - pub fn database_result(&self) -> Result { + /// Returns the value property as an `IDBDatabase`, or an `InvalidStateError`. + pub fn database_result(&self) -> Result { match self.result() { Ok(value) => Ok(value.try_into().unwrap()), Err(error) => Err(error) @@ -139,21 +139,21 @@ impl DbOpenDBRequest { } } -/// The `DbFactory` interface of the IndexedDB API lets applications asynchronously access the indexed databases. The object that implements the interface is `window.indexedDB`. +/// The `IDBFactory` interface of the IndexedDB API lets applications asynchronously access the indexed databases. The object that implements the interface is `window.indexedDB`. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbFactory) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBFactory")] -pub struct DbFactory( Reference ); +pub struct IDBFactory( Reference ); -impl DbFactory { +impl IDBFactory { /// Requests opening a connection to a database. /// /// version can be None. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbFactory/open) - pub fn open>>( &self, name: &str, version: T) -> DbOpenDBRequest { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/open) + pub fn open>>( &self, name: &str, version: T) -> IDBOpenDBRequest { match version.into() { None => js! ( return @{self.as_ref()}.open(@{name}); @@ -168,8 +168,8 @@ impl DbFactory { /// Requests the deletion of a database. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbFactory/deleteDatabase) - pub fn delete_database( &self, name: &str) -> DbOpenDBRequest { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/deleteDatabase) + pub fn delete_database( &self, name: &str) -> IDBOpenDBRequest { js! ( return @{self.as_ref()}.deleteDatabase(@{name}); ).try_into().unwrap() @@ -177,7 +177,7 @@ impl DbFactory { /// Compares two values as keys to determine equality and ordering for `IndexedDB` operations. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbFactory/cmp) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/cmp) pub fn cmp( &self, first: Value, second: Value) -> i16 { js!( return @{self.as_ref()}.cmp(@{first.as_ref()}, @{second.as_ref()}); @@ -186,11 +186,11 @@ impl DbFactory { } -/// The DbCursorDirection enum indicates the direction in which a cursor is traversing the data. +/// The IDBCursorDirection enum indicates the direction in which a cursor is traversing the data. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/direction) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/direction) #[derive(Debug)] -pub enum DbCursorDirection { +pub enum IDBCursorDirection { /// This direction causes the cursor to be opened at the start of the source. Next, /// This direction causes the cursor to be opened at the start of the source. For every key with duplicate values, only the first record is yielded. @@ -201,42 +201,42 @@ pub enum DbCursorDirection { PrevUnique } -fn cursor_direction_to_string( direction: DbCursorDirection) -> String { +fn cursor_direction_to_string( direction: IDBCursorDirection) -> String { match direction { - DbCursorDirection::Next => "next".to_string(), - DbCursorDirection::NextUnique => "nextunique".to_string(), - DbCursorDirection::Prev => "prev".to_string(), - DbCursorDirection::PrevUnique => "prevunique".to_string() + IDBCursorDirection::Next => "next".to_string(), + IDBCursorDirection::NextUnique => "nextunique".to_string(), + IDBCursorDirection::Prev => "prev".to_string(), + IDBCursorDirection::PrevUnique => "prevunique".to_string() } } -fn string_to_cursor_direction( direction: &str) -> DbCursorDirection { +fn string_to_cursor_direction( direction: &str) -> IDBCursorDirection { if direction.eq("next") { - return DbCursorDirection::Next; + return IDBCursorDirection::Next; } else if direction.eq("nextunique") { - return DbCursorDirection::NextUnique; + return IDBCursorDirection::NextUnique; } else if direction.eq("prev") { - return DbCursorDirection::Prev; + return IDBCursorDirection::Prev; } else if direction.eq("prevunique") { - return DbCursorDirection::PrevUnique; + return IDBCursorDirection::PrevUnique; } else { unreachable!("Unknown index direction \"{}\".", direction); } } /// This enum is used to represent the vlaue of the soure property of -/// a `DbCursor`. +/// a `IDBCursor`. #[derive(Debug)] -pub enum DbCursorSource { - Store(DbObjectStore), - Index(DbIndex) +pub enum IDBCursorSource { + Store(IDBObjectStore), + Index(IDBIndex) } error_enum_boilerplate! { - /// An enum of the exceptions that DbCursorSharedMethods.advance() - /// and DbCursorSharedMethods.next may throw. - DbAdvanceError, - /// This DbCursor's transaction is inactive. + /// An enum of the exceptions that IDBCursorSharedMethods.advance() + /// and IDBCursorSharedMethods.next may throw. + IDBAdvanceError, + /// This IDBCursor's transaction is inactive. TransactionInactiveError, /// The value passed into the parameter was zero or a negative number. TypeError, @@ -245,8 +245,8 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - DbContinuePrimaryKeyError, - /// This DbCursor's transaction is inactive. + IDBContinuePrimaryKeyError, + /// This IDBCursor's transaction is inactive. TransactionInactiveError, /// The key parameter may have any of the following conditions: /// * The key is not a valid key. @@ -260,12 +260,12 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - DbUpdateError, - /// This DbCursor's transaction is inactive. + IDBUpdateError, + /// This IDBCursor's transaction is inactive. TransactionInactiveError, /// The transaction mode is read only. ReadOnlyError, - /// The cursor was created using DbIndex.openKeyCursor, is currently being iterated, or has iterated past its end. + /// The cursor was created using IDBIndex.openKeyCursor, is currently being iterated, or has iterated past its end. InvalidStateError, /// The underlying object store uses in-line keys and the property in the value at the object store's key path does not match the key in this cursor's position. DataError, @@ -276,12 +276,12 @@ error_enum_boilerplate! { /// error_enum_boilerplate! { /// - DbAddError, - /// This DbCursor's transaction is inactive. + IDBAddError, + /// This IDBCursor's transaction is inactive. TransactionInactiveError, /// The transaction mode is read only. ReadOnlyError, - /// The cursor was created using DbIndex.openKeyCursor, is currently being iterated, or has iterated past its end. + /// The cursor was created using IDBIndex.openKeyCursor, is currently being iterated, or has iterated past its end. InvalidStateError, /// The underlying object store uses in-line keys and the property in the value at the object store's key path does not match the key in this cursor's position. DataError, @@ -292,83 +292,83 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - DbCursorDeleteError, - /// This DbCursor's transaction is inactive. + IDBCursorDeleteError, + /// This IDBCursor's transaction is inactive. TransactionInactiveError, /// The transaction mode is read-only. ReadOnlyError, - /// The cursor was created using Dbindex.openKeyCursor, is currently being iterated, or has iterated past its end. + /// The cursor was created using IDBindex.openKeyCursor, is currently being iterated, or has iterated past its end. InvalidStateError } error_enum_boilerplate! { - DbClearError, + IDBClearError, /// The transaction associated with this operation is in read-only mode. ReadOnlyError, - /// This DbObjectStore's transaction is inactive. + /// This IDBObjectStore's transaction is inactive. TransactionInactiveError } /// This trait implements all the methods that are shared between -/// `DbCursor` and `DbCursorWithValue`. -pub trait DbCursorSharedMethods: AsRef< Reference > { +/// `IDBCursor` and `IDBCursorWithValue`. +pub trait IDBCursorSharedMethods: AsRef< Reference > { - /// The source read-only property of the `DbCursor` interface returns - /// the `DbObjectStore` or `DbIndex` that the cursor is iterating over. - /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/source) - fn source( &self ) -> DbCursorSource { - if js!( return @{self.as_ref()}.source instanceof DbObjectStore; ).try_into().unwrap() { - DbCursorSource::Store(js!( return @{self.as_ref()}.source ).try_into().unwrap()) - } else if js!( return @{self.as_ref()}.source instanceof DbIndex;).try_into().unwrap() { - DbCursorSource::Index(js!( return @{self.as_ref()}.source ).try_into().unwrap()) + /// The source read-only property of the `IDBCursor` interface returns + /// the `IDBObjectStore` or `IDBIndex` that the cursor is iterating over. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/source) + fn source( &self ) -> IDBCursorSource { + if js!( return @{self.as_ref()}.source instanceof IDBObjectStore; ).try_into().unwrap() { + IDBCursorSource::Store(js!( return @{self.as_ref()}.source ).try_into().unwrap()) + } else if js!( return @{self.as_ref()}.source instanceof IDBIndex;).try_into().unwrap() { + IDBCursorSource::Index(js!( return @{self.as_ref()}.source ).try_into().unwrap()) } else { panic!() } } - /// The `direction` read-only property of the `DbCursor` interface is + /// The `direction` read-only property of the `IDBCursor` interface is /// an enum that represents the direction of traversal of the - /// cursor (set using `DbObjectStore.openCursor` for example). + /// cursor (set using `IDBObjectStore.openCursor` for example). /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/direction) - fn direction( &self ) -> DbCursorDirection { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/direction) + fn direction( &self ) -> IDBCursorDirection { let direction: String = js! ( return @{self.as_ref()}.direction; ).try_into().unwrap(); return string_to_cursor_direction(&direction); } - /// The `key` read-only property of the `DbCursor` interface returns the key + /// The `key` read-only property of the `IDBCursor` interface returns the key /// for the record at the cursor's position. If the cursor is outside its range, /// this is set to undefined. The cursor's key can be any data type. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/key) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/key) fn key( &self ) -> Value { js!( return @{self.as_ref()}.key; ) .try_into().unwrap() } - /// The `primary_key` read-only property of the `DbCursor` interface returns + /// The `primary_key` read-only property of the `IDBCursor` interface returns /// the cursor's current effective key. If the cursor is currently being /// iterated or has iterated outside its range, this is set to undefined. ///The cursor's primary key can be any data type. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/primaryKey) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/primaryKey) fn primary_key( &self ) -> Value { js!( return @{self.as_ref()}.primaryKey; ) .try_into().unwrap() } - /// The advance() method of the DbCursor interface sets the number of times + /// The advance() method of the IDBCursor interface sets the number of times /// a cursor should move its position forward. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/advance) - fn advance( &self, count: u32) -> Result<(), DbAdvanceError> { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/advance) + fn advance( &self, count: u32) -> Result<(), IDBAdvanceError> { js_try!( @{self.as_ref()}.advance(@{count}); ).unwrap() } - /// The next() method of the DbCursor interface advances the cursor to the + /// The next() method of the IDBCursor interface advances the cursor to the /// next position along its direction, to the item whose key matches the optional /// key parameter. If no key (None) is specified, the cursor advances to the immediate /// next position, based on its direction. @@ -376,70 +376,70 @@ pub trait DbCursorSharedMethods: AsRef< Reference > { /// This function stands in for continue in the javascript interface. Continue /// is a keyword in rust and so needed to be renamed. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/continue) - fn next>>( &self, key: K) -> Result<(), DbAdvanceError> { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/continue) + fn next>>( &self, key: K) -> Result<(), IDBAdvanceError> { match key.into() { None => js_try!( @{self.as_ref()}.continue(); ).unwrap(), Some(key) => js_try! ( @{self.as_ref()}.continue(@{key.as_ref()}); ).unwrap() } } - /// The continuePrimaryKey() method of the DbCursor interface advances + /// The continuePrimaryKey() method of the IDBCursor interface advances /// the cursor to the to the item whose key matches the key parameter as /// well as whose primary key matches the primary key parameter. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/continuePrimaryKey) - fn continue_primary_key( &self, key: Value, primary_key: Value) -> Result<(), DbContinuePrimaryKeyError> { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/continuePrimaryKey) + fn continue_primary_key( &self, key: Value, primary_key: Value) -> Result<(), IDBContinuePrimaryKeyError> { js_try!( @{self.as_ref()}.continuePrimaryKey(@{key}, @{primary_key}); ).unwrap() } - /// The update() method of the DbCursor interface returns an DbRequest + /// The update() method of the IDBCursor interface returns an IDBRequest /// object, and, in a separate thread, updates the value at the current /// position of the cursor in the object store. If the cursor points to /// a record that has just been deleted, a new record is created. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/update) - fn update( &self, value: Value) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/update) + fn update( &self, value: Value) -> Result { js_try!( return @{self.as_ref()}.update(@{value.as_ref()}); ).unwrap() } - /// The delete() method of the DbCursor interface returns an DbRequest + /// The delete() method of the IDBCursor interface returns an IDBRequest /// object, and, in a separate thread, deletes the record at the cursor's /// position, without changing the cursor's position. Once the record is /// deleted, the cursor's value is set to null. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor/delete) - fn delete( &self ) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/delete) + fn delete( &self ) -> Result { js_try!( return @{self.as_ref()}.delete(); ).unwrap() } } -/// The DbCursor interface of the IndexedDB API represents a cursor for +/// The IDBCursor interface of the IndexedDB API represents a cursor for /// traversing or iterating over multiple records in a database. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursor) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBCursor")] -pub struct DbCursor( Reference ); +pub struct IDBCursor( Reference ); -impl DbCursorSharedMethods for DbCursor {} +impl IDBCursorSharedMethods for IDBCursor {} -/// The DbCursorWithValue interface of the IndexedDB API represents a cursor +/// The IDBCursorWithValue interface of the IndexedDB API represents a cursor /// for traversing or iterating over multiple records in a database. It is -/// the same as the DbCursor, except that it includes the value property. +/// the same as the IDBCursor, except that it includes the value property. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursorWithValue) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursorWithValue) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBCursorWithValue")] -pub struct DbCursorWithValue( Reference ); +pub struct IDBCursorWithValue( Reference ); -impl DbCursorSharedMethods for DbCursorWithValue {} +impl IDBCursorSharedMethods for IDBCursorWithValue {} -impl DbCursorWithValue { +impl IDBCursorWithValue { /// Returns the value of the current cursor. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbCursorWithValue/value) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursorWithValue/value) pub fn value( &self ) -> Value { js! ( return @{self}.value @@ -447,105 +447,105 @@ impl DbCursorWithValue { } } -/// The DbKeyRange interface of the IndexedDB API represents a continuous interval +/// The IDBKeyRange interface of the IndexedDB API represents a continuous interval /// over some data type that is used for keys. Records can be retrieved from -/// DbObjectStore and DbIndex objects using keys or a range of keys. You can limit +/// IDBObjectStore and IDBIndex objects using keys or a range of keys. You can limit /// the range using lower and upper bounds. For example, you can iterate over all /// values of a key in the value range A–Z. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBKeyRange")] -pub struct DbKeyRange( Reference ); +pub struct IDBKeyRange( Reference ); -impl DbKeyRange { +impl IDBKeyRange { // Static construction methods: - /// The only() method of the DbKeyRange interface creates a new key range + /// The only() method of the IDBKeyRange interface creates a new key range /// containing a single value. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/only) - pub fn only( value: Value ) -> Result { - js_try! ( return DbKeyRange.only(@{value}); ).unwrap() + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/only) + pub fn only( value: Value ) -> Result { + js_try! ( return IDBKeyRange.only(@{value}); ).unwrap() } - /// The lower_bound() method of the DbKeyRange interface creates a new key range + /// The lower_bound() method of the IDBKeyRange interface creates a new key range /// with only a lower bound. if open is false it includes the lower endpoint /// value and is closed. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/lowerBound) - pub fn lower_bound( lower: Value, open: bool ) -> Result { - js_try! ( return DbKeyRange.lowerBound(@{lower}, @{open}); ).unwrap() + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/lowerBound) + pub fn lower_bound( lower: Value, open: bool ) -> Result { + js_try! ( return IDBKeyRange.lowerBound(@{lower}, @{open}); ).unwrap() } - /// The upper_bound() method of the DbKeyRange interface creates a new key range + /// The upper_bound() method of the IDBKeyRange interface creates a new key range /// with only an apper bound. if open is false it includes the upper endpoint /// value and is closed. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/upperBound) - pub fn upper_bound( upper: Value, open: bool ) -> Result { - js_try! ( return DbKeyRange.upperBound(@{upper}, @{open}); ).unwrap() + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/upperBound) + pub fn upper_bound( upper: Value, open: bool ) -> Result { + js_try! ( return IDBKeyRange.upperBound(@{upper}, @{open}); ).unwrap() } - /// The bound() method of the DbKeyRange interface creates a new key range + /// The bound() method of the IDBKeyRange interface creates a new key range /// with the specified upper and lower bounds. The bounds can be open (that /// is, the bounds exclude the endpoint values) or closed (that is, the bounds /// include the endpoint values). /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/bound) - pub fn bound (lower: Value, upper: Value, lower_open: bool, upper_open: bool) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/bound) + pub fn bound (lower: Value, upper: Value, lower_open: bool, upper_open: bool) -> Result { js_try! ( - return DbKeyRange.boundound(@{lower}, @{upper}, @{lower_open}, @{upper_open}); + return IDBKeyRange.boundound(@{lower}, @{upper}, @{lower_open}, @{upper_open}); ).unwrap() } /// Lower bound of the key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/lower) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/lower) pub fn lower( &self ) -> Value { js!( return @{self}.lower; ).try_into().unwrap() } /// Upper bound of the key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/upper) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/upper) pub fn upper( &self ) -> Value { js!( return @{self}.upper; ).try_into().unwrap() } /// Returns false if the lower-bound value is included in the key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/lowerOpen) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/lowerOpen) pub fn lower_open( &self ) -> bool { js!( return @{self}.lowerOpen; ).try_into().unwrap() } /// Returns false if the upper-bound value is included in the key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/upperOpen) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/upperOpen) pub fn upper_open( &self ) -> bool { js!( return @{self}.upperOpen; ).try_into().unwrap() } - /// The includes() method of the DbKeyRange interface returns a boolean + /// The includes() method of the IDBKeyRange interface returns a boolean /// indicating whether a specified key is inside the key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbKeyRange/includes) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange/includes) pub fn includes( &self, value: Value ) -> Result { js_try! ( return @{self}.includes(@{value}); ).unwrap() } } #[derive(Debug)] -pub enum DbKeyOrKeyRange { +pub enum IDBKeyOrKeyRange { None, Value(Value), - Range(DbKeyRange) + Range(IDBKeyRange) } error_enum_boilerplate! { - DbSetNameError, + IDBSetNameError, /// The index, or its object store, has been deleted; or the current transaction /// is not an upgrade transaction. You can only rename indexes during upgrade @@ -562,20 +562,20 @@ error_enum_boilerplate! { error_enum_boilerplate! { /// This Error is raised by various methods ised to query object stores /// and indexes. - DbQueryError, + IDBQueryError, - /// This DbIndex's transaction is inactive. + /// This IDBIndex's transaction is inactive. TransactionInactiveError, /// The key or key range provided contains an invalid key. DataError, - /// The DbIndex has been deleted or removed. + /// The IDBIndex has been deleted or removed. InvalidStateError } error_enum_boilerplate! { - DbIndexError, + IDBIndexError, /// The source object store has been deleted, or the transaction for the object store has finished. InvalidStateError, /// There is no index with the given name (case-sensitive) in the database. @@ -583,12 +583,12 @@ error_enum_boilerplate! { } -/// This trait contains mothods that are Identicle in both DbIndex DbObjectStore -pub trait DbObjectStoreIndexSharedMethods: AsRef< Reference > { +/// This trait contains mothods that are Identicle in both IDBIndex IDBObjectStore +pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// Returns the name of this index or object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/name) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/name) fn name( &self ) -> String { js! ( return @{self.as_ref()}.name; @@ -597,13 +597,13 @@ pub trait DbObjectStoreIndexSharedMethods: AsRef< Reference > { /// Returns the name of this index or object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/name) - fn set_name( &self, name: &str) -> Result<(), DbSetNameError> { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/name) + fn set_name( &self, name: &str) -> Result<(), IDBSetNameError> { js_try! ( @{self.as_ref()}.name = @{name}; ).unwrap() } - /// The key_path read-only property of the DbObjectStore interface returns the - /// key path of this object store. Or in the case of an DbIndex, the current + /// The key_path read-only property of the IDBObjectStore interface returns the + /// key path of this object store. Or in the case of an IDBIndex, the current /// object store. fn key_path( &self ) -> Value { js!( return @{self.as_ref()}.keyPath; ).try_into().unwrap() @@ -611,34 +611,34 @@ pub trait DbObjectStoreIndexSharedMethods: AsRef< Reference > { /// This is for retrieving specific records from an object store or index. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/get) - fn get>( &self, query: Q) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/get) + fn get>( &self, query: Q) -> Result { match query.into() { - DbKeyOrKeyRange::None => js_try! ( + IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.get(); ), - DbKeyOrKeyRange::Value(value) => js_try! ( + IDBKeyOrKeyRange::Value(value) => js_try! ( return @{self.as_ref()}.get(@{value.as_ref()}); ), - DbKeyOrKeyRange::Range(range) => js_try! ( + IDBKeyOrKeyRange::Range(range) => js_try! ( return @{self.as_ref()}.get(@{range.as_ref()}); ) }.unwrap() } - /// Returns an DbRequest object, and, in a separate thread retrieves and + /// Returns an IDBRequest object, and, in a separate thread retrieves and /// returns the record key for the object matching the specified parameter. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/getKey) - fn get_key>( &self, query: Q) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getKey) + fn get_key>( &self, query: Q) -> Result { match query.into() { - DbKeyOrKeyRange::None => js_try! ( + IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getKey(); ), - DbKeyOrKeyRange::Value(value) => js_try! ( + IDBKeyOrKeyRange::Value(value) => js_try! ( return @{self.as_ref()}.getKey(@{value.as_ref()}); ), - DbKeyOrKeyRange::Range(range) => js_try! ( + IDBKeyOrKeyRange::Range(range) => js_try! ( return @{self.as_ref()}.getKey(@{range.as_ref()}); ) }.unwrap() @@ -647,17 +647,17 @@ pub trait DbObjectStoreIndexSharedMethods: AsRef< Reference > { /// The get_ll() method retrieves all objects that are inside the index or /// object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/getAll) - fn get_all, C: Into>>( &self, query: Q, count: C) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/getAll) + fn get_all, C: Into>>( &self, query: Q, count: C) -> Result { match query.into() { - DbKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAll(); ), - DbKeyOrKeyRange::Value(value) => { + IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAll(); ), + IDBKeyOrKeyRange::Value(value) => { match count.into() { None => js_try! ( return @{self.as_ref()}.getAll(@{value.as_ref()}); ), Some(count) => js_try! ( return @{self.as_ref()}.getAll(@{value.as_ref()}, @{count}); ) } }, - DbKeyOrKeyRange::Range(range) => { + IDBKeyOrKeyRange::Range(range) => { match count.into() { None => js_try! ( return @{self.as_ref()}.getAll(@{range.as_ref()}); ), Some(count) => js_try! ( return @{self.as_ref()}.getAll(@{range.as_ref()}, @{count}); ) @@ -666,23 +666,23 @@ pub trait DbObjectStoreIndexSharedMethods: AsRef< Reference > { }.unwrap() } - // Acording to the mozilla documentation the DbIndex version does not + // Acording to the mozilla documentation the IDBIndex version does not // Throw DataError. - /// The get_all_keys() method returns an DbRequest object retrieves record keys + /// The get_all_keys() method returns an IDBRequest object retrieves record keys /// for all objects matching the specified parameter or all objects if no /// parameters are given. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/getAllKeys) - fn get_all_keys, C: Into>>( &self, query: Q, count: C) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/getAllKeys) + fn get_all_keys, C: Into>>( &self, query: Q, count: C) -> Result { match query.into() { - DbKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAllKeys(); ), - DbKeyOrKeyRange::Value(value) => { + IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAllKeys(); ), + IDBKeyOrKeyRange::Value(value) => { match count.into() { None => js_try! ( return @{self.as_ref()}.getAllKeys(@{value.as_ref()}); ), Some(count) => js_try! ( return @{self.as_ref()}.getAllKeys(@{value.as_ref()}, @{count}); ) } }, - DbKeyOrKeyRange::Range(range) => { + IDBKeyOrKeyRange::Range(range) => { match count.into() { None => js_try! ( return @{self.as_ref()}.getAllKeys(@{range.as_ref()}); ), Some(count) => js_try! ( return @{self.as_ref()}.getAllKeys(@{range.as_ref()}, @{count}); ) @@ -691,28 +691,28 @@ pub trait DbObjectStoreIndexSharedMethods: AsRef< Reference > { }.unwrap() } - /// Returns an DbRequest object, and, in a separate thread, returns the total number of records that match the provided key or DbKeyRange + /// Returns an IDBRequest object, and, in a separate thread, returns the total number of records that match the provided key or IDBKeyRange /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/count) - fn count>( &self, query: Q) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/count) + fn count>( &self, query: Q) -> Result { match query.into() { - DbKeyOrKeyRange::None => js_try! ( + IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.count(); ), - DbKeyOrKeyRange::Value(value) => js_try! ( + IDBKeyOrKeyRange::Value(value) => js_try! ( return @{self.as_ref()}.count(@{value.as_ref()}); ), - DbKeyOrKeyRange::Range(range) => js_try! ( + IDBKeyOrKeyRange::Range(range) => js_try! ( return @{self.as_ref()}.count(@{range.as_ref()}); ) }.unwrap() } - /// The open_cursor() method returns an DbRequest object, and, in a separate + /// The open_cursor() method returns an IDBRequest object, and, in a separate /// thread, creates a cursor over the specified key range. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/openCursor) - fn open_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openCursor) + fn open_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { match range.into() { None => js_try! ( return @{self.as_ref()}.openCursor(); ), Some(range) => { @@ -724,12 +724,12 @@ pub trait DbObjectStoreIndexSharedMethods: AsRef< Reference > { }.unwrap() } - /// The open_key_cursor() method returns an DbRequest object, and, in a + /// The open_key_cursor() method returns an IDBRequest object, and, in a /// separate thread, creates a cursor over the specified key range, as arranged /// by this index. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/openKeyCursor) - fn open_key_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openKeyCursor) + fn open_key_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { match range.into() { None => js_try! ( return @{self.as_ref()}.openKeyCursor(); ), Some(range) => { @@ -745,25 +745,25 @@ pub trait DbObjectStoreIndexSharedMethods: AsRef< Reference > { /// Provides asynchronous access to an index in a database. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBIndex")] -pub struct DbIndex( Reference ); +pub struct IDBIndex( Reference ); -impl DbObjectStoreIndexSharedMethods for DbIndex {} +impl IDBObjectStoreIndexSharedMethods for IDBIndex {} -impl DbIndex { +impl IDBIndex { - /// The object_store property of the DbIndex interface returns the name of the object store referenced by the current index. + /// The object_store property of the IDBIndex interface returns the name of the object store referenced by the current index. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/objectStore) - pub fn object_store( &self ) -> DbObjectStore { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/objectStore) + pub fn object_store( &self ) -> IDBObjectStore { js! ( return @{self.as_ref()}.objectStore ).try_into().unwrap() } /// Affects how the index behaves when the result of evaluating the index's key path yields an array. If `true`, there is one record in the index for each item in an array of keys. If `false`, then there is one record for each key that is an array. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/multiEntry) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/multiEntry) pub fn multi_entry( &self ) -> bool { js! ( return @{self.as_ref()}.multiEntry; @@ -772,7 +772,7 @@ impl DbIndex { /// If `true`, this index does not allow duplicate values for a key. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbIndex/unique) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/unique) pub fn unique( &self ) -> bool { js! ( return @{self.as_ref()}.unique; @@ -782,7 +782,7 @@ impl DbIndex { } error_enum_boilerplate! { - DbObjectStoreDeleteError, + IDBObjectStoreDeleteError, /// This object store's transaction is inactive. TransactionInactiveError, /// The object store's transaction mode is read-only. @@ -793,29 +793,29 @@ error_enum_boilerplate! { DataError } -/// The `DbObjectStore` interface of the IndexedDB API represents an object store in a database +/// The `IDBObjectStore` interface of the IndexedDB API represents an object store in a database /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBObjectStore")] -pub struct DbObjectStore( Reference ); +pub struct IDBObjectStore( Reference ); -impl DbObjectStoreIndexSharedMethods for DbObjectStore {} +impl IDBObjectStoreIndexSharedMethods for IDBObjectStore {} -impl DbObjectStore { +impl IDBObjectStore { - /// The index_names read-only property of the `DbObjectStore` interface returns a list of th + /// The index_names read-only property of the `IDBObjectStore` interface returns a list of th /// names of indexes on objects in this object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/indexNames) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/indexNames) pub fn index_names( &self ) -> DOMStringList { js! ( return @{self}.indexNames ).try_into().unwrap() } - /// The `DbTransaction` object to which this object store belongs. + /// The `IDBTransaction` object to which this object store belongs. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/transaction) - pub fn transaction( &self ) -> DbTransaction { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/transaction) + pub fn transaction( &self ) -> IDBTransaction { js! ( return @{self.as_ref()}.transaction; ).try_into().unwrap() @@ -823,7 +823,7 @@ impl DbObjectStore { /// Returns the value of the auto increment flag for this object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/autoIncrement) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/autoIncrement) pub fn auto_increment( &self ) -> bool { js! ( return @{self.as_ref()}.autoIncrement; @@ -833,8 +833,8 @@ impl DbObjectStore { /// Updates a given record in a database, or inserts a new record if the given item does not already exist. /// The key is only needed if /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/put) - pub fn put>>( &self, value: Value, key: T) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/put) + pub fn put>>( &self, value: Value, key: T) -> Result { match key.into() { None => js_try! ( return @{self.as_ref()}.put(@{value.as_ref()}); @@ -845,10 +845,10 @@ impl DbObjectStore { }.unwrap() } - /// Returns an `DbRequest` object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store. + /// Returns an `IDBRequest` object, and, in a separate thread, creates a structured clone of the value, and stores the cloned value in the object store. This is for adding new records to an object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/add) - pub fn add>>( &self, value: Value, key: T) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/add) + pub fn add>>( &self, value: Value, key: T) -> Result { match key.into() { None => js_try! ( return @{self.as_ref()}.add(@{value.as_ref()}); @@ -859,19 +859,19 @@ impl DbObjectStore { }.unwrap() } - /// returns an `DbRequest` object, and, in a separate thread, deletes the specified record or records. + /// returns an `IDBRequest` object, and, in a separate thread, deletes the specified record or records. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/delete) - pub fn delete( &self, query: Value) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/delete) + pub fn delete( &self, query: Value) -> Result { js_try! ( return @{self.as_ref()}.delete(@{query.as_ref()}); ).unwrap() } - /// Returns an DbRequest object, and clears this object store in a separate thread + /// Returns an IDBRequest object, and clears this object store in a separate thread /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/clear) - pub fn clear( &self ) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/clear) + pub fn clear( &self ) -> Result { js_try! ( return @{self.as_ref()}.clear(); ).unwrap() @@ -879,21 +879,21 @@ impl DbObjectStore { /// opens a named index in the current object store /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/index) - pub fn index( &self, name: &str) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/index) + pub fn index( &self, name: &str) -> Result { js_try! ( return @{self.as_ref()}.index(@{name}); ).unwrap() } - // [NewObject] DbIndex createIndex(DOMString name, (DOMString or sequence) keyPath, optional DbIndexParameters options); - /// Creates and returns a new `DbIndex` object in the connected database. + // [NewObject] IDBIndex createIndex(DOMString name, (DOMString or sequence) keyPath, optional IDBIndexParameters options); + /// Creates and returns a new `IDBIndex` object in the connected database. /// /// Note that this method must be called only from a VersionChange /// transaction mode callback. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/createIndex) - pub fn create_index( &self, name: &str, key_path: &str, options: Value) -> DbIndex { // TODO, how am I doing the optinal options? + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/createIndex) + pub fn create_index( &self, name: &str, key_path: &str, options: Value) -> IDBIndex { // TODO, how am I doing the optinal options? js! ( return @{self.as_ref()}.createIndex(@{name}, @{key_path}, @{options.as_ref()}); ).try_into().unwrap() @@ -901,7 +901,7 @@ impl DbObjectStore { /// Destroys the index with the specified name in the connected database, used during a version upgrade. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbObjectStore/deleteIndex) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/deleteIndex) pub fn delete_index( &self, name: &str) { js! { return @{self.as_ref()}.deleteIndex(@{name}); @@ -909,51 +909,51 @@ impl DbObjectStore { } } -/* dictionary DbIndexParameters { +/* dictionary IDBIndexParameters { boolean unique = false; boolean multiEntry = false; };*/ -/// An DbTransactionMode object defining the mode for isolating access to +/// An IDBTransactionMode object defining the mode for isolating access to /// data in the current object stores. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/mode) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/mode) #[derive(Debug)] -pub enum DbTransactionMode { +pub enum IDBTransactionMode { /// Allows data to be read but not changed. ReadOnly, /// Allows reading and writing of data in existing data stores to be changed. ReadWrite, /// Allows any operation to be performed, including ones that delete and /// create object stores and indexes. This mode is for updating the version - /// number of transactions that were started using DbDatabase.set_version(). + /// number of transactions that were started using IDBDatabase.set_version(). /// Transactions of this mode cannot run concurrently with other transactions. /// Transactions in this mode are known as "upgrade transactions." VersionChange } -fn transaction_mode_to_string( mode: DbTransactionMode ) -> String { +fn transaction_mode_to_string( mode: IDBTransactionMode ) -> String { match mode { - DbTransactionMode::ReadOnly => "readonly".to_string(), - DbTransactionMode::ReadWrite => "readwrite".to_string(), - DbTransactionMode::VersionChange => "versionchange".to_string() + IDBTransactionMode::ReadOnly => "readonly".to_string(), + IDBTransactionMode::ReadWrite => "readwrite".to_string(), + IDBTransactionMode::VersionChange => "versionchange".to_string() } } -fn string_to_transaction_mode( mode: &str ) -> DbTransactionMode { +fn string_to_transaction_mode( mode: &str ) -> IDBTransactionMode { if mode.eq("readonly") { - return DbTransactionMode::ReadOnly; + return IDBTransactionMode::ReadOnly; } else if mode.eq("readwrite") { - return DbTransactionMode::ReadWrite; + return IDBTransactionMode::ReadWrite; } else if mode.eq("versionchange") { - return DbTransactionMode::VersionChange; + return IDBTransactionMode::VersionChange; } else { unreachable!("Unknown transaction mode \"{}\".", mode); } } error_enum_boilerplate! { - DbObjectStoreError, + IDBObjectStoreError, /// The requested object store is not in this transaction's scope. NotFoundError, @@ -962,67 +962,67 @@ error_enum_boilerplate! { InvalidStateError } -/// The `DbTransaction` interface of the IndexedDB API provides a static, asynchronous transaction on a database using event handlers. +/// The `IDBTransaction` interface of the IndexedDB API provides a static, asynchronous transaction on a database using event handlers. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBTransaction")] -pub struct DbTransaction( Reference ); +pub struct IDBTransaction( Reference ); -impl IEventTarget for DbTransaction {} +impl IEventTarget for IDBTransaction {} -impl DbTransaction { +impl IDBTransaction { - /// The object_store_names read-only property of the DbTransaction interface returns - /// a DOMStringList of names of DbObjectStore objects. + /// The object_store_names read-only property of the IDBTransaction interface returns + /// a DOMStringList of names of IDBObjectStore objects. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/objectStoreNames) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/objectStoreNames) pub fn object_store_names( &self ) -> DOMStringList { js! ( return @{self}.objectStoreNames ).try_into().unwrap() } - /// The mode read-only property of the `DbTransaction` interface returns the + /// The mode read-only property of the `IDBTransaction` interface returns the /// current mode for accessing the data in the object stores in the scope of the /// transaction (i.e. is the mode to be read-only, or do you want to write to /// the object stores?) The default value is readonly. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/mode - pub fn mode( &self ) -> DbTransactionMode { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/mode + pub fn mode( &self ) -> IDBTransactionMode { let mode: String = js!( return @{self}.mode; ).try_into().unwrap(); string_to_transaction_mode(&mode) } /// Returns the database connection with which this transaction is associated. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/db) - pub fn db( &self ) -> DbDatabase { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/db) + pub fn db( &self ) -> IDBDatabase { js! ( return @{self}.db(); ).try_into().unwrap() } - /// The DbTransaction.error property of the DbTransaction interface returns + /// The IDBTransaction.error property of the IDBTransaction interface returns /// one of several types of error when there is an unsuccessful transaction. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/error) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/error) pub fn error( &self ) -> Option { js!( return @{self}.error; ).try_into().unwrap() } - /// The object_store() method of the DbTransaction interface returns an object + /// The object_store() method of the IDBTransaction interface returns an object /// store that has already been added to the scope of this transaction. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/objectStore) - pub fn object_store( &self, name: &str) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/objectStore) + pub fn object_store( &self, name: &str) -> Result { js_try! ( return @{self.as_ref()}.objectStore(@{name}); ).unwrap() } - /// The abort() method of the DbTransaction interface rolls back all the + /// The abort() method of the IDBTransaction interface rolls back all the /// changes to objects in the database associated with this transaction. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbTransaction/abort) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBTransaction/abort) pub fn abort( &self ) -> Result<(), InvalidStateError> { js_try! ( @{self}.abort(); ).unwrap() } @@ -1030,7 +1030,7 @@ impl DbTransaction { } error_enum_boilerplate! { - DbCreateObjectStoreError, + IDBCreateObjectStoreError, /// Occurs if the method was not called from a versionchange transaction /// callback. For older WebKit browsers, you must call first. @@ -1050,7 +1050,7 @@ error_enum_boilerplate! { } error_enum_boilerplate! { - DbDeleteObjectStoreError, + IDBDeleteObjectStoreError, /// Occurs if the method was not called from a versionchange transaction callback. /// For older WebKit browsers, you must call first. @@ -1064,20 +1064,20 @@ error_enum_boilerplate! { NotFoundError } -/// The `DbDatabase` interface of the IndexedDB API provides a connection to a database. +/// The `IDBDatabase` interface of the IndexedDB API provides a connection to a database. /// -/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase) +/// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBDatabase")] -pub struct DbDatabase( Reference ); +pub struct IDBDatabase( Reference ); -impl IEventTarget for DbDatabase {} +impl IEventTarget for IDBDatabase {} -impl DbDatabase { +impl IDBDatabase { /// Returns the the name of the connected database. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/name) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/name) pub fn name( &self ) -> String { js! ( return @{self.as_ref()}.name; @@ -1086,28 +1086,28 @@ impl DbDatabase { /// Returns the version of the connected database. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/version) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/version) pub fn version( &self ) -> u64 { js! ( return @{self.as_ref()}.version; ).try_into().unwrap() } - /// The objectStoreNames read-only property of the DbDatabase interface is a + /// The objectStoreNames read-only property of the IDBDatabase interface is a /// DOMStringList containing a list of the names of the object stores currently /// in the connected database. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/objectStoreNames) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/objectStoreNames) pub fn object_store_names( &self ) -> DOMStringList { js! ( return @{self}.objectStoreNames ).try_into().unwrap() } - /// Immediately returns a transaction object (`DbTransaction`) containing - /// the `DbTransaction.object_store` method, which you can use to access + /// Immediately returns a transaction object (`IDBTransaction`) containing + /// the `IDBTransaction.object_store` method, which you can use to access /// your object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/transaction) - pub fn transaction( &self, store_names: Vec<&str>, mode: DbTransactionMode) -> DbTransaction { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/transaction) + pub fn transaction( &self, store_names: Vec<&str>, mode: IDBTransactionMode) -> IDBTransaction { js! ( return @{self.as_ref()}.transaction(@{store_names}, @{transaction_mode_to_string(mode)}); ).try_into().unwrap() @@ -1115,7 +1115,7 @@ impl DbDatabase { /// Returns immediately and closes the connection in a separate thread. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/close) + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/close) pub fn close( &self ) { js! { @{self.as_ref()}.close(); @@ -1124,8 +1124,8 @@ impl DbDatabase { /// Creates and returns a new object store. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/createObjectStore) - pub fn create_object_store( &self, name: &str, auto_increment: bool, key_path: &str) -> Result { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/createObjectStore) + pub fn create_object_store( &self, name: &str, auto_increment: bool, key_path: &str) -> Result { js_try! ( return @{self.as_ref()}.createObjectStore(@{name}, { autoIncrement: @{auto_increment}, key_path: @{key_path} } ); ).unwrap() @@ -1133,8 +1133,8 @@ impl DbDatabase { /// Destroys the object store with the given name. /// - /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/DbDatabase/deleteObjectStore) - pub fn delete_object_store( &self, name: &str ) -> Result<(), DbDeleteObjectStoreError> { + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBDatabase/deleteObjectStore) + pub fn delete_object_store( &self, name: &str ) -> Result<(), IDBDeleteObjectStoreError> { js_try! ( @{self.as_ref()}.deleteObjectStore(@{name}); ).unwrap() diff --git a/src/webapi/window.rs b/src/webapi/window.rs index 2445caf6..80d443cc 100644 --- a/src/webapi/window.rs +++ b/src/webapi/window.rs @@ -8,7 +8,7 @@ use webapi::history::History; use webapi::selection::Selection; use webcore::once::Once; use webcore::value::Value; -use webapi::indexeddb::DbFactory; +use webapi::indexeddb::IDBFactory; /// A handle to a pending animation frame request. @@ -136,7 +136,7 @@ impl Window { } /// This is a method - pub fn indexed_db( &self ) -> DbFactory { + pub fn indexed_db( &self ) -> IDBFactory { js! ( return window.indexedDB; ).try_into().unwrap() From f83cff3a4c45554a92d01f76db6977cdf246b588 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:42:52 -0700 Subject: [PATCH 44/85] Add link to specs IDBRequest --- src/webapi/indexeddb.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 262e7644..566dd506 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -28,6 +28,7 @@ pub enum IDBRequestSource { /// IDBRequestSharedMethode represents the methode that are shared between /// IDBOpenDBRequest and IDBRequest. +// https://w3c.github.io/IndexedDB/#idbrequest pub trait IDBRequestSharedMethods : IEventTarget { /// The result read-only property of the `IDBRequest` interface returns the result of the request, From 42438a56bb9053691d1ddef48bad5c92a18bc615 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:44:00 -0700 Subject: [PATCH 45/85] Add missing return to error --- src/webapi/indexeddb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 566dd506..62e211ce 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -43,7 +43,7 @@ pub trait IDBRequestSharedMethods : IEventTarget { /// /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/error) fn error(&self) -> Option { - js!( @{self.as_ref()}.error;).try_into().unwrap() + return js!( @{self.as_ref()}.error;).try_into().unwrap() } /// Returns the source of the request. From a392a39a47d6e1a309abfc932078c1e43474b652 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:44:22 -0700 Subject: [PATCH 46/85] Fix doubled whitespace after -> --- src/webapi/indexeddb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 62e211ce..f05b2556 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -42,7 +42,7 @@ pub trait IDBRequestSharedMethods : IEventTarget { /// Returns the error in the event of an unsuccessful request. /// /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/error) - fn error(&self) -> Option { + fn error(&self) -> Option { return js!( @{self.as_ref()}.error;).try_into().unwrap() } From d3db3d4239a50afc2629b5f26f46bc0e7792a9cf Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:46:28 -0700 Subject: [PATCH 47/85] Change source to return an Option --- src/webapi/indexeddb.rs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index f05b2556..87e8265a 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -49,7 +49,7 @@ pub trait IDBRequestSharedMethods : IEventTarget { /// Returns the source of the request. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/source) - fn source( &self ) -> IDBRequestSource { + fn source( &self ) -> Option { let t: i32 = js!{ if (@{self.as_ref()}.source instanceof IDBObjectStore) { return 0; @@ -62,10 +62,10 @@ pub trait IDBRequestSharedMethods : IEventTarget { } }.try_into().unwrap(); match t { - 0 => IDBRequestSource::Store(js!(return @{self.as_ref()}.source;).try_into().unwrap()), - 1 => IDBRequestSource::Index(js!(return @{self.as_ref()}.source;).try_into().unwrap()), - 2 => IDBRequestSource::Cursor(js!(return @{self.as_ref()}.source;).try_into().unwrap()), - _ => panic!() + 0 => Some(IDBRequestSource::Store(js!(return @{self.as_ref()}.source;).try_into().unwrap())), + 1 => Some(IDBRequestSource::Index(js!(return @{self.as_ref()}.source;).try_into().unwrap())), + 2 => Some(IDBRequestSource::Cursor(js!(return @{self.as_ref()}.source;).try_into().unwrap())), + _ => None } } From 454de219a4a4ff68051c447cbce6d4c176133eb6 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:46:50 -0700 Subject: [PATCH 48/85] Fix typo with backticks in IDBRequest --- src/webapi/indexeddb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 87e8265a..9660a1f8 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -105,7 +105,7 @@ pub trait IDBRequestSharedMethods : IEventTarget { } -/// The `IDBReques`t interface of the IndexedDB API provides access to results +/// The `IDBRequest` interface of the IndexedDB API provides access to results /// of asynchronous requests to databases and database objects using event /// handlers. Events that are received are IDBSuccessEvent and IDBErrorEvent. /// From 6ac1bcb84cc422f00a0bc2c391f99a366c71ce1d Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:51:14 -0700 Subject: [PATCH 49/85] Word-wrap comment --- src/webapi/indexeddb.rs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 9660a1f8..7e22632f 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -140,7 +140,9 @@ impl IDBOpenDBRequest { } } -/// The `IDBFactory` interface of the IndexedDB API lets applications asynchronously access the indexed databases. The object that implements the interface is `window.indexedDB`. +/// The `IDBFactory` interface of the IndexedDB API lets applications +/// asynchronously access the indexed databases. The object that +/// implements the interface is `window.indexedDB`. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory) #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] From 40f1aed88b17e2b8c5d2d38119fd2167ff3b2c2e Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:51:44 -0700 Subject: [PATCH 50/85] Add link to IDBFactory specs --- src/webapi/indexeddb.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 7e22632f..2c95ffde 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -145,6 +145,7 @@ impl IDBOpenDBRequest { /// implements the interface is `window.indexedDB`. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory) +// https://w3c.github.io/IndexedDB/#idbfactory #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBFactory")] pub struct IDBFactory( Reference ); From 5b08f18578970f3f3f750f72c99326e61b7f6119 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 16:55:24 -0700 Subject: [PATCH 51/85] Split database open() to open_with_version(), removing >> --- examples/indexeddb/src/main.rs | 2 +- src/webapi/indexeddb.rs | 24 ++++++++++++------------ 2 files changed, 13 insertions(+), 13 deletions(-) diff --git a/examples/indexeddb/src/main.rs b/examples/indexeddb/src/main.rs index 9a341299..ca262ade 100644 --- a/examples/indexeddb/src/main.rs +++ b/examples/indexeddb/src/main.rs @@ -164,7 +164,7 @@ fn main() { // Open our database; it is created if it doesn't already exist // (see onupgradeneeded below) - let request = window().indexed_db().open("notes", 1); + let request = window().indexed_db().open_with_version("notes", 1); // onerror handler signifies that the database didn't open successfully request.add_event_listener( | _e: IDBErrorEvent| { diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 2c95ffde..ad6cb1db 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -154,21 +154,21 @@ impl IDBFactory { /// Requests opening a connection to a database. /// - /// version can be None. - /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/open) - pub fn open>>( &self, name: &str, version: T) -> IDBOpenDBRequest { - match version.into() { - None => js! ( - return @{self.as_ref()}.open(@{name}); - ).try_into().unwrap(), - Some(version) => js! ( - return @{self.as_ref()}.open(@{name}, @{version}); - ).try_into().unwrap() - } + pub fn open( &self, name: &str) -> IDBOpenDBRequest { + js! ( + return @{self.as_ref()}.open(@{name}); + ).try_into().unwrap() } - + /// Requests opening a connection to a database with a schema version. + /// + /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBFactory/open) + pub fn open_with_version( &self, name: &str, version: u32) -> IDBOpenDBRequest { + js! ( + return @{self.as_ref()}.open(@{name}, @{version}); + ).try_into().unwrap() + } /// Requests the deletion of a database. /// From 6e94092ef98079cba7b4798570c4a94eb34c1b4e Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:01:42 -0700 Subject: [PATCH 52/85] Derive more for IDBCursorDirection --- src/webapi/indexeddb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index ad6cb1db..6a9ea68d 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -193,7 +193,7 @@ impl IDBFactory { /// The IDBCursorDirection enum indicates the direction in which a cursor is traversing the data. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/direction) -#[derive(Debug)] +#[derive(Debug, Copy, Clone, PartialEq, Eq)] pub enum IDBCursorDirection { /// This direction causes the cursor to be opened at the start of the source. Next, From b835ee537db0f88decc80d9cb80f82c37916b2b8 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:03:21 -0700 Subject: [PATCH 53/85] Use match instead of chained if/else --- src/webapi/indexeddb.rs | 16 ++++++---------- 1 file changed, 6 insertions(+), 10 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 6a9ea68d..d6c8be47 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -215,16 +215,12 @@ fn cursor_direction_to_string( direction: IDBCursorDirection) -> String { } fn string_to_cursor_direction( direction: &str) -> IDBCursorDirection { - if direction.eq("next") { - return IDBCursorDirection::Next; - } else if direction.eq("nextunique") { - return IDBCursorDirection::NextUnique; - } else if direction.eq("prev") { - return IDBCursorDirection::Prev; - } else if direction.eq("prevunique") { - return IDBCursorDirection::PrevUnique; - } else { - unreachable!("Unknown index direction \"{}\".", direction); + match direction { + "next" => IDBCursorDirection::Next, + "nextunique" => IDBCursorDirection::NextUnique, + "prev" => IDBCursorDirection::Prev, + "prevunique" => IDBCursorDirection::PrevUnique, + _ => unreachable!("Unknown index direction \"{}\".", direction), } } From 6833fd50b043e0b0e61a209bca01938c09b4c1ae Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:03:33 -0700 Subject: [PATCH 54/85] Fix value typo --- src/webapi/indexeddb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index d6c8be47..8ca70faf 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -224,7 +224,7 @@ fn string_to_cursor_direction( direction: &str) -> IDBCursorDirection { } } -/// This enum is used to represent the vlaue of the soure property of +/// This enum is used to represent the value of the soure property of /// a `IDBCursor`. #[derive(Debug)] pub enum IDBCursorSource { From 365bc9bad3430ca6a389f18d5a3f7187aea7adac Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:06:41 -0700 Subject: [PATCH 55/85] Remove empty doc comments --- src/webapi/indexeddb.rs | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 8ca70faf..9d660e0c 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -273,9 +273,7 @@ error_enum_boilerplate! { DataCloneError } -/// error_enum_boilerplate! { - /// IDBAddError, /// This IDBCursor's transaction is inactive. TransactionInactiveError, From 93551a4cae51584a8d7bd3dad1c074973cf3f382 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:07:42 -0700 Subject: [PATCH 56/85] Add missing semicolons in JavaScript --- src/webapi/indexeddb.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 9d660e0c..c61b69a5 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -317,9 +317,9 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor/source) fn source( &self ) -> IDBCursorSource { if js!( return @{self.as_ref()}.source instanceof IDBObjectStore; ).try_into().unwrap() { - IDBCursorSource::Store(js!( return @{self.as_ref()}.source ).try_into().unwrap()) + IDBCursorSource::Store(js!( return @{self.as_ref()}.source; ).try_into().unwrap()) } else if js!( return @{self.as_ref()}.source instanceof IDBIndex;).try_into().unwrap() { - IDBCursorSource::Index(js!( return @{self.as_ref()}.source ).try_into().unwrap()) + IDBCursorSource::Index(js!( return @{self.as_ref()}.source; ).try_into().unwrap()) } else { panic!() } From 04953f5e0672b6a4f185800f073810fc35356795 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:08:45 -0700 Subject: [PATCH 57/85] Actually fix missing return in error return --- src/webapi/indexeddb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index c61b69a5..ed559201 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -43,7 +43,7 @@ pub trait IDBRequestSharedMethods : IEventTarget { /// /// [(JavaScript docx)](https://developer.mozilla.org/en-US/docs/Web/API/IDBRequest/error) fn error(&self) -> Option { - return js!( @{self.as_ref()}.error;).try_into().unwrap() + js!( return @{self.as_ref()}.error; ).try_into().unwrap() } /// Returns the source of the request. From 7b5eecb95382034918bf881b5db0c2e39db18ba3 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:09:25 -0700 Subject: [PATCH 58/85] Add link to IDBCursor spec --- src/webapi/indexeddb.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index ed559201..d5083b7b 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -416,6 +416,7 @@ pub trait IDBCursorSharedMethods: AsRef< Reference > { /// traversing or iterating over multiple records in a database. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursor) +// https://w3c.github.io/IndexedDB/#idbcursor #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBCursor")] pub struct IDBCursor( Reference ); From 03816a4359dcec368078ff412d2452fa7651ed2b Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:10:10 -0700 Subject: [PATCH 59/85] Fix missing semicolon in js value and indentation --- src/webapi/indexeddb.rs | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index d5083b7b..fbae0452 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -440,9 +440,7 @@ impl IDBCursorWithValue { /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBCursorWithValue/value) pub fn value( &self ) -> Value { - js! ( - return @{self}.value - ).try_into().unwrap() + js!( return @{self}.value; ).try_into().unwrap() } } From 6047c3d416a99ac0ea481dd89f8fbf78e6b8a9f4 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:10:31 -0700 Subject: [PATCH 60/85] Add IDBKeyRange spec link --- src/webapi/indexeddb.rs | 1 + 1 file changed, 1 insertion(+) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index fbae0452..afe86150 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -451,6 +451,7 @@ impl IDBCursorWithValue { /// values of a key in the value range A–Z. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBKeyRange) +// https://w3c.github.io/IndexedDB/#idbkeyrange #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBKeyRange")] pub struct IDBKeyRange( Reference ); From 9cacfecfb93501a63d79b3dbfbefb27b6365755e Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:11:08 -0700 Subject: [PATCH 61/85] Fix mothods typo --- src/webapi/indexeddb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index afe86150..8ef0cb8b 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -581,7 +581,7 @@ error_enum_boilerplate! { } -/// This trait contains mothods that are Identicle in both IDBIndex IDBObjectStore +/// This trait contains methods that are identical in both IDBIndex and IDBObjectStore pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// Returns the name of this index or object store. From 3640e3016cf9a401921d2b58539fd0e158eee3d8 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:11:46 -0700 Subject: [PATCH 62/85] Fix get_all() method typo --- src/webapi/indexeddb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 8ef0cb8b..93e21167 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -642,7 +642,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { }.unwrap() } - /// The get_ll() method retrieves all objects that are inside the index or + /// The get_all() method retrieves all objects that are inside the index or /// object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/getAll) From fbb06911762e016b7c2a7cc798d73f4b0781da85 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:13:21 -0700 Subject: [PATCH 63/85] Simplify get_all count param to Option --- src/webapi/indexeddb.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 93e21167..b93b13d5 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -646,17 +646,17 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/getAll) - fn get_all, C: Into>>( &self, query: Q, count: C) -> Result { + fn get_all>( &self, query: Q, count: Option) -> Result { match query.into() { IDBKeyOrKeyRange::None => js_try! ( return @{self.as_ref()}.getAll(); ), IDBKeyOrKeyRange::Value(value) => { - match count.into() { + match count { None => js_try! ( return @{self.as_ref()}.getAll(@{value.as_ref()}); ), Some(count) => js_try! ( return @{self.as_ref()}.getAll(@{value.as_ref()}, @{count}); ) } }, IDBKeyOrKeyRange::Range(range) => { - match count.into() { + match count { None => js_try! ( return @{self.as_ref()}.getAll(@{range.as_ref()}); ), Some(count) => js_try! ( return @{self.as_ref()}.getAll(@{range.as_ref()}, @{count}); ) } From 49a253e74c97c87304b707b35c38ecb540948042 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:13:28 -0700 Subject: [PATCH 64/85] Revert "Remove empty doc comments" This reverts commit 365bc9bad3430ca6a389f18d5a3f7187aea7adac. --- src/webapi/indexeddb.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index b93b13d5..85cca8d1 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -273,7 +273,9 @@ error_enum_boilerplate! { DataCloneError } +/// error_enum_boilerplate! { + /// IDBAddError, /// This IDBCursor's transaction is inactive. TransactionInactiveError, From cb99095875a29b908f5578bb1e036d8ef859b490 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:14:29 -0700 Subject: [PATCH 65/85] Write a docstring for IDBAddError --- src/webapi/indexeddb.rs | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 85cca8d1..83b5bf27 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -273,9 +273,8 @@ error_enum_boilerplate! { DataCloneError } -/// error_enum_boilerplate! { - /// + /// Errors thrown when adding to the database. IDBAddError, /// This IDBCursor's transaction is inactive. TransactionInactiveError, From a0b25432ee8173b5a12d902487724ce45b5edaa7 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:17:04 -0700 Subject: [PATCH 66/85] Replace more Into> generic with Option<> --- src/webapi/indexeddb.rs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 83b5bf27..f8caccc0 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -711,11 +711,11 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// thread, creates a cursor over the specified key range. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openCursor) - fn open_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { + fn open_cursor>>( &self, range: Q, direction: Option) -> Result { match range.into() { None => js_try! ( return @{self.as_ref()}.openCursor(); ), Some(range) => { - match direction.into() { + match direction { None => js_try! ( return @{self.as_ref()}.openCursor(@{range.as_ref()}); ), Some(direction) => js_try! ( return @{self.as_ref()}.openCursor(@{range.as_ref()}, @{cursor_direction_to_string(direction)}); ) } @@ -728,7 +728,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// by this index. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex/openKeyCursor) - fn open_key_cursor>, D: Into>>( &self, range: Q, direction: D) -> Result { + fn open_key_cursor>>(&self, range: Q, direction: Option) -> Result { match range.into() { None => js_try! ( return @{self.as_ref()}.openKeyCursor(); ), Some(range) => { From 6ba12cb183bd143182309f1d81eed021b91e4cc0 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:20:19 -0700 Subject: [PATCH 67/85] More spec links --- src/webapi/indexeddb.rs | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index f8caccc0..bc76f874 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -745,6 +745,7 @@ pub trait IDBObjectStoreIndexSharedMethods: AsRef< Reference > { /// Provides asynchronous access to an index in a database. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBIndex) +// https://w3c.github.io/IndexedDB/#idbindex #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBIndex")] pub struct IDBIndex( Reference ); @@ -795,6 +796,7 @@ error_enum_boilerplate! { /// The `IDBObjectStore` interface of the IndexedDB API represents an object store in a database /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore) +// https://w3c.github.io/IndexedDB/#idbobjectstore #[derive(Clone, Debug, PartialEq, Eq, ReferenceType)] #[reference(instance_of = "IDBObjectStore")] pub struct IDBObjectStore( Reference ); From c6c76f5bcb1698ee030516bcd2a56dcf38ef2fc9 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:20:31 -0700 Subject: [PATCH 68/85] Fix the typo --- src/webapi/indexeddb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index bc76f874..8e233260 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -805,7 +805,7 @@ impl IDBObjectStoreIndexSharedMethods for IDBObjectStore {} impl IDBObjectStore { - /// The index_names read-only property of the `IDBObjectStore` interface returns a list of th + /// The index_names read-only property of the `IDBObjectStore` interface returns a list of the /// names of indexes on objects in this object store. /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/indexNames) From 694f7ca3167956b911956744e97ddb1722e6231b Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:20:48 -0700 Subject: [PATCH 69/85] Add missing index_names js semicolon --- src/webapi/indexeddb.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/webapi/indexeddb.rs b/src/webapi/indexeddb.rs index 8e233260..76f07880 100644 --- a/src/webapi/indexeddb.rs +++ b/src/webapi/indexeddb.rs @@ -810,7 +810,7 @@ impl IDBObjectStore { /// /// [(JavaScript docs)](https://developer.mozilla.org/en-US/docs/Web/API/IDBObjectStore/indexNames) pub fn index_names( &self ) -> DOMStringList { - js! ( return @{self}.indexNames ).try_into().unwrap() + js! ( return @{self}.indexNames; ).try_into().unwrap() } /// The `IDBTransaction` object to which this object store belongs. From 38c08a6d933c73a72c6f8490344b95be4d3a4120 Mon Sep 17 00:00:00 2001 From: ice_iix Date: Thu, 23 May 2019 17:21:43 -0700 Subject: [PATCH 70/85] Into