Ribbon, panes and rulersDocument
The ribbon of Birch UI Document Editor and how to customise it, the File tab, the mini toolbar, the rulers with tab stops, the styles, navigation and find panes, view modes, autocorrect, paste options and autosave.
The editor opens with a ribbon: a File tab for opening, saving, downloading and printing, and Home, Insert, Draw, Layout, References, Review and View tabs with groups of commands, galleries and menus. Pass ribbon: false for the classic single-row toolbar; passing a toolbar item list also selects the classic toolbar, and toolbar: false without a ribbon option hides the chrome completely.
import { createDocumentEditor } from '@birchui/document';
const editor = createDocumentEditor(host, {
ribbon: {
hiddenTabs: ['references'],
hiddenControls: ['subscript', 'superscript'],
groupOrder: { home: ['styles', 'font', 'paragraph'] },
custom: [
{
tab: 'home',
group: 'matter',
label: 'Matter',
controls: [
{
id: 'fileToMatter',
label: 'File to matter',
icon: 'field',
size: 'large',
run: (api) => fileToMatter(api.getJSON()),
isDisabled: (api) => api.isReadOnly(),
},
],
},
],
},
});Customising the ribbon#
RibbonConfig key |
Effect |
|---|---|
tabs |
The tabs to show, in order. Leave it out for the six standard tabs followed by any custom ones. |
hiddenTabs, hiddenGroups, hiddenControls |
Ids to hide. A group can be written as 'insert/links' to hide it on one tab only. |
groupOrder |
Per tab, the group ids that come first. |
tabLabels |
Replacement labels by tab id. |
custom |
Your own groups. A new tab id creates a tab; tabLabel names it. Controls are buttons or toggles with run, isPressed and isDisabled callbacks that receive the editor API. |
activeTab, collapsed, keyTips |
The tab selected at start, whether the ribbon starts collapsed, and false to turn the Alt key tips off. |
Recipes#
A review-only ribbon with a renamed tab, two controls removed and the Protect group hidden:
createDocumentEditor(host, {
ribbon: {
tabs: ['home', 'review'],
tabLabels: { review: 'Negotiate' },
hiddenControls: ['formatPainter', 'compareDialog'],
hiddenGroups: ['review/protect'],
activeTab: 'review',
},
});Your own tab with a button that calls your application, disabled while the document is empty:
createDocumentEditor(host, {
ribbon: {
custom: [
{
tab: 'contract',
tabLabel: 'Contract',
group: 'workflow',
label: 'Workflow',
controls: [
{
id: 'sendForSignature',
label: 'Send for signature',
size: 'large',
keyTip: 'SS',
run: (api) => sendForSignature(api.getJSON()),
isDisabled: (api) => api.getWordCount().words === 0,
},
],
},
],
},
});A custom group can also join a standard tab (tab: 'review'); order places it among the groups of that tab. Put Styles first on the Home tab, start collapsed and turn key tips off:
createDocumentEditor(host, {
ribbon: { groupOrder: { home: ['styles', 'font'] }, collapsed: true, keyTips: false },
});Switch between the ribbon and the classic toolbar at run time with editor.update({ ribbon: false }) and editor.update({ ribbon: true }). Control ids are the data-tool attributes of the buttons and group ids the data-group attributes of the groups (history, clipboard, font, paragraph, styles and find on the Home tab).
getRibbonTab(), setRibbonTab(id), isRibbonCollapsed() and setRibbonCollapsed(flag) drive the ribbon from code, and ribbonTabChange fires when the tab changes. When the window is too narrow for every group, groups fold into one button each, with the icon of the group over its name and a chevron beside the name; the button opens the group as a menu. Undo and Editing fold first, then Styles, Clipboard and Paragraph, and the Font group last. Below 640 px the ribbon becomes a single scrolling row with a tab switcher and touch-sized buttons, the document zooms to the width of the screen, and panes and dialogs open as bottom sheets.
The File tab#
File is the first entry of the tab row. It opens a panel over the document with every command that concerns the document as a whole, each with an icon, a one-line description and its shortcut:
| Section | Entries (FileItemId) |
|---|---|
| Document | New (new), Open (open, Ctrl+O), Save (save, Ctrl+S) |
| Download as | Word (downloadDocx), PDF (downloadPdf), OpenDocument (downloadOdt), web page (downloadHtml), Markdown (downloadMarkdown), plain text (downloadText) |
| Print and page | Print (print, Ctrl+P), Page setup (pageSetup) |
| About this document | Document properties (properties), Version history (versionHistory), Protect with a password (password), Keyboard shortcuts (shortcuts, Ctrl+/) |
Open reads Word (.docx, .docm, .dotx), Word 97–2003 (.doc), OpenDocument (.odt), RTF, web page (.html), Markdown and plain text files. The format is taken from the bytes of the file first and from its name second, so a .docx file that is really an RTF file still opens. A file that cannot be read is reported in a dialog and through the fileError event, and the document that was open stays as it was. New and Open ask first when the document has changes that were neither saved nor downloaded.
The File name field at the top of the panel names the downloads; it starts as the name of the opened file, or the title of the document.
With the keyboard: Alt then F opens the panel, the arrow keys, Home and End move between its entries, Enter runs one and Escape returns to the document.
Saving to your own storage#
Without options, Save and Ctrl+S download a .docx file. Pass onSaveRequest to save somewhere else, and onOpenRequest or onNewRequest to replace the file chooser or the empty document with your own document list. A callback that returns false hands the request back to the editor.
const editor = createDocumentEditor(host, {
file: {
fileName: 'Master services agreement',
hidden: ['downloadMarkdown', 'downloadText'],
onSaveRequest: async ({ editor }) => {
await api.saveDraft(matterId, editor.getJSON());
},
onOpenRequest: () => false,
},
});
editor.on('fileSaved', ({ fileName, target }) => showStatus(`${fileName} saved (${target})`));
editor.on('fileError', ({ action, error }) => showBanner(action, error));file: false removes the tab and its shortcuts, and ribbon: { hiddenTabs: ['file'] } removes only the tab. A hidden entry loses its shortcut too, so with hidden: ['open'] Ctrl+O is left to the browser.
New from template#
The File tab lists templates under New from template: yours first, then four built-in ones (letter, report, meeting notes and résumé). Choosing one replaces the document with a copy of the template, after a confirmation when there are changes that were not saved.
import type { DocumentInput } from '@birchui/document';
declare function fetchTemplate(id: string): Promise<DocumentInput>;
const editor = createDocumentEditor(host, {
file: {
templates: [
{
id: 'delivery-note',
name: 'Delivery note',
description: 'Consignee, items and signature',
content: () => fetchTemplate('delivery-note'), // a DocumentInput, or a function that returns or resolves to one
},
],
builtinTemplates: false, // leave out the four built-in ones
},
});
editor.getTemplates(); // [{ id, name, description, isBuiltin }]
await editor.newFromTemplate('delivery-note'); // does not ask first
editor.exec('newFromTemplate', 'report'); // asks first when there are unsaved changeshidden: ['templates'] removes the section. A template of yours with the id of a built-in one replaces it. The templateOpened event carries { id, name }. The text of the built-in templates is English; pass your own templates for other languages.
Files from code#
const format = await editor.openFile(file);
const pdf = await editor.exportFile('pdf');
await editor.downloadFile('odt', 'Agreement for signature');
editor.setFileName('Agreement v2');
if (editor.isModified()) await editor.saveFile();openFile(input, { fileName?, format?, password? }) takes a File, a Blob, an ArrayBuffer or a Uint8Array, returns the format it found ('docx', 'doc', 'odt', 'rtf', 'html', 'markdown' or 'text') and rejects with a FileOpenError, a DocumentFormatError, a DocFormatError or a ZipLimitError without changing the document. exportFile(format, { password? }) returns a Blob and downloadFile(format, fileName?) saves it; the formats are 'docx', 'pdf', 'odt', 'html', 'markdown' and 'text'. newDocument() empties the editor without asking. openFileMenu(), closeFileMenu() and isFileMenuOpen() drive the panel, which also opens from the classic toolbar with exec('fileMenu').
Password-protected Word files#
A .docx file that Word or LibreOffice saved with a password (Encrypt with password) opens after the editor asks for the password; a wrong password asks again and leaves the open document alone. Both encryption schemes that Office writes are read: the agile scheme of Office 2010 and later and the standard scheme of Office 2007. A document opened this way is saved and downloaded encrypted with the same password. File → Protect with a password sets a password on any document, changes it or removes it; from then on Save and Download as → Word document write an encrypted file (AES-256, SHA-512, 100,000 rounds). The other formats are never encrypted.
await editor.openFile(file, { password: 'harbour-42' });
editor.hasFilePassword(); // true
const sealed = await editor.exportFile('docx'); // encrypted with the same password
const plain = await editor.exportFile('docx', { password: null });
editor.setFilePassword(null); // later saves are not encryptedWithout a password openFile rejects with a FileOpenError whose code is 'password-required', and with the wrong one 'wrong-password'. Encryption uses the Web Crypto API, so the page must be served over HTTPS or from localhost. The password is kept in memory only; it is not part of getJSON() and is forgotten by newDocument(). Hide the entry with file: { hidden: ['password'] }.
Document mode and zoom#
At the end of the tab row a Document mode list switches between three ways of working. Editing changes the document directly. Reviewing turns track changes on, so every change is recorded as an insertion or a deletion. Viewing makes the document read-only. The list follows setTrackChanges and setReadOnly when they are called from code, and each change is announced to screen readers. When track changes is locked by the document protection, choosing Editing leaves it on and says so. The narrow layout leaves the list out.
The status bar ends with a zoom slider from 25% to 400% in steps of 5% and the current percentage; it follows setZoom and the zoom commands of the View tab.
Search commands#
The box at the end of the tab row finds a command by what it does. Alt+Q puts the cursor in it from anywhere in the editor. Type a few letters and the list shows the matching commands with their icon, the tab or menu they live in and their shortcut:
- It looks through every control of the ribbon tabs that are shown, the items of their menus and galleries (Narrow under Margins, Heading 2 under Paragraph style, Page number under Insert field) and the entries of the File tab.
- It also knows other words for a command: "cross out" finds Strikethrough, "hyperlink" finds Link, "redline" finds Track changes and "export" finds the downloads. Every word typed has to match somewhere, so "margins layout" works too.
- Up and Down move through the list and Enter runs the highlighted command on the selection that was active before, opens its dialog, or shows its menu on the tab where it lives when it needs a choice. Escape clears the box and returns to the document.
- A command that cannot run at the moment (a formatting command in a read-only document, for example) is listed dimmed and does nothing.
The box is a combobox with a listbox for screen readers, and the number of matches is announced. In the narrow layout a search button (a magnifying glass beside the tab switcher, 40 by 44 px) takes its place and opens the same box over the document, and the tab switcher lists Search commands as well; exec('commandSearch') does that from code and with the classic toolbar. Turn the feature off with commandSearch: false.
The other words are translated with the interface: each is a document.search.words.<control id> key holding a comma-separated list, so you can add the vocabulary of your own users.
createDocumentEditor(host, {
localeText: {
'document.search.words.trackChanges': 'revisions, redline, suggesting, markup',
'document.search.words.fileToMatter': 'archive, case file',
},
});Mini toolbar#
Selecting text with the mouse (or with Shift+arrow keys) shows a small formatting toolbar above the selection. It never takes focus by itself; press F6 to move into it and Escape to dismiss it. Typing and scrolling dismiss it too. Turn it off with miniToolbar: false.
Rulers and tab stops#
The horizontal ruler has markers for the first-line, hanging, left and right indents and for the page margins. Click the ruler to add a tab stop of the kind shown in the selector at its start (left, centre, right or decimal), drag a stop to move it and drag it off the ruler to remove it. verticalRuler: true adds a vertical ruler with the top and bottom margins.
editor.setTabStops([
{ position: 150, align: 'left' },
{ position: 451, align: 'right', leader: 'dot' },
]);
editor.getTabStops();
editor.exec('tabsDialog');Positions are points from the start margin. Tab stops are stored on the paragraph (attrs.tabs) and are read from and written to DOCX. A tab character advances to the next stop; right, centre and decimal stops align the text that follows, and leader fills the gap with dots, dashes or a line. Without custom stops a tab advances to the next half inch.
Styles, navigation and find panes#
| Command | Pane |
|---|---|
stylesPane |
The paragraph styles with previews. Apply a style, create one from the selection, modify it, update it to match the selection or delete it. |
navigationPane |
The heading outline as a tree: collapse branches, jump to a heading, promote and demote headings, move a section with its sub-sections up or down, and search the document. |
findPane, replacePane |
Find and replace with match case, whole words and regular expressions and a list of the results in context. |
openPane(id), closePane(id) and isPaneOpen(id) work with the ids 'styles', 'navigation' and 'find'.
Custom styles are part of the document: getStyles(), createStyle(name, format, basedOn), createStyleFromSelection(name), modifyStyle(id, format, name?), updateStyleToMatchSelection(id), deleteStyle(id) and applyStyle(id). They are saved in DocumentData.styles and restored by setJSON; stylesChange fires after every change.
Paragraph, list and page commands#
| Command | Value | Effect |
|---|---|---|
fontDialog, paragraphDialog, bordersDialog, tabsDialog, pageSetupDialog, columnsDialog, noteOptionsDialog, hyperlinkDialog, pasteSpecialDialog, multilevelDialog, numberFormatDialog, autocorrectDialog, documentPropertiesDialog |
Open the dialogs; see Editing dialogs. | |
fontFormat |
FontFormat |
Font, size, colour, underline style and colour, effects, character spacing, scale, position and kerning. |
hyperlink |
HyperlinkOptions or null |
Links the selection to an address, an e-mail address or a heading; null removes the link. |
revealFormatting, clearCharacterFormatting, clearParagraphFormatting, clearCharacterStyle |
The Reveal formatting pane (Shift+F1) and its clear actions. | |
defaultTabStop, documentProperties |
points, DocumentProperties |
The default tab stops and the properties of the document. |
paragraphFormat |
ParagraphFormat |
Alignment, outline level, indents, spacing, contextual spacing, lineRule ('auto', 'exact', 'atLeast') with lineHeightPt, keep with next, keep lines together, widow control and page break before. |
paragraphBorders, paragraphShading |
ParagraphBorders, colour |
Borders per side and a background colour. |
applyListFormat |
{ type, style } |
A bullet or numbering format from the list library. |
defineMultilevelList, applyMultilevelList |
definition, id | Multilevel numbering such as 1 / 1.1 / 1.1.1. Custom definitions are saved in DocumentData.lists. |
changeCase, cycleCase |
'sentence' | 'lower' | 'upper' | 'capitalize' | 'toggle' |
Change case; Shift+F3 cycles. |
dropCap |
'none' | 'drop' | 'margin' or { mode, lines } |
A drop cap on the paragraph. |
symbolDialog, dateTimeDialog, insertDateTime, wordCountDialog |
Symbols, the current date and time, and the word count of the document or the selection. | |
insertBreak |
'page' | 'column' | 'sectionNextPage' | 'sectionContinuous' |
Breaks. |
columns |
number or { count, gap, separator } |
The number of text columns of the section, saved in page.columns. |
lineNumbers |
{ restart, countBy } or null |
Line numbers in the margin, saved in DocumentData.lineNumbers. |
watermark, watermarkDialog |
text or { text, rotation, opacity, color } |
A text watermark on every page, saved in DocumentData.watermark. |
formatPainterLock |
Keeps the format painter on until Escape; double-clicking the brush does the same. | |
formattingMarks |
true, false or nothing to toggle |
Shows paragraph marks, spaces, tabs, non-breaking spaces and hyphens, and optional hyphens (Ctrl+Shift+8, Show formatting marks on the Home tab). |
insertSpecialCharacter |
'nonBreakingSpace' | 'nonBreakingHyphen' | 'optionalHyphen' | 'emDash' | 'enDash' | 'ellipsis' | 'zeroWidthJoiner' | 'zeroWidthNonJoiner' |
Inserts the character at the cursor. |
Emoji#
Insert → Emoji opens a grid of 80 emoji in five groups (smileys, people and gestures, work and objects, signs, travel and places). The arrow keys move through the grid and Enter inserts. editor.exec('insertEmoji', '🚚') inserts any emoji, also one made of several code points.
Formatting marks and hyphenation#
const editor = createDocumentEditor(host, { showFormattingMarks: true, hyphenation: true });
editor.exec('formattingMarks', false);
editor.exec('insertSpecialCharacter', 'nonBreakingSpace');
editor.update({ hyphenation: false });showFormattingMarks starts the editor with the marks shown. The marks are drawn on screen only: they are not part of the document, the print or the PDF. hyphenation: true lets the browser hyphenate words at line ends (hyphens: auto), using the language of the page (<html lang>, or English when the page has none), which needs a browser with a hyphenation dictionary for that language; an optional hyphen marks a break point by hand and works without a dictionary. Both options are off by default.
View modes and appearance#
viewMode: 'read' (or setViewMode('read'), exec('readMode')) hides the ribbon and rulers and makes the document read-only; 'focus' hides the chrome but keeps editing, and shows an Exit focus mode button with its Esc key in the top corner. Escape returns to the editing view and viewModeChange reports the change. fitZoom('width' | 'page') sets and returns the zoom that fits the page.
theme: 'auto' | 'light' | 'dark' selects the colour scheme ('auto' follows the operating system) and darkPage: 'dark' also darkens the page.
Autocorrect#
Autocorrect is on by default: smart quotes and apostrophes, -- to an em dash, - to an en dash, (c), (r) and (tm), fractions such as 1/2, superscript ordinals, lists started with * , - , 1. or a) and links for web and e-mail addresses. Pressing Backspace straight after a correction undoes only the correction. Nothing is corrected in Code paragraphs or during IME composition.
createDocumentEditor(host, {
autocorrect: { autoCapitalize: true, fractions: false, replacements: { msa: 'Master Services Agreement' } },
});Pass autocorrect: false to turn it off. People change these settings in the AutoCorrect options dialog; autocorrectStorage keeps what they chose.
Paste#
Content pasted from Microsoft Word, Google Docs and LibreOffice is cleaned first: Office markup is removed, Word's list paragraphs become real nested lists, and bold, italic, underline, colours, highlight, font sizes, alignment, headings, links and tables are kept. Ctrl+Shift+V pastes the words without their formatting. After a paste a Paste options button appears below the pasted text; it opens a list with Keep source formatting, Merge formatting, Keep text only, Picture and Paste special…, and choosing one redoes the paste in that format, and Ctrl+Alt+V opens the Paste special dialog with the same choices. defaultPasteMode sets the default, pasteOptions: false hides the button, and pasteHtml(html, mode?), exec('pasteMode', mode) and exec('pasteText') do the same from code.
Autosave#
const editor = createDocumentEditor(host, {
autosave: { delay: 2000, save: (data) => api.saveDraft(matterId, data) },
});
editor.on('autosaveError', ({ error }) => showBanner(error));
await editor.saveNow();save runs delay milliseconds after the last change (2000 by default), may return a promise, and is called once more when the editor is destroyed with unsaved changes. autosaveStart, autosaveEnd and autosaveError report progress and isSaving() tells you whether a save is running.