Move into class

This commit is contained in:
Manav Rathi
2024-05-09 13:12:59 +05:30
parent 482639a03c
commit e58424d2c0
3 changed files with 24 additions and 10 deletions

View File

@@ -6,7 +6,7 @@ import { useRouter } from "next/router";
import { useEffect, useState } from "react";
import { advertiseCode, getCastData, register } from "services/pair";
import { storeCastData } from "services/render";
import { castReceiverLoadingIfNeeded } from "../utils/cast-receiver";
import { castReceiverLoadingIfNeeded } from "../services/cast-receiver";
export default function Index() {
const [publicKeyB64, setPublicKeyB64] = useState<string | undefined>();

View File

@@ -2,8 +2,22 @@
export type Cast = typeof cast;
let _cast: Cast | undefined;
let _loader: Promise<Cast> | undefined;
/**
* A holder for the "cast" global object exposed by the Chromecast SDK,
* alongwith auxiliary state we need around it.
*/
class CastReceiver {
/**
* A reference to the `cast` global object that the Chromecast Web Receiver
* SDK attaches to the window.
*
* https://developers.google.com/cast/docs/web_receiver/basic
*/
cast: Cast | undefined;
loader: Promise<Cast> | undefined;
}
const castReceiver = new CastReceiver();
/**
* Load the Chromecast Web Receiver SDK and return a reference to the `cast`
@@ -15,18 +29,18 @@ let _loader: Promise<Cast> | undefined;
* https://developers.google.com/cast/docs/web_receiver/basic
*/
export const castReceiverLoadingIfNeeded = async (): Promise<Cast> => {
if (_cast) return _cast;
if (_loader) return await _loader;
if (castReceiver.cast) return castReceiver.cast;
if (castReceiver.loader) return await castReceiver.loader;
_loader = new Promise((resolve) => {
castReceiver.loader = new Promise((resolve) => {
const script = document.createElement("script");
script.src =
"https://www.gstatic.com/cast/sdk/libs/caf_receiver/v3/cast_receiver_framework.js";
castReceiver.cast = cast;
script.addEventListener("load", () => resolve(cast));
document.body.appendChild(script);
});
const c = await _loader;
_cast = c;
return c;
return await castReceiver.loader;
};

View File

@@ -3,7 +3,7 @@ import { boxSealOpen, toB64 } from "@ente/shared/crypto/internal/libsodium";
import castGateway from "@ente/shared/network/cast";
import { wait } from "@ente/shared/utils";
import _sodium from "libsodium-wrappers";
import { type Cast } from "../utils/cast-receiver";
import { type Cast } from "./cast-receiver";
export interface Registration {
/** A pairing code shown on the screen. A client can use this to connect. */