]> git.proxmox.com Git - proxmox-widget-toolkit.git/blob - src/api-viewer/APIViewer.js
api-viewer: show min/max for values without any other format
[proxmox-widget-toolkit.git] / src / api-viewer / APIViewer.js
1 /*global apiSchema*/
2
3 Ext.onReady(function() {
4 Ext.define('pmx-param-schema', {
5 extend: 'Ext.data.Model',
6 fields: [
7 'name', 'type', 'typetext', 'description', 'verbose_description',
8 'enum', 'minimum', 'maximum', 'minLength', 'maxLength',
9 'pattern', 'title', 'requires', 'format', 'default',
10 'disallow', 'extends', 'links',
11 {
12 name: 'optional',
13 type: 'boolean',
14 },
15 ],
16 });
17
18 let store = Ext.define('pmx-updated-treestore', {
19 extend: 'Ext.data.TreeStore',
20 model: Ext.define('pmx-api-doc', {
21 extend: 'Ext.data.Model',
22 fields: [
23 'path', 'info', 'text',
24 ],
25 }),
26 proxy: {
27 type: 'memory',
28 data: apiSchema,
29 },
30 sorters: [{
31 property: 'leaf',
32 direction: 'ASC',
33 }, {
34 property: 'text',
35 direction: 'ASC',
36 }],
37 filterer: 'bottomup',
38 doFilter: function(node) {
39 this.filterNodes(node, this.getFilters().getFilterFn(), true);
40 },
41
42 filterNodes: function(node, filterFn, parentVisible) {
43 let me = this;
44
45 let match = filterFn(node) && (parentVisible || (node.isRoot() && !me.getRootVisible()));
46
47 if (node.childNodes && node.childNodes.length) {
48 let bottomUpFiltering = me.filterer === 'bottomup';
49 let childMatch;
50 for (const child of node.childNodes) {
51 childMatch = me.filterNodes(child, filterFn, match || bottomUpFiltering) || childMatch;
52 }
53 if (bottomUpFiltering) {
54 match = childMatch || match;
55 }
56 }
57
58 node.set("visible", match, me._silentOptions);
59 return match;
60 },
61
62 }).create();
63
64 let render_description = function(value, metaData, record) {
65 let pdef = record.data;
66
67 value = pdef.verbose_description || value;
68
69 // TODO: try to render asciidoc correctly
70
71 metaData.style = 'white-space:pre-wrap;';
72
73 return Ext.htmlEncode(value);
74 };
75
76 let render_type = function(value, metaData, record) {
77 let pdef = record.data;
78
79 return pdef.enum ? 'enum' : pdef.type || 'string';
80 };
81
82 const renderFormatString = function(obj) {
83 if (!Ext.isObject(obj)) {
84 return obj;
85 }
86 const mandatory = [];
87 const optional = [];
88 Object.entries(obj).forEach(function([name, param]) {
89 let list = param.optional ? optional : mandatory;
90 let str = param.default_key ? `[${name}=]` : `${name}=`;
91 if (param.alias) {
92 return;
93 } else if (param.enum) {
94 str += `(${param.enum?.join(' | ')})`;
95 } else {
96 str += `<${param.format_description || param.pattern || param.type}>`;
97 }
98 list.push(str);
99 });
100 return mandatory.join(", ") + ' ' + optional.map(each => `[,${each}]`).join(' ');
101 };
102
103 let render_simple_format = function(pdef, type_fallback) {
104 if (pdef.typetext) {
105 return pdef.typetext;
106 }
107 if (pdef.enum) {
108 return pdef.enum.join(' | ');
109 }
110 if (pdef.format) {
111 return renderFormatString(pdef.format);
112 }
113 if (pdef.pattern) {
114 return pdef.pattern;
115 }
116 if (pdef.type === 'boolean') {
117 return `<true|false>`;
118 }
119 if (type_fallback && pdef.type) {
120 return `<${pdef.type}>`;
121 }
122 if (pdef.minimum || pdef.maximum) {
123 return `${pdef.minimum || 'N'} - ${pdef.maximum || 'N'}`;
124 }
125 return '';
126 };
127
128 let render_format = function(value, metaData, record) {
129 let pdef = record.data;
130
131 metaData.style = 'white-space:normal;';
132
133 if (pdef.type === 'array' && pdef.items) {
134 let format = render_simple_format(pdef.items, true);
135 return `[${Ext.htmlEncode(format)}, ...]`;
136 }
137
138 return Ext.htmlEncode(render_simple_format(pdef));
139 };
140
141 let real_path = function(path) {
142 if (!path.match(/^[/]/)) {
143 path = `/${path}`;
144 }
145 return path.replace(/^.*\/_upgrade_(\/)?/, "/");
146 };
147
148 let permission_text = function(permission) {
149 let permhtml = "";
150
151 if (permission.user) {
152 if (!permission.description) {
153 if (permission.user === 'world') {
154 permhtml += "Accessible without any authentication.";
155 } else if (permission.user === 'all') {
156 permhtml += "Accessible by all authenticated users.";
157 } else {
158 permhtml += `Only accessible by user "${permission.user}"`;
159 }
160 }
161 } else if (permission.check) {
162 permhtml += `<pre>Check: ${Ext.htmlEncode(JSON.stringify(permission.check))}</pre>`;
163 } else if (permission.userParam) {
164 permhtml += `<div>Check if user matches parameter '${permission.userParam}'`;
165 } else if (permission.or) {
166 permhtml += "<div>Or<div style='padding-left: 10px;'>";
167 permhtml += permission.or.map(v => permission_text(v)).join('');
168 permhtml += "</div></div>";
169 } else if (permission.and) {
170 permhtml += "<div>And<div style='padding-left: 10px;'>";
171 permhtml += permission.and.map(v => permission_text(v)).join('');
172 permhtml += "</div></div>";
173 } else {
174 permhtml += "Unknown syntax!";
175 }
176
177 return permhtml;
178 };
179
180 let render_docu = function(data) {
181 let md = data.info;
182
183 let items = [];
184
185 Ext.Array.each(['GET', 'POST', 'PUT', 'DELETE'], function(method) {
186 let info = md[method];
187 if (info) {
188 let endpoint = real_path(data.path);
189 let usage = `<table><tr><td>HTTP:&nbsp;&nbsp;&nbsp;</td><td>`;
190 usage += `${method} /api2/json${endpoint}</td></tr>`;
191
192 if (typeof cliUsageRenderer === 'function') {
193 usage += cliUsageRenderer(method, endpoint); // eslint-disable-line no-undef
194 }
195
196 let sections = [
197 {
198 title: 'Description',
199 html: Ext.htmlEncode(info.description),
200 bodyPadding: 10,
201 },
202 {
203 title: 'Usage',
204 html: usage,
205 bodyPadding: 10,
206 },
207 ];
208
209 if (info.parameters && info.parameters.properties) {
210 let pstore = Ext.create('Ext.data.Store', {
211 model: 'pmx-param-schema',
212 proxy: {
213 type: 'memory',
214 },
215 groupField: 'optional',
216 sorters: [
217 {
218 property: 'name',
219 direction: 'ASC',
220 },
221 ],
222 });
223
224 Ext.Object.each(info.parameters.properties, function(name, pdef) {
225 pdef.name = name;
226 pstore.add(pdef);
227 });
228
229 pstore.sort();
230
231 let groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
232 enableGroupingMenu: false,
233 groupHeaderTpl: '<tpl if="groupValue">Optional</tpl><tpl if="!groupValue">Required</tpl>',
234 });
235
236 sections.push({
237 xtype: 'gridpanel',
238 title: 'Parameters',
239 features: [groupingFeature],
240 store: pstore,
241 viewConfig: {
242 trackOver: false,
243 stripeRows: true,
244 },
245 columns: [
246 {
247 header: 'Name',
248 dataIndex: 'name',
249 flex: 1,
250 },
251 {
252 header: 'Type',
253 dataIndex: 'type',
254 renderer: render_type,
255 flex: 1,
256 },
257 {
258 header: 'Default',
259 dataIndex: 'default',
260 flex: 1,
261 },
262 {
263 header: 'Format',
264 dataIndex: 'type',
265 renderer: render_format,
266 flex: 2,
267 },
268 {
269 header: 'Description',
270 dataIndex: 'description',
271 renderer: render_description,
272 flex: 6,
273 },
274 ],
275 });
276 }
277
278 if (info.returns) {
279 let retinf = info.returns;
280 let rtype = retinf.type;
281 if (!rtype && retinf.items) {rtype = 'array';}
282 if (!rtype) {rtype = 'object';}
283
284 let rpstore = Ext.create('Ext.data.Store', {
285 model: 'pmx-param-schema',
286 proxy: {
287 type: 'memory',
288 },
289 groupField: 'optional',
290 sorters: [
291 {
292 property: 'name',
293 direction: 'ASC',
294 },
295 ],
296 });
297
298 let properties;
299 if (rtype === 'array' && retinf.items.properties) {
300 properties = retinf.items.properties;
301 }
302
303 if (rtype === 'object' && retinf.properties) {
304 properties = retinf.properties;
305 }
306
307 Ext.Object.each(properties, function(name, pdef) {
308 pdef.name = name;
309 rpstore.add(pdef);
310 });
311
312 rpstore.sort();
313
314 let groupingFeature = Ext.create('Ext.grid.feature.Grouping', {
315 enableGroupingMenu: false,
316 groupHeaderTpl: '<tpl if="groupValue">Optional</tpl><tpl if="!groupValue">Obligatory</tpl>',
317 });
318 let returnhtml;
319 if (retinf.items) {
320 returnhtml = '<pre>items: ' + Ext.htmlEncode(JSON.stringify(retinf.items, null, 4)) + '</pre>';
321 }
322
323 if (retinf.properties) {
324 returnhtml = returnhtml || '';
325 returnhtml += '<pre>properties:' + Ext.htmlEncode(JSON.stringify(retinf.properties, null, 4)) + '</pre>';
326 }
327
328 let rawSection = Ext.create('Ext.panel.Panel', {
329 bodyPadding: '0px 10px 10px 10px',
330 html: returnhtml,
331 hidden: true,
332 });
333
334 sections.push({
335 xtype: 'gridpanel',
336 title: 'Returns: ' + rtype,
337 features: [groupingFeature],
338 store: rpstore,
339 viewConfig: {
340 trackOver: false,
341 stripeRows: true,
342 },
343 columns: [
344 {
345 header: 'Name',
346 dataIndex: 'name',
347 flex: 1,
348 },
349 {
350 header: 'Type',
351 dataIndex: 'type',
352 renderer: render_type,
353 flex: 1,
354 },
355 {
356 header: 'Default',
357 dataIndex: 'default',
358 flex: 1,
359 },
360 {
361 header: 'Format',
362 dataIndex: 'type',
363 renderer: render_format,
364 flex: 2,
365 },
366 {
367 header: 'Description',
368 dataIndex: 'description',
369 renderer: render_description,
370 flex: 6,
371 },
372 ],
373 bbar: [
374 {
375 xtype: 'button',
376 text: 'Show RAW',
377 handler: function(btn) {
378 rawSection.setVisible(!rawSection.isVisible());
379 btn.setText(rawSection.isVisible() ? 'Hide RAW' : 'Show RAW');
380 },
381 },
382 ],
383 });
384
385 sections.push(rawSection);
386 }
387
388 if (!data.path.match(/\/_upgrade_/)) {
389 let permhtml = '';
390
391 if (!info.permissions) {
392 permhtml = "Root only.";
393 } else {
394 if (info.permissions.description) {
395 permhtml += "<div style='white-space:pre-wrap;padding-bottom:10px;'>" +
396 Ext.htmlEncode(info.permissions.description) + "</div>";
397 }
398 permhtml += permission_text(info.permissions);
399 }
400
401 if (info.allowtoken !== undefined && !info.allowtoken) {
402 permhtml += "<br />This API endpoint is not available for API tokens.";
403 }
404
405 sections.push({
406 title: 'Required permissions',
407 bodyPadding: 10,
408 html: permhtml,
409 });
410 }
411
412 items.push({
413 title: method,
414 autoScroll: true,
415 defaults: {
416 border: false,
417 },
418 items: sections,
419 });
420 }
421 });
422
423 let ct = Ext.getCmp('docview');
424 ct.setTitle("Path: " + real_path(data.path));
425 ct.removeAll(true);
426 ct.add(items);
427 ct.setActiveTab(0);
428 };
429
430 Ext.define('Ext.form.SearchField', {
431 extend: 'Ext.form.field.Text',
432 alias: 'widget.searchfield',
433
434 emptyText: 'Search...',
435
436 flex: 1,
437
438 inputType: 'search',
439 listeners: {
440 'change': function() {
441 let value = this.getValue();
442 if (!Ext.isEmpty(value)) {
443 store.filter({
444 property: 'path',
445 value: value,
446 anyMatch: true,
447 });
448 } else {
449 store.clearFilter();
450 }
451 },
452 },
453 });
454
455 let treePanel = Ext.create('Ext.tree.Panel', {
456 title: 'Resource Tree',
457 tbar: [
458 {
459 xtype: 'searchfield',
460 },
461 ],
462 tools: [
463 {
464 type: 'expand',
465 tooltip: 'Expand all',
466 tooltipType: 'title',
467 callback: tree => tree.expandAll(),
468 },
469 {
470 type: 'collapse',
471 tooltip: 'Collapse all',
472 tooltipType: 'title',
473 callback: tree => tree.collapseAll(),
474 },
475 ],
476 store: store,
477 width: 200,
478 region: 'west',
479 split: true,
480 margins: '5 0 5 5',
481 rootVisible: false,
482 listeners: {
483 selectionchange: function(v, selections) {
484 if (!selections[0]) {return;}
485 let rec = selections[0];
486 render_docu(rec.data);
487 location.hash = '#' + rec.data.path;
488 },
489 },
490 });
491
492 Ext.create('Ext.container.Viewport', {
493 layout: 'border',
494 renderTo: Ext.getBody(),
495 items: [
496 treePanel,
497 {
498 xtype: 'tabpanel',
499 title: 'Documentation',
500 id: 'docview',
501 region: 'center',
502 margins: '5 5 5 0',
503 layout: 'fit',
504 items: [],
505 },
506 ],
507 });
508
509 let deepLink = function() {
510 let path = window.location.hash.substring(1).replace(/\/\s*$/, '');
511 let endpoint = store.findNode('path', path);
512
513 if (endpoint) {
514 treePanel.getSelectionModel().select(endpoint);
515 treePanel.expandPath(endpoint.getPath());
516 render_docu(endpoint.data);
517 }
518 };
519 window.onhashchange = deepLink;
520
521 deepLink();
522 });