-
Notifications
You must be signed in to change notification settings - Fork 26
/
Copy pathYamlEditor.jsx
103 lines (94 loc) · 2.78 KB
/
YamlEditor.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
import { React, useState } from "react";
import AceEditor from "react-ace";
import "ace-builds/src-noconflict/theme-github";
import "ace-builds/src-noconflict/ext-language_tools";
import "ace-builds/webpack-resolver";
import "ace-builds/src-noconflict/mode-yaml";
import jsYaml from "js-yaml";
import Ajv from "ajv";
const ajv = new Ajv({ allErrors: true });
import Schema from "../../../static/schema/schema.v2.json";
export default function YamlEditor() {
const [annotations, setAnnotations] = useState([]);
const [value, setValue] = useState(
"# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json\n"
);
const validate = ajv.compile(Schema.definitions.schema);
function getRowFromPath(path) {
// Convert path to row number (0-based)
return path.split("/").length - 1;
}
function getLineNumber(yaml, path) {
const lines = yaml.split("\n");
const pathParts = path.split("/").filter(Boolean);
let currentObj = jsYaml.load(yaml);
let lineNumber = 0;
for (const part of pathParts) {
for (let i = lineNumber; i < lines.length; i++) {
if (lines[i].trim().startsWith(part + ":")) {
lineNumber = i;
break;
}
}
currentObj = currentObj[part];
}
return lineNumber;
}
function onChange(newValue) {
setValue(newValue);
try {
const doc = jsYaml.load(newValue, { strict: true });
const valid = validate(doc);
if (!valid && validate.errors) {
setAnnotations(
validate.errors.map((err) => ({
row: err.instancePath
? getLineNumber(newValue, err.instancePath)
: 0,
column: 0,
text: `${err.keyword}: ${err.message} ${
err?.params?.allowedValues
? `Allowed values: ${err.params.allowedValues.join(", ")}`
: ""
}`,
type: "error",
}))
);
} else {
setAnnotations([]);
}
} catch (err) {
setAnnotations([
{
row: err.instancePath ? getLineNumber(newValue, err.instancePath) : 0,
column: 0,
text:
`${err.keyword}: ${err.message} ${
err?.params?.allowedValues
? `Allowed values: ${err.params.allowedValues.join(", ")}`
: ""
}` || "YAML parsing error",
type: "error",
},
]);
}
}
return (
<AceEditor
mode="yaml"
theme="github"
onChange={onChange}
value={value}
name="yaml-editor"
editorProps={{ $blockScrolling: true }}
setOptions={{
useWorker: false,
showPrintMargin: false,
showGutter: true,
}}
annotations={annotations}
width="100%"
height="400px"
/>
);
}