lookbook 1.5.5 → 2.0.0.beta.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (198) hide show
  1. checksums.yaml +4 -4
  2. data/README.md +13 -31
  3. data/app/assets/lookbook/css/lookbook.css +9 -0
  4. data/app/assets/lookbook/css/themes/blue.css +7 -0
  5. data/app/assets/lookbook/css/themes/green.css +7 -0
  6. data/app/assets/lookbook/css/themes/indigo.css +7 -0
  7. data/app/assets/lookbook/css/themes/rose.css +7 -0
  8. data/app/assets/lookbook/css/themes/zinc.css +7 -0
  9. data/app/assets/lookbook/css/tooltip.css +9 -6
  10. data/app/assets/lookbook/img/lucide-sprite.svg +4960 -0
  11. data/app/assets/lookbook/js/app.js +22 -4
  12. data/app/assets/lookbook/js/helpers/dom.js +4 -7
  13. data/app/assets/lookbook/js/helpers/string.js +4 -11
  14. data/app/assets/lookbook/js/index.js +61 -0
  15. data/app/assets/lookbook/js/lib/lookbook.js +113 -0
  16. data/app/assets/lookbook/js/lib/tippy.js +1 -0
  17. data/app/assets/lookbook/js/lookbook-core.js +1 -0
  18. data/app/assets/lookbook/js/lookbook.js +2 -61
  19. data/app/components/lookbook/base_component.rb +3 -1
  20. data/app/components/lookbook/button/component.html.erb +13 -24
  21. data/app/components/lookbook/button/component.js +13 -3
  22. data/app/components/lookbook/button/component.rb +16 -25
  23. data/app/components/lookbook/code/component.rb +0 -2
  24. data/app/components/lookbook/copy_button/component.html.erb +5 -5
  25. data/app/components/lookbook/copy_button/component.rb +6 -3
  26. data/app/components/lookbook/debug_menu/component.html.erb +1 -0
  27. data/app/components/lookbook/debug_menu/component.rb +12 -1
  28. data/app/components/lookbook/display_options/editor/component.html.erb +1 -1
  29. data/app/components/lookbook/display_options/field/component.css +0 -26
  30. data/app/components/lookbook/display_options/field/component.html.erb +1 -1
  31. data/app/components/lookbook/embed/component.html.erb +6 -51
  32. data/app/components/lookbook/embed/component.rb +17 -16
  33. data/app/components/lookbook/embed/inspector/component.html.erb +102 -0
  34. data/app/components/lookbook/embed/inspector/component.js +46 -0
  35. data/app/components/lookbook/embed/inspector/component.rb +64 -0
  36. data/app/components/lookbook/embed_code_dropdown/component.css +12 -0
  37. data/app/components/lookbook/embed_code_dropdown/component.html.erb +19 -0
  38. data/app/components/lookbook/embed_code_dropdown/component.js +26 -0
  39. data/app/components/lookbook/embed_code_dropdown/component.rb +41 -0
  40. data/app/components/lookbook/header/component.html.erb +7 -6
  41. data/app/components/lookbook/header/component.rb +5 -1
  42. data/app/components/lookbook/icon/component.html.erb +1 -1
  43. data/app/components/lookbook/icon_button/component.html.erb +20 -0
  44. data/app/components/lookbook/icon_button/component.rb +46 -0
  45. data/app/components/lookbook/nav/component.html.erb +0 -1
  46. data/app/components/lookbook/nav/entity/component.rb +2 -2
  47. data/app/components/lookbook/nav/item/component.rb +1 -1
  48. data/app/components/lookbook/page_tabs/component.html.erb +2 -2
  49. data/app/components/lookbook/params/editor/component.rb +1 -0
  50. data/app/components/lookbook/prose/component.rb +1 -3
  51. data/app/components/lookbook/tabs/component.html.erb +2 -2
  52. data/app/components/lookbook/tabs/component.js +1 -1
  53. data/app/components/lookbook/tag_component.rb +2 -1
  54. data/app/components/lookbook/text_button/component.html.erb +26 -0
  55. data/app/components/lookbook/text_button/component.rb +42 -0
  56. data/app/components/lookbook/toolbar/component.html.erb +1 -1
  57. data/app/components/lookbook/viewport/component.rb +0 -4
  58. data/app/controllers/concerns/lookbook/targetable_concern.rb +26 -22
  59. data/app/controllers/concerns/lookbook/with_panels_concern.rb +30 -0
  60. data/app/controllers/concerns/lookbook/with_preview_controller_concern.rb +4 -3
  61. data/app/controllers/lookbook/application_controller.rb +9 -12
  62. data/app/controllers/lookbook/embeds_controller.rb +148 -0
  63. data/app/controllers/lookbook/inspector_controller.rb +3 -22
  64. data/app/controllers/lookbook/page_controller.rb +7 -6
  65. data/app/controllers/lookbook/pages_controller.rb +3 -4
  66. data/app/controllers/lookbook/preview_controller.rb +17 -0
  67. data/app/controllers/lookbook/previews_controller.rb +10 -30
  68. data/app/helpers/lookbook/application_helper.rb +3 -19
  69. data/app/views/layouts/lookbook/application.html.erb +85 -60
  70. data/app/views/layouts/lookbook/embed.html.erb +16 -0
  71. data/app/views/layouts/lookbook/shell.html.erb +1 -1
  72. data/app/views/layouts/lookbook/skeleton.html.erb +13 -8
  73. data/app/views/lookbook/404.html.erb +2 -2
  74. data/app/views/lookbook/embeds/show.html.erb +12 -0
  75. data/app/views/lookbook/inspector/panels/_notes.html.erb +1 -1
  76. data/app/views/lookbook/inspector/panels/_output.html.erb +3 -3
  77. data/app/views/lookbook/inspector/panels/_source.html.erb +6 -6
  78. data/app/views/lookbook/inspector/show.html.erb +130 -123
  79. data/app/views/lookbook/pages/show.html.erb +81 -34
  80. data/app/views/lookbook/partials/_iframe_content_scripts.html.erb +1 -0
  81. data/app/views/lookbook/partials/_user_styles.html.erb +5 -0
  82. data/app/views/lookbook/previews/group.html.erb +14 -0
  83. data/app/views/lookbook/previews/preview.html.erb +5 -0
  84. data/app/views/lookbook/previews/show.html.erb +1 -0
  85. data/config/app.yml +31 -16
  86. data/config/panels.yml +23 -25
  87. data/config/routes.rb +3 -1
  88. data/config/tags.yml +6 -2
  89. data/lib/lookbook/cable/cable.rb +53 -0
  90. data/lib/lookbook/engine.rb +105 -93
  91. data/lib/lookbook/entities/collections/entity_collection.rb +11 -6
  92. data/lib/lookbook/entities/collections/page_collection.rb +33 -8
  93. data/lib/lookbook/entities/collections/preview_collection.rb +42 -17
  94. data/lib/lookbook/entities/collections/render_target_collection.rb +4 -0
  95. data/lib/lookbook/entities/collections/scenario_collection.rb +4 -0
  96. data/lib/lookbook/entities/concerns/{annotatable.rb → annotatable_entity.rb} +7 -6
  97. data/lib/lookbook/entities/concerns/{inspectable.rb → inspectable_entity.rb} +2 -1
  98. data/lib/lookbook/entities/concerns/{locatable.rb → locatable_entity.rb} +8 -14
  99. data/lib/lookbook/entities/concerns/navigable_entity.rb +44 -0
  100. data/lib/lookbook/entities/entity.rb +7 -2
  101. data/lib/lookbook/entities/{page.rb → page_entity.rb} +10 -6
  102. data/lib/lookbook/entities/{page_section.rb → page_section_entity.rb} +1 -1
  103. data/lib/lookbook/entities/preview_entity.rb +99 -0
  104. data/lib/lookbook/entities/renderable_entity.rb +50 -0
  105. data/lib/lookbook/entities/rendered_scenario_entity.rb +53 -0
  106. data/lib/lookbook/entities/scenario_entity.rb +112 -0
  107. data/lib/lookbook/entities/scenario_group_entity.rb +53 -0
  108. data/lib/lookbook/error.rb +5 -5
  109. data/lib/lookbook/file_watcher.rb +19 -35
  110. data/lib/lookbook/helpers/class_names_helper.rb +28 -0
  111. data/lib/lookbook/helpers/page_helper.rb +18 -0
  112. data/{app/helpers/lookbook → lib/lookbook/helpers}/preview_helper.rb +3 -0
  113. data/lib/lookbook/helpers/ui_elements_helper.rb +115 -0
  114. data/lib/lookbook/preview.rb +79 -0
  115. data/lib/lookbook/preview_controller_actions.rb +50 -0
  116. data/lib/lookbook/preview_parser.rb +4 -2
  117. data/lib/lookbook/reloaders.rb +71 -0
  118. data/lib/lookbook/runtime_context.rb +49 -0
  119. data/lib/lookbook/services/data/resolvers/data_resolver.rb +4 -6
  120. data/lib/lookbook/services/entities/entity_tree_builder.rb +6 -6
  121. data/lib/lookbook/services/list_resolver.rb +35 -0
  122. data/lib/lookbook/services/markdown_renderer.rb +12 -2
  123. data/lib/lookbook/services/priority_prefix_parser.rb +16 -0
  124. data/lib/lookbook/services/urls/search_param_encoder.rb +16 -0
  125. data/lib/lookbook/services/urls/search_param_parser.rb +7 -6
  126. data/lib/lookbook/stores/config_store.rb +16 -16
  127. data/lib/lookbook/stores/input_store.rb +1 -3
  128. data/lib/lookbook/stores/panel_store.rb +28 -50
  129. data/lib/lookbook/support/deprecation.rb +5 -0
  130. data/lib/lookbook/support/errors/preview_template_error.rb +7 -0
  131. data/lib/lookbook/support/evented_file_update_checker.rb +69 -0
  132. data/lib/lookbook/support/null_websocket.rb +9 -0
  133. data/lib/lookbook/support/store.rb +9 -0
  134. data/lib/lookbook/support/tree_node.rb +7 -7
  135. data/lib/lookbook/support/utils/path_utils.rb +7 -1
  136. data/lib/lookbook/support/utils/utils.rb +8 -0
  137. data/lib/lookbook/tags/{position_tag.rb → priority_tag.rb} +4 -4
  138. data/lib/lookbook/tags/renders_tag.rb +4 -0
  139. data/lib/lookbook/tags/tag_provider.rb +3 -0
  140. data/lib/lookbook/tags/type_tag.rb +7 -0
  141. data/lib/lookbook/tags/yard_tag.rb +1 -2
  142. data/lib/lookbook/version.rb +1 -1
  143. data/lib/lookbook/websocket.rb +6 -53
  144. data/lib/lookbook.rb +179 -53
  145. data/public/lookbook-assets/css/lookbook.css +432 -376
  146. data/public/lookbook-assets/css/lookbook.css.map +1 -1
  147. data/public/lookbook-assets/css/themes/blue.css +7 -0
  148. data/public/lookbook-assets/css/themes/blue.css.map +1 -1
  149. data/public/lookbook-assets/css/themes/green.css +7 -0
  150. data/public/lookbook-assets/css/themes/green.css.map +1 -1
  151. data/public/lookbook-assets/css/themes/indigo.css +7 -0
  152. data/public/lookbook-assets/css/themes/indigo.css.map +1 -1
  153. data/public/lookbook-assets/css/themes/rose.css +7 -0
  154. data/public/lookbook-assets/css/themes/rose.css.map +1 -1
  155. data/public/lookbook-assets/css/themes/zinc.css +7 -0
  156. data/public/lookbook-assets/css/themes/zinc.css.map +1 -1
  157. data/public/lookbook-assets/img/lucide-sprite.svg +4960 -0
  158. data/public/lookbook-assets/js/embed.js +1363 -843
  159. data/public/lookbook-assets/js/embed.js.map +1 -1
  160. data/public/lookbook-assets/js/iframe.js +906 -0
  161. data/public/lookbook-assets/js/iframe.js.map +1 -0
  162. data/public/lookbook-assets/js/index.js +13567 -0
  163. data/public/lookbook-assets/js/index.js.map +1 -0
  164. data/public/lookbook-assets/js/lookbook-core.js +85 -0
  165. data/public/lookbook-assets/js/lookbook-core.js.map +1 -0
  166. data/public/lookbook-assets/js/lookbook.js +151 -12726
  167. data/public/lookbook-assets/js/lookbook.js.map +1 -1
  168. data/public/lookbook-assets/lookbook-esm.js +1427 -0
  169. data/public/lookbook-assets/lookbook-esm.js.map +1 -0
  170. data/public/lookbook-assets/lookbook-global.js +1427 -0
  171. data/public/lookbook-assets/lookbook-global.js.map +1 -0
  172. data/public/lookbook-assets/lookbook.js +1427 -0
  173. data/public/lookbook-assets/lookbook.js.map +1 -0
  174. metadata +85 -77
  175. data/app/components/lookbook/embed/component.js +0 -39
  176. data/app/helpers/lookbook/component_helper.rb +0 -84
  177. data/app/helpers/lookbook/output_helper.rb +0 -19
  178. data/app/helpers/lookbook/page_helper.rb +0 -34
  179. data/app/views/layouts/lookbook/inspector.html.erb +0 -7
  180. data/app/views/layouts/lookbook/page.html.erb +0 -53
  181. data/app/views/layouts/lookbook/standalone.html.erb +0 -5
  182. data/app/views/lookbook/preview.html.erb +0 -14
  183. data/lib/lookbook/entities/collections/component_collection.rb +0 -4
  184. data/lib/lookbook/entities/collections/preview_example_collection.rb +0 -4
  185. data/lib/lookbook/entities/component.rb +0 -31
  186. data/lib/lookbook/entities/concerns/navigable.rb +0 -43
  187. data/lib/lookbook/entities/preview.rb +0 -87
  188. data/lib/lookbook/entities/preview_example.rb +0 -104
  189. data/lib/lookbook/entities/preview_group.rb +0 -52
  190. data/lib/lookbook/preview_actions.rb +0 -43
  191. data/lib/lookbook/process.rb +0 -21
  192. data/lib/lookbook/rendered_example.rb +0 -37
  193. data/lib/lookbook/services/position_prefix_parser.rb +0 -16
  194. data/lib/lookbook/services/urls/search_param_builder.rb +0 -13
  195. data/lib/lookbook/tags/component_tag.rb +0 -13
  196. /data/app/assets/lookbook/js/{embed.js → iframe.js} +0 -0
  197. /data/{app/channels/lookbook → lib/lookbook/cable}/connection.rb +0 -0
  198. /data/{app/channels/lookbook → lib/lookbook/cable}/reload_channel.rb +0 -0
