diff --git a/browser/content.js b/browser/content.js index fff893ba2..fba7beaee 100644 --- a/browser/content.js +++ b/browser/content.js @@ -13,6 +13,18 @@ document.addEventListener( RENDERER_CSS_URL: browser.runtime.getURL("dist/Vencord.css"), } }); + + chrome.runtime.onMessage.addListener(request => { + window.postMessage({ type: "vencord:keybinds", meta: request.command }); + }) + + window.addEventListener('message', function(event) { + if (event.source !== window) return; + + if (event.data.type === 'OPEN_SHORTCUTS') { + chrome.runtime.sendMessage({ action: "openShortcuts" }); + } + }, false); }, { once: true } ); diff --git a/browser/manifest.json b/browser/manifest.json index 3463e46cf..00802eb47 100644 --- a/browser/manifest.json +++ b/browser/manifest.json @@ -49,5 +49,36 @@ "path": "modifyResponseHeaders.json" } ] + }, + + "background": { + "service_worker": "service-worker.js" + }, + + "commands": { + "TOGGLE_MUTE": { + "description": "Toggle Mute — Toggle your microphone's transmission on and off." + }, + "TOGGLE_DEAFEN": { + "description": "Toggle Deafen — Toggle your speaker's playback on and off. Also disables your microphone while deafened." + }, + "TOGGLE_VOICE_MODE": { + "description": "Toggle VAD — Toggle to switch between Push-to-talk and Voice Activity mode." + }, + "TOGGLE_STREAMER_MODE": { + "description": "Toggle Streamer Mode — Toggle to enable/disable Streamer Mode." + }, + "TOGGLE_GO_LIVE_STREAMING": { + "description": "Toggle Screen Share — Toggle to start/stop streaming in your current voice channel. Streams can only be started with this keybind if Discord recognises the game you are currently playing." + }, + "NAVIGATE_BACK": { + "description": "Navigate Back — Might conflict with your browsers native keybinds" + }, + "NAVIGATE_FORWARD": { + "description": "Navigate Forward — Might conflict with your browsers native keybinds" + }, + "SAVE_CLIP": { + "description": "Save Clip — Clips the last 30 seconds to 2 minutes of your stream, depending on your settings." + } } } diff --git a/browser/service-worker.js b/browser/service-worker.js new file mode 100644 index 000000000..98f234657 --- /dev/null +++ b/browser/service-worker.js @@ -0,0 +1,11 @@ +chrome.commands.onCommand.addListener(async (command) => { + const [tab] = await chrome.tabs.query({ active: true, currentWindow: true }); + + chrome.tabs.sendMessage(tab.id, { command }); +}); + +chrome.runtime.onMessage.addListener((message, sender, sendResponse) => { + if (message.action === "openShortcuts") { + chrome.tabs.create({ url: "about://extensions/shortcuts" }); + } +}); diff --git a/scripts/build/buildWeb.mjs b/scripts/build/buildWeb.mjs index 8fa0c59fe..884188ef2 100644 --- a/scripts/build/buildWeb.mjs +++ b/scripts/build/buildWeb.mjs @@ -184,7 +184,7 @@ const appendCssRuntime = readFile("dist/Vencord.user.css", "utf-8").then(content if (!process.argv.includes("--skip-extension")) { await Promise.all([ appendCssRuntime, - buildExtension("chromium-unpacked", ["modifyResponseHeaders.json", "content.js", "manifest.json", "icon.png"]), + buildExtension("chromium-unpacked", ["modifyResponseHeaders.json", "content.js", "manifest.json", "icon.png", "service-worker.js"]), buildExtension("firefox-unpacked", ["background.js", "content.js", "manifestv2.json", "icon.png"]), ]); diff --git a/scripts/build/common.mjs b/scripts/build/common.mjs index 26866558e..4e3083d5b 100644 --- a/scripts/build/common.mjs +++ b/scripts/build/common.mjs @@ -168,6 +168,7 @@ export const globPlugins = kind => ({ const excluded = (target === "dev" && !IS_DEV) || (target === "web" && kind === "discordDesktop") || + (target === "browser" && kind !== "web") || (target === "desktop" && kind === "web") || (target === "discordDesktop" && kind !== "discordDesktop") || (target === "vesktop" && kind !== "vesktop"); diff --git a/scripts/generatePluginList.ts b/scripts/generatePluginList.ts index 92bcba75e..8b40b536e 100644 --- a/scripts/generatePluginList.ts +++ b/scripts/generatePluginList.ts @@ -40,7 +40,7 @@ interface PluginData { hasCommands: boolean; required: boolean; enabledByDefault: boolean; - target: "discordDesktop" | "vesktop" | "desktop" | "web" | "dev"; + target: "discordDesktop" | "vesktop" | "desktop" | "web" | "browser" | "dev"; filePath: string; } @@ -166,7 +166,7 @@ async function parseFile(fileName: string) { const target = getPluginTarget(fileName); if (target) { - if (!["web", "discordDesktop", "vesktop", "desktop", "dev"].includes(target)) throw fail(`invalid target ${target}`); + if (!["web", "browser", "discordDesktop", "vesktop", "desktop", "dev"].includes(target)) throw fail(`invalid target ${target}`); data.target = target as any; } diff --git a/src/api/Themes.ts b/src/api/Themes.ts index 2aadd78e8..9180faabc 100644 --- a/src/api/Themes.ts +++ b/src/api/Themes.ts @@ -27,6 +27,8 @@ import { userStyleRootNode, vencordRootNode } from "./Styles"; let style: HTMLStyleElement; let themesStyle: HTMLStyleElement; +const themeChangeListeners = new Set<() => void>(); + async function toggle(isEnabled: boolean) { if (!style) { if (isEnabled) { @@ -89,6 +91,7 @@ async function initThemes() { themesStyle.textContent = links.map(link => `@import url("${link.trim()}");`).join("\n"); updatePopoutWindows(); + themeChangeListeners.forEach(listener => listener()); } function applyToPopout(popoutWindow: Window | undefined, key: string) { @@ -147,3 +150,11 @@ export function initQuickCssThemeStore(themeStore: ThemeStore) { initThemes(); }); } + +export function addThemeChangeListener(listener: () => void) { + themeChangeListeners.add(listener); +} + +export function removeThemeChangeListener(listener: () => void) { + themeChangeListeners.delete(listener); +} diff --git a/src/plugins/webPWA.browser/index.tsx b/src/plugins/webPWA.browser/index.tsx new file mode 100644 index 000000000..94ec9d491 --- /dev/null +++ b/src/plugins/webPWA.browser/index.tsx @@ -0,0 +1,204 @@ +/* + * Vencord, a Discord client mod + * Copyright (c) 2024 Vendicated and contributors + * SPDX-License-Identifier: GPL-3.0-or-later + */ + +import { addThemeChangeListener, removeThemeChangeListener } from "@api/Themes"; +import { Devs } from "@utils/constants"; +import { sleep } from "@utils/misc"; +import definePlugin from "@utils/types"; +import { FluxStore } from "@vencord/discord-types"; +import { findStoreLazy } from "@webpack"; +import { NotificationSettingsStore, RelationshipStore, ThemeStore } from "@webpack/common"; + +import managedStyle from "./styles.css?managed"; + +const GuildReadStateStore: FluxStore & { getTotalMentionCount: () => number; hasAnyUnread: () => boolean; } = findStoreLazy("GuildReadStateStore"); + +let _keybinds: Record any; }>; + +function colorToHex(color: string) { + const ctx = document.createElement("canvas").getContext("2d"); + if (!ctx) return "#000000"; // no GPU, you'll have bigger issues than a miscolored title bar + ctx.fillStyle = color; + ctx.fillRect(0, 0, 1, 1); + return "#" + [...ctx.getImageData(0, 0, 1, 1).data.slice(0, 3)].map(n => n.toString(16).padStart(2, "0")).join(""); +} + +let linkEl: HTMLLinkElement | undefined; +async function setManifest() { + // need to wait for CSS changes to flush + await sleep(20); + + if (linkEl) { + URL.revokeObjectURL(linkEl.href); + linkEl.remove(); + } + + const endpoint = "https:" + window.GLOBAL_ENV.WEBAPP_ENDPOINT; + const appUrl = endpoint + "/app"; // URL when PWA launches + const icon = document.querySelector('link[rel="icon"]')!.href; + const styles = getComputedStyle(document.body); + const manifest = { + id: appUrl, + name: "Discord", + short_name: "Discord", + start_url: appUrl, + display: "fullscreen", + display_override: ["window-controls-overlay"], + dir: "ltr", + lang: "en-US", + background_color: colorToHex(styles.getPropertyValue("--background-base-lower")), + theme_color: colorToHex(styles.getPropertyValue("--background-base-lowest")), + scope: endpoint + "/", // scope of all possible URL"s + description: "Imagine a place...", + orientation: "any", + categories: ["social"], + shortcuts: [ + { + name: "Friends", + url: appUrl, + icons: [{ src: icon, sizes: "256x256" }] + } + ], + protocol_handlers: [{ protocol: "web+discord", url: endpoint + "/%s" }], + launch_handler: { client_mode: "navigate-existing" }, + // Strange CDN but these links are straight from discord.com + screenshots: [ + { src: "https://cdn.prod.website-files.com/6257adef93867e50d84d30e2/664723dbe91e5ee8db15cfe7_Discord_Website_Refresh_Activities.webp", sizes: "691x720", type: "image/webp", label: "Activities", form_factor: "wide" }, + { src: "https://cdn.prod.website-files.com/6257adef93867e50d84d30e2/664723da372be4a12a3dc9df_Discord_Website_Refresh_Hop-In.webp", sizes: "939x639", type: "image/webp", label: "Hop In", form_factor: "wide" }, + { src: "https://cdn.prod.website-files.com/6257adef93867e50d84d30e2/664723da94dd30e64e74357a_Discord_Website_Refresh_StatusHover.webp", sizes: "904x708", type: "image/webp", label: "Status", form_factor: "wide" }, + { src: "https://cdn.prod.website-files.com/6257adef93867e50d84d30e2/664723da0a2e6be98fa5216b_Discord_Website_Refresh_Emojis%2BSoundboard-p-1080.webp", sizes: "1080x918", type: "image/webp", label: "Emojis", form_factor: "wide" }, + { src: "https://cdn.prod.website-files.com/6257adef93867e50d84d30e2/6638bdbd1150b7c8509fb2be_Discord_Website_Refresh_SameRoom.webp", sizes: "796x593", type: "image/webp", label: "Rooms", form_factor: "wide" }, + { src: "https://cdn.prod.website-files.com/6257adef93867e50d84d30e2/68407334ccf9aeca71903bab_home-new.webp", sizes: "1716×1606", type: "image/webp", label: "Discord", form_factor: "wide" }, + { src: "https://cdn.prod.website-files.com/6257adef93867e50d84d30e2/6638bcb99c2b8dc14e6f67fd_Discord_Website_Refresh_Platforms.webp", sizes: "760x580", type: "image/webp", label: "Platforms", form_factor: "wide" } + ], + icons: [ + { + src: icon, + sizes: "256x256", + type: "image/png" + }, + { + src: icon, + sizes: "256x256", + type: "image/png", + purpose: "maskable" + } + ] + }; + + linkEl = document.createElement("link"); + linkEl.rel = "manifest"; + linkEl.href = URL.createObjectURL(new Blob([JSON.stringify(manifest)], { type: "application/json" })); + document.head.appendChild(linkEl); +} + +export default definePlugin({ + name: "WebPWA", + description: "Makes Discord installable as an App (PWA). Enables notification badges, global key-binds and Discord's custom title bar.", + authors: [Devs.ThaUnknown], + tags: ["Utility"], + managedStyle, + enabledByDefault: true, + + flux: { + KEYBINDS_REGISTER_GLOBAL_KEYBIND_ACTIONS: ({ keybinds }: { keybinds: Record any; }>; }) => { + _keybinds = keybinds; + } + }, + + ctrl: new AbortController(), + start() { + + // installability + setManifest(); + // user might change theme before installing the PWA + ThemeStore.addChangeListener(setManifest); + addThemeChangeListener(setManifest); + + // notifications + NotificationSettingsStore.addChangeListener(this.setBadge); + GuildReadStateStore.addChangeListener(this.setBadge); + RelationshipStore.addChangeListener(this.setBadge); + + if (!IS_USERSCRIPT) { + // keybinds + this.ctrl.abort(); + this.ctrl = new AbortController(); + window.addEventListener("message", ({ data }) => { + if (data?.type === "vencord:keybinds" && _keybinds) { + const { meta } = data; + if (meta in _keybinds) _keybinds[meta].onTrigger(); + } + }, this.ctrl); + } + }, + stop() { + navigator.setAppBadge(0); + this.ctrl.abort(); + + if (linkEl) { + URL.revokeObjectURL(linkEl.href); + linkEl.remove(); + } + ThemeStore.removeChangeListener(setManifest); + removeThemeChangeListener(setManifest); + + NotificationSettingsStore.removeChangeListener(this.setBadge); + GuildReadStateStore.removeChangeListener(this.setBadge); + RelationshipStore.removeChangeListener(this.setBadge); + }, + + patches: [ + // Vesktop/src/renderer/patches/hideDownloadAppsButton.ts + { + find: '"app-download-button"', + replacement: { + match: /return(?=.{0,50}id:"app-download-button")/, + replace: "return null;return" + } + }, + // Vesktop/blob/main/src/renderer/patches/enableNotificationsByDefault.ts + { + find: '"NotificationSettingsStore', + replacement: { + match: /\.isPlatformEmbedded(?=\?\i\.\i\.ALL)/g, + replace: "$&||true" + } + }, + // Vesktop/src/renderer/patches/keybindButton.tsx + { + find: "#{intl::KEYBIND_IN_BROSWER_NOTICE}", + replacement: { + match: /,{type:"info",children:(?=.{0,50}?#{intl::KEYBIND_IN_BROSWER_NOTICE})/, + replace: ',{type:"info",children:$self.renderKeybindsButton(),_children:', + predicate: () => !IS_USERSCRIPT + } + } + ], + + renderKeybindsButton: () => ( +
+ Custom global Push To X keybinds are supported. Navigate to { window.postMessage({ type: "OPEN_SHORTCUTS" }, "*"); }}>about://extensions/shortcuts to change them. Hold To X keybinds are not supported. +
+ ), + + // Vesktop/src/renderer/appBadge.ts + setBadge: () => { + try { + const mentionCount = GuildReadStateStore.getTotalMentionCount(); + const pendingRequests = RelationshipStore.getPendingCount(); + const hasUnread = GuildReadStateStore.hasAnyUnread(); + const disableUnreadBadge = NotificationSettingsStore.getDisableUnreadBadge(); + + let totalCount = mentionCount + pendingRequests; + if (!totalCount && hasUnread && !disableUnreadBadge) totalCount = -1; + + navigator.setAppBadge(totalCount); + } catch (e) { + console.error(e); + } + } +}); diff --git a/src/plugins/webPWA.browser/styles.css b/src/plugins/webPWA.browser/styles.css new file mode 100644 index 000000000..ae0137363 --- /dev/null +++ b/src/plugins/webPWA.browser/styles.css @@ -0,0 +1,21 @@ +:root { + /* opt out of auto-dark-mode plugins, which break discord css, such as force-dark, dark-reader etc */ + color-scheme: only light; + + /* force title bar to be same as WCO bar height, regardless of zoom, device pixel ratio or OS */ + + /* is only set when WCO is defined, otherwise sets to 0 */ + --custom-app-top-bar-height: env(titlebar-area-height, 0px) !important; +} + +/* position trailing titlebar elements alongside WCO */ +[class*="bar_"] [class*="trailing_"] { + padding-right: calc(100vw - env(titlebar-area-width, 100%) - env(titlebar-area-x, 0px)); +} + +/* force hide trailing icons when standalone so there's no ugly pixel overflow */ +@media all and (display-mode: standalone) { + [class*="bar_"] [class*="trailing_"] { + display: none; + } +} \ No newline at end of file diff --git a/src/utils/constants.ts b/src/utils/constants.ts index 4cd10cf6b..30d5735a4 100644 --- a/src/utils/constants.ts +++ b/src/utils/constants.ts @@ -589,6 +589,10 @@ export const Devs = /* #__PURE__*/ Object.freeze({ name: "RamziAH", id: 1279957227612147747n, }, + ThaUnknown: { + name: "ThaUnknown_", + id: 252390917665718273n + }, SomeAspy: { name: "SomeAspy", id: 516750892372852754n,