Struct ywasm::Doc

source ·
pub struct Doc(/* private fields */);
Expand description

A ywasm document type. Documents are most important units of collaborative resources management. All shared collections live within a scope of their corresponding documents. All updates are generated on per-document basis (rather than individual shared type). All operations on shared collections happen via YTransaction, which lifetime is also bound to a document.

Document manages so-called root types, which are top-level shared types definitions (as opposed to recursively nested types).

A basic workflow sample:

import YDoc from 'ywasm'

const doc = new YDoc()
const txn = doc.beginTransaction()
try {
    const text = txn.getText('name')
    text.push(txn, 'hello world')
    const output = text.toString(txn)
    console.log(output)
} finally {
    txn.free()
}

Implementations§

source§

impl YDoc

source

pub fn new(options: &JsValue) -> Result<YDoc, JsValue>

Creates a new ywasm document. If id parameter was passed it will be used as this document globally unique identifier (it’s up to caller to ensure that requirement). Otherwise it will be assigned a randomly generated number.

source

pub fn get_type(&self) -> u8

source

pub fn prelim(&self) -> bool

Checks if a document is a preliminary type. It returns false, if current document is already a sub-document of another document.

source

pub fn parent_doc(&self) -> Option<YDoc>

Returns a parent document of this document or null if current document is not sub-document.

source

pub fn id(&self) -> f64

Gets unique peer identifier of this YDoc instance.

source

pub fn guid(&self) -> String

Gets globally unique identifier of this YDoc instance.

source

pub fn should_load(&self) -> bool

source

pub fn auto_load(&self) -> bool

source

pub fn transaction(&self, origin: JsValue) -> YTransaction

Returns a new transaction for this document. Ywasm shared data types execute their operations in a context of a given transaction. Each document can have only one active transaction at the time - subsequent attempts will cause exception to be thrown.

Transactions started with doc.beginTransaction can be released using transaction.free method.

Example:

import YDoc from 'ywasm'

// helper function used to simplify transaction
// create/release cycle
YDoc.prototype.transact = callback => {
    const txn = this.transaction()
    try {
        return callback(txn)
    } finally {
        txn.free()
    }
}

const doc = new YDoc()
const text = doc.getText('name')
doc.transact(txn => text.insert(txn, 0, 'hello world'))
source

pub fn get_text(&self, name: &str) -> YText

Returns a YText shared data type, that’s accessible for subsequent accesses using given name.

If there was no instance with this name before, it will be created and then returned.

If there was an instance with this name, but it was of different type, it will be projected onto YText instance.

source

pub fn get_array(&self, name: &str) -> YArray

Returns a YArray shared data type, that’s accessible for subsequent accesses using given name.

If there was no instance with this name before, it will be created and then returned.

If there was an instance with this name, but it was of different type, it will be projected onto YArray instance.

source

pub fn get_map(&self, name: &str) -> YMap

Returns a YMap shared data type, that’s accessible for subsequent accesses using given name.

If there was no instance with this name before, it will be created and then returned.

If there was an instance with this name, but it was of different type, it will be projected onto YMap instance.

source

pub fn get_xml_fragment(&self, name: &str) -> YXmlFragment

Returns a YXmlFragment shared data type, that’s accessible for subsequent accesses using given name.

If there was no instance with this name before, it will be created and then returned.

If there was an instance with this name, but it was of different type, it will be projected onto YXmlFragment instance.

source

pub fn on_update(&self, f: Function) -> Result<Observer, JsValue>

Subscribes given function to be called any time, a remote update is being applied to this document. Function takes an Uint8Array as a parameter which contains a lib0 v1 encoded update.

Returns an observer, which can be freed in order to unsubscribe this callback.

source

pub fn on_update_v2(&self, f: Function) -> Result<Observer, JsValue>

Subscribes given function to be called any time, a remote update is being applied to this document. Function takes an Uint8Array as a parameter which contains a lib0 v2 encoded update.

