Ishan jain
Ishan jain

Reputation: 169

Different Monaco editor components sharing same schema

Describe the bug

I have 2 separate components with Monaco editor react of value JSON. One of the editor has a schema validation defined, problem is another instance also validating with same schema. That instance should not have any validation/schema.

I have created a demo on stackblitz here

// code showing schema validation
  useEffect(() => {
    if (schema) {
      const editorSchema = createEditorSchema(schema);
      monaco?.languages?.json?.jsonDefaults?.setDiagnosticsOptions({
        validate: true,
        schemas: [editorSchema],
      });
    }
  }, [schema]);

To Reproduce

Steps to reproduce the behavior:

  1. Check editor 1 and hover to see the schema error
  2. Check editor 2 which has the schema of editor 1. Problem is editor 2 is validating with its own value.

Expected behavior

Editor 2 which is schema field should not be validated with a schema. It should only show value. Only editor 1 should be validated

Demo Link

Sample demo

Screenshots The editor 2 should not have any validations on schema, find SS below Screenshot 2023-09-19 at 13 33 21

Desktop (please complete the following information):

Additional context I have a feature requirement where I render 2 editor instances. Instances one has value of JSON, instance 2 has JSON schema for first instance.

Upvotes: 0

Views: 837

Answers (2)

Sascha Kurth
Sascha Kurth

Reputation: 1

I don't know your specific use-case, but we had the same problem and solved it by generating a unique id for each editor (simply by using useId) and used it as a "fake filename" to differentiate between the editors:

const editorId = useId()

const onMount: OnMount = (editorInstance, monaco) => {
  monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
    validate: true,
    schemas: [{
      uri: 'http://json-schema.org/draft-04/schema#',
      fileMatch: [`${id}.json`],
      schema: editorSchema
    }]
  })
}

return <Editor
  language="json"
  path={`${editorId}.json`}
  onMount={onMount}
/>

Upvotes: 0

Mike Lischke
Mike Lischke

Reputation: 53502

The Monaco editor is not designed to appear multiple times on a single web page with different settings, like themes, providers or here, the validation scheme. Commands like:

      monaco?.languages?.json?.jsonDefaults?.setDiagnosticsOptions({
        validate: true,
        schemas: [editorSchema],
      });

set values for all instances of the editor control. The only control you have is to place only one editor on a web page and switch pages between different editors, where you can also change the global settings while switching.

Upvotes: 2

Related Questions