monaco-editor 自定义右键获取当前json path

1,810 阅读1分钟

自定义右键

官网 playground:microsoft.github.io/monaco-edit…

代码参考:

editor.addAction({
  id: 'my-get-json-path', // action unique id
  label: 'Get JSON Path', // action 在右键时展示的名称
  precondition: null,
  contextMenuGroupId: 'navigation',// 右键展示位置
  
  run(editor, args) { // 执行代码
    console.log('run')
  }
});

获取editor内用户当前选中 key 的 json path

example: { key1:{a: [{b:222}]} },当用户选中b右键获取当前json path时可以得到 key1.a[0].b

思路:

  1. 使用editor获取当前json的string和当前用户光标所在的selection position selection 结构

    {
        "startLineNumber": 2,
        "startColumn": 6,
        "endLineNumber": 2,
        "endColumn": 6,
        "selectionStartLineNumber": 2,
        "selectionStartColumn": 6,
        "positionLineNumber": 2,
        "positionColumn": 6
    }
    
  2. 将 json string 转成 AST

  3. 深度遍历 AST 内节点,比较节点 node loc position 和 当前光标的selection position,获取到 json path

    AST 示例结构:astexplorer.net/

    {
        key1:111
    }
    

    对应 AST

    {
      "type": "Object",
      "children": [
        {
          "type": "Property",
          "key": {
            "type": "Identifier",
            "value": "key1",
            "raw": "\"key1\"",
            "loc": {
              "start": {
                "line": 2,
                "column": 5,
                "offset": 6
              },
              "end": {
                "line": 2,
                "column": 11,
                "offset": 12
              },
              "source": null
            }
          },
          "value": {
            "type": "Literal",
            "value": 111,
            "raw": "111",
            "loc": {
              "start": {
                "line": 2,
                "column": 13,
                "offset": 14
              },
              "end": {
                "line": 2,
                "column": 16,
                "offset": 17
              },
              "source": null
            }
          },
          "loc": {
            "start": {
              "line": 2,
              "column": 5,
              "offset": 6
            },
            "end": {
              "line": 2,
              "column": 16,
              "offset": 17
            },
            "source": null
          }
        }
      ],
      "loc": {
        "start": {
          "line": 1,
          "column": 1,
          "offset": 0
        },
        "end": {
          "line": 3,
          "column": 2,
          "offset": 19
        },
        "source": null
      }
    }