antonmedv / codejar

An embeddable code editor for the browser 🍯

Home Page:https://medv.io/codejar/

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

CodeJar – an embeddable code editor for the browser

npm npm bundle size

Features

  • Lightweight (2.45 kB only)
  • No dependencies
  • Preserves indentation on a new line
  • Adds closing brackets, quotes
  • Indents line with the Tab key
  • Supports undo/redo

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:

  • tab: string replaces "tabs" with given string. Default: \t.
    • Note: use css rule tab-size to customize size.
  • indentOn: RegExp allows auto indent rule to be customized. Default /[({\[]$/.
  • moveToNewLine: RegExp checks in extra newline character need to be added. Default /^[)}\]]/.
  • spellcheck: boolean enables spellchecking on the editor. Default false.
  • catchTab: boolean catches Tab keypress events and replaces it with tab string. Default: true.
  • preserveIdent: boolean keeps indent levels on new line. Default true.
  • addClosing: boolean automatically adds closing brackets, quotes. Default true.
  • history records history. Default true.
  • window window object. Default: window.
const options = {
  tab: ' '.repeat(4), // default is '\t'
  indentOn: /[(\[]$/, // 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

Become a sponsor

Every line of code in my repositories πŸ“– signifies my unwavering commitment to open source πŸ’‘. Your support 🀝 ensures these projects keep thriving, innovating, and benefiting all πŸ’Ό. If my work has ever resonated 🎡 or helped you, kindly consider showing love ❀️ by sponsoring. πŸš€ Sponsor Me Today! πŸš€

License

MIT

About

An embeddable code editor for the browser 🍯

https://medv.io/codejar/

License:MIT License


Languages

Language:TypeScript 90.7%Language:HTML 9.3%