Skip to content

Commit a940f7d

Browse files
author
Matt Mazzola
committed
Refactor powerbi-client to use updated and hpm, wpmp. Hpm now specifies the window wpmp should send the message to allowing single instance of wpmp to communicate to many different iframe windows.
1 parent c627d4f commit a940f7d

7 files changed

Lines changed: 297 additions & 238 deletions

File tree

‎src/embed.ts‎

Lines changed: 36 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,7 @@
11
import { Utils } from './util';
2+
import * as service from './service';
23
import * as protocol from './protocol';
3-
import * as report from './report';
4-
import * as wpmp from 'window-post-message-proxy';
54
import * as hpm from 'http-post-message';
6-
import * as router from 'powerbi-router';
7-
import * as filters from 'powerbi-filters';
85

96
declare global {
107
interface Document {
@@ -46,19 +43,8 @@ export interface IInternalEmbedConfiguration extends protocol.ILoadConfiguration
4643
}
4744

4845
export interface IEmbedConstructor {
49-
new (hpmFactory: IHpmFactory, wpmpFactory: IWpmpFactory, routerFactory: IRouterFactory, getGlobalAccessToken: IGetGlobalAccessToken, element: HTMLElement, config: IEmbedConfiguration): Embed;
50-
}
51-
52-
export interface IHpmFactory {
53-
(wpmp: wpmp.WindowPostMessageProxy, version?: string, type?: string, origin?: string): hpm.HttpPostMessage;
54-
}
55-
56-
export interface IWpmpFactory {
57-
(window: Window, name?: string, logMessages?: boolean): wpmp.WindowPostMessageProxy;
58-
}
59-
60-
export interface IRouterFactory {
61-
(wpmp: wpmp.WindowPostMessageProxy): router.Router;
46+
new (service: service.PowerBi, hpmFactory: service.IHpmFactory, element: HTMLElement, config: IEmbedConfiguration): Embed;
47+
type: string;
6248
}
6349

6450
export abstract class Embed {
@@ -70,25 +56,27 @@ export abstract class Embed {
7056
private static defaultSettings: protocol.ISettings = {
7157
filterPaneEnabled: true
7258
};
73-
private static defaultDebugOptions: IDebugOptions = {
74-
logMessages: false,
75-
wpmpName: 'SdkReportWpmp'
76-
};
7759

78-
wpmp: wpmp.WindowPostMessageProxy;
60+
eventHandlers: any[];
7961
hpm: hpm.HttpPostMessage;
80-
router: router.Router;
62+
service: service.PowerBi;
8163
element: HTMLElement;
8264
iframe: HTMLIFrameElement;
8365
config: IInternalEmbedConfiguration;
8466

85-
constructor(hpmFactory: IHpmFactory, wpmpFactory: IWpmpFactory, routerFactory: IRouterFactory, getGlobalAccessToken: IGetGlobalAccessToken, element: HTMLElement, config: IEmbedConfiguration) {
67+
/**
68+
* Note: there is circular reference between embeds and service
69+
* The service has list of all embeds on the host page, and each embed has reference to the service that created it.
70+
*/
71+
constructor(service: service.PowerBi, hpmFactory: service.IHpmFactory, element: HTMLElement, config: IEmbedConfiguration) {
72+
this.eventHandlers = [];
73+
this.service = service;
8674
this.element = element;
8775

8876
// TODO: Change when Object.assign is available.
8977
config.settings = Utils.assign({}, Embed.defaultSettings, config.settings);
90-
this.config = Utils.assign({}, Embed.defaultDebugOptions, config);
91-
this.config.accessToken = this.getAccessToken(getGlobalAccessToken);
78+
this.config = Utils.assign({}, config);
79+
this.config.accessToken = this.getAccessToken(service.accessToken);
9280
this.config.embedUrl = this.getEmbedUrl();
9381

9482
// TODO: The findIdFromEmbedUrl method is specific to Reports so it should be in the Report class, but it can't be called until
@@ -111,9 +99,11 @@ export abstract class Embed {
11199
this.iframe = <HTMLIFrameElement>this.element.childNodes[0];
112100
this.iframe.addEventListener('load', () => this.load(this.config), false);
113101

114-
this.wpmp = wpmpFactory(this.iframe.contentWindow, this.config.wpmpName, this.config.logMessages);
115-
this.hpm = hpmFactory(this.wpmp);
116-
this.router = routerFactory(this.wpmp);
102+
this.hpm = hpmFactory(this.iframe.contentWindow, this.service.wpmp);
103+
}
104+
105+
getConfig(): IInternalEmbedConfiguration {
106+
return this.config;
117107
}
118108

119109
/**
@@ -132,12 +122,27 @@ export abstract class Embed {
132122
throw response.body;
133123
});
134124
}
125+
126+
handleEvent(event: service.IEvent<any>): void {
127+
const handler = Utils.find(handler => handler.test(event), this.eventHandlers);
128+
129+
if(handler) {
130+
handler.handle(event.value);
131+
}
132+
}
133+
134+
on<T>(eventName: string, handler: service.IEventHandler<T>): void {
135+
this.eventHandlers.push({
136+
test: (event: service.IEvent<T>) => event.name === eventName,
137+
handle: handler
138+
});
139+
}
135140

136141
/**
137142
* Get access token from first available location: config, attribute, global.
138143
*/
139-
private getAccessToken(getGlobalAccessToken: IGetGlobalAccessToken): string {
140-
const accessToken = this.config.accessToken || this.element.getAttribute(Embed.accessTokenAttribute) || getGlobalAccessToken();
144+
private getAccessToken(globalAccessToken: string): string {
145+
const accessToken = this.config.accessToken || this.element.getAttribute(Embed.accessTokenAttribute) || globalAccessToken;
141146

142147
if (!accessToken) {
143148
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.`);

‎src/factories.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,7 @@
11
/**
22
* TODO: Need to find better place for these factory functions or refactor how we handle dependency injection
3-
* Need to
43
*/
5-
import { IHpmFactory, IWpmpFactory, IRouterFactory } from './embed';
4+
import { IHpmFactory, IWpmpFactory, IRouterFactory } from './service';
65
import * as wpmp from 'window-post-message-proxy';
76
import * as hpm from 'http-post-message';
87
import * as router from 'powerbi-router';
@@ -13,23 +12,27 @@ export {
1312
IRouterFactory
1413
};
1514

16-
export const hpmFactory: IHpmFactory = (wpmp, sdkVersion = '2.0.0', sdkType = 'js', origin = 'sdk') => {
17-
return new hpm.HttpPostMessage(wpmp, {
15+
/**
16+
* TODO: Need to get sdk version and settings from package.json, Generate config file via gulp task?
17+
*/
18+
export const hpmFactory: IHpmFactory = (targetWindow, wpmp, sdkVersion = '2.0.0', sdkType = 'js', origin = 'sdk') => {
19+
return new hpm.HttpPostMessage(targetWindow, wpmp, {
1820
'origin': origin,
1921
'x-sdk-type': sdkType,
2022
'x-sdk-version': sdkVersion
2123
});
2224
};
2325

24-
export const wpmpFactory: IWpmpFactory = (window, name?: string, logMessages?: boolean) => {
25-
return new wpmp.WindowPostMessageProxy(window, {
26+
export const wpmpFactory: IWpmpFactory = (name?: string, logMessages?: boolean, eventSourceOverrideWindow?: Window) => {
27+
return new wpmp.WindowPostMessageProxy({
2628
processTrackingProperties: {
2729
addTrackingProperties: hpm.HttpPostMessage.addTrackingProperties,
2830
getTrackingProperties: hpm.HttpPostMessage.getTrackingProperties,
2931
},
3032
isErrorMessage: hpm.HttpPostMessage.isErrorMessage,
3133
name,
32-
logMessages
34+
logMessages,
35+
eventSourceOverrideWindow
3336
});
3437
};
3538

‎src/report.ts‎

Lines changed: 4 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,10 @@
1+
import * as service from './service';
12
import * as protocol from './protocol';
23
import * as embed from './embed';
34
import * as wpmp from 'window-post-message-proxy';
45
import * as hpm from 'http-post-message';
56
import * as filters from 'powerbi-filters';
67

7-
export interface IEvent<T> {
8-
data: T
9-
}
10-
11-
export interface IEventHandler<T> {
12-
(event: IEvent<T>): any;
13-
}
14-
158
export class Report extends embed.Embed {
169
static allowedEvents = ["dataSelected", "filterAdded", "filterUpdated", "filterRemoved", "pageChanged", "error"];
1710
static type = "Report";
@@ -89,15 +82,13 @@ export class Report extends embed.Embed {
8982
});
9083
}
9184

92-
on<T>(eventName: string, handler: IEventHandler<T>): void {
85+
on<T>(eventName: string, handler: service.IEventHandler<T>): void {
9386
if(Report.allowedEvents.indexOf(eventName) === -1) {
9487
throw new Error(`eventName is must be one of ${Report.allowedEvents}. You passed: ${eventName}`);
9588
}
9689

97-
this.router.post(`/report/events/${eventName}`, (res, req) => {
98-
handler(res.body);
99-
});
100-
}
90+
super.on<T>(eventName, handler);
91+
}
10192

10293
/**
10394
* Set the active page

‎src/service.ts‎

Lines changed: 91 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,31 @@ import { Tile } from './tile';
55
import { Utils } from './util';
66
import * as wpmp from 'window-post-message-proxy';
77
import * as hpm from 'http-post-message';
8+
import * as router from 'powerbi-router';
9+
import * as filters from 'powerbi-filters';
10+
11+
export interface IEvent<T> {
12+
type: string;
13+
id: string;
14+
name: string;
15+
value: T;
16+
}
17+
18+
export interface IEventHandler<T> {
19+
(event: IEvent<T>): any;
20+
}
21+
22+
export interface IHpmFactory {
23+
(targetWindow: Window, wpmp: wpmp.WindowPostMessageProxy, version?: string, type?: string, origin?: string): hpm.HttpPostMessage;
24+
}
25+
26+
export interface IWpmpFactory {
27+
(name?: string, logMessages?: boolean, eventSourceOverrideWindow?: Window): wpmp.WindowPostMessageProxy;
28+
}
29+
30+
export interface IRouterFactory {
31+
(wpmp: wpmp.WindowPostMessageProxy): router.Router;
32+
}
833

934
export interface IPowerBiElement extends HTMLElement {
1035
powerBiEmbed: embed.Embed;
@@ -13,6 +38,8 @@ export interface IPowerBiElement extends HTMLElement {
1338
export interface IPowerBiConfiguration {
1439
autoEmbedOnContentLoaded?: boolean;
1540
onError?: (error: any) => any;
41+
logMessages?: boolean;
42+
wpmpName?: string;
1643
}
1744

1845
export class PowerBi {
@@ -57,25 +84,38 @@ export class PowerBi {
5784

5885
/** List of components (Reports/Tiles) that have been embedded using this service instance. */
5986
private embeds: embed.Embed[];
60-
61-
private hpmFactory: embed.IHpmFactory;
62-
private wpmpFactory: embed.IWpmpFactory;
63-
private routerFactory: embed.IRouterFactory;
87+
private hpmFactory: IHpmFactory;
88+
public wpmp: wpmp.WindowPostMessageProxy;
89+
private router: router.Router;
6490

65-
constructor(hpmFactory: embed.IHpmFactory, wpmpFactory: embed.IWpmpFactory, routerFactory: embed.IRouterFactory, config: IPowerBiConfiguration = {}) {
91+
constructor(hpmFactory: IHpmFactory, wpmpFactory: IWpmpFactory, routerFactory: IRouterFactory, config: IPowerBiConfiguration = {}) {
6692
this.hpmFactory = hpmFactory;
67-
this.wpmpFactory = wpmpFactory;
68-
this.routerFactory = routerFactory;
93+
this.wpmp = wpmpFactory(config.wpmpName, config.logMessages);
94+
this.router = routerFactory(this.wpmp);
95+
96+
/**
97+
* Add handler for report events
98+
*/
99+
this.router.post(`/reports/:reportId/events/:eventName`, (req, res) => {
100+
const event: IEvent<any> = {
101+
type: 'report',
102+
id: req.params.reportId,
103+
name: req.params.eventName,
104+
value: req.body
105+
};
106+
107+
this.handleEvent(event);
108+
});
69109

70110
this.embeds = [];
71-
window.addEventListener('message', this.onReceiveMessage.bind(this), false);
72111

73112
// TODO: Change when Object.assign is available.
74113
this.config = Utils.assign({}, PowerBi.defaultConfig, config);
75114

76115
if (this.config.autoEmbedOnContentLoaded) {
77116
this.enableAutoEmbed();
78117
}
118+
79119
}
80120

81121
/**
@@ -127,7 +167,7 @@ export class PowerBi {
127167
throw new Error(`Attempted to embed component of type: ${componentType} but did not find any matching component. Please verify the type you specified is intended.`);
128168
}
129169

130-
const component = new Component(this.hpmFactory, this.wpmpFactory, this.routerFactory, () => this.accessToken, element, config);
170+
const component = new Component(this, this.hpmFactory, element, config);
131171
element.powerBiEmbed = component;
132172
this.embeds.push(component);
133173

@@ -166,7 +206,7 @@ export class PowerBi {
166206

167207
return powerBiElement.powerBiEmbed;
168208
}
169-
209+
170210
/**
171211
* Given an html element which has component embedded within it, remove the component from list of embeds, remove association with component, and remove the iframe.
172212
*/
@@ -187,6 +227,47 @@ export class PowerBi {
187227
iframe.remove();
188228
}
189229
}
230+
231+
handleEvent(event: IEvent<any>): void {
232+
const embed = Utils.find(embed => {
233+
const config = embed.getConfig();
234+
return (config.type === event.type
235+
&& config.id === event.id);
236+
}, this.embeds);
237+
238+
if(embed) {
239+
embed.handleEvent(event);
240+
}
241+
}
242+
243+
/**
244+
* Translate target into url
245+
* Target may be to the whole report, speific page, or specific visual
246+
*/
247+
private getTargetUrl(target?: protocol.IPageTarget | protocol.IVisualTarget): string {
248+
let targetUrl;
249+
250+
/**
251+
* TODO: I mentioned this issue in the protocol test, but we're tranlating targets from objects
252+
* into parts of the url, and then back to objects. It is a trade off between complixity in this code vs semantic URIs
253+
*
254+
* We could come up with a different idea which passed the target as part of the body
255+
*/
256+
if(!target) {
257+
targetUrl = '/report';
258+
}
259+
else if(target.type === "page") {
260+
targetUrl = `/report/pages/${(<protocol.IPageTarget>target).name}`;
261+
}
262+
else if(target.type === "visual") {
263+
targetUrl = `/report/visuals/${(<protocol.IVisualTarget>target).id}`;
264+
}
265+
else {
266+
throw new Error(`target.type must be either 'page' or 'visual'. You passed: ${target.type}`);
267+
}
268+
269+
return targetUrl;
270+
}
190271

191272
/**
192273
* Handler for window message event.

‎src/util.ts‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ export class Utils {
2626
}
2727
}
2828

29-
static findIndex<T>(predicate: (T) => boolean, xs: T[]): number {
29+
static findIndex<T>(predicate: (x: T) => boolean, xs: T[]): number {
3030
if(!Array.isArray(xs)) {
3131
throw new Error(`You attempted to call find with second parameter that was not an array. You passed: ${xs}`);
3232
}
@@ -42,12 +42,12 @@ export class Utils {
4242
return index;
4343
}
4444

45-
static find<T>(predicate: (T) => boolean, xs: T[]): T {
45+
static find<T>(predicate: (x: T) => boolean, xs: T[]): T {
4646
const index = Utils.findIndex(predicate, xs);
4747
return xs[index];
4848
}
4949

50-
static remove<T>(predicate: (T) => boolean, xs: T[]): void {
50+
static remove<T>(predicate: (x: T) => boolean, xs: T[]): void {
5151
const index = Utils.findIndex(predicate, xs);
5252
xs.splice(index, 1);
5353
}

0 commit comments

Comments
 (0)