gadget_json_generated_form.js 34.1 KB
Newer Older
1 2
/*jslint nomen: true, maxlen: 200, indent: 2, maxerr: 100*/
/*global window, document, URL, rJS, RSVP, jIO */
3

4
(function (window, document, rJS, RSVP, jIO) {
5
  "use strict";
Boris Kocherov's avatar
Boris Kocherov committed
6
  var render_object;
7

8 9
  function decodeJsonPointer(_str) {
    // https://tools.ietf.org/html/rfc6901#section-5
Boris Kocherov's avatar
Boris Kocherov committed
10
    return _str.replace(/~1/g, '/').replace(/~0/g, '~');
11 12 13 14
  }

  function encodeJsonPointer(_str) {
    // https://tools.ietf.org/html/rfc6901#section-5
Boris Kocherov's avatar
Boris Kocherov committed
15
    return _str.replace(/~/g, '~0').replace(/\//g, '~1');
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
  function getBaseUrl(g, path) {
    var base_url,
      key,
      map = g.props.schema_map,
      max_len = 0;
    if (!path) {
      return;
    }
    for (key in map) {
      if (map.hasOwnProperty(key) &&
          path.startsWith(key) &&
          key.length > max_len) {
        base_url = map[key];
        max_len = key.length;
      }
    }
    return base_url;
  }

  function downloadJSON(url) {
    return RSVP.Queue()
      .push(function () {
        return jIO.util.ajax({
          url: url,
          dataType: "json"
        });
      })
      .push(function (evt) {
        return evt.target.response;
      });
  }

  function resolveLocalReference(schema, ref) {
    // 2 here is for #/
    var i, ref_path = ref.substr(2, ref.length),
      parts = ref_path.split("/");
    if (parts.length === 1 && parts[0] === "") {
      // It was uses #/ to reference the entire json so just return it.
      return schema;
    }
    for (i = 0; i < parts.length; i += 1) {
      schema = schema[decodeJsonPointer(parts[i])];
    }
    return schema;
  }

Boris Kocherov's avatar
draft  
Boris Kocherov committed
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
  function getDocumentType(doc) {
    if (doc instanceof Array) {
      return "array";
    }
    return typeof doc;
  }

  function getDocumentSchema(doc) {
    var type = getDocumentType(doc),
      schema = {
        type: type
      };
    if (type === "array") {
      schema.maxItems = 0;
    } else if (type === "object") {
      schema.additionalProperties = false;
    } else {
      schema.readOnly = true;
    }
    return schema;
  }

86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123
  function render_selection(json_field, default_value) {
    var input = document.createElement("select"),
      option = document.createElement("option"),
      option_index,
      optionz;
    input.size = 1;
    option.value = "";
    if (default_value === undefined) {
      option.selected = "selected";
    }
    input.appendChild(option);
    for (option_index in json_field['enum']) {
      if (json_field['enum'].hasOwnProperty(option_index)) {
        optionz = document.createElement("option");
        optionz.value = json_field['enum'][option_index];
        optionz.textContent = json_field['enum'][option_index];
        if (json_field['enum'][option_index] === default_value) {
          optionz.selected = "selected";
        }
        input.appendChild(optionz);
      }
    }
    return input;
  }

  function render_textarea(json_field, default_value, data_format) {
    var input = document.createElement("textarea");
    if (default_value !== undefined) {
      if (default_value instanceof Array) {
        input.value = default_value.join("\n");
      } else {
        input.value = default_value;
      }
    }
    input["data-format"] = data_format;
    return input;
  }

Boris Kocherov's avatar
Boris Kocherov committed
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156
  function addSubForm(options) {
    var element = options.element,
      g = options.gadget,
      property_name,
      parent_path = options.path || element.name,
      scope,
      input_element;

    scope = parent_path + Math.random().toString(36).substr(2, 9);
    if (options.parent_type !== "array") {
      property_name = options.property_name;
      if (!property_name) {
        input_element = element.parentNode.querySelector("input[type='text']");
        property_name = input_element.value;
      }
      if (!property_name) {
        // XXX notify user
        // you can't create property without property_name
        return RSVP.Queue();
      }
      if (g.props.objects[parent_path].hasOwnProperty(property_name) && g.props.objects[parent_path][property_name] !== "") {
        // XXX notify user
        // you can't create property with existed property_name
        return RSVP.Queue();
      }
      if (input_element) {
        input_element.value = "";
      }
    }

    return g.declareGadget('gadget_json_generated_form.html', {scope: scope})
      .push(function (form_gadget) {
        form_gadget.element.setAttribute("data-json-parent", parent_path);
157 158
        form_gadget.element.setAttribute("data-gadget-parent-scope",
          g.element.getAttribute("data-gadget-scope"));
159
        if (options.parent_type !== "array") {
Boris Kocherov's avatar
Boris Kocherov committed
160 161 162 163 164
          g.props.objects[parent_path][property_name] = scope;
          form_gadget.element.setAttribute("data-json-property-name", property_name);
        }
        return form_gadget.renderForm({
          schema: options.schema_part,
165
          schema_path: options.schema_path,
Boris Kocherov's avatar
Boris Kocherov committed
166 167 168 169
          document: options.default_dict,
          display_label: options.parent_type !== "array",
          scope: scope
        });
Boris Kocherov's avatar
Boris Kocherov committed
170
      });
Boris Kocherov's avatar
Boris Kocherov committed
171 172
  }

173
  function render_array(gadget, json_field, default_array, root, path, schema_path) {
Boris Kocherov's avatar
Boris Kocherov committed
174 175 176 177 178
    var queue = RSVP.Queue(),
      div,
      div_input,
      input,
      item_schema,
Boris Kocherov's avatar
draft  
Boris Kocherov committed
179 180 181 182 183
      i,
      maxItems = json_field.maxItems;
    div = document.createElement("div");
    div.setAttribute("class", "subfield");
    div.title = json_field.description;
Boris Kocherov's avatar
Boris Kocherov committed
184

Boris Kocherov's avatar
draft  
Boris Kocherov committed
185 186 187 188 189 190 191 192 193 194 195
    div_input = document.createElement("div");
    div_input.setAttribute("class", "input");

    function element_append(child) {
      if (child) {
        div_input.appendChild(child);
      }
    }

    if (maxItems === undefined || default_array.length < maxItems) {
      item_schema = json_field.items;
Boris Kocherov's avatar
Boris Kocherov committed
196 197

      input = document.createElement("button");
Boris Kocherov's avatar
Boris Kocherov committed
198 199 200
      input.setAttribute("class",
        "ui-shadow-inset ui-btn ui-btn-inline ui-corner-all" +
        " ui-btn-icon-notext ui-icon-btn ui-icon-plus ui-input-btn");
Boris Kocherov's avatar
Boris Kocherov committed
201 202 203 204
      input.type = "button";
      input.name = path;
      gadget.props.add_buttons.push({
        element: input,
Boris Kocherov's avatar
draft  
Boris Kocherov committed
205 206
        event: function () {
          return addSubForm({
Boris Kocherov's avatar
Boris Kocherov committed
207 208 209
            gadget: gadget,
            parent_type: 'array',
            element: input,
210
            schema_path: schema_path + '/items',
Boris Kocherov's avatar
Boris Kocherov committed
211 212
            schema_part: item_schema
          })
Boris Kocherov's avatar
draft  
Boris Kocherov committed
213 214
            .push(element_append);
        }
Boris Kocherov's avatar
Boris Kocherov committed
215
      });
Boris Kocherov's avatar
draft  
Boris Kocherov committed
216 217 218 219
    } else {
      input = document.createElement("div");
      input.setAttribute("class", "input");
    }
Boris Kocherov's avatar
Boris Kocherov committed
220

Boris Kocherov's avatar
draft  
Boris Kocherov committed
221 222 223 224
    div_input.appendChild(input);
    div.appendChild(div_input);

    if (default_array) {
Boris Kocherov's avatar
Boris Kocherov committed
225
      for (i = 0; i < default_array.length; i = i + 1) {
Boris Kocherov's avatar
draft  
Boris Kocherov committed
226 227 228 229 230 231 232
        queue
          .push(
            addSubForm.bind(gadget, {
              gadget: gadget,
              parent_type: 'array',
              path: path,
              element: input,
233
              schema_path: schema_path + '/items',
Boris Kocherov's avatar
draft  
Boris Kocherov committed
234 235 236 237 238
              schema_part: item_schema,
              default_dict: default_array[i]
            })
          )
          .push(element_append);
Boris Kocherov's avatar
Boris Kocherov committed
239 240
      }
    }
Boris Kocherov's avatar
draft  
Boris Kocherov committed
241
    root.appendChild(div);
Boris Kocherov's avatar
Boris Kocherov committed
242
    // XXX add failback rendering if default_array not array
Boris Kocherov's avatar
Boris Kocherov committed
243 244 245 246
    // input = render_textarea(json_field, default_value, "array");
    return queue;
  }

Boris Kocherov's avatar
Boris Kocherov committed
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291
  function expandSchema(g, schema, schema_path) {
    if (schema.$ref) {
      return g.loadJSONSchema(schema.$ref, schema_path)
        .push(function (schema_part) {
          return schema_part;
        });
    }
    return RSVP.Queue()
      .push(function () {
        return schema;
      });
  }

  function allOf(g, schema_array, schema_path) {
    return RSVP.Queue()
      .push(function () {
        var i,
          arr = [];
        for (i = 0; i < schema_array.length; i += 1) {
          arr.push(expandSchema(g, schema_array[i], schema_path));
        }
        return RSVP.all(arr);
      })
      .push(function (arr) {
        var i,
          key,
          next_schema,
          schema = arr[0];
        for (i = 1; i < arr.length; i += 1) {
          next_schema = arr[i];
          for (key in next_schema) {
            if (next_schema.hasOwnProperty(key)) {
              if (schema.hasOwnProperty(key)) {
                // XXX need use many many rules for merging
                schema[key] = next_schema[key];
              } else {
                schema[key] = next_schema[key];
              }
            }
          }
        }
        return schema;
      });
  }

292
  function render_field(gadget, key, path, json_field, default_value, root, schema_path) {
293 294 295 296 297
    var div,
      label,
      div_input,
      span_info,
      span_error,
298
      input,
299
      first_path,
300
      queue = RSVP.Queue();
301

302
    if (path && key) {
303
      first_path = path + encodeJsonPointer(key);
304 305 306
    } else {
      first_path = "";
    }
307

Boris Kocherov's avatar
draft  
Boris Kocherov committed
308 309
    if (json_field === undefined) {
      json_field = getDocumentSchema(default_value);
310 311
    }

Boris Kocherov's avatar
Boris Kocherov committed
312 313 314 315 316 317 318
    if (json_field.allOf !== undefined) {
      return allOf(gadget, json_field.allOf, schema_path)
        .push(function (schema_part) {
          return render_field(gadget, key, path, schema_part, default_value, root, schema_path);
        });
    }

319
    if (json_field.$ref !== undefined) {
320
      return gadget.loadJSONSchema(json_field.$ref, schema_path)
321
        .push(function (schema_part) {
322
          return render_field(gadget, key, path, schema_part, default_value, root, schema_path);
323 324 325 326
        });
    }

    if (json_field.type === undefined && default_value) {
Boris Kocherov's avatar
draft  
Boris Kocherov committed
327 328 329
      json_field.type = getDocumentType(default_value);
    }

330 331 332 333 334 335 336 337 338 339 340
    // XXX bad peace of code
    // we can not change schema
    // but our schema in slapos bad
    if (!json_field.type) {
      if (json_field.properties &&
          json_field.required &&
          json_field.required.length > 0) {
        json_field.type = "object";
      }
    }

341 342 343
    div = document.createElement("div");
    div.setAttribute("class", "subfield");
    div.title = json_field.description;
Boris Kocherov's avatar
draft  
Boris Kocherov committed
344 345 346
    // if (key && !first_path) {
    if (false) {
      // XXX;
347 348 349 350 351 352 353
      label = document.createElement("input");
      label.value = key;
      gadget.props.property_name_edit = label;
    } else {
      label = document.createElement("label");
      label.textContent = json_field.title || key;
    }
354 355 356
    div.appendChild(label);
    div_input = document.createElement("div");
    div_input.setAttribute("class", "input");
357

Boris Kocherov's avatar
draft  
Boris Kocherov committed
358
    if (json_field.enum !== undefined) {
359
      input = render_selection(json_field, default_value);
360 361 362 363 364 365 366 367 368
    }

    if (json_field.type === "boolean") {
      if (default_value === "true") {
        default_value = true;
      }
      if (default_value === "false") {
        default_value = false;
      }
Boris Kocherov's avatar
draft  
Boris Kocherov committed
369 370 371 372
      input = render_selection({
        type: "boolean",
        enum: [true, false]
      }, default_value);
373 374
    }

Boris Kocherov's avatar
draft  
Boris Kocherov committed
375 376
    if (!input && ["string", "integer", "number"].indexOf(json_field.type) >= 0) {
      if (json_field.contentMediaType === "text/plain") {
377 378 379 380 381 382 383 384 385 386 387 388 389
        input = render_textarea(json_field, default_value, "string");
      } else {
        input = document.createElement("input");
        if (default_value !== undefined) {
          input.value = default_value;
        }

        if (json_field.type === "integer") {
          input.type = "number";
        } else {
          input.type = "text";
        }
      }
390 391
    }

Boris Kocherov's avatar
Boris Kocherov committed
392 393 394 395 396 397
    if (json_field.type === "array") {
      queue = render_array(
        gadget,
        json_field,
        default_value,
        div_input,
398 399
        first_path + '/',
        schema_path
Boris Kocherov's avatar
Boris Kocherov committed
400
      );
Boris Kocherov's avatar
Boris Kocherov committed
401
      div.setAttribute("data-json-path", first_path + '/');
402
      gadget.props.arrays[first_path +  '/'] = div;
Boris Kocherov's avatar
Boris Kocherov committed
403 404 405
      div.setAttribute("data-json-type", json_field.type);
    }

406
    if (json_field.type === "object") {
407 408 409 410 411 412 413
      queue
        .push(function () {
          return render_object(
            gadget,
            json_field,
            default_value,
            div_input,
414 415
            first_path + '/',
            schema_path
Boris Kocherov's avatar
Boris Kocherov committed
416
          );
417
        });
Boris Kocherov's avatar
Boris Kocherov committed
418
      div.setAttribute("data-json-path", first_path + '/');
419
    }
420

421 422 423 424
    if (input) {
      // object and array excluded from
      // gadget.props.inputs not contain values
      gadget.props.inputs.push(input);
425
      input.name = first_path;
426 427
      input.setAttribute("class", "slapos-parameter");
      div_input.appendChild(input);
428 429
    }

430 431 432 433
    if (json_field.info !== undefined) {
      span_info = document.createElement("span");
      span_info.textContent = json_field.info;
      div_input.appendChild(span_info);
434
    }
435 436 437 438
    span_error = document.createElement("span");
    span_error.setAttribute("class", "error");
    div_input.appendChild(span_error);
    div.appendChild(div_input);
439

440 441 442 443 444
    return queue
      .push(function () {
        root.appendChild(div);
        return div;
      });
445 446
  }

447
  render_object = function (g, json_field, default_dict, root, path, schema_path) {
Boris Kocherov's avatar
draft  
Boris Kocherov committed
448 449 450
    var additionalProperties,
      key,
      required = json_field.required || [],
451
      properties = json_field.properties,
452
      used_properties = {},
453 454 455 456 457 458 459 460
      queue = RSVP.Queue(),
      scope = "property_add_" + Math.random().toString(36).substr(2, 9),
      selector = {
        event: function () {
          return g.getDeclaredGadget(scope)
            .push(function (z) {
              return z.getContent()
                .push(function (value) {
461 462 463 464 465 466 467 468 469 470 471 472 473 474
                  var property_name_array = value[scope].split('/'),
                    property_name,
                    schema,
                    schema_path_local,
                    anyOfidx = property_name_array[1];
                  property_name = decodeJsonPointer(property_name_array[0]);
                  schema_path_local = schema_path + '/properties/' +
                    encodeJsonPointer(property_name);
                  if (property_name_array.length > 1) {
                    schema = json_field.properties[property_name].anyOf[anyOfidx];
                    schema_path_local += '/' + anyOfidx;
                  } else {
                    schema = json_field.properties[property_name];
                  }
Boris Kocherov's avatar
Boris Kocherov committed
475
                  used_properties[property_name] = "";
476 477
                  return addSubForm({
                    gadget: g,
Boris Kocherov's avatar
Boris Kocherov committed
478
                    property_name: property_name,
479
                    path: path,
480 481
                    schema_path: schema_path_local,
                    schema_part: schema
482 483 484 485 486 487 488 489 490 491 492
                  });
                })
                .push(function (element) {
                  z.element.parentNode.insertBefore(element, z.element);
                });
            })
            .push(selector.rerender);
        },
        rerender: function () {
          return g.getDeclaredGadget(scope)
            .push(function (g) {
Boris Kocherov's avatar
Boris Kocherov committed
493
              var property_name,
494 495 496
                i,
                anyOf,
                description,
497
                item_list = [["add property", "add property"]];
498 499
              for (property_name in properties) {
                if (properties.hasOwnProperty(property_name) &&
Boris Kocherov's avatar
Boris Kocherov committed
500
                    !used_properties.hasOwnProperty(property_name)) {
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515
                  anyOf = properties[property_name].anyOf;
                  if (anyOf) {
                    for (i = 0; i < anyOf.length; i += 1) {
                      description = anyOf[i].$ref ||
                        anyOf[i].title ||
                        anyOf[i].type ||
                        anyOf[i].description;
                      item_list.push([
                        property_name + '/' + description,
                        encodeJsonPointer(property_name) + '/' + i.toString()
                      ]);
                    }
                  } else {
                    item_list.push([property_name, property_name]);
                  }
516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
                }
              }
              return g.render({
                name: scope,
                editable: true,
                hidden: item_list.length <= 1,
                value: item_list[0][1],
                item_list: item_list
              })
              //not need if gadget_html5_select.render return element
                .push(function () {
                  return g.element;
                });
            });
        }
      };
532

533
    g.props.add_property_selections[scope] = selector;
Boris Kocherov's avatar
draft  
Boris Kocherov committed
534 535 536 537 538 539
    g.props.objects[path] = used_properties;

    function root_append(child) {
      root.appendChild(child);
    }

540 541 542
    function addAdditional(schema) {
      var div,
        div_input,
Boris Kocherov's avatar
Boris Kocherov committed
543 544
        input,
        property_name;
545 546 547 548 549 550 551 552

      div = document.createElement("div");
      div.setAttribute("class", "subfield");
      div.title = json_field.description;

      div_input = document.createElement("div");
      div_input.setAttribute("class", "input");

Boris Kocherov's avatar
draft  
Boris Kocherov committed
553 554
      function element_append(child) {
        if (child) {
555 556
          // insert additionalProperty before selector
          selector.element.parentNode.insertBefore(child, selector.element);
Boris Kocherov's avatar
draft  
Boris Kocherov committed
557 558 559
        }
      }

560 561 562 563 564
      input = document.createElement("input");
      input.type = "text";
      div_input.appendChild(input);

      input = document.createElement("button");
Boris Kocherov's avatar
Boris Kocherov committed
565 566 567
      input.setAttribute("class",
        "ui-shadow-inset ui-btn ui-btn-inline ui-corner-all" +
        " ui-btn-icon-notext ui-icon-btn ui-icon-plus ui-input-btn");
568 569
      input.type = "button";
      input.name = path;
570
      g.props.add_buttons.push({
571
        element: input,
Boris Kocherov's avatar
draft  
Boris Kocherov committed
572 573 574 575
        event: function () {
          return addSubForm({
            gadget: g,
            element: input,
576
            schema_path: schema_path + '/additionalProperties',
Boris Kocherov's avatar
draft  
Boris Kocherov committed
577 578 579 580
            schema_part: schema
          })
            .push(element_append);
        }
581 582 583 584 585
      });
      div_input.appendChild(input);
      div.appendChild(div_input);


Boris Kocherov's avatar
Boris Kocherov committed
586 587 588
      for (property_name in default_dict) {
        if (default_dict.hasOwnProperty(property_name) && !used_properties.hasOwnProperty(property_name)) {
          used_properties[property_name] = "";
589 590
          queue
            .push(
Boris Kocherov's avatar
draft  
Boris Kocherov committed
591 592
              addSubForm.bind(g, {
                gadget: g,
Boris Kocherov's avatar
Boris Kocherov committed
593
                property_name: property_name,
594 595
                path: path,
                element: input,
596
                schema_path: schema_path + '/additionalProperties',
597
                schema_part: schema,
Boris Kocherov's avatar
Boris Kocherov committed
598
                default_dict: default_dict[property_name]
599
              })
Boris Kocherov's avatar
draft  
Boris Kocherov committed
600 601
            )
            .push(element_append);
602 603 604 605 606 607 608
        }
      }
      queue.push(function () {
        root.appendChild(div);
      });
    }

609 610 611 612
    if (default_dict === undefined) {
      default_dict = {};
    }

613 614
    for (key in json_field.properties) {
      if (json_field.properties.hasOwnProperty(key)) {
Boris Kocherov's avatar
draft  
Boris Kocherov committed
615 616 617 618 619 620 621
        if (required.indexOf(key) >= 0) {
          used_properties[key] = false;
          if (json_field.properties[key].default !== undefined) {
            json_field.properties[key].info = '(default = ' + json_field.properties[key].default + ')';
          }
          queue
            .push(render_field.bind(g, g, key, path,
Boris Kocherov's avatar
Boris Kocherov committed
622 623
                json_field.properties[key], default_dict[key], root)
              );
Boris Kocherov's avatar
draft  
Boris Kocherov committed
624 625 626 627 628 629 630 631
        } else if (default_dict.hasOwnProperty(key)) {
          used_properties[key] = "";
          queue
            .push(
              addSubForm.bind(g, {
                gadget: g,
                property_name: key,
                path: path,
632
                schema_path: schema_path + '/properties/' + encodeJsonPointer(key),
Boris Kocherov's avatar
draft  
Boris Kocherov committed
633 634 635 636 637
                schema_part: json_field.properties[key],
                default_dict: default_dict[key]
              })
            )
            .push(root_append);
638 639 640
        }
      }
    }
641 642 643 644 645 646

    queue
      .push(function () {
        return g.declareGadget("gadget_html5_select.html", {scope: scope});
      })
      .push(selector.rerender)
647 648 649 650
      .push(function (element) {
        selector.element = element;
        return root_append(element);
      });
Boris Kocherov's avatar
draft  
Boris Kocherov committed
651

652 653
    if (json_field.patternProperties !== undefined) {
      if (json_field.patternProperties['.*'] !== undefined) {
654
        addAdditional(json_field.patternProperties['.*']);
655 656 657
      }
    }

Boris Kocherov's avatar
draft  
Boris Kocherov committed
658 659 660 661 662
    if (json_field.additionalProperties === undefined) {
      additionalProperties = true;
    } else {
      additionalProperties = json_field.additionalProperties;
    }
663
    if (getDocumentType(additionalProperties) === "object") {
Boris Kocherov's avatar
draft  
Boris Kocherov committed
664
      addAdditional(additionalProperties);
665 666
    }

667 668
    for (key in default_dict) {
      if (default_dict.hasOwnProperty(key)) {
669
        if (!used_properties.hasOwnProperty(key)) {
670
          queue
671 672 673 674 675 676 677 678 679 680 681
            .push(
              addSubForm.bind(g, {
                gadget: g,
                property_name: key,
                path: path,
                schema_path: "",
                schema_part: undefined,
                default_dict: default_dict[key]
              })
            )
            .push(root_append);
682 683 684
        }
      }
    }
685
    return queue;
Boris Kocherov's avatar
Boris Kocherov committed
686
  };
687

Boris Kocherov's avatar
Boris Kocherov committed
688
  function getFormValuesAsJSONDict(g) {
Boris Kocherov's avatar
Boris Kocherov committed
689
    var multi_level_dict = {"": {}},
690
      scope,
Boris Kocherov's avatar
Boris Kocherov committed
691 692
      options = g.props,
      array,
693 694
      path,
      key,
Boris Kocherov's avatar
Boris Kocherov committed
695 696
      i,
      len,
697
      queue = RSVP.Queue();
698

699
    function convertOnMultiLevel(d, key, value) {
Boris Kocherov's avatar
Boris Kocherov committed
700
      var ii,
701 702
        kk,
        key_list = key.split("/");
Boris Kocherov's avatar
Boris Kocherov committed
703 704 705
      for (ii = 0; ii < key_list.length; ii += 1) {
        kk = decodeJsonPointer(key_list[ii]);
        if (ii === key_list.length - 1) {
Boris Kocherov's avatar
Boris Kocherov committed
706
          if (value !== undefined) {
Boris Kocherov's avatar
Boris Kocherov committed
707
            d[kk] = value;
Boris Kocherov's avatar
Boris Kocherov committed
708 709
          } else {
            return d[kk];
Boris Kocherov's avatar
Boris Kocherov committed
710
          }
711 712 713 714 715 716 717 718 719
        } else {
          if (!d.hasOwnProperty(kk)) {
            d[kk] = {};
          }
          d = d[kk];
        }
      }
    }

720
    function recursiveGetContent(scope, path) {
721 722
      queue
        .push(function () {
723 724 725
          return g.getDeclaredGadget(scope);
        })
        .push(function (gadget) {
726 727 728
          return gadget.getContent();
        })
        .push(function (jdict) {
729
          convertOnMultiLevel(multi_level_dict, path, jdict);
730 731 732
        });
    }

Boris Kocherov's avatar
Boris Kocherov committed
733
    function getContentAndPushArray(scope, parent_path) {
Boris Kocherov's avatar
Boris Kocherov committed
734 735 736 737 738 739 740 741
      queue
        .push(function () {
          return g.getDeclaredGadget(scope);
        })
        .push(function (gadget) {
          return gadget.getContent();
        })
        .push(function (jdict) {
Boris Kocherov's avatar
Boris Kocherov committed
742
          var arr = convertOnMultiLevel(multi_level_dict, parent_path);
Boris Kocherov's avatar
Boris Kocherov committed
743 744
          if (!(arr instanceof Array)) {
            arr = [];
Boris Kocherov's avatar
Boris Kocherov committed
745
            convertOnMultiLevel(multi_level_dict, parent_path, arr);
Boris Kocherov's avatar
Boris Kocherov committed
746
          }
Boris Kocherov's avatar
Boris Kocherov committed
747
          arr.push(jdict);
Boris Kocherov's avatar
Boris Kocherov committed
748 749 750
        });
    }

751 752
    for (path in options.arrays) {
      if (options.arrays.hasOwnProperty(path)) {
753
        array = options.arrays[path]
754 755
          .querySelectorAll("div[data-json-parent='" + path + "']" +
            "[data-gadget-parent-scope='" + g.element.getAttribute("data-gadget-scope") + "']");
Boris Kocherov's avatar
Boris Kocherov committed
756
        len = array.length;
Boris Kocherov's avatar
Boris Kocherov committed
757
        for (i = 0; i < len; i = i + 1) {
Boris Kocherov's avatar
Boris Kocherov committed
758 759 760
          getContentAndPushArray(
            array[i].getAttribute('data-gadget-scope'),
            // slice remove concluding '/'
761
            path.slice(0, -1)
Boris Kocherov's avatar
Boris Kocherov committed
762 763 764 765 766
          );
        }
      }
    }

767 768 769 770 771 772 773 774 775 776
    for (path in options.objects) {
      if (options.objects.hasOwnProperty(path)) {
        for (key in options.objects[path]) {
          if (options.objects[path].hasOwnProperty(key)) {
            scope = options.objects[path][key];
            if (scope) {
              recursiveGetContent(scope, path + encodeJsonPointer(key));
            }
          }
        }
777 778 779
      }
    }

780 781
    return queue
      .push(function () {
782
        var json_dict = {},
Boris Kocherov's avatar
Boris Kocherov committed
783
          k;
784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
        g.props.inputs.forEach(function (input) {
          if (input.name === "" || input.value !== "") {
            if (input.type === 'number') {
              json_dict[input.name] = parseInt(input.value, 10);
            } else if (input.value === "true") {
              json_dict[input.name] = true;
            } else if (input.value === "false") {
              json_dict[input.name] = false;
            } else if (input.tagName === "TEXTAREA") {
              if (input["data-format"] === "string") {
                json_dict[input.name] = input.value;
              } else {
                json_dict[input.name] = input.value.split('\n');
              }
            } else {
              json_dict[input.name] = input.value;
            }
          }
        });
Boris Kocherov's avatar
Boris Kocherov committed
803 804 805
        for (k in json_dict) {
          if (json_dict.hasOwnProperty(k)) {
            convertOnMultiLevel(multi_level_dict, k, json_dict[k]);
806 807
          }
        }
808
        return multi_level_dict[""];
809
      });
810 811
  }

812 813
  function getSubGadgetElement(g, scope) {
    return g.element.querySelector("div[data-gadget-scope='" + scope + "']");
814 815
  }

816
  rJS(window)
Boris Kocherov's avatar
Boris Kocherov committed
817 818 819
    .ready(function () {
      var g = this;
      g.props = {};
820
      g.options = {};
Boris Kocherov's avatar
Boris Kocherov committed
821 822 823
    })
    .declareAcquiredMethod("notifyValid", "notifyValid")
    .declareAcquiredMethod("notifyInvalid", "notifyInvalid")
824

825
    .declareAcquiredMethod("renameChildrenParent", "renameChildren")
Boris Kocherov's avatar
Boris Kocherov committed
826
    .allowPublicAcquisition("renameChildren", function (opt_arr, scope) {
827 828
      var property_name,
        objects = this.props.objects,
Boris Kocherov's avatar
Boris Kocherov committed
829 830
        new_name = opt_arr[0],
        element = getSubGadgetElement(this, scope),
831 832 833
        parent = element.getAttribute('data-json-parent');
      if (objects.hasOwnProperty(parent)) {
        parent = objects[parent];
Boris Kocherov's avatar
Boris Kocherov committed
834
        if (parent.hasOwnProperty(new_name)) {
Boris Kocherov's avatar
Boris Kocherov committed
835
          throw new Error("property already exist");
836
        }
Boris Kocherov's avatar
Boris Kocherov committed
837
        // XXX validate property if property pattern
838
        for (property_name in parent) {
Boris Kocherov's avatar
Boris Kocherov committed
839
          if (parent.hasOwnProperty(property_name) && parent[property_name] === scope) {
840
            delete parent[property_name];
Boris Kocherov's avatar
Boris Kocherov committed
841 842
            parent[new_name] = scope;
            return new_name;
843 844
          }
        }
Boris Kocherov's avatar
Boris Kocherov committed
845
        throw new Error("gadget not found for renaming");
846 847 848 849 850
      }
    })
    .declareMethod("rename", function (new_name, event) {
      var g = this,
        name = g.element.getAttribute('data-json-property-name');
Boris Kocherov's avatar
Boris Kocherov committed
851
      return this.renameChildrenParent(new_name)
852 853 854 855
        .push(function () {
          return g.element.setAttribute('data-json-property-name', new_name);
        })
        .push(undefined, function (error) {
Boris Kocherov's avatar
Boris Kocherov committed
856
          // XXX notify user
857 858 859 860
          event.srcElement.value = name;
          event.srcElement.focus();
        });
    })
Boris Kocherov's avatar
Boris Kocherov committed
861 862
    .declareAcquiredMethod("selfRemove", "deleteChildren")
    .allowPublicAcquisition("deleteChildren", function (arr, scope) {
863 864
      var g = this,
        key,
865
        objects = this.props.objects,
Boris Kocherov's avatar
Boris Kocherov committed
866
        element = getSubGadgetElement(g, scope),
867 868
        parent = element.getAttribute("data-json-parent"),
        tasks = [];
869 870 871 872 873 874
      if (objects.hasOwnProperty(parent)) {
        parent = objects[parent];
        for (key in parent) {
          if (parent.hasOwnProperty(key) && parent[key] === scope) {
            delete parent[key];
          }
875 876 877
        }
      }
      element.parentNode.removeChild(element);
878 879 880 881 882 883 884 885
      for (key in g.props.add_property_selections) {
        if (g.props.add_property_selections.hasOwnProperty(key)) {
          tasks.push(g.props
            .add_property_selections[key]
            .rerender());
        }
      }
      return RSVP.All(tasks);
886 887
    })

888 889 890 891
    .declareAcquiredMethod("processValidationParent", "processValidation")
    .allowPublicAcquisition("processValidation", function (json_dict) {
      return this.processValidation(undefined, json_dict);
    })
Boris Kocherov's avatar
Boris Kocherov committed
892 893
    .declareMethod('processValidation', function (schema_url, json_dict) {
      var g = this;
894
      if (!schema_url) {
Boris Kocherov's avatar
Boris Kocherov committed
895
        if (g.options.schema_url) {
896
          schema_url = g.options.schema_url;
Boris Kocherov's avatar
Boris Kocherov committed
897 898
        } else {
          return g.processValidationParent(json_dict);
899 900
        }
      }
Boris Kocherov's avatar
Boris Kocherov committed
901 902
      if (!json_dict) {
        json_dict = getFormValuesAsJSONDict(g);
903 904 905 906 907
      } else {
        json_dict = RSVP.Queue()
          .push(function () {
            return json_dict;
          });
Boris Kocherov's avatar
Boris Kocherov committed
908
      }
909 910 911 912 913
      return RSVP.Queue()
        .push(function () {
          return RSVP.all([
            g.getDeclaredGadget('loadschema'),
            json_dict
914
          ]);
915 916 917
        })
        .push(function (ret) {
          var loadschema_gadget = ret[0],
Boris Kocherov's avatar
Boris Kocherov committed
918 919
            json_d = ret[1];
          return loadschema_gadget.validateJSON(schema_url, json_d);
Boris Kocherov's avatar
Boris Kocherov committed
920
        })
921
        .push(function (validation) {
922
          var index,
923
            div,
924
            field_name;
925

926
          g.element.querySelectorAll("span.error").forEach(function (span) {
927 928 929
            span.textContent = "";
          });

930
          g.element.querySelectorAll("div.error-input").forEach(function (div) {
931 932 933
            div.setAttribute("class", "");
          });
          if (validation.valid) {
Boris Kocherov's avatar
Boris Kocherov committed
934
            return "VALID";
935
          }
936 937 938 939
          for (index in validation.errors) {
            if (validation.errors.hasOwnProperty(index)) {
              field_name = validation.errors[index].dataPath;
              div = g.element.querySelector(".slapos-parameter[name='" + field_name  + "']").parentNode;
940
              div.setAttribute("class", "slapos-parameter error-input");
941
              div.querySelector("span.error").textContent = validation.errors[index].message;
942 943 944
            }
          }

945 946 947 948 949 950
          for (index in validation.missing) {
            if (validation.missing.hasOwnProperty(index)) {
              field_name = validation.missing[index].dataPath;
              div = g.element.querySelector('.slapos-parameter[name=' + field_name  + "']").parentNode;
              div.setAttribute("class", "error-input");
              div.querySelector("span.error").textContent = validation.missing[index].message;
951 952 953 954 955 956
            }
          }
          return "ERROR";
        });
    })

957
    .allowPublicAcquisition("notifyValid", function (arr, sub_scope) {
Boris Kocherov's avatar
Boris Kocherov committed
958
      return true;
959 960 961 962 963 964 965 966 967 968
    })
    .allowPublicAcquisition("notifyChange", function (arr, sub_scope) {
      var g = this,
        opt = arr[0];
      if (opt.type === "change") {
        return g.props
          .add_property_selections[sub_scope]
          .event();
      }
    })
Boris Kocherov's avatar
Boris Kocherov committed
969 970
    .declareMethod('renderForm', function (options) {
      var g = this,
971
        property_name = g.element.getAttribute('data-json-property-name'),
972
        schema = options.schema,
Boris Kocherov's avatar
Boris Kocherov committed
973 974
        delete_button,
        root;
975 976
      g.props.inputs = [];
      g.props.add_buttons = [];
977
      g.props.add_property_selections = {};
Boris Kocherov's avatar
Boris Kocherov committed
978
      g.props.arrays = {};
979
      g.props.objects = {};
Boris Kocherov's avatar
Boris Kocherov committed
980
      g.props.path = options.path; // self gadget scope
981 982
      if (!property_name || !options.display_label) {
        property_name = "";
Boris Kocherov's avatar
Boris Kocherov committed
983
      }
Boris Kocherov's avatar
Boris Kocherov committed
984 985 986 987 988 989
      root = g.element.querySelector('[data-json-path="/"]');
      if (!root) {
        root = g.element;
      }
      while (root.firstChild) {
        root.removeChild(root.firstChild);
990
      }
991 992
      if (!g.props.toplevel) {
        delete_button = document.createElement("button");
Boris Kocherov's avatar
Boris Kocherov committed
993 994 995
        delete_button.setAttribute("class",
          "ui-shadow-inset ui-btn ui-btn-inline ui-corner-all" +
          " ui-btn-icon-notext ui-icon-btn ui-icon-trash-o ui-input-btn");
996 997 998
        delete_button.type = "button";
        delete_button.name = options.path;
        g.props.delete_button = delete_button;
Boris Kocherov's avatar
Boris Kocherov committed
999
        root.appendChild(delete_button);
1000
      }
1001
      return render_field(g, property_name, "", schema, options.document, root, options.schema_path)
1002 1003 1004 1005
        .push(function () {
          g.listenEvents();
          return g.element;
        });
1006 1007
    })

1008 1009 1010 1011 1012 1013
    .declareMethod("loadJSONSchema", function (url, path) {
      var g = this,
        protocol,
        download_url,
        base_url,
        hash;
Boris Kocherov's avatar
Boris Kocherov committed
1014 1015 1016
      if (!g.props.toplevel) {
        return g.loadJSONSchemaParent(url, path);
      }
1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053
      // XXX need use $id
      base_url = getBaseUrl(g, path);
      if (!base_url) {
        // allow relative link
        base_url = window.location;
      }
      if (!path) {
        path = "/";
      }
      url = new URL(url, base_url);
      protocol = url.protocol;
      if (protocol === "http:" || protocol === "https:") {
        if (window.location.protocol !==  protocol) {
          throw new Error("You cannot mixed http and https calls");
        }
      }
      download_url = url.origin + url.pathname;
      hash = url.hash;
      url = url.href;
      return RSVP.Queue()
        .push(function () {
          if (g.props.schema_cache.hasOwnProperty(download_url)) {
            return g.props.schema_cache[download_url];
          }
          return downloadJSON(download_url)
            .push(function (json) {
              g.props.schema_cache[download_url] = json;
              return json;
            });
        })
        .push(function (json) {
          g.props.schema_map[path] = url;
          return resolveLocalReference(json, hash);
        });
    })
    .declareAcquiredMethod("loadJSONSchemaParent", "loadJSONSchemaTop")
    .allowPublicAcquisition("loadJSONSchemaTop", function (arr) {
Boris Kocherov's avatar
Boris Kocherov committed
1054
      return this.loadJSONSchema(arr[0], arr[1]);
1055
    })
1056
    .declareMethod('render', function (options) {
Boris Kocherov's avatar
Boris Kocherov committed
1057
      var g = this,
1058
        queue;
1059
      g.props.toplevel = true;
1060 1061 1062 1063 1064
      // contain map of current normalized schema
      // json pointer and corresponding url
      // it's need for schema uri computation
      g.props.schema_map = {};
      g.props.schema_cache = {};
Boris Kocherov's avatar
Boris Kocherov committed
1065 1066 1067 1068
      g.options = options;
      if (!options.value) {
        options.value = {};
      }
1069 1070 1071 1072 1073 1074
      if (options.schema) {
        queue = RSVP.Queue()
          .push(function () {
            return options.schema;
          });
      } else {
Boris Kocherov's avatar
Boris Kocherov committed
1075
        queue = g.loadJSONSchema(options.schema_url);
1076
      }
1077 1078
      return queue
        .push(function (schema) {
Boris Kocherov's avatar
Boris Kocherov committed
1079
          g.options.schema = schema;
Boris Kocherov's avatar
Boris Kocherov committed
1080 1081
          return g.renderForm({
            schema: schema,
1082
            schema_path: "",
Boris Kocherov's avatar
Boris Kocherov committed
1083 1084
            document: options.value
          });
1085 1086
        })
        .push(function () {
Boris Kocherov's avatar
Boris Kocherov committed
1087
          return g;
1088 1089 1090
        });
    })

1091 1092 1093
    .onEvent('click', function (evt) {
      if (evt.target === this.props.delete_button) {
        return this.selfRemove(evt);
1094 1095
      }

1096 1097 1098 1099 1100 1101
      var button_list = this.props.add_buttons,
        i;
      for (i = 0; i < button_list.length; i = i + 1) {
        if (evt.target === button_list[i].element) {
          return button_list[i].event(evt);
        }
1102
      }
1103
    })
1104

1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120
    .onEvent('change', function (evt) {
      if (evt.target === this.props.property_name_edit) {
        return this.rename(this.props.property_name_edit.value, evt);
      }

      var field_list = this.props.inputs,
        i;
      for (i = 0; i < field_list.length; i = i + 1) {
        if (evt.target === field_list[i].element) {
          return this.processValidation.bind(this, this.options.schema_url, undefined)(evt);
        }
      }
    })
    .declareJob('listenEvents', function () {
      // XXX Disable
      return;
1121 1122 1123
    })

    .declareMethod('getContent', function () {
1124 1125 1126 1127 1128 1129 1130 1131 1132
      var g = this;
      return getFormValuesAsJSONDict(g);
      // return g.processValidation(g.options.schema_url, json_dict)
      //   .push(function (status) {
      //     return {
      //       value: json_dict,
      //       status: status
      //     };
      //   });
1133 1134
    });

1135
}(window, document, rJS, RSVP, jIO));