ajaxorg / ace

Ace (Ajax.org Cloud9 Editor)
https://ace.c9.io
Other
26.77k stars 5.29k forks source link

YAML Validation #5405

Closed MarketingPip closed 11 months ago

MarketingPip commented 11 months ago

Describe the feature

This idea / code / logic was taken from this Codepen but I do this it will be useful. See here

Use Case

This feature will be a great addition to the Ace Editor project.

Proposed Solution

window.define = ace.define;

// Define the YAML validation function
function validateYaml(editor) {
  let getYamlCodeValidationErrors = (code) => {
    var error = '';
    try {
      jsyaml.safeLoad(code);
    } catch (e) {
      error = e;
    }
    return error;
  };

  let code = editor.getValue();
  let error = getYamlCodeValidationErrors(code);
  if (error) {
    editor.getSession().setAnnotations([
      {
        row: error.mark.line,
        column: error.mark.column,
        text: error.reason,
        type: 'error',
      },
    ]);
  } else {
    editor.getSession().setAnnotations([]);
  }
}

// Attach the validation function to the editor as a plugin
ace.define('ace/plugin/yaml-validation', ['require', 'exports', 'module', 'ace/lib/dom', 'ace/lib/lang'], function (
  require,
  exports,
  module
) {
  var dom = require('ace/lib/dom');
  var lang = require('ace/lib/lang');

  exports.validateYaml = validateYaml;

  exports.init = function (editor) {
    // Add an event listener for changes in the editor content
    editor.on('change', lang.deferredCall(function () {
      validateYaml(editor);
    }));

    // Initial validation
    validateYaml(editor);
  };

});

// Use the plugin with your existing code
var code = `
- name: Homer
  lastname: Simpson
  childs:
   - name: Bart
   - name: Lisa
   - name: Maggie
`;

var editor = ace.edit('editor');
editor.setTheme('ace/theme/monokai');
editor.setSession(ace.createEditSession(code, 'ace/mode/yaml'));

// Initialize the YAML validation plugin
ace.require('ace/plugin/yaml-validation').init(editor);

Other Information

No response

Acknowledgements

ACE version used

0.0.0

akoreman commented 11 months ago

Hi, thanks for opening the feature request, but I'm going to close it.

For Ace, we're moving away from having language features inside the editor itself and focusing on the core-editing functionality of Ace. For language features like these, we suggest using third-party extensions for Ace like ace-linters. An example of how ace-linters can be used can be found here.

MarketingPip commented 11 months ago

@akoreman Hey Alice!

No worries at all! I figured this would possibly be a good extension under official list. (Tho I can understand you not wanting to if avoiding / trying to avoid taking care of the support for linters.)

Tho - I feel like it is a shame not having these being just directly endorsed by Ace Editor. (Maybe it is tho and I missed it in README.)

That said - I hope you have a great week! 👍

ps; dope work on your portfolio / gh profile.