Giter Club home page Giter Club logo

svelte-jsoneditor's Introduction

svelte-jsoneditor

A web-based tool to view, edit, format, transform, and validate JSON.

Try it out: https://jsoneditoronline.org

The library is written with Svelte, but can be used in plain JavaScript too and in any framework (SolidJS, React, Vue, Angular, etc).

JSONEditor tree mode screenshot JSONEditor text mode screenshot JSONEditor table mode screenshot

Features

  • View and edit JSON
  • Has a low level text editor and high level tree view and table view
  • Format (beautify) and compact JSON
  • Sort, query, filter, and transform JSON
  • Repair JSON
  • JSON schema validation and pluggable custom validation
  • Color highlighting, undo/redo, search and replace
  • Utilities like a color picker and timestamp tag
  • Handles large JSON documents up to 512 MB

Install

For usage in a Svelte project:

npm install svelte-jsoneditor

For usage in vanilla JavaScript or frameworks like SolidJS, React, Vue, Angular, etc:

npm install vanilla-jsoneditor

Use

Examples

Svelte usage

Create a JSONEditor with two-way binding bind:json:

<script>
  import { JSONEditor } from 'svelte-jsoneditor'

  let content = {
    text: undefined, // can be used to pass a stringified JSON document instead
    json: {
      array: [1, 2, 3],
      boolean: true,
      color: '#82b92c',
      null: null,
      number: 123,
      object: { a: 'b', c: 'd' },
      string: 'Hello World'
    }
  }
</script>

<div>
  <JSONEditor bind:content />
</div>

Or one-way binding:

<script>
  import { JSONEditor } from 'svelte-jsoneditor'

  let content = {
    text: undefined, // can be used to pass a stringified JSON document instead
    json: {
      greeting: 'Hello World'
    }
  }

  function handleChange(updatedContent, previousContent, { contentErrors, patchResult }) {
    // content is an object { json: unknown } | { text: string }
    console.log('onChange: ', { updatedContent, previousContent, contentErrors, patchResult })
    content = updatedContent
  }
</script>

<div>
  <JSONEditor {content} onChange="{handleChange}" />
</div>

Vanilla bundle (use in React, Vue, Angular, plain JavaScript, ...)

The library provides a vanilla bundle of the editor via the npm library vanilla-jsoneditor (instead of svelte-jsoneditor) which can be used in any browser environment and framework. In a framework like React, Vue, or Angular, you'll need to write some wrapper code around the class interface.

If you have a setup for your project with a bundler (like Vite, Rollup, or Webpack), it is best to use the default ES import:

// for use in a React, Vue, or Angular project
import { JSONEditor } from 'vanilla-jsoneditor'

If you want to use the library straight in the browser, use the provided standalone ES bundle:

// for use directly in the browser
import { JSONEditor } from 'vanilla-jsoneditor/standalone.js'

The standalone bundle contains all dependencies of vanilla-jsoneditor, for example lodash-es and Ajv. If you use some of these dependencies in your project too, it means that they will be bundled twice in your web application, leading to a needlessly large application size. In general, it is preferable to use the default import { JSONEditor } from 'vanilla-jsoneditor' so dependencies can be reused.

Browser example loading the standalone ES module:

<!doctype html>
<html lang="en">
  <head>
    <title>JSONEditor</title>
  </head>
  <body>
    <div id="jsoneditor"></div>

    <script type="module">
      import { JSONEditor } from 'vanilla-jsoneditor/standalone.js'

      // Or use it through a CDN (not recommended for use in production):
      // import { JSONEditor } from 'https://unpkg.com/vanilla-jsoneditor/standalone.js'
      // import { JSONEditor } from 'https://cdn.jsdelivr.net/npm/vanilla-jsoneditor/standalone.js'

      let content = {
        text: undefined,
        json: {
          greeting: 'Hello World'
        }
      }

      const editor = new JSONEditor({
        target: document.getElementById('jsoneditor'),
        props: {
          content,
          onChange: (updatedContent, previousContent, { contentErrors, patchResult }) => {
            // content is an object { json: unknown } | { text: string }
            console.log('onChange', { updatedContent, previousContent, contentErrors, patchResult })
            content = updatedContent
          }
        }
      })

      // use methods get, set, update, and onChange to get data in or out of the editor.
      // Use updateProps to update properties.
    </script>
  </body>
</html>

Wrapper libraries for specific frameworks

To make it easier to use the library in your framework of choice, you can use a wrapper library:

API

constructor

Svelte component:

<script>
  import { JSONEditor } from 'svelte-jsoneditor'

  let content = { text: '[1,2,3]' }
</script>

<div>
  <JSONEditor {content} />
</div>

JavasScript class:

import { JSONEditor } from 'vanilla-jsoneditor' // or 'vanilla-jsoneditor/standalone.js'

const content = { text: '[1,2,3]' }

const editor = new JSONEditor({
  target: document.getElementById('jsoneditor'),
  props: {
    content,
    onChange: (updatedContent, previousContent, { contentErrors, patchResult }) => {
      // content is an object { json: unknown } | { text: string }
      console.log('onChange', { updatedContent, previousContent, contentErrors, patchResult })
    }
  }
})

properties

