yrby

Example

A record-backed editor

Open this page in two windows and type in either one. Rails saves the text to its database, and the button below reads it back in Ruby.

Everyone who visits this page edits the same text, and it's cleared after a day with no activity. Don't type anything private.

Connecting…

Read back from Rails

Type something, then select “Read saved text”.
doc = @document.collaborative_document(:body).y_doc
doc.read_text("content")

How it's wired

The view renders collaborative_document_tag. Once the Yjs document syncs, the page's script attaches CodeMirror to it. When the lease's abort signal fires, the script removes CodeMirror again. The document session keeps any edits the server hasn't confirmed yet, so removing the editor doesn't lose them.

This page runs the published gems and client. The site adds the same limits to the gem's channel that the public demos use. In your own app, check that the user can edit the record before you render the tag.

Getting started · The JavaScript client

The source

This is the code this page runs, read from the server's disk when the page renders. The script imports only published packages.

app/views/examples/document.html.erb
<% content_for :title, "A record-backed editor · yrby" %>
<% content_for :head do %>
  <script type="module" src="<%= busted "/document.js" %>"></script>
<% end %>
<div class="docs-body max-w-3xl">
  <p class="text-sm text-accent">Example</p>
  <h1>A record-backed editor</h1>
  <p>Open this page in two windows and type in either one. Rails saves the
    text to its database, and the button below reads it back in Ruby.</p>
  <p>Everyone who visits this page edits the same text, and it's cleared
    after a day with no activity. Don't type anything private.</p>
</div>
<p id="document-status" role="status" class="my-4 text-sm text-zinc-400">Connecting…</p>
<template id="document-template">
<%= collaborative_document_tag @document, :body, id: "document-editor", class: "block rounded-lg border border-zinc-700 bg-zinc-900 p-3" do %>
  <div data-editor-mount aria-label="Shared document"></div>
<% end %>
</template>
<div id="document-container"></div>
<section class="docs-body mt-8 max-w-3xl">
  <h2>Read back from Rails</h2>
  <button id="read-document" class="rounded border border-zinc-600 px-3 py-2 text-sm">Read saved text</button>
  <pre id="stored-document" aria-live="polite">Type something, then select “Read saved text”.</pre>
  <%= code_block "ruby", "doc = @document.collaborative_document(:body).y_doc\ndoc.read_text(\"content\")" %>
  <h2>How it's wired</h2>
  <p>The view renders <code>collaborative_document_tag</code>. Once the
    Yjs document syncs, the page's script attaches CodeMirror to it. When the
    lease's abort signal fires, the script removes CodeMirror again. The
    document session keeps any edits the server hasn't confirmed yet, so
    removing the editor doesn't lose them.</p>
  <p>This page runs the published gems and client. The site adds the same
    limits to the gem's channel that the public demos use. In your own app, check
    that the user can edit the record before you render the tag.</p>
  <p><a href="/docs/getting-started">Getting started</a> ·
    <a href="/docs/javascript-client">The JavaScript client</a></p>
</section>
<%= render "source_files", paths: ["app/views/examples/document.html.erb", "frontend/src/document.js"],
           note: "The script imports only published packages." %>
frontend/src/document.js
import { createConsumer } from "@anycable/web"
import { YrbyDocumentElement } from "yrby-client/element"
import { EditorState } from "@codemirror/state"
import { EditorView, basicSetup } from "codemirror"
import { oneDark } from "@codemirror/theme-one-dark"
import { yCollab } from "y-codemirror.next"

const status = document.querySelector("#document-status")
const cableUrl = new URL(document.querySelector('meta[name="action-cable-url"]').content, location.href)
cableUrl.protocol = location.protocol === "https:" ? "wss:" : "ws:"
const cable = createConsumer(cableUrl.href)
// These rooms are public, so awareness goes through the server's checked
// receive path. Clearing `whisper` makes the provider send it that way.
const consumer = {
  subscriptions: {
    create(params, callbacks) {
      const subscription = cable.subscriptions.create(params, {
        ...callbacks,
        received(message) {
          if (message?.notice === "document_full") {
            status.textContent = "This shared scratchpad is full, so new edits won't be saved. Anything typed since then is only in this tab."
          } else if (message?.notice === "file_refused") {
            status.textContent = "This site doesn't accept files or embedded images, so new edits from this tab won't be saved. Reload the page to keep editing."
          } else {
            callbacks.received(message)
          }
        },
      })
      subscription.whisper = undefined
      return subscription
    },
  },
}
YrbyDocumentElement.consumer = consumer

document.addEventListener("yrby:synced", ({ target, detail }) => {
  if (target.id !== "document-editor") return
  const editor = new EditorView({
    parent: target.querySelector("[data-editor-mount]"),
    state: EditorState.create({
      doc: detail.doc.getText("content").toString(),
      extensions: [basicSetup, oneDark, EditorView.lineWrapping,
        EditorView.theme({ ".cm-content": { minHeight: "140px" } }),
        EditorView.contentAttributes.of({ "aria-label": "Shared document" }),
        yCollab(detail.doc.getText("content"), detail.provider.awareness)],
    }),
  })
  const off = detail.provider.onStatusChange(({ status: state }) => {
    status.textContent = state === "synced" ? "Synced. Ready to edit." : "Reconnecting…"
  })
  status.textContent = "Synced. Ready to edit."
  detail.signal.addEventListener("abort", () => {
    off()
    editor.destroy()
  }, { once: true })
})

document.addEventListener("yrby:error", () => {
  status.textContent = "Couldn't connect. Keep this tab open so your unsaved edits aren't lost."
})

document.querySelector("#read-document").addEventListener("click", async () => {
  const output = document.querySelector("#stored-document")
  try {
    const response = await fetch("/examples/document/stored", { cache: "no-store" })
    if (!response.ok) throw new Error("Read failed")
    const { body } = await response.json()
    output.textContent = body || "The saved document is empty."
  } catch {
    output.textContent = "Couldn't read the saved document. Try again."
  }
})

// The element registers itself on import. The markup stays in a template until
// the AnyCable consumer and the editor listener above are set up.
document.querySelector("#document-container").append(
  document.querySelector("#document-template").content.cloneNode(true),
)