renderjs.js 57.1 KB
Newer Older
1
/*! RenderJs */
2
/*jslint nomen: true*/
3

Ivan Tyagov's avatar
Ivan Tyagov committed
4
/*
5
 * renderJs - Generic Gadget library renderer.
Ivan Tyagov's avatar
Ivan Tyagov committed
6 7
 * http://www.renderjs.org/documentation
 */
8
(function (document, window, RSVP, DOMParser, Channel, MutationObserver,
Romain Courteaud's avatar
Romain Courteaud committed
9
           Node, FileReader, Blob, navigator, Event, URL) {
10
  "use strict";
11

12 13 14 15 16 17 18 19 20 21 22 23 24
  function readBlobAsDataURL(blob) {
    var fr = new FileReader();
    return new RSVP.Promise(function (resolve, reject) {
      fr.addEventListener("load", function (evt) {
        resolve(evt.target.result);
      });
      fr.addEventListener("error", reject);
      fr.readAsDataURL(blob);
    }, function () {
      fr.abort();
    });
  }

Romain Courteaud's avatar
Romain Courteaud committed
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
  function loopEventListener(target, type, useCapture, callback,
                             prevent_default) {
    //////////////////////////
    // Infinite event listener (promise is never resolved)
    // eventListener is removed when promise is cancelled/rejected
    //////////////////////////
    var handle_event_callback,
      callback_promise;

    if (prevent_default === undefined) {
      prevent_default = true;
    }

    function cancelResolver() {
      if ((callback_promise !== undefined) &&
          (typeof callback_promise.cancel === "function")) {
        callback_promise.cancel();
      }
    }

    function canceller() {
      if (handle_event_callback !== undefined) {
        target.removeEventListener(type, handle_event_callback, useCapture);
      }
      cancelResolver();
    }
    function itsANonResolvableTrap(resolve, reject) {
      var result;
      handle_event_callback = function (evt) {
        if (prevent_default) {
          evt.stopPropagation();
          evt.preventDefault();
        }

        cancelResolver();

        try {
          result = callback(evt);
        } catch (e) {
          result = RSVP.reject(e);
        }

        callback_promise = result;
        new RSVP.Queue()
          .push(function () {
            return result;
          })
          .push(undefined, function (error) {
            if (!(error instanceof RSVP.CancellationError)) {
              canceller();
              reject(error);
            }
          });
      };

      target.addEventListener(type, handle_event_callback, useCapture);
    }
    return new RSVP.Promise(itsANonResolvableTrap, canceller);
  }

85 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 124
  function ajax(url) {
    var xhr;
    function resolver(resolve, reject) {
      function handler() {
        try {
          if (xhr.readyState === 0) {
            // UNSENT
            reject(xhr);
          } else if (xhr.readyState === 4) {
            // DONE
            if ((xhr.status < 200) || (xhr.status >= 300) ||
                (!/^text\/html[;]?/.test(
                  xhr.getResponseHeader("Content-Type") || ""
                ))) {
              reject(xhr);
            } else {
              resolve(xhr);
            }
          }
        } catch (e) {
          reject(e);
        }
      }

      xhr = new XMLHttpRequest();
      xhr.open("GET", url);
      xhr.onreadystatechange = handler;
      xhr.setRequestHeader('Accept', 'text/html');
      xhr.withCredentials = true;
      xhr.send();
    }

    function canceller() {
      if ((xhr !== undefined) && (xhr.readyState !== xhr.DONE)) {
        xhr.abort();
      }
    }
    return new RSVP.Promise(resolver, canceller);
  }

125
  var gadget_model_defer_dict = {},
126 127
    javascript_registration_dict = {},
    stylesheet_registration_dict = {},
128
    gadget_loading_klass_list = [],
129
    loading_klass_promise,
130
    renderJS,
131
    Monitor,
132
    scope_increment = 0,
133
    isAbsoluteOrDataURL = new RegExp('^(?:[a-z]+:)?//|data:', 'i'),
134
    is_page_unloaded = false,
135 136
    error_list = [],
    bootstrap_deferred_object = new RSVP.defer();
137 138 139 140

  window.addEventListener('error', function (error) {
    error_list.push(error);
  });
141 142 143 144 145 146

  window.addEventListener('beforeunload', function () {
    // XXX If another listener cancel the page unload,
    // it will not restore renderJS crash report
    is_page_unloaded = true;
  });
147

148 149 150
  /////////////////////////////////////////////////////////////////
  // Helper functions
  /////////////////////////////////////////////////////////////////
151 152 153 154 155 156 157 158
  function removeHash(url) {
    var index = url.indexOf('#');
    if (index > 0) {
      url = url.substring(0, index);
    }
    return url;
  }

159
  function letsCrash(e) {
160 161 162
    var i,
      body,
      container,
163 164 165
      paragraph,
      link,
      error;
166 167 168 169 170 171
    if (is_page_unloaded) {
      /*global console*/
      console.info('-- Error dropped, as page is unloaded');
      console.info(e);
      return;
    }
172

173
    error_list.push(e);
174 175 176
    // Add error handling stack
    error_list.push(new Error('stopping renderJS'));

177 178 179 180
    body = document.getElementsByTagName('body')[0];
    while (body.firstChild) {
      body.removeChild(body.firstChild);
    }
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201

    container = document.createElement("section");
    paragraph = document.createElement("h1");
    paragraph.textContent = 'Unhandled Error';
    container.appendChild(paragraph);

    paragraph = document.createElement("p");
    paragraph.textContent = 'Please report this error to the support team';
    container.appendChild(paragraph);

    paragraph = document.createElement("p");
    paragraph.textContent = 'Location: ';
    link = document.createElement("a");
    link.href = link.textContent = window.location.toString();
    paragraph.appendChild(link);
    container.appendChild(paragraph);

    paragraph = document.createElement("p");
    paragraph.textContent = 'User-agent: ' + navigator.userAgent;
    container.appendChild(paragraph);

202 203 204 205
    paragraph = document.createElement("p");
    paragraph.textContent = 'Date: ' + new Date(Date.now()).toISOString();
    container.appendChild(paragraph);

206 207
    body.appendChild(container);

208
    for (i = 0; i < error_list.length; i += 1) {
209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242
      error = error_list[i];

      if (error instanceof Event) {
        error = {
          string: error.toString(),
          message: error.message,
          type: error.type,
          target: error.target
        };
        if (error.target !== undefined) {
          error_list.splice(i + 1, 0, error.target);
        }
      }

      if (error instanceof XMLHttpRequest) {
        error = {
          message: error.toString(),
          readyState: error.readyState,
          status: error.status,
          statusText: error.statusText,
          response: error.response,
          responseUrl: error.responseUrl,
          response_headers: error.getAllResponseHeaders()
        };
      }
      if (error.constructor === Array ||
          error.constructor === String ||
          error.constructor === Object) {
        try {
          error = JSON.stringify(error);
        } catch (ignore) {
        }
      }

243 244 245
      container = document.createElement("section");

      paragraph = document.createElement("h2");
246
      paragraph.textContent = error.message || error;
247 248
      container.appendChild(paragraph);

249
      if (error.fileName !== undefined) {
250 251
        paragraph = document.createElement("p");
        paragraph.textContent = 'File: ' +
252 253
          error.fileName +
          ': ' + error.lineNumber;
254 255 256
        container.appendChild(paragraph);
      }

257
      if (error.stack !== undefined) {
258
        paragraph = document.createElement("pre");
259
        paragraph.textContent = 'Stack: ' + error.stack;
260 261 262 263 264
        container.appendChild(paragraph);
      }

      body.appendChild(container);
    }
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 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381
    // XXX Do not crash the application if it fails
    // Where to write the error?
    /*global console*/
    console.error(e.stack);
    console.error(e);
  }

  /////////////////////////////////////////////////////////////////
  // Service Monitor promise
  /////////////////////////////////////////////////////////////////
  function ResolvedMonitorError(message) {
    this.name = "resolved";
    if ((message !== undefined) && (typeof message !== "string")) {
      throw new TypeError('You must pass a string.');
    }
    this.message = message || "Default Message";
  }
  ResolvedMonitorError.prototype = new Error();
  ResolvedMonitorError.prototype.constructor = ResolvedMonitorError;

  Monitor = function () {
    var monitor = this,
      promise_list = [],
      promise,
      reject,
      notify,
      resolved;

    if (!(this instanceof Monitor)) {
      return new Monitor();
    }

    function canceller() {
      var len = promise_list.length,
        i;
      for (i = 0; i < len; i += 1) {
        promise_list[i].cancel();
      }
      // Clean it to speed up other canceller run
      promise_list = [];
    }

    promise = new RSVP.Promise(function (done, fail, progress) {
      reject = function (rejectedReason) {
        if (resolved) {
          return;
        }
        monitor.isRejected = true;
        monitor.rejectedReason = rejectedReason;
        resolved = true;
        canceller();
        return fail(rejectedReason);
      };
      notify = progress;
    }, canceller);

    monitor.cancel = function () {
      if (resolved) {
        return;
      }
      resolved = true;
      promise.cancel();
      promise.fail(function (rejectedReason) {
        monitor.isRejected = true;
        monitor.rejectedReason = rejectedReason;
      });
    };
    monitor.then = function () {
      return promise.then.apply(promise, arguments);
    };
    monitor.fail = function () {
      return promise.fail.apply(promise, arguments);
    };

    monitor.monitor = function (promise_to_monitor) {
      if (resolved) {
        throw new ResolvedMonitorError();
      }
      var queue = new RSVP.Queue()
        .push(function () {
          return promise_to_monitor;
        })
        .push(function (fulfillmentValue) {
          // Promise to monitor is fullfilled, remove it from the list
          var len = promise_list.length,
            sub_promise_to_monitor,
            new_promise_list = [],
            i;
          for (i = 0; i < len; i += 1) {
            sub_promise_to_monitor = promise_list[i];
            if (!(sub_promise_to_monitor.isFulfilled ||
                sub_promise_to_monitor.isRejected)) {
              new_promise_list.push(sub_promise_to_monitor);
            }
          }
          promise_list = new_promise_list;
        }, function (rejectedReason) {
          if (rejectedReason instanceof RSVP.CancellationError) {
            if (!(promise_to_monitor.isFulfilled &&
                  promise_to_monitor.isRejected)) {
              // The queue could be cancelled before the first push is run
              promise_to_monitor.cancel();
            }
          }
          reject(rejectedReason);
          throw rejectedReason;
        }, function (notificationValue) {
          notify(notificationValue);
          return notificationValue;
        });

      promise_list.push(queue);

      return this;
    };
  };

Romain Courteaud's avatar
Romain Courteaud committed
382
  Monitor.prototype = Object.create(RSVP.Promise.prototype);
383 384
  Monitor.prototype.constructor = Monitor;

385 386 387
  /////////////////////////////////////////////////////////////////
  // RenderJSGadget
  /////////////////////////////////////////////////////////////////
388 389 390 391 392
  function RenderJSGadget() {
    if (!(this instanceof RenderJSGadget)) {
      return new RenderJSGadget();
    }
  }
393 394 395 396 397 398
  RenderJSGadget.prototype.__title = "";
  RenderJSGadget.prototype.__interface_list = [];
  RenderJSGadget.prototype.__path = "";
  RenderJSGadget.prototype.__html = "";
  RenderJSGadget.prototype.__required_css_list = [];
  RenderJSGadget.prototype.__required_js_list = [];
399

400 401 402 403 404
  function createMonitor(g) {
    if (g.__monitor !== undefined) {
      g.__monitor.cancel();
    }
    g.__monitor = new Monitor();
405 406 407
    g.__job_dict = {};
    g.__job_list = [];
    g.__job_triggered = false;
408 409 410 411 412 413 414 415 416 417
    g.__monitor.fail(function (error) {
      if (!(error instanceof RSVP.CancellationError)) {
        return g.aq_reportServiceError(error);
      }
    }).fail(function (error) {
      // Crash the application if the acquisition generates an error.
      return letsCrash(error);
    });
  }

418 419 420
  function clearGadgetInternalParameters() {
    this.__sub_gadget_dict = {};
    createMonitor(this);
421 422
  }

423 424
  function loadSubGadgetDOMDeclaration() {
    var element_list = this.element.querySelectorAll('[data-gadget-url]'),
425 426 427 428 429
      element,
      promise_list = [],
      scope,
      url,
      sandbox,
430 431 432 433 434 435 436 437 438 439 440 441 442 443
      i,
      context = this;

    function prepareReportGadgetDeclarationError(scope) {
      return function (error) {
        var aq_dict = context.__acquired_method_dict || {},
          method_name = 'reportGadgetDeclarationError';
        if (aq_dict.hasOwnProperty(method_name)) {
          return aq_dict[method_name].apply(context,
                                            [arguments, scope]);
        }
        throw error;
      };
    }
444 445 446 447 448 449

    for (i = 0; i < element_list.length; i += 1) {
      element = element_list[i];
      scope = element.getAttribute("data-gadget-scope");
      url = element.getAttribute("data-gadget-url");
      sandbox = element.getAttribute("data-gadget-sandbox");
450
      if (url !== null) {
451 452 453 454 455 456 457 458
        promise_list.push(
          context.declareGadget(url, {
            element: element,
            scope: scope || undefined,
            sandbox: sandbox || undefined
          })
            .push(undefined, prepareReportGadgetDeclarationError(scope))
        );
459 460 461 462 463 464 465 466
      }
    }

    return RSVP.all(promise_list);
  }

  RenderJSGadget.__ready_list = [clearGadgetInternalParameters,
                                 loadSubGadgetDOMDeclaration];
Romain Courteaud's avatar
Romain Courteaud committed
467
  RenderJSGadget.ready = function (callback) {
468
    this.__ready_list.push(callback);
Romain Courteaud's avatar
Romain Courteaud committed
469
    return this;
Romain Courteaud's avatar
Romain Courteaud committed
470
  };
471 472
  RenderJSGadget.setState = function (state_dict) {
    var json_state = JSON.stringify(state_dict);
473
    this.__ready_list.unshift(function () {
474 475
      this.state = JSON.parse(json_state);
    });
476
    return this;
477 478 479 480 481
  };
  RenderJSGadget.onStateChange = function (callback) {
    this.prototype.__state_change_callback = callback;
    return this;
  };
Romain Courteaud's avatar
Romain Courteaud committed
482

483 484 485 486 487
  RenderJSGadget.__service_list = [];
  RenderJSGadget.declareService = function (callback) {
    this.__service_list.push(callback);
    return this;
  };
Romain Courteaud's avatar
Romain Courteaud committed
488 489 490
  RenderJSGadget.onEvent = function (type, callback, use_capture,
                                     prevent_default) {
    this.__service_list.push(function () {
491
      return loopEventListener(this.element, type, use_capture,
Romain Courteaud's avatar
Romain Courteaud committed
492 493 494 495
                               callback.bind(this), prevent_default);
    });
    return this;
  };
496

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
  function runJob(gadget, name, callback, argument_list) {
    var job_promise = new RSVP.Queue()
      .push(function () {
        return callback.apply(gadget, argument_list);
      });
    if (gadget.__job_dict.hasOwnProperty(name)) {
      gadget.__job_dict[name].cancel();
    }
    gadget.__job_dict[name] = job_promise;
    gadget.__monitor.monitor(new RSVP.Queue()
      .push(function () {
        return job_promise;
      })
      .push(undefined, function (error) {
        if (!(error instanceof RSVP.CancellationError)) {
          throw error;
        }
      }));
  }

517 518 519 520
  function startService(gadget) {
    gadget.__monitor.monitor(new RSVP.Queue()
      .push(function () {
        var i,
521 522
          service_list = gadget.constructor.__service_list,
          job_list = gadget.__job_list;
523 524 525
        for (i = 0; i < service_list.length; i += 1) {
          gadget.__monitor.monitor(service_list[i].apply(gadget));
        }
526 527 528 529 530
        for (i = 0; i < job_list.length; i += 1) {
          runJob(gadget, job_list[i][0], job_list[i][1], job_list[i][2]);
        }
        gadget.__job_list = [];
        gadget.__job_triggered = true;
531 532 533 534
      })
      );
  }

535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554
  /////////////////////////////////////////////////////////////////
  // RenderJSGadget.declareJob
  // gadget internal method, which trigger execution
  // of a function inside a service
  /////////////////////////////////////////////////////////////////
  RenderJSGadget.declareJob = function (name, callback) {
    this.prototype[name] = function () {
      var context = this,
        argument_list = arguments;

      if (context.__job_triggered) {
        runJob(context, name, callback, argument_list);
      } else {
        context.__job_list.push([name, callback, argument_list]);
      }
    };
    // Allow chain
    return this;
  };

555 556 557
  /////////////////////////////////////////////////////////////////
  // RenderJSGadget.declareMethod
  /////////////////////////////////////////////////////////////////
Romain Courteaud's avatar
Romain Courteaud committed
558 559
  RenderJSGadget.declareMethod = function (name, callback) {
    this.prototype[name] = function () {
560 561 562 563 564 565
      var context = this,
        argument_list = arguments;

      return new RSVP.Queue()
        .push(function () {
          return callback.apply(context, argument_list);
Romain Courteaud's avatar
Romain Courteaud committed
566
        });
Romain Courteaud's avatar
Romain Courteaud committed
567 568 569
    };
    // Allow chain
    return this;
570 571
  };

Romain Courteaud's avatar
Romain Courteaud committed
572
  RenderJSGadget
Romain Courteaud's avatar
Romain Courteaud committed
573 574
    .declareMethod('getInterfaceList', function () {
      // Returns the list of gadget prototype
575
      return this.__interface_list;
Romain Courteaud's avatar
Romain Courteaud committed
576 577 578
    })
    .declareMethod('getRequiredCSSList', function () {
      // Returns a list of CSS required by the gadget
579
      return this.__required_css_list;
Romain Courteaud's avatar
Romain Courteaud committed
580 581 582
    })
    .declareMethod('getRequiredJSList', function () {
      // Returns a list of JS required by the gadget
583
      return this.__required_js_list;
Romain Courteaud's avatar
Romain Courteaud committed
584 585 586
    })
    .declareMethod('getPath', function () {
      // Returns the path of the code of a gadget
587
      return this.__path;
Romain Courteaud's avatar
Romain Courteaud committed
588 589 590
    })
    .declareMethod('getTitle', function () {
      // Returns the title of a gadget
591
      return this.__title;
Romain Courteaud's avatar
Romain Courteaud committed
592
    })
593 594
    .declareMethod('getElement', function () {
      // Returns the DOM Element of a gadget
595 596
      // XXX Kept for compatibility. Use element property directly
      if (this.element === undefined) {
597 598
        throw new Error("No element defined");
      }
599
      return this.element;
600 601
    })
    .declareMethod('changeState', function (state_dict) {
602 603
      var next_onStateChange = new RSVP.Queue(),
        previous_onStateCHange,
604
        context = this;
605 606 607
      if (context.hasOwnProperty('__previous_onStateChange')) {
        previous_onStateCHange = context.__previous_onStateChange;
        next_onStateChange
608
          .push(function () {
609
            return previous_onStateCHange;
610
          })
611 612 613
          .push(undefined, function () {
            // Run callback even if previous failed
            return;
614
          });
615
      }
616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648
      context.__previous_onStateChange = next_onStateChange;
      return next_onStateChange
        .push(function () {
          var key,
            modified = false,
            previous_cancelled = context.hasOwnProperty('__modification_dict'),
            modification_dict;
          if (previous_cancelled) {
            modification_dict = context.__modification_dict;
            modified = true;
          } else {
            modification_dict = {};
          }
          for (key in state_dict) {
            if (state_dict.hasOwnProperty(key) &&
                (state_dict[key] !== context.state[key])) {
              context.state[key] = state_dict[key];
              modification_dict[key] = state_dict[key];
              modified = true;
            }
          }
          if (modified && context.__state_change_callback !== undefined) {
            context.__modification_dict = modification_dict;
            return new RSVP.Queue()
              .push(function () {
                return context.__state_change_callback(modification_dict);
              })
              .push(function (result) {
                delete context.__modification_dict;
                return result;
              });
          }
        });
649 650
    });

651 652 653
  /////////////////////////////////////////////////////////////////
  // RenderJSGadget.declareAcquiredMethod
  /////////////////////////////////////////////////////////////////
654 655 656 657 658 659 660 661 662 663 664 665
  function acquire(child_gadget, method_name, argument_list) {
    var gadget = this,
      key,
      gadget_scope;

    for (key in gadget.__sub_gadget_dict) {
      if (gadget.__sub_gadget_dict.hasOwnProperty(key)) {
        if (gadget.__sub_gadget_dict[key] === child_gadget) {
          gadget_scope = key;
        }
      }
    }
666 667
    return new RSVP.Queue()
      .push(function () {
668 669 670 671 672
        // Do not specify default __acquired_method_dict on prototype
        // to prevent modifying this default value (with
        // allowPublicAcquiredMethod for example)
        var aq_dict = gadget.__acquired_method_dict || {};
        if (aq_dict.hasOwnProperty(method_name)) {
673 674
          return aq_dict[method_name].apply(gadget,
                                            [argument_list, gadget_scope]);
675 676 677 678 679
        }
        throw new renderJS.AcquisitionError("aq_dynamic is not defined");
      })
      .push(undefined, function (error) {
        if (error instanceof renderJS.AcquisitionError) {
680
          return gadget.__aq_parent(method_name, argument_list);
681 682 683 684 685 686 687 688
        }
        throw error;
      });
  }

  RenderJSGadget.declareAcquiredMethod =
    function (name, method_name_to_acquire) {
      this.prototype[name] = function () {
Romain Courteaud's avatar
Romain Courteaud committed
689 690 691 692 693 694
        var argument_list = Array.prototype.slice.call(arguments, 0),
          gadget = this;
        return new RSVP.Queue()
          .push(function () {
            return gadget.__aq_parent(method_name_to_acquire, argument_list);
          });
695 696 697 698 699
      };

      // Allow chain
      return this;
    };
700 701
  RenderJSGadget.declareAcquiredMethod("aq_reportServiceError",
                                       "reportServiceError");
702 703
  RenderJSGadget.declareAcquiredMethod("aq_reportGadgetDeclarationError",
                                       "reportGadgetDeclarationError");
704

705
  /////////////////////////////////////////////////////////////////
706
  // RenderJSGadget.allowPublicAcquisition
707 708 709 710 711 712 713 714 715
  /////////////////////////////////////////////////////////////////
  RenderJSGadget.allowPublicAcquisition =
    function (method_name, callback) {
      this.prototype.__acquired_method_dict[method_name] = callback;

      // Allow chain
      return this;
    };

716 717 718 719 720 721 722 723
  // Set aq_parent on gadget_instance which call acquire on parent_gadget
  function setAqParent(gadget_instance, parent_gadget) {
    gadget_instance.__aq_parent = function (method_name, argument_list) {
      return acquire.apply(parent_gadget, [gadget_instance, method_name,
                                           argument_list]);
    };
  }

724 725 726 727 728 729 730
  /////////////////////////////////////////////////////////////////
  // RenderJSEmbeddedGadget
  /////////////////////////////////////////////////////////////////
  // Class inheritance
  function RenderJSEmbeddedGadget() {
    if (!(this instanceof RenderJSEmbeddedGadget)) {
      return new RenderJSEmbeddedGadget();
731
    }
732 733
    RenderJSGadget.call(this);
  }
734
  RenderJSEmbeddedGadget.__ready_list = RenderJSGadget.__ready_list.slice();
735 736
  RenderJSEmbeddedGadget.__service_list =
    RenderJSGadget.__service_list.slice();
737 738
  RenderJSEmbeddedGadget.ready =
    RenderJSGadget.ready;
739 740 741 742
  RenderJSEmbeddedGadget.setState =
    RenderJSGadget.setState;
  RenderJSEmbeddedGadget.onStateChange =
    RenderJSGadget.onStateChange;
743 744
  RenderJSEmbeddedGadget.declareService =
    RenderJSGadget.declareService;
Romain Courteaud's avatar
Romain Courteaud committed
745 746
  RenderJSEmbeddedGadget.onEvent =
    RenderJSGadget.onEvent;
747 748 749 750 751 752
  RenderJSEmbeddedGadget.prototype = new RenderJSGadget();
  RenderJSEmbeddedGadget.prototype.constructor = RenderJSEmbeddedGadget;

  /////////////////////////////////////////////////////////////////
  // privateDeclarePublicGadget
  /////////////////////////////////////////////////////////////////
753
  function privateDeclarePublicGadget(url, options, parent_gadget) {
754

755
    return new RSVP.Queue()
756
      .push(function () {
757 758 759 760 761 762 763 764
        return renderJS.declareGadgetKlass(url)
          // gadget loading should not be interrupted
          // if not, gadget's definition will not be complete
          //.then will return another promise
          //so loading_klass_promise can't be cancel
          .then(function (result) {
            return result;
          });
765
      })
766
      // Get the gadget class and instanciate it
767
      .push(function (Klass) {
768 769 770
        if (options.element === undefined) {
          options.element = document.createElement("div");
        }
771
        var i,
772
          gadget_instance,
773 774
          template_node_list = Klass.__template_element.body.childNodes,
          fragment = document.createDocumentFragment();
775
        gadget_instance = new Klass();
776
        gadget_instance.element = options.element;
777
        gadget_instance.state = {};
778
        for (i = 0; i < template_node_list.length; i += 1) {
779
          fragment.appendChild(
780 781
            template_node_list[i].cloneNode(true)
          );
782
        }
783
        gadget_instance.element.appendChild(fragment);
784
        setAqParent(gadget_instance, parent_gadget);
785 786 787 788 789 790 791 792 793 794 795 796 797
        return gadget_instance;
      });
  }

  /////////////////////////////////////////////////////////////////
  // RenderJSIframeGadget
  /////////////////////////////////////////////////////////////////
  function RenderJSIframeGadget() {
    if (!(this instanceof RenderJSIframeGadget)) {
      return new RenderJSIframeGadget();
    }
    RenderJSGadget.call(this);
  }
798
  RenderJSIframeGadget.__ready_list = RenderJSGadget.__ready_list.slice();
799 800
  RenderJSIframeGadget.ready =
    RenderJSGadget.ready;
801 802 803 804
  RenderJSIframeGadget.setState =
    RenderJSGadget.setState;
  RenderJSIframeGadget.onStateChange =
    RenderJSGadget.onStateChange;
805 806 807
  RenderJSIframeGadget.__service_list = RenderJSGadget.__service_list.slice();
  RenderJSIframeGadget.declareService =
    RenderJSGadget.declareService;
Romain Courteaud's avatar
Romain Courteaud committed
808 809
  RenderJSIframeGadget.onEvent =
    RenderJSGadget.onEvent;
810 811 812 813 814 815
  RenderJSIframeGadget.prototype = new RenderJSGadget();
  RenderJSIframeGadget.prototype.constructor = RenderJSIframeGadget;

  /////////////////////////////////////////////////////////////////
  // privateDeclareIframeGadget
  /////////////////////////////////////////////////////////////////
816
  function privateDeclareIframeGadget(url, options, parent_gadget) {
817 818 819 820
    var gadget_instance,
      iframe,
      iframe_loading_deferred = RSVP.defer();
    if (options.element === undefined) {
821 822
      throw new Error("DOM element is required to create Iframe Gadget " +
                      url);
823 824 825
    }

    // Check if the element is attached to the DOM
826
    if (!document.contains(options.element)) {
827 828
      throw new Error("The parent element is not attached to the DOM for " +
                      url);
829 830 831
    }

    gadget_instance = new RenderJSIframeGadget();
832
    setAqParent(gadget_instance, parent_gadget);
833
    iframe = document.createElement("iframe");
834 835 836 837 838 839 840 841 842 843 844
    iframe.addEventListener('error', function (error) {
      iframe_loading_deferred.reject(error);
    });
    iframe.addEventListener('load', function () {
      return RSVP.timeout(5000)
        .fail(function () {
          iframe_loading_deferred.reject(
            new Error('Timeout while loading: ' + url)
          );
        });
    });
845 846
//    gadget_instance.element.setAttribute("seamless", "seamless");
    iframe.setAttribute("src", url);
847
    gadget_instance.__path = url;
848
    gadget_instance.element = options.element;
849
    gadget_instance.state = {};
850 851 852 853 854 855
    // Attach it to the DOM
    options.element.appendChild(iframe);

    // XXX Manage unbind when deleting the gadget

    // Create the communication channel with the iframe
856
    gadget_instance.__chan = Channel.build({
857 858 859 860 861 862
      window: iframe.contentWindow,
      origin: "*",
      scope: "renderJS"
    });

    // Create new method from the declareMethod call inside the iframe
863 864 865
    gadget_instance.__chan.bind("declareMethod",
                                function (trans, method_name) {
        gadget_instance[method_name] = function () {
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883
          var argument_list = arguments,
            wait_promise = new RSVP.Promise(function (resolve, reject) {
              gadget_instance.__chan.call({
                method: "methodCall",
                params: [
                  method_name,
                  Array.prototype.slice.call(argument_list, 0)],
                success: function (s) {
                  resolve(s);
                },
                error: function (e) {
                  reject(e);
                }
              });
            });
          return new RSVP.Queue()
            .push(function () {
              return wait_promise;
884 885 886 887
            });
        };
        return "OK";
      });
888 889

    // Wait for the iframe to be loaded before continuing
890
    gadget_instance.__chan.bind("ready", function (trans) {
891 892 893
      iframe_loading_deferred.resolve(gadget_instance);
      return "OK";
    });
894
    gadget_instance.__chan.bind("failed", function (trans, params) {
895 896 897
      iframe_loading_deferred.reject(params);
      return "OK";
    });
898
    gadget_instance.__chan.bind("acquire", function (trans, params) {
Romain Courteaud's avatar
Romain Courteaud committed
899
      gadget_instance.__aq_parent.apply(gadget_instance, params)
900 901 902 903 904 905 906 907
        .then(function (g) {
          trans.complete(g);
        }).fail(function (e) {
          trans.error(e.toString());
        });
      trans.delayReturn(true);
    });

908
    return iframe_loading_deferred.promise;
909 910
  }

911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937
  /////////////////////////////////////////////////////////////////
  // privateDeclareDataUrlGadget
  /////////////////////////////////////////////////////////////////
  function privateDeclareDataUrlGadget(url, options, parent_gadget) {

    return new RSVP.Queue()
      .push(function () {
        return ajax(url);
      })
      .push(function (xhr) {
        // Insert a "base" element, in order to resolve all relative links
        // which could get broken with a data url
        var doc = (new DOMParser()).parseFromString(xhr.responseText,
                                                    'text/html'),
          base = doc.createElement('base'),
          blob;
        base.href = url;
        doc.head.insertBefore(base, doc.head.firstChild);
        blob = new Blob([doc.documentElement.outerHTML],
                        {type: "text/html;charset=UTF-8"});
        return readBlobAsDataURL(blob);
      })
      .push(function (data_url) {
        return privateDeclareIframeGadget(data_url, options, parent_gadget);
      });
  }

938 939 940
  /////////////////////////////////////////////////////////////////
  // RenderJSGadget.declareGadget
  /////////////////////////////////////////////////////////////////
941 942
  RenderJSGadget
    .declareMethod('declareGadget', function (url, options) {
943
      var parent_gadget = this;
944

945 946 947 948 949 950
      if (options === undefined) {
        options = {};
      }
      if (options.sandbox === undefined) {
        options.sandbox = "public";
      }
951

952 953
      // transform url to absolute url if it is relative
      url = renderJS.getAbsoluteURL(url, this.__path);
954 955

      return new RSVP.Queue()
956 957 958 959 960 961
        .push(function () {
          var method;
          if (options.sandbox === "public") {
            method = privateDeclarePublicGadget;
          } else if (options.sandbox === "iframe") {
            method = privateDeclareIframeGadget;
962 963
          } else if (options.sandbox === "dataurl") {
            method = privateDeclareDataUrlGadget;
964 965 966 967
          } else {
            throw new Error("Unsupported sandbox options '" +
                            options.sandbox + "'");
          }
968
          return method(url, options, parent_gadget);
969 970
        })
        // Set the HTML context
971
        .push(function (gadget_instance) {
972
          var i,
973 974
            scope,
            queue = new RSVP.Queue();
975 976 977 978
          // Trigger calling of all ready callback
          function ready_wrapper() {
            return gadget_instance;
          }
979
          function ready_executable_wrapper(fct) {
980 981
            return function () {
              return fct.call(gadget_instance, gadget_instance);
982 983
            };
          }
984
          for (i = 0; i < gadget_instance.constructor.__ready_list.length;
985 986
               i += 1) {
            // Put a timeout?
987 988 989
            queue.push(ready_executable_wrapper(
              gadget_instance.constructor.__ready_list[i]
            ));
990 991 992
            // Always return the gadget instance after ready function
            queue.push(ready_wrapper);
          }
993

994
          // Store local reference to the gadget instance
995 996 997 998 999 1000 1001 1002
          scope = options.scope;
          if (scope === undefined) {
            scope = 'RJS_' + scope_increment;
            scope_increment += 1;
            while (parent_gadget.__sub_gadget_dict.hasOwnProperty(scope)) {
              scope = 'RJS_' + scope_increment;
              scope_increment += 1;
            }
1003
          }
1004
          parent_gadget.__sub_gadget_dict[scope] = gadget_instance;
1005 1006
          gadget_instance.element.setAttribute("data-gadget-scope",
                                               scope);
1007

1008
          // Put some attribute to ease page layout comprehension
1009 1010 1011 1012
          gadget_instance.element.setAttribute("data-gadget-url", url);
          gadget_instance.element.setAttribute("data-gadget-sandbox",
                                               options.sandbox);
          gadget_instance.element._gadget = gadget_instance;
1013

1014
          if (document.contains(gadget_instance.element)) {
1015 1016 1017 1018 1019
            // Put a timeout
            queue.push(startService);
          }
          // Always return the gadget instance after ready function
          queue.push(ready_wrapper);
1020

1021
          return queue;
1022 1023
        });
    })
1024
    .declareMethod('getDeclaredGadget', function (gadget_scope) {
1025
      if (!this.__sub_gadget_dict.hasOwnProperty(gadget_scope)) {
1026 1027
        throw new Error("Gadget scope '" + gadget_scope + "' is not known.");
      }
1028
      return this.__sub_gadget_dict[gadget_scope];
1029 1030
    })
    .declareMethod('dropGadget', function (gadget_scope) {
1031
      if (!this.__sub_gadget_dict.hasOwnProperty(gadget_scope)) {
1032 1033 1034
        throw new Error("Gadget scope '" + gadget_scope + "' is not known.");
      }
      // http://perfectionkills.com/understanding-delete/
1035
      delete this.__sub_gadget_dict[gadget_scope];
1036
    });
Romain Courteaud's avatar
Romain Courteaud committed
1037

1038 1039 1040
  /////////////////////////////////////////////////////////////////
  // renderJS selector
  /////////////////////////////////////////////////////////////////
1041
  renderJS = function (selector) {
Romain Courteaud's avatar
Romain Courteaud committed
1042 1043
    var result;
    if (selector === window) {
1044
      // window is the 'this' value when loading a javascript file
Romain Courteaud's avatar
Romain Courteaud committed
1045
      // In this case, use the current loading gadget constructor
1046
      result = gadget_loading_klass_list[0];
Romain Courteaud's avatar
Romain Courteaud committed
1047 1048 1049 1050 1051
    }
    if (result === undefined) {
      throw new Error("Unknown selector '" + selector + "'");
    }
    return result;
1052 1053
  };

1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067
  /////////////////////////////////////////////////////////////////
  // renderJS.AcquisitionError
  /////////////////////////////////////////////////////////////////
  renderJS.AcquisitionError = function (message) {
    this.name = "AcquisitionError";
    if ((message !== undefined) && (typeof message !== "string")) {
      throw new TypeError('You must pass a string.');
    }
    this.message = message || "Acquisition failed";
  };
  renderJS.AcquisitionError.prototype = new Error();
  renderJS.AcquisitionError.prototype.constructor =
    renderJS.AcquisitionError;

1068 1069 1070 1071
  /////////////////////////////////////////////////////////////////
  // renderJS.getAbsoluteURL
  /////////////////////////////////////////////////////////////////
  renderJS.getAbsoluteURL = function (url, base_url) {
Romain Courteaud's avatar
Romain Courteaud committed
1072 1073
    if (base_url && url) {
      return new URL(url, base_url).href;
1074 1075 1076 1077
    }
    return url;
  };

1078 1079 1080
  /////////////////////////////////////////////////////////////////
  // renderJS.declareJS
  /////////////////////////////////////////////////////////////////
1081
  renderJS.declareJS = function (url, container, pop) {
1082
    // https://www.html5rocks.com/en/tutorials/speed/script-loading/
1083 1084 1085
    // Prevent infinite recursion if loading render.js
    // more than once
    var result;
1086
    if (javascript_registration_dict.hasOwnProperty(url)) {
1087
      result = RSVP.resolve();
1088
    } else {
1089
      javascript_registration_dict[url] = null;
1090 1091 1092
      result = new RSVP.Promise(function (resolve, reject) {
        var newScript;
        newScript = document.createElement('script');
1093
        newScript.async = false;
1094 1095
        newScript.type = 'text/javascript';
        newScript.onload = function () {
1096 1097 1098 1099
          if (pop === true) {
            // Drop the current loading klass info used by selector
            gadget_loading_klass_list.shift();
          }
1100 1101 1102
          resolve();
        };
        newScript.onerror = function (e) {
1103 1104 1105 1106
          if (pop === true) {
            // Drop the current loading klass info used by selector
            gadget_loading_klass_list.shift();
          }
1107 1108
          reject(e);
        };
1109 1110
        newScript.src = url;
        container.appendChild(newScript);
1111 1112
      });
    }
1113
    return result;
1114 1115
  };

1116 1117 1118
  /////////////////////////////////////////////////////////////////
  // renderJS.declareCSS
  /////////////////////////////////////////////////////////////////
1119
  renderJS.declareCSS = function (url, container) {
1120
    // https://github.com/furf/jquery-getCSS/blob/master/jquery.getCSS.js
1121 1122 1123
    // No way to cleanly check if a css has been loaded
    // So, always resolve the promise...
    // http://requirejs.org/docs/faq-advanced.html#css
1124
    var result;
1125
    if (stylesheet_registration_dict.hasOwnProperty(url)) {
1126
      result = RSVP.resolve();
1127
    } else {
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140
      result = new RSVP.Promise(function (resolve, reject) {
        var link;
        link = document.createElement('link');
        link.rel = 'stylesheet';
        link.type = 'text/css';
        link.href = url;
        link.onload = function () {
          stylesheet_registration_dict[url] = null;
          resolve();
        };
        link.onerror = function (e) {
          reject(e);
        };
1141
        container.appendChild(link);
1142 1143 1144 1145
      });
    }
    return result;
  };
1146

1147 1148 1149
  /////////////////////////////////////////////////////////////////
  // renderJS.declareGadgetKlass
  /////////////////////////////////////////////////////////////////
1150

1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194
  function parse(xhr, url) {
    var tmp_constructor,
      key,
      parsed_html;
    // Class inheritance
    tmp_constructor = function () {
      RenderJSGadget.call(this);
    };
    tmp_constructor.__ready_list = RenderJSGadget.__ready_list.slice();
    tmp_constructor.__service_list = RenderJSGadget.__service_list.slice();
    tmp_constructor.declareMethod =
      RenderJSGadget.declareMethod;
    tmp_constructor.declareJob =
      RenderJSGadget.declareJob;
    tmp_constructor.declareAcquiredMethod =
      RenderJSGadget.declareAcquiredMethod;
    tmp_constructor.allowPublicAcquisition =
      RenderJSGadget.allowPublicAcquisition;
    tmp_constructor.ready =
      RenderJSGadget.ready;
    tmp_constructor.setState =
      RenderJSGadget.setState;
    tmp_constructor.onStateChange =
      RenderJSGadget.onStateChange;
    tmp_constructor.declareService =
      RenderJSGadget.declareService;
    tmp_constructor.onEvent =
      RenderJSGadget.onEvent;
    tmp_constructor.prototype = new RenderJSGadget();
    tmp_constructor.prototype.constructor = tmp_constructor;
    tmp_constructor.prototype.__path = url;
    tmp_constructor.prototype.__acquired_method_dict = {};
    // https://developer.mozilla.org/en-US/docs/HTML_in_XMLHttpRequest
    // https://developer.mozilla.org/en-US/docs/Web/API/DOMParser
    // https://developer.mozilla.org/en-US/docs/Code_snippets/HTML_to_DOM
    tmp_constructor.__template_element =
      (new DOMParser()).parseFromString(xhr.responseText, "text/html");
    parsed_html = renderJS.parseGadgetHTMLDocument(
      tmp_constructor.__template_element,
      url
    );
    for (key in parsed_html) {
      if (parsed_html.hasOwnProperty(key)) {
        tmp_constructor.prototype['__' + key] = parsed_html[key];
1195 1196
      }
    }
1197 1198
    return tmp_constructor;
  }
1199

1200 1201
  renderJS.declareGadgetKlass = function (url) {
    if (gadget_model_defer_dict.hasOwnProperty(url)) {
1202
      // Return klass object if it already exists
1203
      return gadget_model_defer_dict[url].promise;
1204
    }
1205 1206

    var tmp_constructor,
1207
      defer = RSVP.defer();
1208 1209 1210 1211 1212 1213 1214 1215 1216

    gadget_model_defer_dict[url] = defer;

    // Change the global variable to update the loading queue
    loading_klass_promise = defer.promise;

    // Fetch the HTML page and parse it
    return new RSVP.Queue()
      .push(function () {
1217
        return ajax(url);
1218
      })
1219 1220
      .push(function (result) {
        tmp_constructor = parse(result, url);
1221 1222 1223 1224 1225 1226
        var fragment = document.createDocumentFragment(),
          promise_list = [],
          i,
          js_list = tmp_constructor.prototype.__required_js_list,
          css_list = tmp_constructor.prototype.__required_css_list;
        // Load JS
1227 1228 1229 1230 1231 1232
        if (js_list.length) {
          gadget_loading_klass_list.push(tmp_constructor);
          for (i = 0; i < js_list.length - 1; i += 1) {
            promise_list.push(renderJS.declareJS(js_list[i], fragment));
          }
          promise_list.push(renderJS.declareJS(js_list[i], fragment, true));
1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
        }
        // Load CSS
        for (i = 0; i < css_list.length; i += 1) {
          promise_list.push(renderJS.declareCSS(css_list[i], fragment));
        }
        document.head.appendChild(fragment);
        return RSVP.all(promise_list);
      })
      .push(function () {
        defer.resolve(tmp_constructor);
        return tmp_constructor;
      })
      .push(undefined, function (e) {
        // Drop the current loading klass info used by selector
        // even in case of error
        defer.reject(e);
        throw e;
      });
1251 1252
  };

1253 1254 1255
  /////////////////////////////////////////////////////////////////
  // renderJS.clearGadgetKlassList
  /////////////////////////////////////////////////////////////////
1256 1257
  // For test purpose only
  renderJS.clearGadgetKlassList = function () {
1258
    gadget_model_defer_dict = {};
1259 1260
    javascript_registration_dict = {};
    stylesheet_registration_dict = {};
1261 1262
  };

1263 1264 1265
  /////////////////////////////////////////////////////////////////
  // renderJS.parseGadgetHTMLDocument
  /////////////////////////////////////////////////////////////////
1266
  renderJS.parseGadgetHTMLDocument = function (document_element, url) {
1267
    var settings = {
1268 1269 1270
        title: "",
        interface_list: [],
        required_css_list: [],
1271
        required_js_list: []
1272 1273
      },
      i,
1274
      element;
1275

1276
    if (!url || !isAbsoluteOrDataURL.test(url)) {
1277
      throw new Error("The url should be absolute: " + url);
1278 1279
    }

1280 1281 1282
    if (document_element.nodeType === 9) {
      settings.title = document_element.title;

1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304
      if (document_element.head !== null) {
        for (i = 0; i < document_element.head.children.length; i += 1) {
          element = document_element.head.children[i];
          if (element.href !== null) {
            // XXX Manage relative URL during extraction of URLs
            // element.href returns absolute URL in firefox but "" in chrome;
            if (element.rel === "stylesheet") {
              settings.required_css_list.push(
                renderJS.getAbsoluteURL(element.getAttribute("href"), url)
              );
            } else if (element.nodeName === "SCRIPT" &&
                       (element.type === "text/javascript" ||
                        !element.type)) {
              settings.required_js_list.push(
                renderJS.getAbsoluteURL(element.getAttribute("src"), url)
              );
            } else if (element.rel ===
                       "http://www.renderjs.org/rel/interface") {
              settings.interface_list.push(
                renderJS.getAbsoluteURL(element.getAttribute("href"), url)
              );
            }
1305 1306
          }
        }
Romain Courteaud's avatar
Typo  
Romain Courteaud committed
1307
      }
1308
    } else {
1309
      throw new Error("The first parameter should be an HTMLDocument");
1310
    }
1311
    return settings;
1312
  };
1313 1314 1315 1316

  /////////////////////////////////////////////////////////////////
  // global
  /////////////////////////////////////////////////////////////////
1317
  window.rJS = window.renderJS = renderJS;
1318 1319 1320
  window.__RenderJSGadget = RenderJSGadget;
  window.__RenderJSEmbeddedGadget = RenderJSEmbeddedGadget;
  window.__RenderJSIframeGadget = RenderJSIframeGadget;
1321 1322 1323 1324 1325

  ///////////////////////////////////////////////////
  // Bootstrap process. Register the self gadget.
  ///////////////////////////////////////////////////

1326 1327 1328 1329 1330 1331 1332 1333 1334 1335

  // Manually initializes the self gadget if the DOMContentLoaded event
  // is triggered before everything was ready.
  // (For instance, the HTML-tag for the self gadget gets inserted after
  //  page load)
  renderJS.manualBootstrap = function () {
    bootstrap_deferred_object.resolve();
  };


Romain Courteaud's avatar
Romain Courteaud committed
1336
  function bootstrap() {
1337
    var url = removeHash(window.location.href),
1338
      TmpConstructor,
1339
      root_gadget,
1340
      loading_gadget_promise = new RSVP.Queue(),
1341 1342 1343 1344
      declare_method_count = 0,
      embedded_channel,
      notifyReady,
      notifyDeclareMethod,
1345
      gadget_ready = false,
Xiaowu Zhang's avatar
Xiaowu Zhang committed
1346
      iframe_top_gadget,
1347 1348 1349 1350 1351
      last_acquisition_gadget,
      declare_method_list_waiting = [],
      gadget_failed = false,
      gadget_error,
      connection_ready = false;
1352

Romain Courteaud's avatar
Romain Courteaud committed
1353
    // Create the gadget class for the current url
1354
    if (gadget_model_defer_dict.hasOwnProperty(url)) {
Romain Courteaud's avatar
Romain Courteaud committed
1355
      throw new Error("bootstrap should not be called twice");
1356
    }
1357
    loading_klass_promise = new RSVP.Promise(function (resolve, reject) {
1358

Xiaowu Zhang's avatar
Xiaowu Zhang committed
1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371
      last_acquisition_gadget = new RenderJSGadget();
      last_acquisition_gadget.__acquired_method_dict = {
        reportServiceError: function (param_list) {
          letsCrash(param_list[0]);
        }
      };
      // Stop acquisition on the last acquisition gadget
      // Do not put this on the klass, as their could be multiple instances
      last_acquisition_gadget.__aq_parent = function (method_name) {
        throw new renderJS.AcquisitionError(
          "No gadget provides " + method_name
        );
      };
1372

Xiaowu Zhang's avatar
Xiaowu Zhang committed
1373 1374 1375 1376 1377 1378 1379 1380 1381
      //we need to determine tmp_constructor's value before exit bootstrap
      //because of function : renderJS
      //but since the channel checking is async,
      //we can't use code structure like:
      // if channel communication is ok
      //    tmp_constructor = RenderJSGadget
      // else
      //    tmp_constructor = RenderJSEmbeddedGadget
      if (window.self === window.top) {
1382
        // XXX Copy/Paste from declareGadgetKlass
1383
        TmpConstructor = function () {
1384 1385
          RenderJSGadget.call(this);
        };
1386 1387 1388
        TmpConstructor.declareMethod = RenderJSGadget.declareMethod;
        TmpConstructor.declareJob = RenderJSGadget.declareJob;
        TmpConstructor.declareAcquiredMethod =
1389
          RenderJSGadget.declareAcquiredMethod;
1390
        TmpConstructor.allowPublicAcquisition =
1391
          RenderJSGadget.allowPublicAcquisition;
1392 1393 1394 1395 1396 1397
        TmpConstructor.__ready_list = RenderJSGadget.__ready_list.slice();
        TmpConstructor.ready = RenderJSGadget.ready;
        TmpConstructor.setState = RenderJSGadget.setState;
        TmpConstructor.onStateChange = RenderJSGadget.onStateChange;
        TmpConstructor.__service_list = RenderJSGadget.__service_list.slice();
        TmpConstructor.declareService =
1398
          RenderJSGadget.declareService;
1399
        TmpConstructor.onEvent =
Romain Courteaud's avatar
Romain Courteaud committed
1400
          RenderJSGadget.onEvent;
1401 1402 1403 1404 1405 1406
        TmpConstructor.prototype = new RenderJSGadget();
        TmpConstructor.prototype.constructor = TmpConstructor;
        TmpConstructor.prototype.__path = url;
        gadget_model_defer_dict[url] = {
          promise: RSVP.resolve(TmpConstructor)
        };
1407 1408

        // Create the root gadget instance and put it in the loading stack
1409
        root_gadget = new TmpConstructor();
1410

1411
        setAqParent(root_gadget, last_acquisition_gadget);
1412

1413 1414
      } else {
        // Create the root gadget instance and put it in the loading stack
1415 1416 1417 1418
        TmpConstructor = RenderJSEmbeddedGadget;
        TmpConstructor.__ready_list = RenderJSGadget.__ready_list.slice();
        TmpConstructor.__service_list = RenderJSGadget.__service_list.slice();
        TmpConstructor.prototype.__path = url;
1419
        root_gadget = new RenderJSEmbeddedGadget();
1420
        setAqParent(root_gadget, last_acquisition_gadget);
1421

1422 1423 1424 1425 1426 1427 1428 1429 1430 1431
        // Create the communication channel
        embedded_channel = Channel.build({
          window: window.parent,
          origin: "*",
          scope: "renderJS",
          onReady: function () {
            var k;
            iframe_top_gadget = false;
            //Default: Define __aq_parent to inform parent window
            root_gadget.__aq_parent =
1432
              TmpConstructor.prototype.__aq_parent = function (method_name,
1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478
                argument_list, time_out) {
                return new RSVP.Promise(function (resolve, reject) {
                  embedded_channel.call({
                    method: "acquire",
                    params: [
                      method_name,
                      argument_list
                    ],
                    success: function (s) {
                      resolve(s);
                    },
                    error: function (e) {
                      reject(e);
                    },
                    timeout: time_out
                  });
                });
              };

            // Channel is ready, so now declare Function
            notifyDeclareMethod = function (name) {
              declare_method_count += 1;
              embedded_channel.call({
                method: "declareMethod",
                params: name,
                success: function () {
                  declare_method_count -= 1;
                  notifyReady();
                },
                error: function () {
                  declare_method_count -= 1;
                }
              });
            };
            for (k = 0; k < declare_method_list_waiting.length; k += 1) {
              notifyDeclareMethod(declare_method_list_waiting[k]);
            }
            declare_method_list_waiting = [];
            // If Gadget Failed Notify Parent
            if (gadget_failed) {
              embedded_channel.notify({
                method: "failed",
                params: gadget_error
              });
              return;
            }
1479 1480 1481 1482 1483 1484 1485 1486 1487 1488
            connection_ready = true;
            notifyReady();
            //the channel is ok
            //so bind calls to renderJS method on the instance
            embedded_channel.bind("methodCall", function (trans, v) {
              root_gadget[v[0]].apply(root_gadget, v[1])
                .then(function (g) {
                  trans.complete(g);
                }).fail(function (e) {
                  trans.error(e.toString());
1489
                });
1490 1491
              trans.delayReturn(true);
            });
1492 1493
          }
        });
1494 1495 1496 1497 1498 1499 1500 1501 1502 1503

        // Notify parent about gadget instanciation
        notifyReady = function () {
          if ((declare_method_count === 0) && (gadget_ready === true)) {
            embedded_channel.notify({method: "ready"});
          }
        };

        // Inform parent gadget about declareMethod calls here.
        notifyDeclareMethod = function (name) {
1504
          declare_method_list_waiting.push(name);
1505 1506 1507 1508 1509 1510 1511 1512 1513
        };

        notifyDeclareMethod("getInterfaceList");
        notifyDeclareMethod("getRequiredCSSList");
        notifyDeclareMethod("getRequiredJSList");
        notifyDeclareMethod("getPath");
        notifyDeclareMethod("getTitle");

        // Surcharge declareMethod to inform parent window
1514
        TmpConstructor.declareMethod = function (name, callback) {
1515 1516 1517 1518
          var result = RenderJSGadget.declareMethod.apply(
              this,
              [name, callback]
            );
1519 1520 1521
          notifyDeclareMethod(name);
          return result;
        };
1522

1523
        TmpConstructor.declareService =
1524
          RenderJSGadget.declareService;
1525
        TmpConstructor.declareJob =
1526
          RenderJSGadget.declareJob;
1527
        TmpConstructor.onEvent =
Romain Courteaud's avatar
Romain Courteaud committed
1528
          RenderJSGadget.onEvent;
1529
        TmpConstructor.declareAcquiredMethod =
1530
          RenderJSGadget.declareAcquiredMethod;
1531
        TmpConstructor.allowPublicAcquisition =
1532
          RenderJSGadget.allowPublicAcquisition;
1533

1534
        iframe_top_gadget = true;
1535
      }
1536

1537
      TmpConstructor.prototype.__acquired_method_dict = {};
1538
      gadget_loading_klass_list.push(TmpConstructor);
Romain Courteaud's avatar
Romain Courteaud committed
1539

1540
      function init() {
1541
        // XXX HTML properties can only be set when the DOM is fully loaded
1542
        var settings = renderJS.parseGadgetHTMLDocument(document, url),
1543
          j,
1544 1545
          key,
          fragment = document.createDocumentFragment();
1546 1547
        for (key in settings) {
          if (settings.hasOwnProperty(key)) {
1548
            TmpConstructor.prototype['__' + key] = settings[key];
1549
          }
Romain Courteaud's avatar
Romain Courteaud committed
1550
        }
1551
        TmpConstructor.__template_element = document.createElement("div");
1552
        root_gadget.element = document.body;
1553
        root_gadget.state = {};
1554
        for (j = 0; j < root_gadget.element.childNodes.length; j += 1) {
1555
          fragment.appendChild(
1556
            root_gadget.element.childNodes[j].cloneNode(true)
1557 1558
          );
        }
1559
        TmpConstructor.__template_element.appendChild(fragment);
1560 1561 1562 1563 1564
        RSVP.all([root_gadget.getRequiredJSList(),
                  root_gadget.getRequiredCSSList()])
          .then(function (all_list) {
            var i,
              js_list = all_list[0],
1565
              css_list = all_list[1];
1566 1567 1568 1569 1570 1571
            for (i = 0; i < js_list.length; i += 1) {
              javascript_registration_dict[js_list[i]] = null;
            }
            for (i = 0; i < css_list.length; i += 1) {
              stylesheet_registration_dict[css_list[i]] = null;
            }
1572
            gadget_loading_klass_list.shift();
1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640
          }).then(function () {

            // select the target node
            var target = document.querySelector('body'),
              // create an observer instance
              observer = new MutationObserver(function (mutations) {
                var i, k, len, len2, node, added_list;
                mutations.forEach(function (mutation) {
                  if (mutation.type === 'childList') {

                    len = mutation.removedNodes.length;
                    for (i = 0; i < len; i += 1) {
                      node = mutation.removedNodes[i];
                      if (node.nodeType === Node.ELEMENT_NODE) {
                        if (node.hasAttribute("data-gadget-url") &&
                            (node._gadget !== undefined)) {
                          createMonitor(node._gadget);
                        }
                        added_list =
                          node.querySelectorAll("[data-gadget-url]");
                        len2 = added_list.length;
                        for (k = 0; k < len2; k += 1) {
                          node = added_list[k];
                          if (node._gadget !== undefined) {
                            createMonitor(node._gadget);
                          }
                        }
                      }
                    }

                    len = mutation.addedNodes.length;
                    for (i = 0; i < len; i += 1) {
                      node = mutation.addedNodes[i];
                      if (node.nodeType === Node.ELEMENT_NODE) {
                        if (node.hasAttribute("data-gadget-url") &&
                            (node._gadget !== undefined)) {
                          if (document.contains(node)) {
                            startService(node._gadget);
                          }
                        }
                        added_list =
                          node.querySelectorAll("[data-gadget-url]");
                        len2 = added_list.length;
                        for (k = 0; k < len2; k += 1) {
                          node = added_list[k];
                          if (document.contains(node)) {
                            if (node._gadget !== undefined) {
                              startService(node._gadget);
                            }
                          }
                        }
                      }
                    }

                  }
                });
              }),
              // configuration of the observer:
              config = {
                childList: true,
                subtree: true,
                attributes: false,
                characterData: false
              };

            // pass in the target node, as well as the observer options
            observer.observe(target, config);

1641 1642
            return root_gadget;
          }).then(resolve, function (e) {
1643
            reject(e);
1644
            console.error(e);
1645
            throw e;
Romain Courteaud's avatar
Romain Courteaud committed
1646
          });
1647
      }
1648 1649 1650 1651 1652 1653 1654 1655 1656 1657
      document.addEventListener('DOMContentLoaded',
                                bootstrap_deferred_object.resolve, false);
      // Return Promies/Queue here instead of directly calling init()
      return new RSVP.Queue()
        .push(function () {
          return bootstrap_deferred_object.promise;
        })
        .push(function () {
          return init();
        });
Romain Courteaud's avatar
Romain Courteaud committed
1658
    });
1659

1660 1661 1662 1663 1664 1665 1666 1667 1668 1669
    loading_gadget_promise
      .push(function () {
        return loading_klass_promise;
      })
      .push(function (root_gadget) {
        var i;

        function ready_wrapper() {
          return root_gadget;
        }
1670 1671 1672 1673 1674
        function ready_executable_wrapper(fct) {
          return function (g) {
            return fct.call(g, g);
          };
        }
1675 1676
        TmpConstructor.ready(function () {
          return startService(this);
1677 1678
        });

1679
        loading_gadget_promise.push(ready_wrapper);
1680
        for (i = 0; i < TmpConstructor.__ready_list.length; i += 1) {
1681 1682
          // Put a timeout?
          loading_gadget_promise
1683
            .push(ready_executable_wrapper(TmpConstructor.__ready_list[i]))
1684 1685 1686 1687
            // Always return the gadget instance after ready function
            .push(ready_wrapper);
        }
      });
1688 1689 1690 1691 1692 1693 1694
    if (window.self === window.top) {
      loading_gadget_promise
        .fail(function (e) {
          letsCrash(e);
          throw e;
        });
    } else {
1695
      // Inform parent window that gadget is correctly loaded
1696 1697 1698
      loading_gadget_promise
        .then(function () {
          gadget_ready = true;
1699 1700 1701
          if (connection_ready) {
            notifyReady();
          }
1702 1703
        })
        .fail(function (e) {
Xiaowu Zhang's avatar
Xiaowu Zhang committed
1704 1705
          //top gadget in iframe
          if (iframe_top_gadget) {
1706 1707
            gadget_failed = true;
            gadget_error = e.toString();
Xiaowu Zhang's avatar
Xiaowu Zhang committed
1708 1709 1710 1711
            letsCrash(e);
          } else {
            embedded_channel.notify({method: "failed", params: e.toString()});
          }
1712 1713
          throw e;
        });
1714 1715
    }

Romain Courteaud's avatar
Romain Courteaud committed
1716 1717
  }
  bootstrap();
1718

1719
}(document, window, RSVP, DOMParser, Channel, MutationObserver, Node,
Romain Courteaud's avatar
Romain Courteaud committed
1720
  FileReader, Blob, navigator, Event, URL));