blob: db59422d1b81eb86d97f787dcef509bc94df361b [file] [log] [blame]
Akron479994e2018-07-02 13:21:44 +02001/**
2 * The plugin system is based
3 * on registered widgets (iframes) from
4 * foreign services.
5 * The server component spawns new iframes and
6 * listens to them.
7 *
8 * @author Nils Diewald
9 */
10
Akrona6c32b92018-07-02 18:39:42 +020011define(["plugin/widget", "util"], function (widgetClass) {
Akron479994e2018-07-02 13:21:44 +020012 "use strict";
13
Akrona6c32b92018-07-02 18:39:42 +020014 // TODO:
15 // This is a counter to limit acceptable incoming messages
16 // to hundred. For every message, this will be decreased
17 // (down to 0), for every second this will be increased
18 // (up to 100).
19 var c = 100;
20
21 // Contains all widgets to address with
22 // messages to them
23 var widgets = {};
24
Akron479994e2018-07-02 13:21:44 +020025 return {
26
27 /**
28 * Create new plugin management system
29 */
30 create : function () {
31 return Object.create(this)._init();
32 },
33
34 /*
35 * Initialize the plugin manager by establishing
36 * the global 'message' hook.
37 */
38 _init : function () {
39
40 var that = this;
41 window.addEventListener("message", function (e) {
42 that._receiveMsg(e);
43 });
44 return this;
45 },
46
47 /**
48 * Open a new widget on a certain element
Akron479994e2018-07-02 13:21:44 +020049 */
50 addWidget : function (element, src) {
51
Akrona6c32b92018-07-02 18:39:42 +020052 // Create a unique random ID per widget
53 var id = 'id-' + this._randomID();
54
55 // Create a new widget
56 var widget = widgetClass.create(src, id);
57
58 // Store the widget based on the identifier
59 widgets[id] = widget;
60
61 // Open widget in frontend
62 element.appendChild(
63 widget.element()
64 );
Akron479994e2018-07-02 13:21:44 +020065 },
66
67 // Receive a call from an embedded iframe
68 _receiveMsg : function (e) {
69 // Get event data
70 var d = e.data;
71
Akrona6c32b92018-07-02 18:39:42 +020072 // e.origin is probably set and okay
Akron479994e2018-07-02 13:21:44 +020073
Akrona6c32b92018-07-02 18:39:42 +020074 // TODO:
75 // Deal with mad iframes
76
77 // Get the widget
78 var widget = widgets[d["originID"]];
79
80 // If the addressed widget does not exist - fail
81 if (!widget)
82 return;
83
84
Akron479994e2018-07-02 13:21:44 +020085 // Resize the iframe
86 if (d.action === 'resize') {
87
Akrona6c32b92018-07-02 18:39:42 +020088 widget.resize(d);
Akron479994e2018-07-02 13:21:44 +020089 }
90
91 // Log message from iframe
92 else if (d.action === 'log') {
93 KorAP.log(d.code, d.msg);
Akrona6c32b92018-07-02 18:39:42 +020094 };
95
96 // TODO:
97 // Close
Akron479994e2018-07-02 13:21:44 +020098 },
99
Akrona6c32b92018-07-02 18:39:42 +0200100 // Get a random identifier
101 _randomID : function () {
102 return randomID(20);
Akron479994e2018-07-02 13:21:44 +0200103 }
104 }
105});