CoTexts

Jazz provides two CoValue types for collaborative text editing, collectively referred to as "CoText" values:

  • co.plainText() for simple text editing without formatting
  • co.richText() for rich text with HTML-based formatting (extends co.plainText())

Both types enable real-time collaborative editing of text content while maintaining consistency across multiple users.

Note: If you're looking for a quick way to add rich text editing to your app, check out jazz-richtext-prosemirror.

const const note: CoPlainTextnote = import coco.
function plainText(): PlainTextSchema
export plainText
plainText
().
function create(text: string, options?: {
    owner: Account | Group;
} | Account | Group): CoPlainText
create
("Meeting notes", { owner: Account | Groupowner:
const me: Account | ({
    [x: string]: any;
} & Account)
me
});
// Update the text const note: CoPlainTextnote.CoPlainText.applyDiff(other: string): void
Apply text, modifying the text in place. Calculates the diff and applies it to the CoValue.
@categoryMutation
applyDiff
("Meeting notes for Tuesday");
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v20.11.1/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(const note: CoPlainTextnote.CoPlainText.toString(): string
Returns a string representation of a string.
toString
()); // "Meeting notes for Tuesday"

For a full example of CoTexts in action, see our Richtext example app, which shows plain text and rich text editing.

co.plainText() vs z.string()

While z.string() is perfect for simple text fields, co.plainText() is the right choice when you need:

  • Frequent text edits that aren't just replacing the whole field
  • Fine-grained control over text edits (inserting, deleting at specific positions)
  • Multiple users editing the same text simultaneously
  • Character-by-character collaboration
  • Efficient merging of concurrent changes

Both support real-time updates, but co.plainText() provides specialized tools for collaborative editing scenarios.

Creating CoText Values

CoText values are typically used as fields in your schemas:

const 
const Profile: CoProfileSchema<{
    name: z.z.ZodString;
    bio: PlainTextSchema;
    description: RichTextSchema;
}>
Profile
= import coco.
profile<{
    name: z.z.ZodString;
    bio: PlainTextSchema;
    description: RichTextSchema;
}>(shape?: ({
    name: z.z.ZodString;
    bio: PlainTextSchema;
    description: RichTextSchema;
} & {
    ...;
}) | undefined): CoProfileSchema<...>
export profile
profile
({
name: z.z.ZodString & z.z.core.$ZodString<string>name: import zz.
function string(params?: string | z.z.core.$ZodStringParams): z.z.ZodString
export string
string
(),
bio: PlainTextSchemabio: import coco.
function plainText(): PlainTextSchema
export plainText
plainText
(), // Plain text field
description: RichTextSchemadescription: import coco.
function richText(): RichTextSchema
export richText
richText
(), // Rich text with formatting
});

Create a CoText value with a simple string:

// Create plaintext with default ownership (current user)
const const note: CoPlainTextnote = import coco.
function plainText(): PlainTextSchema
export plainText
plainText
().
function create(text: string, options?: {
    owner: Account | Group;
} | Account | Group): CoPlainText
create
("Meeting notes", { owner: Account | Groupowner:
const me: Account | ({
    [x: string]: any;
} & Account)
me
});
// Create rich text with HTML content const const document: CoRichTextdocument = import coco.
function richText(): RichTextSchema
export richText
richText
().
function create(text: string, options?: {
    owner: Account | Group;
} | Account | Group): CoRichText
create
("<p>Project <strong>overview</strong></p>",
{ owner: Account | Groupowner:
const me: Account | ({
    [x: string]: any;
} & Account)
me
}
);

Ownership

Like other CoValues, you can specify ownership when creating CoTexts.