@@ -1,569 +1,1327 @@
1
- (() => {
2
- var $b2e1fd3e30ab1f5c$exports = {};
1
+ // modules are defined as an array
2
+ // [ module function, map of requires ]
3
+ //
4
+ // map of requires is short require name -> numeric require
5
+ //
6
+ // anything defined in a previous bundle is accessed via the
7
+ // orig method which is the require for previous bundles
8
+
9
+ (function (modules, entry, mainEntry, parcelRequireName, globalName) {
10
+ /* eslint-disable no-undef */
11
+ var globalObject =
12
+ typeof globalThis !== 'undefined'
13
+ ? globalThis
14
+ : typeof self !== 'undefined'
15
+ ? self
16
+ : typeof window !== 'undefined'
17
+ ? window
18
+ : typeof global !== 'undefined'
19
+ ? global
20
+ : {};
21
+ /* eslint-enable no-undef */
22
+
23
+ // Save the require from previous bundle to this closure if any
24
+ var previousRequire =
25
+ typeof globalObject[parcelRequireName] === 'function' &&
26
+ globalObject[parcelRequireName];
27
+
28
+ var cache = previousRequire.cache || {};
29
+ // Do not use `require` to prevent Webpack from trying to bundle this call
30
+ var nodeRequire =
31
+ typeof module !== 'undefined' &&
32
+ typeof module.require === 'function' &&
33
+ module.require.bind(module);
34
+
35
+ function newRequire(name, jumped) {
36
+ if (!cache[name]) {
37
+ if (!modules[name]) {
38
+ // if we cannot find the module within our internal map or
39
+ // cache jump to the current global require ie. the last bundle
40
+ // that was added to the page.
41
+ var currentRequire =
42
+ typeof globalObject[parcelRequireName] === 'function' &&
43
+ globalObject[parcelRequireName];
44
+ if (!jumped && currentRequire) {
45
+ return currentRequire(name, true);
46
+ }
47
+
48
+ // If there are other bundles on this page the require from the
49
+ // previous one is saved to 'previousRequire'. Repeat this as
50
+ // many times as there are bundles until the module is found or
51
+ // we exhaust the require chain.
52
+ if (previousRequire) {
53
+ return previousRequire(name, true);
54
+ }
55
+
56
+ // Try the node require function if it exists.
57
+ if (nodeRequire && typeof name === 'string') {
58
+ return nodeRequire(name);
59
+ }
60
+
61
+ var err = new Error("Cannot find module '" + name + "'");
62
+ err.code = 'MODULE_NOT_FOUND';
63
+ throw err;
64
+ }
65
+
66
+ localRequire.resolve = resolve;
67
+ localRequire.cache = {};
68
+
69
+ var module = (cache[name] = new newRequire.Module(name));
70
+
71
+ modules[name][0].call(
72
+ module.exports,
73
+ localRequire,
74
+ module,
75
+ module.exports,
76
+ this
77
+ );
78
+ }
79
+
80
+ return cache[name].exports;
81
+
82
+ function localRequire(x) {
83
+ var res = localRequire.resolve(x);
84
+ return res === false ? {} : newRequire(res);
85
+ }
86
+
87
+ function resolve(x) {
88
+ var id = modules[name][1][x];
89
+ return id != null ? id : x;
90
+ }
91
+ }
92
+
93
+ function Module(moduleName) {
94
+ this.id = moduleName;
95
+ this.bundle = newRequire;
96
+ this.exports = {};
97
+ }
98
+
99
+ newRequire.isParcelRequire = true;
100
+ newRequire.Module = Module;
101
+ newRequire.modules = modules;
102
+ newRequire.cache = cache;
103
+ newRequire.parent = previousRequire;
104
+ newRequire.register = function (id, exports) {
105
+ modules[id] = [
106
+ function (require, module) {
107
+ module.exports = exports;
108
+ },
109
+ {},
110
+ ];
111
+ };
112
+
113
+ Object.defineProperty(newRequire, 'root', {
114
+ get: function () {
115
+ return globalObject[parcelRequireName];
116
+ },
117
+ });
118
+
119
+ globalObject[parcelRequireName] = newRequire;
120
+
121
+ for (var i = 0; i < entry.length; i++) {
122
+ newRequire(entry[i]);
123
+ }
124
+
125
+ if (mainEntry) {
126
+ // Expose entry point to Node, AMD or browser globals
127
+ // Based on https://github.com/ForbesLindesay/umd/blob/master/template.js
128
+ var mainExports = newRequire(mainEntry);
129
+
130
+ // CommonJS
131
+ if (typeof exports === 'object' && typeof module !== 'undefined') {
132
+ module.exports = mainExports;
133
+
134
+ // RequireJS
135
+ } else if (typeof define === 'function' && define.amd) {
136
+ define(function () {
137
+ return mainExports;
138
+ });
139
+
140
+ // <script>
141
+ } else if (globalName) {
142
+ this[globalName] = mainExports;
143
+ }
144
+ }
145
+ })({"2Ac7p":[function(require,module,exports) {
146
+ var global = arguments[3];
147
+ var HMR_HOST = null;
148
+ var HMR_PORT = 5111;
149
+ var HMR_SECURE = false;
150
+ var HMR_ENV_HASH = "d6ea1d42532a7575";
151
+ module.bundle.HMR_BUNDLE_ID = "9c5a05b5e79a47f2";
152
+ "use strict";
153
+ /* global HMR_HOST, HMR_PORT, HMR_ENV_HASH, HMR_SECURE, chrome, browser, globalThis, __parcel__import__, __parcel__importScripts__, ServiceWorkerGlobalScope */ /*::
154
+ import type {
155
+ HMRAsset,
156
+ HMRMessage,
157
+ } from '@parcel/reporter-dev-server/src/HMRServer.js';
158
+ interface ParcelRequire {
159
+ (string): mixed;
160
+ cache: {|[string]: ParcelModule|};
161
+ hotData: mixed;
162
+ Module: any;
163
+ parent: ?ParcelRequire;
164
+ isParcelRequire: true;
165
+ modules: {|[string]: [Function, {|[string]: string|}]|};
166
+ HMR_BUNDLE_ID: string;
167
+ root: ParcelRequire;
168
+ }
169
+ interface ParcelModule {
170
+ hot: {|
171
+ data: mixed,
172
+ accept(cb: (Function) => void): void,
173
+ dispose(cb: (mixed) => void): void,
174
+ // accept(deps: Array<string> | string, cb: (Function) => void): void,
175
+ // decline(): void,
176
+ _acceptCallbacks: Array<(Function) => void>,
177
+ _disposeCallbacks: Array<(mixed) => void>,
178
+ |};
179
+ }
180
+ interface ExtensionContext {
181
+ runtime: {|
182
+ reload(): void,
183
+ getURL(url: string): string;
184
+ getManifest(): {manifest_version: number, ...};
185
+ |};
186
+ }
187
+ declare var module: {bundle: ParcelRequire, ...};
188
+ declare var HMR_HOST: string;
189
+ declare var HMR_PORT: string;
190
+ declare var HMR_ENV_HASH: string;
191
+ declare var HMR_SECURE: boolean;
192
+ declare var chrome: ExtensionContext;
193
+ declare var browser: ExtensionContext;
194
+ declare var __parcel__import__: (string) => Promise<void>;
195
+ declare var __parcel__importScripts__: (string) => Promise<void>;
196
+ declare var globalThis: typeof self;
197
+ declare var ServiceWorkerGlobalScope: Object;
198
+ */ var OVERLAY_ID = "__parcel__error__overlay__";
199
+ var OldModule = module.bundle.Module;
200
+ function Module(moduleName) {
201
+ OldModule.call(this, moduleName);
202
+ this.hot = {
203
+ data: module.bundle.hotData,
204
+ _acceptCallbacks: [],
205
+ _disposeCallbacks: [],
206
+ accept: function(fn) {
207
+ this._acceptCallbacks.push(fn || function() {});
208
+ },
209
+ dispose: function(fn) {
210
+ this._disposeCallbacks.push(fn);
211
+ }
212
+ };
213
+ module.bundle.hotData = undefined;
214
+ }
215
+ module.bundle.Module = Module;
216
+ var checkedAssets, acceptedAssets, assetsToAccept /*: Array<[ParcelRequire, string]> */ ;
217
+ function getHostname() {
218
+ return HMR_HOST || (location.protocol.indexOf("http") === 0 ? location.hostname : "localhost");
219
+ }
220
+ function getPort() {
221
+ return HMR_PORT || location.port;
222
+ } // eslint-disable-next-line no-redeclare
223
+ var parent = module.bundle.parent;
224
+ if ((!parent || !parent.isParcelRequire) && typeof WebSocket !== "undefined") {
225
+ var hostname = getHostname();
226
+ var port = getPort();
227
+ var protocol = HMR_SECURE || location.protocol == "https:" && !/localhost|127.0.0.1|0.0.0.0/.test(hostname) ? "wss" : "ws";
228
+ var ws = new WebSocket(protocol + "://" + hostname + (port ? ":" + port : "") + "/"); // Web extension context
229
+ var extCtx = typeof chrome === "undefined" ? typeof browser === "undefined" ? null : browser : chrome; // Safari doesn't support sourceURL in error stacks.
230
+ // eval may also be disabled via CSP, so do a quick check.
231
+ var supportsSourceURL = false;
232
+ try {
233
+ (0, eval)('throw new Error("test"); //# sourceURL=test.js');
234
+ } catch (err) {
235
+ supportsSourceURL = err.stack.includes("test.js");
236
+ } // $FlowFixMe
237
+ ws.onmessage = async function(event) {
238
+ checkedAssets = {} /*: {|[string]: boolean|} */ ;
239
+ acceptedAssets = {} /*: {|[string]: boolean|} */ ;
240
+ assetsToAccept = [];
241
+ var data = JSON.parse(event.data);
242
+ if (data.type === "update") {
243
+ // Remove error overlay if there is one
244
+ if (typeof document !== "undefined") removeErrorOverlay();
245
+ let assets = data.assets.filter((asset)=>asset.envHash === HMR_ENV_HASH); // Handle HMR Update
246
+ let handled = assets.every((asset)=>{
247
+ return asset.type === "css" || asset.type === "js" && hmrAcceptCheck(module.bundle.root, asset.id, asset.depsByBundle);
248
+ });
249
+ if (handled) {
250
+ console.clear(); // Dispatch custom event so other runtimes (e.g React Refresh) are aware.
251
+ if (typeof window !== "undefined" && typeof CustomEvent !== "undefined") window.dispatchEvent(new CustomEvent("parcelhmraccept"));
252
+ await hmrApplyUpdates(assets);
253
+ for(var i = 0; i < assetsToAccept.length; i++){
254
+ var id = assetsToAccept[i][1];
255
+ if (!acceptedAssets[id]) hmrAcceptRun(assetsToAccept[i][0], id);
256
+ }
257
+ } else fullReload();
258
+ }
259
+ if (data.type === "error") {
260
+ // Log parcel errors to console
261
+ for (let ansiDiagnostic of data.diagnostics.ansi){
262
+ let stack = ansiDiagnostic.codeframe ? ansiDiagnostic.codeframe : ansiDiagnostic.stack;
263
+ console.error("\uD83D\uDEA8 [parcel]: " + ansiDiagnostic.message + "\n" + stack + "\n\n" + ansiDiagnostic.hints.join("\n"));
264
+ }
265
+ if (typeof document !== "undefined") {
266
+ // Render the fancy html overlay
267
+ removeErrorOverlay();
268
+ var overlay = createErrorOverlay(data.diagnostics.html); // $FlowFixMe
269
+ document.body.appendChild(overlay);
270
+ }
271
+ }
272
+ };
273
+ ws.onerror = function(e) {
274
+ console.error(e.message);
275
+ };
276
+ ws.onclose = function() {
277
+ console.warn("[parcel] \uD83D\uDEA8 Connection to the HMR server was lost");
278
+ };
279
+ }
280
+ function removeErrorOverlay() {
281
+ var overlay = document.getElementById(OVERLAY_ID);
282
+ if (overlay) {
283
+ overlay.remove();
284
+ console.log("[parcel] ✨ Error resolved");
285
+ }
286
+ }
287
+ function createErrorOverlay(diagnostics) {
288
+ var overlay = document.createElement("div");
289
+ overlay.id = OVERLAY_ID;
290
+ let errorHTML = '<div style="background: black; opacity: 0.85; font-size: 16px; color: white; position: fixed; height: 100%; width: 100%; top: 0px; left: 0px; padding: 30px; font-family: Menlo, Consolas, monospace; z-index: 9999;">';
291
+ for (let diagnostic of diagnostics){
292
+ let stack = diagnostic.frames.length ? diagnostic.frames.reduce((p, frame)=>{
293
+ return `${p}
294
+ <a href="/__parcel_launch_editor?file=${encodeURIComponent(frame.location)}" style="text-decoration: underline; color: #888" onclick="fetch(this.href); return false">${frame.location}</a>
295
+ ${frame.code}`;
296
+ }, "") : diagnostic.stack;
297
+ errorHTML += `
298
+ <div>
299
+ <div style="font-size: 18px; font-weight: bold; margin-top: 20px;">
300
+ 🚨 ${diagnostic.message}
301
+ </div>
302
+ <pre>${stack}</pre>
303
+ <div>
304
+ ${diagnostic.hints.map((hint)=>"<div>\uD83D\uDCA1 " + hint + "</div>").join("")}
305
+ </div>
306
+ ${diagnostic.documentation ? `<div>📝 <a style="color: violet" href="${diagnostic.documentation}" target="_blank">Learn more</a></div>` : ""}
307
+ </div>
308
+ `;
309
+ }
310
+ errorHTML += "</div>";
311
+ overlay.innerHTML = errorHTML;
312
+ return overlay;
313
+ }
314
+ function fullReload() {
315
+ if ("reload" in location) location.reload();
316
+ else if (extCtx && extCtx.runtime && extCtx.runtime.reload) extCtx.runtime.reload();
317
+ }
318
+ function getParents(bundle, id) /*: Array<[ParcelRequire, string]> */ {
319
+ var modules = bundle.modules;
320
+ if (!modules) return [];
321
+ var parents = [];
322
+ var k, d, dep;
323
+ for(k in modules)for(d in modules[k][1]){
324
+ dep = modules[k][1][d];
325
+ if (dep === id || Array.isArray(dep) && dep[dep.length - 1] === id) parents.push([
326
+ bundle,
327
+ k
328
+ ]);
329
+ }
330
+ if (bundle.parent) parents = parents.concat(getParents(bundle.parent, id));
331
+ return parents;
332
+ }
333
+ function updateLink(link) {
334
+ var newLink = link.cloneNode();
335
+ newLink.onload = function() {
336
+ if (link.parentNode !== null) // $FlowFixMe
337
+ link.parentNode.removeChild(link);
338
+ };
339
+ newLink.setAttribute("href", link.getAttribute("href").split("?")[0] + "?" + Date.now()); // $FlowFixMe
340
+ link.parentNode.insertBefore(newLink, link.nextSibling);
341
+ }
342
+ var cssTimeout = null;
343
+ function reloadCSS() {
344
+ if (cssTimeout) return;
345
+ cssTimeout = setTimeout(function() {
346
+ var links = document.querySelectorAll('link[rel="stylesheet"]');
347
+ for(var i = 0; i < links.length; i++){
348
+ // $FlowFixMe[incompatible-type]
349
+ var href = links[i].getAttribute("href");
350
+ var hostname = getHostname();
351
+ var servedFromHMRServer = hostname === "localhost" ? new RegExp("^(https?:\\/\\/(0.0.0.0|127.0.0.1)|localhost):" + getPort()).test(href) : href.indexOf(hostname + ":" + getPort());
352
+ var absolute = /^https?:\/\//i.test(href) && href.indexOf(location.origin) !== 0 && !servedFromHMRServer;
353
+ if (!absolute) updateLink(links[i]);
354
+ }
355
+ cssTimeout = null;
356
+ }, 50);
357
+ }
358
+ function hmrDownload(asset) {
359
+ if (asset.type === "js") {
360
+ if (typeof document !== "undefined") {
361
+ let script = document.createElement("script");
362
+ script.src = asset.url + "?t=" + Date.now();
363
+ if (asset.outputFormat === "esmodule") script.type = "module";
364
+ return new Promise((resolve, reject)=>{
365
+ var _document$head;
366
+ script.onload = ()=>resolve(script);
367
+ script.onerror = reject;
368
+ (_document$head = document.head) === null || _document$head === void 0 || _document$head.appendChild(script);
369
+ });
370
+ } else if (typeof importScripts === "function") {
371
+ // Worker scripts
372
+ if (asset.outputFormat === "esmodule") return import(asset.url + "?t=" + Date.now());
373
+ else return new Promise((resolve, reject)=>{
374
+ try {
375
+ importScripts(asset.url + "?t=" + Date.now());
376
+ resolve();
377
+ } catch (err) {
378
+ reject(err);
379
+ }
380
+ });
381
+ }
382
+ }
383
+ }
384
+ async function hmrApplyUpdates(assets) {
385
+ global.parcelHotUpdate = Object.create(null);
386
+ let scriptsToRemove;
387
+ try {
388
+ // If sourceURL comments aren't supported in eval, we need to load
389
+ // the update from the dev server over HTTP so that stack traces
390
+ // are correct in errors/logs. This is much slower than eval, so
391
+ // we only do it if needed (currently just Safari).
392
+ // https://bugs.webkit.org/show_bug.cgi?id=137297
393
+ // This path is also taken if a CSP disallows eval.
394
+ if (!supportsSourceURL) {
395
+ let promises = assets.map((asset)=>{
396
+ var _hmrDownload;
397
+ return (_hmrDownload = hmrDownload(asset)) === null || _hmrDownload === void 0 ? void 0 : _hmrDownload.catch((err)=>{
398
+ // Web extension bugfix for Chromium
399
+ // https://bugs.chromium.org/p/chromium/issues/detail?id=1255412#c12
400
+ if (extCtx && extCtx.runtime && extCtx.runtime.getManifest().manifest_version == 3) {
401
+ if (typeof ServiceWorkerGlobalScope != "undefined" && global instanceof ServiceWorkerGlobalScope) {
402
+ extCtx.runtime.reload();
403
+ return;
404
+ }
405
+ asset.url = extCtx.runtime.getURL("/__parcel_hmr_proxy__?url=" + encodeURIComponent(asset.url + "?t=" + Date.now()));
406
+ return hmrDownload(asset);
407
+ }
408
+ throw err;
409
+ });
410
+ });
411
+ scriptsToRemove = await Promise.all(promises);
412
+ }
413
+ assets.forEach(function(asset) {
414
+ hmrApply(module.bundle.root, asset);
415
+ });
416
+ } finally{
417
+ delete global.parcelHotUpdate;
418
+ if (scriptsToRemove) scriptsToRemove.forEach((script)=>{
419
+ if (script) {
420
+ var _document$head2;
421
+ (_document$head2 = document.head) === null || _document$head2 === void 0 || _document$head2.removeChild(script);
422
+ }
423
+ });
424
+ }
425
+ }
426
+ function hmrApply(bundle, asset) {
427
+ var modules = bundle.modules;
428
+ if (!modules) return;
429
+ if (asset.type === "css") reloadCSS();
430
+ else if (asset.type === "js") {
431
+ let deps = asset.depsByBundle[bundle.HMR_BUNDLE_ID];
432
+ if (deps) {
433
+ if (modules[asset.id]) {
434
+ // Remove dependencies that are removed and will become orphaned.
435
+ // This is necessary so that if the asset is added back again, the cache is gone, and we prevent a full page reload.
436
+ let oldDeps = modules[asset.id][1];
437
+ for(let dep in oldDeps)if (!deps[dep] || deps[dep] !== oldDeps[dep]) {
438
+ let id = oldDeps[dep];
439
+ let parents = getParents(module.bundle.root, id);
440
+ if (parents.length === 1) hmrDelete(module.bundle.root, id);
441
+ }
442
+ }
443
+ if (supportsSourceURL) // Global eval. We would use `new Function` here but browser
444
+ // support for source maps is better with eval.
445
+ (0, eval)(asset.output);
446
+ // $FlowFixMe
447
+ let fn = global.parcelHotUpdate[asset.id];
448
+ modules[asset.id] = [
449
+ fn,
450
+ deps
451
+ ];
452
+ } else if (bundle.parent) hmrApply(bundle.parent, asset);
453
+ }
454
+ }
455
+ function hmrDelete(bundle, id) {
456
+ let modules = bundle.modules;
457
+ if (!modules) return;
458
+ if (modules[id]) {
459
+ // Collect dependencies that will become orphaned when this module is deleted.
460
+ let deps = modules[id][1];
461
+ let orphans = [];
462
+ for(let dep in deps){
463
+ let parents = getParents(module.bundle.root, deps[dep]);
464
+ if (parents.length === 1) orphans.push(deps[dep]);
465
+ } // Delete the module. This must be done before deleting dependencies in case of circular dependencies.
466
+ delete modules[id];
467
+ delete bundle.cache[id]; // Now delete the orphans.
468
+ orphans.forEach((id)=>{
469
+ hmrDelete(module.bundle.root, id);
470
+ });
471
+ } else if (bundle.parent) hmrDelete(bundle.parent, id);
472
+ }
473
+ function hmrAcceptCheck(bundle, id, depsByBundle) {
474
+ if (hmrAcceptCheckOne(bundle, id, depsByBundle)) return true;
475
+ // Traverse parents breadth first. All possible ancestries must accept the HMR update, or we'll reload.
476
+ let parents = getParents(module.bundle.root, id);
477
+ let accepted = false;
478
+ while(parents.length > 0){
479
+ let v = parents.shift();
480
+ let a = hmrAcceptCheckOne(v[0], v[1], null);
481
+ if (a) // If this parent accepts, stop traversing upward, but still consider siblings.
482
+ accepted = true;
483
+ else {
484
+ // Otherwise, queue the parents in the next level upward.
485
+ let p = getParents(module.bundle.root, v[1]);
486
+ if (p.length === 0) {
487
+ // If there are no parents, then we've reached an entry without accepting. Reload.
488
+ accepted = false;
489
+ break;
490
+ }
491
+ parents.push(...p);
492
+ }
493
+ }
494
+ return accepted;
495
+ }
496
+ function hmrAcceptCheckOne(bundle, id, depsByBundle) {
497
+ var modules = bundle.modules;
498
+ if (!modules) return;
499
+ if (depsByBundle && !depsByBundle[bundle.HMR_BUNDLE_ID]) {
500
+ // If we reached the root bundle without finding where the asset should go,
501
+ // there's nothing to do. Mark as "accepted" so we don't reload the page.
502
+ if (!bundle.parent) return true;
503
+ return hmrAcceptCheck(bundle.parent, id, depsByBundle);
504
+ }
505
+ if (checkedAssets[id]) return true;
506
+ checkedAssets[id] = true;
507
+ var cached = bundle.cache[id];
508
+ assetsToAccept.push([
509
+ bundle,
510
+ id
511
+ ]);
512
+ if (!cached || cached.hot && cached.hot._acceptCallbacks.length) return true;
513
+ }
514
+ function hmrAcceptRun(bundle, id) {
515
+ var cached = bundle.cache[id];
516
+ bundle.hotData = {};
517
+ if (cached && cached.hot) cached.hot.data = bundle.hotData;
518
+ if (cached && cached.hot && cached.hot._disposeCallbacks.length) cached.hot._disposeCallbacks.forEach(function(cb) {
519
+ cb(bundle.hotData);
520
+ });
521
+ delete bundle.cache[id];
522
+ bundle(id);
523
+ cached = bundle.cache[id];
524
+ if (cached && cached.hot && cached.hot._acceptCallbacks.length) cached.hot._acceptCallbacks.forEach(function(cb) {
525
+ var assetsToAlsoAccept = cb(function() {
526
+ return getParents(module.bundle.root, id);
527
+ });
528
+ if (assetsToAlsoAccept && assetsToAccept.length) // $FlowFixMe[method-unbinding]
529
+ assetsToAccept.push.apply(assetsToAccept, assetsToAlsoAccept);
530
+ });
531
+ acceptedAssets[id] = true;
532
+ }
533
+
534
+ },{}],"p4VhZ":[function(require,module,exports) {
535
+ var _iframeResizer = require("iframe-resizer/js/iframeResizer");
536
+ window.Lookbook = window.Lookbook || {};
537
+ window.Lookbook.initEmbeds = function() {
538
+ const embeds = Array.from(document.querySelectorAll("lookbook-embed"));
539
+ embeds.forEach((embed)=>{
540
+ const attrs = Array.from(embed.attributes);
541
+ const iframe = createIframe(attrs);
542
+ embed.replaceWith(iframe);
543
+ });
544
+ window.iFrameResize({}, "[data-lookbook-embed]");
545
+ };
546
+ const endpoint = "embed";
547
+ const defaultBasePath = `//${location.host}/lookbook`;
548
+ function createIframe(attrs) {
549
+ const src = buildSrc(attrs);
550
+ const id = attrValue(attrs, "id");
551
+ const classes = attrValue(attrs, "class", "").split(" ").map((c)=>c.trim()).filter((c)=>c.length);
552
+ const iframe = document.createElement("iframe");
553
+ iframe.src = src;
554
+ if (id) iframe.id = id;
555
+ iframe.setAttribute("frameborder", 0);
556
+ iframe.setAttribute("data-lookbook-embed", true);
557
+ if (classes.length) iframe.classList.add(...classes);
558
+ iframe.style.width = "100%";
559
+ iframe.style.transition = "height 0.3s";
560
+ iframe.style.boxShadow = "0px 0px 4px rgba(0,0,0,0.15)";
561
+ iframe.style.borderRadius = "8px";
562
+ return iframe;
563
+ }
564
+ function buildSrc(attrs) {
565
+ const basePath = attrValue(attrs, "base") || defaultBasePath;
566
+ const props = {};
567
+ attrsWithout(attrs, "base", "class").forEach(({ name , value })=>{
568
+ name = name.replace("-", "_").toLowerCase();
569
+ value = encodeURIComponent(value);
570
+ props[name] = value;
571
+ });
572
+ return [
573
+ basePath,
574
+ endpoint
575
+ ].join("/") + `?props=${JSON.stringify(props)}`;
576
+ }
577
+ function attrValue(attrs, name, fallback = null) {
578
+ const attr = attrs.find((attr)=>attr.name === name);
579
+ return attr ? attr.value : fallback;
580
+ }
581
+ function attrsWithout(attrs, ...without) {
582
+ return attrs.filter((attr)=>!without.includes(attr.name));
583
+ }
584
+ function insertAfter(newNode, referenceNode) {
585
+ referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
586
+ }
587
+
588
+ },{"iframe-resizer/js/iframeResizer":"l3td4"}],"l3td4":[function(require,module,exports) {
3
589
  /*
4
- * File: iframeResizer.contentWindow.js
5
- * Desc: Include this file in any page being loaded into an iframe
6
- * to force the iframe to resize to the content size.
7
- * Requires: iframeResizer.js on host page.
590
+ * File: iframeResizer.js
591
+ * Desc: Force iframes to size to content.
592
+ * Requires: iframeResizer.contentWindow.js to be loaded into the target frame.
8
593
  * Doc: https://github.com/davidjbradshaw/iframe-resizer
9
594
  * Author: David J. Bradshaw - dave@bradshaw.net
10
- *
595
+ * Contributor: Jure Mav - jure.mav@gmail.com
596
+ * Contributor: Reed Dadoune - reed@dadoune.com
11
597
  */ // eslint-disable-next-line sonarjs/cognitive-complexity, no-shadow-restricted-names
12
598
  (function(undefined) {
13
599
  if (typeof window === "undefined") return; // don't run for server side render
14
- var autoResize = true, base = 10, bodyBackground = "", bodyMargin = 0, bodyMarginStr = "", bodyObserver = null, bodyPadding = "", calculateWidth = false, doubleEventList = {
15
- resize: 1,
16
- click: 1
17
- }, eventCancelTimer = 128, firstRun = true, height = 1, heightCalcModeDefault = "bodyOffset", heightCalcMode = heightCalcModeDefault, initLock = true, initMsg = "", inPageLinks = {}, interval = 32, intervalTimer = null, logging = false, mouseEvents = false, msgID = "[iFrameSizer]", msgIdLen = msgID.length, myID = "", resetRequiredMethods = {
600
+ var count = 0, logEnabled = false, hiddenCheckEnabled = false, msgHeader = "message", msgHeaderLen = msgHeader.length, msgId = "[iFrameSizer]", msgIdLen = msgId.length, pagePosition = null, requestAnimationFrame = window.requestAnimationFrame, resetRequiredMethods = {
18
601
  max: 1,
19
- min: 1,
602
+ scroll: 1,
20
603
  bodyScroll: 1,
21
604
  documentElementScroll: 1
22
- }, resizeFrom = "child", sendPermit = true, target = window.parent, targetOriginDefault = "*", tolerance = 0, triggerLocked = false, triggerLockedTimer = null, throttledTimer = 16, width = 1, widthCalcModeDefault = "scroll", widthCalcMode = widthCalcModeDefault, win = window, onMessage = function() {
23
- warn("onMessage function not defined");
24
- }, onReady = function() {}, onPageInfo = function() {}, customCalcMethods = {
25
- height: function() {
26
- warn("Custom height calculation function not defined");
27
- return document.documentElement.offsetHeight;
605
+ }, settings = {}, timer = null, defaults = {
606
+ autoResize: true,
607
+ bodyBackground: null,
608
+ bodyMargin: null,
609
+ bodyMarginV1: 8,
610
+ bodyPadding: null,
611
+ checkOrigin: true,
612
+ inPageLinks: false,
613
+ enablePublicMethods: true,
614
+ heightCalculationMethod: "bodyOffset",
615
+ id: "iFrameResizer",
616
+ interval: 32,
617
+ log: false,
618
+ maxHeight: Infinity,
619
+ maxWidth: Infinity,
620
+ minHeight: 0,
621
+ minWidth: 0,
622
+ mouseEvents: true,
623
+ resizeFrom: "parent",
624
+ scrolling: false,
625
+ sizeHeight: true,
626
+ sizeWidth: false,
627
+ warningTimeout: 5000,
628
+ tolerance: 0,
629
+ widthCalculationMethod: "scroll",
630
+ onClose: function() {
631
+ return true;
28
632
  },
29
- width: function() {
30
- warn("Custom width calculation function not defined");
31
- return document.body.scrollWidth;
633
+ onClosed: function() {},
634
+ onInit: function() {},
635
+ onMessage: function() {
636
+ warn("onMessage function not defined");
637
+ },
638
+ onMouseEnter: function() {},
639
+ onMouseLeave: function() {},
640
+ onResized: function() {},
641
+ onScroll: function() {
642
+ return true;
32
643
  }
33
- }, eventHandlersByName = {}, passiveSupported = false;
34
- function noop() {}
35
- try {
36
- var options = Object.create({}, {
37
- passive: {
38
- // eslint-disable-next-line getter-return
39
- get: function() {
40
- passiveSupported = true;
41
- }
42
- }
43
- });
44
- window.addEventListener("test", noop, options);
45
- window.removeEventListener("test", noop, options);
46
- } catch (error) {
47
- /* */ }
48
- function addEventListener(el, evt, func, options) {
49
- el.addEventListener(evt, func, passiveSupported ? options || {} : false);
644
+ };
645
+ function getMutationObserver() {
646
+ return window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
647
+ }
648
+ function addEventListener(el, evt, func) {
649
+ el.addEventListener(evt, func, false);
50
650
  }
51
651
  function removeEventListener(el, evt, func) {
52
652
  el.removeEventListener(evt, func, false);
53
653
  }
54
- function capitalizeFirstLetter(string) {
55
- return string.charAt(0).toUpperCase() + string.slice(1);
56
- }
57
- // Based on underscore.js
58
- function throttle(func) {
59
- var context, args, result, timeout = null, previous = 0, later = function() {
60
- previous = Date.now();
61
- timeout = null;
62
- result = func.apply(context, args);
63
- if (!timeout) // eslint-disable-next-line no-multi-assign
64
- context = args = null;
65
- };
66
- return function() {
67
- var now = Date.now();
68
- if (!previous) previous = now;
69
- var remaining = throttledTimer - (now - previous);
70
- context = this;
71
- args = arguments;
72
- if (remaining <= 0 || remaining > throttledTimer) {
73
- if (timeout) {
74
- clearTimeout(timeout);
75
- timeout = null;
76
- }
77
- previous = now;
78
- result = func.apply(context, args);
79
- if (!timeout) // eslint-disable-next-line no-multi-assign
80
- context = args = null;
81
- } else if (!timeout) timeout = setTimeout(later, remaining);
82
- return result;
83
- };
654
+ function setupRequestAnimationFrame() {
655
+ var vendors = [
656
+ "moz",
657
+ "webkit",
658
+ "o",
659
+ "ms"
660
+ ];
661
+ var x;
662
+ // Remove vendor prefixing if prefixed and break early if not
663
+ for(x = 0; x < vendors.length && !requestAnimationFrame; x += 1)requestAnimationFrame = window[vendors[x] + "RequestAnimationFrame"];
664
+ if (!requestAnimationFrame) log("setup", "RequestAnimationFrame not supported");
665
+ else // Firefox extension content-scripts have a globalThis object that is not the same as window.
666
+ // Binding `requestAnimationFrame` to window allows the function to work and prevents errors
667
+ // being thrown when run in that context, and should be a no-op in every other context.
668
+ requestAnimationFrame = requestAnimationFrame.bind(window);
84
669
  }
85
- function formatLogMsg(msg) {
86
- return msgID + "[" + myID + "] " + msg;
87
- }
88
- function log(msg) {
89
- if (logging && "object" === typeof window.console) // eslint-disable-next-line no-console
90
- console.log(formatLogMsg(msg));
91
- }
92
- function warn(msg) {
93
- if ("object" === typeof window.console) // eslint-disable-next-line no-console
94
- console.warn(formatLogMsg(msg));
95
- }
96
- function init() {
97
- readDataFromParent();
98
- log("Initialising iFrame (" + window.location.href + ")");
99
- readDataFromPage();
100
- setMargin();
101
- setBodyStyle("background", bodyBackground);
102
- setBodyStyle("padding", bodyPadding);
103
- injectClearFixIntoBodyElement();
104
- checkHeightMode();
105
- checkWidthMode();
106
- stopInfiniteResizingOfIFrame();
107
- setupPublicMethods();
108
- setupMouseEvents();
109
- startEventListeners();
110
- inPageLinks = setupInPageLinks();
111
- sendSize("init", "Init message from host page");
112
- onReady();
113
- }
114
- function readDataFromParent() {
115
- function strBool(str) {
116
- return "true" === str;
117
- }
118
- var data = initMsg.slice(msgIdLen).split(":");
119
- myID = data[0];
120
- bodyMargin = undefined === data[1] ? bodyMargin : Number(data[1]) // For V1 compatibility
121
- ;
122
- calculateWidth = undefined === data[2] ? calculateWidth : strBool(data[2]);
123
- logging = undefined === data[3] ? logging : strBool(data[3]);
124
- interval = undefined === data[4] ? interval : Number(data[4]);
125
- autoResize = undefined === data[6] ? autoResize : strBool(data[6]);
126
- bodyMarginStr = data[7];
127
- heightCalcMode = undefined === data[8] ? heightCalcMode : data[8];
128
- bodyBackground = data[9];
129
- bodyPadding = data[10];
130
- tolerance = undefined === data[11] ? tolerance : Number(data[11]);
131
- inPageLinks.enable = undefined === data[12] ? false : strBool(data[12]);
132
- resizeFrom = undefined === data[13] ? resizeFrom : data[13];
133
- widthCalcMode = undefined === data[14] ? widthCalcMode : data[14];
134
- mouseEvents = undefined === data[15] ? mouseEvents : strBool(data[15]);
135
- }
136
- function depricate(key) {
137
- var splitName = key.split("Callback");
138
- if (splitName.length === 2) {
139
- var name = "on" + splitName[0].charAt(0).toUpperCase() + splitName[0].slice(1);
140
- this[name] = this[key];
141
- delete this[key];
142
- warn("Deprecated: '" + key + "' has been renamed '" + name + "'. The old method will be removed in the next major version.");
143
- }
144
- }
145
- function readDataFromPage() {
146
- function readData() {
147
- var data = window.iFrameResizer;
148
- log("Reading data from page: " + JSON.stringify(data));
149
- Object.keys(data).forEach(depricate, data);
150
- onMessage = "onMessage" in data ? data.onMessage : onMessage;
151
- onReady = "onReady" in data ? data.onReady : onReady;
152
- targetOriginDefault = "targetOrigin" in data ? data.targetOrigin : targetOriginDefault;
153
- heightCalcMode = "heightCalculationMethod" in data ? data.heightCalculationMethod : heightCalcMode;
154
- widthCalcMode = "widthCalculationMethod" in data ? data.widthCalculationMethod : widthCalcMode;
155
- }
156
- function setupCustomCalcMethods(calcMode, calcFunc) {
157
- if ("function" === typeof calcMode) {
158
- log("Setup custom " + calcFunc + "CalcMethod");
159
- customCalcMethods[calcFunc] = calcMode;
160
- calcMode = "custom";
161
- }
162
- return calcMode;
163
- }
164
- if ("iFrameResizer" in window && Object === window.iFrameResizer.constructor) {
165
- readData();
166
- heightCalcMode = setupCustomCalcMethods(heightCalcMode, "height");
167
- widthCalcMode = setupCustomCalcMethods(widthCalcMode, "width");
168
- }
169
- log("TargetOrigin for parent set to: " + targetOriginDefault);
170
- }
171
- function chkCSS(attr, value) {
172
- if (-1 !== value.indexOf("-")) {
173
- warn("Negative CSS value ignored for " + attr);
174
- value = "";
175
- }
176
- return value;
177
- }
178
- function setBodyStyle(attr, value) {
179
- if (undefined !== value && "" !== value && "null" !== value) {
180
- document.body.style[attr] = value;
181
- log("Body " + attr + ' set to "' + value + '"');
182
- }
183
- }
184
- function setMargin() {
185
- // If called via V1 script, convert bodyMargin from int to str
186
- if (undefined === bodyMarginStr) bodyMarginStr = bodyMargin + "px";
187
- setBodyStyle("margin", chkCSS("margin", bodyMarginStr));
188
- }
189
- function stopInfiniteResizingOfIFrame() {
190
- document.documentElement.style.height = "";
191
- document.body.style.height = "";
192
- log('HTML & body height set to "auto"');
193
- }
194
- function manageTriggerEvent(options) {
195
- var listener = {
196
- add: function(eventName) {
197
- function handleEvent() {
198
- sendSize(options.eventName, options.eventType);
199
- }
200
- eventHandlersByName[eventName] = handleEvent;
201
- addEventListener(window, eventName, handleEvent, {
202
- passive: true
203
- });
204
- },
205
- remove: function(eventName) {
206
- var handleEvent = eventHandlersByName[eventName];
207
- delete eventHandlersByName[eventName];
208
- removeEventListener(window, eventName, handleEvent);
209
- }
210
- };
211
- if (options.eventNames && Array.prototype.map) {
212
- options.eventName = options.eventNames[0];
213
- options.eventNames.map(listener[options.method]);
214
- } else listener[options.method](options.eventName);
215
- log(capitalizeFirstLetter(options.method) + " event listener: " + options.eventType);
216
- }
217
- function manageEventListeners(method) {
218
- manageTriggerEvent({
219
- method: method,
220
- eventType: "Animation Start",
221
- eventNames: [
222
- "animationstart",
223
- "webkitAnimationStart"
224
- ]
225
- });
226
- manageTriggerEvent({
227
- method: method,
228
- eventType: "Animation Iteration",
229
- eventNames: [
230
- "animationiteration",
231
- "webkitAnimationIteration"
232
- ]
233
- });
234
- manageTriggerEvent({
235
- method: method,
236
- eventType: "Animation End",
237
- eventNames: [
238
- "animationend",
239
- "webkitAnimationEnd"
240
- ]
241
- });
242
- manageTriggerEvent({
243
- method: method,
244
- eventType: "Input",
245
- eventName: "input"
246
- });
247
- manageTriggerEvent({
248
- method: method,
249
- eventType: "Mouse Up",
250
- eventName: "mouseup"
251
- });
252
- manageTriggerEvent({
253
- method: method,
254
- eventType: "Mouse Down",
255
- eventName: "mousedown"
256
- });
257
- manageTriggerEvent({
258
- method: method,
259
- eventType: "Orientation Change",
260
- eventName: "orientationchange"
261
- });
262
- manageTriggerEvent({
263
- method: method,
264
- eventType: "Print",
265
- eventNames: [
266
- "afterprint",
267
- "beforeprint"
268
- ]
269
- });
270
- manageTriggerEvent({
271
- method: method,
272
- eventType: "Ready State Change",
273
- eventName: "readystatechange"
274
- });
275
- manageTriggerEvent({
276
- method: method,
277
- eventType: "Touch Start",
278
- eventName: "touchstart"
279
- });
280
- manageTriggerEvent({
281
- method: method,
282
- eventType: "Touch End",
283
- eventName: "touchend"
284
- });
285
- manageTriggerEvent({
286
- method: method,
287
- eventType: "Touch Cancel",
288
- eventName: "touchcancel"
289
- });
290
- manageTriggerEvent({
291
- method: method,
292
- eventType: "Transition Start",
293
- eventNames: [
294
- "transitionstart",
295
- "webkitTransitionStart",
296
- "MSTransitionStart",
297
- "oTransitionStart",
298
- "otransitionstart"
299
- ]
300
- });
301
- manageTriggerEvent({
302
- method: method,
303
- eventType: "Transition Iteration",
304
- eventNames: [
305
- "transitioniteration",
306
- "webkitTransitionIteration",
307
- "MSTransitionIteration",
308
- "oTransitionIteration",
309
- "otransitioniteration"
310
- ]
311
- });
312
- manageTriggerEvent({
313
- method: method,
314
- eventType: "Transition End",
315
- eventNames: [
316
- "transitionend",
317
- "webkitTransitionEnd",
318
- "MSTransitionEnd",
319
- "oTransitionEnd",
320
- "otransitionend"
321
- ]
322
- });
323
- if ("child" === resizeFrom) manageTriggerEvent({
324
- method: method,
325
- eventType: "IFrame Resized",
326
- eventName: "resize"
327
- });
670
+ function getMyID(iframeId) {
671
+ var retStr = "Host page: " + iframeId;
672
+ if (window.top !== window.self) retStr = window.parentIFrame && window.parentIFrame.getId ? window.parentIFrame.getId() + ": " + iframeId : "Nested host page: " + iframeId;
673
+ return retStr;
674
+ }
675
+ function formatLogHeader(iframeId) {
676
+ return msgId + "[" + getMyID(iframeId) + "]";
677
+ }
678
+ function isLogEnabled(iframeId) {
679
+ return settings[iframeId] ? settings[iframeId].log : logEnabled;
680
+ }
681
+ function log(iframeId, msg) {
682
+ output("log", iframeId, msg, isLogEnabled(iframeId));
683
+ }
684
+ function info(iframeId, msg) {
685
+ output("info", iframeId, msg, isLogEnabled(iframeId));
686
+ }
687
+ function warn(iframeId, msg) {
688
+ output("warn", iframeId, msg, true);
328
689
  }
329
- function checkCalcMode(calcMode, calcModeDefault, modes, type) {
330
- if (calcModeDefault !== calcMode) {
331
- if (!(calcMode in modes)) {
332
- warn(calcMode + " is not a valid option for " + type + "CalculationMethod.");
333
- calcMode = calcModeDefault;
334
- }
335
- log(type + ' calculation method set to "' + calcMode + '"');
336
- }
337
- return calcMode;
338
- }
339
- function checkHeightMode() {
340
- heightCalcMode = checkCalcMode(heightCalcMode, heightCalcModeDefault, getHeight, "height");
341
- }
342
- function checkWidthMode() {
343
- widthCalcMode = checkCalcMode(widthCalcMode, widthCalcModeDefault, getWidth, "width");
344
- }
345
- function startEventListeners() {
346
- if (true === autoResize) {
347
- manageEventListeners("add");
348
- setupMutationObserver();
349
- } else log("Auto Resize disabled");
350
- }
351
- // function stopMsgsToParent() {
352
- // log('Disable outgoing messages')
353
- // sendPermit = false
354
- // }
355
- // function removeMsgListener() {
356
- // log('Remove event listener: Message')
357
- // removeEventListener(window, 'message', receiver)
358
- // }
359
- function disconnectMutationObserver() {
360
- if (null !== bodyObserver) /* istanbul ignore next */ // Not testable in PhantonJS
361
- bodyObserver.disconnect();
362
- }
363
- function stopEventListeners() {
364
- manageEventListeners("remove");
365
- disconnectMutationObserver();
366
- clearInterval(intervalTimer);
367
- }
368
- // function teardown() {
369
- // stopMsgsToParent()
370
- // removeMsgListener()
371
- // if (true === autoResize) stopEventListeners()
372
- // }
373
- function injectClearFixIntoBodyElement() {
374
- var clearFix = document.createElement("div");
375
- clearFix.style.clear = "both";
376
- // Guard against the following having been globally redefined in CSS.
377
- clearFix.style.display = "block";
378
- clearFix.style.height = "0";
379
- document.body.appendChild(clearFix);
380
- }
381
- function setupInPageLinks() {
382
- function getPagePosition() {
690
+ function output(type, iframeId, msg, enabled) {
691
+ if (true === enabled && "object" === typeof window.console) // eslint-disable-next-line no-console
692
+ console[type](formatLogHeader(iframeId), msg);
693
+ }
694
+ function iFrameListener(event) {
695
+ function resizeIFrame() {
696
+ function resize() {
697
+ setSize(messageData);
698
+ setPagePosition(iframeId);
699
+ on("onResized", messageData);
700
+ }
701
+ ensureInRange("Height");
702
+ ensureInRange("Width");
703
+ syncResize(resize, messageData, "init");
704
+ }
705
+ function processMsg() {
706
+ var data = msg.substr(msgIdLen).split(":");
707
+ var height = data[1] ? parseInt(data[1], 10) : 0;
708
+ var iframe = settings[data[0]] && settings[data[0]].iframe;
709
+ var compStyle = getComputedStyle(iframe);
383
710
  return {
384
- x: window.pageXOffset === undefined ? document.documentElement.scrollLeft : window.pageXOffset,
385
- y: window.pageYOffset === undefined ? document.documentElement.scrollTop : window.pageYOffset
711
+ iframe: iframe,
712
+ id: data[0],
713
+ height: height + getPaddingEnds(compStyle) + getBorderEnds(compStyle),
714
+ width: data[2],
715
+ type: data[3]
386
716
  };
387
717
  }
388
- function getElementPosition(el) {
389
- var elPosition = el.getBoundingClientRect(), pagePosition = getPagePosition();
718
+ function getPaddingEnds(compStyle) {
719
+ if (compStyle.boxSizing !== "border-box") return 0;
720
+ var top = compStyle.paddingTop ? parseInt(compStyle.paddingTop, 10) : 0;
721
+ var bot = compStyle.paddingBottom ? parseInt(compStyle.paddingBottom, 10) : 0;
722
+ return top + bot;
723
+ }
724
+ function getBorderEnds(compStyle) {
725
+ if (compStyle.boxSizing !== "border-box") return 0;
726
+ var top = compStyle.borderTopWidth ? parseInt(compStyle.borderTopWidth, 10) : 0;
727
+ var bot = compStyle.borderBottomWidth ? parseInt(compStyle.borderBottomWidth, 10) : 0;
728
+ return top + bot;
729
+ }
730
+ function ensureInRange(Dimension) {
731
+ var max = Number(settings[iframeId]["max" + Dimension]), min = Number(settings[iframeId]["min" + Dimension]), dimension = Dimension.toLowerCase(), size = Number(messageData[dimension]);
732
+ log(iframeId, "Checking " + dimension + " is in range " + min + "-" + max);
733
+ if (size < min) {
734
+ size = min;
735
+ log(iframeId, "Set " + dimension + " to min value");
736
+ }
737
+ if (size > max) {
738
+ size = max;
739
+ log(iframeId, "Set " + dimension + " to max value");
740
+ }
741
+ messageData[dimension] = "" + size;
742
+ }
743
+ function isMessageFromIFrame() {
744
+ function checkAllowedOrigin() {
745
+ function checkList() {
746
+ var i = 0, retCode = false;
747
+ log(iframeId, "Checking connection is from allowed list of origins: " + checkOrigin);
748
+ for(; i < checkOrigin.length; i++)if (checkOrigin[i] === origin) {
749
+ retCode = true;
750
+ break;
751
+ }
752
+ return retCode;
753
+ }
754
+ function checkSingle() {
755
+ var remoteHost = settings[iframeId] && settings[iframeId].remoteHost;
756
+ log(iframeId, "Checking connection is from: " + remoteHost);
757
+ return origin === remoteHost;
758
+ }
759
+ return checkOrigin.constructor === Array ? checkList() : checkSingle();
760
+ }
761
+ var origin = event.origin, checkOrigin = settings[iframeId] && settings[iframeId].checkOrigin;
762
+ if (checkOrigin && "" + origin !== "null" && !checkAllowedOrigin()) throw new Error("Unexpected message received from: " + origin + " for " + messageData.iframe.id + ". Message was: " + event.data + ". This error can be disabled by setting the checkOrigin: false option or by providing of array of trusted domains.");
763
+ return true;
764
+ }
765
+ function isMessageForUs() {
766
+ return msgId === ("" + msg).substr(0, msgIdLen) && msg.substr(msgIdLen).split(":")[0] in settings // ''+Protects against non-string msg
767
+ ;
768
+ }
769
+ function isMessageFromMetaParent() {
770
+ // Test if this message is from a parent above us. This is an ugly test, however, updating
771
+ // the message format would break backwards compatibity.
772
+ var retCode = messageData.type in {
773
+ true: 1,
774
+ false: 1,
775
+ undefined: 1
776
+ };
777
+ if (retCode) log(iframeId, "Ignoring init message from meta parent page");
778
+ return retCode;
779
+ }
780
+ function getMsgBody(offset) {
781
+ return msg.substr(msg.indexOf(":") + msgHeaderLen + offset);
782
+ }
783
+ function forwardMsgFromIFrame(msgBody) {
784
+ log(iframeId, "onMessage passed: {iframe: " + messageData.iframe.id + ", message: " + msgBody + "}");
785
+ on("onMessage", {
786
+ iframe: messageData.iframe,
787
+ message: JSON.parse(msgBody)
788
+ });
789
+ log(iframeId, "--");
790
+ }
791
+ function getPageInfo() {
792
+ var bodyPosition = document.body.getBoundingClientRect(), iFramePosition = messageData.iframe.getBoundingClientRect();
793
+ return JSON.stringify({
794
+ iframeHeight: iFramePosition.height,
795
+ iframeWidth: iFramePosition.width,
796
+ clientHeight: Math.max(document.documentElement.clientHeight, window.innerHeight || 0),
797
+ clientWidth: Math.max(document.documentElement.clientWidth, window.innerWidth || 0),
798
+ offsetTop: parseInt(iFramePosition.top - bodyPosition.top, 10),
799
+ offsetLeft: parseInt(iFramePosition.left - bodyPosition.left, 10),
800
+ scrollTop: window.pageYOffset,
801
+ scrollLeft: window.pageXOffset,
802
+ documentHeight: document.documentElement.clientHeight,
803
+ documentWidth: document.documentElement.clientWidth,
804
+ windowHeight: window.innerHeight,
805
+ windowWidth: window.innerWidth
806
+ });
807
+ }
808
+ function sendPageInfoToIframe(iframe, iframeId) {
809
+ function debouncedTrigger() {
810
+ trigger("Send Page Info", "pageInfo:" + getPageInfo(), iframe, iframeId);
811
+ }
812
+ debounceFrameEvents(debouncedTrigger, 32, iframeId);
813
+ }
814
+ function startPageInfoMonitor() {
815
+ function setListener(type, func) {
816
+ function sendPageInfo() {
817
+ if (settings[id]) sendPageInfoToIframe(settings[id].iframe, id);
818
+ else stop();
819
+ }
820
+ [
821
+ "scroll",
822
+ "resize"
823
+ ].forEach(function(evt) {
824
+ log(id, type + evt + " listener for sendPageInfo");
825
+ func(window, evt, sendPageInfo);
826
+ });
827
+ }
828
+ function stop() {
829
+ setListener("Remove ", removeEventListener);
830
+ }
831
+ function start() {
832
+ setListener("Add ", addEventListener);
833
+ }
834
+ var id = iframeId // Create locally scoped copy of iFrame ID
835
+ ;
836
+ start();
837
+ if (settings[id]) settings[id].stopPageInfo = stop;
838
+ }
839
+ function stopPageInfoMonitor() {
840
+ if (settings[iframeId] && settings[iframeId].stopPageInfo) {
841
+ settings[iframeId].stopPageInfo();
842
+ delete settings[iframeId].stopPageInfo;
843
+ }
844
+ }
845
+ function checkIFrameExists() {
846
+ var retBool = true;
847
+ if (null === messageData.iframe) {
848
+ warn(iframeId, "IFrame (" + messageData.id + ") not found");
849
+ retBool = false;
850
+ }
851
+ return retBool;
852
+ }
853
+ function getElementPosition(target) {
854
+ var iFramePosition = target.getBoundingClientRect();
855
+ getPagePosition(iframeId);
390
856
  return {
391
- x: parseInt(elPosition.left, 10) + parseInt(pagePosition.x, 10),
392
- y: parseInt(elPosition.top, 10) + parseInt(pagePosition.y, 10)
857
+ x: Math.floor(Number(iFramePosition.left) + Number(pagePosition.x)),
858
+ y: Math.floor(Number(iFramePosition.top) + Number(pagePosition.y))
393
859
  };
394
860
  }
861
+ function scrollRequestFromChild(addOffset) {
862
+ /* istanbul ignore next */ // Not testable in Karma
863
+ function reposition() {
864
+ pagePosition = newPosition;
865
+ scrollTo();
866
+ log(iframeId, "--");
867
+ }
868
+ function calcOffset() {
869
+ return {
870
+ x: Number(messageData.width) + offset.x,
871
+ y: Number(messageData.height) + offset.y
872
+ };
873
+ }
874
+ function scrollParent() {
875
+ if (window.parentIFrame) window.parentIFrame["scrollTo" + (addOffset ? "Offset" : "")](newPosition.x, newPosition.y);
876
+ else warn(iframeId, "Unable to scroll to requested position, window.parentIFrame not found");
877
+ }
878
+ var offset = addOffset ? getElementPosition(messageData.iframe) : {
879
+ x: 0,
880
+ y: 0
881
+ }, newPosition = calcOffset();
882
+ log(iframeId, "Reposition requested from iFrame (offset x:" + offset.x + " y:" + offset.y + ")");
883
+ if (window.top !== window.self) scrollParent();
884
+ else reposition();
885
+ }
886
+ function scrollTo() {
887
+ if (false !== on("onScroll", pagePosition)) setPagePosition(iframeId);
888
+ else unsetPagePosition();
889
+ }
395
890
  function findTarget(location) {
396
- function jumpToTarget(target) {
891
+ function jumpToTarget() {
397
892
  var jumpPosition = getElementPosition(target);
398
- log("Moving to in page link (#" + hash + ") at x: " + jumpPosition.x + " y: " + jumpPosition.y);
399
- sendMsg(jumpPosition.y, jumpPosition.x, "scrollToOffset") // X&Y reversed at sendMsg uses height/width
400
- ;
401
- }
402
- var hash = location.split("#")[1] || location, hashData = decodeURIComponent(hash), target = document.getElementById(hashData) || document.getElementsByName(hashData)[0];
403
- if (undefined === target) {
404
- log("In page link (#" + hash + ") not found in iFrame, so sending to parent");
405
- sendMsg(0, 0, "inPageLink", "#" + hash);
406
- } else jumpToTarget(target);
407
- }
408
- function checkLocationHash() {
409
- var hash = window.location.hash;
410
- var href = window.location.href;
411
- if ("" !== hash && "#" !== hash) findTarget(href);
412
- }
413
- function bindAnchors() {
414
- function setupLink(el) {
415
- function linkClicked(e) {
416
- e.preventDefault();
417
- /* jshint validthis:true */ findTarget(this.getAttribute("href"));
418
- }
419
- if ("#" !== el.getAttribute("href")) addEventListener(el, "click", linkClicked);
420
- }
421
- Array.prototype.forEach.call(document.querySelectorAll('a[href^="#"]'), setupLink);
422
- }
423
- function bindLocationHash() {
424
- addEventListener(window, "hashchange", checkLocationHash);
425
- }
426
- function initCheck() {
427
- // Check if page loaded with location hash after init resize
428
- setTimeout(checkLocationHash, eventCancelTimer);
429
- }
430
- function enableInPageLinks() {
431
- /* istanbul ignore else */ // Not testable in phantonJS
432
- if (Array.prototype.forEach && document.querySelectorAll) {
433
- log("Setting up location.hash handlers");
434
- bindAnchors();
435
- bindLocationHash();
436
- initCheck();
437
- } else warn("In page linking not fully supported in this browser! (See README.md for IE8 workaround)");
438
- }
439
- if (inPageLinks.enable) enableInPageLinks();
440
- else log("In page linking not enabled");
441
- return {
442
- findTarget: findTarget
443
- };
893
+ log(iframeId, "Moving to in page link (#" + hash + ") at x: " + jumpPosition.x + " y: " + jumpPosition.y);
894
+ pagePosition = {
895
+ x: jumpPosition.x,
896
+ y: jumpPosition.y
897
+ };
898
+ scrollTo();
899
+ log(iframeId, "--");
900
+ }
901
+ function jumpToParent() {
902
+ if (window.parentIFrame) window.parentIFrame.moveToAnchor(hash);
903
+ else log(iframeId, "In page link #" + hash + " not found and window.parentIFrame not found");
904
+ }
905
+ var hash = location.split("#")[1] || "", hashData = decodeURIComponent(hash), target = document.getElementById(hashData) || document.getElementsByName(hashData)[0];
906
+ if (target) jumpToTarget();
907
+ else if (window.top !== window.self) jumpToParent();
908
+ else log(iframeId, "In page link #" + hash + " not found");
909
+ }
910
+ function onMouse(event) {
911
+ var mousePos = {};
912
+ if (Number(messageData.width) === 0 && Number(messageData.height) === 0) {
913
+ var data = getMsgBody(9).split(":");
914
+ mousePos = {
915
+ x: data[1],
916
+ y: data[0]
917
+ };
918
+ } else mousePos = {
919
+ x: messageData.width,
920
+ y: messageData.height
921
+ };
922
+ on(event, {
923
+ iframe: messageData.iframe,
924
+ screenX: Number(mousePos.x),
925
+ screenY: Number(mousePos.y),
926
+ type: messageData.type
927
+ });
928
+ }
929
+ function on(funcName, val) {
930
+ return chkEvent(iframeId, funcName, val);
931
+ }
932
+ function actionMsg() {
933
+ if (settings[iframeId] && settings[iframeId].firstRun) firstRun();
934
+ switch(messageData.type){
935
+ case "close":
936
+ closeIFrame(messageData.iframe);
937
+ break;
938
+ case "message":
939
+ forwardMsgFromIFrame(getMsgBody(6));
940
+ break;
941
+ case "mouseenter":
942
+ onMouse("onMouseEnter");
943
+ break;
944
+ case "mouseleave":
945
+ onMouse("onMouseLeave");
946
+ break;
947
+ case "autoResize":
948
+ settings[iframeId].autoResize = JSON.parse(getMsgBody(9));
949
+ break;
950
+ case "scrollTo":
951
+ scrollRequestFromChild(false);
952
+ break;
953
+ case "scrollToOffset":
954
+ scrollRequestFromChild(true);
955
+ break;
956
+ case "pageInfo":
957
+ sendPageInfoToIframe(settings[iframeId] && settings[iframeId].iframe, iframeId);
958
+ startPageInfoMonitor();
959
+ break;
960
+ case "pageInfoStop":
961
+ stopPageInfoMonitor();
962
+ break;
963
+ case "inPageLink":
964
+ findTarget(getMsgBody(9));
965
+ break;
966
+ case "reset":
967
+ resetIFrame(messageData);
968
+ break;
969
+ case "init":
970
+ resizeIFrame();
971
+ on("onInit", messageData.iframe);
972
+ break;
973
+ default:
974
+ if (Number(messageData.width) === 0 && Number(messageData.height) === 0) warn("Unsupported message received (" + messageData.type + "), this is likely due to the iframe containing a later " + "version of iframe-resizer than the parent page");
975
+ else resizeIFrame();
976
+ }
977
+ }
978
+ function hasSettings(iframeId) {
979
+ var retBool = true;
980
+ if (!settings[iframeId]) {
981
+ retBool = false;
982
+ warn(messageData.type + " No settings for " + iframeId + ". Message was: " + msg);
983
+ }
984
+ return retBool;
985
+ }
986
+ function iFrameReadyMsgReceived() {
987
+ // eslint-disable-next-line no-restricted-syntax, guard-for-in
988
+ for(var iframeId in settings)trigger("iFrame requested init", createOutgoingMsg(iframeId), settings[iframeId].iframe, iframeId);
989
+ }
990
+ function firstRun() {
991
+ if (settings[iframeId]) settings[iframeId].firstRun = false;
992
+ }
993
+ var msg = event.data, messageData = {}, iframeId = null;
994
+ if ("[iFrameResizerChild]Ready" === msg) iFrameReadyMsgReceived();
995
+ else if (isMessageForUs()) {
996
+ messageData = processMsg();
997
+ iframeId = messageData.id;
998
+ if (settings[iframeId]) settings[iframeId].loaded = true;
999
+ if (!isMessageFromMetaParent() && hasSettings(iframeId)) {
1000
+ log(iframeId, "Received: " + msg);
1001
+ if (checkIFrameExists() && isMessageFromIFrame()) actionMsg();
1002
+ }
1003
+ } else info(iframeId, "Ignored: " + msg);
444
1004
  }
445
- function setupMouseEvents() {
446
- if (mouseEvents !== true) return;
447
- function sendMouse(e) {
448
- sendMsg(0, 0, e.type, e.screenY + ":" + e.screenX);
449
- }
450
- function addMouseListener(evt, name) {
451
- log("Add event listener: " + name);
452
- addEventListener(window.document, evt, sendMouse);
453
- }
454
- addMouseListener("mouseenter", "Mouse Enter");
455
- addMouseListener("mouseleave", "Mouse Leave");
456
- }
457
- function setupPublicMethods() {
458
- log("Enable public methods");
459
- win.parentIFrame = {
460
- autoResize: function autoResizeF(resize) {
461
- if (true === resize && false === autoResize) {
462
- autoResize = true;
463
- startEventListeners();
464
- } else if (false === resize && true === autoResize) {
465
- autoResize = false;
466
- stopEventListeners();
467
- }
468
- sendMsg(0, 0, "autoResize", JSON.stringify(autoResize));
469
- return autoResize;
470
- },
471
- close: function closeF() {
472
- sendMsg(0, 0, "close");
473
- // teardown()
474
- },
475
- getId: function getIdF() {
476
- return myID;
477
- },
478
- getPageInfo: function getPageInfoF(callback) {
479
- if ("function" === typeof callback) {
480
- onPageInfo = callback;
481
- sendMsg(0, 0, "pageInfo");
482
- } else {
483
- onPageInfo = function() {};
484
- sendMsg(0, 0, "pageInfoStop");
485
- }
486
- },
487
- moveToAnchor: function moveToAnchorF(hash) {
488
- inPageLinks.findTarget(hash);
489
- },
490
- reset: function resetF() {
491
- resetIFrame("parentIFrame.reset");
492
- },
493
- scrollTo: function scrollToF(x, y) {
494
- sendMsg(y, x, "scrollTo") // X&Y reversed at sendMsg uses height/width
495
- ;
496
- },
497
- scrollToOffset: function scrollToF(x, y) {
498
- sendMsg(y, x, "scrollToOffset") // X&Y reversed at sendMsg uses height/width
499
- ;
500
- },
501
- sendMessage: function sendMessageF(msg, targetOrigin) {
502
- sendMsg(0, 0, "message", JSON.stringify(msg), targetOrigin);
503
- },
504
- setHeightCalculationMethod: function setHeightCalculationMethodF(heightCalculationMethod) {
505
- heightCalcMode = heightCalculationMethod;
506
- checkHeightMode();
507
- },
508
- setWidthCalculationMethod: function setWidthCalculationMethodF(widthCalculationMethod) {
509
- widthCalcMode = widthCalculationMethod;
510
- checkWidthMode();
511
- },
512
- setTargetOrigin: function setTargetOriginF(targetOrigin) {
513
- log("Set targetOrigin: " + targetOrigin);
514
- targetOriginDefault = targetOrigin;
515
- },
516
- size: function sizeF(customHeight, customWidth) {
517
- var valString = "" + (customHeight || "") + (customWidth ? "," + customWidth : "");
518
- sendSize("size", "parentIFrame.size(" + valString + ")", customHeight, customWidth);
1005
+ function chkEvent(iframeId, funcName, val) {
1006
+ var func = null, retVal = null;
1007
+ if (settings[iframeId]) {
1008
+ func = settings[iframeId][funcName];
1009
+ if ("function" === typeof func) retVal = func(val);
1010
+ else throw new TypeError(funcName + " on iFrame[" + iframeId + "] is not a function");
1011
+ }
1012
+ return retVal;
1013
+ }
1014
+ function removeIframeListeners(iframe) {
1015
+ var iframeId = iframe.id;
1016
+ delete settings[iframeId];
1017
+ }
1018
+ function closeIFrame(iframe) {
1019
+ var iframeId = iframe.id;
1020
+ if (chkEvent(iframeId, "onClose", iframeId) === false) {
1021
+ log(iframeId, "Close iframe cancelled by onClose event");
1022
+ return;
1023
+ }
1024
+ log(iframeId, "Removing iFrame: " + iframeId);
1025
+ try {
1026
+ // Catch race condition error with React
1027
+ if (iframe.parentNode) iframe.parentNode.removeChild(iframe);
1028
+ } catch (error) {
1029
+ warn(error);
1030
+ }
1031
+ chkEvent(iframeId, "onClosed", iframeId);
1032
+ log(iframeId, "--");
1033
+ removeIframeListeners(iframe);
1034
+ }
1035
+ function getPagePosition(iframeId) {
1036
+ if (null === pagePosition) {
1037
+ pagePosition = {
1038
+ x: window.pageXOffset !== undefined ? window.pageXOffset : document.documentElement.scrollLeft,
1039
+ y: window.pageYOffset !== undefined ? window.pageYOffset : document.documentElement.scrollTop
1040
+ };
1041
+ log(iframeId, "Get page position: " + pagePosition.x + "," + pagePosition.y);
1042
+ }
1043
+ }
1044
+ function setPagePosition(iframeId) {
1045
+ if (null !== pagePosition) {
1046
+ window.scrollTo(pagePosition.x, pagePosition.y);
1047
+ log(iframeId, "Set page position: " + pagePosition.x + "," + pagePosition.y);
1048
+ unsetPagePosition();
1049
+ }
1050
+ }
1051
+ function unsetPagePosition() {
1052
+ pagePosition = null;
1053
+ }
1054
+ function resetIFrame(messageData) {
1055
+ function reset() {
1056
+ setSize(messageData);
1057
+ trigger("reset", "reset", messageData.iframe, messageData.id);
1058
+ }
1059
+ log(messageData.id, "Size reset requested by " + ("init" === messageData.type ? "host page" : "iFrame"));
1060
+ getPagePosition(messageData.id);
1061
+ syncResize(reset, messageData, "reset");
1062
+ }
1063
+ function setSize(messageData) {
1064
+ function setDimension(dimension) {
1065
+ if (!messageData.id) {
1066
+ log("undefined", "messageData id not set");
1067
+ return;
519
1068
  }
520
- };
1069
+ messageData.iframe.style[dimension] = messageData[dimension] + "px";
1070
+ log(messageData.id, "IFrame (" + iframeId + ") " + dimension + " set to " + messageData[dimension] + "px");
1071
+ }
1072
+ function chkZero(dimension) {
1073
+ // FireFox sets dimension of hidden iFrames to zero.
1074
+ // So if we detect that set up an event to check for
1075
+ // when iFrame becomes visible.
1076
+ /* istanbul ignore next */ // Not testable in PhantomJS
1077
+ if (!hiddenCheckEnabled && "0" === messageData[dimension]) {
1078
+ hiddenCheckEnabled = true;
1079
+ log(iframeId, "Hidden iFrame detected, creating visibility listener");
1080
+ fixHiddenIFrames();
1081
+ }
1082
+ }
1083
+ function processDimension(dimension) {
1084
+ setDimension(dimension);
1085
+ chkZero(dimension);
1086
+ }
1087
+ var iframeId = messageData.iframe.id;
1088
+ if (settings[iframeId]) {
1089
+ if (settings[iframeId].sizeHeight) processDimension("height");
1090
+ if (settings[iframeId].sizeWidth) processDimension("width");
1091
+ }
521
1092
  }
522
- function initInterval() {
523
- if (0 !== interval) {
524
- log("setInterval: " + interval + "ms");
525
- intervalTimer = setInterval(function() {
526
- sendSize("interval", "setInterval: " + interval);
527
- }, Math.abs(interval));
1093
+ function syncResize(func, messageData, doNotSync) {
1094
+ /* istanbul ignore if */ // Not testable in PhantomJS
1095
+ if (doNotSync !== messageData.type && requestAnimationFrame && // including check for jasmine because had trouble getting spy to work in unit test using requestAnimationFrame
1096
+ !window.jasmine) {
1097
+ log(messageData.id, "Requesting animation frame");
1098
+ requestAnimationFrame(func);
1099
+ } else func();
1100
+ }
1101
+ function trigger(calleeMsg, msg, iframe, id, noResponseWarning) {
1102
+ function postMessageToIFrame() {
1103
+ var target = settings[id] && settings[id].targetOrigin;
1104
+ log(id, "[" + calleeMsg + "] Sending msg to iframe[" + id + "] (" + msg + ") targetOrigin: " + target);
1105
+ iframe.contentWindow.postMessage(msgId + msg, target);
1106
+ }
1107
+ function iFrameNotFound() {
1108
+ warn(id, "[" + calleeMsg + "] IFrame(" + id + ") not found");
1109
+ }
1110
+ function chkAndSend() {
1111
+ if (iframe && "contentWindow" in iframe && null !== iframe.contentWindow) // Null test for PhantomJS
1112
+ postMessageToIFrame();
1113
+ else iFrameNotFound();
1114
+ }
1115
+ function warnOnNoResponse() {
1116
+ function warning() {
1117
+ if (settings[id] && !settings[id].loaded && !errorShown) {
1118
+ errorShown = true;
1119
+ warn(id, "IFrame has not responded within " + settings[id].warningTimeout / 1000 + " seconds. Check iFrameResizer.contentWindow.js has been loaded in iFrame. This message can be ignored if everything is working, or you can set the warningTimeout option to a higher value or zero to suppress this warning.");
1120
+ }
1121
+ }
1122
+ if (!!noResponseWarning && settings[id] && !!settings[id].warningTimeout) settings[id].msgTimeout = setTimeout(warning, settings[id].warningTimeout);
1123
+ }
1124
+ var errorShown = false;
1125
+ id = id || iframe.id;
1126
+ if (settings[id]) {
1127
+ chkAndSend();
1128
+ warnOnNoResponse();
528
1129
  }
529
1130
  }
530
- // Not testable in PhantomJS
531
- /* istanbul ignore next */ function setupBodyMutationObserver() {
532
- function addImageLoadListners(mutation) {
533
- function addImageLoadListener(element) {
534
- if (false === element.complete) {
535
- log("Attach listeners to " + element.src);
536
- element.addEventListener("load", imageLoaded, false);
537
- element.addEventListener("error", imageError, false);
538
- elements.push(element);
1131
+ function createOutgoingMsg(iframeId) {
1132
+ return iframeId + ":" + settings[iframeId].bodyMarginV1 + ":" + settings[iframeId].sizeWidth + ":" + settings[iframeId].log + ":" + settings[iframeId].interval + ":" + settings[iframeId].enablePublicMethods + ":" + settings[iframeId].autoResize + ":" + settings[iframeId].bodyMargin + ":" + settings[iframeId].heightCalculationMethod + ":" + settings[iframeId].bodyBackground + ":" + settings[iframeId].bodyPadding + ":" + settings[iframeId].tolerance + ":" + settings[iframeId].inPageLinks + ":" + settings[iframeId].resizeFrom + ":" + settings[iframeId].widthCalculationMethod + ":" + settings[iframeId].mouseEvents;
1133
+ }
1134
+ function isNumber(value) {
1135
+ return typeof value === "number";
1136
+ }
1137
+ function setupIFrame(iframe, options) {
1138
+ function setLimits() {
1139
+ function addStyle(style) {
1140
+ var styleValue = settings[iframeId][style];
1141
+ if (Infinity !== styleValue && 0 !== styleValue) {
1142
+ iframe.style[style] = isNumber(styleValue) ? styleValue + "px" : styleValue;
1143
+ log(iframeId, "Set " + style + " = " + iframe.style[style]);
539
1144
  }
540
1145
  }
541
- if (mutation.type === "attributes" && mutation.attributeName === "src") addImageLoadListener(mutation.target);
542
- else if (mutation.type === "childList") Array.prototype.forEach.call(mutation.target.querySelectorAll("img"), addImageLoadListener);
1146
+ function chkMinMax(dimension) {
1147
+ if (settings[iframeId]["min" + dimension] > settings[iframeId]["max" + dimension]) throw new Error("Value for min" + dimension + " can not be greater than max" + dimension);
1148
+ }
1149
+ chkMinMax("Height");
1150
+ chkMinMax("Width");
1151
+ addStyle("maxHeight");
1152
+ addStyle("minHeight");
1153
+ addStyle("maxWidth");
1154
+ addStyle("minWidth");
1155
+ }
1156
+ function newId() {
1157
+ var id = options && options.id || defaults.id + count++;
1158
+ if (null !== document.getElementById(id)) id += count++;
1159
+ return id;
1160
+ }
1161
+ function ensureHasId(iframeId) {
1162
+ if ("" === iframeId) {
1163
+ // eslint-disable-next-line no-multi-assign
1164
+ iframe.id = iframeId = newId();
1165
+ logEnabled = (options || {}).log;
1166
+ log(iframeId, "Added missing iframe ID: " + iframeId + " (" + iframe.src + ")");
1167
+ }
1168
+ return iframeId;
1169
+ }
1170
+ function setScrolling() {
1171
+ log(iframeId, "IFrame scrolling " + (settings[iframeId] && settings[iframeId].scrolling ? "enabled" : "disabled") + " for " + iframeId);
1172
+ iframe.style.overflow = false === (settings[iframeId] && settings[iframeId].scrolling) ? "hidden" : "auto";
1173
+ switch(settings[iframeId] && settings[iframeId].scrolling){
1174
+ case "omit":
1175
+ break;
1176
+ case true:
1177
+ iframe.scrolling = "yes";
1178
+ break;
1179
+ case false:
1180
+ iframe.scrolling = "no";
1181
+ break;
1182
+ default:
1183
+ iframe.scrolling = settings[iframeId] ? settings[iframeId].scrolling : "no";
1184
+ }
1185
+ }
1186
+ // The V1 iFrame script expects an int, where as in V2 expects a CSS
1187
+ // string value such as '1px 3em', so if we have an int for V2, set V1=V2
1188
+ // and then convert V2 to a string PX value.
1189
+ function setupBodyMarginValues() {
1190
+ if ("number" === typeof (settings[iframeId] && settings[iframeId].bodyMargin) || "0" === (settings[iframeId] && settings[iframeId].bodyMargin)) {
1191
+ settings[iframeId].bodyMarginV1 = settings[iframeId].bodyMargin;
1192
+ settings[iframeId].bodyMargin = "" + settings[iframeId].bodyMargin + "px";
1193
+ }
543
1194
  }
544
- function removeFromArray(element) {
545
- elements.splice(elements.indexOf(element), 1);
1195
+ function checkReset() {
1196
+ // Reduce scope of firstRun to function, because IE8's JS execution
1197
+ // context stack is borked and this value gets externally
1198
+ // changed midway through running this function!!!
1199
+ var firstRun = settings[iframeId] && settings[iframeId].firstRun, resetRequertMethod = settings[iframeId] && settings[iframeId].heightCalculationMethod in resetRequiredMethods;
1200
+ if (!firstRun && resetRequertMethod) resetIFrame({
1201
+ iframe: iframe,
1202
+ height: 0,
1203
+ width: 0,
1204
+ type: "init"
1205
+ });
546
1206
  }
547
- function removeImageLoadListener(element) {
548
- log("Remove listeners from " + element.src);
549
- element.removeEventListener("load", imageLoaded, false);
550
- element.removeEventListener("error", imageError, false);
551
- removeFromArray(element);
1207
+ function setupIFrameObject() {
1208
+ if (settings[iframeId]) settings[iframeId].iframe.iFrameResizer = {
1209
+ close: closeIFrame.bind(null, settings[iframeId].iframe),
1210
+ removeListeners: removeIframeListeners.bind(null, settings[iframeId].iframe),
1211
+ resize: trigger.bind(null, "Window resize", "resize", settings[iframeId].iframe),
1212
+ moveToAnchor: function(anchor) {
1213
+ trigger("Move to anchor", "moveToAnchor:" + anchor, settings[iframeId].iframe, iframeId);
1214
+ },
1215
+ sendMessage: function(message) {
1216
+ message = JSON.stringify(message);
1217
+ trigger("Send Message", "message:" + message, settings[iframeId].iframe, iframeId);
1218
+ }
1219
+ };
552
1220
  }
553
- function imageEventTriggered(event, type, typeDesc) {
554
- removeImageLoadListener(event.target);
555
- sendSize(type, typeDesc + ": " + event.target.src);
1221
+ // We have to call trigger twice, as we can not be sure if all
1222
+ // iframes have completed loading when this code runs. The
1223
+ // event listener also catches the page changing in the iFrame.
1224
+ function init(msg) {
1225
+ function iFrameLoaded() {
1226
+ trigger("iFrame.onload", msg, iframe, undefined, true);
1227
+ checkReset();
1228
+ }
1229
+ function createDestroyObserver(MutationObserver) {
1230
+ if (!iframe.parentNode) return;
1231
+ var destroyObserver = new MutationObserver(function(mutations) {
1232
+ mutations.forEach(function(mutation) {
1233
+ var removedNodes = Array.prototype.slice.call(mutation.removedNodes) // Transform NodeList into an Array
1234
+ ;
1235
+ removedNodes.forEach(function(removedNode) {
1236
+ if (removedNode === iframe) closeIFrame(iframe);
1237
+ });
1238
+ });
1239
+ });
1240
+ destroyObserver.observe(iframe.parentNode, {
1241
+ childList: true
1242
+ });
1243
+ }
1244
+ var MutationObserver = getMutationObserver();
1245
+ if (MutationObserver) createDestroyObserver(MutationObserver);
1246
+ addEventListener(iframe, "load", iFrameLoaded);
1247
+ trigger("init", msg, iframe, undefined, true);
556
1248
  }
557
- function imageLoaded(event) {
558
- imageEventTriggered(event, "imageLoad", "Image loaded");
1249
+ function checkOptions(options) {
1250
+ if ("object" !== typeof options) throw new TypeError("Options is not an object");
559
1251
  }
560
- function imageError(event) {
561
- imageEventTriggered(event, "imageLoadFailed", "Image load failed");
1252
+ function copyOptions(options) {
1253
+ // eslint-disable-next-line no-restricted-syntax
1254
+ for(var option in defaults)if (Object.prototype.hasOwnProperty.call(defaults, option)) settings[iframeId][option] = Object.prototype.hasOwnProperty.call(options, option) ? options[option] : defaults[option];
1255
+ }
1256
+ function getTargetOrigin(remoteHost) {
1257
+ return "" === remoteHost || null !== remoteHost.match(/^(about:blank|javascript:|file:\/\/)/) ? "*" : remoteHost;
1258
+ }
1259
+ function depricate(key) {
1260
+ var splitName = key.split("Callback");
1261
+ if (splitName.length === 2) {
1262
+ var name = "on" + splitName[0].charAt(0).toUpperCase() + splitName[0].slice(1);
1263
+ this[name] = this[key];
1264
+ delete this[key];
1265
+ warn(iframeId, "Deprecated: '" + key + "' has been renamed '" + name + "'. The old method will be removed in the next major version.");
1266
+ }
1267
+ }
1268
+ function processOptions(options) {
1269
+ options = options || {};
1270
+ settings[iframeId] = {
1271
+ firstRun: true,
1272
+ iframe: iframe,
1273
+ remoteHost: iframe.src && iframe.src.split("/").slice(0, 3).join("/")
1274
+ };
1275
+ checkOptions(options);
1276
+ Object.keys(options).forEach(depricate, options);
1277
+ copyOptions(options);
1278
+ if (settings[iframeId]) settings[iframeId].targetOrigin = true === settings[iframeId].checkOrigin ? getTargetOrigin(settings[iframeId].remoteHost) : "*";
1279
+ }
1280
+ function beenHere() {
1281
+ return iframeId in settings && "iFrameResizer" in iframe;
1282
+ }
1283
+ var iframeId = ensureHasId(iframe.id);
1284
+ if (!beenHere()) {
1285
+ processOptions(options);
1286
+ setScrolling();
1287
+ setLimits();
1288
+ setupBodyMarginValues();
1289
+ init(createOutgoingMsg(iframeId));
1290
+ setupIFrameObject();
1291
+ } else warn(iframeId, "Ignored iFrame, already setup.");
1292
+ }
1293
+ function debouce(fn, time) {
1294
+ if (null === timer) timer = setTimeout(function() {
1295
+ timer = null;
1296
+ fn();
1297
+ }, time);
1298
+ }
1299
+ var frameTimer = {};
1300
+ function debounceFrameEvents(fn, time, frameId) {
1301
+ if (!frameTimer[frameId]) frameTimer[frameId] = setTimeout(function() {
1302
+ frameTimer[frameId] = null;
1303
+ fn();
1304
+ }, time);
1305
+ }
1306
+ // Not testable in PhantomJS
1307
+ /* istanbul ignore next */ function fixHiddenIFrames() {
1308
+ function checkIFrames() {
1309
+ function checkIFrame(settingId) {
1310
+ function chkDimension(dimension) {
1311
+ return "0px" === (settings[settingId] && settings[settingId].iframe.style[dimension]);
1312
+ }
1313
+ function isVisible(el) {
1314
+ return null !== el.offsetParent;
1315
+ }
1316
+ if (settings[settingId] && isVisible(settings[settingId].iframe) && (chkDimension("height") || chkDimension("width"))) trigger("Visibility change", "resize", settings[settingId].iframe, settingId);
1317
+ }
1318
+ Object.keys(settings).forEach(function(key) {
1319
+ checkIFrame(key);
1320
+ });
562
1321
  }
563
1322
  function mutationObserved(mutations) {
564
- sendSize("mutationObserver", "mutationObserver: " + mutations[0].target + " " + mutations[0].type);
565
- // Deal with WebKit / Blink asyncing image loading when tags are injected into the page
566
- mutations.forEach(addImageLoadListners);
1323
+ log("window", "Mutation observed: " + mutations[0].target + " " + mutations[0].type);
1324
+ debouce(checkIFrames, 16);
567
1325
  }
568
1326
  function createMutationObserver() {
569
1327
  var target = document.querySelector("body"), config = {
@@ -573,335 +1331,97 @@ var $b2e1fd3e30ab1f5c$exports = {};
573
1331
  characterDataOldValue: false,
574
1332
  childList: true,
575
1333
  subtree: true
576
- };
577
- observer = new MutationObserver(mutationObserved);
578
- log("Create body MutationObserver");
1334
+ }, observer = new MutationObserver(mutationObserved);
579
1335
  observer.observe(target, config);
580
- return observer;
581
- }
582
- var elements = [], MutationObserver = window.MutationObserver || window.WebKitMutationObserver, observer = createMutationObserver();
583
- return {
584
- disconnect: function() {
585
- if ("disconnect" in observer) {
586
- log("Disconnect body MutationObserver");
587
- observer.disconnect();
588
- elements.forEach(removeImageLoadListener);
589
- }
590
- }
591
- };
592
- }
593
- function setupMutationObserver() {
594
- var forceIntervalTimer = 0 > interval;
595
- // Not testable in PhantomJS
596
- /* istanbul ignore if */ if (window.MutationObserver || window.WebKitMutationObserver) {
597
- if (forceIntervalTimer) initInterval();
598
- else bodyObserver = setupBodyMutationObserver();
599
- } else {
600
- log("MutationObserver not supported in this browser!");
601
- initInterval();
602
- }
603
- }
604
- // document.documentElement.offsetHeight is not reliable, so
605
- // we have to jump through hoops to get a better value.
606
- function getComputedStyle(prop, el) {
607
- var retVal = 0;
608
- el = el || document.body // Not testable in phantonJS
609
- ;
610
- retVal = document.defaultView.getComputedStyle(el, null);
611
- retVal = null === retVal ? 0 : retVal[prop];
612
- return parseInt(retVal, base);
613
- }
614
- function chkEventThottle(timer) {
615
- if (timer > throttledTimer / 2) {
616
- throttledTimer = 2 * timer;
617
- log("Event throttle increased to " + throttledTimer + "ms");
618
- }
619
- }
620
- // Idea from https://github.com/guardian/iframe-messenger
621
- function getMaxElement(side, elements) {
622
- var elementsLength = elements.length, elVal = 0, maxVal = 0, Side = capitalizeFirstLetter(side), timer = Date.now();
623
- for(var i = 0; i < elementsLength; i++){
624
- elVal = elements[i].getBoundingClientRect()[side] + getComputedStyle("margin" + Side, elements[i]);
625
- if (elVal > maxVal) maxVal = elVal;
626
- }
627
- timer = Date.now() - timer;
628
- log("Parsed " + elementsLength + " HTML elements");
629
- log("Element position calculated in " + timer + "ms");
630
- chkEventThottle(timer);
631
- return maxVal;
632
- }
633
- function getAllMeasurements(dimensions) {
634
- return [
635
- dimensions.bodyOffset(),
636
- dimensions.bodyScroll(),
637
- dimensions.documentElementOffset(),
638
- dimensions.documentElementScroll()
639
- ];
640
- }
641
- function getTaggedElements(side, tag) {
642
- function noTaggedElementsFound() {
643
- warn("No tagged elements (" + tag + ") found on page");
644
- return document.querySelectorAll("body *");
645
1336
  }
646
- var elements = document.querySelectorAll("[" + tag + "]");
647
- if (elements.length === 0) noTaggedElementsFound();
648
- return getMaxElement(side, elements);
1337
+ var MutationObserver = getMutationObserver();
1338
+ if (MutationObserver) createMutationObserver();
649
1339
  }
650
- function getAllElements() {
651
- return document.querySelectorAll("body *");
1340
+ function resizeIFrames(event) {
1341
+ function resize() {
1342
+ sendTriggerMsg("Window " + event, "resize");
1343
+ }
1344
+ log("window", "Trigger event: " + event);
1345
+ debouce(resize, 16);
652
1346
  }
653
- var getHeight = {
654
- bodyOffset: function getBodyOffsetHeight() {
655
- return document.body.offsetHeight + getComputedStyle("marginTop") + getComputedStyle("marginBottom");
656
- },
657
- offset: function() {
658
- return getHeight.bodyOffset() // Backwards compatibility
659
- ;
660
- },
661
- bodyScroll: function getBodyScrollHeight() {
662
- return document.body.scrollHeight;
663
- },
664
- custom: function getCustomWidth() {
665
- return customCalcMethods.height();
666
- },
667
- documentElementOffset: function getDEOffsetHeight() {
668
- return document.documentElement.offsetHeight;
669
- },
670
- documentElementScroll: function getDEScrollHeight() {
671
- return document.documentElement.scrollHeight;
672
- },
673
- max: function getMaxHeight() {
674
- return Math.max.apply(null, getAllMeasurements(getHeight));
675
- },
676
- min: function getMinHeight() {
677
- return Math.min.apply(null, getAllMeasurements(getHeight));
678
- },
679
- grow: function growHeight() {
680
- return getHeight.max() // Run max without the forced downsizing
681
- ;
682
- },
683
- lowestElement: function getBestHeight() {
684
- return Math.max(getHeight.bodyOffset() || getHeight.documentElementOffset(), getMaxElement("bottom", getAllElements()));
685
- },
686
- taggedElement: function getTaggedElementsHeight() {
687
- return getTaggedElements("bottom", "data-iframe-height");
1347
+ // Not testable in PhantomJS
1348
+ /* istanbul ignore next */ function tabVisible() {
1349
+ function resize() {
1350
+ sendTriggerMsg("Tab Visable", "resize");
688
1351
  }
689
- }, getWidth = {
690
- bodyScroll: function getBodyScrollWidth() {
691
- return document.body.scrollWidth;
692
- },
693
- bodyOffset: function getBodyOffsetWidth() {
694
- return document.body.offsetWidth;
695
- },
696
- custom: function getCustomWidth() {
697
- return customCalcMethods.width();
698
- },
699
- documentElementScroll: function getDEScrollWidth() {
700
- return document.documentElement.scrollWidth;
701
- },
702
- documentElementOffset: function getDEOffsetWidth() {
703
- return document.documentElement.offsetWidth;
704
- },
705
- scroll: function getMaxWidth() {
706
- return Math.max(getWidth.bodyScroll(), getWidth.documentElementScroll());
707
- },
708
- max: function getMaxWidth() {
709
- return Math.max.apply(null, getAllMeasurements(getWidth));
710
- },
711
- min: function getMinWidth() {
712
- return Math.min.apply(null, getAllMeasurements(getWidth));
713
- },
714
- rightMostElement: function rightMostElement() {
715
- return getMaxElement("right", getAllElements());
716
- },
717
- taggedElement: function getTaggedElementsWidth() {
718
- return getTaggedElements("right", "data-iframe-width");
1352
+ if ("hidden" !== document.visibilityState) {
1353
+ log("document", "Trigger event: Visiblity change");
1354
+ debouce(resize, 16);
719
1355
  }
720
- };
721
- function sizeIFrame(triggerEvent, triggerEventDesc, customHeight, customWidth) {
722
- function resizeIFrame() {
723
- height = currentHeight;
724
- width = currentWidth;
725
- sendMsg(height, width, triggerEvent);
726
- }
727
- function isSizeChangeDetected() {
728
- function checkTolarance(a, b) {
729
- var retVal = Math.abs(a - b) <= tolerance;
730
- return !retVal;
731
- }
732
- currentHeight = undefined === customHeight ? getHeight[heightCalcMode]() : customHeight;
733
- currentWidth = undefined === customWidth ? getWidth[widthCalcMode]() : customWidth;
734
- return checkTolarance(height, currentHeight) || calculateWidth && checkTolarance(width, currentWidth);
735
- }
736
- function isForceResizableEvent() {
737
- return !(triggerEvent in {
738
- init: 1,
739
- interval: 1,
740
- size: 1
741
- });
1356
+ }
1357
+ function sendTriggerMsg(eventName, event) {
1358
+ function isIFrameResizeEnabled(iframeId) {
1359
+ return settings[iframeId] && "parent" === settings[iframeId].resizeFrom && settings[iframeId].autoResize && !settings[iframeId].firstRun;
742
1360
  }
743
- function isForceResizableCalcMode() {
744
- return heightCalcMode in resetRequiredMethods || calculateWidth && widthCalcMode in resetRequiredMethods;
745
- }
746
- function logIgnored() {
747
- log("No change in size detected");
748
- }
749
- function checkDownSizing() {
750
- if (isForceResizableEvent() && isForceResizableCalcMode()) resetIFrame(triggerEventDesc);
751
- else if (!(triggerEvent in {
752
- interval: 1
753
- })) logIgnored();
754
- }
755
- var currentHeight, currentWidth;
756
- if (isSizeChangeDetected() || "init" === triggerEvent) {
757
- lockTrigger();
758
- resizeIFrame();
759
- } else checkDownSizing();
760
- }
761
- var sizeIFrameThrottled = throttle(sizeIFrame);
762
- function sendSize(triggerEvent, triggerEventDesc, customHeight, customWidth) {
763
- function recordTrigger() {
764
- if (!(triggerEvent in {
765
- reset: 1,
766
- resetPage: 1,
767
- init: 1
768
- })) log("Trigger event: " + triggerEventDesc);
769
- }
770
- function isDoubleFiredEvent() {
771
- return triggerLocked && triggerEvent in doubleEventList;
772
- }
773
- if (isDoubleFiredEvent()) log("Trigger event cancelled: " + triggerEvent);
774
- else {
775
- recordTrigger();
776
- if (triggerEvent === "init") sizeIFrame(triggerEvent, triggerEventDesc, customHeight, customWidth);
777
- else sizeIFrameThrottled(triggerEvent, triggerEventDesc, customHeight, customWidth);
778
- }
779
- }
780
- function lockTrigger() {
781
- if (!triggerLocked) {
782
- triggerLocked = true;
783
- log("Trigger event lock on");
784
- }
785
- clearTimeout(triggerLockedTimer);
786
- triggerLockedTimer = setTimeout(function() {
787
- triggerLocked = false;
788
- log("Trigger event lock off");
789
- log("--");
790
- }, eventCancelTimer);
791
- }
792
- function triggerReset(triggerEvent) {
793
- height = getHeight[heightCalcMode]();
794
- width = getWidth[widthCalcMode]();
795
- sendMsg(height, width, triggerEvent);
796
- }
797
- function resetIFrame(triggerEventDesc) {
798
- var hcm = heightCalcMode;
799
- heightCalcMode = heightCalcModeDefault;
800
- log("Reset trigger event: " + triggerEventDesc);
801
- lockTrigger();
802
- triggerReset("reset");
803
- heightCalcMode = hcm;
804
- }
805
- function sendMsg(height, width, triggerEvent, msg, targetOrigin) {
806
- function setTargetOrigin() {
807
- if (undefined === targetOrigin) targetOrigin = targetOriginDefault;
808
- else log("Message targetOrigin: " + targetOrigin);
809
- }
810
- function sendToParent() {
811
- var size = height + ":" + width, message = myID + ":" + size + ":" + triggerEvent + (undefined === msg ? "" : ":" + msg);
812
- log("Sending message to host page (" + message + ")");
813
- target.postMessage(msgID + message, targetOrigin);
814
- }
815
- if (true === sendPermit) {
816
- setTargetOrigin();
817
- sendToParent();
818
- }
819
- }
820
- function receiver(event) {
821
- var processRequestFromParent = {
822
- init: function initFromParent() {
823
- initMsg = event.data;
824
- target = event.source;
825
- init();
826
- firstRun = false;
827
- setTimeout(function() {
828
- initLock = false;
829
- }, eventCancelTimer);
830
- },
831
- reset: function resetFromParent() {
832
- if (initLock) log("Page reset ignored by init");
833
- else {
834
- log("Page size reset by host page");
835
- triggerReset("resetPage");
836
- }
837
- },
838
- resize: function resizeFromParent() {
839
- sendSize("resizeParent", "Parent window requested size check");
840
- },
841
- moveToAnchor: function moveToAnchorF() {
842
- inPageLinks.findTarget(getData());
843
- },
844
- inPageLink: function inPageLinkF() {
845
- this.moveToAnchor();
846
- },
847
- pageInfo: function pageInfoFromParent() {
848
- var msgBody = getData();
849
- log("PageInfoFromParent called from parent: " + msgBody);
850
- onPageInfo(JSON.parse(msgBody));
851
- log(" --");
852
- },
853
- message: function messageFromParent() {
854
- var msgBody = getData();
855
- log("onMessage called from parent: " + msgBody);
856
- // eslint-disable-next-line sonarjs/no-extra-arguments
857
- onMessage(JSON.parse(msgBody));
858
- log(" --");
1361
+ Object.keys(settings).forEach(function(iframeId) {
1362
+ if (isIFrameResizeEnabled(iframeId)) trigger(eventName, event, settings[iframeId].iframe, iframeId);
1363
+ });
1364
+ }
1365
+ function setupEventListeners() {
1366
+ addEventListener(window, "message", iFrameListener);
1367
+ addEventListener(window, "resize", function() {
1368
+ resizeIFrames("resize");
1369
+ });
1370
+ addEventListener(document, "visibilitychange", tabVisible);
1371
+ addEventListener(document, "-webkit-visibilitychange", tabVisible);
1372
+ }
1373
+ function factory() {
1374
+ function init(options, element) {
1375
+ function chkType() {
1376
+ if (!element.tagName) throw new TypeError("Object is not a valid DOM element");
1377
+ else if ("IFRAME" !== element.tagName.toUpperCase()) throw new TypeError("Expected <IFRAME> tag, found <" + element.tagName + ">");
1378
+ }
1379
+ if (element) {
1380
+ chkType();
1381
+ setupIFrame(element, options);
1382
+ iFrames.push(element);
859
1383
  }
860
- };
861
- function isMessageForUs() {
862
- return msgID === ("" + event.data).slice(0, msgIdLen) // ''+ Protects against non-string messages
863
- ;
864
- }
865
- function getMessageType() {
866
- return event.data.split("]")[1].split(":")[0];
867
- }
868
- function getData() {
869
- return event.data.slice(event.data.indexOf(":") + 1);
870
- }
871
- function isMiddleTier() {
872
- return !(0, $b2e1fd3e30ab1f5c$exports) && "iFrameResize" in window || window.jQuery !== undefined && "iFrameResize" in window.jQuery.prototype;
873
- }
874
- function isInitMsg() {
875
- // Test if this message is from a child below us. This is an ugly test, however, updating
876
- // the message format would break backwards compatibility.
877
- return event.data.split(":")[2] in {
878
- true: 1,
879
- false: 1
880
- };
881
- }
882
- function callFromParent() {
883
- var messageType = getMessageType();
884
- if (messageType in processRequestFromParent) processRequestFromParent[messageType]();
885
- else if (!isMiddleTier() && !isInitMsg()) warn("Unexpected message (" + event.data + ")");
886
1384
  }
887
- function processMessage() {
888
- if (false === firstRun) callFromParent();
889
- else if (isInitMsg()) processRequestFromParent.init();
890
- else log('Ignored message of type "' + getMessageType() + '". Received before initialization.');
1385
+ function warnDeprecatedOptions(options) {
1386
+ if (options && options.enablePublicMethods) warn("enablePublicMethods option has been removed, public methods are now always available in the iFrame");
891
1387
  }
892
- if (isMessageForUs()) processMessage();
1388
+ var iFrames;
1389
+ setupRequestAnimationFrame();
1390
+ setupEventListeners();
1391
+ return function iFrameResizeF(options, target) {
1392
+ iFrames = [] // Only return iFrames past in on this call
1393
+ ;
1394
+ warnDeprecatedOptions(options);
1395
+ switch(typeof target){
1396
+ case "undefined":
1397
+ case "string":
1398
+ Array.prototype.forEach.call(document.querySelectorAll(target || "iframe"), init.bind(undefined, options));
1399
+ break;
1400
+ case "object":
1401
+ init(options, target);
1402
+ break;
1403
+ default:
1404
+ throw new TypeError("Unexpected data type (" + typeof target + ")");
1405
+ }
1406
+ return iFrames;
1407
+ };
893
1408
  }
894
- // Normally the parent kicks things off when it detects the iFrame has loaded.
895
- // If this script is async-loaded, then tell parent page to retry init.
896
- function chkLateLoaded() {
897
- if ("loading" !== document.readyState) window.parent.postMessage("[iFrameResizerChild]Ready", "*");
1409
+ function createJQueryPublicMethod($) {
1410
+ if (!$.fn) info("", "Unable to bind to jQuery, it is not fully loaded.");
1411
+ else if (!$.fn.iFrameResize) $.fn.iFrameResize = function $iFrameResizeF(options) {
1412
+ function init(index, element) {
1413
+ setupIFrame(element, options);
1414
+ }
1415
+ return this.filter("iframe").each(init).end();
1416
+ };
898
1417
  }
899
- addEventListener(window, "message", receiver);
900
- addEventListener(window, "readystatechange", chkLateLoaded);
901
- chkLateLoaded();
1418
+ if (window.jQuery) createJQueryPublicMethod(window.jQuery);
1419
+ if (typeof define === "function" && define.amd) define([], factory);
1420
+ else if (typeof module.exports === "object") // Node for browserfy
1421
+ module.exports = factory();
1422
+ window.iFrameResize = window.iFrameResize || factory();
902
1423
  })();
903
1424
 
1425
+ },{}]},["2Ac7p","p4VhZ"], "p4VhZ", "parcelRequirea49c")
904
1426
 
905
-
906
- })();
907
1427
  //# sourceMappingURL=embed.js.map