Properties such as content and mode are either passed as attributes to the Svelte component, like <JSONEditor {content} {mode} />, or via the props in case of the vanilla JS constructor: new JSONEditor({ target, props: { content, mode }.

content

content: Content

Pass the JSON contents to be rendered in the JSONEditor. Content is an object containing a property json (a parsed JSON document) or text (a stringified JSON document). Only one of the two properties must be defined. You can pass both content types to the editor independent of in what mode it is. You can use two-way binding via bind:content.

IMPORTANT: only make immutable changes to content. Mutable changes will mess up history and rendered contents. See section Immutability.

selection

selection: JSONEditorSelection | null

The current selected contents. You can use two-way binding using bind:selection. The tree mode supports MultiSelection, KeySelection, ValueSelection, InsideSelection, or AfterSelection. The table mode supports ValueSelection, and text mode supports TextSelection..

mode

mode: 'tree' | 'text' | 'table'

Open the editor in 'tree' mode (default), 'table' mode, or 'text' mode (formerly: code mode).

mainMenuBar

mainMenuBar: boolean

Show the main menu bar. Default value is true.

navigationBar

navigationBar: boolean

Show the navigation bar with, where you can see the selected path and navigate through your document from there. Default value is true.

statusBar

statusBar: boolean

Show a status bar at the bottom of the 'text' editor, showing information about the cursor location and selected contents. Default value is true.

askToFormat

askToFormat: boolean

When true (default), the user will be asked whether he/she wants to format the JSON document when a compact document is loaded or pasted in 'text' mode. Only applicable to 'text' mode.

readOnly

readOnly: boolean

Open the editor in read-only mode: no changes can be made, non-relevant buttons are hidden from the menu, and the context menu is not enabled. Default value is false.

indentation

indentation: number | string

Number of spaces use for indentation when stringifying JSON, or a string to be used as indentation like '\t' to use a tab as indentation, or ' ' to use 4 spaces (which is equivalent to configuring indentation: 4). See also property tabSize.

tabSize

tabSize: number

When indentation is configured as a tab character (indentation: '\t'), tabSize configures how large a tab character is rendered. Default value is 4. Only applicable to text mode.

escapeControlCharacters

escapeControlCharacters: boolean

False by default. When true, control characters like newline and tab are rendered as escaped characters \n and \t. Only applicable for 'tree' mode, in 'text' mode control characters are always escaped.

escapeUnicodeCharacters

escapeUnicodeCharacters: boolean

False by default. When true, unicode characters like ☎ and 😀 are rendered escaped like \u260e and \ud83d\ude00.

flattenColumns

flattenColumns: boolean

True by default. Only applicable to 'table' mode. When true, nested object properties will be displayed each in their own column, with the nested path as column name. When false, nested objects will be rendered inline, and double-clicking them will open them in a popup.

validator

validator: function (json: unknown): ValidationError[]

Validate the JSON document. For example use the built-in JSON Schema validator powered by Ajv:

import { createAjvValidator } from 'svelte-jsoneditor'

const validator = createAjvValidator({ schema, schemaDefinitions })

parser

parser: JSON = JSON

Configure a custom JSON parser, like lossless-json. By default, the native JSON parser of JavaScript is used. The JSON interface is an object with a parse and stringify function. For example:

<script>
  import { JSONEditor } from 'svelte-jsoneditor'
  import { parse, stringify } from 'lossless-json'

  const LosslessJSONParser = { parse, stringify }

  let content = { text: '[1,2,3]' }
</script>

<div>
  <JSONEditor {content} parser="{LosslessJSONParser}" />
</div>

validationParser

validationParser: JSONParser = JSON

Only applicable when a validator is provided. This is the same as parser, except that this parser is used to parse the data before sending it to the validator. Configure a custom JSON parser that is used to parse JSON before passing it to the validator. By default, the built-in JSON parser is used. When passing a custom validationParser, make sure the output of the parser is supported by the configured validator. So, when the validationParser can output bigint numbers or other numeric types, the validator must also support that. In tree mode, when parser is not equal to validationParser, the JSON document will be converted before it is passed to the validator via validationParser.parse(parser.stringify(json)).

pathParser

pathParser: JSONPathParser

An optional object with a parse and stringify method to parse and stringify a JSONPath, which is an array with property names. The pathParser is used in the path editor in the navigation bar, which is opened by clicking the edit button on the right side of the navigation bar. The pathParser.parse function is allowed to throw an Error when the input is invalid. By default, a JSON Path notation is used, which looks like $.data[2].nested.property. Alternatively, it is possible to use for example a JSON Pointer notation like /data/2/nested/property or something custom-made. Related helper functions: parseJSONPath and stringifyJSONPath, parseJSONPointer and compileJSONPointer.

onError

onError(err: Error)

Callback fired when an error occurs. Default implementation is to log an error in the console and show a simple alert message to the user.

onChange

onChange(content: Content, previousContent: Content, changeStatus: { contentErrors: ContentErrors | null, patchResult: JSONPatchResult | null })

The callback which is invoked on every change of the contents made by the user from within the editor. It will not trigger on changes that are applied programmatically via methods like .set(), .update(), or .patch().

The returned content is sometimes of type { json }, and sometimes of type { text }. Which of the two is returned depends on the mode of the editor, the change that is applied, and the state of the document (valid, invalid, empty). Please be aware that { text } can contain invalid JSON: whilst typing in text mode, a JSON document will be temporarily invalid, like when the user is typing a new string. The parameter patchResult is only returned on changes that can be represented as a JSON Patch document, and for example not when freely typing in text mode.

onChangeMode

onChangeMode(mode: 'tree' | 'text' | 'table')

Invoked when the mode is changed.

onClassName

onClassName(path: Path, value: any): string | undefined

Add a custom class name to specific nodes, based on their path and/or value. Note that in the custom class, you can override CSS variables like --jse-contents-background-color to change the styling of a node, like the background color. Relevant variables are:

--jse-contents-background-color
--jse-selection-background-color
--jse-selection-background-inactive-color
--jse-hover-background-color
--jse-context-menu-pointer-hover-background
--jse-context-menu-pointer-background
--jse-context-menu-pointer-background-highlight
--jse-collapsed-items-background-color
--jse-collapsed-items-selected-background-color

To adjust the text color of keys or values, the color of the classes .jse-key and .jse-value can be overwritten.

onRenderValue

onRenderValue(props: RenderValueProps) : RenderValueComponentDescription[]

Customize rendering of the values. By default, renderValue is used, which renders a value as an editable div and depending on the value can also render a boolean toggle, a color picker, and a timestamp tag. Multiple components can be rendered alongside each other, like the boolean toggle and color picker being rendered left from the editable div. Built in value renderer components: EditableValue, ReadonlyValue, BooleanToggle, ColorPicker, TimestampTag, EnumValue.

For JSON Schema enums, there is a ready-made value renderer renderJSONSchemaEnum which renders enums using the EnumValue component. This can be used like:

import { renderJSONSchemaEnum, renderValue } from 'svelte-jsoneditor'

function onRenderValue(props) {
  // use the enum renderer, and fallback on the default renderer
  return renderJSONSchemaEnum(props, schema, schemaDefinitions) || renderValue(props)
}

The callback onRenderValue must return an array with one or multiple renderers. Each renderer can be either a Svelte component or a Svelte action:

interface SvelteComponentRenderer {
  component: typeof SvelteComponent<RenderValuePropsOptional>
  props: Record<string, unknown>
}

interface SvelteActionRenderer {
  action: Action // Svelte Action
  props: Record<string, unknown>
}

The SvelteComponentRenderer interface can be used to provide Svelte components like the EnumValue component mentioned above. The SvelteActionRenderer expects a Svelte Action as action property. Since this interface is a plain JavaScript interface, this allows to create custom components in a vanilla JS environment. Basically it is a function that gets a DOM node passed, and needs to return an object with update and destroy functions:

const myRendererAction = {
  action: (node) => {
    // attach something to the HTML DOM node
    return {
      update: (node) => {
        // update the DOM
      },
      destroy: () => {
        // cleanup the DOM
      }
    }
  }
}

onRenderMenu

onRenderMenu(items: MenuItem[], context: { mode: 'tree' | 'text' | 'table', modal: boolean, readOnly: boolean }) : MenuItem[] | undefined

Callback which can be used to make changes to the menu items. New items can be added, or existing items can be removed or reorganized. When the function returns undefined, the original items will be applied.

Using the context values mode, modal, and readOnly, different actions can be taken depending on the mode of the editor and whether the editor is rendered inside a modal or not, or depending on whether it is read-only.

A menu item MenuItem can be one of the following types:

  • Button:

    interface MenuButton {
      type: 'button'
      onClick: () => void
      icon?: IconDefinition
      text?: string
      title?: string
      className?: string
      disabled?: boolean
    }
  • Separator (gray vertical line between a group of items):

    interface MenuSeparator {
      type: 'separator'
    }
  • Space (fills up empty space):

    interface MenuSpace {
      type: 'space'
    }

onRenderContextMenu

onRenderContextMenu(items: ContextMenuItem[], context: { mode: 'tree' | 'text' | 'table', modal: boolean, readOnly: boolean, selection: JSONEditorSelection | null }) : ContextMenuItem[] | false | undefined

Callback which can be used to make changes to the context menu items. New items can be added, or existing items can be removed or reorganized. When the function returns undefined, the original items will be applied and the context menu will be displayed when readOnly is false. When the function returns false, the context menu will never be displayed. The callback is triggered too when the editor is readOnly, and in most cases you want to return false then.

Using the context values mode, modal, readOnly and selection, different actions can be taken depending on the mode of the editor, whether the editor is rendered inside a modal or not, whether the editor is read-only or not, and depending on the path of selection.

A menu item ContextMenuItem can be one of the following types:

  • Button:

    interface MenuButton {
      type: 'button'
      onClick: () => void
      icon?: IconDefinition
      text?: string
      title?: string
      className?: string
      disabled?: boolean
    }
  • Dropdown button:

    interface MenuDropDownButton {
      type: 'dropdown-button'
      main: MenuButton
      width?: string
      items: MenuButton[]
    }
  • Separator (gray line between a group of items):

    interface MenuSeparator {
      type: 'separator'
    }
  • Menu row and column:

    interface MenuLabel {
      type: 'label'
      text: string
    }
    
    interface ContextMenuColumn {
      type: 'column'
      items: Array<MenuButton | MenuDropDownButton | MenuLabel | MenuSeparator>
    }
    
    interface ContextMenuRow {
      type: 'row'
      items: Array<MenuButton | MenuDropDownButton | ContextMenuColumn>
    }

onSelect

onSelect: (selection: JSONEditorSelection | null) => void

Callback invoked when the selection is changed. When the selection is removed, the callback is invoked with undefined as argument. In text mode, a TextSelection will be fired. In tree and table mode, a JSONSelection will be fired (which can be MultiSelection, KeySelection, ValueSelection, InsideSelection, or AfterSelection). Use typeguards like isTextSelection and isValueSelection to check what type the selection has.

queryLanguages

queryLanguages: QueryLanguage[]

Configure one or multiple query language that can be used in the Transform modal. The library comes with three languages:

import {
  jmespathQueryLanguage,
  lodashQueryLanguage,
  javascriptQueryLanguage
} from 'svelte-jsoneditor'

const allQueryLanguages = [jmespathQueryLanguage, lodashQueryLanguage, javascriptQueryLanguage]

By default, only javascriptQueryLanguage is loaded.

queryLanguageId

queryLanguageId: string

The id of the currently selected query language.

onChangeQueryLanguage

onChangeQueryLanguage: (queryLanguageId: string) => void

Callback function invoked when the user changes the selected query language in the TransformModal via the configuration button top right.

  • onFocus() callback fired when the editor got focus.
  • onBlur() callback fired when the editor lost focus.

methods

Methods can be called on a JSONEditor instance. In Svelte, you can create a reference and call a method like:

<script>
  let editor

  function logContents() {
    const content = editor.get() // using a method
    console.log(content)
  }
</script>

<JSONEditor bind:this={editor} />

In the vanilla editor, the constructor returns an instance:

const editor = new JSONEditor({ ... })

function logContents() {
  const content = editor.get() // using a method
  console.log(content)
}

Note that most methods are asynchronous and will resolve after the editor is re-rendered (on the next tick).

get

JSONEditor.prototype.get(): Content

Get the current JSON document.

IMPORTANT: do not mutate the received content, that will mess up history and rendered contents. See section Immutability.

set

JSONEditor.prototype.set(content: Content): Promise<void>

Replace the current content. Will reset the state of the editor. See also method update(content).

update

JSONEditor.prototype.update(content: Content): Promise<void>

Update the loaded content, keeping the state of the editor (like expanded objects). You can also call editor.updateProps({ content }). See also method set(content).

IMPORTANT: only apply immutable changes to content. Mutable changes will mess up history and rendered contents. See section Immutability.

patch

JSONEditor.prototype.patch(operations: JSONPatchDocument) : Promise<JSONPatchResult>

Apply a JSON patch document to update the contents of the JSON document. A JSON patch document is a list with JSON Patch operations.

IMPORTANT: only apply immutable changes to the contents. Mutable changes will mess up history and rendered contents. See section Immutability.

updateProps

JSONEditor.prototype.updateProps(props: Object): Promise<void>

Tpdate some or all of the properties. Updated content can be passed too; this is equivalent to calling update(content). Example:

editor.updateProps({
  readOnly: true
})

expand

JSONEditor.prototype.expand([callback: (path: Path) => boolean]): Promise<void>

Expand or collapse paths in the editor. The callback determines which paths will be expanded. If no callback is provided, all paths will be expanded. It is only possible to expand a path when all of its parent paths are expanded too. Examples:

  • editor.expand(path => true) expand all
  • editor.expand(path => false) collapse all
  • editor.expand(path => path.length < 2) expand all paths up to 2 levels deep

transform

JSONEditor.prototype.transform({ id?: string, rootPath?: [], onTransform: ({ operations: JSONPatchDocument, json: unknown, transformedJson: unknown }) => void, onClose: () => void })

Programmatically trigger clicking of the transform button in the main menu, opening the transform model. If a callback onTransform is provided, it will replace the build-in logic to apply a transform, allowing you to process the transform operations in an alternative way. If provided, onClose callback will trigger when the transform modal closes, both after the user clicked apply or cancel. If an id is provided, the transform modal will load the previous status of this id instead of the status of the editors transform modal.

scrollTo

JSONEditor.prototype.scrollTo(path: Path): Promise<void>

Scroll the editor vertically such that the specified path comes into view. Only applicable to modes tree and table. The path will be expanded when needed. The returned Promise is resolved after scrolling is finished.

findElement

JSONEditor.prototype.findElement(path: Path)

Find the DOM element of a given path. Returns null when not found.

acceptAutoRepair

JSONEditor.prototype.acceptAutoRepair(): Promise<Content>

In tree mode, invalid JSON is automatically repaired when loaded. When the repair was successful, the repaired contents are rendered but not yet applied to the document itself until the user clicks "Ok" or starts editing the data. Instead of accepting the repair, the user can also click "Repair manually instead". Invoking .acceptAutoRepair() will programmatically accept the repair. This will trigger an update, and the method itself also returns the updated contents. In case of text mode or when the editor is not in an "accept auto repair" status, nothing will happen, and the contents will be returned as is.

refresh

JSONEditor.prototype.refresh(): Promise<void>

Refresh rendering of the contents, for example after changing the font size. This is only available in text mode.

validate

JSONEditor.prototype.validate() : ContentErrors | null

Get all current parse errors and validation errors.

select

JSONEditor.prototype.select(newSelection: JSONEditorSelection | null)

Change the current selection. See also option selection.

focus

JSONEditor.prototype.focus(): Promise<void>

Give the editor focus.

destroy

JSONEditor.prototype.destroy(): Promise<void>

Destroy the editor, remove it from the DOM.

Utility functions

The library exports a set of utility functions. The exact definitions of those functions can be found in the TypeScript d

  • Rendering of values:
    • renderValue
    • renderJSONSchemaEnum
    • Components:
      • BooleanToggle
      • ColorPicker
      • EditableValue
      • EnumValue
      • ReadonlyValue
      • TimestampTag
  • Validation:
    • createAjvValidator
  • Query languages:
    • lodashQueryLanguage
    • javascriptQueryLanguage
    • jmespathQueryLanguage
  • Content:
    • isContent
    • isTextContent
    • isJSONContent
    • isLargeContent
    • toTextContent
    • toJSONContent
    • estimateSerializedSize
  • Selection:
    • isValueSelection
    • isKeySelection
    • isInsideSelection
    • isAfterSelection
    • isMultiSelection,
    • isEditingSelection
    • createValueSelection
    • createKeySelection
    • createInsideSelection,
    • createAfterSelection
    • createMultiSelection
  • Parser:
    • isEqualParser
  • Path:
    • parseJSONPath
    • stringifyJSONPath
  • Actions:
    • resizeObserver
    • onEscape
  • Typeguards:
    • isContentParseError
    • isContentValidationErrors
  • More: you can install immutable-json-patch and use its functions:
    • immutableJSONPatch
    • revertJSONPatch
    • parseJSONPointer
    • parsePath
    • parseFrom
    • compileJSONPointer
    • compileJSONPointerProp
    • getIn
    • setIn
    • updateIn
    • insertAt
    • existsIn
    • deleteIn

Types

The TypeScript types (like Content, JSONSelection, and JSONPatchOperation) are defined in the following source file:

https://github.com/josdejong/svelte-jsoneditor/blob/main/src/lib/types.ts

Styling

The editor can be styled using the available CSS variables. A full list with all variables can be found here:

https://github.com/josdejong/svelte-jsoneditor/blob/main/src/lib/themes/defaults.scss

Custom theme color

For example, to change the default blue theme color to anthracite:

<script>
  import { JSONEditor } from 'svelte-jsoneditor'

  let content = {
    text: undefined, // can be used to pass a stringified JSON document instead
    json: {
      string: 'Hello custom theme color :)'
    }
  }
</script>

<div class="my-json-editor">
  <JSONEditor bind:content />
</div>

<style>
  .my-json-editor {
    /* define a custom theme color */
    --jse-theme-color: #383e42;
    --jse-theme-color-highlight: #687177;
  }
</style>

Dark theme

The editor comes with a built-in dark theme. To use this theme:

  • Load the css file of the dark theme: themes/jse-theme-dark.css
  • Add the class name jse-theme-dark of the dark theme to the HTML container element where the editor is loaded.

It is possible to load styling of multiple themes, and toggle them by changing the class name (like jse-theme-dark) attached to the HTML container element.

Full Svelte example:

<script>
  import { JSONEditor } from 'svelte-jsoneditor'

  let content = {
    text: undefined, // can be used to pass a stringified JSON document instead
    json: {
      string: 'Hello dark theme :)'
    }
  }
</script>

<!-- use a theme by adding its name to the container class -->
<div class="my-json-editor jse-theme-dark">
  <JSONEditor bind:content />
</div>

<style>
  /* load one or multiple themes */
  @import 'svelte-jsoneditor/themes/jse-theme-dark.css';
</style>

Updating styles dynamically

When updating CSS variables dynamically, it is necessary to refresh the via editorRef.refresh() to update the font-size of the line numbers in the gutter and update the colors of the indentation markers in text mode:

<script>
  let editorRef

  function refresh() {
    editorRef?.refresh()
  }
</script>
<JSONEditor bind:this="{editorRef}" ... />

Immutability

It is important that the content of the editor is only updated in an immutable way. Mutating the content will break the history (undo/redo), and will not always immediately update the user interface according to the changes.

The reasons for requiring immutable changes are:

  1. It is necessary in order to support history (undo/redo).
  2. It allows efficiently re-rendering only changed sections of the user interface.

Other advantages of an immutable way of working are that it makes the data that you work with much more predictive and less error-prone. You can learn more about immutability by searching for articles or videos about the subject, such as this video or this article. Immutability is not always the best choice, but in the case of this JSON Editor we're dealing with large and deeply nested data structures, in which we typically make only small changes like updating a single nested value. An immutable approach really shines here, enabling svelte-jsoneditor to smoothly render and edit JSON documents up to 512 MB.

Here is an example of a mutable change:

// mutable change (NOT SUPPORTED!)
function updateDate() {
  const lastEdited = new Date().toISOString()
  const content = toJsonContent(myJsonEditor.get())
  content.json.lastEdited = lastEdited // <- this is a mutable change
  myJsonEditor.update(content)
  // ERROR: The UI will not update immediately but only update after changing something
  // inside the editor like the selection. And most importantly, history is broken now,
  // because the original document is mutated. You cannot undo this action.
}

Instead, you can apply the same change in an immutable way. There are various options for that:

// immutable change using a libary like "mutative" or "immer" (efficient and easy to work with)
import { create } from 'mutative'
function updateDate1() {
  const content = toJsonContent(myJsonEditor.get())
  const updatedContent = create(content, (draft) => {
    draft.json.lastEdited = new Date().toISOString()
  })
  myJsonEditor.update(updatedContent)
}

// immutable change using "immutable-json-patch"
import { setIn } from 'immutable-json-patch'
function updateDate2() {
  const content = toJsonContent(myJsonEditor.get())
  const updatedContent = setIn(content, ['json', 'lastEdited'], new Date().toISOString())
  myJsonEditor.update(updatedContent)
}

// immutable change using the spread operator (not handy for updates in nested data)
function updateDate3() {
  const content = toJsonContent(myJsonEditor.get())
  const updatedContent = {
    json: {
      ...content.json,
      lastEdited: new Date().toISOString()
    }
  }
  myJsonEditor.update(updatedContent)
}

// immutable change by creating a deep clone (simple though inefficient)
import { cloneDeep } from 'lodash-es'
function updateDate4() {
  const content = toJsonContent(myJsonEditor.get())
  const updatedContent = cloneDeep(content)
  updatedContent.json.lastEdited = new Date().toISOString()
  myJsonEditor.update(updatedContent)
}

Differences between josdejong/svelte-jsoneditor and josdejong/jsoneditor

This library josdejong/svelte-jsoneditor is the successor of josdejong/jsoneditor. The main differences are:

josdejong/jsoneditor josdejong/svelte-jsoneditor
Creation Original (first published in 2011) Successor (first published in 2021)
Framework Implemented in plain JavaScript, using low level DOM operations Uses Svelte
Tree mode A tree view having context menu buttons on the left of every line. The keys and values are always in editable state. A tree view utilizing right-click to open the context menu, and double-click to start editing a key or value (more similar to a Spreadsheet or text editor). It supports copy/paste from and to the system clipboard.
Text mode Powered by Ace editor Powered by Code Mirror
Preview mode Used to preview large documents Not needed, both tree and text mode can handle large documents

The main reasons to create a new library instead of extending the existing one are:

  • The codebase had become hard to maintain, the architecture needed a big overhaul. The codebase uses plain JavaScript to create and update the DOM based on changes in the state of the application. This is complex. Letting a framework like Svelte do this for you makes the code base much simpler.
  • Performance limitations in the old editor.
  • Tree mode: the classic tree mode of josdejong/jsoneditor is simple and straightforward, but also limited. The new tree mode of josdejong/svelte-jsoneditor allows for much more streamlined editing and interaction. It works quite similar to a Spreadsheet or text editor. Navigate and select using the Arrow and Shift+Arrow keys or by dragging with the mouse. Double-click (or press Enter) to start editing a key or value. Open the context menu by right-clicking on the item or selection you want to operate on. Use cut/copy/paste to move parts of the JSON around and interoperate with other applications.
  • Code or text mode: the Ace editor library is using an outdated module system (AMD) and the way it is bundled and published is hard to integrate in modern JavaScript projects. Code Mirror 6 is very straightforward to integrate, has much better performance, and is very extensible (paving the way for future features).

Known issues

When the library gives compile errors in your Svelte setup, it could be related to Vite having trouble importing ESM/CommonJS libraries the right way. The error could look like:

SyntaxError: The requested module '/node_modules/json-source-map/index.js?v=fda884be' does not provide an export named 'default' (at jsonUtils.js?v=fda884be:2:8)

A workaround is to add the following to your vite.config.js file (read more):

// ...

/** @type {import('vite').UserConfig} */
const config = {
  // ...
  optimizeDeps: {
    include: [
      'ajv-dist',
      'immutable-json-patch',
      'lodash-es',
      '@fortawesome/free-regular-svg-icons',
      'jmespath'
    ]
  }
}

// ...

Develop

To get started: clone the git repository, run npm install, and then npm run dev.

All available scripts:

npm install             # Install dependencies (once)

npm run dev             # Start the demo project (at http://localhost:5173)
npm run build           # Build the library (output in ./package and ./package-vanilla)

npm run test            # Run unit tests in watch mode
npm run test-ci         # Run unit tests once
npm run coverage        # Run unit test coverage (output in ./coverage)

npm run check           # Run Svelte checks
npm run lint            # Run linter
npm run format          # Automatically fix linting issues

npm run release-dry-run # To run the build and see the change list without actually publishing
npm run release         # Publish to npm (requires login). This will test, check, lint, build,
                        # increase the version number, update the changelog, and publish to npm.
                        # Note that it will publish two npm packages: `svelte-jsoneditor`
                        # and `vanilla-jsoneditor`.

License

svelte-jsoneditor is released as open source under the permissive the ISC license.

If you are using svelte-jsoneditor commercially, there is a social (but no legal) expectation that you help fund its maintenance. Start here.

svelte-jsoneditor's People

Contributors

1pone avatar anlinguist avatar bostondevin avatar clement-fischer avatar cloydlau avatar fauzi9331 avatar gerardosabetta avatar hybridwebdev avatar josdejong avatar koalabear84 avatar leafoftree avatar milahu avatar nrot avatar osverdlo avatar sammousa avatar wernerstucky avatar yodon avatar zhangtao25 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

svelte-jsoneditor's Issues

Can't find a way to reformat the code view

In the old version, I can paste in some JSON, click on TREE, then click back on CODE, and it is all nicely formatted for me.
In the new version, it just restores my unformatted JSON.

Switching to the old view because of this.

Make it TypeScript compatible

I am using typescript in my project and e.g. when I use "createAjvValidator" and pass it a schema, TypeScript complains because due to the comment in the code it thinks there is some JSON type and my data is not of that type.

It would be great if the exposed functions would be made properly TypeScript compatible, or at least fixed in a way that TypeScript is not confused and treats everything as any instead of non-existing types.

Babel, svelte-jsoneditor >0.3.5 error: "You may need an additional loader to handle the result of these loaders."

For some reason svelte-jsoneditor@>0.3.5 crashes in react starter app just after being imported:

Steps to reproduce:

  • npx create-react-app my-app
  • cd my-app
  • yarn add [email protected]
  • add this line to src/App.js: import {JSONEditor} from 'svelte-jsoneditor/dist/jsoneditor.js';
  • run npm start
  • see the error:
Failed to compile
./node_modules/svelte-jsoneditor/dist/jsoneditor.js 13423:12
Module parse failed: Unexpected token (13423:12)
File was processed with these loaders:
 * ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js
You may need an additional loader to handle the result of these loaders.
|     label: "descending"
|   }];
>   let f = u?.filter?.path ? I(u.filter.path) : null,
|       p = u?.filter?.relation ? h.find(e => e.value === u.filter.relation) : null,
|       m = u?.filter?.value || "",
This error occurred during the build time and cannot be dismissed.

