Skip to content

Saving and loading ​

ts
import { advancedSchema } from '@writeon/advanced/schema'
import {
  createEditor,
  type DocJSON,
  debounce,
  type Editor,
} from '@writeon/core'
import { basic } from '@writeon/core/presets'
import { fromHTML, toHTML } from '@writeon/html'
import { fromMarkdown, toMarkdown } from '@writeon/markdown'

const extensions = [...basic(), advancedSchema()]

declare function saveDraft(doc: DocJSON): Promise<void>
declare const stored: DocJSON

// Save at most twice a second.
const save = debounce((editor: Editor) => {
  return saveDraft(editor.getJSON())
}, 500)

const editor = createEditor({
  extensions,
  content: stored,
  label: 'Draft',
  onChange: save,
})

// And once more before the page goes away.
window.addEventListener('pagehide', () => save.flush())

// Replace the whole document (not added to the undo history).
editor.setContent(stored)

// Other formats, always with the same extensions.
const doc = editor.getJSON()
const html = toHTML(doc, { extensions })
const markdown = toMarkdown(doc, { extensions })

const fromOldHtml = fromHTML('<p>Hello <b>world</b></p>', {
  extensions,
})
const fromReadme = fromMarkdown('# Title\n\n- one\n- two', {
  extensions,
})

export { fromOldHtml, fromReadme, html, markdown }

onChange ​

onChange runs after every change. Serializing the document on each keystroke is cheap for small documents, but for saving use debounce() from @writeon/core: it has flush() for the last pending call (before navigating away) and cancel().

HTML ​

@writeon/html converts both ways:

  • toHTML(doc, { extensions }) renders semantic HTML. It runs on the server too (no DOM needed).
  • fromHTML(html, { extensions }) parses HTML inside an inert <template>, so scripts and images in it never run or load. On the server, pass a document (for example from linkedom or jsdom).

officePaste() is an extension that cleans up pastes from Word and Google Docs.

Rendering user content

toHTML() trusts the document it is given. For documents that came from a browser, validate them first, or use toSafeHTML() from @writeon/server. See Security.

Markdown ​

@writeon/markdown reads and writes GitHub-flavoured Markdown, including tables and task lists. Raw HTML in Markdown stays text. Underline has no Markdown syntax and is dropped.

markdownPaste() turns pasted Markdown into formatted content; the parser is loaded the first time the editor gets focus.