Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added rich text formatting #21

Merged
merged 4 commits into from
May 6, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/type_conversions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ pub fn insert_at(dst: &Array, txn: &mut Transaction, index: u32, src: Vec<PyObje
}

const MAX_JS_NUMBER: i64 = 2_i64.pow(53) - 1;
fn py_into_any(v: PyObject) -> Option<Any> {
pub fn py_into_any(v: PyObject) -> Option<Any> {
Python::with_gil(|py| -> Option<Any> {
let v = v.as_ref(py);

Expand Down
117 changes: 114 additions & 3 deletions src/y_text.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
use std::collections::HashMap;
use std::rc::Rc;

use lib0::any::Any;
use pyo3::exceptions::PyTypeError;
use pyo3::prelude::*;
use pyo3::types::PyList;
use yrs::types::text::TextEvent;
use yrs::types::Attrs;
use yrs::{SubscriptionId, Text, Transaction};

use crate::shared_types::SharedType;
use crate::type_conversions::py_into_any;
use crate::type_conversions::ToPython;
use crate::y_transaction::YTransaction;

Expand Down Expand Up @@ -86,10 +91,86 @@ impl YText {
}

/// Inserts a given `chunk` of text into this `YText` instance, starting at a given `index`.
pub fn insert(&mut self, txn: &mut YTransaction, index: u32, chunk: &str) {
pub fn insert(
&mut self,
txn: &mut YTransaction,
index: u32,
chunk: &str,
attributes: Option<HashMap<String, PyObject>>,
) -> PyResult<()> {
let attributes: Option<PyResult<Attrs>> = attributes.map(Self::parse_attrs);

if let Some(Ok(attributes)) = attributes {
match &mut self.0 {
SharedType::Integrated(text) => {
text.insert_with_attributes(txn, index, chunk, attributes);
Ok(())
}
SharedType::Prelim(_) => Err(PyTypeError::new_err("OOf")),
}
} else if let Some(Err(error)) = attributes {
Err(error)
} else {
match &mut self.0 {
SharedType::Integrated(text) => text.insert(txn, index, chunk),
SharedType::Prelim(prelim_string) => {
prelim_string.insert_str(index as usize, chunk)
}
}
Ok(())
}
}

/// Inserts a given `embed` object into this `YText` instance, starting at a given `index`.
///
/// Optional object with defined `attributes` will be used to wrap provided `embed`
/// with a formatting blocks.`attributes` are only supported for a `YText` instance which
/// already has been integrated into document store.
pub fn insert_embed(
&mut self,
txn: &mut YTransaction,
index: u32,
embed: PyObject,
attributes: Option<HashMap<String, PyObject>>,
) -> PyResult<()> {
match &mut self.0 {
SharedType::Integrated(v) => v.insert(txn, index, chunk),
SharedType::Prelim(v) => v.insert_str(index as usize, chunk),
SharedType::Integrated(text) => {
let content = py_into_any(embed)
.ok_or(PyTypeError::new_err("Content could not be embedded"))?;
if let Some(Ok(attrs)) = attributes.map(Self::parse_attrs) {
text.insert_embed_with_attributes(txn, index, content, attrs)
} else {
text.insert_embed(txn, index, content)
}
Ok(())
}
SharedType::Prelim(_) => Err(PyTypeError::new_err(
"Insert embeds requires YText instance to be integrated first.",
)),
}
}

/// Wraps an existing piece of text within a range described by `index`-`length` parameters with
/// formatting blocks containing provided `attributes` metadata. This method only works for
/// `YText` instances that already have been integrated into document store.
pub fn format(
&mut self,
txn: &mut YTransaction,
index: u32,
length: u32,
attributes: HashMap<String, PyObject>,
) -> PyResult<()> {
match Self::parse_attrs(attributes) {
Ok(attrs) => match &mut self.0 {
SharedType::Integrated(text) => {
text.format(txn, index, length, attrs);
Ok(())
}
SharedType::Prelim(_) => Err(PyTypeError::new_err(
"Insert embeds requires YText instance to be integrated first.",
)),
},
Err(err) => Err(err),
}
}

Expand Down Expand Up @@ -143,6 +224,25 @@ impl YText {
}
}

impl YText {
fn parse_attrs(attrs: HashMap<String, PyObject>) -> PyResult<Attrs> {
attrs
.into_iter()
.map(|(k, v)| {
let key = Rc::from(k);
let value = py_into_any(v);
if let Some(value) = value {
Ok((key, value))
} else {
Err(PyTypeError::new_err(
"Cannot convert attributes into a standard type".to_string(),
))
}
})
.collect()
}
}

/// Event generated by `YYText.observe` method. Emitted during transaction commit phase.
#[pyclass(unsendable)]
pub struct YTextEvent {
Expand Down Expand Up @@ -218,4 +318,15 @@ impl YTextEvent {
delta
}
}

fn __str__(&self) -> String {
format!(
"YTextEvent(target={:?}, delta={:?})",
self.target, self.delta
)
}

fn __repr__(&self) -> String {
self.__str__()
}
}
59 changes: 59 additions & 0 deletions tests/test_y_text.py
Original file line number Diff line number Diff line change
Expand Up @@ -136,3 +136,62 @@ def register_callback(x, callback):

assert str(target) == str(x)
assert delta == [{"insert": "abcd"}]


def test_delta_embed_attributes():

d1 = Y.YDoc()
text = d1.get_text("test")

delta = None

def callback(e):
nonlocal delta
delta = e.delta

sub = text.observe(callback)

with d1.begin_transaction() as txn:
text.insert(txn, 0, "ab", {"bold": True})
text.insert_embed(txn, 1, {"image": "imageSrc.png"}, {"width": 100})

expected = [
{"insert": "a", "attributes": {"bold": True}},
{"insert": {"image": "imageSrc.png"}, "attributes": {"width": 100}},
{"insert": "b", "attributes": {"bold": True}},
]
assert delta == expected

text.unobserve(sub)


def test_formatting():
d1 = Y.YDoc()
text = d1.get_text("test")

delta = None
target = None

def callback(e):
nonlocal delta
nonlocal target
delta = e.delta
target = e.target

sub = text.observe(callback)

with d1.begin_transaction() as txn:
text.insert(txn, 0, "stylish")
text.format(txn, 0, 4, {"bold": True})

assert delta == [
{"insert": "styl", "attributes": {"bold": True}},
{"insert": "ish"},
]

with d1.begin_transaction() as txn:
text.format(txn, 4, 7, {"bold": True})

assert delta == [{"retain": 4}, {"retain": 3, "attributes": {"bold": True}}]

text.unobserve(sub)
31 changes: 29 additions & 2 deletions y_py.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -375,9 +375,36 @@ class YText:
Returns:
The underlying shared string stored in this data type.
"""
def insert(self, txn: YTransaction, index: int, chunk: str):
def insert(
self,
txn: YTransaction,
index: int,
chunk: str,
attributes: Optional[Dict[str, Any]],
):
"""
Inserts a string of text into the `YText` instance starting at a given `index`.
Attributes are optional style modifiers (`{"bold": True}`) that can be attached to the inserted string.
Attributes are only supported for a `YText` instance which already has been integrated into document store.
"""
def insert_embed(
self,
txn: YTransaction,
index: int,
embed: Any,
attributes: Optional[Dict[str, Any]],
):
"""
Inserts embedded content into the YText at the provided index. Attributes are user-defined metadata associated with the embedded content.
Attributes are only supported for a `YText` instance which already has been integrated into document store.
"""
def format(
self, txn: YTransaction, index: int, length: int, attributes: Dict[str, Any]
):
"""
Inserts a given `chunk` of text into this `YText` instance, starting at a given `index`.
Wraps an existing piece of text within a range described by `index`-`length` parameters with
formatting blocks containing provided `attributes` metadata. This method only works for
`YText` instances that already have been integrated into document store
"""
def push(self, txn: YTransaction, chunk: str):
"""
Expand Down