yrby

yrby-laravel · a separate package, built on yrby · beta

Collaborative editing for Laravel Rust

yrby-laravel adds collaborative editing to Laravel Rust. Multiple people edit the same document and see each other's changes and cursors live. Changes are saved to your database first, then broadcast to everyone else over Reverb.

It's built on yrby's Rust core. If your app is on Rails, you want yrby-rails.

Cargo.toml
[dependencies]laravel-rust = { version = "0.1", features = ["database-postgres", "reverb"] }yrby-laravel = "0.1"
src/app.rsapp
Application::configure()    .with_providers(|providers| {        providers.add(YrbyServiceProvider);    })
terminal
laravel migratenpm install yrby-laravel yrby-client

The crate is on crates.io and the browser package is on npm.

Try it

This page is served by a small Laravel Rust app running yrby-laravel. The editor below is a real document in that app's database. You have a room to yourself, so open it in a second window and type in both.

You are … · connecting · here now: just you Open this room in another window ↗

There's no sign-in here, so rooms are rate limited, capped in size and deleted after a day without changes. The app is examples/live in the yrby-laravel repository, and this page's template is in this site's repository.

Authorization

A document is a route in your app, protected by your session and a policy like any other route. Mark the model as collaborative, then add a route with the policy method to check:

// src/models/post.rs: a post has documents
impl Collaborative for Post {}

// src/routes/web.rs: who may edit a post's documents
route.documents(PostPolicy::edit);

The body of post 42 is now at /yrby/post/42/body. The one route handles every document on the model, and another model is the same two lines.

The policy is checked on every change, so there are no tokens to issue or expire. Guests get a 401 and anyone the policy rejects gets a 403. If someone loses access while they have the page open, their next keystroke gets a 403 too. It isn't saved or sent to anyone else. The check adds about a millisecond per change.

Reading uses the same policy. Changes are broadcast on a private Reverb channel, and the only way to join it is with a signature from the document's route. One gap for now is that someone who's already connected when they lose access keeps receiving changes until their socket reconnects or they try to type.

route.document gives one document its own URL and policy method. Both helpers are shorthand for a handler like this one, which you can write yourself if you need more than one check:

// POST /posts/{post}/body, written out
pub async fn body(
    user: Authenticated<User>,
    post: Post,
    request: Request,
) -> laravel::Result<Json<Value>> {
    user.authorize(PostPolicy::edit, &post).await?;
    post.document("body").sync(&request).await
}

In the browser

New Laravel Rust apps come with Inertia and React. Pass the document to the page as a prop:

// the page's handler
inertia::render("Post", props! { body => post.document("body") })

On the page, give it to useDocument. You don't write a URL or set up Echo. The hook opens the document on mount and closes it on unmount. You get a Yjs document back, so any editor with a Yjs binding works. Here's Tiptap:

import { useDocument } from "yrby-laravel/react";

// The handler passed props! { body => post.document("body") }.
export default function Post({ body, user }) {
  const { document, refused } = useDocument(body, { user });

  // null until the document has synced
  return document && <Editor document={document} user={user} editable={!refused} />;
}

function Editor({ document, user, editable }) {
  const editor = useEditor({
    editable,
    extensions: [
      StarterKit.configure({ undoRedo: false }),
      Collaboration.configure({ document: document.doc }),
      CollaborationCaret.configure({ provider: document.provider, user }),
    ],
  }, [document]);
  return <EditorContent editor={editor} />;
}

For Vue it's the same hook from yrby-laravel/vue, and it returns refs:

<script setup>
import { useDocument } from "yrby-laravel/vue";
import Editor from "./Editor.vue";

const props = defineProps(["body", "user"]);
const { document, refused } = useDocument(() => props.body, { user: props.user });
</script>

<template>
  <Editor v-if="document" :document="document" :user="user" :editable="!refused" />
</template>

For server-rendered pages there's a tag. Pass the document to the view and put yrby_document where the editor goes:

// the page's handler
view("post", data! { body => post.document("body") })
{{ yrby_document(body) }}

That renders <yrby-document src="/yrby/post/42/body">. Import the element and attach your editor once a document has synced. One listener handles every tag in your app:

import "yrby-laravel/element";