I've noticed downgrading to [email protected] seems fixing the issue for now.
Thanks in advance!

Issue with Use in NextJs

I realize this package does not necessarily support the build process of NextJs, but I wanted to share the error I am getting with the module for JSONEditor in svelte-jsoneditor/dist/jsoneditor.js that is crashing my dev server.

import { JSONEditor } from 'svelte-jsoneditor/dist/jsoneditor.js';
TypeError: Cannot read properties of undefined (reading 'ace')
    at file:///Users/.../node_modules/svelte-jsoneditor/dist/jsoneditor.js:47:20281
    at file:///Users/.../node_modules/svelte-jsoneditor/dist/jsoneditor.js:47:20475
    at file:///.../node_modules/svelte-jsoneditor/dist/jsoneditor.js:47:20483
    at file:///Users/.../node_modules/svelte-jsoneditor/dist/jsoneditor.js:47:383518
    at ModuleJob.run (node:internal/modules/esm/module_job:183:25)
    at async Loader.import (node:internal/modules/esm/loader:178:24)
    at async importModuleDynamicallyWrapper (node:internal/vm/module:437:15)
ERROR: "dev:next" exited with 1.

I am not sure what ace is in this case, but would appreciate any ideas for debugging.

Sidenote: I updated the react codesandbox in a fork to match the new interface for content - https://codesandbox.io/s/svelte-jsoneditor-react-forked-0k1bl