Returns an observer, which can be freed in order to unsubscribe this callback.

source

pub fn on_after_transaction(&self, f: Function) -> Result<Observer, JsValue>

Subscribes given function to be called, whenever a transaction created by this document is being committed.

Returns an observer, which can be freed in order to unsubscribe this callback.

source

pub fn on_subdocs(&self, f: Function) -> Result<Observer, JsValue>

Subscribes given function to be called, whenever a subdocuments are being added, removed or loaded as children of a current document.

Returns an observer, which can be freed in order to unsubscribe this callback.

source

pub fn on_destroy(&self, f: Function) -> Result<Observer, JsValue>

Subscribes given function to be called, whenever current document is being destroyed.

Returns an observer, which can be freed in order to unsubscribe this callback.

source

pub fn load(&self, parent_txn: &ImplicitTransaction) -> Result<(), JsValue>

Notify the parent document that you request to load data into this subdocument (if it is a subdocument).

source

pub fn destroy(&self, parent_txn: &ImplicitTransaction) -> Result<(), JsValue>

Emit onDestroy event and unregister all event handlers.

source

pub fn subdocs(&self, txn: &ImplicitTransaction) -> Result<Array, JsValue>

Returns a list of sub-documents existings within the scope of this document.

source

pub fn subdoc_guids(&self, txn: &ImplicitTransaction) -> Result<Set, JsValue>

Returns a list of unique identifiers of the sub-documents existings within the scope of this document.

source

pub fn roots(&self, txn: &ImplicitTransaction) -> Result<Array, JsValue>

Returns a list of all root-level replicated collections, together with their types. These collections can then be accessed via getMap/getText etc. methods.

Example:

import * as Y from 'ywasm'

const doc = new Y.YDoc()
const ymap = doc.getMap('a')
const yarray = doc.getArray('b')
const ytext = doc.getText('c')
const yxml = doc.getXmlFragment('d')

const roots = doc.roots() // [['a',ymap], ['b',yarray], ['c',ytext], ['d',yxml]]

Methods from Deref<Target = Doc>§

source

pub fn client_id(&self) -> u64

A unique client identifier, that’s also a unique identifier of current document replica and it’s subdocuments.

source

pub fn guid(&self) -> &Arc<str>

A globally unique identifier, that’s also a unique identifier of current document replica, and unlike Doc::client_id it’s not shared with its subdocuments.

source

pub fn options(&self) -> &Options

Returns config options of this Doc instance.

source

pub fn get_or_insert_text<N>(&self, name: N) -> TextRef
where N: Into<Arc<str>>,

Returns a TextRef data structure stored under a given name. Text structures are used for collaborative text editing: they expose operations to append and remove chunks of text, which are free to execute concurrently by multiple peers over remote boundaries.

If no structure under defined name existed before, it will be created and returned instead.

If a structure under defined name already existed, but its type was different it will be reinterpreted as a text (in such case a sequence component of complex data type will be interpreted as a list of text chunks).

§Panics

This method requires exclusive access to an underlying document store. If there is another transaction in process, it will panic. It’s advised to define all root shared types during the document creation.

source

pub fn get_or_insert_map<N>(&self, name: N) -> MapRef
where N: Into<Arc<str>>,

Returns a MapRef data structure stored under a given name. Maps are used to store key-value pairs associated. These values can be primitive data (similar but not limited to a JavaScript Object Notation) as well as other shared types (Yrs maps, arrays, text structures etc.), enabling to construct a complex recursive tree structures.

If no structure under defined name existed before, it will be created and returned instead.

If a structure under defined name already existed, but its type was different it will be reinterpreted as a map (in such case a map component of complex data type will be interpreted as native map).

§Panics

This method requires exclusive access to an underlying document store. If there is another transaction in process, it will panic. It’s advised to define all root shared types during the document creation.

source

pub fn get_or_insert_array<N>(&self, name: N) -> ArrayRef
where N: Into<Arc<str>>,

