Implementación de finalización de código en Ace Editor


Ace (Ajax.org Cloud9 Editor) — -. , . — . , , . .




Ace Python, -, .


, , : Ace, Monaco, CodeMirror. CodeMirror , . Monaco, , , ce .


Ace , . (, if-else, try-except, class, def, etc). , , ? — ( ). . — , , . .



, , Ace . , Angular, , ng2-ace-editor .


npm install --save ng2-ace-editor brace ace-builds

.


Editor.component.html


<ace-editor
  id="editor"
  #scriptEditor
  [options]="options"
  [autoUpdateContent]="true"
  [mode]="'python'"
  [theme]="'github'"
  [(text)]="script"
  [style.height.px]="600"
></ace-editor>

editor.component.ts


import { Component } from '@angular/core';
import * as ace from 'brace';
//   
import 'brace/mode/python';
//  
import 'brace/snippets/python';
//  
import 'brace/theme/github';
import 'brace/ext/language_tools';

@Component({
  selector: 'app-editor',
  templateUrl: './editor.component.html',
  styleUrls: ['./editor.component.css']
})
export class EditorComponent {
  script = 'import sys\n\nprint("test")';
  options = {
    enableBasicAutocompletion: true,
    enableLiveAutocompletion: true,
    enableSnippets: true
  };

  constructor() { }
}

, ace ng2-ace-editor.


, ace editor, - brace. , brace ace. , , ace.



“enableSnippets” , .


import 'brace/snippets/python'

, .




, , . .


, plunker, : name, value, score, meta. , . . ,


getCompletions: function(editor, session, pos, prefix, callback)

callback . Editor . Session — . Pos — , , prefix — .


, ace/ext/language_tools.js. ,


getDocTooltip: function(item)

innerHTML .


, :


export interface ICompleter {

  getCompletions(
    editor: ace.Editor,
    session: ace.IEditSession,
    pos: ace.Position,
    prefix: string,
    callback: (data: any | null, completions: CompletionModel[]) => void
  ): void;

  getTooltip(item: CompletionModel): void;

}

callback: completions . data — , null. , , :)


, caption. Name Meta. snippet, , . , , . : “{1:variable}”. 1 — (, 1), variable — -.


:


export interface CompletionModel {
  caption: string;
  description?: string;
  snippet?: string;
  meta: string;
  type: string;
  value?: string;
  parent?: string;
  docHTML?: string;
  //  .   -  ,  - 
  inputParameters?: { [name: string]: string };
}

InputParameters. , , :)



, :


export interface MetaInfoModel {
  //  
  Name: string;
  // 
  Description: string;
  //   
  Type: string;
  //   
  Children: MetaInfoModel[];
  //  ,   
  InputParameters?: { [name: string]: string };
}

, , . , , .


, . :


  1. completions: { [name: string]: CompletionModel[] } — : . , . .
  2. completionsTree: { [name: string]: string[] } : . .
  3. roots: string[] — , .

-, getCompletions , , caption. . , , . . , - WebApi, GetRoleById. GetRoleById, . :


  1. (.. WebApi.GetRoleById, GetRoleById)
  2. , .

, - ( WebApi if. ). , .


. , ( ):


  • — -.
  • , , + .
  • , , . , , , .

, . (, , ).


, , -. HTML , .


getDocTooltip completion. ( ) . :


Si se especifica un fragmento en el tipo y no se especifica docHTML , entonces consideramos que se trata de una sugerencia simple (palabra clave, fragmento, etc.) y configuramos la plantilla como se establece casi de forma predeterminada.


  item.docHTML = [
          '<b>',
          item.caption,
          '</b>',
          '<hr></hr>',
          item.snippet
        ].join('');

Si el objeto tiene parámetros de entrada, entonces ya es más difícil. Es necesario recopilar los parámetros de entrada, la ruta completa, agregar una descripción y ensamblar el HTML.


//   
      let signature = Object.keys(item.inputParameters)
        .map(x => `${x} ${item.inputParameters[x]}`)
        .join(', ');

      if (signature) {
        signature = `(${signature})`;
      }

      const path = [];
      //     
      if (item.parent) {
        let parentId = item.parent;
        while (parentId) {
          path.push(parentId);
          parentId = this.completions[parentId][0].parent;
        }
      }
      const displayName =
        [...path.reverse(), item.caption].join('.') + signature;
      let type = item.type;
      if (item.meta === 'class') {
        type = 'class';
      }

      const description = item.description || '';
      let html = `<b>${type} ${displayName}</b><hr>`;
      if (description) {
        html += `<p style="max-width: 400px; white-space: normal;">${description}</p>`;
      }
      item.docHTML = html;

El resultado será algo como esto.


Para entrada limpia:




Como puede ver, se muestran nuestras clases.

Para acceder a través del punto:



Como puede ver, después del punto solo vemos métodos secundarios para la clase WebApi .

Si no hay metadatos, al acceder a través de un punto



, se muestran los datos locales.

Conclusión


Obtuvimos un autocompletado bastante conveniente, que se puede usar con la implementación sin problemas :)


.

Source: https://habr.com/ru/post/undefined/


All Articles