Support tabs for indentation

Please add a checkbox to the Configure indentation dialogue so that the editor can use literal tabs. When checked, use the number to set tabSize, but set indentUnit to a single tab character, rather than tabSize × space characters.

Drag selected nodes up and down

Implement dragging the selected node(s) up or down. Create a configuration option to enable/disable dragging an object outside of it's current object/array.

classic tree view is necessary

Would sugguest to keep tree view option. Some guys might like to use new view. But some guys might still get used to classic tree view mode. So better keep it there.

Trying to open a large file in code mode causes editor layout to overflow

I've been trying to open a relatively large (around ~150 MiB) in code mode, for which the editor seems to raise a warning that this could browser to hang. Since the file is minified, however, the last editor line seems to have a calculated width of 1.08636e+09 px which causes the editor layout to overflow (screenshot below):

layout-overflow

Select content within brackets using double click

In classic mode I could select the content within brackets by double clicking the text within the brackets (content only) or in front of the brackets (content + brackets). This is not working anymore. Will this feature be implemented in the new version as well?

out of the box incompatible with current sveltekit scaffolding

Not sure if this is an issue, but when I make a new project using "npm init svelte@next" and use this module using "npm install svelte-jsoneditor" and try to use it, I see this error:

Must use import to load ES Module: C:\Users\tom\Desktop\stuff\sc\client\node_modules\svelte-jsoneditor\dist\jsoneditor.js require() of ES modules is not supported. require() of C:\Users\tom\Desktop\stuff\sc\client\node_modules\svelte-jsoneditor\dist\jsoneditor.js from C:\Users\tom\Desktop\stuff\sc\client\node_modules\@sveltejs\kit\dist\index2.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules. Instead rename jsoneditor.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Users\tom\Desktop\stuff\sc\client\node_modules\svelte-jsoneditor\package.json.

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Users\tom\Desktop\stuff\sc\client\node_modules\svelte-jsoneditor\dist\jsoneditor.js
require() of ES modules is not supported.
require() of C:\Users\tom\Desktop\stuff\sc\client\node_modules\svelte-jsoneditor\dist\jsoneditor.js from C:\Users\tom\Desktop\stuff\sc\client\node_modules\@sveltejs\kit\dist\index2.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename jsoneditor.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Users\tom\Desktop\stuff\sc\client\node_modules\svelte-jsoneditor\package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1080:13)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Module.require (internal/modules/cjs/loader.js:952:19)
    at require (internal/modules/cjs/helpers.js:88:18)
    at load_node (C:\Users\tom\Desktop\stuff\sc\client\node_modules\@sveltejs\kit\src\api\dev\loader.js:137:22)
    at get_module (C:\Users\tom\Desktop\stuff\sc\client\node_modules\@sveltejs\kit\src\api\dev\loader.js:20:26)
    at C:\Users\tom\Desktop\stuff\sc\client\node_modules\@sveltejs\kit\src\api\dev\loader.js:108:27
    at Array.map (<anonymous>)
    at initialize_module (C:\Users\tom\Desktop\stuff\sc\client\node_modules\@sveltejs\kit\src\api\dev\loader.js:107:10)
    at C:\Users\tom\Desktop\stuff\sc\client\node_modules\@sveltejs\kit\src\api\dev\loader.js:47:22
    at C:\Users\tom\Desktop\stuff\sc\client\node_modules\@sveltejs\kit\src\api\dev\loader.js:108:21
    at async Promise.all (index 2)
    at initialize_module (C:\Users\tom\Desktop\stuff\sc\client\node_modules\@sveltejs\kit\src\api\dev\loader.js:106:8)
    at C:\Users\tom\Desktop\stuff\sc\client\node_modules\@sveltejs\kit\src\api\dev\index.js:318:32
    at get_response (C:\Users\tom\Desktop\stuff\sc\client\node_modules\@sveltejs\kit\src\renderer\page.js:141:16)

