A platform for community discussion. Free, open, simple.
UX: improve Zoom livestream on mobile and small screens (#42584)
Kris54f57d033fcf
diff --git a/plugins/discourse-events/app/controllers/discourse_calendar/livestream_controller.rb b/plugins/discourse-events/app/controllers/discourse_calendar/livestream_controller.rbindex 0e1c9c6ef6b..bfa9a4bf3ec 100644--- a/plugins/discourse-events/app/controllers/discourse_calendar/livestream_controller.rb+++ b/plugins/discourse-events/app/controllers/discourse_calendar/livestream_controller.rb@@ -5,6 +5,48 @@ module DiscourseCalendarrequires_plugin DiscourseCalendar::PLUGIN_NAMErequires_login+ skip_before_action :check_xhr, only: [:zoom_frame]++ # Kept in step with the version the app itself loads the SDK at, in+ # `lib/load-zoom-meeting-sdk.js`.+ ZOOM_SDK_VERSION = "6.2.0"+ ZOOM_SDK_CDN = "https://source.zoom.us"++ # Hosts Zoom's full-page meeting view for embedding. The meeting sizes+ # itself to the window it is in, so it is given a window of its own to+ # render into and the page around it stays free for other content.+ def zoom_frame+ topic = Topic.find_by(id: params[:topic_id])++ # Not found rather than forbidden, and the same for a topic that is not+ # there as for one that may not be seen: the signature this page goes on+ # to ask for answers that way too, and between them they should not say+ # more about a topic than the other does.+ raise Discourse::NotFound if topic.blank? || !guardian.can_see?(topic)+ raise Discourse::NotFound if !SiteSetting.livestream_zoom_enabled++ # The page is served outside the app, so it has none of the site's colors+ # to hand. Only the one the button is built from is needed.+ @accent_color = "##{ColorScheme.hex_for_name("tertiary") || "0088cc"}"++ signature_params = { topic_id: topic.id }+ # TODO (martin) showzoom is for testing only, remove before merge+ signature_params[:ignore_timeframe] = true if params[:showzoom].present?++ @config = {+ cdn: ZOOM_SDK_CDN,+ sdkVersion: ZOOM_SDK_VERSION,+ signatureUrl: "#{frame_base_path}/signature.json?#{signature_params.to_query}",+ # Zoom navigates this window when the user leaves, which is the only+ # notice the page around it gets that the meeting is over.+ leaveUrl:+ "#{Discourse.base_url_no_prefix}#{frame_base_path}/frame?topic_id=#{topic.id}&left=1",+ hasLeft: params[:left].present?,+ }++ render layout: false+ end+def prepare_zoom_signatureDiscourseCalendar::Livestream::PrepareZoomJoin.call(service_params.deep_merge(params: { topic_id: params[:topic_id] }),@@ -17,5 +59,11 @@ module DiscourseCalendaron_failure { raise Discourse::NotFound }endend++ private++ def frame_base_path+ "#{Discourse.base_path}/discourse-calendar/livestream/zoom"+ endendenddiff --git a/plugins/discourse-events/app/views/discourse_calendar/livestream/zoom_frame.html.erb b/plugins/discourse-events/app/views/discourse_calendar/livestream/zoom_frame.html.erbnew file mode 100644index 00000000000..db50024b726--- /dev/null+++ b/plugins/discourse-events/app/views/discourse_calendar/livestream/zoom_frame.html.erb@@ -0,0 +1,286 @@+<!DOCTYPE html>+<html lang="<%= I18n.locale %>">+ <head>+ <meta charset="utf-8">+ <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">+ <meta name="robots" content="noindex">+ <title><%= t("discourse_calendar.livestream.zoom.frame_title") %></title>+ <style>+ html,+ body {+ height: 100%;+ margin: 0;+ overflow: hidden;+ background: #000;+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto,+ "Helvetica Neue", Arial, sans-serif;+ }++ /* The whole frame takes the tap, so there is no aiming to be done, while+ what is drawn inside it is button-sized. */+ #join {+ position: absolute;+ inset: 0;+ display: flex;+ align-items: center;+ justify-content: center;+ width: 100%;+ height: 100%;+ padding: 0;+ border: 0;+ background: transparent;+ font: inherit;+ cursor: pointer;+ -webkit-tap-highlight-color: transparent;+ }++ #join span {+ display: inline-flex;+ align-items: center;+ gap: 0.5em;+ padding: 0.7em 1.4em;+ border-radius: 6px;+ background: <%= @accent_color %>;+ color: #fff;+ font-size: 1.05em;+ font-weight: 600;+ line-height: 1;+ box-shadow: 0 2px 6px rgb(0 0 0 / 45%);+ }++ #join:active span {+ transform: translateY(1px);+ }++ #join[disabled] {+ cursor: default;+ }++ #join[disabled] span {+ opacity: 0.6;+ box-shadow: none;+ }++ #join svg {+ width: 1.1em;+ height: 1.1em;+ fill: currentcolor;+ }+ </style>+ </head>+ <body>+ <%# Joining has to start from a tap taken inside this document: the SDK asks+ for the microphone, and a mobile browser only prompts for it while the+ page holds a user activation, which does not survive the navigation+ here from the topic.++ Asking earlier, from the tap that navigates here, does not help. Safari+ scopes a microphone grant to the document that was given it, so the+ meeting is asked again regardless and the user is prompted twice. %>+ <button id="join" type="button">+ <span>+ <svg viewBox="0 0 576 512" aria-hidden="true"><path d="M336 64H48C21.5 64 0 85.5 0 112v288c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48V112c0-26.5-21.5-48-48-48zm212.2 25.7L416 181.8v148.4l132.2 92.1c15.9 11 37.8-.2 37.8-19.7V109.4c0-19.5-21.9-30.7-37.8-19.7z"/></svg>+ <%= t("discourse_calendar.livestream.zoom.frame_join") %>+ </span>+ </button>++ <script nonce="<%= csp_nonce_placeholder %>">+ window.zoomFrameConfig = <%= raw @config.to_json %>;+ window.zoomFrameConfig.joiningLabel = "<%= j t("discourse_calendar.livestream.zoom.frame_joining") %>";+ </script>+ <script nonce="<%= csp_nonce_placeholder %>">+ (function () {+ const config = window.zoomFrameConfig;+ // Vendored dependencies of the SDK: React must precede ReactDOM, and+ // Redux precede its thunk.+ const DEPENDENCIES = [+ "react",+ "react-dom",+ "redux",+ "redux-thunk",+ "lodash",+ ];++ // `meetingStatus` in the SDK's own numbering: 1 connecting, 2 connected,+ // 3 disconnected, 4 reconnecting.+ const MEETING_DISCONNECTED = 3;++ // `state` rather than `type`: the page this is embedded in is not the+ // only thing listening to the window, and `type` is a common enough key+ // in other postMessage protocols to be taken for one of theirs.+ function post(state) {+ window.parent?.postMessage(+ { source: "discourse-zoom-frame", state },+ window.location.origin+ );+ }++ function loadScript(src) {+ return new Promise(function (resolve, reject) {+ const element = document.createElement("script");+ element.src = src;+ element.onload = resolve;+ element.onerror = function () {+ reject(new Error("Failed to load " + src));+ };+ document.head.appendChild(element);+ });+ }++ // Whether the microphone is ours to use, which is also how it is asked+ // for. Called from a tap it raises the prompt; called without one it+ // settles what is already granted, since a browser will not prompt+ // outside a user's activation — it just refuses.+ //+ // The grant is this document's, which is the one the SDK asks from, so+ // it inherits it and the stream itself is no longer needed here.+ async function microphoneReady() {+ try {+ const stream = await navigator.mediaDevices.getUserMedia({+ audio: true,+ });+ stream.getTracks().forEach(function (track) {+ track.stop();+ });+ return true;+ } catch (error) {+ // eslint-disable-next-line no-console+ console.warn("Microphone unavailable for Zoom meeting", error);+ return false;+ }+ }++ async function join() {+ for (const dependency of DEPENDENCIES) {+ await loadScript(+ config.cdn + "/" + config.sdkVersion + "/lib/vendor/" + dependency + ".min.js"+ );+ }+ await loadScript(+ config.cdn + "/zoom-meeting-" + config.sdkVersion + ".min.js"+ );++ const response = await fetch(config.signatureUrl, {+ credentials: "same-origin",+ headers: {+ "Accept": "application/json",+ "X-Requested-With": "XMLHttpRequest",+ },+ });++ if (!response.ok) {+ throw new Error("Signature request failed: " + response.status);+ }++ const payload = await response.json();+ const ZoomMtg = window.ZoomMtg;++ ZoomMtg.preLoadWasm();+ ZoomMtg.prepareWebSDK();+ ZoomMtg.i18n.load("en-US");+ ZoomMtg.i18n.reload("en-US");++ await new Promise(function (resolve, reject) {+ ZoomMtg.init({+ leaveUrl: config.leaveUrl,+ patchJsMedia: true,+ disableCallOut: true,+ success: resolve,+ error: reject,+ });+ });++ // Leaving does not always take the window to `leaveUrl`: ending a+ // meeting, being removed from one, or losing it altogether leaves+ // Zoom sitting on a screen of its own with nothing on it to act on.+ // The status is reported either way, so it is what the page around+ // the frame is told by.+ ZoomMtg.inMeetingServiceListener("onMeetingStatus", function (status) {+ if (status && status.meetingStatus === MEETING_DISCONNECTED) {+ post("left");+ }+ });++ await new Promise(function (resolve, reject) {+ ZoomMtg.join({+ signature: payload.signature,+ sdkKey: payload.sdk_key,+ meetingNumber: payload.meeting_number,+ passWord: payload.password || "",+ userName: payload.user_name,+ userEmail: payload.user_email,+ success: resolve,+ error: reject,+ });+ });+ }++ const joinButton = document.getElementById("join");++ // Zoom left the meeting by navigating this window to `leaveUrl`, so+ // there is nothing to join: the page around the frame decides where the+ // user goes next.+ if (config.hasLeft) {+ joinButton.remove();+ post("left");+ return;+ }++ let starting = false;++ async function start() {+ if (starting) {+ return;+ }++ starting = true;+ joinButton.disabled = true;+ joinButton.querySelector("span").textContent = config.joiningLabel;++ try {+ await join();+ joinButton.remove();+ } catch (error) {+ // eslint-disable-next-line no-console+ console.error("Error joining Zoom meeting", error);+ joinButton.remove();+ post("error");+ }+ }++ joinButton.addEventListener("click", async function () {+ await microphoneReady();+ start();+ });++ // Whether the microphone has already been granted, asked in the one way+ // that cannot itself raise a prompt. Requesting the microphone to find+ // out would ask a second time for something the page before this one+ // has often just been given.+ async function microphoneAlreadyGranted() {+ try {+ const status = await navigator.permissions.query({+ name: "microphone",+ });++ return status.state === "granted";+ } catch {+ // Not every browser will answer for the microphone. Saying no+ // leaves the button to ask, which is always safe.+ return false;+ }+ }++ // A browser that carries a microphone grant between documents has+ // nothing left to ask, so the meeting is joined outright and the button+ // is never shown. Safari is not one of them: it grants per document,+ // and there the button is what asks, from a tap.+ microphoneAlreadyGranted().then(function (granted) {+ if (granted) {+ start();+ }+ });+ })();+ </script>+ </body>+</html>diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjsindex 5a0b89c7772..6f3c9fdfce5 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/livestream/embeddable-chat-channel.gjs@@ -65,7 +65,13 @@ export default class EmbedableChatChannel extends Component {this.activeChannel.currentUserMembership = membership;}+ // Inline means the channel is laid out by its parent rather than pinned over+ // the page, so neither the visibility toggle nor a way to dismiss it applies.get showCloseButton() {+ if (this.args.inline) {+ return false;+ }+return this.args.onClose || !this.embeddableChat.isMobileModal;}@@ -82,9 +88,13 @@ export default class EmbedableChatChannel extends Component {<template><divid="custom-chat-container"- class={{dConcatClass- (if this.embeddableChat.isMobileChatVisible "mobile")- (unless this.embeddableChat.isMobileModal "no-modal-mobile")+ class={{if+ @inline+ "inline"+ (dConcatClass+ (if this.embeddableChat.isMobileChatVisible "mobile")+ (unless this.embeddableChat.isMobileModal "no-modal-mobile")+ )}}{{this.updateChannel}}>diff --git a/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-page.gjs b/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-page.gjsindex be7967ca225..ddd609f846f 100644--- a/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-page.gjs+++ b/plugins/discourse-events/assets/javascripts/discourse/components/livestream/zoom-page.gjs@@ -5,35 +5,37 @@ import { action } from "@ember/object";import { service } from "@ember/service";import { modifier } from "ember-modifier";import bodyClass from "discourse/helpers/body-class";+import { bind } from "discourse/lib/decorators";import getURL from "discourse/lib/get-url";import { wantsNewWindow } from "discourse/lib/intercept-click";import DButton from "discourse/ui-kit/d-button";+import dConcatClass from "discourse/ui-kit/helpers/d-concat-class";import { i18n } from "discourse-i18n";import DiscoursePostEvent from "discourse/plugins/discourse-events/discourse/components/discourse-post-event";import DiscoursePostEventEvent from "discourse/plugins/discourse-events/discourse/models/discourse-post-event-event";-import fetchZoomJoinPayload from "../../lib/fetch-zoom-join-payload";-import { loadZoomMeetingSdk } from "../../lib/load-zoom-meeting-sdk";+import zoomFrameUrl from "../../lib/zoom-frame-url";import { isWithinEventTimeframe } from "../../models/discourse-post-event-event";-import MobileEmbeddableChatModal from "./modal/mobile-embeddable-chat-modal";+import dismissKeyboardOnChatSend from "../../modifiers/dismiss-keyboard-on-chat-send";+import zoomPageViewportFit from "../../modifiers/zoom-page-viewport-fit";+import EmbeddableChatChannel from "./embeddable-chat-channel";++const FRAME_MESSAGE_SOURCE = "discourse-zoom-frame";export default class LivestreamZoomPage extends Component {- @service modal;+ @service currentUser;+ @service embeddableChat;@service siteSettings;@tracked errorMessage;- // Plain (non-tracked) guard so the modifier can read and set it within the- // same render without triggering a tracked-property backtracking assertion.- // It is only used to ensure the SDK is set up once, never rendered.- hasLoaded = false;+ // Bumped to reload the frame, which is what a retry amounts to: the meeting+ // is set up by the page inside it, from scratch, on load.+ @tracked joinAttempt = 0;- setupZoom = modifier(async () => {- if (this.hasLoaded || !this.canJoinNow) {- return;- }+ listenForFrame = modifier(() => {+ window.addEventListener("message", this.onFrameMessage);- this.hasLoaded = true;- await this.loadZoom();+ return () => window.removeEventListener("message", this.onFrameMessage);});get post() {@@ -67,81 +69,61 @@ export default class LivestreamZoomPage extends Component {return this.event?.livestreamUrl;}- get mobileLeaveUrl() {+ get topicUrl() {return getURL(- `/t/${this.args.topic.slug}/${this.args.topic.id}/zoom?zoom_left=1`+ this.args.topic.url || `/t/${this.args.topic.slug}/${this.args.topic.id}`);}- get retryZoomRoute() {- return getURL(`/t/${this.args.topic.slug}/${this.args.topic.id}/zoom`);+ // Zoom's meeting view sizes itself to the window it is in, so it is given one+ // of its own. Inside the frame the viewport is the frame, which leaves the+ // page free to put chat below it.+ get frameUrl() {+ return zoomFrameUrl({+ topicId: this.args.topic.id,+ attempt: this.joinAttempt,+ // TODO (martin) showzoom is for testing only, remove before merge+ ignoreTimeframe: new URLSearchParams(window.location.search).get(+ "showzoom"+ ),+ });}- get topicUrl() {- return getURL(- this.args.topic.url || `/t/${this.args.topic.slug}/${this.args.topic.id}`+ get canRenderChat() {+ return (+ this.siteSettings.chat_enabled &&+ this.currentUser &&+ this.embeddableChat.userCanChat &&+ this.chatChannelId);}- get returnedFromZoom() {- return new URLSearchParams(window.location.search).has("zoom_left");+ get chatChannelId() {+ return this.args.topic?.chat_channel_id;}- @action- async loadZoom() {- if (this.returnedFromZoom) {- this.errorMessage = i18n("discourse_calendar.livestream.zoom.load_error");+ @bind+ onFrameMessage(event) {+ if (+ event.origin !== window.location.origin ||+ event.data?.source !== FRAME_MESSAGE_SOURCE+ ) {return;}- try {- const payload = await fetchZoomJoinPayload(this.args.topic.id);- const ZoomMtg = await loadZoomMeetingSdk();-- ZoomMtg.preLoadWasm();- ZoomMtg.prepareWebSDK();- ZoomMtg.i18n.load("en-US");- ZoomMtg.i18n.reload("en-US");-- await new Promise((resolve, reject) => {- ZoomMtg.init({- leaveUrl: this.mobileLeaveUrl,- patchJsMedia: true,- disableCallOut: true,- success: resolve,- error: reject,- });- });-- await new Promise((resolve, reject) => {- ZoomMtg.join({- signature: payload.signature,- sdkKey: payload.sdk_key,- meetingNumber: payload.meeting_number,- passWord: payload.password || "",- userName: payload.user_name,- userEmail: payload.user_email,- success: resolve,- error: reject,- });- });- } catch {+ if (event.data.state === "left") {+ // This page is only ever the meeting, so a user who leaves it has+ // nowhere to go but back to the topic the webinar belongs to.+ window.location.assign(this.topicUrl);+ } else if (event.data.state === "error") {this.errorMessage = i18n("discourse_calendar.livestream.zoom.load_error");}}- get canOpenChat() {- return this.args.topic?.chat_channel_id && this.siteSettings.chat_enabled;- }-- @action- openChat() {- this.modal.show(MobileEmbeddableChatModal);- }-@actionretryZoom() {- window.location.assign(this.retryZoomRoute);+ this.errorMessage = null;+ this.joinAttempt++;}@action@@ -156,7 +138,13 @@ export default class LivestreamZoomPage extends Component {<template>{{bodyClass "discourse-calendar-livestream-zoom-full"}}- <div class="discourse-calendar-livestream-zoom-page">+ <div+ class={{dConcatClass+ "discourse-calendar-livestream-zoom-page"+ (if this.canRenderChat "--with-chat")+ }}+ {{zoomPageViewportFit}}+ >{{#if this.canJoinNow}}{{#if this.errorMessage}}<div class="discourse-calendar-livestream-zoom-page__fallback">@@ -168,21 +156,22 @@ export default class LivestreamZoomPage extends Component {@icon="up-right-from-square"/>- {{#if this.returnedFromZoom}}- <DButton- @action={{this.retryZoom}}- @label="discourse_calendar.livestream.zoom.join"- @icon="video"- class="btn-primary"- />- {{/if}}+ <DButton+ @action={{this.retryZoom}}+ @label="discourse_calendar.livestream.zoom.join"+ @icon="video"+ class="btn-primary"+ /></div>{{/if}}- <div+ <iframeclass="discourse-calendar-livestream-zoom-page__frame"- {{this.setupZoom}}- ></div>+ src={{this.frameUrl}}+ title={{i18n "discourse_calendar.livestream.zoom.frame_title"}}+ allow="camera; microphone; autoplay; display-capture; fullscreen"+ {{this.listenForFrame}}+ ></iframe>{{else}}<div class="discourse-calendar-livestream-zoom-page__waiting-wrapper"><p class="discourse-calendar-livestream-zoom-page__waiting">@@ -205,13 +194,16 @@ export default class LivestreamZoomPage extends Component {{{/if}}- {{#if this.canOpenChat}}- <DButton- class="discourse-calendar-livestream-zoom-page__chat-button btn-primary"- @action={{this.openChat}}- @label="discourse_calendar.livestream.zoom.chat"- @icon="comments"- />+ {{#if this.canRenderChat}}+ <div+ class="discourse-calendar-livestream-zoom-page__chat"+ {{dismissKeyboardOnChatSend}}+ >+ <EmbeddableChatChannel+ @chatChannelId={{this.chatChannelId}}+ @inline={{true}}+ />+ </div>{{/if}}</div></template>diff --git a/plugins/discourse-events/assets/javascripts/discourse/lib/load-zoom-meeting-sdk.js b/plugins/discourse-events/assets/javascripts/discourse/lib/load-zoom-meeting-sdk.jsindex 0599bcdcff1..ca43b70b30f 100644--- a/plugins/discourse-events/assets/javascripts/discourse/lib/load-zoom-meeting-sdk.js+++ b/plugins/discourse-events/assets/javascripts/discourse/lib/load-zoom-meeting-sdk.js@@ -4,10 +4,14 @@ import loadScript from "discourse/lib/load-script";// stays out of Discourse's build and Zoom serves matching wasm/AV assets from// the same origin. Bump this to adopt a newer SDK release.// https://developers.zoom.us/docs/meeting-sdk/web/get-started/+//+// The page the meeting is embedded in loads the SDK for itself and pins the+// same version in `LivestreamController::ZOOM_SDK_VERSION`, which a bump here+// has to carry to.const ZOOM_SDK_VERSION = "6.2.0";const CDN = "https://source.zoom.us";-// Shared by both views; React must precede ReactDOM, and Redux precede its thunk.+// React must precede ReactDOM, and Redux precede its thunk.const DEPENDENCIES = ["react", "react-dom", "redux", "redux-thunk", "lodash"];async function loadDependencies() {@@ -16,13 +20,6 @@ async function loadDependencies() {}}-// Client View (`ZoomMtg`) - renders the full Zoom client UI.-export async function loadZoomMeetingSdk() {- await loadDependencies();- await loadScript(`${CDN}/zoom-meeting-${ZOOM_SDK_VERSION}.min.js`);- return window.ZoomMtg;-}-// Component View (`ZoomMtgEmbedded`) - embeds Zoom inside a container element.export async function loadZoomMeetingSdkEmbedded() {await loadDependencies();diff --git a/plugins/discourse-events/assets/javascripts/discourse/lib/zoom-frame-url.js b/plugins/discourse-events/assets/javascripts/discourse/lib/zoom-frame-url.jsnew file mode 100644index 00000000000..5846f1452d9--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/lib/zoom-frame-url.js@@ -0,0 +1,19 @@+import getURL from "discourse/lib/get-url";++// The meeting runs in a window of its own, served by the page this addresses.+// `attempt` is what a retry changes: the frame sets the meeting up as it loads,+// so a new URL is how it is asked to do that again.+export default function zoomFrameUrl({+ topicId,+ attempt = 0,+ ignoreTimeframe,+}) {+ const params = new URLSearchParams({ topic_id: topicId, attempt });++ // TODO (martin) showzoom is for testing only, remove before merge+ if (ignoreTimeframe) {+ params.set("showzoom", "1");+ }++ return getURL(`/discourse-calendar/livestream/zoom/frame?${params}`);+}diff --git a/plugins/discourse-events/assets/javascripts/discourse/modifiers/dismiss-keyboard-on-chat-send.js b/plugins/discourse-events/assets/javascripts/discourse/modifiers/dismiss-keyboard-on-chat-send.jsnew file mode 100644index 00000000000..617cbc86dee--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/modifiers/dismiss-keyboard-on-chat-send.js@@ -0,0 +1,24 @@+import { modifier } from "ember-modifier";++export default modifier((element) => {+ const onClick = (event) => {+ if (!event.target.closest("button.-send")) {+ return;+ }++ // Only a keyboard that is covering the meeting is worth giving focus up+ // for. The page's own attribute rather than core's `keyboard-visible`+ // class: that is set from the window's height against the viewport's, which+ // only part company on a browser that lets the keyboard overlay the page.+ // Android shrinks the window to fit one, leaving the class unset.+ if (!element.closest("[data-keyboard-open]")) {+ return;+ }++ element.querySelector(".chat-composer__input")?.blur();+ };++ element.addEventListener("click", onClick);++ return () => element.removeEventListener("click", onClick);+});diff --git a/plugins/discourse-events/assets/javascripts/discourse/modifiers/zoom-page-viewport-fit.js b/plugins/discourse-events/assets/javascripts/discourse/modifiers/zoom-page-viewport-fit.jsnew file mode 100644index 00000000000..1a28586f20f--- /dev/null+++ b/plugins/discourse-events/assets/javascripts/discourse/modifiers/zoom-page-viewport-fit.js@@ -0,0 +1,152 @@+import { cancel } from "@ember/runloop";+import { modifier } from "ember-modifier";+import discourseDebounce from "discourse/lib/debounce";++// The viewport is resized repeatedly while the keyboard animates, and every one+// of those is a size the page should not be laid out at.+const SETTLE_DELAY = 50;++// Long enough after a keyboard arrives for it to have taken its space and the+// page to have been laid out around it, and equally for one to have finished+// leaving.+const KEYBOARD_SETTLE_DELAY = 400;++function isTextEntry(node) {+ return !!node?.matches?.("input, textarea, [contenteditable='true']");+}++// The meeting and chat divide up exactly what the viewport is showing, which+// only measuring can establish: the header and whatever spacing the layout+// applies above them all come out of the height they have to share.+//+// The measurements are published as custom properties for the stylesheet to lay+// the page out from, and a keyboard is announced with an attribute. Scrolling+// is left alone but for putting the composer in view when one opens.+export default modifier((element) => {+ const viewport = window.visualViewport;++ if (!viewport) {+ return;+ }++ // Whether the composer holds focus is the one signal for the keyboard that+ // cannot feed back into itself. Measuring the keyboard against the window+ // instead does: anything that scrolls the page retracts the browser's+ // toolbars, which resizes the viewport, which reads as the keyboard closing.+ let editing = false;+ let restingViewportHeight = viewport.height;+ let hasScrolledToComposer = false;+ let resizeHandler = null;+ let composerHandler = null;+ let settleHandler = null;++ // With a keyboard up the page becomes a scroller of its own, pinned over what+ // is visible, and this puts the composer at the end of it. Scrolling the+ // page's own contents is what makes the position reliable: the document's+ // scrolling stops at the layout viewport, which the keyboard is allowed to+ // overlap, so its end can never reach the keyboard's top edge.+ const showComposer = () => {+ composerHandler = null;++ if (editing) {+ element.scrollTop = element.scrollHeight;+ }+ };++ const apply = () => {+ // Held across keyboard states: the meeting is sized from it, and+ // remeasuring while a keyboard covers part of the page would resize the+ // meeting to fit what is left, which is the one thing this is meant to+ // avoid.+ if (!editing) {+ restingViewportHeight = viewport.height;+ }++ const keyboardHeight = Math.max(0, restingViewportHeight - viewport.height);+ const keyboardIsOpen = editing && keyboardHeight > 0;++ // Announced before anything is measured against it. A keyboard takes the+ // page out of the document's flow and gives it back afterwards, and an+ // offset read while it is still in the arrangement it is leaving describes+ // where the page was rather than where it is about to be.+ //+ // A data attribute rather than a class: the class attribute belongs to the+ // template, which would drop anything set on it here the next time it+ // renders.+ if (keyboardIsOpen) {+ element.dataset.keyboardOpen = "true";+ } else {+ delete element.dataset.keyboardOpen;+ }++ const offsetFromDocumentTop =+ element.getBoundingClientRect().top + window.scrollY;+ const resting = restingViewportHeight - offsetFromDocumentTop;++ element.style.setProperty(+ "--livestream-zoom-resting-height",+ `${resting}px`+ );+ element.style.setProperty(+ "--livestream-zoom-visible-height",+ `${viewport.height}px`+ );++ // Where the visible area begins within the viewport a fixed element is+ // positioned against. A keyboard can leave the two with different tops.+ element.style.setProperty(+ "--livestream-zoom-visible-top",+ `${viewport.offsetTop}px`+ );++ if (keyboardIsOpen && !hasScrolledToComposer) {+ hasScrolledToComposer = true;+ composerHandler = discourseDebounce(showComposer, KEYBOARD_SETTLE_DELAY);+ }++ if (!keyboardIsOpen) {+ cancel(composerHandler);+ composerHandler = null;+ hasScrolledToComposer = false;+ }+ };++ const onViewportResize = () => {+ resizeHandler = discourseDebounce(apply, SETTLE_DELAY);+ };++ const onFocusChange = (event) => {+ if (!isTextEntry(event.target)) {+ return;+ }++ editing = event.type === "focusin";+ apply();++ // A keyboard on its way out resizes the viewport as it goes, and the last+ // of those can still arrive before it has finished: the page would be+ // measured against a viewport that is still growing, and nothing would come+ // afterwards to correct it. One more measurement once it is done settles+ // the page at the size it actually ended up with.+ if (!editing) {+ settleHandler = discourseDebounce(apply, KEYBOARD_SETTLE_DELAY);+ }+ };++ apply();++ viewport.addEventListener("resize", onViewportResize);+ window.addEventListener("orientationchange", onViewportResize);+ element.addEventListener("focusin", onFocusChange);+ element.addEventListener("focusout", onFocusChange);++ return () => {+ cancel(resizeHandler);+ cancel(composerHandler);+ cancel(settleHandler);+ viewport.removeEventListener("resize", onViewportResize);+ window.removeEventListener("orientationchange", onViewportResize);+ element.removeEventListener("focusin", onFocusChange);+ element.removeEventListener("focusout", onFocusChange);+ };+});diff --git a/plugins/discourse-events/assets/stylesheets/common/livestream.scss b/plugins/discourse-events/assets/stylesheets/common/livestream.scssindex f725a55e987..a78e26a3150 100644--- a/plugins/discourse-events/assets/stylesheets/common/livestream.scss+++ b/plugins/discourse-events/assets/stylesheets/common/livestream.scss@@ -1,3 +1,5 @@+@use "lib/viewport";+body.chat-enabled.livestream-topic.confirmed-event-assistance {.topic-navigation {display: none;@@ -104,13 +106,65 @@ body.chat-enabled.livestream-topic.confirmed-event-assistance {}}+// The meeting is the page here, so it is given the viewport below the header+// whole: anything the layout adds around it is height the page cannot have,+// and overflowing it drags the meeting under the sticky header.+body.discourse-calendar-livestream-zoom-full {+ #main-outlet {+ padding: 0 !important; // override horizon styles+ }++ #main-container,+ .powered-by-discourse {+ display: none;+ }+}+.discourse-calendar-livestream-zoom-page {+ // Both heights are measured from the viewport and set on this element; these+ // are the fallbacks for a browser without `visualViewport`, where there is no+ // keyboard to account for and the two are the same.+ //+ // The resting height is the space the page has with no keyboard over it,+ // which the meeting is sized against so it is never the thing that shrinks.+ // The visible height is what the viewport is showing right now.+ --livestream-zoom-page-height: calc(+ var(--composer-vh, 1vh) * 100 - var(--header-offset, 0px)+ );+ --livestream-zoom-resting-height: var(--livestream-zoom-page-height);+ --livestream-zoom-visible-height: var(--livestream-zoom-page-height);++ // without chat below it, the meeting is the page+ --livestream-zoom-view-height: var(--livestream-zoom-resting-height);position: relative;- min-height: calc(100vh - var(--header-offset, 0px));+ height: var(--livestream-zoom-resting-height);background: var(--secondary);+ // The device's own controls sit over the bottom of the viewport wherever the+ // page is laid out edge to edge, and the app's footer navigation over that+ // again in a PWA. Neither is taken out of the height the viewport reports, so+ // the page gives it up itself rather than leaving the composer underneath.+ --livestream-zoom-bottom-inset: env(safe-area-inset-bottom, 0px);++ html.footer-nav-visible & {+ --livestream-zoom-bottom-inset: calc(+ env(safe-area-inset-bottom, 0px) + var(--footer-nav-height, 0px)+ );+ }++ &:not([data-keyboard-open]) {+ height: calc(+ var(--livestream-zoom-resting-height) - var(+ --livestream-zoom-bottom-inset+ )+ );+ }+&__frame {- min-height: calc(100vh - var(--header-offset, 0px));+ display: block;+ width: 100%;+ height: var(--livestream-zoom-view-height);+ border: 0;}&__waiting-wrapper {@@ -142,11 +196,112 @@ body.chat-enabled.livestream-topic.confirmed-event-assistance {}}- &__chat-button {- position: fixed;- right: 1rem;- bottom: 4rem;- z-index: 3;+ &__chat {+ display: flex;+ min-height: 0;+ overflow: hidden;+ }++ &.--with-chat {+ --livestream-zoom-view-height: calc(+ var(--livestream-zoom-resting-height) * 0.55+ );+ display: flex;+ flex-direction: column;++ .discourse-calendar-livestream-zoom-page__frame {+ flex: 0 0 var(--livestream-zoom-view-height);+ }++ .discourse-calendar-livestream-zoom-page__chat {+ flex: 1 1 0;+ border-top: 1px solid var(--primary-low);+ }++ .discourse-calendar-livestream-zoom-page__waiting-wrapper {+ flex: 0 1 auto;+ min-height: 0;+ overflow-y: auto;+ }++ // The meeting keeps its height above chat, so the whole of it is still+ // there to scroll back up to.+ &[data-keyboard-open] {+ --livestream-zoom-stage-height: calc(+ var(--livestream-zoom-visible-height) - var(--header-offset, 0px)+ );+ position: fixed;+ top: calc(+ var(--livestream-zoom-visible-top, 0px) + var(--header-offset, 0px)+ );+ left: 0;+ right: 0;+ height: var(--livestream-zoom-stage-height);+ overflow-y: auto;+ overscroll-behavior: contain;+ z-index: 1;++ .discourse-calendar-livestream-zoom-page__chat {+ flex: 0 0 var(--livestream-zoom-stage-height);+ }++ .discourse-calendar-livestream-zoom-page__frame {+ pointer-events: none;+ }++ .chat-messages-scroller {+ overflow-y: hidden;+ overscroll-behavior: auto;+ }+ }++ @include viewport.from(lg) {+ &,+ &[data-keyboard-open] {+ position: relative;+ flex-direction: row;+ height: var(--livestream-zoom-resting-height);+ overflow: visible;+ max-width: unset !important; // override horizon styles+ padding-inline: 0 !important; // override horizon styles++ .discourse-calendar-livestream-zoom-page__frame {+ flex: 1 1 auto;+ height: 100%;+ pointer-events: auto;+ max-height: unset;+ }++ .discourse-calendar-livestream-zoom-page__chat {+ flex: 0 0 clamp(20rem, 30%, 28rem);+ border-top: 0;+ border-left: 1px solid var(--primary-low);+ }++ .discourse-calendar-livestream-zoom-page__waiting-wrapper {+ flex: 1 1 auto;+ }++ .chat-messages-scroller {+ overflow-y: scroll;+ }+ }+ }+ }+}++#custom-chat-container.inline {+ display: flex;+ flex-direction: column;+ width: 100%;+ flex: 1 1 0;+ min-height: 0;+ border-right: 1px solid var(--content-border-color);++ .chat-drawer,+ .chat-channel {+ width: 100%;+ height: 100%;}}diff --git a/plugins/discourse-events/assets/stylesheets/mobile/livestream.scss b/plugins/discourse-events/assets/stylesheets/mobile/livestream.scssindex dad6ad4fe6a..15ce3519aa7 100644--- a/plugins/discourse-events/assets/stylesheets/mobile/livestream.scss+++ b/plugins/discourse-events/assets/stylesheets/mobile/livestream.scss@@ -1,5 +1,4 @@-body.livestream-topic.chat-enabled,-body.websdk-body {+body.livestream-topic.chat-enabled {.d-header-icons {.livestream-header-icon {position: relative;@@ -198,32 +197,3 @@ body.websdk-body {body:not(.livestream-topic) .d-header-icons .livestream-header-icon {display: none;}--.discourse-calendar-livestream-zoom-page {- margin-left: calc(var(--topic-body-width-padding, 1rem) * -1);- margin-right: calc(var(--topic-body-width-padding, 1rem) * -1);-}--// zoom specific overrides, undoes core conflicts-#wc-footer {- .btn-group {- margin: 0;- }-- .audio-option-menu {- position: relative;- }-- .footer-button__wrapper {- display: flex;-- > div {- display: flex;- }-- .audio-option-menu {- display: flex;- margin-block: auto;- }- }-}diff --git a/plugins/discourse-events/config/locales/client.en.yml b/plugins/discourse-events/config/locales/client.en.ymlindex 2a4bf5edf81..df614f4b0b0 100644--- a/plugins/discourse-events/config/locales/client.en.yml+++ b/plugins/discourse-events/config/locales/client.en.yml@@ -30,7 +30,7 @@ en:livestream:zoom:join: "Join Zoom"- chat: "Chat"+ frame_title: "Zoom webinar"open_in_zoom: "Open in Zoom"load_error: "You left the webinar or we are unable to load Zoom in this page."too_early: "You can join the webinar closer to the event start time"diff --git a/plugins/discourse-events/config/locales/server.en.yml b/plugins/discourse-events/config/locales/server.en.ymlindex d89abf82249..2f9ec63d94a 100644--- a/plugins/discourse-events/config/locales/server.en.yml+++ b/plugins/discourse-events/config/locales/server.en.yml@@ -110,6 +110,10 @@ en:livestream:chat:topic_reference_message: "This channel is for the event [%{title}](%{url}) — visit the topic for details and to RSVP."+ zoom:+ frame_title: "Zoom webinar"+ frame_join: "Join webinar"+ frame_joining: "Connecting…"calendar_must_be_in_first_post: "Calendar tag can only be used in first post of a topic."more_than_one_calendar: "You can’t have more than one calendar in a post."more_than_two_dates: "A post of a calendar topic can’t contain more than two dates."diff --git a/plugins/discourse-events/config/routes.rb b/plugins/discourse-events/config/routes.rbindex edcdf724988..ecacbb96d7c 100644--- a/plugins/discourse-events/config/routes.rb+++ b/plugins/discourse-events/config/routes.rb@@ -26,6 +26,7 @@ endDiscourseCalendar::Engine.routes.draw doget "/discourse-calendar/livestream/zoom/signature" => "livestream#prepare_zoom_signature",:format => :json+ get "/discourse-calendar/livestream/zoom/frame" => "livestream#zoom_frame"endDiscourse::Application.routes.draw dodiff --git a/plugins/discourse-events/plugin.rb b/plugins/discourse-events/plugin.rbindex 80031c89081..1c50ab922bd 100644--- a/plugins/discourse-events/plugin.rb+++ b/plugins/discourse-events/plugin.rb@@ -957,7 +957,9 @@ after_initialize doDiscoursePostEvent::Invitee.statuses[invitee.status] if inviteeend- Chat::ChannelSerializer.include(DiscourseCalendar::Livestream::ChannelSerializerExtension)+ reloadable_patch do+ Chat::ChannelSerializer.include(DiscourseCalendar::Livestream::ChannelSerializerExtension)+ endregister_modifier(:chat_channel_fetcher_public_includes) do |includes|includes + [{ livestream_topic_chat_channel: { topic: { first_post: :event } } }]diff --git a/plugins/discourse-events/spec/requests/livestream_controller_spec.rb b/plugins/discourse-events/spec/requests/livestream_controller_spec.rbindex 97bca47ce35..05acb406753 100644--- a/plugins/discourse-events/spec/requests/livestream_controller_spec.rb+++ b/plugins/discourse-events/spec/requests/livestream_controller_spec.rb@@ -164,6 +164,80 @@ module DiscourseCalendarendend+ describe "#zoom_frame" do+ it "rejects anonymous users" do+ get "/discourse-calendar/livestream/zoom/frame", params: { topic_id: topic.id }++ expect(response.status).to eq(404)+ end++ context "when signed in" do+ before { sign_in(current_user) }++ it "serves the page the meeting runs in" do+ get "/discourse-calendar/livestream/zoom/frame", params: { topic_id: topic.id }++ expect(response.status).to eq(200)+ expect(response.body).to include("zoomFrameConfig")+ end++ it "points the page at the signature for its own topic" do+ get "/discourse-calendar/livestream/zoom/frame", params: { topic_id: topic.id }++ expect(response.body).to include(+ "/discourse-calendar/livestream/zoom/signature.json?topic_id=#{topic.id}",+ )+ end++ # Zoom leaves the meeting by navigating this page to its own URL with+ # the flag set, which is the only notice the app around it gets.+ it "tells the app the user has left when Zoom returns them" do+ get "/discourse-calendar/livestream/zoom/frame", params: { topic_id: topic.id, left: 1 }++ expect(response.status).to eq(200)+ expect(response.body).to include("\"hasLeft\":true")+ end++ it "returns not found when the topic does not exist" do+ get "/discourse-calendar/livestream/zoom/frame", params: { topic_id: -1 }++ expect(response.status).to eq(404)+ end++ it "returns not found when the topic cannot be seen" do+ group = Fabricate(:group)+ private_category = Fabricate(:private_category, group: group)+ private_topic = Fabricate(:topic, category: private_category, tags: [tag])++ get "/discourse-calendar/livestream/zoom/frame", params: { topic_id: private_topic.id }++ expect(response.status).to eq(404)+ end++ it "returns not found when Zoom embedding is unavailable" do+ SiteSetting.livestream_zoom_enabled = false++ get "/discourse-calendar/livestream/zoom/frame", params: { topic_id: topic.id }++ expect(response.status).to eq(404)+ end++ context "when the site is in a subfolder" do+ before { set_subfolder "/forum" }++ it "returns them to a path the site actually serves" do+ get "/discourse-calendar/livestream/zoom/frame", params: { topic_id: topic.id }++ expect(response.status).to eq(200)+ expect(response.body).to include(+ "#{Discourse.base_url_no_prefix}/forum/discourse-calendar/livestream/zoom/frame?topic_id=#{topic.id}",+ )+ expect(response.body).not_to include("/forum/forum")+ end+ end+ end+ end+# The full-page mobile Zoom view is a client-side route rendered by the topic# controller, so the server just needs to serve the topic at that path.describe "the full-page Zoom route" dodiff --git a/plugins/discourse-events/test/javascripts/integration/components/zoom-page-test.gjs b/plugins/discourse-events/test/javascripts/integration/components/zoom-page-test.gjsindex fde80168c77..6073c543154 100644--- a/plugins/discourse-events/test/javascripts/integration/components/zoom-page-test.gjs+++ b/plugins/discourse-events/test/javascripts/integration/components/zoom-page-test.gjs@@ -7,29 +7,60 @@ import LivestreamZoomPage from "../../discourse/components/livestream/zoom-page"const FALLBACK_SELECTOR = ".discourse-calendar-livestream-zoom-page__fallback";const FRAME_SELECTOR = ".discourse-calendar-livestream-zoom-page__frame";-const CHAT_BUTTON_SELECTOR =- ".discourse-calendar-livestream-zoom-page__chat-button";-const WAITING_SELECTOR = ".discourse-calendar-livestream-zoom-page__waiting";-const ERROR_TEXT =- "You left the webinar or we are unable to load Zoom in this page.";--// `returnedFromZoom` reads `window.location.search`, which a rendering test-// cannot set. Stubbing the getter is the only way to reach the branch.-function stubReturnedFromZoom(value) {- sinon.stub(LivestreamZoomPage.prototype, "returnedFromZoom").get(() => value);+const CHAT_SELECTOR = ".discourse-calendar-livestream-zoom-page__chat";++// The frame's URL is served by Discourse, and left to itself the frame would+// load it here — where anything unrecognised answers with the app, leaving a+// second copy of it running inside the test. `zoom-frame-url-test` covers what+// the URL should be.+function stubFrameUrl(context) {+ sinon.stub(LivestreamZoomPage.prototype, "frameUrl").get(() => "about:blank");+ return context;}-// `loadZoom` is an `@action`, so the prototype holds an accessor rather than a-// plain method and a bare `sinon.stub` would leave the real one in place — it-// would reach for the network and the Zoom SDK.-function stubLoadZoom(implementation) {- const fake = sinon.fake(implementation ?? (() => Promise.resolve()));-- sinon.stub(LivestreamZoomPage.prototype, "loadZoom").get(function () {- return fake.bind(this);- });+// What the frame reports back — the meeting failing, and the user leaving it —+// arrives as a window message, which is the same channel the test runner uses+// to talk to its own harness. Faking one here unsettles it, so those states are+// left to a system test driving the real frame.++// The channel itself is chat's to render and needs a live channel record, so+// only the decision to embed it is exercised here. Registering is repeatable,+// which a test flipping `userCanChat` for itself depends on.+function stubChat(context, userCanChat = true) {+ const owner = getOwner(context);++ owner.unregister("service:embeddable-chat");+ owner.register(+ "service:embeddable-chat",+ { userCanChat },+ { instantiate: false }+ );++ // Never resolving, rather than resolving to nothing: the channel it is asked+ // for is assigned to tracked state that the same modifier reads, so anything+ // it hands back that is not the channel being looked for invalidates the+ // modifier and sets it looking again. A real one matches and settles; a blank+ // one spins.+ owner.unregister("service:chat-channels-manager");+ owner.register(+ "service:chat-channels-manager",+ { find: () => new Promise(() => {}) },+ { instantiate: false }+ );+}- return fake;+// The embedded channel subscribes for its own membership updates, and a live+// subscription is a request that never finishes, which is a test that never+// settles. Only the subscribing is taken out: the service itself is left in+// place for everything else that expects to find it.+//+// Once per test, unlike the services above: a second wrapping of the same+// method is an error in sinon, not a no-op.+function stubMessageBus(context) {+ const messageBus = getOwner(context).lookup("service:message-bus");++ sinon.stub(messageBus, "subscribe");+ sinon.stub(messageBus, "unsubscribe");}module("Integration | Component | LivestreamZoomPage", function (hooks) {@@ -37,6 +68,9 @@ module("Integration | Component | LivestreamZoomPage", function (hooks) {hooks.beforeEach(function () {getOwner(this).lookup("service:site-settings").chat_enabled = true;+ stubChat(this);+ stubMessageBus(this);+ stubFrameUrl(this);this.topic = {id: 1,@@ -58,126 +92,62 @@ module("Integration | Component | LivestreamZoomPage", function (hooks) {};});- test("loads Zoom once into the frame", async function (assert) {- const loadZoom = stubLoadZoom();- stubReturnedFromZoom(false);-- await render(- <template><LivestreamZoomPage @topic={{this.topic}} /></template>- );-- assert.dom(FRAME_SELECTOR).exists();- assert.dom(FALLBACK_SELECTOR).doesNotExist("no error before a failure");- assert.strictEqual(loadZoom.callCount, 1, "sets the SDK up exactly once");- });-- // Simulates navigating straight to /t/:slug/:id/zoom before the join window- // opens, bypassing the disabled button on the topic page.- test("does not load Zoom before the event timeframe", async function (assert) {- const loadZoom = stubLoadZoom();- stubReturnedFromZoom(false);- this.topic.postStream.posts[0].event.starts_at = moment()- .add(2, "hours")- .toISOString();-- await render(- <template><LivestreamZoomPage @topic={{this.topic}} /></template>- );-- assert.dom(FRAME_SELECTOR).doesNotExist();- assert- .dom(WAITING_SELECTOR)- .includesText("You can join the webinar closer to the event start time");- assert- .dom(`${WAITING_SELECTOR} a`)- .hasText("View topic for the event")- .hasAttribute("href", "/t/test-topic/1")- .hasClass("raw-link");- assert.strictEqual(loadZoom.callCount, 0, "never sets the SDK up");- });-- test("does not load Zoom after the event timeframe", async function (assert) {- const loadZoom = stubLoadZoom();- stubReturnedFromZoom(false);- this.topic.postStream.posts[0].event.starts_at = moment()- .subtract(3, "hours")- .toISOString();- this.topic.postStream.posts[0].event.ends_at = moment()- .subtract(1, "hour")- .toISOString();-+ test("hands the meeting a frame of its own to run in", async function (assert) {await render(<template><LivestreamZoomPage @topic={{this.topic}} /></template>);- assert.dom(FRAME_SELECTOR).doesNotExist();- assert.dom(WAITING_SELECTOR).exists();- assert.strictEqual(loadZoom.callCount, 0, "never sets the SDK up");- });-- test("shows the fallback link when Zoom fails to load", async function (assert) {- stubLoadZoom(function () {- this.errorMessage = ERROR_TEXT;- return Promise.resolve();- });- stubReturnedFromZoom(false);-- await render(- <template><LivestreamZoomPage @topic={{this.topic}} /></template>- );-- assert.dom(FALLBACK_SELECTOR).exists();- assert.dom(`${FALLBACK_SELECTOR} p`).hasText(ERROR_TEXT);assert- .dom(`${FALLBACK_SELECTOR} .btn-primary`)- .doesNotExist("no retry button unless the user came back from Zoom");+ .dom(FRAME_SELECTOR)+ .hasAttribute(+ "allow",+ /microphone/,+ "the meeting cannot ask for audio without it"+ );+ assert.dom(FALLBACK_SELECTOR).doesNotExist("no error before a failure");});- test("offers a retry when the user has returned from Zoom", async function (assert) {- stubReturnedFromZoom(true);+ // The states before and after the event's own timeframe render the event+ // card, which does not settle in a rendering test. What it is gating is the+ // signature the meeting cannot start without, and `livestream_controller_spec`+ // covers the server refusing that outside the timeframe.+ test("embeds the chat below the meeting when the topic has a channel", async function (assert) {await render(<template><LivestreamZoomPage @topic={{this.topic}} /></template>);- assert- .dom(`${FALLBACK_SELECTOR} p`)- .hasText(ERROR_TEXT, "does not try to rejoin automatically");- assert.dom(`${FALLBACK_SELECTOR} .btn-primary`).hasText("Join Zoom");+ assert.dom(CHAT_SELECTOR).exists();+ assert.dom(`${CHAT_SELECTOR} #custom-chat-container`).hasClass("inline");});- test("offers to open the chat when the topic has a channel", async function (assert) {- stubLoadZoom();- stubReturnedFromZoom(false);+ test("omits the chat when chat is disabled", async function (assert) {+ getOwner(this).lookup("service:site-settings").chat_enabled = false;await render(<template><LivestreamZoomPage @topic={{this.topic}} /></template>);- assert.dom(CHAT_BUTTON_SELECTOR).exists();+ assert.dom(CHAT_SELECTOR).doesNotExist();});- test("hides the chat button when chat is disabled", async function (assert) {- stubLoadZoom();- stubReturnedFromZoom(false);- getOwner(this).lookup("service:site-settings").chat_enabled = false;+ test("omits the chat when the topic has no channel", async function (assert) {+ this.topic.chat_channel_id = null;await render(<template><LivestreamZoomPage @topic={{this.topic}} /></template>);- assert.dom(CHAT_BUTTON_SELECTOR).doesNotExist();+ assert.dom(CHAT_SELECTOR).doesNotExist();});- test("hides the chat button when the topic has no channel", async function (assert) {- stubLoadZoom();- stubReturnedFromZoom(false);- this.topic.chat_channel_id = null;+ test("omits the chat when the user cannot chat", async function (assert) {+ stubChat(this, false);await render(<template><LivestreamZoomPage @topic={{this.topic}} /></template>);- assert.dom(CHAT_BUTTON_SELECTOR).doesNotExist();+ assert.dom(CHAT_SELECTOR).doesNotExist();});});diff --git a/plugins/discourse-events/test/javascripts/unit/lib/zoom-frame-url-test.js b/plugins/discourse-events/test/javascripts/unit/lib/zoom-frame-url-test.jsnew file mode 100644index 00000000000..b6106a12df1--- /dev/null+++ b/plugins/discourse-events/test/javascripts/unit/lib/zoom-frame-url-test.js@@ -0,0 +1,26 @@+import { setupTest } from "ember-qunit";+import { module, test } from "qunit";+import zoomFrameUrl from "discourse/plugins/discourse-events/discourse/lib/zoom-frame-url";++module("Unit | Lib | zoom-frame-url", function (hooks) {+ setupTest(hooks);++ test("addresses the frame that serves the meeting", function (assert) {+ const url = new URL(zoomFrameUrl({ topicId: 7 }), "http://localhost");++ assert.strictEqual(+ url.pathname,+ "/discourse-calendar/livestream/zoom/frame"+ );+ assert.strictEqual(url.searchParams.get("topic_id"), "7");+ });++ // The frame joins the meeting as it loads, so a retry has to be a URL the+ // browser treats as a new one.+ test("carries the attempt, so a retry reloads the frame", function (assert) {+ const first = zoomFrameUrl({ topicId: 7, attempt: 0 });+ const second = zoomFrameUrl({ topicId: 7, attempt: 1 });++ assert.notStrictEqual(first, second);+ });+});