mirror of
https://github.com/casdoor/casdoor.git
synced 2025-07-03 20:50:19 +08:00
feat: add Casbin editor's checking in model editor (#3166)
* feat: add model syntax linting and update dependencies * refactor: move model linter logic to separate module
This commit is contained in:
@ -18,9 +18,8 @@ import * as ModelBackend from "./backend/ModelBackend";
|
||||
import * as OrganizationBackend from "./backend/OrganizationBackend";
|
||||
import * as Setting from "./Setting";
|
||||
import i18next from "i18next";
|
||||
|
||||
import {Controlled as CodeMirror} from "react-codemirror2";
|
||||
import "codemirror/lib/codemirror.css";
|
||||
import {createLinter} from "./utils/modelLinter";
|
||||
|
||||
require("codemirror/mode/properties/properties");
|
||||
|
||||
@ -150,13 +149,21 @@ class ModelEditPage extends React.Component {
|
||||
<div style={{width: "100%"}} >
|
||||
<CodeMirror
|
||||
value={this.state.model.modelText}
|
||||
options={{mode: "properties", theme: "default"}}
|
||||
options={{
|
||||
mode: "properties",
|
||||
theme: "default",
|
||||
lineNumbers: true,
|
||||
lint: true,
|
||||
}}
|
||||
onBeforeChange={(editor, data, value) => {
|
||||
if (Setting.builtInObject(this.state.model)) {
|
||||
return;
|
||||
}
|
||||
this.updateModelField("modelText", value);
|
||||
}}
|
||||
editorDidMount={(editor, value, cb) => {
|
||||
createLinter(editor.constructor);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
</Col>
|
||||
|
42
web/src/utils/modelLinter.js
Normal file
42
web/src/utils/modelLinter.js
Normal file
@ -0,0 +1,42 @@
|
||||
import {newModel} from "casbin";
|
||||
import "codemirror/lib/codemirror.css";
|
||||
import "codemirror/addon/lint/lint.css";
|
||||
import "codemirror/addon/lint/lint";
|
||||
|
||||
export const checkModelSyntax = (modelText) => {
|
||||
try {
|
||||
const model = newModel(modelText);
|
||||
if (!model.model.get("r") || !model.model.get("p") || !model.model.get("e")) {
|
||||
throw new Error("Model is missing one or more required sections (r, p, or e)");
|
||||
}
|
||||
return null;
|
||||
} catch (e) {
|
||||
return e.message;
|
||||
}
|
||||
};
|
||||
|
||||
export const createLinter = (CodeMirror) => {
|
||||
CodeMirror.registerHelper("lint", "properties", (text) => {
|
||||
const error = checkModelSyntax(text);
|
||||
if (error) {
|
||||
const lineMatch = error.match(/line (\d+)/);
|
||||
if (lineMatch) {
|
||||
const lineNumber = parseInt(lineMatch[1], 10) - 1;
|
||||
return [{
|
||||
from: CodeMirror.Pos(lineNumber, 0),
|
||||
to: CodeMirror.Pos(lineNumber, text.split("\n")[lineNumber].length),
|
||||
message: error,
|
||||
severity: "error",
|
||||
}];
|
||||
} else {
|
||||
return [{
|
||||
from: CodeMirror.Pos(0, 0),
|
||||
to: CodeMirror.Pos(text.split("\n").length - 1),
|
||||
message: error,
|
||||
severity: "error",
|
||||
}];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
});
|
||||
};
|
Reference in New Issue
Block a user