diff --git a/.eslintignore b/.eslintignore index f06235c4..a8c16873 100644 --- a/.eslintignore +++ b/.eslintignore @@ -1,2 +1,4 @@ node_modules dist +samples/*/dist +samples/*/dist-tsc diff --git a/README.md b/README.md index 331c0706..bbb4515c 100644 --- a/README.md +++ b/README.md @@ -8,6 +8,8 @@ by the BigBlueButton HTML5 client to extend its functionalities. An overview of the plugin architecture and capabilities can be found [here](https://github.com/bigbluebutton/plugins/blob/main/README.md#capabilities-and-technical-details). +For comprehensive documentation including architecture details, please refer to the [official BigBlueButton plugins documentation](https://docs.bigbluebutton.org/plugins/). + ## Examples A variety of example implementations to manipulate different parts of the BBB client can be found in the [`samples`](samples) folder. @@ -114,21 +116,23 @@ In this case, the your manifest URL will be `https:///plugins/sampleM ### Manifest Json -Here is as complete `manifest.json` example with all possible configurations: +Here is a complete `manifest.json` example with all possible configurations: ```json { "requiredSdkVersion": "~0.0.59", "name": "MyPlugin", + "version": "1.0.0", "javascriptEntrypointUrl": "MyPlugin.js", - "localesBaseUrl": "https://cdn.domain.com/my-plugin/", // Optional + "javascriptEntrypointIntegrity": "sha384-Bwsz2rxm...", + "localesBaseUrl": "https://cdn.domain.com/my-plugin/", "dataChannels": [ { "name": "public-channel", "pushPermission": ["moderator", "presenter"], // "moderator","presenter", "all" "replaceOrDeletePermission": ["moderator", "creator"] // "moderator", "presenter","all", "creator" } - ], // One can enable more data-channels to better organize client communication + ], "eventPersistence": { "isEnabled": true // By default it is not enabled }, @@ -140,6 +144,9 @@ Here is as complete `manifest.json` example with all possible configurations: "permissions": ["moderator", "viewer"] } ], + "serverCommandsPermission": { + "chat.sendCustomPublicChatMessage": ["presenter", "moderator"] + }, "settingsSchema": [ { "name": "myJson", @@ -154,6 +161,39 @@ Here is as complete `manifest.json` example with all possible configurations: } ``` +**Manifest field descriptions:** + +| Field | Required | Description | +|-------|----------|-------------| +| `requiredSdkVersion` | Yes | Specifies the SDK version compatibility (e.g., `~0.0.59`) | +| `name` | Yes | Plugin name as referenced in configuration | +| `version` | No | Plugin version for cache-busting (appends `?version=X` to JS URL) | +| `javascriptEntrypointUrl` | Yes | URL to the main JavaScript bundle | +| `javascriptEntrypointIntegrity` | No | Subresource Integrity (SRI) hash for security | +| `localesBaseUrl` | No | Base URL for internationalization locale files | +| `dataChannels` | No | Array of data channels for inter-client communication | +| `eventPersistence` | No | Configuration for persisting events to meeting recording | +| `remoteDataSources` | No | External API endpoints for fetching data | +| `serverCommandsPermission` | No | Role-based permissions for server commands | +| `settingsSchema` | No | Configuration schema for plugin settings | + +**Possible values for permissions:** +- `pushPermission`: `"moderator"`, `"presenter"`, `"all"`, `"viewer"` +- `replaceOrDeletePermission`: `"moderator"`, `"presenter"`, `"all"`, `"viewer"`, `"creator"` +- `serverCommandsPermission`: `"moderator"`, `"presenter"`, `"all"`, `"viewer"` +- `remoteDataSources.permissions`: `"moderator"`, `"viewer"`, `"presenter"` + +**Possible values for fetchMode:** +- `"onMeetingCreate"`: Fetch once when meeting is created and cache the result +- `"onDemand"`: Fetch every time the plugin requests the data + +**Possible values for settingsSchema.type:** +- `"int"`: Integer number +- `"float"`: Floating-point number +- `"string"`: Text string +- `"boolean"`: True/false value +- `"json"`: JSON object + To better understand remote-data-sources, please, refer to [this section](#external-data-resources) **settingsSchema:** @@ -229,12 +269,229 @@ That being said, here are the extensible areas we have so far: Mind that no plugin will interfere into another's extensible area. So feel free to set whatever you need into a certain plugin with no worries. -### Auxiliary functions: +**Example usage for different extensible areas:** + +```typescript +BbbPluginSdk.initialize(pluginUuid); +const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + +useEffect(() => { + // 1. Action Bar Items (bottom toolbar) + pluginApi.setActionsBarItems([ + new ActionsBarButton({ + icon: { iconName: 'user' }, + tooltip: 'My custom action', + onClick: () => pluginLogger.info('Action bar button clicked'), + position: ActionsBarPosition.RIGHT, + }), + new ActionsBarSeparator({ + position: ActionsBarPosition.RIGHT, + }), + ]); + + // 2. Action Button Dropdown Items (three dots menu in action bar) + pluginApi.setActionButtonDropdownItems([ + new ActionButtonDropdownSeparator(), + new ActionButtonDropdownOption({ + label: 'Custom dropdown option', + icon: 'copy', + tooltip: 'This is a custom option', + onClick: () => pluginLogger.info('Dropdown option clicked'), + }), + ]); + + // 3. Options Dropdown Items (three dots menu in top-right) + pluginApi.setOptionsDropdownItems([ + new OptionsDropdownSeparator(), + new OptionsDropdownOption({ + label: 'Plugin Settings', + icon: 'settings', + onClick: () => pluginLogger.info('Options clicked'), + }), + ]); + + // 4. Nav Bar Items (top navigation bar) + pluginApi.setNavBarItems([ + new NavBarButton({ + icon: 'user', + label: 'Custom Nav Button', + tooltip: 'Navigate to custom area', + position: NavBarItemPosition.RIGHT, + onClick: () => pluginLogger.info('Nav button clicked'), + hasSeparator: true, + }), + new NavBarInfo({ + label: 'Plugin Active', + position: NavBarItemPosition.CENTER, + hasSeparator: false, + }), + ]); + + // 5. Presentation Toolbar Items (presentation controls) + pluginApi.setPresentationToolbarItems([ + new PresentationToolbarButton({ + label: 'Custom Tool', + tooltip: 'Use custom presentation tool', + onClick: () => pluginLogger.info('Presentation tool clicked'), + }), + new PresentationToolbarSeparator(), + ]); + + // 6. User List Dropdown Items (per-user menu) + pluginApi.setUserListDropdownItems([ + new UserListDropdownSeparator(), + new UserListDropdownOption({ + label: 'View Profile', + icon: 'user', + onClick: (userId) => { + pluginLogger.info('View profile for user:', userId); + }, + }), + ]); + + // 7. Audio Settings Dropdown Items + pluginApi.setAudioSettingsDropdownItems([ + new AudioSettingsDropdownOption({ + label: 'Audio Plugin Settings', + icon: 'settings', + onClick: () => pluginLogger.info('Audio settings clicked'), + }), + ]); + + // 8. Camera Settings Dropdown Items + pluginApi.setCameraSettingsDropdownItems([ + new CameraSettingsDropdownOption({ + label: 'Camera Plugin Settings', + icon: 'video', + onClick: () => pluginLogger.info('Camera settings clicked'), + }), + ]); + + // 9. Floating Window + pluginApi.setFloatingWindows([ + new FloatingWindow({ + top: 100, + left: 100, + width: 400, + height: 300, + movable: true, + resizable: true, + backgroundColor: '#ffffff', + boxShadow: '0 4px 12px rgba(0,0,0,0.15)', + contentFunction: (element: HTMLElement) => { + const root = ReactDOM.createRoot(element); + root.render( +
+

Custom Floating Window

+

This is custom plugin content!

+
+ ); + return root; + }, + }), + ]); + + // 10. Generic Content Sidekick Area + pluginApi.setGenericContentItems([ + new GenericContentSidekickArea({ + id: 'my-plugin-content', + name: 'Plugin Content', + section: 'Custom Section', + buttonIcon: 'copy', + open: false, + contentFunction: (element: HTMLElement) => { + const root = ReactDOM.createRoot(element); + root.render( +
+

Sidekick Content

+

Custom sidekick panel content here!