// Create with shared ownership
const const teamGroup: GroupteamGroup = class Group
@categoryIdentity & Permissions
Group
.
Group.create<Group>(this: CoValueClass<Group>, options?: {
    owner: Account;
} | Account): Group
create
();
const teamGroup: GroupteamGroup.Group.addMember(member: Account, role: AccountRole): void (+1 overload)addMember(
const colleagueAccount: Account | ({
    [x: string]: any;
} & Account)
colleagueAccount
, "writer");
const const teamNote: CoPlainTextteamNote = import coco.
function plainText(): PlainTextSchema
export plainText
plainText
().
function create(text: string, options?: {
    owner: Account | Group;
} | Account | Group): CoPlainText
create
("Team updates", { owner: Group | Accountowner: const teamGroup: GroupteamGroup });

See Groups as permission scopes for more information on how to use groups to control access to CoText values.

Reading Text

CoText values work similarly to JavaScript strings:

// Get the text content
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v20.11.1/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(const note: CoPlainTextnote.CoPlainText.toString(): string
Returns a string representation of a string.
toString
()); // "Meeting notes"
var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v20.11.1/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(`${const note: CoPlainTextnote}`); // "Meeting notes"
// Check the text length var console: Console
The `console` module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers. The module exports two specific components: * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without importing the `node:console` module. _**Warning**_: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for more information. Example using the global `console`: ```js console.log('hello world'); // Prints: hello world, to stdout console.log('hello %s', 'world'); // Prints: hello world, to stdout console.error(new Error('Whoops, something bad happened')); // Prints error message and stack trace to stderr: // Error: Whoops, something bad happened // at [eval]:5:15 // at Script.runInThisContext (node:vm:132:18) // at Object.runInThisContext (node:vm:309:38) // at node:internal/process/execution:77:19 // at [eval]-wrapper:6:22 // at evalScript (node:internal/process/execution:76:60) // at node:internal/main/eval_string:23:3 const name = 'Will Robinson'; console.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to stderr ``` Example using the `Console` class: ```js const out = getStreamSomehow(); const err = getStreamSomehow(); const myConsole = new console.Console(out, err); myConsole.log('hello world'); // Prints: hello world, to out myConsole.log('hello %s', 'world'); // Prints: hello world, to out myConsole.error(new Error('Whoops, something bad happened')); // Prints: [Error: Whoops, something bad happened], to err const name = 'Will Robinson'; myConsole.warn(`Danger ${name}! Danger!`); // Prints: Danger Will Robinson! Danger!, to err ```
@see[source](https://github.com/nodejs/node/blob/v20.11.1/lib/console.js)
console
.Console.log(message?: any, ...optionalParams: any[]): void (+1 overload)
Prints to `stdout` with newline. Multiple arguments can be passed, with the first used as the primary message and all additional used as substitution values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). ```js const count = 5; console.log('count: %d', count); // Prints: count: 5, to stdout console.log('count:', count); // Prints: count: 5, to stdout ``` See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information.
@sincev0.1.100
log
(const note: CoPlainTextnote.CoPlainText.length: number
Returns the length of a String object.
length
); // 14

Making Edits

Insert and delete text with intuitive methods:

// Insert text at a specific position
const note: CoPlainTextnote.CoPlainText.insertBefore(idx: number, text: string): voidinsertBefore(8, "weekly ");  // "Meeting weekly notes"

// Insert after a position
const note: CoPlainTextnote.CoPlainText.insertAfter(idx: number, text: string): voidinsertAfter(21, " for Monday");  // "Meeting weekly notes for Monday"

// Delete a range of text
const note: CoPlainTextnote.
CoPlainText.deleteRange(range: {
    from: number;
    to: number;
}): void
deleteRange
({ from: numberfrom: 8, to: numberto: 15 }); // "Meeting notes for Monday"
// Apply a diff to update the entire text const note: CoPlainTextnote.CoPlainText.applyDiff(other: string): void
Apply text, modifying the text in place. Calculates the diff and applies it to the CoValue.
@categoryMutation
applyDiff
("Team meeting notes for Tuesday");

Applying Diffs

Use applyDiff to efficiently update text with minimal changes:

