manoca-editor 配置带 Schema 的 JSON 编辑器实现 JSON 代码补全

借助 https://github.com/suren-atoyan/monaco-react 在 React 中使用 monaco-editor, 以及 @monaco-editor/react 中 JSON Schema 配置实现 JSON 代码的补全

带 Schema 的 JSON 编辑器

主要代码:

ts
1import { loader, Editor } from "@monaco-editor/react";
2import * as monaco from "monaco-editor";
3import schema from "@/schemas/DeclarativeNetRequest.Rule.json";
4
5export const modelUri = monaco.Uri.parse("rule.json");
6export const example = {
7  id: 1,
8  action: {
9    type: "modifyHeaders",
10    responseHeaders: [
11      {
12        header: "Access-Control-Allow-Origin",
13        operation: "set",
14        value: "*",
15      },
16    ],
17  },
18  condition: {
19    urlFilter: "https://example.com/url",
20  },
21};
22
23monaco.languages.json.jsonDefaults.setDiagnosticsOptions({
24  validate: true,
25  schemas: [
26    {
27      uri: "http://myserver/foo-schema.json",
28      fileMatch: [modelUri.toString()],
29      schema,
30    },
31  ],
32});
33
34loader.config({
35  monaco,
36});
37
38export default Editor;

DeclarativeNetRequest.Rule.json 文件 (可以通过 ts-json-schema-generator 从 typescript 类型生成 JSON Schema)

