Overview
The formatJustifyCenter inputType is triggered when the user applies center alignment to selected paragraphs. The browser sets text-align: center on the affected elements.
Basic Behavior
Scenario: Paragraph selected
Before (Paragraph selected)
HTML:
<p>This is a paragraph.</p>
After formatJustifyCenter
HTML:
<p style="text-align: center;">This is a paragraph.</p>
Text aligned to center
Editor-Specific Handling
Different editor frameworks handle text alignment similarly. Here's how major editors implement formatJustifyCenter:
Slate.js
Center Alignment
Slate applies alignment as a block property:
import { Editor, Transforms, Element } from 'slate';
element.addEventListener('beforeinput', (e) => {
if (e.inputType === 'formatJustifyCenter') {
e.preventDefault();
Transforms.setNodes(editor, {
align: 'center',
}, {
match: n => Element.isElement(n) && Editor.isBlock(editor, n),
});
}
});
- Block property: Alignment is stored as a property on block elements.
- Transforms.setNodes: Sets
align: 'center'on selected blocks.
ProseMirror
Center Alignment
ProseMirror uses block attribute:
view.dom.addEventListener('beforeinput', (e) => {
if (e.inputType === 'formatJustifyCenter') {
e.preventDefault();
const { state, dispatch } = view;
const { $from } = state.selection;
const blockType = schema.nodes.paragraph;
const tr = state.tr.setBlockType($from.before(), $from.after(), blockType, {
...blockType.attrs,
align: 'center',
});
dispatch(tr);
}
});
- Block attribute: Alignment is stored as an attribute on block nodes.
Draft.js
Center Alignment
Draft.js uses block-level styles:
function handleJustifyCenter(editorState) {
return RichUtils.toggleBlockType(editorState, 'center');
}
- Block type: Uses block type for alignment.