@player-ui/pubsub-plugin 0.4.0-next.7 → 0.4.0-next.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/handler.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { Player, PlayerPlugin, InProgressState } from '@player-ui/player';
2
+ import { getPubSubPlugin } from './utils';
3
+
4
+ export type PubSubHandler<T extends unknown[]> = (
5
+ context: InProgressState,
6
+ ...args: T
7
+ ) => void;
8
+
9
+ export type SubscriptionMap = Map<string, PubSubHandler<any>>;
10
+
11
+ /**
12
+ * Plugin to easily add subscribers to the PubSubPlugin
13
+ */
14
+ export class PubSubHandlerPlugin implements PlayerPlugin {
15
+ name = 'pubsub-handler';
16
+ private subscriptions: SubscriptionMap;
17
+
18
+ constructor(subscriptions: SubscriptionMap) {
19
+ this.subscriptions = subscriptions;
20
+ }
21
+
22
+ apply(player: Player) {
23
+ const pubsub = getPubSubPlugin(player);
24
+
25
+ player.hooks.onStart.tap(this.name, () => {
26
+ this.subscriptions.forEach((handler, key) => {
27
+ pubsub.subscribe(key, (_, ...args) => {
28
+ const state = player.getState();
29
+
30
+ if (state.status === 'in-progress') {
31
+ return handler(state, ...args);
32
+ }
33
+
34
+ player.logger.info(
35
+ `[PubSubHandlerPlugin] subscriber for ${key} was called when player was not in-progress`
36
+ );
37
+ });
38
+ });
39
+ });
40
+ }
41
+ }
package/src/index.ts CHANGED
@@ -1,2 +1,3 @@
1
- export * from './pubsub';
1
+ export * from './plugin';
2
2
  export * from './symbols';
3
+ export * from './handler';
package/src/plugin.ts ADDED
@@ -0,0 +1,102 @@
1
+ import type {
2
+ Player,
3
+ PlayerPlugin,
4
+ ExpressionContext,
5
+ } from '@player-ui/player';
6
+ import type { SubscribeHandler } from './pubsub';
7
+ import { pubsub } from './pubsub';
8
+ import { PubSubPluginSymbol } from './symbols';
9
+
10
+ export interface PubSubConfig {
11
+ /** A custom expression name to register */
12
+ expressionName: string;
13
+ }
14
+
15
+ /**
16
+ * The PubSubPlugin is a great way to enable your FRF content to publish events back to your app
17
+ * It injects a publish() function into the expression language, and will forward all events back to any subscribers.
18
+ *
19
+ * Published/Subscribed events support a hierarchy:
20
+ * - publish('foo', 'data') -- will trigger any listeners for 'foo'
21
+ * - publish('foo.bar', 'data') -- will trigger any listeners for 'foo' or 'foo.bar'
22
+ *
23
+ */
24
+ export class PubSubPlugin implements PlayerPlugin {
25
+ name = 'pub-sub';
26
+
27
+ static Symbol = PubSubPluginSymbol;
28
+ public readonly symbol = PubSubPlugin.Symbol;
29
+
30
+ private expressionName: string;
31
+
32
+ constructor(config?: PubSubConfig) {
33
+ this.expressionName = config?.expressionName ?? 'publish';
34
+ }
35
+
36
+ apply(player: Player) {
37
+ player.hooks.expressionEvaluator.tap(this.name, (expEvaluator) => {
38
+ const existingExpression = expEvaluator.operators.expressions.get(
39
+ this.expressionName
40
+ );
41
+
42
+ if (existingExpression) {
43
+ player.logger.warn(
44
+ `[PubSubPlugin] expression ${this.expressionName} is already registered.`
45
+ );
46
+ } else {
47
+ expEvaluator.addExpressionFunction(
48
+ this.expressionName,
49
+ (_ctx: ExpressionContext, event: unknown, ...args: unknown[]) => {
50
+ if (typeof event === 'string') {
51
+ this.publish(event, ...args);
52
+ }
53
+ }
54
+ );
55
+ }
56
+ });
57
+
58
+ player.hooks.onEnd.tap(this.name, () => {
59
+ this.clear();
60
+ });
61
+ }
62
+
63
+ /**
64
+ * A way of publishing an event, notifying any listeners
65
+ *
66
+ * @param event - The name of the event to publish. Can take sub-topics like: foo.bar
67
+ * @param data - Any additional data to attach to the event
68
+ */
69
+ publish(event: string, ...args: unknown[]) {
70
+ pubsub.publish(event, ...args);
71
+ }
72
+
73
+ /**
74
+ * Subscribe to an event with the given name. The handler will get called for any published event
75
+ *
76
+ * @param event - The name of the event to subscribe to
77
+ * @param handler - A function to be called when the event is triggered
78
+ * @returns A token to be used to unsubscribe from the event
79
+ */
80
+ subscribe<T extends string, A extends unknown[]>(
81
+ event: T,
82
+ handler: SubscribeHandler<T, A>
83
+ ) {
84
+ return pubsub.subscribe(event, handler);
85
+ }
86
+
87
+ /**
88
+ * Remove any subscriptions using the given token
89
+ *
90
+ * @param token - A token from a `subscribe` call
91
+ */
92
+ unsubscribe(token: string) {
93
+ pubsub.unsubscribe(token);
94
+ }
95
+
96
+ /**
97
+ * Remove all subscriptions
98
+ */
99
+ clear() {
100
+ pubsub.clear();
101
+ }
102
+ }
package/src/pubsub.ts CHANGED
@@ -1,77 +1,173 @@
1
- import pubsub from 'pubsub-js';
2
- import type {
3
- Player,
4
- PlayerPlugin,
5
- ExpressionContext,
6
- } from '@player-ui/player';
7
- import { PubSubPluginSymbol } from './symbols';
8
-
9
- export interface PubSubConfig {
10
- /** A custom expression name to register */
11
- expressionName: string;
12
- }
1
+ /**
2
+ * Based off the pubsub-js library and rewritten to match the same used APIs but modified so that
3
+ * multiple arguments could be passed into the publish and subscription handlers.
4
+ */
5
+
6
+ export type SubscribeHandler<T extends string, A extends unknown[]> = (
7
+ type: T,
8
+ ...args: A
9
+ ) => void;
10
+
11
+ export type PubSubUUID = `uuid_${number}`;
13
12
 