+
+ ); + return root; + }, + }), + ]); + + // 11. User List Item Additional Information + pluginApi.setUserListItemAdditionalInformation([ + new UserListItemAdditionalInformation({ + userId: 'specific-user-id', // or use a function to determine dynamically + label: 'VIP', + icon: 'star', + }), + ]); + + // 12. Presentation Dropdown Items + pluginApi.setPresentationDropdownItems([ + new PresentationDropdownOption({ + label: 'Export Presentation', + icon: 'download', + onClick: () => pluginLogger.info('Export presentation clicked'), + }), + ]); + + // 13. User Camera Dropdown Items + pluginApi.setUserCameraDropdownItems([ + new UserCameraDropdownOption({ + label: 'Camera Effects', + icon: 'video', + displayFunction: ({ userId }) => { + // Show only for specific users or conditions + return true; + }, + onClick: ({ userId, streamId }) => { + pluginLogger.info('Camera option clicked:', userId, streamId); + }, + }), + ]); + +}, []); + +``` + +**Key Points:** +- Each extensible area has its own setter function (e.g., `setActionsBarItems`, `setOptionsDropdownItems`) +- Items are set as arrays, allowing multiple items per area +- Use separators to visually group related items +- Items from different plugins won't conflict - each plugin manages its own items +- Most items support icons, labels, tooltips, and onClick handlers +- Some items support positioning (LEFT, CENTER, RIGHT) or display conditions + +### Auxiliary functions - `getSessionToken`: returns the user session token located on the user's URL. - `getJoinUrl`: returns the join url associated with the parameters passed as an argument. Since it fetches the BigBlueButton API, this getter method is asynchronous. - `useLocaleMessages`: returns the messages to be used in internationalization functions (recommend to use `react-intl`, as example, refer to official plugins) +**Example usage:** + +```typescript +BbbPluginSdk.initialize(pluginUuid); +const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + +// Get session token +const sessionToken = pluginApi.getSessionToken(); +console.log('Session token:', sessionToken); + +// Get join URL (async) +useEffect(() => { + pluginApi.getJoinUrl({ + fullName: 'John Doe', + role: 'MODERATOR', + // other join parameters... + }).then((joinUrl) => { + console.log('Join URL:', joinUrl); + }); +}, []); + +// Use locale messages for internationalization +const localeMessages = pluginApi.useLocaleMessages(); +console.log('Current locale:', localeMessages); + +return null; + +``` + ### Realtime data consumption - `useCurrentPresentation` hook: provides information regarding the current presentation; @@ -259,6 +516,87 @@ export interface GraphqlResponseWrapper { So we have the `data`, which is different for each hook, that's why it's a generic, the error, that will be set if, and only if, there is an error, otherwise it is undefined, and loading, which tells the developer if the query is still loading (being fetched) or not. +**Example usage:** + +```typescript + BbbPluginSdk.initialize(pluginUuid); + const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + + // Get current user information + const { data: currentUser, loading: userLoading, error: userError } = + pluginApi.useCurrentUser(); + + // Get meeting information + const { data: meeting, loading: meetingLoading } = pluginApi.useMeeting(); + + // Get current presentation + const { data: presentation } = pluginApi.useCurrentPresentation(); + + // Get all users basic info + const { data: usersBasicInfo } = pluginApi.useUsersBasicInfo(); + + // Get loaded chat messages + const { data: chatMessages } = pluginApi.useLoadedChatMessages(); + + // Get talking indicators + const { data: talkingIndicators } = pluginApi.useTalkingIndicator(); + + // Get plugin settings + const { data: pluginSettings } = pluginApi.usePluginSettings(); + + useEffect(() => { + if (currentUser && !userLoading) { + pluginLogger.info('Current user:', currentUser); + pluginLogger.info('User is presenter:', currentUser.presenter); + pluginLogger.info('User is moderator:', currentUser.isModerator); + } + if (userError) { + pluginLogger.error('Error fetching user:', userError); + } + }, [currentUser, userLoading, userError]); + + useEffect(() => { + if (meeting) { + pluginLogger.info('Meeting ID:', meeting.meetingId); + pluginLogger.info('Meeting name:', meeting.name); + } + }, [meeting]); + + useEffect(() => { + if (presentation) { + pluginLogger.info('Current page:', presentation.currentPage?.num); + pluginLogger.info('Total pages:', presentation.totalPages); + } + }, [presentation]); + + useEffect(() => { + if (chatMessages) { + pluginLogger.info('Total messages:', chatMessages.length); + chatMessages.forEach((msg) => { + pluginLogger.info(`Message from ${msg.senderName}: ${msg.message}`); + }); + } + }, [chatMessages]); + + // Custom subscription example + const { data: customData } = pluginApi.useCustomSubscription(` + subscription MyCustomSubscription { + user { + userId + name + role + } + } + `); + + useEffect(() => { + if (customData) { + pluginLogger.info('Custom subscription data:', customData); + } + }, [customData]); + +``` + ### Realtime Data Creation **`useCustomMutation` Hook** @@ -346,8 +684,8 @@ The data-channel name must be in the `manifest.json` along with all the permissi "dataChannels": [ { "name": "channel-name", - "pushPermission": ["moderator", "presenter"], - "replaceOrDeletePermission": ["moderator", "sender"] + "pushPermission": ["moderator","presenter"], + "replaceOrDeletePermission": ["moderator", "creator"] } ] } @@ -446,19 +784,71 @@ One other thing is that the type of the return is precisely the same type requir - captions: - setDisplayAudioCaptions: This function will set the track of transcripted audio to be displayed or disable it; -See usage ahead: +**Example usage:** + +```typescript + BbbPluginSdk.initialize(pluginUuid); + const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + + useEffect(() => { + // Open and fill chat form + pluginApi.uiCommands.chat.form.open(); + pluginApi.uiCommands.chat.form.fill({ + text: 'Just an example message filled by the plugin', + }); + + // Set speaker volume to 50% + pluginApi.uiCommands.conference.setSpeakerLevel(0.5); + + // Set external video volume to 75% + pluginApi.uiCommands.externalVideo.volume.set(0.75); + + // Change layout + pluginApi.uiCommands.layout.setEnforcedLayout('FOCUS'); + + // Show/hide nav bar + pluginApi.uiCommands.navBar.setDisplayNavBar(false); + + // Send a notification + pluginApi.uiCommands.notification.send({ + type: 'info', + message: 'This is a notification from the plugin', + icon: 'user', + }); + + // Open presentation area + pluginApi.uiCommands.presentationArea.open(); + + // Sidekick area commands + pluginApi.uiCommands.sidekickArea.options.setMenuBadge('my-content-id', '5'); + pluginApi.uiCommands.sidekickArea.options.renameGenericContentMenu( + 'my-content-id', + 'New Menu Name' + ); + pluginApi.uiCommands.sidekickArea.options.renameGenericContentSection( + 'my-content-id', + 'New Section Name' + ); + + // Camera commands + pluginApi.uiCommands.camera.setSelfViewDisableAllDevices(true); + pluginApi.uiCommands.camera.setSelfViewDisable('camera-stream-id', false); + + // Set away status + pluginApi.uiCommands.userStatus.setAwayStatus(true); + }, []); -```ts -pluginApi.uiCommands.chat.form.open(); -pluginApi.uiCommands.chat.form.fill({ - text: 'Just an example message filled by the plugin', -}); ``` So the idea is that we have a `uiCommands` object and at a point, there will be the command to do the intended action, such as open the chat form and/or fill it, as demonstrated above ### Server Commands + `serverCommands` object: It contains all the possible commands available to the developer to interact with the BBB core server, see the ones implemented down below: + + - chat: + - sendPublicChatMessage: This function sends a message to the public chat on behalf of the currently logged-in user. + `serverCommands` object: It contains all the possible commands available to the developer to interact with the BBB core server, see the ones implemented down below: - chat: @@ -472,30 +862,335 @@ So the idea is that we have a `uiCommands` object and at a point, there will be - save: this function saves the given text, locale and caption type - addLocale: this function sends a locale to be added to the available options +**Example usage:** + +```typescript + BbbPluginSdk.initialize(pluginUuid); + const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + + useEffect(() => { + // Add a button that sends a chat message + pluginApi.setActionButtonDropdownItems([ + new ActionButtonDropdownOption({ + label: 'Send chat message', + icon: 'chat', + onClick: () => { + // Send a public chat message + pluginApi.serverCommands.chat.sendPublicChatMessage({ + textMessageInMarkdownFormat: 'Hello from plugin!', + pluginCustomMetadata: pluginUuid, + }); + }, + }), + new ActionButtonDropdownOption({ + label: 'Send custom message', + icon: 'copy', + onClick: () => { + // Send a custom public chat message with metadata + pluginApi.serverCommands.chat.sendCustomPublicMessage({ + textMessageInMarkdownFormat: '**Custom message** with metadata', + pluginCustomMetadata: { + type: 'notification', + pluginId: pluginUuid, + timestamp: Date.now(), + }, + }); + }, + }), + new ActionButtonDropdownOption({ + label: 'Save caption', + icon: 'closed_caption', + onClick: () => { + // Save a caption + pluginApi.serverCommands.caption.save({ + text: 'This is a caption text', + locale: 'en-US', + captionType: 'TYPED', + }); + }, + }), + new ActionButtonDropdownOption({ + label: 'Add caption locale', + icon: 'closed_caption', + onClick: () => { + // Add a new locale option for captions + pluginApi.serverCommands.caption.addLocale({ + locale: 'pt-BR', + localeName: 'Portuguese (Brazil)', + }); + }, + }), + ]); + }, []); + +``` + +**Note on permissions:** Some server commands have permission controls based on roles defined in the manifest. See the [Manifest Json](#manifest-json) section for configuration details. + ### Dom Element Manipulation - `useChatMessageDomElements` hook: This hook will return the dom element of a chat message reactively, so one can modify whatever is inside, such as text, css, js, etc.; - `useUserCameraDomElements` hook: This hook will return the dom element of each of the user's webcam corresponding to the streamIds passed reactively, so one can modify whatever is inside, such as text, css, js, etc., and also can get the video element within it; +**Example usage:** + +```typescript + BbbPluginSdk.initialize(pluginUuid); + const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + const [chatIdsToHighlight, setChatIdsToHighlight] = useState([]); + const [streamIdsToStyle, setStreamIdsToStyle] = useState([]); + + // Example 1: Manipulate chat messages (highlight mentions) + const { data: chatMessages } = pluginApi.useLoadedChatMessages(); + + useEffect(() => { + if (chatMessages) { + // Filter messages that mention someone with @ pattern + const MENTION_REGEX = /@([A-Z][a-z]+ ){0,2}[A-Z][a-z]+/; + const messageIds = chatMessages + .filter((msg) => MENTION_REGEX.test(msg.message)) + .map((msg) => msg.messageId); + setChatIdsToHighlight(messageIds); + } + }, [chatMessages]); + + // Get DOM elements for the chat messages we want to manipulate + const chatMessagesDomElements = pluginApi.useChatMessageDomElements(chatIdsToHighlight); + + useEffect(() => { + if (chatMessagesDomElements && chatMessagesDomElements.length > 0) { + chatMessagesDomElements.forEach((chatMessageDomElement) => { + const MENTION_REGEX = /@([A-Z][a-z]+ ){0,2}[A-Z][a-z]+/; + const mention = chatMessageDomElement.innerHTML.match(MENTION_REGEX); + + if (mention) { + // Highlight the mention with custom styling + chatMessageDomElement.innerHTML = chatMessageDomElement.innerHTML.replace( + mention[0], + `${mention[0]}` + ); + } + + // Style the parent element + const { parentElement } = chatMessageDomElement; + if (parentElement) { + parentElement.style.paddingTop = '0.5rem'; + parentElement.style.paddingBottom = '0.5rem'; + parentElement.style.borderLeft = '3px solid #4185cf'; + parentElement.style.backgroundColor = '#f8f9fa'; + } + + pluginLogger.info('Styled chat message:', chatMessageDomElement); + }); + } + }, [chatMessagesDomElements]); + + // Example 2: Manipulate user camera streams + const { data: videoStreams } = pluginApi.useCustomSubscription(` + subscription VideoStreams { + user_camera { + streamId + user { + userId + name + } + } + } + `); + + useEffect(() => { + if (videoStreams?.user_camera) { + // Get all stream IDs + const streamIds = videoStreams.user_camera.map((stream) => stream.streamId); + setStreamIdsToStyle(streamIds); + } + }, [videoStreams]); + + // Get DOM elements for user cameras + const userCameraDomElements = pluginApi.useUserCameraDomElements(streamIdsToStyle); + + useEffect(() => { + if (userCameraDomElements && userCameraDomElements.length > 0) { + userCameraDomElements.forEach((cameraElement) => { + // Add a custom border to the camera + cameraElement.element.style.border = '3px solid #0c5cb3'; + cameraElement.element.style.borderRadius = '8px'; + cameraElement.element.style.boxShadow = '0 4px 6px rgba(0, 0, 0, 0.1)'; + + // Access the video element directly + if (cameraElement.videoElement) { + cameraElement.videoElement.style.objectFit = 'cover'; + pluginLogger.info('Styled video element for stream:', cameraElement.streamId); + } + + // Add a custom overlay + const overlay = document.createElement('div'); + overlay.style.position = 'absolute'; + overlay.style.top = '5px'; + overlay.style.right = '5px'; + overlay.style.backgroundColor = 'rgba(0, 0, 0, 0.7)'; + overlay.style.color = 'white'; + overlay.style.padding = '4px 8px'; + overlay.style.borderRadius = '4px'; + overlay.style.fontSize = '12px'; + overlay.textContent = '🎥 Live'; + cameraElement.element.style.position = 'relative'; + cameraElement.element.appendChild(overlay); + }); + } + }, [userCameraDomElements]); +``` + +**Important notes:** +- Use DOM manipulation carefully and only when necessary +- Always check if elements exist before manipulating them +- Prefer using the provided hooks over direct DOM queries +- Be aware that excessive DOM manipulation can impact performance +- When styling chat messages, avoid changing the actual text content as it may cause issues with recordings for more information on that, see [guidelines section](https://docs.bigbluebutton.org/plugins/#dom-element-manipulation-guidelines) + ### Learning Analytics Dashboard integration -- `sendGenericDataForLearningAnalyticsDashboard`: This function will send data for the bbb to render inside the plugin's table +This integration allow you to insert/update entry in LAD (Learning Analytics Dashboard) via `upsertUserData` function and also delete entries via `deleteUserData` function. + +It's an object available in the `pluginApi` that wraps those 3 functions: + +- `pluginApi.learningAnalyticsDashboard.upsertUserData` +- `pluginApi.learningAnalyticsDashboard.deleteUserData` +- `pluginApi.learningAnalyticsDashboard.clearAllUsersData` -The object structure of this function's argument must be: +For the `upsert` function, the argument's data object structure must be: ```ts -interface GenericDataForLearningAnalyticsDashboard { - cardTitle: string; // Yet to be implemented (future updates) +interface LearningAnalyticsDashboardUserData { + cardTitle: string; columnTitle: string; value: string; } ``` +For the `deleteUserData` function, the argument's data object structure must be: + +```ts +interface LearningAnalyticsDashboardDeleteUserData { + cardTitle: string; + columnTitle: string; +} +``` + +For the `clearAllUsersData` function, the argument is the cardTitle (optionally), and when it's not sent, all the entries for a specific plugin will be deleted. (And if the card ends up empty, it will be removed) + +If the user is a moderator, there is the possibility to publish data on behalf of other users by using the second **optional** parameter named `targetUserId` + So that the data will appear in the following form: -| User | Count | `` | -| --------- | :---- | --------------: | -| user-name | 1 | `` | +| User | Count | `` | +| --- | :-- | --: | +| user-name | 1 | `` | + +**Example usage:** + +```typescript + BbbPluginSdk.initialize(pluginUuid); + const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + const [interactionCount, setInteractionCount] = useState(0); + + // Example: Track user interactions and send to Learning Analytics Dashboard + useEffect(() => { + const handleUserInteraction = () => { + const newCount = interactionCount + 1; + setInteractionCount(newCount); + + // Send data to Learning Analytics Dashboard + pluginApi.sendGenericDataForLearningAnalyticsDashboard({ + cardTitle: 'User Interactions', // For future use + columnTitle: 'Total Clicks', + value: newCount.toString(), + }); + + pluginLogger.info('Sent interaction data to dashboard:', newCount); + }; + + // Example: Track button clicks + pluginApi.setActionButtonDropdownItems([ + new ActionButtonDropdownOption({ + label: 'Track Interaction', + icon: 'user', + onClick: handleUserInteraction, + }), + ]); + }, [interactionCount]); + + // Example: Send engagement metrics periodically + useEffect(() => { + const interval = setInterval(() => { + const engagementScore = Math.floor(Math.random() * 100); + + pluginApi.sendGenericDataForLearningAnalyticsDashboard({ + cardTitle: 'Engagement Metrics', + columnTitle: 'Engagement Score', + value: `${engagementScore}%`, + }); + + pluginLogger.info('Sent engagement score:', engagementScore); + }, 60000); // Every minute + + return () => clearInterval(interval); + }, []); + + // Example: Track specific plugin events + const { data: chatMessages } = pluginApi.useLoadedChatMessages(); + + useEffect(() => { + if (chatMessages) { + const messageCount = chatMessages.length; + + pluginApi.sendGenericDataForLearningAnalyticsDashboard({ + cardTitle: 'Chat Activity', + columnTitle: 'Messages Sent', + value: messageCount.toString(), + }); + } + }, [chatMessages]); + +``` + +**Use cases for Learning Analytics:** +- Track user participation and engagement +- Monitor plugin-specific metrics (e.g., poll responses, quiz answers) +- Measure feature usage and adoption +- Collect custom learning indicators +- Generate post-meeting reports with plugin data + + +See example of use ahead: + +```ts +const targetUserId = 'abcd-efg'; +pluginApi.learningAnalyticsDashboard.upsertUserData( + { + cardTitle: 'Example Title', + columnTitle: 'link sent by user', + value: '[link](https://my-website.com/abc.png)' + }, + targetUserId, +); + +pluginApi.learningAnalyticsDashboard.deleteUserData( + { + cardTitle: 'Example Title', + columnTitle: 'link sent by user', + }, + targetUserId, +); + +pluginApi.learningAnalyticsDashboard.clearAllUsersData(columnTitle); + +pluginApi.learningAnalyticsDashboard.clearAllUsersData(); // Or without the Column Title +``` + +Note 1: the `value` field (in the upsert function's argument) supports markdown, so feel free to use it as you wish. + +Note 2: pluginApi.sendGenericDataForLearningAnalyticsDashboard is now being deprecated, but has the same data structure as upsert (without the possibility to send entry on behalf of another user) ### External data resources @@ -560,12 +1255,167 @@ pluginApi }); ``` -### Meta\_ parameters +### Fetch ui data on demand + +- `getUiData` async function: This will return certain data from the UI depending on the parameter the developer uses. Unlike the `useUiData` this function does not return real-time information as it changes. See the currently supported: + - PresentationWhiteboardUiDataNames.CURRENT_PAGE_SNAPSHOT; + +**Example usage:** + +```typescript + BbbPluginSdk.initialize(pluginUuid); + const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + + useEffect(() => { + pluginApi.setActionButtonDropdownItems([ + new ActionButtonDropdownOption({ + label: 'Capture whiteboard snapshot', + icon: 'copy', + onClick: async () => { + // Fetch the current whiteboard page as a PNG snapshot + const snapshotData = await pluginApi.getUiData( + PresentationWhiteboardUiDataNames.CURRENT_PAGE_SNAPSHOT + ); + + if (snapshotData?.pngBase64) { + console.log('Whiteboard snapshot (base64 PNG):', snapshotData.pngBase64); + + // Example: Download the snapshot + const link = document.createElement('a'); + link.href = `data:image/png;base64,${snapshotData.pngBase64}`; + link.download = `whiteboard-snapshot-${Date.now()}.png`; + link.click(); + } + }, + }), + ]); + }, []); + +``` + +### Customize manifest.json + +The following sections explain how you can dynamically customize your manifest.json for different runs. + +#### Meta_ parameters This is not part of the API, but it's a way of passing information to the manifest. Any value can be passed like this, one just needs to put something like `${meta_nameOfParameter}` in a specific config of the manifest, and in the `/create` call, set this meta-parameter to whatever is preferred, like `meta_nameOfParameter="Sample message"` This feature is mainly used for security purposes, see [external data section](#external-data-resources). But can be used for customization reasons as well. +**Example:** + +```json +{ + "requiredSdkVersion": "~0.0.59", + "name": "MyPlugin", + "javascriptEntrypointUrl": "MyPlugin.js", + "remoteDataSources": [ + { + "name": "userData", + "url": "${meta_userDataEndpoint}", + "fetchMode": "onMeetingCreate", + "permissions": ["moderator", "viewer"] + } + ] +} +``` + +Then in the `/create` call: + +``` +meta_userDataEndpoint=https://my-api.com/users +pluginManifests=[{"url": "https://my-cdn.com/my-plugin/manifest.json"}] +``` + +#### Plugin_ parameters + +`plugin_` parameters work similarly to `meta_` parameters, allowing data to be passed dynamically to the manifest. While they can serve the same purposes — like security or customization — they are specifically scoped to individual plugins. + +**Format:** + +``` +plugin__ +``` + +- `` — The name of the plugin as defined in `manifest.json`. +- `` — The parameter's name. It may include letters (uppercase or lowercase), numbers and hyphens (`-`). + +This naming convention ensures that each plugin has its own namespace for parameters. Other plugins cannot access values outside their own namespace. For example: + +``` +plugin_MyPlugin_api-endpoint=https://api.example.com +plugin_MyPlugin_theme-color=blue +``` + +This isolates the parameter to `MyPlugin` and avoids conflicts with other plugins. + +**Example manifest.json:** + +```json +{ + "requiredSdkVersion": "~0.0.59", + "name": "MyPlugin", + "javascriptEntrypointUrl": "MyPlugin.js", + "dataChannels": [ + { + "name": "${plugin_MyPlugin_channel-name:defaultChannel}", + "pushPermission": ["moderator", "presenter"], + "replaceOrDeletePermission": ["moderator", "creator"] + } + ], + "remoteDataSources": [ + { + "name": "pluginData", + "url": "${plugin_MyPlugin_api-endpoint}", + "fetchMode": "onDemand", + "permissions": ["moderator"] + } + ] +} +``` + +Then in the `/create` call: + +``` +plugin_MyPlugin_channel-name=customChannelName +plugin_MyPlugin_api-endpoint=https://my-api.com/plugin-data +pluginManifests=[{"url": "https://my-cdn.com/my-plugin/manifest.json"}] +``` + +#### Default value (fallback) for missing placeholder's parameters + +If a plugin expects a placeholder (via `meta_` or `plugin_`) but doesn't receive a value, the plugin will fail to load. To prevent this, both types of placeholders support default values. This allows the system administrator to define fallback values, ensuring the plugin loads correctly. + +**Example with a default value:** + +```json +{ + "requiredSdkVersion": "~0.0.59", + "name": "MyPlugin", + "javascriptEntrypointUrl": "MyPlugin.js", + "dataChannels": [ + { + "name": "${plugin_MyPlugin_data-channel-name:storeState}", + "pushPermission": ["moderator", "presenter"], + "replaceOrDeletePermission": ["moderator", "creator"] + } + ], + "remoteDataSources": [ + { + "name": "apiData", + "url": "${meta_apiEndpoint:https://default-api.com/data}", + "fetchMode": "onMeetingCreate", + "permissions": ["moderator"] + } + ] +} +``` + +In this example: +- If `plugin_MyPlugin_data-channel-name` is not provided, it will fall back to `"storeState"` +- If `meta_apiEndpoint` is not provided, it will fall back to `"https://default-api.com/data"` + ### Event persistence This feature will allow the developer to save an information (an event) in the `event.xml` file of the meeting, if it's being recorded. @@ -620,6 +1470,185 @@ Where `` is the id of the the meeting you just recorded. Then, among ``` +## Common Patterns and Best Practices + +This section covers common patterns and best practices for plugin development. + +### Plugin Initialization Pattern + +Always initialize your plugin in this order: + +```typescript +import { BbbPluginSdk, PluginApi } from 'bigbluebutton-html-plugin-sdk'; +import { useEffect } from 'react'; + +function MyPlugin({ pluginUuid }: MyPluginProps) { + // 1. Initialize the SDK (must be first) + BbbPluginSdk.initialize(pluginUuid); + + // 2. Get the plugin API instance + const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + + // 3. Use hooks to fetch data + const { data: currentUser } = pluginApi.useCurrentUser(); + + // 4. Set up UI extensions in useEffect + useEffect(() => { + // Register UI items here + pluginApi.setActionButtonDropdownItems([...]); + }, []); // Empty dependency array for one-time setup + + // 5. Return null (plugins typically don't render directly) + return null; +} +``` + +### Error Handling Pattern + +```typescript +function MyPlugin({ pluginUuid }: MyPluginProps) { + BbbPluginSdk.initialize(pluginUuid); + const pluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + + const { data, loading, error } = pluginApi.useCurrentUser(); + + useEffect(() => { + if (error) { + pluginLogger.error('Error fetching user data:', error); + // Show user-friendly notification + pluginApi.uiCommands.notification.send({ + type: 'error', + message: 'Failed to load plugin. Please refresh the page.', + icon: 'warning', + }); + return; + } + + if (loading) { + pluginLogger.info('Loading user data...'); + return; + } + + if (data) { + // Proceed with plugin logic + pluginLogger.info('User data loaded successfully'); + } + }, [data, loading, error]); + + return null; +} +``` + +### State Management Pattern + +```typescript +function MyPlugin({ pluginUuid }: MyPluginProps) { + BbbPluginSdk.initialize(pluginUuid); + const pluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + const [count, setCount] = useState(0); + const [isActive, setIsActive] = useState(false); + + useEffect(() => { + pluginApi.setActionButtonDropdownItems([ + new ActionButtonDropdownOption({ + label: `Counter: ${count}`, + icon: 'copy', + onClick: () => { + setCount(prevCount => prevCount + 1); + setIsActive(true); + }, + }), + ]); + }, [count]); // Re-render when count changes + + return null; +} +``` + +### Data Channel Communication Pattern + +```typescript +interface MessageType { + userId: string; + message: string; + timestamp: number; +} + +function MyPlugin({ pluginUuid }: MyPluginProps) { + BbbPluginSdk.initialize(pluginUuid); + const pluginApi = BbbPluginSdk.getPluginApi(pluginUuid); + + const { + data: messages, + pushEntry, + deleteEntry, + } = pluginApi.useDataChannel( + 'my-channel', + DataChannelTypes.ALL_ITEMS, + 'default' + ); + + const sendMessage = (text: string) => { + if (pushEntry) { + pushEntry({ + userId: 'current-user-id', + message: text, + timestamp: Date.now(), + }); + } + }; + + const clearMessages = () => { + if (deleteEntry) { + deleteEntry(RESET_DATA_CHANNEL); + } + }; + + useEffect(() => { + pluginApi.setActionButtonDropdownItems([ + new ActionButtonDropdownOption({ + label: 'Send Message', + icon: 'chat', + onClick: () => sendMessage('Hello!'), + }), + new ActionButtonDropdownOption({ + label: 'Clear Messages', + icon: 'delete', + onClick: clearMessages, + }), + ]); + }, []); + + useEffect(() => { + if (messages?.data) { + pluginLogger.info('Messages:', messages.data); + } + }, [messages]); + + return null; +} +``` + +### Best Practices + +1. **Always initialize the SDK first** before using any plugin API +2. **Use TypeScript** for type safety and better development experience +3. **Handle loading and error states** gracefully +4. **Clean up resources** (intervals, event listeners) in useEffect cleanup +5. **Use pluginLogger** instead of console.log for better debugging +6. **Test your plugin** with different user roles (moderator, presenter, viewer) +7. **Use the samples** as reference - they demonstrate best practices +8. **Document your plugin** - include a README with usage instructions + +### Performance Tips + +- **Minimize re-renders**: Use proper dependency arrays in useEffect +- **Avoid excessive DOM manipulation**: Use the provided hooks when possible +- **Debounce frequent operations**: Use debouncing for frequent UI updates +- **Clean up subscriptions**: Always return cleanup functions from useEffect +- **Use memoization**: Use React.useMemo and React.useCallback for expensive operations + + ### Frequently Asked Questions (FAQ) **How do I remove a certain extensible area that I don't want anymore?** diff --git a/package-lock.json b/package-lock.json index 40858d9d..cbfe60f5 100644 --- a/package-lock.json +++ b/package-lock.json @@ -376,13 +376,12 @@ } }, "node_modules/@playwright/test": { - "version": "1.51.1", - "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.51.1.tgz", - "integrity": "sha512-nM+kEaTSAoVlXmMPH10017vn3FSiFqr/bh4fKg9vmAdMfd9SDqRZNvPSiAHADc/itWak+qPvMPZQOPwCBW7k7Q==", + "version": "1.56.1", + "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.56.1.tgz", + "integrity": "sha512-vSMYtL/zOcFpvJCW71Q/OEGQb7KYBPAdKh35WNSkaZA75JlAO8ED8UN6GUNTm3drWomcbcqRPFqQbLae8yBTdg==", "dev": true, - "license": "Apache-2.0", "dependencies": { - "playwright": "1.51.1" + "playwright": "1.56.1" }, "bin": { "playwright": "cli.js" @@ -1000,9 +999,9 @@ } }, "node_modules/axios": { - "version": "1.12.2", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.12.2.tgz", - "integrity": "sha512-vMJzPewAlRyOgxV2dU0Cuz2O8zzzx9VYtbJOaBgXFeLc4IV/Eg50n4LowmehOOR61S8ZMpc2K5Sa7g6A4jfkUw==", + "version": "1.13.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.13.1.tgz", + "integrity": "sha512-hU4EGxxt+j7TQijx1oYdAjw4xuIp1wRQSsbMFwSthCWeBQur1eF+qJ5iQ5sN3Tw8YRzQNKb8jszgBdMDVqwJcw==", "dev": true, "dependencies": { "follow-redirects": "^1.15.6", @@ -3681,13 +3680,12 @@ } }, "node_modules/playwright": { - "version": "1.51.1", - "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.51.1.tgz", - "integrity": "sha512-kkx+MB2KQRkyxjYPc3a0wLZZoDczmppyGJIvQ43l+aZihkaVvmu/21kiyaHeHjiFxjxNNFnUncKmcGIyOojsaw==", + "version": "1.56.1", + "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.56.1.tgz", + "integrity": "sha512-aFi5B0WovBHTEvpM3DzXTUaeN6eN0qWnTkKx4NQaH4Wvcmc153PdaY2UBdSYKaGYw+UyWXSVyxDUg5DoPEttjw==", "dev": true, - "license": "Apache-2.0", "dependencies": { - "playwright-core": "1.51.1" + "playwright-core": "1.56.1" }, "bin": { "playwright": "cli.js" @@ -3700,11 +3698,10 @@ } }, "node_modules/playwright-core": { - "version": "1.51.1", - "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.51.1.tgz", - "integrity": "sha512-/crRMj8+j/Nq5s8QcvegseuyeZPxpQCZb6HNk3Sos3BlZyAknRjoyJPFWkpNn8v0+P3WiwqFF8P+zQo4eqiNuw==", + "version": "1.56.1", + "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz", + "integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==", "dev": true, - "license": "Apache-2.0", "bin": { "playwright-core": "cli.js" }, @@ -4328,9 +4325,9 @@ "dev": true }, "node_modules/to-buffer": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/to-buffer/-/to-buffer-1.2.1.tgz", - "integrity": "sha512-tB82LpAIWjhLYbqjx3X4zEeHN6M8CiuOEy2JY8SEQVdYRe3CCHOFaqrBW1doLDrfpWhplcW7BL+bO3/6S3pcDQ==", + "version": "1.2.2", + "resolved": "https://registry.npmjs.org/to-buffer/-/to-buffer-1.2.2.tgz", + "integrity": "sha512-db0E3UJjcFhpDhAF4tLo03oli3pwl3dbnzXOUIlRKrp+ldk/VUxzpWYZENsw2SZiuBjHAk7DfB0VU7NKdpb6sw==", "dev": true, "dependencies": { "isarray": "^2.0.5", diff --git a/samples/sample-actions-bar-plugin/src/sample-actions-bar-plugin/component.tsx b/samples/sample-actions-bar-plugin/src/sample-actions-bar-plugin/component.tsx index c6ea75f4..a04840ca 100644 --- a/samples/sample-actions-bar-plugin/src/sample-actions-bar-plugin/component.tsx +++ b/samples/sample-actions-bar-plugin/src/sample-actions-bar-plugin/component.tsx @@ -7,6 +7,7 @@ import { PluginApi, UsersBasicInfoResponseFromGraphqlWrapper, pluginLogger, } from 'bigbluebutton-html-plugin-sdk'; + import { SampleActionsBarPluginProps } from './types'; function SampleActionsBarPlugin({ diff --git a/samples/sample-apps-gallery-item-plugin/src/sample-apps-gallery-item-plugin/component.tsx b/samples/sample-apps-gallery-item-plugin/src/sample-apps-gallery-item-plugin/component.tsx index 220bccce..93d8ed01 100644 --- a/samples/sample-apps-gallery-item-plugin/src/sample-apps-gallery-item-plugin/component.tsx +++ b/samples/sample-apps-gallery-item-plugin/src/sample-apps-gallery-item-plugin/component.tsx @@ -18,14 +18,14 @@ function SampleAppsGalleryItemPlugin({ useEffect(() => { const buttonToUserListItem: - AppsGalleryInterface = new AppsGalleryEntry({ - icon: 'user', - name: 'Sample Apps Gallery Entry', - onClick: () => { - pluginLogger.info('The apps gallery item from plugin was clicked'); - setModalOpen(true); - }, - }); + AppsGalleryInterface = new AppsGalleryEntry({ + icon: 'user', + name: 'Sample Apps Gallery Entry', + onClick: () => { + pluginLogger.info('The apps gallery item from plugin was clicked'); + setModalOpen(true); + }, + }); pluginApi.setAppsGalleryItems([ buttonToUserListItem, diff --git a/samples/sample-data-channel-plugin/manifest.json b/samples/sample-data-channel-plugin/manifest.json index 004e0c74..8c00bbc0 100644 --- a/samples/sample-data-channel-plugin/manifest.json +++ b/samples/sample-data-channel-plugin/manifest.json @@ -1,8 +1,14 @@ { "requiredSdkVersion": "~0.1.5", "name": "SampleDataChannelPlugin", + "version": "0.0.8-beta1", "javascriptEntrypointUrl": "SampleDataChannelPlugin.js", "localesBaseUrl": "https://cdn.dominio.com/pluginabc/", + "loggerSettings": { + "console": { + "level": "error" + } + }, "dataChannels": [ { "name": "public-channel", @@ -12,7 +18,7 @@ ], "replaceOrDeletePermission": [ "moderator", - "sender" + "creator" ] } ] diff --git a/samples/sample-generic-content-sidekick-plugin/src/components/sample-generic-content-sidekick-plugin-item/component.tsx b/samples/sample-generic-content-sidekick-plugin/src/components/sample-generic-content-sidekick-plugin-item/component.tsx index 4f572768..ff5df8eb 100644 --- a/samples/sample-generic-content-sidekick-plugin/src/components/sample-generic-content-sidekick-plugin-item/component.tsx +++ b/samples/sample-generic-content-sidekick-plugin/src/components/sample-generic-content-sidekick-plugin-item/component.tsx @@ -28,6 +28,7 @@ function SampleGenericContentSidekickPlugin( id: GENERIC_CONTENT_BADGE_ID, name: 'Generic Content 1', section: 'Section 1', + dataTest: 'section-1-generic-content-sidekick-abc', buttonIcon: 'video', open: false, contentFunction: (element: HTMLElement) => { diff --git a/samples/sample-presentation-dropdown-plugin/src/components/sample-presentation-dropdown-plugin/component.tsx b/samples/sample-presentation-dropdown-plugin/src/components/sample-presentation-dropdown-plugin/component.tsx index 923e014a..ebd43927 100644 --- a/samples/sample-presentation-dropdown-plugin/src/components/sample-presentation-dropdown-plugin/component.tsx +++ b/samples/sample-presentation-dropdown-plugin/src/components/sample-presentation-dropdown-plugin/component.tsx @@ -4,10 +4,10 @@ import { useEffect } from 'react'; import { BbbPluginSdk, PluginApi, - pluginLogger, PresentationDropdownInterface, PresentationDropdownOption, PresentationDropdownSeparator, + pluginLogger, } from 'bigbluebutton-html-plugin-sdk'; import { SamplePresentationDropdownPluginProps } from './types'; diff --git a/samples/sample-screenshare-helper-plugin/src/sample-screenshare-helper-plugin/component.tsx b/samples/sample-screenshare-helper-plugin/src/sample-screenshare-helper-plugin/component.tsx index 14ede133..e72be8f2 100644 --- a/samples/sample-screenshare-helper-plugin/src/sample-screenshare-helper-plugin/component.tsx +++ b/samples/sample-screenshare-helper-plugin/src/sample-screenshare-helper-plugin/component.tsx @@ -4,14 +4,14 @@ import { useEffect } from 'react'; import { BbbPluginSdk, PluginApi, - pluginLogger, ScreenshareHelperItemPosition, ScreenshareHelperButton, + pluginLogger, } from 'bigbluebutton-html-plugin-sdk'; import { SampleUserCameraDropdownPluginProps } from './types'; function SampleUserCameraDropdownPlugin({ pluginUuid: uuid }: SampleUserCameraDropdownPluginProps): -React.ReactElement { + React.ReactElement { BbbPluginSdk.initialize(uuid); const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(uuid); diff --git a/samples/sample-ui-events-plugin/src/sample-ui-events-plugin-item/component.tsx b/samples/sample-ui-events-plugin/src/sample-ui-events-plugin-item/component.tsx index 145bd8f3..6eb4fc1f 100644 --- a/samples/sample-ui-events-plugin/src/sample-ui-events-plugin-item/component.tsx +++ b/samples/sample-ui-events-plugin/src/sample-ui-events-plugin-item/component.tsx @@ -9,7 +9,7 @@ import { import { SampleUiEventsPluginProps } from './types'; function SampleUiEventsPlugin({ pluginUuid: uuid }: SampleUiEventsPluginProps): -React.ReactElement { + React.ReactElement { BbbPluginSdk.initialize(uuid); const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(uuid); const userListOpened = pluginApi diff --git a/samples/sample-use-meeting/src/sample-use-meeting/component.tsx b/samples/sample-use-meeting/src/sample-use-meeting/component.tsx index 1eb33e84..6b2f01cb 100644 --- a/samples/sample-use-meeting/src/sample-use-meeting/component.tsx +++ b/samples/sample-use-meeting/src/sample-use-meeting/component.tsx @@ -7,7 +7,7 @@ import { import { SampleUseMeetingPluginProps } from './types'; function SampleUseMeetingPlugin({ pluginUuid: uuid }: SampleUseMeetingPluginProps): -React.ReactElement { + React.ReactElement { BbbPluginSdk.initialize(uuid); const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(uuid); const meetingInfoGraphqlResponse = pluginApi.useMeeting(); diff --git a/samples/sample-user-camera-dropdown-plugin/src/sample-user-camera-dropdown-plugin-item/component.tsx b/samples/sample-user-camera-dropdown-plugin/src/sample-user-camera-dropdown-plugin-item/component.tsx index 3590e6e1..23189a17 100644 --- a/samples/sample-user-camera-dropdown-plugin/src/sample-user-camera-dropdown-plugin-item/component.tsx +++ b/samples/sample-user-camera-dropdown-plugin/src/sample-user-camera-dropdown-plugin-item/component.tsx @@ -4,15 +4,15 @@ import { useEffect } from 'react'; import { BbbPluginSdk, PluginApi, - pluginLogger, UserCameraDropdownOption, UserCameraDropdownSeparator, + pluginLogger, } from 'bigbluebutton-html-plugin-sdk'; import { SampleUserCameraDropdownPluginProps, VideoStreamsSubscriptionResultType } from './types'; import { VIDEO_STREAMS_SUBSCRIPTION } from '../queries'; function SampleUserCameraDropdownPlugin({ pluginUuid: uuid }: SampleUserCameraDropdownPluginProps): -React.ReactElement { + React.ReactElement { BbbPluginSdk.initialize(uuid); const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(uuid); diff --git a/samples/sample-user-camera-helper-plugin/src/sample-user-camera-helper-plugin/component.tsx b/samples/sample-user-camera-helper-plugin/src/sample-user-camera-helper-plugin/component.tsx index c3a63e4d..79c8671c 100644 --- a/samples/sample-user-camera-helper-plugin/src/sample-user-camera-helper-plugin/component.tsx +++ b/samples/sample-user-camera-helper-plugin/src/sample-user-camera-helper-plugin/component.tsx @@ -4,15 +4,15 @@ import { useEffect } from 'react'; import { BbbPluginSdk, PluginApi, - pluginLogger, UserCameraHelperButton, UserCameraHelperItemPosition, + pluginLogger, } from 'bigbluebutton-html-plugin-sdk'; import { SampleUserCameraHelperPluginProps, VideoStreamsSubscriptionResultType } from './types'; import { VIDEO_STREAMS_SUBSCRIPTION } from '../queries'; function SampleUserCameraHelperPlugin({ pluginUuid: uuid }: SampleUserCameraHelperPluginProps): -React.ReactElement { + React.ReactElement { BbbPluginSdk.initialize(uuid); const pluginApi: PluginApi = BbbPluginSdk.getPluginApi(uuid); diff --git a/samples/sample-user-list-dropdown-plugin/src/sample-user-list-dropdown-plugin-item/component.tsx b/samples/sample-user-list-dropdown-plugin/src/sample-user-list-dropdown-plugin-item/component.tsx index 62c74a15..92fc84d6 100644 --- a/samples/sample-user-list-dropdown-plugin/src/sample-user-list-dropdown-plugin-item/component.tsx +++ b/samples/sample-user-list-dropdown-plugin/src/sample-user-list-dropdown-plugin-item/component.tsx @@ -4,11 +4,11 @@ import { useEffect } from 'react'; import { BbbPluginSdk, PluginApi, - pluginLogger, UserListDropdownFixedContentInformation, UserListDropdownInterface, UserListDropdownOption, UserListDropdownSeparator, + pluginLogger, } from 'bigbluebutton-html-plugin-sdk'; import { SampleUserListDropdownPluginProps } from './types'; @@ -21,48 +21,48 @@ function SampleUserListDropdownPlugin({ useEffect(() => { if (loadedUserList !== undefined && loadedUserList.length > 0) { const listOfInformationToSend: - Array = loadedUserList.map( - (user) => { - const buttonToUserListItem: - UserListDropdownInterface = new UserListDropdownFixedContentInformation({ - label: 'Warning test', - iconRight: 'warning', - userId: user.userId, - textColor: 'red', - allowed: true, - }); - return buttonToUserListItem as UserListDropdownInterface; - }, - ); + Array = loadedUserList.map( + (user) => { + const buttonToUserListItem: + UserListDropdownInterface = new UserListDropdownFixedContentInformation({ + label: 'Warning test', + iconRight: 'warning', + userId: user.userId, + textColor: 'red', + allowed: true, + }); + return buttonToUserListItem as UserListDropdownInterface; + }, + ); const listOfOptionsToSend: - Array = loadedUserList.map( - (user) => { - const buttonToUserListItem: - UserListDropdownInterface = new UserListDropdownOption({ - label: 'Click to log something in the console', - icon: 'user', - userId: user.userId, - tooltip: 'This will log something in the console', - allowed: true, - onClick: () => { - pluginLogger.info('Log from sample user-list-dropdown-plugin'); - }, - }); - return buttonToUserListItem as UserListDropdownInterface; - }, - ); + Array = loadedUserList.map( + (user) => { + const buttonToUserListItem: + UserListDropdownInterface = new UserListDropdownOption({ + label: 'Click to log something in the console', + icon: 'user', + userId: user.userId, + tooltip: 'This will log something in the console', + allowed: true, + onClick: () => { + pluginLogger.info('Log from sample user-list-dropdown-plugin'); + }, + }); + return buttonToUserListItem as UserListDropdownInterface; + }, + ); const listOfDropdownsToSend: - Array = loadedUserList.map( - (user) => { - const dropdownToUserListItem: - UserListDropdownInterface = new UserListDropdownSeparator({ - userId: user.userId, - }); - return dropdownToUserListItem as UserListDropdownInterface; - }, - ); + Array = loadedUserList.map( + (user) => { + const dropdownToUserListItem: + UserListDropdownInterface = new UserListDropdownSeparator({ + userId: user.userId, + }); + return dropdownToUserListItem as UserListDropdownInterface; + }, + ); pluginApi.setUserListDropdownItems( [...listOfInformationToSend, ...listOfDropdownsToSend, ...listOfOptionsToSend], ); diff --git a/src/core/api/BbbPluginSdk.ts b/src/core/api/BbbPluginSdk.ts index a7e58dad..82a09959 100644 --- a/src/core/api/BbbPluginSdk.ts +++ b/src/core/api/BbbPluginSdk.ts @@ -46,7 +46,12 @@ import { useUiData } from '../../ui-data/hooks/hooks'; import { UseMeetingFunction } from '../../data-consumption/domain/meeting/from-core/types'; import { useMeeting } from '../../data-consumption/domain/meeting/from-core/hooks'; import { serverCommands } from '../../server-commands/commands'; -import { sendGenericDataForLearningAnalyticsDashboard } from '../../learning-analytics-dashboard/hooks'; +import { + clearAllUsersData, + deleteUserData, + sendGenericDataForLearningAnalyticsDashboard, + upsertUserData, +} from '../../learning-analytics-dashboard/commands'; import { GenericDataForLearningAnalyticsDashboard } from '../../learning-analytics-dashboard/types'; import { getRemoteData } from '../../remote-data/utils'; import { persistEventFunctionWrapper } from '../../event-persistence/hooks'; @@ -56,6 +61,8 @@ import { useCustomQuery } from '../../data-consumption/domain/shared/custom-quer import { UseCustomQueryFunction } from '../../data-consumption/domain/shared/custom-query/types'; import { useCustomMutation } from '../../data-creation/hook'; import { UseCustomMutationFunction } from '../../data-creation/types'; +import { UseMeetingDataFunction } from '../../data-consumption/domain/meeting/meeting-data/types'; +import { useMeetingData } from '../../data-consumption/domain/meeting/meeting-data/hooks'; declare const window: PluginBrowserWindow; @@ -98,6 +105,7 @@ export abstract class BbbPluginSdk { pluginApi.useLoadedUserList = (() => useLoadedUserList()) as UseLoadedUserListFunction; pluginApi.useCurrentUser = (() => useCurrentUser()) as UseCurrentUserFunction; pluginApi.useMeeting = (() => useMeeting()) as UseMeetingFunction; + pluginApi.useMeetingData = useMeetingData as UseMeetingDataFunction; pluginApi.useUsersBasicInfo = (() => useUsersBasicInfo()) as UseUsersBasicInfoFunction; pluginApi.useTalkingIndicator = (() => useTalkingIndicator()) as UseTalkingIndicatorFunction; pluginApi.getJoinUrl = (params) => getJoinUrl(params); @@ -131,6 +139,22 @@ export abstract class BbbPluginSdk { pluginApi.sendGenericDataForLearningAnalyticsDashboard = ( data: GenericDataForLearningAnalyticsDashboard, ) => sendGenericDataForLearningAnalyticsDashboard(data, pluginName); + pluginApi.learningAnalyticsDashboard = { + upsertUserData: (data, targetUserId) => upsertUserData( + data, + pluginName, + targetUserId, + ), + deleteUserData: (data, targetUserId) => deleteUserData( + data, + pluginName, + targetUserId, + ), + clearAllUsersData: (cardTitle?: string) => clearAllUsersData( + pluginName, + cardTitle, + ), + }; pluginApi.getRemoteData = ( dataSourceName: string, ) => getRemoteData(dataSourceName, pluginName); @@ -207,7 +231,6 @@ export abstract class BbbPluginSdk { localesBaseUrl, }; } - return window.bbb_plugins[uuid]; } } diff --git a/src/core/api/types.ts b/src/core/api/types.ts index 6aa3ea6c..fdf0fdee 100644 --- a/src/core/api/types.ts +++ b/src/core/api/types.ts @@ -1,3 +1,4 @@ +import { Logger } from 'browser-bunyan'; import { UiCommands } from '../../ui-commands/types'; import { UseChatMessageDomElementsFunction } from '../../dom-element-manipulation/chat/message/types'; import { MediaAreaInterface } from '../../extensible-areas/media-area-item/types'; @@ -27,7 +28,7 @@ import { GenericContentInterface } from '../../extensible-areas/generic-content- import { UseUiDataFunction } from '../../ui-data/hooks/types'; import { UseMeetingFunction } from '../../data-consumption/domain/meeting/from-core/types'; import { ServerCommands } from '../../server-commands/types'; -import { SendGenericDataForLearningAnalyticsDashboard } from '../../learning-analytics-dashboard/types'; +import { LearningAnalyticsDashboardWrapperObject, SendGenericDataForLearningAnalyticsDashboard } from '../../learning-analytics-dashboard/types'; import { UseUserCameraDomElementsFunction } from '../../dom-element-manipulation/user-camera/types'; import { AppsGalleryInterface, ScreenshareHelperInterface, UserCameraHelperInterface } from '../../extensible-areas'; import { GetDataSource } from '../../remote-data/types'; @@ -37,6 +38,7 @@ import { UseShouldUnmountPluginFunction } from '../auxiliary/plugin-unmount/type import { GetUiDataFunction } from '../../ui-data/getters/types'; import { UseCustomQueryFunction } from '../../data-consumption/domain/shared/custom-query/types'; import { UseCustomMutationFunction } from '../../data-creation/types'; +import { UseMeetingDataFunction } from '../../data-consumption/domain/meeting/meeting-data/types'; // Setter Functions for the API export type SetPresentationToolbarItems = (presentationToolbarItem: @@ -152,8 +154,21 @@ export interface PluginApi { * * @returns `GraphqlResponseWrapper` with the CurrentMeeting type. * + * @deprecated use {@link useMeetingData} + * */ useMeeting?: UseMeetingFunction; + /** + * Returns an object containing the data on the current meeting, i.e. the meeting on which the + * plugin is running. + * + * @param projectionFunction - function to select only specific fields from the + * Meeting type (Optional - if not provided, returns all fields). + * + * @returns `GraphqlResponseWrapper` with the CurrentMeeting type. + * + */ + useMeetingData?: UseMeetingDataFunction; /** * Returns an object containing the brief data on every user in te meeting. * @@ -292,12 +307,22 @@ export interface PluginApi { */ useLocaleMessages?: UseLocaleMessagesFunction /** + * @deprecated Use {@link learningAnalyticsDashboard.upsertUserData} object instead. + * * Send data to the Learning analytics dashboard * * @param data - object in which one can render in the learning analytics dashboard * */ sendGenericDataForLearningAnalyticsDashboard?: SendGenericDataForLearningAnalyticsDashboard; + /** + * Wrapper object of functions related to the learning analytics dashboard. + * It contains the following functions: + * - deleteGenericData: Deletes a certain entry in the learning dashboard generic-data; + * - upsertGenericData: Updates or insert a generic data entry in the learning dashboard; + * + */ + learningAnalyticsDashboard?: LearningAnalyticsDashboardWrapperObject; /** * Fetches external data from pre-defined data-source in manifest. * @@ -313,6 +338,30 @@ export interface PluginApi { * */ persistEvent?: PersistEventFunction; + /** + * Function used to log in the console. + */ + logger?: Logger; +} + +export interface Console { + enabled: boolean + level: string +} + +export interface External { + enabled: boolean + level: string + url: string + method: string + throttleInterval: number + flushOnClose: boolean + logTag: string +} + +export interface ClientLog { + console: Console + external: External } export interface MeetingClientSettings { @@ -320,6 +369,7 @@ export interface MeetingClientSettings { app: { bbbWebBase: string; } + clientLog: ClientLog; } } diff --git a/src/data-consumption/domain/meeting/index.ts b/src/data-consumption/domain/meeting/index.ts index 0b68de78..c9321833 100644 --- a/src/data-consumption/domain/meeting/index.ts +++ b/src/data-consumption/domain/meeting/index.ts @@ -1 +1,2 @@ export { Meeting } from './from-core/types'; +export { MeetingData } from './meeting-data/types'; diff --git a/src/data-consumption/domain/meeting/meeting-data/hooks.ts b/src/data-consumption/domain/meeting/meeting-data/hooks.ts new file mode 100644 index 00000000..fa2ee282 --- /dev/null +++ b/src/data-consumption/domain/meeting/meeting-data/hooks.ts @@ -0,0 +1,16 @@ +import { DeepPartial } from '../../../../data-consumption/factory/types'; +import { useProjectedValue } from '../../../../data-consumption/factory/hooks'; +import { DataConsumptionHooks } from '../../../enums'; +import { createDataConsumptionHook } from '../../../factory/hookCreator'; +import { MeetingData } from './types'; + +export const useMeetingData = ( + projectionFunction?: (q: MeetingData) => DeepPartial, +) => useProjectedValue( + createDataConsumptionHook< + MeetingData + >( + DataConsumptionHooks.MEETING_DATA, + ), + projectionFunction, +); diff --git a/src/data-consumption/domain/meeting/meeting-data/types.ts b/src/data-consumption/domain/meeting/meeting-data/types.ts new file mode 100644 index 00000000..151896e0 --- /dev/null +++ b/src/data-consumption/domain/meeting/meeting-data/types.ts @@ -0,0 +1,154 @@ +import { DeepPartial } from '../../../../data-consumption/factory/types'; +import { GraphqlResponseWrapper } from '../../../../core'; + +export interface LockSettings { + disableCam: boolean; + disableMic: boolean; + disableNotes: boolean; + disablePrivateChat: boolean; + disablePublicChat: boolean; + hasActiveLockSetting: boolean; + hideUserList: boolean; + hideViewersCursor: boolean; + hideViewersAnnotation: false, + meetingId: boolean; + webcamsOnlyForModerator: boolean; +} + +export interface groups { + groupId: string; + name: string; +} + +export interface WelcomeSettings { + welcomeMsg: string; + welcomeMsgForModerators: string; + meetingId: string; +} + +export interface MeetingRecording { + isRecording: boolean; + startedAt: Date; + previousRecordedTimeInSeconds: number; + startedBy: string; + stoppedAt: number; + stoppedBy: string; +} +export interface MeetingRecordingPolicies { + allowStartStopRecording: boolean; + autoStartRecording: boolean; + record: boolean; + keepEvents: boolean; + startedAt: number; + startedBy: string; + stoppedAt: number; + stoppedBy: string; +} + +export interface UsersPolicies { + allowModsToEjectCameras: boolean; + allowModsToUnmuteUsers: boolean; + authenticatedGuest: boolean; + allowPromoteGuestToModerator: boolean; + guestPolicy: string; + maxUserConcurrentAccesses: number; + maxUsers: number; + meetingId: string; + meetingLayout: string; + userCameraCap: number; + webcamsOnlyForModerator: boolean; + guestLobbyMessage: string | null; +} + +export interface VoiceSettings { + dialNumber: string; + meetingId: string; + muteOnStart: boolean; + telVoice: string; + voiceConf: string; +} + +export interface BreakoutPolicies { + breakoutRooms: Array; + captureNotes: string; + captureNotesFilename: string; + captureSlides: string; + captureSlidesFilename: string; + freeJoin: boolean; + parentId: string; + privateChatEnabled: boolean; + record: boolean; + sequence: number; +} + +export interface BreakoutRoomsCommonProperties { + durationInSeconds: number; + freeJoin: boolean; + sendInvitationToModerators: boolean; + startedAt: Date; +} + +export interface ExternalVideo { + externalVideoId: string; + playerCurrentTime: number; + playerPlaybackRate: number; + playerPlaying: boolean; + externalVideoUrl: string; + startedSharingAt: number; + stoppedSharingAt: number; + updatedAt: string; +} + +export interface Layout { + currentLayoutType: string; +} + +export interface ComponentsFlags { + hasCaption: boolean; + hasBreakoutRoom: boolean; + hasExternalVideo: boolean; + hasPoll: boolean; + hasScreenshare: boolean; + hasTimer: boolean; + showRemainingTime: boolean; + hasCameraAsContent: boolean; + hasScreenshareAsContent: boolean; + hasCurrentPresentation: boolean; + hasSharedNotes: boolean; + isSharedNotesPinned: boolean; +} + +export interface MeetingData { + createdTime: number; + disabledFeatures: Array; + durationInSeconds: number; + extId: string; + isBreakout: boolean; + learningDashboardAccessToken: string; + maxPinnedCameras: number; + meetingCameraCap: number; + cameraBridge: string; + screenShareBridge: string; + audioBridge: string; + meetingId: string; + name: string; + notifyRecordingIsOn: boolean; + presentationUploadExternalDescription: string; + presentationUploadExternalUrl: string; + usersPolicies: UsersPolicies; + lockSettings: LockSettings; + voiceSettings: VoiceSettings; + breakoutPolicies: BreakoutPolicies; + breakoutRoomsCommonProperties: BreakoutRoomsCommonProperties; + externalVideo: ExternalVideo; + layout: Layout; + componentsFlags: ComponentsFlags; + endWhenNoModerator: boolean; + endWhenNoModeratorDelayInMinutes: number; + loginUrl: string | null; + groups: Array; +} + +export type UseMeetingDataFunction = ( + projectionFunction?: (q: MeetingData) => DeepPartial, +) => GraphqlResponseWrapper; diff --git a/src/data-consumption/domain/users/users-basic-info/types.ts b/src/data-consumption/domain/users/users-basic-info/types.ts index 66b427e7..5ae21780 100644 --- a/src/data-consumption/domain/users/users-basic-info/types.ts +++ b/src/data-consumption/domain/users/users-basic-info/types.ts @@ -4,6 +4,8 @@ export interface UsersBasicInfoData { userId: string; extId: string; name: string; + nameSortable: string; + bot: boolean; /** * @deprecated use {@link isModerator} instead */ diff --git a/src/data-consumption/enums.ts b/src/data-consumption/enums.ts index b8ed57f2..238ce3c1 100644 --- a/src/data-consumption/enums.ts +++ b/src/data-consumption/enums.ts @@ -5,6 +5,7 @@ export enum DataConsumptionHooks { USERS_BASIC_INFO = 'Hooks::UseUsersBasicInfo', LOADED_CHAT_MESSAGES = 'Hooks::UseLoadedChatMessages', MEETING = 'Hooks::UseMeeting', + MEETING_DATA = 'Hooks::UseMeetingData', TALKING_INDICATOR = 'Hooks::UseTalkingIndicator', CUSTOM_SUBSCRIPTION = 'Hooks::CustomSubscription', CUSTOM_QUERY = 'Hooks::CustomQuery', diff --git a/src/data-consumption/factory/hooks.ts b/src/data-consumption/factory/hooks.ts new file mode 100644 index 00000000..d88bd48c --- /dev/null +++ b/src/data-consumption/factory/hooks.ts @@ -0,0 +1,82 @@ +import { + useRef, + useMemo, + useEffect, + useState, +} from 'react'; +import { sortedStringify } from '../utils'; +import { GraphqlResponseWrapper } from '../../core'; +import { hasErrorChanged } from './utils'; +import { DeepPartial } from './types'; + +// Function overload for array type +export function useProjectedValue( + queryResult: GraphqlResponseWrapper, + project?: (q: TQueryResult) => DeepPartial, +): GraphqlResponseWrapper | GraphqlResponseWrapper[]>; +// Function overload for single value type +export function useProjectedValue( + queryResult: GraphqlResponseWrapper, + project?: (q: TQueryResult) => DeepPartial, +): GraphqlResponseWrapper | GraphqlResponseWrapper>; +// Implementation +export function useProjectedValue( + queryResult: GraphqlResponseWrapper, + project?: (q: TQueryResult) => DeepPartial, +): GraphqlResponseWrapper + | GraphqlResponseWrapper[] | DeepPartial> { + if (!project) return queryResult; + + const isArray = Array.isArray(queryResult.data); + + // Store the previous projected data to compare against + const previousProjectedDataRef = useRef< + DeepPartial[] | DeepPartial | undefined + >(undefined); + + // Compute the new projected value from the data field + const currentProjectedData = useMemo(() => { + if (!queryResult.data) return undefined; + if (isArray) { + return (queryResult.data as TQueryResult[]).map((item) => project(item)); + } + return project(queryResult.data as TQueryResult); + }, [queryResult.data, project, isArray]); + + // Initialize state with the wrapper structure + const [projectionResult, setProjectionResult] = useState< + GraphqlResponseWrapper[] | DeepPartial> + >({ + loading: queryResult.loading, + data: currentProjectedData, + error: queryResult.error, + }); + + useEffect(() => { + // Perform deep equality check using sortedStringify + const currentSerialized = sortedStringify(currentProjectedData); + const previousSerialized = sortedStringify(previousProjectedDataRef.current); + + // Check if loading or error states changed + const loadingChanged = queryResult.loading !== projectionResult.loading; + const errorChanged = hasErrorChanged(projectionResult.error, queryResult.error); + + // Only update if the projected data, loading, or error state has changed + if (currentSerialized !== previousSerialized || loadingChanged || errorChanged) { + previousProjectedDataRef.current = currentProjectedData; + setProjectionResult({ + loading: queryResult.loading, + data: currentProjectedData, + error: queryResult.error, + }); + } + }, [ + currentProjectedData, + queryResult.loading, + queryResult.error, + projectionResult.loading, + projectionResult.error, + ]); + + return projectionResult; +} diff --git a/src/data-consumption/factory/types.ts b/src/data-consumption/factory/types.ts new file mode 100644 index 00000000..1a58cf55 --- /dev/null +++ b/src/data-consumption/factory/types.ts @@ -0,0 +1,7 @@ +export type DeepPartial = { + [K in keyof T]?: T[K] extends (infer U)[] + ? DeepPartial[] + : T[K] extends object + ? DeepPartial + : T[K]; +}; diff --git a/src/data-consumption/factory/utils.ts b/src/data-consumption/factory/utils.ts new file mode 100644 index 00000000..0eacd4d0 --- /dev/null +++ b/src/data-consumption/factory/utils.ts @@ -0,0 +1,11 @@ +import { ApolloError } from '@apollo/client'; +import { sortedStringify } from '../utils'; + +export const hasErrorChanged = ( + previousResultError?: ApolloError, + currentResultError?: ApolloError, +) => { + const currentSerialized = sortedStringify(currentResultError); + const previousSerialized = sortedStringify(previousResultError); + return currentSerialized !== previousSerialized; +}; diff --git a/src/data-consumption/index.ts b/src/data-consumption/index.ts index 0a28ea66..410f4af5 100644 --- a/src/data-consumption/index.ts +++ b/src/data-consumption/index.ts @@ -4,3 +4,5 @@ export * from './domain/meeting'; export * from './domain/users'; export * from './domain/user-voice'; export * from './domain/shared'; + +export * from './factory/types'; diff --git a/src/extensible-areas/actions-bar-item/types.ts b/src/extensible-areas/actions-bar-item/types.ts index 07b63888..6c8746f9 100644 --- a/src/extensible-areas/actions-bar-item/types.ts +++ b/src/extensible-areas/actions-bar-item/types.ts @@ -5,7 +5,7 @@ import { ActionsBarItemType, ActionsBarPosition } from './enums'; /** * Interface for the generic Actions bar item. (`position` is mandatory) */ -export interface ActionsBarInterface extends PluginProvidedUiItemDescriptor{ +export interface ActionsBarInterface extends PluginProvidedUiItemDescriptor { position: ActionsBarPosition; } diff --git a/src/extensible-areas/apps-gallery-item/component.ts b/src/extensible-areas/apps-gallery-item/component.ts index a5ed782f..72735d64 100644 --- a/src/extensible-areas/apps-gallery-item/component.ts +++ b/src/extensible-areas/apps-gallery-item/component.ts @@ -10,12 +10,26 @@ export class AppsGalleryEntry implements AppsGalleryInterface { icon: string = ''; + dataTest: string; + onClick: () => void; + /** + * Returns object to be used in the setter for the Apps Gallery. In this case, + * an entry. + * + * @param name - name to be displayed in the apps gallery entry. + * @param icon - icon to be displayed in the apps gallery entry. + * @param dataTest - string attribute to be used for testing + * @param onClick - function to be called when clicking the entry. + * + * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). + */ constructor({ id, name, icon, + dataTest = '', onClick, }: AppsGalleryItemProps) { if (id) { @@ -23,6 +37,7 @@ export class AppsGalleryEntry implements AppsGalleryInterface { } this.name = name; this.icon = icon; + this.dataTest = dataTest; this.onClick = onClick; } diff --git a/src/extensible-areas/apps-gallery-item/types.ts b/src/extensible-areas/apps-gallery-item/types.ts index db656367..580f339e 100644 --- a/src/extensible-areas/apps-gallery-item/types.ts +++ b/src/extensible-areas/apps-gallery-item/types.ts @@ -9,5 +9,6 @@ export interface AppsGalleryItemProps { id?: string; name: string; icon: string; + dataTest?: string; onClick: () => void; } diff --git a/src/extensible-areas/base.ts b/src/extensible-areas/base.ts index 3d425bb7..4727a103 100644 --- a/src/extensible-areas/base.ts +++ b/src/extensible-areas/base.ts @@ -28,4 +28,5 @@ export interface PluginProvidedUiItemDescriptor { id: string; type: PluginProvidedUiItemType; setItemId: (id: string) => void; + dataTest?: string; } diff --git a/src/extensible-areas/floating-window/component.ts b/src/extensible-areas/floating-window/component.ts index 6b86e76b..4c7e07d2 100644 --- a/src/extensible-areas/floating-window/component.ts +++ b/src/extensible-areas/floating-window/component.ts @@ -19,6 +19,10 @@ export class FloatingWindow implements FloatingWindowInterface { boxShadow: string; + zIndex?: number; + + dataTest?: string; + contentFunction: (element: HTMLElement) => ReactDOM.Root; /** @@ -32,6 +36,7 @@ export class FloatingWindow implements FloatingWindowInterface { * @param movable - tells whether the floating window is movable or static. * @param backgroundColor - background color of the floating window. * @param boxShadow - box shadow to apply to the floating window + * @param zIndex - z-index of the floating window (Optional). * @param contentFunction - function that gives the html element to render the content of * the floating window. It must return the root element where the floating window was rendered. * @@ -44,7 +49,9 @@ export class FloatingWindow implements FloatingWindowInterface { movable, backgroundColor, boxShadow, + zIndex, contentFunction, + dataTest, }: FloatingWindowProps) { if (id) { this.id = id; @@ -52,8 +59,10 @@ export class FloatingWindow implements FloatingWindowInterface { this.top = top; this.left = left; this.movable = movable; + this.dataTest = dataTest; this.backgroundColor = backgroundColor; this.boxShadow = boxShadow; + this.zIndex = zIndex; this.contentFunction = contentFunction; this.type = FloatingWindowType.CONTAINER; diff --git a/src/extensible-areas/floating-window/types.ts b/src/extensible-areas/floating-window/types.ts index ecb56732..560d7d65 100644 --- a/src/extensible-areas/floating-window/types.ts +++ b/src/extensible-areas/floating-window/types.ts @@ -11,6 +11,8 @@ export interface FloatingWindowProps { movable: boolean; backgroundColor: string; boxShadow: string; + zIndex?: number; + dataTest?: string; contentFunction: (element: HTMLElement) => ReactDOM.Root; } diff --git a/src/extensible-areas/generic-content-item/component.ts b/src/extensible-areas/generic-content-item/component.ts index 12170d36..9e0413dd 100644 --- a/src/extensible-areas/generic-content-item/component.ts +++ b/src/extensible-areas/generic-content-item/component.ts @@ -11,22 +11,26 @@ export class GenericContentMainArea implements GenericContentInterface { contentFunction: (element: HTMLElement) => ReactDOM.Root; + dataTest: string; + /** * Returns an object that when used in the setter as a generic content will be rendered * over the meeting main presentation. * * @param contentFunction - function that gives the html element to render the content of * the generic component + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ - id, contentFunction, + id, contentFunction, dataTest = '', }: GenericContentMainAreaProps) { if (id) { this.id = id; } this.contentFunction = contentFunction; + this.dataTest = dataTest; this.type = GenericContentType.MAIN_AREA; } @@ -48,6 +52,8 @@ export class GenericContentSidekickArea implements GenericContentInterface { open: boolean = false; + dataTest: string; + contentFunction: (element: HTMLElement) => ReactDOM.Root; /** @@ -63,11 +69,12 @@ export class GenericContentSidekickArea implements GenericContentInterface { * displayed * @param buttonIcon - the icon of the associated sidebar navigation button * @param open - boolean value to decide wether to start open + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ - id, contentFunction, name, section, buttonIcon, open, + id, contentFunction, name, section, buttonIcon, open, dataTest = '', }: GenericContentSidekickAreaProps) { if (id) { this.id = id; @@ -76,6 +83,7 @@ export class GenericContentSidekickArea implements GenericContentInterface { this.name = name; this.section = section; this.buttonIcon = buttonIcon; + this.dataTest = dataTest; this.type = GenericContentType.SIDEKICK_AREA; this.open = open; } diff --git a/src/extensible-areas/generic-content-item/types.ts b/src/extensible-areas/generic-content-item/types.ts index 46c05065..55d026a5 100644 --- a/src/extensible-areas/generic-content-item/types.ts +++ b/src/extensible-areas/generic-content-item/types.ts @@ -7,6 +7,7 @@ export interface GenericContentInterface extends PluginProvidedUiItemDescriptor export interface GenericContentMainAreaProps { id?: string; contentFunction: (element: HTMLElement) => ReactDOM.Root; + dataTest?: string; } export interface GenericContentSidekickAreaProps { @@ -16,4 +17,5 @@ export interface GenericContentSidekickAreaProps { section: string; buttonIcon: string; open: boolean; + dataTest?: string; } diff --git a/src/extensible-areas/nav-bar-item/component.ts b/src/extensible-areas/nav-bar-item/component.ts index e769f320..29c03dfc 100644 --- a/src/extensible-areas/nav-bar-item/component.ts +++ b/src/extensible-areas/nav-bar-item/component.ts @@ -19,6 +19,8 @@ export class NavBarButton implements NavBarInterface { disabled: boolean; + dataTest: string; + position: NavBarItemPosition; hasSeparator: boolean; @@ -38,11 +40,12 @@ export class NavBarButton implements NavBarInterface { * @param hasSeparator - boolean indicating whether the navigation bar button has separator * (vertical bar) * @param disabled - if true, the navigation bar button will not be clickable + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ - id, label = '', icon = '', tooltip = '', disabled = true, onClick = () => {}, + id, label = '', icon = '', tooltip = '', disabled = true, dataTest = '', onClick = () => {}, position = NavBarItemPosition.RIGHT, hasSeparator = true, }: NavBarButtonProps) { if (id) { @@ -52,6 +55,7 @@ export class NavBarButton implements NavBarInterface { this.icon = icon; this.tooltip = tooltip; this.disabled = disabled; + this.dataTest = dataTest; this.onClick = onClick; this.type = NavBarItemType.BUTTON; this.hasSeparator = hasSeparator; @@ -70,6 +74,8 @@ export class NavBarInfo implements NavBarInterface { label: string; + dataTest: string; + hasSeparator: boolean; position: NavBarItemPosition; @@ -83,17 +89,19 @@ export class NavBarInfo implements NavBarInterface { * See {@link NavBarItemPosition} * @param hasSeparator - boolean indicating whether the navigation bar information has separator * (vertical bar) + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ id, label = '', position = NavBarItemPosition.RIGHT, - hasSeparator = true, + hasSeparator = true, dataTest = '', }: NavBarInfoProps) { if (id) { this.id = id; } this.label = label; + this.dataTest = dataTest; this.type = NavBarItemType.INFO; this.position = position; this.hasSeparator = hasSeparator; diff --git a/src/extensible-areas/nav-bar-item/types.ts b/src/extensible-areas/nav-bar-item/types.ts index 4952503b..737042f2 100644 --- a/src/extensible-areas/nav-bar-item/types.ts +++ b/src/extensible-areas/nav-bar-item/types.ts @@ -15,6 +15,7 @@ export interface NavBarButtonProps { hasSeparator: boolean; position: NavBarItemPosition; onClick: () => void; + dataTest?: string; } export interface NavBarInfoProps { @@ -22,4 +23,5 @@ export interface NavBarInfoProps { label: string; hasSeparator: boolean; position: NavBarItemPosition; + dataTest?: string; } diff --git a/src/extensible-areas/options-dropdown-item/component.ts b/src/extensible-areas/options-dropdown-item/component.ts index 20b0422c..08fe90c6 100644 --- a/src/extensible-areas/options-dropdown-item/component.ts +++ b/src/extensible-areas/options-dropdown-item/component.ts @@ -14,6 +14,8 @@ export class OptionsDropdownOption implements OptionsDropdownInterface { icon: string; + dataTest: string; + onClick: () => void; /** @@ -22,18 +24,20 @@ export class OptionsDropdownOption implements OptionsDropdownInterface { * * @param label - label to be displayed in the options dropdown option. * @param icon - icon to be displayed in the options dropdown. It goes in the left side of it. + * @param dataTest - string attribute to be used for testing * @param onClick - function to be called when clicking the option. * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ - id, label = '', icon = '', onClick = () => {}, + id, label = '', icon = '', dataTest = '', onClick = () => {}, }: OptionsDropdownOptionProps) { if (id) { this.id = id; } this.label = label; this.icon = icon; + this.dataTest = dataTest; this.onClick = onClick; this.type = OptionsDropdownItemType.OPTION; } @@ -48,13 +52,18 @@ export class OptionsDropdownSeparator implements OptionsDropdownInterface { type: OptionsDropdownItemType; + dataTest: string; + /** * Returns object to be used in the setter for the Navigation Bar. In this case, * a separator. * + * @param dataTest - string attribute to be used for testing + * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ - constructor() { + constructor({ dataTest = '' } = {}) { + this.dataTest = dataTest; this.type = OptionsDropdownItemType.SEPARATOR; } diff --git a/src/extensible-areas/options-dropdown-item/types.ts b/src/extensible-areas/options-dropdown-item/types.ts index d4d8ffd5..c08bd3df 100644 --- a/src/extensible-areas/options-dropdown-item/types.ts +++ b/src/extensible-areas/options-dropdown-item/types.ts @@ -15,4 +15,5 @@ export interface OptionsDropdownOptionProps { label: string; icon: string; onClick: () => void; + dataTest?: string; } diff --git a/src/extensible-areas/presentation-dropdown-item/component.ts b/src/extensible-areas/presentation-dropdown-item/component.ts index 210c98e4..9ed50230 100644 --- a/src/extensible-areas/presentation-dropdown-item/component.ts +++ b/src/extensible-areas/presentation-dropdown-item/component.ts @@ -14,6 +14,8 @@ export class PresentationDropdownOption implements PresentationDropdownInterface icon: string; + dataTest: string; + onClick: () => void; /** @@ -23,18 +25,20 @@ export class PresentationDropdownOption implements PresentationDropdownInterface * @param label - label to be displayed in the presentation dropdown option. * @param icon - icon to be displayed in the presentation dropdown. * It goes in the left side of it. + * @param dataTest - string attribute to be used for testing * @param onClick - function to be called when clicking the option. * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ - id, label = '', icon = '', onClick = () => {}, + id, label = '', icon = '', dataTest = '', onClick = () => {}, }: PresentationDropdownOptionProps) { if (id) { this.id = id; } this.label = label; this.icon = icon; + this.dataTest = dataTest; this.onClick = onClick; this.type = PresentationDropdownItemType.OPTION; } @@ -49,13 +53,18 @@ export class PresentationDropdownSeparator implements PresentationDropdownInterf type: PresentationDropdownItemType; + dataTest: string; + /** * Returns object to be used in the setter for the Presentation Dropdown. In this case, * a separator (horizontal thin black line). - + * + * @param dataTest - string attribute to be used for testing + * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ - constructor() { + constructor({ dataTest = '' } = {}) { + this.dataTest = dataTest; this.type = PresentationDropdownItemType.SEPARATOR; } diff --git a/src/extensible-areas/presentation-dropdown-item/types.ts b/src/extensible-areas/presentation-dropdown-item/types.ts index 1553528b..a5363a3c 100644 --- a/src/extensible-areas/presentation-dropdown-item/types.ts +++ b/src/extensible-areas/presentation-dropdown-item/types.ts @@ -15,4 +15,5 @@ export interface PresentationDropdownOptionProps { label: string; icon: string; onClick: () => void; + dataTest?: string; } diff --git a/src/extensible-areas/screenshare-helper-item/component.ts b/src/extensible-areas/screenshare-helper-item/component.ts index 01255aca..93bc9f3f 100644 --- a/src/extensible-areas/screenshare-helper-item/component.ts +++ b/src/extensible-areas/screenshare-helper-item/component.ts @@ -20,6 +20,8 @@ export class ScreenshareHelperButton implements ScreenshareHelperButtonInterface disabled: boolean; + dataTest: string; + position: ScreenshareHelperItemPosition; onClick: (args: ScreenshareHelperButtonOnclickCallback) => void; @@ -37,11 +39,12 @@ export class ScreenshareHelperButton implements ScreenshareHelperButtonInterface * @param hasSeparator - boolean indicating whether the screenshare helper button has separator * (vertical bar) * @param disabled - if true, the screenshare helper button will not be clickable + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ - id, label = '', icon = '', tooltip = '', disabled = true, onClick = () => {}, + id, label = '', icon = '', tooltip = '', disabled = true, dataTest = '', onClick = () => {}, position = ScreenshareHelperItemPosition.TOP_RIGHT, }: ScreenshareHelperButtonProps) { if (id) { @@ -51,6 +54,7 @@ export class ScreenshareHelperButton implements ScreenshareHelperButtonInterface this.icon = icon; this.tooltip = tooltip; this.disabled = disabled; + this.dataTest = dataTest; this.onClick = onClick; this.type = ScreenshareHelperItemType.BUTTON; this.position = position; diff --git a/src/extensible-areas/screenshare-helper-item/types.ts b/src/extensible-areas/screenshare-helper-item/types.ts index 8f907e5c..6448c37f 100644 --- a/src/extensible-areas/screenshare-helper-item/types.ts +++ b/src/extensible-areas/screenshare-helper-item/types.ts @@ -32,4 +32,5 @@ export interface ScreenshareHelperButtonProps { hasSeparator: boolean; position: ScreenshareHelperItemPosition; onClick: (args: ScreenshareHelperButtonOnclickCallback) => void; + dataTest?: string; } diff --git a/src/extensible-areas/user-camera-dropdown-item/component.ts b/src/extensible-areas/user-camera-dropdown-item/component.ts index 62aab540..500ead9e 100644 --- a/src/extensible-areas/user-camera-dropdown-item/component.ts +++ b/src/extensible-areas/user-camera-dropdown-item/component.ts @@ -17,6 +17,8 @@ export class UserCameraDropdownOption implements UserCameraDropdownInterface { icon: string; + dataTest: string; + onClick: (args: OnclickFunctionCallbackArguments) => void; displayFunction?: (args: UserCameraDropdownCallbackFunctionsArguments) => boolean; @@ -27,12 +29,13 @@ export class UserCameraDropdownOption implements UserCameraDropdownInterface { * * @param label - label to be displayed in the option. * @param icon - icon to be displayed in the option. Left side of it. + * @param dataTest - string attribute to be used for testing * @param onClick - function to be called when clicking the button * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5) */ constructor({ - id, label = '', icon = '', onClick = () => {}, + id, label = '', icon = '', dataTest = '', onClick = () => {}, displayFunction = () => true, }: UserCameraDropdownOptionProps) { if (id) { @@ -41,6 +44,7 @@ export class UserCameraDropdownOption implements UserCameraDropdownInterface { this.displayFunction = displayFunction; this.label = label; this.icon = icon; + this.dataTest = dataTest; this.onClick = onClick; this.type = UserCameraDropdownItemType.OPTION; } @@ -55,18 +59,23 @@ export class UserCameraDropdownSeparator implements UserCameraDropdownInterface type: UserCameraDropdownItemType; + dataTest: string; + displayFunction?: (args: UserCameraDropdownCallbackFunctionsArguments) => boolean; /** * Returns object to be used in the setter for User Camera Dropdown. In this case * a separator. * + * @param dataTest - string attribute to be used for testing + * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5) */ constructor({ - displayFunction, + displayFunction, dataTest = '', }: UserCameraDropdownSeparatorProps = { displayFunction: () => true }) { this.displayFunction = displayFunction; + this.dataTest = dataTest; this.type = UserCameraDropdownItemType.SEPARATOR; } diff --git a/src/extensible-areas/user-camera-dropdown-item/types.ts b/src/extensible-areas/user-camera-dropdown-item/types.ts index 6b9e3452..61184b3e 100644 --- a/src/extensible-areas/user-camera-dropdown-item/types.ts +++ b/src/extensible-areas/user-camera-dropdown-item/types.ts @@ -22,6 +22,7 @@ export interface UserCameraDropdownInterface extends PluginProvidedUiItemDescrip export interface UserCameraDropdownSeparatorProps { displayFunction?: (args: UserCameraDropdownCallbackFunctionsArguments) => boolean; + dataTest?: string; } export interface UserCameraDropdownOptionProps { @@ -30,4 +31,5 @@ export interface UserCameraDropdownOptionProps { icon: string; onClick: (args: OnclickFunctionCallbackArguments) => void; displayFunction?: (args: UserCameraDropdownCallbackFunctionsArguments) => boolean; + dataTest?: string; } diff --git a/src/extensible-areas/user-camera-helper-item/component.ts b/src/extensible-areas/user-camera-helper-item/component.ts index a28d91ee..a5c9cbcf 100644 --- a/src/extensible-areas/user-camera-helper-item/component.ts +++ b/src/extensible-areas/user-camera-helper-item/component.ts @@ -23,6 +23,8 @@ export class UserCameraHelperButton implements UserCameraHelperButtonInterface { disabled: boolean; + dataTest: string; + position: UserCameraHelperItemPosition; onClick: (args: UserCameraHelperButtonOnclickCallback) => void; @@ -40,11 +42,12 @@ export class UserCameraHelperButton implements UserCameraHelperButtonInterface { * @param position - position to place the userCamera helper button. * See {@link UserCameraHelperItemPosition} * @param disabled - if true, the userCamera helper button will not be clickable + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ - id, label = '', icon = '', tooltip = '', disabled = true, onClick = () => {}, + id, label = '', icon = '', tooltip = '', disabled = true, dataTest = '', onClick = () => {}, position = UserCameraHelperItemPosition.TOP_RIGHT, displayFunction, }: UserCameraHelperButtonProps) { if (id) { @@ -54,6 +57,7 @@ export class UserCameraHelperButton implements UserCameraHelperButtonInterface { this.icon = icon; this.tooltip = tooltip; this.disabled = disabled; + this.dataTest = dataTest; this.onClick = onClick; this.displayFunction = displayFunction; this.type = UserCameraHelperItemType.BUTTON; diff --git a/src/extensible-areas/user-camera-helper-item/types.ts b/src/extensible-areas/user-camera-helper-item/types.ts index 5a5eb5fc..6474d741 100644 --- a/src/extensible-areas/user-camera-helper-item/types.ts +++ b/src/extensible-areas/user-camera-helper-item/types.ts @@ -41,4 +41,5 @@ export interface UserCameraHelperButtonProps { displayFunction?: (args: UserCameraHelperCallbackFunctionArguments) => boolean; position: UserCameraHelperItemPosition; onClick: (args: UserCameraHelperButtonOnclickCallback) => void; + dataTest?: string; } diff --git a/src/extensible-areas/user-list-dropdown-item/component.ts b/src/extensible-areas/user-list-dropdown-item/component.ts index a217db16..3dd4255f 100644 --- a/src/extensible-areas/user-list-dropdown-item/component.ts +++ b/src/extensible-areas/user-list-dropdown-item/component.ts @@ -25,6 +25,8 @@ export class UserListDropdownOption implements UserListDropdownInterface { allowed: boolean; + dataTest: string; + onClick: () => void; /** @@ -38,11 +40,12 @@ export class UserListDropdownOption implements UserListDropdownInterface { * @param allowed - if false, the use list dropdown will not appear in the dropdown. * @param userId - the userId in which this dropdown option will appear when the user * list item is clicked. + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ - label = '', icon = '', tooltip = '', allowed = true, onClick = () => {}, + label = '', icon = '', tooltip = '', allowed = true, dataTest = '', onClick = () => {}, userId = '', }: UserListDropdownOptionProps) { this.userId = userId; @@ -50,6 +53,7 @@ export class UserListDropdownOption implements UserListDropdownInterface { this.icon = icon; this.tooltip = tooltip; this.allowed = allowed; + this.dataTest = dataTest; this.onClick = onClick; this.type = UserListDropdownItemType.OPTION; } @@ -68,18 +72,22 @@ export class UserListDropdownSeparator implements UserListDropdownInterface { type: UserListDropdownItemType; + dataTest: string; + /** * Returns object to be used in the setter for the User List Dropdown. In this case, * a separator. * * @param userId - the userId in which this dropdown separator will appear when the user * list item is clicked. + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ - constructor({ userId = '', position = UserListDropdownSeparatorPosition.AFTER }: UserListDropdownSeparatorProps) { + constructor({ userId = '', position = UserListDropdownSeparatorPosition.AFTER, dataTest = '' }: UserListDropdownSeparatorProps) { this.userId = userId; this.position = position; + this.dataTest = dataTest; this.type = UserListDropdownItemType.SEPARATOR; } @@ -105,6 +113,8 @@ export class UserListDropdownFixedContentInformation implements UserListDropdown allowed: boolean; + dataTest: string; + /** * Returns object to be used in the setter for the User List Dropdown. In this case, * a button. @@ -118,12 +128,13 @@ export class UserListDropdownFixedContentInformation implements UserListDropdown * @param textColor - Color that the text will have. * @param userId - the userId in which this dropdown information will appear when the user * list item is clicked. + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ id, label = '', icon = '', iconRight = '', allowed = true, - userId = '', textColor = '', + userId = '', textColor = '', dataTest = '', }: UserListDropdownFixedContentInformationProps) { if (id) { this.id = id; @@ -134,6 +145,7 @@ export class UserListDropdownFixedContentInformation implements UserListDropdown this.iconRight = iconRight; this.textColor = textColor; this.allowed = allowed; + this.dataTest = dataTest; this.type = UserListDropdownItemType.FIXED_CONTENT_INFORMATION; } @@ -152,6 +164,8 @@ implements UserListDropdownInterface { type: UserListDropdownItemType; + dataTest: string; + contentFunction: (element: HTMLElement) => void; /** @@ -167,18 +181,20 @@ implements UserListDropdownInterface { * @param textColor - Color that the text will have. * @param userId - the userId in which this dropdown information will appear when the user * list item is clicked. + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ id, contentFunction, allowed = true, - userId = '', + userId = '', dataTest = '', }: UserListDropdownGenericContentInformationProps) { if (id) { this.id = id; } this.userId = userId; this.allowed = allowed; + this.dataTest = dataTest; this.contentFunction = contentFunction; this.type = UserListDropdownItemType.GENERIC_CONTENT_INFORMATION; } @@ -199,6 +215,8 @@ export class UserListDropdownTitleAction implements UserListDropdownInterface { tooltip: string; + dataTest: string; + onClick: (args: UserListDropdownTitleActionOnClickArguments) => void; /** @@ -211,11 +229,12 @@ export class UserListDropdownTitleAction implements UserListDropdownInterface { * It goes on the left side of it. * @param userId - the userId in which this dropdown title action will appear when the user * list item is clicked. + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ - id, icon = '', userId = '', onClick, tooltip, + id, icon = '', userId = '', onClick, tooltip, dataTest = '', }: UserListDropdownTitleActionProps) { if (id) { this.id = id; @@ -223,6 +242,7 @@ export class UserListDropdownTitleAction implements UserListDropdownInterface { this.userId = userId; this.icon = icon; this.tooltip = tooltip; + this.dataTest = dataTest; this.onClick = onClick; this.type = UserListDropdownItemType.TITLE_ACTION; } diff --git a/src/extensible-areas/user-list-dropdown-item/types.ts b/src/extensible-areas/user-list-dropdown-item/types.ts index 55ebaf72..e8ded734 100644 --- a/src/extensible-areas/user-list-dropdown-item/types.ts +++ b/src/extensible-areas/user-list-dropdown-item/types.ts @@ -19,11 +19,13 @@ export interface UserListDropdownOptionProps { allowed: boolean; userId: string; onClick: () => void; + dataTest?: string; } export interface UserListDropdownSeparatorProps { userId: string; position?: UserListDropdownSeparatorPosition; + dataTest?: string; } export interface UserListDropdownGenericContentInformationProps { @@ -31,6 +33,7 @@ export interface UserListDropdownGenericContentInformationProps { contentFunction: (element: HTMLElement) => void; allowed: boolean; userId: string; + dataTest?: string; } export interface UserListDropdownFixedContentInformationProps { @@ -41,6 +44,7 @@ export interface UserListDropdownFixedContentInformationProps { allowed: boolean; userId: string; textColor: string; + dataTest?: string; } export interface UserListDropdownTitleActionOnClickArguments { @@ -53,4 +57,5 @@ export interface UserListDropdownTitleActionProps { icon: string; userId: string; onClick: (args: UserListDropdownTitleActionOnClickArguments) => void; + dataTest?: string; } diff --git a/src/extensible-areas/user-list-item-additional-information/component.ts b/src/extensible-areas/user-list-item-additional-information/component.ts index 22ad7f1d..c831aad3 100644 --- a/src/extensible-areas/user-list-item-additional-information/component.ts +++ b/src/extensible-areas/user-list-item-additional-information/component.ts @@ -15,6 +15,8 @@ export class UserListItemIcon implements UserListItemAdditionalInformationInterf icon: string; + dataTest: string; + /** * Returns object to be used in the setter for the User List Item Additional information Item. * In this case, a icon. @@ -23,17 +25,19 @@ export class UserListItemIcon implements UserListItemAdditionalInformationInterf * It goes on the left side of it. * @param userId - the userId in which this information will appear when the user * list item is clicked. + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ - id, icon = '', userId = '', + id, icon = '', userId = '', dataTest = '', }: UserListItemIconProps) { if (id) { this.id = id; } this.icon = icon; this.userId = userId; + this.dataTest = dataTest; this.type = UserListItemAdditionalInformationType.ICON; } @@ -53,6 +57,8 @@ export class UserListItemLabel implements UserListItemAdditionalInformationInter label: string; + dataTest: string; + /** * Returns object to be used in the setter for the User List Item Additional information Item. * In this case, a label (Information). @@ -62,11 +68,12 @@ export class UserListItemLabel implements UserListItemAdditionalInformationInter * It goes on the left side of it. * @param userId - the userId in which this information will appear when the user * list item is clicked. + * @param dataTest - string attribute to be used for testing * * @returns Object that will be interpreted by the core of Bigbluebutton (HTML5). */ constructor({ - id, icon = '', userId = '', label = '', + id, icon = '', userId = '', label = '', dataTest = '', }: UserListItemLabelProps) { if (id) { this.id = id; @@ -74,6 +81,7 @@ export class UserListItemLabel implements UserListItemAdditionalInformationInter this.icon = icon; this.label = label; this.userId = userId; + this.dataTest = dataTest; this.type = UserListItemAdditionalInformationType.LABEL; } diff --git a/src/extensible-areas/user-list-item-additional-information/types.ts b/src/extensible-areas/user-list-item-additional-information/types.ts index f4ce96c9..73b4ca8b 100644 --- a/src/extensible-areas/user-list-item-additional-information/types.ts +++ b/src/extensible-areas/user-list-item-additional-information/types.ts @@ -15,6 +15,7 @@ export interface UserListItemIconProps { id?: string; userId: string; icon: string; + dataTest?: string; } export interface UserListItemLabelProps { @@ -22,4 +23,5 @@ export interface UserListItemLabelProps { userId: string; icon: string; label: string; + dataTest?: string; } diff --git a/src/learning-analytics-dashboard/commands.ts b/src/learning-analytics-dashboard/commands.ts new file mode 100644 index 00000000..c7bf6b2b --- /dev/null +++ b/src/learning-analytics-dashboard/commands.ts @@ -0,0 +1,81 @@ +import { + LearningAnalyticsDashboardEventDetails, + GenericDataForLearningAnalyticsDashboard, + LearningAnalyticsDashboardUserData, + LearningAnalyticsDashboardDeleteUserData, + ClearLearningAnalyticsDashboardEventDetails, +} from './types'; +import { LearningAnalyticsDashboardEvents } from './enums'; + +export const sendGenericDataForLearningAnalyticsDashboard = ( + data: GenericDataForLearningAnalyticsDashboard, + pluginName: string, +) => { + window.dispatchEvent( + new CustomEvent< + LearningAnalyticsDashboardEventDetails>(LearningAnalyticsDashboardEvents.GENERIC_DATA_SENT, { + detail: { + pluginName, + data, + }, + }), + ); +}; + +export const upsertUserData = ( + data: LearningAnalyticsDashboardUserData, + pluginName: string, + targetUserId?: string, +) => { + window.dispatchEvent( + new CustomEvent< + LearningAnalyticsDashboardEventDetails>( + LearningAnalyticsDashboardEvents.UPSERT_USER_DATA_COMMAND_SENT, + { + detail: { + pluginName, + data, + targetUserId, + }, + }, + ), + ); +}; + +export const deleteUserData = ( + data: LearningAnalyticsDashboardDeleteUserData, + pluginName: string, + targetUserId?: string, +) => { + window.dispatchEvent( + new CustomEvent< + LearningAnalyticsDashboardEventDetails>( + LearningAnalyticsDashboardEvents.DELETE_USER_DATA_COMMAND_SENT, + { + detail: { + pluginName, + data, + targetUserId, + }, + }, + ), + ); +}; + +export const clearAllUsersData = ( + pluginName: string, + cardTitle?: string, +) => { + window.dispatchEvent( + new CustomEvent< + ClearLearningAnalyticsDashboardEventDetails>( + LearningAnalyticsDashboardEvents.CLEAR_ALL_USERS_DATA_COMMAND_SENT, + { + detail: { + pluginName, + cardTitle, + }, + }, + ), + ); +}; diff --git a/src/learning-analytics-dashboard/enums.ts b/src/learning-analytics-dashboard/enums.ts index fe5b568d..e229c343 100644 --- a/src/learning-analytics-dashboard/enums.ts +++ b/src/learning-analytics-dashboard/enums.ts @@ -1,3 +1,6 @@ export enum LearningAnalyticsDashboardEvents { GENERIC_DATA_SENT = 'GENERIC_DATA_FOR_LEARNING_ANALYTICS_DASHBOARD_SENT', + UPSERT_USER_DATA_COMMAND_SENT = 'UPSERT_USER_DATA_COMMAND_FOR_LEARNING_ANALYTICS_DASHBOARD_SENT', + DELETE_USER_DATA_COMMAND_SENT = 'DELETE_USER_DATA_COMMAND_FOR_LEARNING_ANALYTICS_DASHBOARD_SENT', + CLEAR_ALL_USERS_DATA_COMMAND_SENT = 'CLEAR_ALL_USERS_DATA_COMMAND_SENT_COMMAND_FOR_LEARNING_ANALYTICS_DASHBOARD_SENT', } diff --git a/src/learning-analytics-dashboard/hooks.ts b/src/learning-analytics-dashboard/hooks.ts deleted file mode 100644 index 1a1a3766..00000000 --- a/src/learning-analytics-dashboard/hooks.ts +++ /dev/null @@ -1,20 +0,0 @@ -import { - LearningAnalyticsDashboardEventDetails, - GenericDataForLearningAnalyticsDashboard, -} from './types'; -import { LearningAnalyticsDashboardEvents } from './enums'; - -export const sendGenericDataForLearningAnalyticsDashboard = ( - data: GenericDataForLearningAnalyticsDashboard, - pluginName: string, -) => { - window.dispatchEvent( - new CustomEvent< - LearningAnalyticsDashboardEventDetails>(LearningAnalyticsDashboardEvents.GENERIC_DATA_SENT, { - detail: { - pluginName, - data, - }, - }), - ); -}; diff --git a/src/learning-analytics-dashboard/types.ts b/src/learning-analytics-dashboard/types.ts index a93c426d..139e93cc 100644 --- a/src/learning-analytics-dashboard/types.ts +++ b/src/learning-analytics-dashboard/types.ts @@ -1,13 +1,70 @@ +// Deprecated Send data function export interface GenericDataForLearningAnalyticsDashboard { cardTitle: string; columnTitle: string; value: string; } +export type SendGenericDataForLearningAnalyticsDashboard = ( + data: GenericDataForLearningAnalyticsDashboard) => void; + +// Upsert function +export interface LearningAnalyticsDashboardUserData { + cardTitle: string; + columnTitle: string; + value: string; +} + +export type UpsertUserDataFunction = ( + data: LearningAnalyticsDashboardUserData, + targetUserId?: string, +) => void; + +// Delete function +export interface LearningAnalyticsDashboardDeleteUserData { + cardTitle: string; + columnTitle: string; +} + +export type DeleteUserDataFunction = ( + data: LearningAnalyticsDashboardDeleteUserData, + targetUserId?: string, +) => void; + +export type ClearUsersDataFunction = (cardTitle?: string) => void; + +// General typing. export interface LearningAnalyticsDashboardEventDetails { pluginName: string; - data: GenericDataForLearningAnalyticsDashboard; + data: GenericDataForLearningAnalyticsDashboard + | LearningAnalyticsDashboardUserData | LearningAnalyticsDashboardDeleteUserData; + targetUserId?: string; } -export type SendGenericDataForLearningAnalyticsDashboard = ( - data: GenericDataForLearningAnalyticsDashboard) => void; +export interface ClearLearningAnalyticsDashboardEventDetails { + pluginName: string; + cardTitle?: string; +} + +export interface LearningAnalyticsDashboardWrapperObject { + /** + * Updates or insert a generic data entry in the learning dashboard for a target user + * (if target user is not passed, current user will be considered); + * + * @param data Data to insert or update + * @targetUserId string representing the internal userId of the target user (Optional) + */ + upsertUserData: UpsertUserDataFunction; + /** + * Deletes generic data entry for target user (if target user is not passed, + * current user will be considered). + * + * @param data Data to be deleted + * @targetUserId string representing the internal userId of the target user (Optional) + */ + deleteUserData: DeleteUserDataFunction; + /** + * Clears all Users Data for a specific plugin. (No arguments required) + */ + clearAllUsersData: ClearUsersDataFunction; +} diff --git a/src/utils/logger/logger.ts b/src/utils/logger/logger.ts index feb2e4be..6cd28f95 100644 --- a/src/utils/logger/logger.ts +++ b/src/utils/logger/logger.ts @@ -1,7 +1,12 @@ -import { createLogger, INFO, stdSerializers } from 'browser-bunyan'; +import { + createLogger, INFO, stdSerializers, Logger, StreamOptions, +} from 'browser-bunyan'; import { ConsoleFormattedStream } from '@browser-bunyan/console-formatted-stream'; +import { BbbPluginSdk } from '../../core'; -const pluginLogger = createLogger({ +const uuid = document.currentScript?.getAttribute('uuid') || 'root'; + +export const fallbackLogger: Logger = createLogger({ name: 'PluginLogger', streams: [ { @@ -9,9 +14,57 @@ const pluginLogger = createLogger({ stream: new ConsoleFormattedStream(), }, ], - serializers: stdSerializers, src: true, }); +function isValidLogger(obj: unknown): obj is Logger { + return ( + typeof obj === 'object' + && obj !== null + && typeof (obj as Logger).info === 'function' + && typeof (obj as Logger).error === 'function' + ); +} + +function getLogger(): Logger { + try { + const api = BbbPluginSdk.getPluginApi(uuid); + const logger = api?.logger; + + if (isValidLogger(logger)) { + return logger; + } + return fallbackLogger; + } catch (err) { + return fallbackLogger; + } +} + +type LoggerArgument = string | Error | Record; + +function logWith(level: T, ...args: LoggerArgument[]): void { + const logger = getLogger(); + const method = logger[level] as (...params: LoggerArgument[]) => void; + + try { + method.call(logger, ...args); + } catch (err) { + // eslint-disable-next-line no-console + console.error(`[pluginLogger.${String(level)}] fallback`, err, ...args); + } +} + +const pluginLogger = { + error: (...args: LoggerArgument[]) => logWith('error', ...args), + warn: (...args: LoggerArgument[]) => logWith('warn', ...args), + info: (...args: LoggerArgument[]) => logWith('info', ...args), + debug: (...args: LoggerArgument[]) => logWith('debug', ...args), + trace: (...args: LoggerArgument[]) => logWith('trace', ...args), + addStream(stream: StreamOptions) { + const logger = getLogger(); + logger.addStream.call(logger, stream); + }, +} as Logger; + export default pluginLogger;