Copy and paste text with its colors, weights, decorations and lists, between text blocks and from other apps.
Text blocks read and write their formatted content as HTML. engine.block.getTextAsHTML() returns a range of a text block as HTML with inline CSS. The HTML states the color, background color, weight, italic, decorations, script style, case, font size, letter spacing and typeface of each run. It also states the list style, list level, alignment and line height of each paragraph. engine.block.replaceTextWithHTML() replaces a range with the text and formatting of HTML. This is the same text/html format that browsers and other apps put on the clipboard.
This guide covers the built-in copy and paste, copying formatted text between blocks, pasting HTML from other apps, handling HTML without text, and connecting your own input to the clipboard.
Using the Built-in Copy and Paste#
In text edit mode, Ctrl+C, Ctrl+X and Ctrl+V (Cmd on macOS) keep the formatting of the selected text. The editor writes both plain text and HTML to the clipboard, so a paste into another app also keeps the formatting. Text from another app keeps its formatting when it is pasted into a text block. The editor needs no code for this. Paste and Match Style pastes the plain text in the style at the cursor.
Canva reads only the plain text of a copy from CE.SDK, because Canva ignores the formatting of other apps.
A paste of plain text, or of HTML that holds no text, such as a copied image, inserts the plain text of the clipboard.
Create the Text Blocks#
We create text blocks that use a typeface with bold and italic fonts, and we format ranges of the first block. The ranges are UTF-16 indices [from, to).
// Create three text blocks that use a typeface with bold and italic fontsconst createTextBlock = (y: number): DesignBlockId => { const block = engine.block.create('text'); engine.block.appendChild(page, block); engine.block.setPositionX(block, 50); engine.block.setPositionY(block, y); engine.block.setWidth(block, 700); engine.block.setHeightMode(block, 'Auto'); engine.block.setFont( block, ROBOTO_TYPEFACE.fonts[0].uri, ROBOTO_TYPEFACE ); engine.block.setTextFontSize(block, 36, { unit: 'Pixel' }); return block;};const source = createTextBlock(40);const copy = createTextBlock(140);const pasted = createTextBlock(240);
// Format ranges of the source block, using UTF-16 indicesengine.block.replaceText(source, 'Bold, italic and red text');engine.block.setTextFontWeight(source, 'bold', 0, 4);engine.block.setTextFontStyle(source, 'italic', 6, 12);engine.block.setTextColor(source, { r: 1, g: 0, b: 0, a: 1 }, 17, 20);engine.block.toggleTextDecorationUnderline(source, 21, 25);Copy Formatted Text Between Blocks#
We read the source block as HTML with engine.block.getTextAsHTML() and write it to the second block with engine.block.replaceTextWithHTML(). HTML from getTextAsHTML() sets every format it carries, the typeface and the font size included. The typeface applies only when a typeface of the scene holds its font file. Otherwise the text keeps the typeface at the insert position, with the weight and style of the source.
// Read the whole source block as HTML and replace the text of the copy.// HTML from getTextAsHTML() restores every format, typeface and font size included.const html = engine.block.getTextAsHTML(source);engine.block.replaceTextWithHTML(copy, html);Without a range, both calls use the whole text. While a user edits the block, they use the selection instead, and replaceTextWithHTML() moves the cursor behind the inserted text.
Copy a Range#
We pass from and to to copy a part of a block. To insert without replacing text, we pass the same index twice, here the length of the text. An empty range returns an empty string.
// Copy only " red" and insert it at the end of the copy.// The same index for `from` and `to` inserts without replacing.const redHtml = engine.block.getTextAsHTML(source, 16, 20);const end = engine.block.getString(copy, 'text/text').length;engine.block.replaceTextWithHTML(copy, redHtml, end, end);Paste HTML From Other Apps#
We pass HTML from any source to engine.block.replaceTextWithHTML(). HTML from apps such as Google Docs, Word, a web page or an Apple app sets weight, italic, decorations, script style and case. It also sets the text color, background color, font size, letter spacing, line height, lists and alignment. Markup that is not supported keeps only its text.
// HTML from another app sets weight, italic, decorations, colors, lists, the font size,// the letter spacing and the line height. Its font family applies when a typeface of the// asset sources has that family. Otherwise the text keeps the typeface of the block.engine.block.replaceTextWithHTML( pasted, '<p style="line-height:1.5"><b style="font-size:24px">Bold</b> and ' + '<span style="color:#ff0000">red</span></p><ul><li>item</li></ul>');The pasted text takes the first font family of the HTML that a typeface of the asset sources has. Without such a typeface, it keeps the typeface of the block. A CSS px is one pixel of a scene whose font size unit is the pixel, so the size reads as in the source app. A gray, black or white that covers the largest part of the pasted text is the default color of the source app. It does not replace the color of the block, and the same rule applies to the background color. A pasted paragraph without a list keeps the list of the target paragraph.
Paste and Match Style#
Paste and Match Style pastes only the plain text, which takes the style at the cursor, as typed text does. In the editor in Chrome, Edge and Firefox, it is Cmd+Shift+V on macOS and Ctrl+Shift+V on Windows and Linux. These browsers give the paste only the plain text. A custom input does the same with engine.block.replaceText() and the text/plain of the clipboard.
Handle HTML Without Text#
When the HTML holds no text, replaceTextWithHTML() throws an engine error with the code BLOCK.TEXT_HTML_HAS_NO_TEXT and changes nothing. We narrow the error with isEngineError() and insert the plain text with engine.block.replaceText() instead. Other errors are thrown again.
/** * Inserts HTML with its formatting. HTML without text, such as a copied * image, makes the engine throw and change nothing, so insert the plain * text instead. */function pasteHTMLOrText( engine: CreativeEngine, block: DesignBlockId, html: string, plainText: string): void { try { engine.block.replaceTextWithHTML(block, html); } catch (error) { if (isEngineError(error) && error.code === 'BLOCK.TEXT_HTML_HAS_NO_TEXT') { engine.block.replaceText(block, plainText); } else { throw error; } }}The Error Catalog lists every error code. Here, we paste HTML that holds only an image:
// This HTML holds only an image, so the plain text is inserted insteadconst fallback = createTextBlock(400);pasteHTMLOrText( engine, fallback, '<p><img src="https://img.ly/static/ubq_samples/sample_1.jpg"></p>', 'Plain text instead of an image');Connect a Custom Input to the Clipboard#
We add a text field with a paste and a copy event handler. The paste handler reads text/html and text/plain from clipboardData, calls preventDefault(), and replaces the text of the selected text block. The copy handler writes the HTML of the block and its plain text, so apps without HTML support still get the text.
// A custom text field that moves formatted text between the system// clipboard and the selected text blockconst input = document.createElement('textarea');input.placeholder = 'Select a text block, then paste or copy here';input.style.cssText = 'position:fixed;bottom:16px;left:50%;transform:translateX(-50%);width:320px;z-index:1000;';document.body.appendChild(input);
const selectedTextBlock = (): DesignBlockId | undefined => engine.block .findAllSelected() .find((block) => engine.block.getType(block) === '//ly.img.ubq/text');
input.addEventListener('paste', (event: ClipboardEvent) => { const block = selectedTextBlock(); const clipboard = event.clipboardData; if (block == null || clipboard == null) { return; } event.preventDefault(); const plainText = clipboard.getData('text/plain'); const pastedHtml = clipboard.getData('text/html'); if (pastedHtml === '') { engine.block.replaceText(block, plainText); } else { pasteHTMLOrText(engine, block, pastedHtml, plainText); }});
input.addEventListener('copy', (event: ClipboardEvent) => { const block = selectedTextBlock(); const clipboard = event.clipboardData; if (block == null || clipboard == null) { return; } event.preventDefault(); // Write both formats, so apps without HTML support get the plain text clipboard.setData( 'text/plain', engine.block.getString(block, 'text/text') ); clipboard.setData('text/html', engine.block.getTextAsHTML(block));});Scopes#
Without the text/character scope, replaceTextWithHTML() inserts only the text, with the style at the insert position. Without the fill/change scope, or when the text color is bound to a variable, no color is pasted. When the font size or the typeface of the block is bound to a variable, it is not pasted. See Lock Design to set scopes.
API Reference#
| Method | Purpose |
|---|---|
engine.block.getTextAsHTML() |
Get a UTF-16 range of a text block as HTML with its formatting |
engine.block.replaceTextWithHTML() |
Replace a range with the text and formatting of HTML |
engine.block.replaceText() |
Insert plain text, for HTML without text |
engine.block.getString() |
Read the plain text with 'text/text', for example to find the end index |
isEngineError() |
Narrow a caught error to read its code |
Troubleshooting#
Pasted text has a different typeface than in the source app: No typeface of the asset sources has the font family of the source app, so the text keeps the typeface of the block. Add that typeface to an asset source. See Text Styling.
Pasted text is much smaller or larger than the block: The paste keeps the font size of the source app. In Chrome, Edge and Firefox, paste with Cmd+Shift+V or Ctrl+Shift+V to paste the plain text in the style of the block.
A paste into Canva has no formatting: Canva reads only the plain text of other apps.
Bold or italic text does not show: The typeface of the block has no bold or italic font. Use a typeface that has these fonts.
The paste throws an error: The HTML holds no text, and the error code is BLOCK.TEXT_HTML_HAS_NO_TEXT. Insert the plain text of the clipboard instead.
The text color of the paste is not used: A gray, black or white that covers the largest part of the pasted text does not change the color of the block. The same rule applies to the background color. Other colors are used, unless the block does not allow the fill/change scope or its text color is bound to a variable.
Next Steps#
- Edit Text: replace, remove and format text with range-based APIs.
- Text Decorations: add underline, strikethrough and overline to text ranges.