Home

Awesome

<p align="center"><a href="https://medv.io/codejar/"><img src="https://medv.io/assets/codejar.svg" width="72"></a></p> <h3 align="center">CodeJar – an embeddable code editor for the browser</h3> <p align="center"><a href="https://medv.io/codejar/"><img src="https://medv.io/assets/codejar/screenshot.png" width="709"></a></p>

npm npm bundle size

Features

Getting Started

Install CodeJar 🍯   via npm:

npm i codejar

Create an element and init the CodeJar 🍯:

<div class="editor"></div>
<script>
  let jar = CodeJar(document.querySelector('.editor'), highlight)
</script>

Second argument to CodeJar is a highlighting function (like Prism.js, highlight.js):

const highlight = (editor: HTMLElement) => {
  const code = editor.textContent
  code = code.replace('foo', '<span style="color: red">foo</span>')
  editor.innerHTML = code
}

const jar = CodeJar(editor, highlight)

Third argument to CodeJar is options:

const options = {
  tab: ' '.repeat(4), // default is '\t'
  indentOn: /[(\[]$/, // default is /{$/
  autoclose: { 
    open: `([{*`, // default is `([{'"`
    close: `)]}*` // default is `)]}'"`
  }
}

const jar = CodeJar(editor, highlight, options)

API

updateCode(string)

Updates the code.

jar.updateCode(`let foo = bar`)

updateOptions(Partial<Options>)

Updates the options.

jar.updateOptions({tab: '\t'})

onUpdate((code: string) => void)

Calls callback on code updates.

jar.onUpdate(code => {
  console.log(code)
})

toString(): string

Return current code.

let code = jar.toString()

save(): string

Saves current cursor position.

let pos = jar.save()

restore(pos: Position)

Restore cursor position.

jar.restore(pos)

recordHistory()

Saves current editor state to history.

destroy()

Removes event listeners from editor.

Related

License

MIT