# Text styles from code

> Change text and Fabric.js setSelectionStyles ranges from code without moving bold, color or font onto the wrong letters, with one undo step per edit.

Source: https://fabricjs-document-engine.jscrate.dev/docs/guides/text-styles
Last updated: 2026-10-02

Fabric.js keeps the style of each letter by its position: line 0, letter 6 is bold. When code changes `text`, those positions do not move, so after an insert the bold word is no longer the bold word ([fabric.js #6133](https://github.com/fabricjs/fabric.js/issues/6133)). Fabric.js setSelectionStyles changes the style of a range, but it does not help when the text itself changes. `insertChars` and `removeChars` do move styles, but they fire no event, and while the user types they leave the hidden textarea behind.

## Try it

```tsx
"use client";

import { IText } from "fabric";
import { createTextCommands } from "fabricjs-document-engine";
import { useDocumentEngine } from "fabricjs-document-engine/react";
import {
  BoldIcon,
  RotateCcwIcon,
  TextCursorIcon,
  Undo2Icon,
  WandIcon,
} from "lucide-react";
import { useTranslations } from "next-intl";
import { useEffect, useRef, useState } from "react";

import { DemoCanvas, DemoFrame, Status, Toolbar, ToolButton } from "./demo-ui";
import { useFabricCanvas } from "./use-fabric-canvas";

const STRONG = { fontWeight: "bold", fill: "#6f00ff" } as const;

function makeText() {
  return new IText("Hello world", {
    left: 40,
    top: 110,
    originX: "left",
    originY: "top",
    fontSize: 46,
    fill: "#0d0d0d",
    styles: { 0: { 6: STRONG, 7: STRONG, 8: STRONG, 9: STRONG, 10: STRONG } },
  });
}

export default function TextCommandsDemo() {
  const t = useTranslations("demos");
  const { elementRef, canvas } = useFabricCanvas();
  const engine = useDocumentEngine(canvas);
  const textRef = useRef<IText | null>(null);
  const [message, setMessage] = useState("");

  function reset() {
    if (!engine) return;
    if (textRef.current) engine.canvas.remove(textRef.current);
    const text = makeText();
    textRef.current = text;
    engine.canvas.add(text);
    engine.clearHistory();
    engine.canvas.requestRenderAll();
    setMessage("");
  }

  useEffect(reset, [engine]);

  function current() {
    return engine?.getObjectById(
      (textRef.current as unknown as { id: string } | null)?.id ?? ""
    ) as IText | undefined;
  }

  function insertWithCommands() {
    const text = current();
    if (!engine || !text) return;
    createTextCommands(engine).insertText(text, 0, "Oh, ");
    setMessage(t("textCommands.inserted"));
  }

  function setDirectly() {
    const text = current();
    if (!engine || !text) return;
    text.set("text", `Oh, ${text.text}`);
    engine.canvas.requestRenderAll();
    setMessage(t("textCommands.direct"));
  }

  function boldFirstWord() {
    const text = current();
    if (!engine || !text) return;
    const end = [...text.text].indexOf(" ");
    createTextCommands(engine).setTextStyle(
      text,
      0,
      end === -1 ? text.text.length : end,
      { fontWeight: "bold" }
    );
    setMessage(t("textCommands.styled"));
  }

  async function undo() {
    if (!engine) return;
    await engine.undo();
    textRef.current = engine.canvas.getObjects()[0] as IText;
    setMessage(t("textCommands.undone"));
  }

  return (
    <DemoFrame>
      <DemoCanvas elementRef={elementRef} label={t("canvas")} />

      <Toolbar>
        <ToolButton
          icon={WandIcon}
          label={t("textCommands.insert")}
          primary
          disabled={!engine}
          onClick={insertWithCommands}
        />
        <ToolButton
          icon={TextCursorIcon}
          label={t("textCommands.setText")}
          disabled={!engine}
          onClick={setDirectly}
        />
        <ToolButton
          icon={BoldIcon}
          label={t("textCommands.bold")}
          disabled={!engine}
          onClick={boldFirstWord}
        />
        <ToolButton
          icon={Undo2Icon}
          label={t("undo")}
          iconOnly
          disabled={!engine}
          onClick={() => void undo()}
        />
        <ToolButton
          icon={RotateCcwIcon}
          label={t("textCommands.reset")}
          iconOnly
          disabled={!engine}
          onClick={reset}
        />
      </Toolbar>

      <Status tone={message ? "ok" : "idle"}>
        {message || t("textCommands.hint")}
      </Status>
    </DemoFrame>
  );
}
```

```tsx
import { Canvas } from "fabric";
import { useLayoutEffect, useRef, useState } from "react";

/**
 * The page every demo draws on. The document keeps this size; CSS scales the
 * canvas down to fit its card, so saved documents and exports never depend on
 * the screen.
 */
export const PAGE = { width: 480, height: 300 };

// Selection handles in the site's style. Fabric does not save these.
const SELECTION = {
  borderColor: "#6f00ff",
  borderScaleFactor: 1.5,
  borderOpacityWhenMoving: 0.5,
  cornerStyle: "circle",
  cornerSize: 11,
  cornerColor: "#ffffff",
  cornerStrokeColor: "#6f00ff",
  transparentCorners: false,
} as const;

export function styleSelection(canvas: Canvas) {
  canvas.set({
    selectionColor: "rgba(111, 0, 255, 0.06)",
    selectionBorderColor: "#6f00ff",
    selectionLineWidth: 1,
  });
  const style = () => canvas.getActiveObject()?.set(SELECTION);
  canvas.on("selection:created", style);
  canvas.on("selection:updated", style);
}

/**
 * Creates a Fabric.js canvas once the `<canvas>` element exists, and disposes
 * it on unmount. The engine is created from the returned `canvas`.
 */
export function useFabricCanvas({ width, height } = PAGE) {
  const elementRef = useRef<HTMLCanvasElement>(null);
  const [canvas, setCanvas] = useState<Canvas | null>(null);

  // A layout effect creates the canvas before the first paint.
  useLayoutEffect(() => {
    const created = new Canvas(elementRef.current!, {
      width,
      height,
      backgroundColor: "#ffffff",
    });
    styleSelection(created);
    setCanvas(created);

    return () => {
      // Dispose after the engine's own cleanup, so its last recovery copy
      // still sees the objects.
      setTimeout(() => created.dispose().catch(() => undefined));
    };
  }, [width, height]);

  return { elementRef, canvas };
}
```

```tsx
import { Circle, type FabricObject, Rect, Triangle } from "fabric";
import type { LucideIcon } from "lucide-react";

import { cn } from "@/lib/utils";

import { PAGE } from "./use-fabric-canvas";

export const COLORS = ["#f2836f", "#5fe6c4", "#7ad9ec", "#6f00ff", "#ffd666"];

// Demo shapes are placed by their top-left corner, like a design tool.
const CORNER = { originX: "left", originY: "top" } as const;

/** A new shape at a random spot on the page. */
export function newShape(kind: "square" | "circle", fill?: string) {
  const left = 40 + Math.random() * (PAGE.width - 160);
  const top = 30 + Math.random() * (PAGE.height - 120);
  const color = fill ?? COLORS[Math.floor(Math.random() * COLORS.length)];
  return kind === "square"
    ? new Rect({
        ...CORNER,
        left,
        top,
        width: 88,
        height: 64,
        rx: 10,
        ry: 10,
        fill: color,
      })
    : new Circle({ ...CORNER, left, top, radius: 34, fill: color });
}

/** A small composed drawing, so no demo starts on an empty page. */
export function seedShapes(): FabricObject[] {
  return [
    new Rect({
      ...CORNER,
      left: 48,
      top: 56,
      width: 176,
      height: 124,
      rx: 16,
      ry: 16,
      fill: COLORS[4],
    }),
    new Circle({ ...CORNER, left: 268, top: 44, radius: 58, fill: COLORS[0] }),
    new Rect({
      ...CORNER,
      left: 256,
      top: 196,
      width: 176,
      height: 52,
      rx: 26,
      ry: 26,
      fill: COLORS[1],
    }),
    new Triangle({
      ...CORNER,
      left: 96,
      top: 196,
      width: 72,
      height: 60,
      fill: COLORS[3],
    }),
  ];
}

export function DemoFrame({
  className,
  ...props
}: React.ComponentProps<"div">) {
  return (
    <div
      className={cn(
        "flex w-full max-w-md flex-col gap-3 text-left outline-none",
        className
      )}
      {...props}
    />
  );
}

/**
 * Scales the fixed-size Fabric canvas to the frame's width. The rules are
 * `!important` because Fabric writes its sizes as inline styles.
 */
export function DemoCanvas({
  elementRef,
  label,
  page = PAGE,
  children,
}: {
  elementRef: React.Ref<HTMLCanvasElement>;
  label: string;
  page?: { width: number; height: number };
  children?: React.ReactNode;
}) {
  return (
    <div
      className="relative overflow-hidden rounded-lg border bg-white shadow-xs [&_.canvas-container]:aspect-(--page)! [&_.canvas-container]:h-auto! [&_.canvas-container]:w-full! [&_canvas]:h-full! [&_canvas]:w-full!"
      style={
        { "--page": `${page.width} / ${page.height}` } as React.CSSProperties
      }
    >
      <div>
        <canvas ref={elementRef} aria-label={label} />
      </div>
      {children}
    </div>
  );
}

export function Toolbar({ className, ...props }: React.ComponentProps<"div">) {
  return (
    <div
      className={cn("flex flex-wrap items-center gap-1.5", className)}
      {...props}
    />
  );
}

export function ToolButton({
  icon: Icon,
  label,
  iconOnly = false,
  primary = false,
  className,
  ...props
}: React.ComponentProps<"button"> & {
  icon: LucideIcon;
  label: string;
  iconOnly?: boolean;
  primary?: boolean;
}) {
  return (
    <button
      type="button"
      title={label}
      aria-label={iconOnly ? label : undefined}
      className={cn(
        "inline-flex h-8 min-w-0 items-center justify-center gap-1.5 rounded-md border px-2.5 text-[13px] font-medium whitespace-nowrap transition-colors disabled:pointer-events-none disabled:opacity-40 [&_svg]:size-3.5 [&_svg]:shrink-0",
        primary
          ? "border-transparent bg-foreground text-background hover:bg-foreground/85"
          : "bg-background hover:bg-muted",
        iconOnly && "w-8 px-0",
        className
      )}
      {...props}
    >
      <Icon aria-hidden />
      {!iconOnly && <span className="truncate">{label}</span>}
    </button>
  );
}

const TONES = {
  idle: "bg-zinc-400",
  busy: "bg-amber-400",
  ok: "bg-emerald-500",
  error: "bg-red-500",
};

/** One line of status text. Its height never changes, so the card never jumps. */
export function Status({
  tone = "idle",
  children,
}: {
  tone?: keyof typeof TONES;
  children: React.ReactNode;
}) {
  return (
    <p
      role="status"
      className="flex h-5 min-w-0 items-center gap-2 text-[13px] text-muted-foreground"
    >
      <span
        aria-hidden
        className={cn("size-1.5 shrink-0 rounded-full", TONES[tone])}
      />
      <span className="truncate">{children}</span>
    </p>
  );
}
```

**Set text directly** shows the problem: the bold, purple text color stays on the old letters. **Insert with commands** keeps it on "world".

## Edit text without losing styles

```ts
import { createTextCommands } from "fabricjs-document-engine";

const text = createTextCommands(engine);

text.insertText(title, 0, "New: ");
text.replaceText(title, 5, 9, "Big", { fontWeight: "bold" });
text.deleteText(title, 0, 5);
text.setTextStyle(title, 0, 3, { fill: "#6f00ff" });
```

- Positions count graphemes, as the cursor does, so an emoji is one letter.
- Inserted text takes the style of the letter before it, or the `style` you pass. `null` inserts it without style.
- The cursor, the selection and the hidden textarea follow the edit, even while the user is typing.
- `changed` and `text:changed` fire, so the document is marked unsaved.
- Each command is one undo step.

`setTextStyle` merges a style into a range like Fabric.js setSelectionStyles does, and records the undo step for you. All of this works for rich text in IText, Textbox and their subclasses.

## Several edits as one step

The functions behind the commands, `replaceTextRange` and `setTextRangeStyle`, record nothing on their own. Wrap them in a transaction:

```ts
import { replaceTextRange } from "fabricjs-document-engine";

engine.transaction("Rename", () => {
  replaceTextRange(title, 0, 5, "Hello");
  replaceTextRange(subtitle, 0, 0, "Draft: ");
});
```

Styles are moved as runs of `{ start, end, style }`, so an edit costs the number of runs, not the number of letters. `shiftStyleRuns` is exported for your own text tools.

For typing on phones see [Typing on phones](https://fabricjs-document-engine.jscrate.dev/docs/guides/mobile-text-input), and for undo grouping [Undo and redo](https://fabricjs-document-engine.jscrate.dev/docs/guides/undo-redo). Every signature is in the [Text API](https://fabricjs-document-engine.jscrate.dev/docs/api/text-api), next to Fabric.js setSelectionStyles helpers you may still use.
