forked from microsoft/PowerBI-JavaScript
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathembed.ts
More file actions
332 lines (292 loc) · 10.2 KB
/
embed.ts
File metadata and controls
332 lines (292 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
import * as utils from './util';
import * as service from './service';
import * as models from 'powerbi-models';
import * as hpm from 'http-post-message';
declare global {
interface Document {
// Mozilla Fullscreen
mozCancelFullScreen: Function;
// Ms Fullscreen
msExitFullscreen: Function;
}
interface HTMLIFrameElement {
// Mozilla Fullscreen
mozRequestFullScreen: Function;
// Ms Fullscreen
msRequestFullscreen: Function;
}
}
// TODO: Re-use ILoadConfiguration interface to prevent duplicating properties.
// Current issue is that they are optional when embedding since they can be specificed as attributes but they are required when loading.
/**
* Configuration settings for Power BI embed components
*
* @export
* @interface IEmbedConfiguration
*/
export interface IEmbedConfiguration {
type?: string;
id?: string;
uniqueId?: string;
embedUrl?: string;
accessToken?: string;
settings?: models.ISettings;
pageName?: string;
filters?: (models.IBasicFilter | models.IAdvancedFilter)[];
}
export interface IInternalEmbedConfiguration extends models.ILoadConfiguration {
uniqueId: string;
type: string;
embedUrl: string;
}
export interface IInternalEventHandler<T> {
test(event: service.IEvent<T>): boolean;
handle(event: service.ICustomEvent<T>): void;
}
/**
* Base class for all Power BI embed components
*
* @export
* @abstract
* @class Embed
*/
export abstract class Embed {
static allowedEvents = ["loaded"];
static accessTokenAttribute = 'powerbi-access-token';
static embedUrlAttribute = 'powerbi-embed-url';
static nameAttribute = 'powerbi-name';
static typeAttribute = 'powerbi-type';
static type: string;
private static defaultSettings: models.ISettings = {
filterPaneEnabled: true
};
allowedEvents = [];
/**
* Gets or set the event handler registered for this embed component
*
* @type {IInternalEventHandler<any>[]}
*/
eventHandlers: IInternalEventHandler<any>[];
/**
* Gets or sets the Power BI embed service
*
* @type {service.Service}
*/
service: service.Service;
/**
* Gets or sets the HTML element containing the Power BI embed component
*
* @type {HTMLElement}
*/
element: HTMLElement;
/**
* Gets or sets the HTML iframe element that renders the Power BI embed component
*
* @type {HTMLIFrameElement}
*/
iframe: HTMLIFrameElement;
/**
* Gets or sets the configuration settings for the embed component
*
* @type {IInternalEmbedConfiguration}
*/
config: IInternalEmbedConfiguration;
/**
* Creates an instance of Embed.
*
* Note: there is circular reference between embeds and service
* The service has list of all embeds on the host page, and each embed has reference to the service that created it.
*
* @param {service.Service} service
* @param {HTMLElement} element
* @param {IEmbedConfiguration} config
*/
constructor(service: service.Service, element: HTMLElement, config: IEmbedConfiguration) {
Array.prototype.push.apply(this.allowedEvents, Embed.allowedEvents);
this.eventHandlers = [];
this.service = service;
this.element = element;
// TODO: Change when Object.assign is available.
const settings = utils.assign({}, Embed.defaultSettings, config.settings);
this.config = utils.assign({ settings }, config);
this.config.accessToken = this.getAccessToken(service.accessToken);
this.config.embedUrl = this.getEmbedUrl();
this.config.id = this.getId();
this.config.uniqueId = this.getUniqueId();
const iframeHtml = `<iframe style="width:100%;height:100%;" src="${this.config.embedUrl}" scrolling="no" allowfullscreen="true"></iframe>`;
this.element.innerHTML = iframeHtml;
this.iframe = <HTMLIFrameElement>this.element.childNodes[0];
this.iframe.addEventListener('load', () => this.load(this.config), false);
}
/**
* Sends load configuration data.
*
* ```javascript
* report.load({
* type: 'report',
* id: '5dac7a4a-4452-46b3-99f6-a25915e0fe55',
* accessToken: 'eyJ0eXA ... TaE2rTSbmg',
* settings: {
* navContentPaneEnabled: false
* },
* pageName: "DefaultPage",
* filters: [
* {
* ... DefaultReportFilter ...
* }
* ]
* })
* .catch(error => { ... });
* ```
*
* @param {models.ILoadConfiguration} config
* @returns {Promise<void>}
*/
load(config: models.ILoadConfiguration): Promise<void> {
const errors = models.validateLoad(config);
if(errors) {
throw errors;
}
return this.service.hpm.post<void>('/report/load', config, { uid: this.config.uniqueId }, this.iframe.contentWindow)
.then(response => {
return response.body;
},
response => {
throw response.body;
});
}
/**
* Removes event handler(s) from list of handlers.
*
* If reference to existing handle function is specified remove specific handler.
* If handler is not specified, remove all handlers for the event name specified.
*
* ```javascript
* report.off('pageChanged')
*
* or
*
* const logHandler = function (event) {
* console.log(event);
* };
*
* report.off('pageChanged', logHandler);
* ```
*
* @template T
* @param {string} eventName
* @param {service.IEventHandler<T>} [handler]
*/
off<T>(eventName: string, handler?: service.IEventHandler<T>): void {
const fakeEvent: service.IEvent<any> = { name: eventName, type: null, id: null, value: null };
if(handler) {
utils.remove(eventHandler => eventHandler.test(fakeEvent) && (eventHandler.handle === handler), this.eventHandlers);
this.element.removeEventListener(eventName, <any>handler);
}
else {
const eventHandlersToRemove = this.eventHandlers
.filter(eventHandler => eventHandler.test(fakeEvent));
eventHandlersToRemove
.forEach(eventHandlerToRemove => {
utils.remove(eventHandler => eventHandler === eventHandlerToRemove, this.eventHandlers);
this.element.removeEventListener(eventName, <any>eventHandlerToRemove.handle);
});
}
}
/**
* Adds event handler for specific event.
*
* ```javascript
* report.on('pageChanged', (event) => {
* console.log('PageChanged: ', event.page.name);
* });
* ```
*
* @template T
* @param {string} eventName
* @param {service.IEventHandler<T>} handler
*/
on<T>(eventName: string, handler: service.IEventHandler<T>): void {
if(this.allowedEvents.indexOf(eventName) === -1) {
throw new Error(`eventName is must be one of ${this.allowedEvents}. You passed: ${eventName}`);
}
this.eventHandlers.push({
test: (event: service.IEvent<T>) => event.name === eventName,
handle: handler
});
this.element.addEventListener(eventName, <any>handler)
}
/**
* Get access token from first available location: config, attribute, global.
*
* @private
* @param {string} globalAccessToken
* @returns {string}
*/
private getAccessToken(globalAccessToken: string): string {
const accessToken = this.config.accessToken || this.element.getAttribute(Embed.accessTokenAttribute) || globalAccessToken;
if (!accessToken) {
throw new Error(`No access token was found for element. You must specify an access token directly on the element using attribute '${Embed.accessTokenAttribute}' or specify a global token at: powerbi.accessToken.`);
}
return accessToken;
}
/**
* Get embed url from first available location: options, attribute.
*
* @private
* @returns {string}
*/
private getEmbedUrl(): string {
const embedUrl = this.config.embedUrl || this.element.getAttribute(Embed.embedUrlAttribute);
if (typeof embedUrl !== 'string' || embedUrl.length === 0) {
throw new Error(`Embed Url is required, but it was not found. You must provide an embed url either as part of embed configuration or as attribute '${Embed.embedUrlAttribute}'.`);
}
return embedUrl;
}
/**
* Get unique id from first available location: options, attribute.
* If neither is provided generate unique string.
*
* @private
* @returns {string}
*/
private getUniqueId(): string {
return this.config.uniqueId || this.element.getAttribute(Embed.nameAttribute) || utils.createRandomString();
}
/**
* Get report id from first available location: options, attribute.
*
* @abstract
* @returns {string}
*/
abstract getId(): string;
/**
* Request the browser to make the component's iframe fullscreen.
*/
fullscreen(): void {
const requestFullScreen = this.iframe.requestFullscreen || this.iframe.msRequestFullscreen || this.iframe.mozRequestFullScreen || this.iframe.webkitRequestFullscreen;
requestFullScreen.call(this.iframe);
}
/**
* Exit fullscreen.
*/
exitFullscreen(): void {
if (!this.isFullscreen(this.iframe)) {
return;
}
const exitFullscreen = document.exitFullscreen || document.mozCancelFullScreen || document.webkitExitFullscreen || document.msExitFullscreen;
exitFullscreen.call(document);
}
/**
* Return true if iframe is fullscreen,
* otherwise return false
*
* @private
* @param {HTMLIFrameElement} iframe
* @returns {boolean}
*/
private isFullscreen(iframe: HTMLIFrameElement): boolean {
const options = ['fullscreenElement', 'webkitFullscreenElement', 'mozFullscreenScreenElement', 'msFullscreenElement'];
return options.some(option => document[option] === iframe);
}
}