Returns an ArrayRef data structure stored under a given name. Array structures are used for storing a sequences of elements in ordered manner, positioning given element accordingly to its index.

If no structure under defined name existed before, it will be created and returned instead.

If a structure under defined name already existed, but its type was different it will be reinterpreted as an array (in such case a sequence component of complex data type will be interpreted as a list of inserted values).

§Panics

This method requires exclusive access to an underlying document store. If there is another transaction in process, it will panic. It’s advised to define all root shared types during the document creation.

source

pub fn get_or_insert_xml_fragment<N>(&self, name: N) -> XmlFragmentRef
where N: Into<Arc<str>>,

Returns a XmlFragmentRef data structure stored under a given name. XML elements represent nodes of XML document. They can contain attributes (key-value pairs, both of string type) and other nested XML elements or text values, which are stored in their insertion order.

If no structure under defined name existed before, it will be created and returned instead.

If a structure under defined name already existed, but its type was different it will be reinterpreted as a XML element (in such case a map component of complex data type will be interpreted as map of its attributes, while a sequence component - as a list of its child XML nodes).

§Panics

This method requires exclusive access to an underlying document store. If there is another transaction in process, it will panic. It’s advised to define all root shared types during the document creation.

source

pub fn observe_update_v1<F>(&self, f: F) -> Result<Subscription, BorrowMutError>
where F: Fn(&TransactionMut<'_>, &UpdateEvent) + 'static,

Subscribe callback function for any changes performed within transaction scope. These changes are encoded using lib0 v1 encoding and can be decoded using [Update::decode_v1] if necessary or passed to remote peers right away. This callback is triggered on function commit.

Returns a subscription, which will unsubscribe function when dropped.

source

pub fn observe_update_v2<F>(&self, f: F) -> Result<Subscription, BorrowMutError>
where F: Fn(&TransactionMut<'_>, &UpdateEvent) + 'static,

Subscribe callback function for any changes performed within transaction scope. These changes are encoded using lib0 v2 encoding and can be decoded using [Update::decode_v2] if necessary or passed to remote peers right away. This callback is triggered on function commit.

Returns a subscription, which will unsubscribe function when dropped.

source

pub fn observe_transaction_cleanup<F>( &self, f: F ) -> Result<Subscription, BorrowMutError>
where F: Fn(&TransactionMut<'_>, &TransactionCleanupEvent) + 'static,

Subscribe callback function to updates on the Doc. The callback will receive state updates and deletions when a document transaction is committed.

source

pub fn observe_after_transaction<F>( &self, f: F ) -> Result<Subscription, BorrowMutError>
where F: Fn(&mut TransactionMut<'_>) + 'static,

source

pub fn observe_subdocs<F>(&self, f: F) -> Result<Subscription, BorrowMutError>
where F: Fn(&TransactionMut<'_>, &SubdocsEvent) + 'static,

Subscribe callback function, that will be called whenever a subdocuments inserted in this Doc will request a load.

source

pub fn observe_destroy<F>(&self, f: F) -> Result<Subscription, BorrowMutError>
where F: Fn(&TransactionMut<'_>, &Doc) + 'static,

Subscribe callback function, that will be called whenever a [DocRef::destroy] has been called.

source

pub fn load<T>(&self, parent_txn: &mut T)
where T: WriteTxn,

Sends a load request to a parent document. Works only if current document is a sub-document of an another document.

source

pub fn destroy<T>(&self, parent_txn: &mut T)
where T: WriteTxn,

Starts destroy procedure for a current document, triggering an “destroy” callback and invalidating all event callback subscriptions.

source

pub fn parent_doc(&self) -> Option<Doc>

If current document has been inserted as a sub-document, returns a reference to a parent document, which contains it.

source

pub fn branch_id(&self) -> Option<BranchID>

Trait Implementations§

source§

impl Deref for YDoc

§

type Target = Doc

The resulting type after dereferencing.
source§

fn deref(&self) -> &Self::Target

Dereferences the value.
source§

impl From<Doc> for YDoc

source§

fn from(doc: Doc) -> Self

Converts to this type from the input type.
source§

impl From<YDoc> for JsValue

source§

fn from(value: YDoc) -> Self

Converts to this type from the input type.
source§

impl FromWasmAbi for YDoc

§

type Abi = u32

The wasm ABI type that this converts from when coming back out from the ABI boundary.
source§

unsafe fn from_abi(js: u32) -> Self

Recover a Self from Self::Abi. Read more
source§

impl IntoWasmAbi for YDoc

§

type Abi = u32

The wasm ABI type that this converts into when crossing the ABI boundary.
source§

fn into_abi(self) -> u32

Convert self into Self::Abi so that it can be sent across the wasm ABI boundary.
source§

impl LongRefFromWasmAbi for YDoc

§

type Abi = u32

Same as RefFromWasmAbi::Abi
§

type Anchor = Ref<'static, YDoc>

Same as RefFromWasmAbi::Anchor
source§

unsafe fn long_ref_from_abi(js: Self::Abi) -> Self::Anchor

Same as RefFromWasmAbi::ref_from_abi
source§

impl OptionFromWasmAbi for YDoc

source§

fn is_none(abi: &Self::Abi) -> bool

Tests whether the argument is a “none” instance. If so it will be deserialized as None, and otherwise it will be passed to FromWasmAbi.
source§

impl OptionIntoWasmAbi for YDoc

source§

fn none() -> Self::Abi

Returns an ABI instance indicating “none”, which JS will interpret as the None branch of this option. Read more
source§

impl RefFromWasmAbi for YDoc

§

type Abi = u32

The wasm ABI type references to Self are recovered from.
§

type Anchor = Ref<'static, YDoc>

The type that holds the reference to Self for the duration of the invocation of the function that has an &Self parameter. This is required to ensure that the lifetimes don’t persist beyond one function call, and so that they remain anonymous.
source§

unsafe fn ref_from_abi(js: Self::Abi) -> Self::Anchor

Recover a Self::Anchor from Self::Abi. Read more
source§

impl RefMutFromWasmAbi for YDoc

§

type Abi = u32

Same as RefFromWasmAbi::Abi
§

type Anchor = RefMut<'static, YDoc>

Same as RefFromWasmAbi::Anchor
source§

unsafe fn ref_mut_from_abi(js: Self::Abi) -> Self::Anchor

Same as RefFromWasmAbi::ref_from_abi
source§

impl TryFromJsValue for YDoc

§

type Error = JsValue

The type returned in the event of a conversion error.
source§

fn try_from_js_value(value: JsValue) -> Result<Self, Self::Error>

Performs the conversion.
source§

impl VectorFromWasmAbi for YDoc

§

type Abi = <Box<[JsValue]> as FromWasmAbi>::Abi

source§

unsafe fn vector_from_abi(js: Self::Abi) -> Box<[YDoc]>

source§

impl VectorIntoWasmAbi for YDoc

§

type Abi = <Box<[JsValue]> as IntoWasmAbi>::Abi

source§

fn vector_into_abi(vector: Box<[YDoc]>) -> Self::Abi

source§

impl WasmDescribe for YDoc

source§

impl WasmDescribeVector for YDoc

Auto Trait Implementations§

§

impl Freeze for YDoc

§

impl !RefUnwindSafe for YDoc

§

impl Send for YDoc

§

impl Sync for YDoc

§

impl Unpin for YDoc

§

impl !UnwindSafe for YDoc

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ReturnWasmAbi for T
where T: IntoWasmAbi,

§

type Abi = <T as IntoWasmAbi>::Abi

Same as IntoWasmAbi::Abi
source§

fn return_abi(self) -> <T as ReturnWasmAbi>::Abi

Same as IntoWasmAbi::into_abi, except that it may throw and never return in the case of Err.
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.