서식 있는 텍스트
Tiptap을 에디터 틀에 넣어 고정된 도구 모음, 필드의 상태, 데이터로 된 문서를 갖추세요.
이 페이지의 내용
Master UI에는 자체 에디터가 없습니다. 서식 있는 텍스트 편집, 즉 문서 모델, 선택 영역, 실행 기록, 붙여넣기, 입력기의 글자 조합은 대규모 엔진이 할 일이며, 이미 좋은 엔진이 있습니다. Master UI는 그런 엔진에 틀을 제공합니다. editor 계약이 편집 영역, 도구 모음, 상태, 문서 콘텐츠의 모양을 정하므로, 서식 있는 텍스트 필드가 페이지의 다른 모든 필드와 같은 모양과 동작을 갖습니다. 이 가이드에서는 일반 JavaScript로 Tiptap을 이 틀에 넣습니다.
서식 있는 텍스트
<div class="grid gap-lg w-full max-w(720) mx-auto" data-example="rich-text"> <div class="field"> <span id="rich-text-label">Release notes</span> <div class="editor"> <div class="toolbar editor-toolbar" role="toolbar" aria-label="Formatting" aria-controls="rich-text-document"> <select class="select select-sm" data-command="style" aria-label="Text style"> <option value="paragraph">Paragraph</option> <option value="heading">Heading</option> <option value="subheading">Subheading</option> </select> <span class="toolbar-separator" role="separator" aria-orientation="vertical"></span> <button type="button" class="btn btn-quiet btn-sm btn-square" data-command="bold" aria-label="Bold" aria-keyshortcuts="Control+B Meta+B" aria-pressed="false"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M4.6667 3H8.3333C12.3333 3 12.3333 7.6667 8.3333 7.6667H4.6667M4.6667 3V13H9C13.3333 13 13.3333 7.6667 9 7.6667" /> </svg> </button> <button type="button" class="btn btn-quiet btn-sm btn-square" data-command="italic" aria-label="Italic" aria-keyshortcuts="Control+I Meta+I" aria-pressed="false"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M6.6667 3L12.6667 3" /> <path d="M3.3333 13L9.3333 13" /> <path d="M9.6667 3L6.3333 13" stroke-linecap="butt" /> </svg> </button> <button type="button" class="btn btn-quiet btn-sm btn-square" data-command="underline" aria-label="Underline" aria-keyshortcuts="Control+U Meta+U" aria-pressed="false"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M4.3333 2.6667V7.6667C4.3333 12.3333 11.6667 12.3333 11.6667 7.6667V2.6667" /> <path d="M3 14L13 14" /> </svg> </button> <span class="toolbar-separator" role="separator" aria-orientation="vertical"></span> <button type="button" class="btn btn-quiet btn-sm btn-square" data-command="bulletList" aria-label="Bulleted list" aria-pressed="false"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <circle cx="3" cy="4" r="0.5" fill="currentColor" stroke="none" /> <path d="M6 4L13.5 4" /> <circle cx="3" cy="8" r="0.5" fill="currentColor" stroke="none" /> <path d="M6 8L13.5 8" /> <circle cx="3" cy="12" r="0.5" fill="currentColor" stroke="none" /> <path d="M6 12L13.5 12" /> </svg> </button> <button type="button" class="btn btn-quiet btn-sm btn-square" data-command="orderedList" aria-label="Numbered list" aria-pressed="false"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M2 3.3333L3 2.6667V6M2 6H4" stroke-width="0.8" /> <path d="M2 9.6667C2 8.3333 4 8.3333 4 9.6667C4 10.6667 2 11 2 12.6667H4" stroke-width="0.8" /> <path d="M6.6667 4.6667L14 4.6667" /> <path d="M6.6667 11.3333L14 11.3333" /> </svg> </button> <button type="button" class="btn btn-quiet btn-sm btn-square" data-command="blockquote" aria-label="Quotation" aria-pressed="false"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M2.7667 3.3333H6.2333Q6.6667 3.3333 6.6667 3.7667V8.6667C6.6667 11.3333 4.6667 12.6667 2.3333 12.6667V10.6667C4 10.6667 4.3333 9.6667 4.3333 8H2.7667Q2.3333 8 2.3333 7.5667V3.7667Q2.3333 3.3333 2.7667 3.3333Z" /> <path d="M9.7667 3.3333H13.2333Q13.6667 3.3333 13.6667 3.7667V8.6667C13.6667 11.3333 11.6667 12.6667 9.3333 12.6667V10.6667C11 10.6667 11.3333 9.6667 11.3333 8H9.7667Q9.3333 8 9.3333 7.5667V3.7667Q9.3333 3.3333 9.7667 3.3333Z" /> </svg> </button> <span class="toolbar-separator" role="separator" aria-orientation="vertical"></span> <button type="button" class="btn btn-quiet btn-sm btn-square" data-command="link" popovertarget="rich-text-link" aria-label="Link" aria-pressed="false"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M9 4.3333L10 3.3333C11.0125 2.3208 12.6541 2.3208 13.6667 3.3333C14.6792 4.3459 14.6792 5.9875 13.6667 7L11.6667 9C10.6541 10.0125 9.0125 10.0125 8 9" /> <path d="M9 4.3333L10 3.3333C11.0125 2.3208 12.6541 2.3208 13.6667 3.3333C14.6792 4.3459 14.6792 5.9875 13.6667 7L11.6667 9C10.6541 10.0125 9.0125 10.0125 8 9" transform="rotate(180 8 8)" /> </svg> </button> <span class="toolbar-separator" role="separator" aria-orientation="vertical"></span> <button type="button" class="btn btn-quiet btn-sm btn-square" data-command="undo" aria-label="Undo" aria-keyshortcuts="Control+Z Meta+Z"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M6 3L3.1414 5.8586A0.2 0.2 0 0 0 3.1414 6.1414L6 9" /> <path d="M2.715 6.4108A0.4996 0.4996 0 0 0 3 6.5H9.5A2.9999 2.9999 0 0 1 10.6043 12.2894Q10.0722 12.5 9.5 12.5L5.9755 12.5006A0.5 0.5 0 0 0 5.9266 13.4946L6 13.5H9.5A3.9999 3.9999 0 0 0 10.9724 5.7808Q10.263 5.5 9.5 5.5L2.9621 5.5014A0.5007 0.5007 0 0 0 2.715 5.5892A0.7044 0.7044 0 0 0 2.715 6.4108Z" fill="currentColor" stroke="none" fill-rule="evenodd" /> </svg> </button> <button type="button" class="btn btn-quiet btn-sm btn-square" data-command="redo" aria-label="Redo" aria-keyshortcuts="Control+Shift+Z Meta+Shift+Z"> <svg class="icon" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M6 3L3.1414 5.8586A0.2 0.2 0 0 0 3.1414 6.1414L6 9" transform="translate(16 0) scale(-1 1)" /> <path d="M2.715 6.4108A0.4996 0.4996 0 0 0 3 6.5H9.5A2.9999 2.9999 0 0 1 10.6043 12.2894Q10.0722 12.5 9.5 12.5L5.9755 12.5006A0.5 0.5 0 0 0 5.9266 13.4946L6 13.5H9.5A3.9999 3.9999 0 0 0 10.9724 5.7808Q10.263 5.5 9.5 5.5L2.9621 5.5014A0.5007 0.5007 0 0 0 2.715 5.5892A0.7044 0.7044 0 0 0 2.715 6.4108Z" fill="currentColor" stroke="none" fill-rule="evenodd" transform="translate(16 0) scale(-1 1)" /> </svg> </button> </div> <div class="flex flex-col" data-editor></div> </div> <p class="field-hint" id="rich-text-hint">Headings, lists, quotations and links. Pasted text keeps its structure, not its styling.</p> <p class="field-error" id="rich-text-error">Write at least a sentence before you publish.</p> </div> <form class="popover grid gap-sm w(288)" id="rich-text-link" popover aria-label="Link"> <label class="field">Address <input class="input input-sm" type="url" name="href" required placeholder="https://example.com" autocomplete="url"> </label> <div class="flex justify-end gap-xs"> <button type="button" class="btn btn-sm btn-quiet" data-command="unlink">Remove link</button> <button type="submit" class="btn btn-sm btn-primary">Apply</button> </div> </form> <div class="flex flex-wrap items-center gap-sm"> <label class="check"> <input type="checkbox" role="switch" class="switch" data-state="readonly">Read only</label> <label class="check"> <input type="checkbox" role="switch" class="switch" data-state="disabled">Disabled</label> <span class="grow(1)"></span> <button type="button" class="btn btn-sm" data-command="replace">Load other notes</button> <button type="button" class="btn btn-sm" data-command="reset">Reset</button> </div> <div class="accordion"> <details class="accordion-item"> <summary class="accordion-trigger">The value, as JSON <svg class="icon accordion-chevron" viewBox="0 0 16 16" fill="none" stroke="currentColor" stroke-width="1" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"> <path d="M6 3.5L10.3586 7.8586A0.2 0.2 0 0 1 10.3586 8.1414L6 12.5" transform="rotate(90 8 8)" /> </svg> </summary> <div class="accordion-content"> <pre class="code-block max-h(240)" tabindex="0" role="region" aria-label="The value, as JSON"><code data-value></code></pre> </div> </details> </div></div>import { Editor, Extension } from '@tiptap/core'import StarterKit from '@tiptap/starter-kit'import { toolbar } from '@master/ui/behaviors/toolbar.js'import { notes, other } from './content.js'/** * A heading writes the class of its level, so the editor styles it without selecting the element: Heading * itself renders no attribute for its level. */const headingClass = Extension.create({ name: 'headingClass', addGlobalAttributes() { return [{ types: ['heading'], attributes: { headingClass: { default: null, parseHTML: () => null, renderHTML: (attributes) => ({ class: attributes.level === 3 ? 'editor-subheading' : 'editor-heading' }), }, }, }] },})/** What the toolbar's buttons do, and how each asks whether it is on and whether it can run now. */const commands = { bold: { run: (chain) => chain.toggleBold(), active: 'bold' }, italic: { run: (chain) => chain.toggleItalic(), active: 'italic' }, underline: { run: (chain) => chain.toggleUnderline(), active: 'underline' }, bulletList: { run: (chain) => chain.toggleBulletList(), active: 'bulletList' }, orderedList: { run: (chain) => chain.toggleOrderedList(), active: 'orderedList' }, blockquote: { run: (chain) => chain.toggleBlockquote(), active: 'blockquote' }, undo: { run: (chain) => chain.undo() }, redo: { run: (chain) => chain.redo() },}/** * Tiptap in the editor frame. Tiptap owns the document, the selection, the history and the keys, an input * method's composition among them; this module only connects the toolbar and the states to it, and returns * the function that destroys it. */export function mount(root) { const controller = new AbortController() const { signal } = controller const frame = root.querySelector('.editor') const bar = root.querySelector('.editor-toolbar') const style = bar.querySelector('[data-command="style"]') const linkButton = bar.querySelector('[data-command="link"]') const form = root.querySelector('#rich-text-link') const output = root.querySelector('[data-value]') const states = { readonly: false, disabled: false } /** The document's own attributes: its role, its name, its description and its states. */ const attributes = () => ({ id: 'rich-text-document', class: 'editor-document', role: 'textbox', 'aria-multiline': 'true', 'aria-labelledby': 'rich-text-label', // A referenced node is read even while it is hidden: the error is named only while it shows. 'aria-describedby': invalid ? 'rich-text-hint rich-text-error' : 'rich-text-hint', // A document that cannot be edited is still read and scrolled with the keys; one that is disabled says so. ...(states.readonly ? { tabindex: '0' } : {}), ...(states.disabled ? { 'aria-disabled': 'true' } : {}), ...(states.readonly ? { 'aria-readonly': 'true' } : {}), ...(invalid ? { 'aria-invalid': 'true' } : {}), }) let invalid = false const editor = new Editor({ element: root.querySelector('[data-editor]'), content: notes, extensions: [ StarterKit.configure({ heading: { levels: [2, 3] }, paragraph: { HTMLAttributes: { class: 'editor-paragraph' } }, bulletList: { HTMLAttributes: { class: 'editor-list' } }, orderedList: { HTMLAttributes: { class: 'editor-list editor-list-numbered' } }, listItem: { HTMLAttributes: { class: 'editor-item' } }, blockquote: { HTMLAttributes: { class: 'editor-quote' } }, code: { HTMLAttributes: { class: 'code' } }, codeBlock: { HTMLAttributes: { class: 'code-block' } }, horizontalRule: { HTMLAttributes: { class: 'editor-rule' } }, // A link is followed with the keyboard or a modifier click outside the editor, never by a click while editing. link: { openOnClick: false, autolink: true, defaultProtocol: 'https', HTMLAttributes: { class: 'editor-link', rel: 'noopener noreferrer nofollow', target: null } }, }), headingClass, ], editorProps: { attributes: attributes() }, }) const detachToolbar = toolbar(bar) /** Say what the selection holds and what can run now, on the toolbar. */ function sync() { const editable = editor.isEditable for (const button of bar.querySelectorAll('button[data-command]')) { const command = commands[button.dataset.command] if (button === linkButton) { button.setAttribute('aria-pressed', String(editor.isActive('link'))) button.disabled = !editable continue } if (command.active) button.setAttribute('aria-pressed', String(editor.isActive(command.active))) // While the document can be edited, a tool that cannot run now says so and stays in the arrows' way; while it // cannot, the whole bar is disabled. button.disabled = !editable button.setAttribute('aria-disabled', String(editable && !command.run(editor.can().chain()).run())) } style.disabled = !editable style.value = editor.isActive('heading', { level: 2 }) ? 'heading' : editor.isActive('heading', { level: 3 }) ? 'subheading' : 'paragraph' } /** The value as data: what an application saves. It is written as text, never as markup. */ let pending = 0 function show() { cancelAnimationFrame(pending) pending = requestAnimationFrame(() => { output.textContent = JSON.stringify(editor.getJSON(), null, 2) }) } /** Draw the states the reader chose, and the invalid one, on the frame and the document. */ function mark() { editor.setEditable(!states.readonly && !states.disabled, false) editor.setOptions({ editorProps: { attributes: attributes() } }) if (states.disabled) frame.setAttribute('aria-disabled', 'true') else frame.removeAttribute('aria-disabled') sync() } editor.on('transaction', sync) editor.on('update', () => { show() // An error is cleared as soon as the reader writes again. if (invalid && !editor.isEmpty) { invalid = false mark() } }) // Empty on leaving: the error shows, as a field's does once the reader has tried. editor.on('blur', () => { if (editor.isEmpty && editor.isEditable && !invalid) { invalid = true mark() } }) bar.addEventListener('click', (click) => { const button = click.target.closest('button[data-command]') const command = button && commands[button.dataset.command] // Every tool hands focus back to the document, where the reader was writing. if (command) command.run(editor.chain().focus()).run() // The link button only opens its form: what it says comes from the selection, not from the press. if (button === linkButton) sync() }, { signal }) style.addEventListener('change', () => { const chain = editor.chain().focus() if (style.value === 'paragraph') chain.setParagraph().run() else chain.setHeading({ level: style.value === 'heading' ? 2 : 3 }).run() }, { signal }) // The link form opens with the link under the caret, and puts the address on the selection when sent. const field = form.elements.href form.addEventListener('toggle', (toggle) => { if (toggle.newState !== 'open') return field.value = editor.getAttributes('link').href ?? '' field.focus() }, { signal }) form.addEventListener('submit', (submit) => { submit.preventDefault() if (!field.reportValidity()) return const href = field.value const chain = editor.chain().focus().extendMarkRange('link') if (editor.state.selection.empty && !editor.isActive('link')) { chain.insertContent({ type: 'text', text: href, marks: [{ type: 'link', attrs: { href } }] }).run() } else { chain.setLink({ href }).run() } form.hidePopover() }, { signal }) form.querySelector('[data-command="unlink"]').addEventListener('click', () => { editor.chain().focus().extendMarkRange('link').unsetLink().run() form.hidePopover() }, { signal }) root.addEventListener('click', (click) => { const command = click.target.closest('[data-command]')?.dataset.command // A document from outside replaces the one in the editor, as loading a saved draft does. if (command === 'replace') editor.commands.setContent(other) if (command === 'reset') editor.commands.setContent(notes) }, { signal }) root.addEventListener('change', (change) => { const state = change.target.dataset?.state if (!state) return states[state] = change.target.checked mark() }, { signal }) sync() show() return () => { controller.abort() cancelAnimationFrame(pending) detachToolbar() editor.destroy() if (form.matches(':popover-open')) form.hidePopover() }}/** * Documents as Tiptap stores them: JSON, the data an application saves and loads. Nothing here is HTML, so * nothing a reader wrote is ever put into the page as markup. */export const notes = { type: 'doc', content: [ { type: 'heading', attrs: { level: 2 }, content: [{ type: 'text', text: 'Version 0.4' }] }, { type: 'paragraph', content: [ { type: 'text', text: 'Category colors arrive: ' }, { type: 'text', marks: [{ type: 'bold' }], text: 'twenty-three palettes' }, { type: 'text', text: ', each with a surface, a text, a line and a mark that keep their contrast in every theme.' }, ] }, { type: 'bulletList', content: [ { type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Badges and chips take a category.' }] }] }, { type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'A schedule shows a month and an agenda.' }] }] }, ] }, { type: 'paragraph', content: [ { type: 'text', text: 'Read the ' }, { type: 'text', marks: [{ type: 'link', attrs: { href: 'https://ui.master.co/components/category' } }], text: 'category guide' }, { type: 'text', text: ' before you choose one.' }, ] }, ],}export const other = { type: 'doc', content: [ { type: 'heading', attrs: { level: 3 }, content: [{ type: 'text', text: 'From the server' }] }, { type: 'blockquote', content: [{ type: 'paragraph', content: [{ type: 'text', marks: [{ type: 'italic' }], text: 'A component is a class on a native element.' }] }] }, { type: 'orderedList', content: [ { type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Read the contract.' }] }] }, { type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Write the markup.' }] }] }, { type: 'listItem', content: [{ type: 'paragraph', content: [{ type: 'text', text: 'Run the checker.' }] }] }, ] }, ],}#역할 분담
| 담당 | |
|---|---|
| Tiptap | 문서와 스키마, 선택 영역, 실행 취소와 다시 실행, 키와 단축키, 붙여넣기, 입력기, 편집 가능하게 만드는 요소 |
editor | 틀과 상태, 도구 모음 영역, 문서 크기, 문단·제목·목록·인용문·링크·구분선의 모양 |
toolbar와 그 동작 | 컨트롤을 Tab 키 이동 순서에서 한 지점으로 묶기, 컨트롤 사이의 방향키 이동, 눌린 버튼 |
| 페이지 | 둘을 연결하는 일: 각 버튼이 실행하는 명령, 버튼의 상태, 값을 보낼 곳 |
@master/ui는 어떤 에디터에도 의존하지 않으며, 에디터를 감싸는 React, Svelte, Vue 컴포넌트도 없습니다. 이 예제는 사이트 자체의 예제이며 Tiptap은 사이트의 의존성입니다. 예제를 복사하거나, 같은 방식으로 ProseMirror, Lexical 등 다른 엔진을 적용하세요. 계약은 바뀌지 않습니다.
#엔진을 틀에 넣기
Tiptap은 요소를 편집 가능하게 만들고 그 안에 문서를 작성합니다. 그 요소에 필드의 컨트롤이 갖는 역할, 이름, 설명과 함께 editor-document를 지정하도록 하고, 렌더링하는 노드에 에디터의 클래스를 작성하도록 Tiptap을 설정하세요. editor 스타일시트는 요소를 직접 선택하지 않으므로, 제목은 h2이기 때문이 아니라 editor-heading이 있기 때문에 스타일이 적용됩니다. 인라인 코드와 코드 블록에는 라이브러리의 코드 클래스를 사용합니다.
const editor = new Editor({ element: root.querySelector('[data-editor]'), content: notes, extensions: [ StarterKit.configure({ heading: { levels: [2, 3] }, paragraph: { HTMLAttributes: { class: 'editor-paragraph' } }, bulletList: { HTMLAttributes: { class: 'editor-list' } }, orderedList: { HTMLAttributes: { class: 'editor-list editor-list-numbered' } }, listItem: { HTMLAttributes: { class: 'editor-item' } }, blockquote: { HTMLAttributes: { class: 'editor-quote' } }, code: { HTMLAttributes: { class: 'code' } }, codeBlock: { HTMLAttributes: { class: 'code-block' } }, horizontalRule: { HTMLAttributes: { class: 'editor-rule' } }, link: { openOnClick: false, autolink: true, defaultProtocol: 'https', HTMLAttributes: { class: 'editor-link' } }, }), headingClass, ], editorProps: { attributes: { class: 'editor-document', role: 'textbox', 'aria-multiline': 'true', 'aria-labelledby': 'rich-text-label', 'aria-describedby': 'rich-text-hint rich-text-error' }, },})제목은 수준을 나타내는 속성을 렌더링하지 않으므로, 예제의 headingClass 같은 작은 확장이 수준마다 클래스를 지정합니다. 두 번째 수준에는 editor-heading을, 세 번째 수준에는 editor-subheading을 지정합니다. 문서는 --editor-rows줄(기본값 6줄)에서 --editor-max-rows줄까지 늘어난 뒤 스크롤됩니다.
#도구 모음 연결
도구 모음은 editor-toolbar를 지정한 도구 모음이며, 편집 영역 상단에 붙여 배치합니다. 도구 모음 동작은 이를 Tab 키 이동 순서에서 한 지점으로 만들어 방향키로 이동할 수 있게 하고, 버튼을 aria-pressed로 눌린 상태로 표시합니다. 각 버튼이 무엇을 하고 무엇을 알려 주는지는 페이지가 결정합니다.
- 버튼을 누르면 명령을 실행하고 포커스를 되돌립니다.
editor.chain().focus().toggleBold().run()을 실행하면 독자는 Tiptap이 유지한 선택 영역과 함께 작성하던 문서로 돌아갑니다. - 선택 영역이 눌린 상태를 결정합니다. 트랜잭션마다 각 버튼의
aria-pressed를editor.isActive(...)로 설정하므로, 캐럿이 굵은 텍스트 안에 있으면 어디서든 굵게 버튼이 눌린 상태로 읽히고, 텍스트 스타일 선택 메뉴에는 캐럿이 속한 블록의 스타일이 표시됩니다. - 실행할 수 없는 것은 비활성화합니다.
editor.can()은 문서를 변경하지 않고 명령을 실행할 수 있는지 확인합니다. 실행 취소할 내용이 없으면 실행 취소 버튼이 비활성화되고, 에디터가 읽기 전용이거나 비활성화되면 모든 컨트롤이 비활성화됩니다. - 링크는 프롬프트가 아니라 작은 폼입니다. 링크 버튼은 URL 필드가 있는 팝오버를 엽니다. 필드 자체의 유효성 검사가 주소를 확인하고, 적용 버튼은 선택 영역에 링크를 적용하거나 선택 영역이 없으면 주소를 텍스트로 삽입합니다. 제거 버튼은 링크를 제거합니다. Tiptap은
javascript:같은 주소를 거부하며, 링크에는rel="noopener noreferrer nofollow"가 지정됩니다.
각 아이콘 버튼에 이름을 지정하고, Tiptap이 이미 처리하는 단축키를 aria-keyshortcuts로 지정하세요. 그러면 스크린 리더가 둘 다 알려 줄 수 있습니다.
#상태
| 상태 | 표시 | 예제에서 설정하는 방법 |
|---|---|---|
| 포커스 | editor-document의 :focus | 문서에 포커스가 있으면 브라우저가 설정합니다. 틀이 필드의 포커스 링과 함께 강조됩니다. |
| 유효하지 않음 | editor-document의 aria-invalid="true" | 내용이 비어 있으면 틀에 오류 상태를 나타내는 테두리가 표시되고 필드의 field-error가 나타나며, 독자가 다시 작성할 때까지 유지됩니다. |
| 읽기 전용 | editor-document의 aria-readonly="true" | editor.setEditable(false)와 속성. 텍스트를 읽고 복사할 수 있습니다. |
| 비활성화 | editor의 aria-disabled="true" | editor.setEditable(false), 속성, 모든 컨트롤 비활성화 |
상태는 Tiptap이 자신의 요소에 유지하는 속성입니다. 요소에 직접 설정하지 말고 editor.setOptions({ editorProps: { attributes } })로 설정하세요. 그렇지 않으면 다음 렌더링에서 사라집니다.
#값
Tiptap의 문서는 데이터입니다. 애플리케이션은 editor.getJSON()의 반환값을 저장하고, 다른 메모 불러오기와 초기화 버튼처럼 editor.commands.setContent(json)으로 저장된 문서를 불러옵니다. 예제는 JSON을 textContent로 작성하므로, 독자가 입력한 내용이 마크업으로 페이지에 들어가지 않습니다. 에디터 밖에서 콘텐츠를 HTML로 표시해야 한다면 서버에서 JSON으로 HTML을 렌더링하고 새니타이저를 거치게 하세요.
저장이나 유효성 검사에는 update를, 도구 모음을 그릴 때는 transaction을 수신하세요. 둘 다 문서를 바꾸지 않습니다. 페이지는 문서에 별도의 키 처리기를 추가하지 않습니다. 일본어, 중국어, 한국어를 조합하는 입력기는 Enter 키와 방향키를 사용하며, Tiptap은 글자 조합이 진행 중인지 알고 있습니다. 유효성 검사는 키 입력이 아니라 blur에서 하세요.
#정리
에디터는 리스너, 뷰, 실행 기록을 보유합니다. mount()는 도구 모음 동작을 해제하고, 페이지의 리스너를 제거하고, editor.destroy()를 호출하는 함수를 반환합니다. 필드가 페이지에서 사라질 때, 예를 들어 프레임워크에서 컴포넌트가 마운트 해제될 때 이 함수를 호출하세요.
#이 예제에서 다루지 않는 것
- 선택 영역을 따라다니는 도구 모음. 선택한 텍스트 위에 떠 있는 도구 모음을 만들려면 선택 영역이 그려지는 위치를 추적해야 합니다. 이는 Tiptap의
BubbleMenu확장과 그 위치 지정 기능이 담당하며, 이 가이드에서는 도구 모음을 고정해 둡니다. - 멘션, 표, 이미지, 공동 편집. 각각 Tiptap 확장과 별도의 인터페이스가 필요합니다.
- Markdown 가져오기와 내보내기. 서버에서 JSON을 변환하세요.