// Original text: "Team status update"
const const minutes: CoPlainTextminutes = import coco.
function plainText(): PlainTextSchema
export plainText
plainText
().
function create(text: string, options?: {
    owner: Account | Group;
} | Account | Group): CoPlainText
create
("Team status update", { owner: Account | Groupowner:
const me: Account | ({
    [x: string]: any;
} & Account)
me
});
// Replace the entire text with a new version const minutes: CoPlainTextminutes.CoPlainText.applyDiff(other: string): void
Apply text, modifying the text in place. Calculates the diff and applies it to the CoValue.
@categoryMutation
applyDiff
("Weekly team status update for Project X");
// Make partial changes let let text: stringtext = const minutes: CoPlainTextminutes.CoPlainText.toString(): string
Returns a string representation of a string.
toString
();
let text: stringtext = let text: stringtext.String.replace(searchValue: string | RegExp, replaceValue: string): string (+3 overloads)
Replaces text in a string, using a regular expression or search string.
@paramsearchValue A string or regular expression to search for.@paramreplaceValue A string containing the text to replace. When the {@linkcode searchValue} is a `RegExp`, all matches are replaced if the `g` flag is set (or only those matches at the beginning, if the `y` flag is also present). Otherwise, only the first match of {@linkcode searchValue} is replaced.
replace
("Weekly", "Monday");
const minutes: CoPlainTextminutes.CoPlainText.applyDiff(other: string): void
Apply text, modifying the text in place. Calculates the diff and applies it to the CoValue.
@categoryMutation
applyDiff
(let text: stringtext); // Efficiently updates only what changed

Perfect for handling user input in form controls:

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { co, z } from "jazz-tools";
import { createJazzTestAccount } from 'jazz-tools/testing';

const note = ref(null);
const textContent = ref("");

onMounted(async () => {
  const me = await createJazzTestAccount();
  note.value = co.plainText().create("", { owner: me });
  textContent.value = note.value.toString();
});

function updateText(e) {
  if (note.value) {
    note.value.applyDiff(e.target.value);
    textContent.value = note.value.toString();
  }
}
</script>

<template>
  <textarea
    :value="textContent"
    @input="updateText"
  />
</template>

Using Rich Text with ProseMirror

Jazz provides a dedicated plugin for integrating co.richText() with the popular ProseMirror editor. This plugin, jazz-richtext-prosemirror, enables bidirectional synchronization between your co.richText() instances and ProseMirror editors.

ProseMirror Plugin Features

  • Bidirectional Sync: Changes in the editor automatically update the co.richText() and vice versa
  • Real-time Collaboration: Multiple users can edit the same document simultaneously
  • HTML Conversion: Automatically converts between HTML (used by co.richText()) and ProseMirror's document model

Installation

pnpm add jazz-richtext-prosemirror \
  prosemirror-view \
  prosemirror-state \
  prosemirror-schema-basic

Integration

We don't currently have a Vue-specific example, but you need help you can request one, or ask on Discord.

For use without a framework:

import { co, z } from "jazz-tools";
import { createJazzPlugin } from "jazz-richtext-prosemirror";
import { exampleSetup } from "prosemirror-example-setup";
import { schema } from "prosemirror-schema-basic";
import { EditorState } from "prosemirror-state";
import { EditorView } from "prosemirror-view";

function setupRichTextEditor(coRichText, container) {
  // Create the Jazz plugin for ProseMirror
  // Providing a co.richText() instance to the plugin to automatically sync changes
  const jazzPlugin = createJazzPlugin(coRichText); 

  // Set up ProseMirror with Jazz plugin
  const view = new EditorView(container, {
    state: EditorState.create({
      schema,
      plugins: [
        ...exampleSetup({ schema }),
        jazzPlugin,
      ],
    }),
  });

  // Return cleanup function
  return () => {
    view.destroy();
  };
}

// Usage
const document = co.richText().create("<p>Initial content</p>", { owner: me });
const editorContainer = document.getElementById("editor");
const cleanup = setupRichTextEditor(document, editorContainer);

// Later when done with the editor
cleanup();