josdejong / svelte-jsoneditor

A web-based tool to view, edit, format, repair, query, transform, and validate JSON
https://jsoneditoronline.org
Other
814 stars 108 forks source link

How to set cursor location? #404

Closed tkddnr924 closed 4 months ago

tkddnr924 commented 4 months ago

Question

(Written through Google Translate)

I'm making a Nuxt3 project using the json-editor-vue module.

The code I want to construct is to automatically format the json data when I enter the json data in the editor and then continue to write the json data.

This will move the cursor to the front.

How shall I do it? (If json-editor-vue doesn't work, please close it.)

code

import { parse } from 'lossless-json'

const eventChange = async (content, previousContent, changeStatus) => {
  if (changeStatus.contentErrors !== null) {
    return
  }

  const editor = refEditor.value.jsonEditor
  const editorContent = editor.get().text

  if (editorContent?.length > 0 && editorContent !== "{\n  \n}") {
    // upload store
    uploadJsonData.value = parse(editorContent)

    // patch
    await editor.patch(parse(editorContent))

   // go to cursor
    /*
    * #1
    * editor.updateProps({
    *   selection: { anchor: 1, head: 1 },
    * })
    *
    * #2
    * editor.select(...?)
    *
    * #3
    * editor.focus() / Not working
    * */
  }
}
josdejong commented 4 months ago

I see you closed this issue, did you solve it?

tkddnr924 commented 4 months ago

yes. I solved the problem using the select() function.

I left an issue because I couldn't understand the structure of "Selection". I solved it after checking the Types in Readme😂

Thank you~

tkddnr924 commented 4 months ago

The code I used is this.

const repairJsonData = async () => {
  const editor = refEditor.value.jsonEditor
  const editorContent = editor.get().text

  if (editorContent?.length > 0 && editorContent !== "{}" && editorContent !== "{\n  \n}") {
    // patch
    await editor.patch(parse(editorContent))
    // move selection to end line
    await changeSelection(calculateSelection(parse(editorContent)))
  }
}

const changeSelection = async length => {
  const editor = refEditor.value.jsonEditor
  const selection = {
    type: "text",
    ranges: [{ anchor: length, head: length }],
    main: 0,
  }
  await editor.select(selection)
}
josdejong commented 4 months ago

Ah, good to hear, thanks for sharing your solution!