14
13
  /**
15
- * The PubSubPlugin is a great way to enable your Content content to publish events back to your app
16
- * It injects a publish() function into the expression language, and will forward all events back to any subscribers.
17
- *
18
- * Published/Subscribed events support a hierarchy:
19
- * - publish('foo', 'data') -- will trigger any listeners for 'foo'
20
- * - publish('foo.bar', 'data') -- will trigger any listeners for 'foo' or 'foo.bar'
21
- *
14
+ * Split a string into an array of event layers
22
15
  */
23
- export class PubSubPlugin implements PlayerPlugin {
24
- name = 'pub-sub';
16
+ function splitEvent(event: string) {
17
+ return event.split('.').reduce<string[]>((prev, curr, index) => {
18
+ if (index === 0) {
19
+ return [curr];
20
+ }
25
21
 
26
- static Symbol = PubSubPluginSymbol;
27
- public readonly symbol = PubSubPlugin.Symbol;
22
+ return [...prev, `${prev[index - 1]}.${curr}`];
23
+ }, []);
24
+ }
28
25
 
29
- private expressionName: string;
26
+ let count = 1;
30
27
 
31
- constructor(config?: PubSubConfig) {
32
- this.expressionName = config?.expressionName ?? 'publish';
28
+ /**
29
+ * Tiny pubsub maker
30
+ */
31
+ class TinyPubSub {
32
+ private events: Map<string, Map<PubSubUUID, SubscribeHandler<any, any>>>;
33
+ private tokens: Map<PubSubUUID, string>;
34
+
35
+ constructor() {
36
+ this.events = new Map();
37
+ this.tokens = new Map();
33
38
  }
34
39
 
35
- apply(player: Player) {
36
- player.hooks.expressionEvaluator.tap(this.name, (expEvaluator) => {
37
- expEvaluator.addExpressionFunction(
38
- this.expressionName,
39
- (_ctx: ExpressionContext, event: unknown, data: unknown) => {
40
- if (typeof event === 'string') {
41
- this.publish(event, data);
42
- }
43
- }
44
- );
45
- });
40
+ /**
41
+ * Publish an event with any number of additional arguments
42
+ */
43
+ publish(event: string, ...args: unknown[]) {
44
+ if (typeof event !== 'string') {
45
+ return;
46
+ }
47
+
48
+ if (event.includes('.')) {
49
+ const eventKeys = splitEvent(event);
50
+
51
+ eventKeys.forEach((key) => {
52
+ this.deliver(key, event, ...args);
53
+ });
54
+ } else {
55
+ this.deliver(event, event, ...args);
56
+ }
57
+
58
+ this.deliver('*', event, ...args);
46
59
  }
47
60
 
48
61
  /**
49
- * A way of publishing an event, notifying any listeners
62
+ * Subscribe to an event
63
+ *
64
+ * Events are also heirarchical when separated by a period. Given the following:
50
65
  *
51
- * @param event - The name of the event to publish. Can take sub-topics like: foo.bar
52
- * @param data - Any additional data to attach to the event
66
+ * publish('a.b.c', 'one', 'two', 'three)
67
+ *
68
+ * The subscribe event will be called when the event is passed as 'a', 'a.b', or 'a.b.c'.
69
+ *
70
+ * @example
71
+ * // subscribes to the top level 'a' publish
72
+ * subscribe('a', (event, ...args) => console.log(event, ...args))
53
73
  */
54
- publish(event: string, data: unknown) {
55
- pubsub.publishSync(event, data);
74
+ subscribe(event: string, handler: SubscribeHandler<any, any>) {
75
+ const uuid = `uuid_${++count}`;
76
+
77
+ if (typeof event === 'string') {
78
+ if (!this.events.has(event)) {
79
+ this.events.set(event, new Map());
80
+ }
81
+
82
+ const handlers = this.events.get(event);
83
+ handlers!.set(uuid as PubSubUUID, handler);
84
+ this.tokens.set(uuid as PubSubUUID, event);
85
+ }
86
+
87
+ return uuid;
56
88
  }
57
89
 
58
90
  /**
59
- * Subscribe to an event with the given name. The handler will get called for any published event
91
+ * Unsubscribes to a specific subscription given it's symbol or an entire
92
+ * event when passed as a string.
60
93
  *
61
- * @param event - The name of the event to subscribe to
62
- * @param handler - A function to be called when the event is triggered
63
- * @returns A token to be used to unsubscribe from the event
94
+ * When existing subscriptions exist for heirarchical events such as 'a.b.c',
95
+ * when passing an event 'a' to unsubscribe, all subscriptions for 'a', 'a.b',
96
+ * & 'a.b.c' will be unsubscribed as well.
64
97
  */
65
- subscribe(event: string, handler: (e: string, data: unknown) => void) {
66
- return pubsub.subscribe(event, handler);
98
+ unsubscribe(value: string | symbol) {
99
+ if (typeof value === 'string' && value.startsWith('uuid')) {
100
+ const path = this.tokens.get(value as PubSubUUID);
101
+
102
+ if (typeof path === 'undefined') {
103
+ return;
104
+ }
105
+
106
+ const innerPath = this.events.get(path);
107
+ innerPath?.delete(value as PubSubUUID);
108
+ this.tokens.delete(value as PubSubUUID);
109
+ return;
110
+ }
111
+
112
+ if (typeof value === 'string') {
113
+ for (const key of this.events.keys()) {
114
+ if (key.indexOf(value) === 0) {
115
+ const tokens = this.events.get(key);
116
+
117
+ if (tokens && tokens.size) {
118
+ // eslint-disable-next-line max-depth
119
+ for (const token of tokens.keys()) {
120
+ this.tokens.delete(token);
121
+ }
122
+ }
123
+
124
+ this.events.delete(key);
125
+ }
126
+ }
127
+ }
67
128
  }
68
129
 
69
130
  /**
70
- * Remove any subscriptions using the given token
71
- *
72
- * @param token - A token from a `subscribe` call
131
+ * Get the number of subscriptions for a specific event, or when left blank
132
+ * will return the overall number of subscriptions for the entire pubsub.
73
133
  */
74
- unsubscribe(token: string) {
75
- pubsub.unsubscribe(token);
134
+ count(event?: string) {
135
+ let counter = 0;
136
+
137
+ if (typeof event === 'undefined') {
138
+ for (const handlers of this.events.values()) {
139
+ counter += handlers.size;
140
+ }
141
+
142
+ return counter;
143
+ }
144
+
145
+ const handlers = this.events.get(event);
146
+
147
+ if (handlers?.size) {
148
+ return handlers.size;
149
+ }
150
+
151
+ return counter;
152
+ }
153
+
154
+ /**
155
+ * Deletes all existing subscriptions
156
+ */
157
+ clear() {
158
+ this.events.clear();
159
+ this.tokens.clear();
160
+ }
161
+
162
+ private deliver(path: string, event: string, ...args: unknown[]) {
163
+ const handlers = this.events.get(path);
164
+
165
+ if (handlers && handlers.size) {
166
+ for (const handler of handlers.values()) {
167
+ handler(event, ...args);
168
+ }
169
+ }
76
170
  }
77
171
  }
172
+
173
+ export const pubsub = new TinyPubSub();
package/src/utils.ts ADDED
@@ -0,0 +1,17 @@
1
+ import type { Player } from '@player-ui/player';
2
+ import { PubSubPlugin } from './plugin';
3
+ import { PubSubPluginSymbol } from './symbols';
4
+
5
+ /**
6
+ * Returns the existing PubSubPlugin or creates and registers a new plugin
7
+ */
8
+ export function getPubSubPlugin(player: Player) {
9
+ const existing = player.findPlugin<PubSubPlugin>(PubSubPluginSymbol);
10
+ const plugin = existing || new PubSubPlugin();
11
+
12
+ if (!existing) {
13
+ player.registerPlugin(plugin);
14
+ }
15
+
16
+ return plugin;
17
+ }