json
1{
2  "uri": "http://json-schema.org/draft-07/schema#",
3  "$ref": "#/definitions/DeclarativeNetRequest.Rule",
4  "definitions": {
5    "DeclarativeNetRequest.Rule": {
6      "type": "object",
7      "properties": {
8        "id": {
9          "type": "number",
10          "description": "An id which uniquely identifies a rule. Mandatory and should be >= 1."
11        },
12        "priority": {
13          "type": "number",
14          "description": "Rule priority. Defaults to 1. When specified, should be >= 1 Optional."
15        },
16        "condition": {
17          "$ref": "#/definitions/DeclarativeNetRequest.RuleConditionType",
18          "description": "The condition under which this rule is triggered."
19        },
20        "action": {
21          "$ref": "#/definitions/DeclarativeNetRequest.RuleActionType",
22          "description": "The action to take if this rule is matched."
23        }
24      },
25      "required": ["id", "condition", "action"],
26      "additionalProperties": false
27    },
28    "DeclarativeNetRequest.RuleConditionType": {
29      "type": "object",
30      "properties": {
31        "urlFilter": {
32          "type": "string",
33          "description": "TODO: link to doc explaining supported pattern. The pattern which is matched against the network request url. Only one of 'urlFilter' or 'regexFilter' can be specified. Optional."
34        },
35        "regexFilter": {
36          "type": "string",
37          "description": "Regular expression to match against the network request url. Only one of 'urlFilter' or 'regexFilter' can be specified. Optional."
38        },
39        "isUrlFilterCaseSensitive": {
40          "type": "boolean",
41          "description": "Whether 'urlFilter' or 'regexFilter' is case-sensitive. Optional."
42        },
43        "initiatorDomains": {
44          "type": "array",
45          "items": {
46            "type": "string"
47          },
48          "description": "The rule will only match network requests originating from the list of 'initiatorDomains'. If the list is omitted, the rule is applied to requests from all domains. Optional."
49        },
50        "excludedInitiatorDomains": {
51          "type": "array",
52          "items": {
53            "type": "string"
54          },
55          "description": "The rule will not match network requests originating from the list of 'initiatorDomains'. If the list is empty or omitted, no domains are excluded. This takes precedence over 'initiatorDomains'. Optional."
56        },
57        "requestDomains": {
58          "type": "array",
59          "items": {
60            "type": "string"
61          },
62          "description": "The rule will only match network requests when the domain matches one from the list of 'requestDomains'. If the list is omitted, the rule is applied to requests from all domains. Optional."
63        },
64        "excludedRequestDomains": {
65          "type": "array",
66          "items": {
67            "type": "string"
68          },
69          "description": "The rule will not match network requests when the domains matches one from the list of 'excludedRequestDomains'. If the list is empty or omitted, no domains are excluded. This takes precedence over 'requestDomains'. Optional."
70        },
71        "resourceTypes": {
72          "type": "array",
73          "items": {
74            "$ref": "#/definitions/DeclarativeNetRequest.ResourceType"
75          },
76          "description": "List of resource types which the rule can match. When the rule action is 'allowAllRequests', this must be specified and may only contain 'main_frame' or 'sub_frame'. Cannot be specified if 'excludedResourceTypes' is specified. If neither of them is specified, all resource types except 'main_frame' are matched. Optional."
77        },
78        "excludedResourceTypes": {
79          "type": "array",
80          "items": {
81            "$ref": "#/definitions/DeclarativeNetRequest.ResourceType"
82          },
83          "description": "List of resource types which the rule won't match. Cannot be specified if 'resourceTypes' is specified. If neither of them is specified, all resource types except 'main_frame' are matched. Optional."
84        },
85        "requestMethods": {
86          "type": "array",
87          "items": {
88            "type": "string"
89          },
90          "description": "List of HTTP request methods which the rule can match. Should be a lower-case method such as 'connect', 'delete', 'get', 'head', 'options', 'patch', 'post', 'put'.' Optional."
91        },
92        "excludedRequestMethods": {
93          "type": "array",
94          "items": {
95            "type": "string"
96          },
97          "description": "List of request methods which the rule won't match. Cannot be specified if 'requestMethods' is specified. If neither of them is specified, all request methods are matched. Optional."
98        },
99        "domainType": {
100          "$ref": "#/definitions/DeclarativeNetRequest.RuleConditionDomainTypeEnum",
101          "description": "Specifies whether the network request is first-party or third-party to the domain from which it originated. If omitted, all requests are matched. Optional."
102        },
103        "tabIds": {
104          "type": "array",
105          "items": {
106            "type": "number"
107          },
108          "description": "List of tabIds which the rule should match. An ID of -1 matches requests which don't originate from a tab. Only supported for session-scoped rules. Optional."
109        },
110        "excludedTabIds": {
111          "type": "array",
112          "items": {
113            "type": "number"
114          },
115          "description": "List of tabIds which the rule should not match. An ID of -1 excludes requests which don't originate from a tab. Only supported for session-scoped rules. Optional."
116        }
117      },
118      "additionalProperties": false,
119      "description": "The condition under which this rule is triggered."
120    },
121    "DeclarativeNetRequest.ResourceType": {
122      "type": "string",
123      "enum": [
124        "main_frame",
125        "sub_frame",
126        "stylesheet",
127        "script",
128        "image",
129        "object",
130        "object_subrequest",
131        "xmlhttprequest",
132        "xslt",
133        "ping",
134        "beacon",
135        "xml_dtd",
136        "font",
137        "media",
138        "websocket",
139        "csp_report",
140        "imageset",
141        "web_manifest",
142        "speculative",
143        "other"
144      ],
145      "description": "How the requested resource will be used. Comparable to the webRequest.ResourceType type."
146    },
147    "DeclarativeNetRequest.RuleConditionDomainTypeEnum": {
148      "type": "string",
149      "enum": ["firstParty", "thirdParty"],
150      "description": "Specifies whether the network request is first-party or third-party to the domain from which it originated. If omitted, all requests are matched."
151    },
152    "DeclarativeNetRequest.RuleActionType": {
153      "type": "object",
154      "properties": {
155        "type": {
156          "$ref": "#/definitions/DeclarativeNetRequest.RuleActionTypeEnum"
157        },
158        "redirect": {
159          "$ref": "#/definitions/DeclarativeNetRequest.RuleActionRedirectType",
160          "description": "Describes how the redirect should be performed. Only valid when type is 'redirect'. Optional."
161        },
162        "requestHeaders": {
163          "type": "array",
164          "items": {
165            "$ref": "#/definitions/DeclarativeNetRequest.RuleActionRequestHeadersItemType"
166          },
167          "description": "The request headers to modify for the request. Only valid when type is 'modifyHeaders'. Optional."
168        },
169        "responseHeaders": {
170          "type": "array",
171          "items": {
172            "$ref": "#/definitions/DeclarativeNetRequest.RuleActionResponseHeadersItemType"
173          },
174          "description": "The response headers to modify for the request. Only valid when type is 'modifyHeaders'. Optional."
175        }
176      },
177      "required": ["type"],
178      "additionalProperties": false,
179      "description": "The action to take if this rule is matched."
180    },
181    "DeclarativeNetRequest.RuleActionTypeEnum": {
182      "type": "string",
183      "enum": [
184        "block",
185        "redirect",
186        "allow",
187        "upgradeScheme",
188        "modifyHeaders",
189        "allowAllRequests"
190      ]
191    },
192    "DeclarativeNetRequest.RuleActionRedirectType": {
193      "type": "object",
194      "properties": {
195        "extensionPath": {
196          "type": "string",
197          "description": "Path relative to the extension directory. Should start with '/'. Optional."
198        },
199        "transform": {
200          "$ref": "#/definitions/DeclarativeNetRequest.URLTransform",
201          "description": "Url transformations to perform. Optional."
202        },
203        "url": {
204          "type": "string",
205          "description": "The redirect url. Redirects to JavaScript urls are not allowed. Optional."
206        },
207        "regexSubstitution": {
208          "type": "string",
209          "description": "Substitution pattern for rules which specify a 'regexFilter'. The first match of regexFilter within the url will be replaced with this pattern. Within regexSubstitution, backslash-escaped digits (\\1 to \\9) can be used to insert the corresponding capture groups. \\0 refers to the entire matching text. Optional."
210        }
211      },
212      "additionalProperties": false,
213      "description": "Describes how the redirect should be performed. Only valid when type is 'redirect'."
214    },
215    "DeclarativeNetRequest.URLTransform": {
216      "type": "object",
217      "properties": {
218        "scheme": {
219          "$ref": "#/definitions/DeclarativeNetRequest.URLTransformSchemeEnum",
220          "description": "The new scheme for the request. Optional."
221        },
222        "username": {
223          "type": "string",
224          "description": "The new username for the request. Optional."
225        },
226        "password": {
227          "type": "string",
228          "description": "The new password for the request. Optional."
229        },
230        "host": {
231          "type": "string",
232          "description": "The new host name for the request. Optional."
233        },
234        "port": {
235          "type": "string",
236          "description": "The new port for the request. If empty, the existing port is cleared. Optional."
237        },
238        "path": {
239          "type": "string",
240          "description": "The new path for the request. If empty, the existing path is cleared. Optional."
241        },
242        "query": {
243          "type": "string",
244          "description": "The new query for the request. Should be either empty, in which case the existing query is cleared; or should begin with '?'. Cannot be specified if 'queryTransform' is specified. Optional."
245        },
246        "queryTransform": {
247          "$ref": "#/definitions/DeclarativeNetRequest.URLTransformQueryTransformType",
248          "description": "Add, remove or replace query key-value pairs. Cannot be specified if 'query' is specified. Optional."
249        },
250        "fragment": {
251          "type": "string",
252          "description": "The new fragment for the request. Should be either empty, in which case the existing fragment is cleared; or should begin with '#'. Optional."
253        }
254      },
255      "additionalProperties": false,
256      "description": "Describes the type of the Rule.action.redirect.transform property."
257    },
258    "DeclarativeNetRequest.URLTransformSchemeEnum": {
259      "type": "string",
260      "enum": ["http", "https", "moz-extension"],
261      "description": "The new scheme for the request."
262    },
263    "DeclarativeNetRequest.URLTransformQueryTransformType": {
264      "type": "object",
265      "properties": {
266        "removeParams": {
267          "type": "array",
268          "items": {
269            "type": "string"
270          },
271          "description": "The list of query keys to be removed. Optional."
272        },
273        "addOrReplaceParams": {
274          "type": "array",
275          "items": {
276            "$ref": "#/definitions/DeclarativeNetRequest.URLTransformQueryTransformAddOrReplaceParamsItemType"
277          },
278          "description": "The list of query key-value pairs to be added or replaced. Optional."
279        }
280      },
281      "additionalProperties": false,
282      "description": "Add, remove or replace query key-value pairs. Cannot be specified if 'query' is specified."
283    },
284    "DeclarativeNetRequest.URLTransformQueryTransformAddOrReplaceParamsItemType": {
285      "type": "object",
286      "properties": {
287        "key": {
288          "type": "string"
289        },
290        "value": {
291          "type": "string"
292        },
293        "replaceOnly": {
294          "type": "boolean",
295          "description": "If true, the query key is replaced only if it's already present. Otherwise, the key is also added if it's missing. Optional."
296        }
297      },
298      "required": ["key", "value"],
299      "additionalProperties": false
300    },
301    "DeclarativeNetRequest.RuleActionRequestHeadersItemType": {
302      "type": "object",
303      "properties": {
304        "header": {
305          "type": "string",
306          "description": "The name of the request header to be modified."
307        },
308        "operation": {
309          "type": "string",
310          "enum": ["append", "set", "remove"],
311          "description": "The operation to be performed on a header."
312        },
313        "value": {
314          "type": "string",
315          "description": "The new value for the header. Must be specified for the 'append' and 'set' operations. Optional."
316        }
317      },
318      "required": ["header", "operation"],
319      "additionalProperties": false
320    },
321    "DeclarativeNetRequest.RuleActionResponseHeadersItemType": {
322      "type": "object",
323      "properties": {
324        "header": {
325          "type": "string",
326          "description": "The name of the response header to be modified."
327        },
328        "operation": {
329          "type": "string",
330          "enum": ["append", "set", "remove"],
331          "description": "The operation to be performed on a header."
332        },
333        "value": {
334          "type": "string",
335          "description": "The new value for the header. Must be specified for the 'append' and 'set' operations. Optional."
336        }
337      },
338      "required": ["header", "operation"],
339      "additionalProperties": false
340    }
341  }
342}

主要通过设置 setDiagnosticsOptions 方法中的 fileMatch 属性来匹配 Schema

使用时设置 path 即可

ts
1<Editor
2  path={modelUri.toString()}
3  height="400px"
4  language="json"
5/>