// One listener for the whole app.
document.addEventListener("yrby:synced", ({ target, detail }) => {
  const editor = new Editor({
    element: target,
    extensions: [
      StarterKit.configure({ undoRedo: false }),
      Collaboration.configure({ document: detail.doc }),
      CollaborationCaret.configure({ provider: detail.provider, user: detail.user }),
    ],
  });
  detail.signal.addEventListener("abort", () => editor.destroy(), { once: true });
});

This is all built on yrby-client. Requests carry your session cookie and Laravel's CSRF token. If the app refuses one, syncing stops. The hooks set refused to the status, and the tag fires yrby:refused. The hooks and the tag both call openDocument, which you can also call yourself.

How it works

Reverb speaks the Pusher protocol, where the server doesn't see what browsers send over the socket. So the browser sends each change to your app over HTTP. The app saves it, broadcasts it through Reverb to everyone else, and then acknowledges it. If saving or broadcasting fails there's no acknowledgment, and the browser sends the change again.

Nothing is kept in memory between requests, so any process can serve any document. Presence (names and cursors) goes from browser to browser and isn't stored.

Editing from the server

post.document("body") works anywhere in your app, like a handler, a job or a command. edit gives your closure the document, and whatever you change is saved and sent to every open editor:

use yrby_laravel::yrs::{Transact, XmlElementPrelim, XmlFragment, XmlTextPrelim};

// Add a paragraph to a post's body, as Tiptap stores one.
post.document("body")
    .edit(|doc| {
        let body = doc.get_or_insert_xml_fragment("default");
        let text = XmlTextPrelim::new(note);
        let paragraph = XmlElementPrelim::new("paragraph", [text.into()]);
        body.push_back(&mut doc.transact_mut(), paragraph);
    })
    .await?;

y_doc reads a document without changing it, and append saves a Yjs update you already have, like an import.

Rendering to HTML

You can render a document to HTML on the server, for something like a public page or an email. There's no Node or headless browser involved. ProseMirror::tiptap() produces the same HTML as Tiptap's getHTML(), and to_text returns plain text for search or previews:

use yrby_laravel::{Collaborative, ProseMirror};

// GET /posts/{post}: a read-only page, no editor
pub async fn show(post: Post) -> laravel::Result<View> {
    let tiptap = ProseMirror::tiptap();
    let body = post.document("body").to_html(&tiptap).await?;
    Ok(view("post", data! {
        title => &post.title,
        body => body.unwrap_or_default(),
    }))
}

The document's text is escaped, so the view can print body as markup. The renderer is tested against HTML captured from a real editor. You can add rules for your own node types, and Lexical::new() renders a Lexical editor's core nodes.

Storage

Documents are stored in two tables in your own database, which can be PostgreSQL, MySQL, MariaDB or SQLite. Every change is a row, and every 64 changes are merged into the document's snapshot. When someone joins, they're served from those rows without the document being rebuilt in memory.

A document belongs to its record through a polymorphic relationship. Laravel needs to know which models can be the parent, so you define a small model over yrby's table:

// Every model in this app that has yrby documents.
#[morph]
pub enum Documented {
    Post(Post),
}

// A row in yrby's y_documents table.
#[model(table = "y_documents")]
pub struct Document {
    pub id: i64,
    pub key: String,
    pub record_type: Option<MorphType<Documented>>,
    pub record_id: Option<i64>,
    pub name: Option<String>,
    pub created_at: Timestamp,
    pub updated_at: Timestamp,
    #[morph_to]
    pub record: MorphTo<Option<Documented>>,
}

// On Post:
#[morph_many(Document::record)]
pub documents: MorphMany<Document>,

Then a post's documents are a normal relationship:

// All of a post's documents: body, summary and so on.
let documents = post.documents().order_by(Document::id.asc()).get().await?;

The model has no column for a document's contents, so loading the relationship doesn't load every snapshot.

Encryption at rest is per attribute, set on the model:

impl Collaborative for Post {
    const DOCUMENTS: &'static [DocumentOptions] =
        &[DocumentOptions::new("body").encrypted()];
}

It uses Laravel's encrypter and your APP_KEY, and key rotation works the way it does elsewhere in Laravel. Documents saved before you turned it on stay readable. Encrypted documents take about 2.4 times the space.

Built on yrby

yrby's sync protocol and storage rules are a Rust crate, yrby-core. yrby-laravel connects that crate to Laravel Rust's routes, database and broadcasting.

yrby-laravel is in beta, like Laravel Rust itself, so expect breaking changes before 1.0. It's tested end to end with two people editing in real browsers, and the sync and storage tests run on all four databases.