首頁 > 軟體

Monaco Editor實現sql和java程式碼提示實現範例

2022-08-05 22:00:04

monaco editor建立

//建立和設定值
if (!this.monacoEditor) {
  this.monacoEditor = monaco.editor.create(this._node, {
    value: value || code,
    language: language,
    ...options
  });
  this.monacoEditor.onDidChangeModelContent(e => {
    const value = this.monacoEditor.getValue(); //使value和其值保持一致
    if (value !== this.value) {
      this.value = value;
      this.props.getValue && this.props.getValue(value)
    }
  });
}
// 設定編輯器語言
  this.completionItemProvider = monaco.languages.registerCompletionItemProvider(
    language,
    {
      triggerCharacters: [' ', '.', ...this.triggerCharacters],
      provideCompletionItems: (model, position) =>
        this.sqlSnippets.provideCompletionItems(model, position)
    }
  )

sql提示(庫表欄位關聯)

async provideCompletionItems(model, position) {
  const { lineNumber, column } = position
  // 遊標前文字
  const textBeforePointer = model.getValueInRange({
    startLineNumber: lineNumber,
    startColumn: 0,
    endLineNumber: lineNumber,
    endColumn: column
  })
  const textBeforePointerMulti = model.getValueInRange({
    startLineNumber: 1,
    startColumn: 0,
    endLineNumber: lineNumber,
    endColumn: column
  })
  // 遊標後文字
  // const textAfterPointer = model.getValueInRange({
  //   startLineNumber: lineNumber,
  //   startColumn: column,
  //   endLineNumber: lineNumber,
  //   endColumn: model.getLineMaxColumn(model.getLineCount())
  // })
  const textAfterPointerMulti = model.getValueInRange({
    startLineNumber: lineNumber,
    startColumn: column,
    endLineNumber: model.getLineCount(),
    endColumn: model.getLineMaxColumn(model.getLineCount())
  })
  // const nextTokens = textAfterPointer.trim().split(/s+/)
  // const nextToken = nextTokens[0].toLowerCase()
  const tokens = textBeforePointer.trim().split(/s+/)
  const lastToken = tokens[tokens.length - 1].toLowerCase()
  // 資料庫名聯想
  if (lastToken === 'database') {
    return {
      suggestions: this.getDataBaseSuggest()
    }
    // <庫名>.<表名> || <別名>.<欄位>
  } else if (lastToken.endsWith('.')) {
    // 去掉點後的字串
    const tokenNoDot = lastToken.slice(0, lastToken.length - 1)
    if (this.dbSchema.find(db => db.dbName === tokenNoDot.replace(/^.*,/g, ''))) {
      // <庫名>.<表名>聯想
      return {
        suggestions: [...this.getTableSuggestByDbName(tokenNoDot.replace(/^.*,/g, ''))]
      }
    } else if (this.getTableNameAndTableAlia(textBeforePointerMulti.split(';')[textBeforePointerMulti.split(';').length - 1] + textAfterPointerMulti.split(';')[0])) {
      const tableInfoList = this.getTableNameAndTableAlia(textBeforePointerMulti.split(';')[textBeforePointerMulti.split(';').length - 1] + textAfterPointerMulti.split(';')[0])
      const currentTable = tableInfoList.find(item => item.tableAlia === tokenNoDot.replace(/^.*,/g, ''))
      // <別名>.<欄位>聯想
      if (currentTable && currentTable.tableName) {
        return {
          suggestions: await this.getTableColumnSuggestByTableAlia(currentTable.tableName)
        }
      } else {
        return {
          suggestions: []
        }
      }
    } else {
      return {
        suggestions: []
      }
    }
    // 庫名聯想
  } else if (lastToken === 'from' || lastToken === 'join' || /(from|join)s+.*?s?,s*$/.test(textBeforePointer.replace(/.*?(/gm, '').toLowerCase())) {
    // const tables = this.getTableSuggest()
    const databases = this.getDataBaseSuggest()
    return {
      suggestions: databases
    }
    // 欄位聯想
  } else if (['select', 'where', 'order by', 'group by', 'by', 'and', 'or', 'having', 'distinct', 'on'].includes(lastToken.replace(/.*?(/g, '')) || (lastToken.endsWith('.') && !this.dbSchema.find(db => `${db.dbName}.` === lastToken)) || /(select|where|order by|group by|by|and|or|having|distinct|on)s+.*?s?,s*$/.test(textBeforePointer.toLowerCase())) {
    return {
      suggestions: await this.getTableColumnSuggest()
    }
    // 自定義欄位聯想
  } else if (this.customKeywords.toString().includes(lastToken)) {
    return {
      suggestions: this.getCustomSuggest(lastToken.startsWith('$'))
    }
    // 預設聯想
  } else {
    return {
      suggestions: [...this.getDataBaseSuggest(), ...this.getTableSuggest(), ...this.getKeywordSuggest()]
    }
  }
}

java自定義聯想

 monaco.languages.registerCompletionItemProvider(
  language,
  {
    triggerCharacters: ['ds.','.'],
    provideCompletionItems: (model, position) =>{
      const { lineNumber, column } = position
      // 遊標前文字
      const textBeforePointer = model.getValueInRange({
        startLineNumber: lineNumber,
        startColumn: 0,
        endLineNumber: lineNumber,
        endColumn: column
      })
      if(['ds.'].includes(textBeforePointer)){
        return {suggestions: [
            {
              label: 'connection("")', //顯示的提示名稱
              insertText: 'connection("")' //選擇後貼上到編輯器中的文字
            },
            {
              label: 'query("","")',
              insertText: 'query("","")'
            },
          ]};
      }
      if(['ds.connection("").'].includes(textBeforePointer)){
        return {suggestions: [
            {
              label: 'query("")',
              insertText: 'query("")',
            },
          ]};
      }
    }
  }
)

以上就是Monaco Editor程式碼提示sql和java實現範例的詳細內容,更多關於Monaco Editor程式碼提示的資料請關注it145.com其它相關文章!


IT145.com E-mail:sddin#qq.com