Not sure if this is a svelte problem, a sapper/sveltekit problem or what, just something to note that users seeking the bleeding edge of technology might run into this wall.

Steps to reproduce:

  1. npm init svelte@next
  2. npm install svelte-jsoneditor
  3. follow the basic usage example for svelte, just importing it in your component will yield the above

-- additional info

Maybe this is just my misunderstanding. I tried npm installing the previous jsoneditor and am having similar issues. Are these projects not usable as npm packages? Or is sveltekit/sapper completely busted?

-- more info

Good/bad news! After some additional testing (creating a new svelte project without sveltekit), following the example for svelte-jsoneditor worked. It is probably fine to attribute these errors to sveltekit or its bundler snowpack, and hopefully that is not indicative of impending disaster when sveltekit is stable 👍

shift+enter for previous search result

image

it would be great if SHIFT+ENTER key combination will show previous search result as it works in Chrome, Vscode and everywhere, i guess.

Thanks in advance!

Cannot read property 'c' of undefined if component is unloaded / conditionally rendered

I thought maybe this was related to the svelte router library I chose at first, but then I reproduced the issue with this minimal component:

<script>
    import {JSONEditor} from "svelte-jsoneditor";
    let show = true;
</script>

<div>
    <button on:click={() => show = !show}>Toggle</button>
    {#if show}
        <JSONEditor />
    {/if}
</div>

This issue can also be reproduced if you have the json editor component loaded in a component that is loaded / unloaded by the "svelte-routing" package.

Error: Method expand is not available in mode "tree"

When calling expand() from onChangeMode callback and where mode === 'tree' I get the following error:

Error: Method expand is not available in mode "tree"
    at lE.eval (https://i4vo7.csb.app/node_modules/svelte-jsoneditor/dist/jsoneditor.js:33:182026)
    at expand (https://i4vo7.csb.app/src/JSONEditor.tsx:36:22)
    at handleOnChangeMode (https://i4vo7.csb.app/src/JSONEditor.tsx:58:7)
    at HTMLButtonElement.G (https://i4vo7.csb.app/node_modules/svelte-jsoneditor/dist/jsoneditor.js:33:179849)
    at HTMLButtonElement.eval (https://i4vo7.csb.app/node_modules/svelte-jsoneditor/dist/jsoneditor.js:29:23080)

The expand method works ok when first mounting the component, but not when switching between modes.

See the issue in the following sandbox:
https://codesandbox.io/s/blue-cloud-i4vo7

On first load the nodes are expanded, but when clicking to code and back to tree, that's when the expand method fails.

Am I calling it correctly?

constructor options not working

Hello,

Working with the newest library, I've noticed some things....

navigationBar: false, mainMenuBar: false, readOnly: false, onClassName: CallbackFn(),

don't seem to be working.

Issue with pressing Enter when using with React

This is an issue in the sandbox:

When you are in Code mode and press enter it resets the cursor to the top of the editor. I am assuming this has something to do with the implementation of the value or onChange in the ace editor, but would appreciate help with debugging this.

Kapture 2021-10-06 at 13 46 26

losing focus doesnt stop field edit

image
clicking outside the editor does not stop the field edit. Old jsoneditor work fine here - it stops field edit on clicking outside of himself

Hide contextmenu in tree mode

I just want a pure editable Json tree view, so can I hide context menu besides css?

I want to hide both drop-down triangle and insert triangle, like this
image

Server side rendering

Using svelte-kit, this error seems to occur when onMount is present and the page is refreshed.

Failing to build within NextJS project

Hello, I was super excited to see this project. I've been using the original version within my project and it does have it quarks. My steps for repo:

  1. use a nextJS project (typescript)
  2. npm install svelte-jsoneditor
  3. npm install --save-dev @rollup/plugin-json svelte-preprocess sass
  4. add ./rollup.config.js to the root
  5. Add import { JSONEditor } from "svelte-jsoneditor"; to my component
  6. Add in my render() function
  7. run 'npm run build'

Errors:

Build error occurred
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /Users/sean.stringer/dev/skinconfig.admin/node_modules/svelte-jsoneditor/dist/jsoneditor.js
require() of ES modules is not supported.
require() of /Users/sean.stringer/dev/skinconfig.admin/node_modules/svelte-jsoneditor/dist/jsoneditor.js from /Users/sean.stringer/dev/skinconfig.admin/dist/.next/server/pages/skinconfig.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename jsoneditor.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/sean.stringer/dev/skinconfig.admin/node_modules/svelte-jsoneditor/package.json.

at Object.Module._extensions..js (internal/modules/cjs/loader.js:1153:13)
at Module.load (internal/modules/cjs/loader.js:985:32)
at Function.Module._load (internal/modules/cjs/loader.js:878:14)
at Module.require (internal/modules/cjs/loader.js:1025:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Object.lfQ6 (/Users/sean.stringer/dev/skinconfig.admin/dist/.next/server/pages/skinconfig.js:240:18)
at __webpack_require__ (/Users/sean.stringer/dev/skinconfig.admin/dist/.next/server/pages/skinconfig.js:23:31)
at Module.qmwh (/Users/sean.stringer/dev/skinconfig.admin/dist/.next/server/pages/skinconfig.js:288:35)
at __webpack_require__ (/Users/sean.stringer/dev/skinconfig.admin/dist/.next/server/pages/skinconfig.js:23:31)
at Object.21 (/Users/sean.stringer/dev/skinconfig.admin/dist/.next/server/pages/skinconfig.js:120:18) {

type: 'NodeError',
code: 'ERR_REQUIRE_ESM'
}

As you can see I'm getting a ERR_REQUIRE_ESM error. The message is telling me to do a couple things different.

Has anyone run into this issue?

Bug: unexpected delete

If I click other than the pull-down button after editing keyword or content in a object, the object disappears in total.

export 'JSONEditor' was not found in 'svelte-jsoneditor'

I am looking to use this new beta editor in a react application (not create-react-app) and was following this issue about wrapping it in a react wrapper #4

When i try to use the codesandbox posted in that issue above, i get the following error:

export 'JSONEditor' (imported as 'JSONEditor') was not found in 'svelte-jsoneditor' (module has no exports)

importing like so:

import { JSONEditor } from "svelte-jsoneditor";

Do you know why this could be happening? Webpack is being used to compile

Transpile bundle to support older JavaScript environments

For some reason [email protected] can not compiling when use npm:

✖ [14:12:16] 1 error in compiling process.
[error] in ./~/svelte-jsoneditor/dist/jsoneditor.js
Module parse failed: /Users/haha/dev_code/demo/vendors/node_modules/svelte-jsoneditor/dist/jsoneditor.js Unexpected token (1:17468)
You may need an appropriate loader to handle this file type.
SyntaxError: Unexpected token (1:17468)
@ ./client/components/ScSvelteJSONEditor/SvelteJSONEditor.js 6:24-52

need help ,thanks!!

How to import bundle from plain JS

I want to use this library in a small PHP/JS project.
Reading the docs I'm trying to follow the examples for plain javascript.

This line:

import { JSONEditor } from 'svelte-jsoneditor'

does not work because the browser (Firefox) requires the module name starts with /, ./ or ../.
So I changed it to an absolute path:

import { JSONEditor } from '/node_modules/svelte-jsoneditor/dist/jsoneditor.js'

Now I have a 404 (even the path is correct - PHP Storm can retrieve the file) and another error:

Loading module from “http://mydevice.local/node_modules/svelte-jsoneditor/dist/jsoneditor.js” was blocked because of a disallowed MIME type (“text/html”).

I copied and paste this example in my HTML page. I only adjusted the path of the module to match the actual position on my machine.

Again, if I copy to the bundle file to /js/jsoneditor.js and change the include to a common script tag like this:

<script type="text/javascript" src="/js/jsoneditor.js">

I get this error:

Uncaught SyntaxError: export declarations may only appear at top level of a module jsoneditor.js:55:43779

Does not work with Sveltekit

I tried svelte-jsoneditor with Sveltekit and got the following error. Just thought you might like to know. Looks like a great project you've got going.

document is not defined
ReferenceError: document is not defined
at /Volumes/Userdata/Users/clarke/dev/svelte/auth-kit/node_modules/vanilla-picker/dist/vanilla-picker.js:1000:19
at /Volumes/Userdata/Users/clarke/dev/svelte/auth-kit/node_modules/vanilla-picker/dist/vanilla-picker.js:9:83
at Object. (/Volumes/Userdata/Users/clarke/dev/svelte/auth-kit/node_modules/vanilla-picker/dist/vanilla-picker.js:12:3)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at ModuleWrap. (node:internal/modules/esm/translators:168:29)
at ModuleJob.run (node:internal/modules/esm/module_job:197:25)
at async Promise.all (index 0)
document is not defined
ReferenceError: document is not defined
at /Volumes/Userdata/Users/clarke/dev/svelte/auth-kit/node_modules/vanilla-picker/dist/vanilla-picker.js:1000:19
at /Volumes/Userdata/Users/clarke/dev/svelte/auth-kit/node_modules/vanilla-picker/dist/vanilla-picker.js:9:83
at Object. (/Volumes/Userdata/Users/clarke/dev/svelte/auth-kit/node_modules/vanilla-picker/dist/vanilla-picker.js:12:3)
at Module._compile (node:internal/modules/cjs/loader:1103:14)
at Object.Module._extensions..js (node:internal/modules/cjs/loader:1157:10)
at Module.load (node:internal/modules/cjs/loader:981:32)
at Function.Module._load (node:internal/modules/cjs/loader:822:12)
at ModuleWrap. (node:internal/modules/esm/translators:168:29)
at ModuleJob.run (node:internal/modules/esm/module_job:197:25)
at async Promise.all (index 0)

Context menu don´t work inside shadowDOM.

If you create a component that extends HTMLElement and use shadowDOM, the context menus wont appear.
How to reproduce:

  1. Create a class that extends HTMLElement
  2. Create a ShadowDOM via: this.attachShadow({mode: 'open'});
  3. Create a svelt-jsoneditor inside this custom Element
  4. Context menu don´t work.

If you keep everthing the same but don´t use shadowDOM it works as expected.

Disable Menu on readOnly

Looks like there is support for a readOnly param (although its not in the documentation). Seems to work fine, except the menu still has all the options to modify everything - they just don't do anything.

Can we disable the popup menu items related to modifying the data when in readOnly mode

Cannot find module 'node-sass'

Getting the following error after fresh install of svelte-kit.

node v14.17.4
svelte v3.34.0
svelte-jsoneditor v0.1.6"

Might this be because it is missing in the dependencies

`[vite] Internal server error: Cannot find any of modules: sass,node-sass

Error: Cannot find module 'node-sass'
Require stack:

  • /mnt/c/dev/repo/node_modules/svelte-preprocess/dist/modules/utils.js
  • /mnt/c/dev/repo/node_modules/svelte-preprocess/dist/autoProcess.js
  • /mnt/c/dev/repo/node_modules/svelte-preprocess/dist/index.js
    Plugin: vite-plugin-svelte
    File: /mnt/c/dev/repo/node_modules/svelte-jsoneditor/src/components/modals/SortModal.svelte`

`<button>` elements in the editor cause parent forms to submit

Situation: I have the json-editor as one of the children inside a <form> element. Clicking on the <button> elements of the json-editor, such as the "expand" button, causes the parent form to get submitted. This is because the <button> elements don't have type="button" attribute.

Fix: Add type="button" as an attribute to all <button>s used in the editor.

Should I open a PR for the same? Thanks :)

vite: TypeError: Cannot set properties of undefined (setting 'j')

TLDR: how to actually use this library? 0__o
... project template?

when i run the example json_schema_validation.svelte, i get the error

Uncaught SyntaxError: The requested module '/node_modules/.pnpm/[email protected]/node_modules/debug/src/browser.js?v=ab0664fe' does not provide an export named 'default'

from

backtrace

// node_modules/debug/src/browser.js

module.exports = require('./common')(exports);
// node_modules/debug/src/common.js

function setup(env) {
        createDebug.debug = createDebug;
        // ...
        return createDebug;
}

module.exports = setup;

looks like a problem with vite and commonjs ...

reproduce

npm i -g pnpm
pnpx create-vite frontend --template svelte
cd frontend
pnpm install svelte-jsoneditor
cd src
curl -L -o App.svelte https://github.com/josdejong/svelte-jsoneditor/raw/main/src/routes/examples/json_schema_validation.svelte
sed -i 's/\$lib/svelte-jsoneditor/' App.svelte
cd ..
npm run dev

related

also pnpm does not run the prepare script when i install from git ...

npm rm svelte-jsoneditor
pnpm i https://github.com/josdejong/svelte-jsoneditor.git

stat node_modules/svelte-jsoneditor/dist
stat: cannot statx 'node_modules/svelte-jsoneditor/dist': No such file or directory

Default tree mode is not understandable

All indents are coming as expanded in default. If there is an tree mode button, people better understand how to collapse all indents and display in the tree mode. I had to read the documentation for not leaving JSON editor. It was the fastest, most convenient tool I've been using, I had difficulty with the tree mode. This is a feedback, hope you keep doing great work!

P.S: I'll try to use all new features through time

Reorder JSON

Was testing the BETA and can't seem to find the reorder feature - kept jumping back the the "old" to fix my JSON order.
Is the reorder feature available on the new version?

Difference from https://github.com/josdejong/jsoneditor?

Thank you for this brilliant library. Ive been a long time user of jsoneditoronline.org (its a pinned tab since I use it all the time 😁).

Would be good to have some documentation as to how this package is different from your previous lib (https://github.com/josdejong/jsoneditor) and also why you decided to create another.

I also see that the demo for the earlier is pointing to http://jsoneditoronline.org/ while the latter is pointing to https://jsoneditoronline.org/, but both seem to be running off svelte-jsoneditor as per the changelog.

preficed class names, css variables

When styling the editor it has been easy since the classnames are static and not all hashed. For example, I can target classes like .code-mode and .contents. This works really well for the most part, until I have other styles that apply to common class names like .contents or .row, resulting in unexpected conflicts.

Material UI solves the issue of helping to avoid conflicts while also providing static classes to target by prefixing their classes with .Mui, like .MuiButton.

I realize it could be a breaking change if something like this were done, but I think it could be a good pattern to use in order to help consuming projects avoid conflicts, while also allowing customizability. I believe this prefix could be added in the build process.

@josdejong , if you are open to this as a change, I can work on a PR, but I wanted to ask to gage interest before going and making the change without buy in.

navigation button submits form

hey, your navigation button have this html:

<button class="jse-navigation-bar-button jse-navigation-bar-arrow svelte-lfr3gu">...</button>

so, it dont have type = button attr specified. That means browsers threat such buttons as submit buttons (proof https://stackoverflow.com/a/9643866/10099510)

I use your json-editor as a part of bootstrap form so it makes some trouble in our case 😀

rollup error: Cannot read file .svelte-kit/tsconfig.json

error

$ rollup --config rollup.config.bundle.js

src/lib/index.js → package/dist/jsoneditor.js...
(!) Plugin typescript: @rollup/plugin-typescript TS5083: Cannot read file '.svelte-kit/tsconfig.json'.
[!] (plugin typescript) Error: @rollup/plugin-typescript: Couldn't process compiler options

this file is missing

"extends": "./.svelte-kit/tsconfig.json",

fixed (?) by removing the line from tsconfig.json

Wrapping in React Component

Attempting to wrap in a React component. I'm able to get it to display, although not perfectly. But then after a couple seconds it generates an error:
TypeError: Cannot read property 'ownerDocument' of undefined

Here is the code in the wrapper:

import React, {useRef} from 'react'
import { JSONEditor } from 'svelte-jsoneditor/dist/jsoneditor.js'

const JSONEditorComponent = ( {} ) => {
    const editor = useRef(null)

    const onRef = ( ref ) => {
        if(ref) {
            console.log('ON REF', ref)
            editor.current = new JSONEditor({
                target: ref,
                props: {
                    json: {
                        greeting: 'Hello World'
                    },
                    onChange: (content) => {
                        // content is an object { json: JSON | undefined, text: string | undefined }
                        console.log('onChange', content)

                    }
                }
            })
        }
    }

    return (
        <div id="json-editor" ref={onRef}/>
    )
}

Any one more advanced with React able to get this working?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.