types.ts 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397
  1. import type { Emitter } from "nanoevents";
  2. import type * as consts from "./constants";
  3. import type { scriptInfo } from "./constants";
  4. import type { addSelectorListener } from "./observers";
  5. import type resources from "../assets/resources.json";
  6. import type locales from "../assets/locales.json";
  7. import type { getResourceUrl, getSessionId, getVideoTime, TrLocale, t, tp } from "./utils";
  8. import type { getFeatures, saveFeatures } from "./config";
  9. import type { SiteEventsMap } from "./siteEvents";
  10. /** Custom CLI args passed to rollup */
  11. export type RollupArgs = Partial<{
  12. "config-mode": "development" | "production";
  13. "config-branch": "main" | "develop";
  14. "config-host": "greasyfork" | "github" | "openuserjs";
  15. "config-assetSource": "local" | "github";
  16. "config-suffix": string;
  17. }>;
  18. // I know TS enums are impure but it doesn't really matter here, plus they look cooler
  19. export enum LogLevel {
  20. Debug,
  21. Info,
  22. }
  23. /** Which domain this script is currently running on */
  24. export type Domain = "yt" | "ytm";
  25. /** A URL string that starts with "http://" or "https://" */
  26. export type HttpUrlString = `http://${string}` | `https://${string}`;
  27. /** Key of a resource in `assets/resources.json` and extra keys defined by `tools/post-build.ts` */
  28. export type ResourceKey = keyof typeof resources | `trans-${keyof typeof locales}` | "changelog";
  29. /** Describes a single hotkey */
  30. export type HotkeyObj = {
  31. code: string,
  32. shift: boolean,
  33. ctrl: boolean,
  34. alt: boolean,
  35. };
  36. export type ObserverName = "body" | "playerBar" | "playerBarInfo";
  37. export type LyricsCacheEntry = {
  38. artist: string;
  39. song: string;
  40. url: string;
  41. viewed: number;
  42. added: number;
  43. };
  44. //#MARKER plugins
  45. // /** Intents (permissions) BYTM has to grant to the plugin for it to work */
  46. // export enum PluginIntent {
  47. // /** Plugin has access to hidden config values */
  48. // HiddenConfigValues = 1,
  49. // /** Plugin can write to the feature configuration */
  50. // WriteFeatureConfig = 2,
  51. // /** Plugin can write to the lyrics cache */
  52. // WriteLyricsCache = 4,
  53. // /** Plugin can add new translations and overwrite existing ones */
  54. // WriteTranslations = 8,
  55. // /** Plugin can create modal dialogs */
  56. // CreateModalDialogs = 16,
  57. // }
  58. /** Result of a plugin registration */
  59. export type PluginRegisterResult = {
  60. /** Public info about the registered plugin */
  61. info: PluginInfo;
  62. /** Emitter for plugin events - see {@linkcode PluginEventMap} for a list of events */
  63. events: Emitter<PluginEventMap>;
  64. }
  65. /** Minimal object that describes a plugin - this is all info the other installed plugins can see */
  66. export type PluginInfo = {
  67. /** Name of the plugin */
  68. name: string;
  69. /**
  70. * Adding the namespace and the name property makes the unique identifier for a plugin.
  71. * If one exists with the same name and namespace as this plugin, it may be overwritten at registration.
  72. * I recommend to set this value to a URL pointing to your homepage, or the author's username.
  73. */
  74. namespace: string;
  75. /** Version of the plugin as an array containing three whole numbers: `[major_version, minor_version, patch_version]` */
  76. version: [major: number, minor: number, patch: number];
  77. };
  78. /** Minimum part of the PluginDef object needed to make up the resolvable plugin identifier */
  79. export type PluginDefResolvable = PluginDef | { plugin: Pick<PluginDef["plugin"], "name" | "namespace"> };
  80. /** An object that describes a BYTM plugin */
  81. export type PluginDef = {
  82. plugin: PluginInfo & {
  83. /**
  84. * Descriptions of at least en_US and optionally any other locale supported by BYTM.
  85. * When an untranslated locale is set, the description will default to the value of en_US
  86. */
  87. description: Partial<Record<keyof typeof locales, string>> & {
  88. en_US: string;
  89. };
  90. /** URL to the plugin's icon - recommended size: 48x48 to 128x128 */
  91. iconUrl?: string;
  92. /** Homepage URLs for the plugin */
  93. homepage?: {
  94. /** URL to the plugin's GitHub repo */
  95. github?: string;
  96. /** URL to the plugin's GreasyFork page */
  97. greasyfork?: string;
  98. /** URL to the plugin's OpenUserJS page */
  99. openuserjs?: string;
  100. };
  101. };
  102. // /** TODO(v2.3 / v3): Intents (permissions) BYTM has to grant the plugin for it to work */
  103. // intents?: Array<PluginIntent>;
  104. /** Info about the plugin contributors */
  105. contributors?: Array<{
  106. /** Name of this contributor */
  107. name: string;
  108. /** (optional) Email address of this contributor */
  109. email?: string;
  110. /** (optional) URL to this plugin contributor's homepage / GitHub profile */
  111. url?: string;
  112. }>;
  113. };
  114. /** All events that are dispatched to plugins individually */
  115. export type PluginEventMap =
  116. & {
  117. /** Called when the plugin is registered on BYTM's side */
  118. pluginRegistered: (info: PluginInfo) => void;
  119. }
  120. & SiteEventsMap;
  121. /** A plugin in either the queue or registered map */
  122. export type PluginItem =
  123. & {
  124. def: PluginDef;
  125. }
  126. & Pick<PluginRegisterResult, "events">;
  127. /** All functions exposed by the interface on the global `BYTM` object */
  128. export type InterfaceFunctions = {
  129. /** Adds a listener to one of the already present SelectorObserver instances */
  130. addSelectorListener: typeof addSelectorListener;
  131. /**
  132. * Returns the URL of a resource as defined in `assets/resources.json`
  133. * There are also some resources like translation files that get added by `tools/post-build.ts`
  134. *
  135. * The returned URL is a `blob:` URL served up by the userscript extension
  136. * This makes the resource fast to fetch and also prevents CORS issues
  137. */
  138. getResourceUrl: typeof getResourceUrl;
  139. /** Returns the unique session ID for the current tab */
  140. getSessionId: typeof getSessionId;
  141. /**
  142. * Returns the current video time (on both YT and YTM)
  143. * In case it can't be determined on YT, mouse movement is simulated to bring up the video time
  144. * In order for that edge case not to error out, the function would need to be called in response to a user interaction event (e.g. click) due to the strict autoplay policy in browsers
  145. */
  146. getVideoTime: typeof getVideoTime;
  147. /** Returns the translation for the provided translation key and set locale (check the files in the folder `assets/translations`) */
  148. t: typeof t;
  149. /** Returns the translation for the provided translation key, including pluralization identifier and set locale (check the files in the folder `assets/translations`) */
  150. tp: typeof tp;
  151. /** Returns the current feature configuration */
  152. getFeatures: typeof getFeatures;
  153. /** Overwrites the feature configuration with the provided one */
  154. saveFeatures: typeof saveFeatures;
  155. };
  156. // shim for the BYTM interface properties
  157. export type BytmObject =
  158. {
  159. [key: string]: unknown;
  160. locale: TrLocale;
  161. logLevel: LogLevel;
  162. }
  163. // information from the userscript header
  164. & typeof scriptInfo
  165. // certain variables from `src/constants.ts`
  166. & Pick<typeof consts, "mode" | "branch" | "host" | "buildNumber" | "compressionFormat">
  167. // global functions exposed through the interface in `src/interface.ts`
  168. & InterfaceFunctions
  169. // others
  170. & {
  171. // the entire UserUtils library
  172. UserUtils: typeof import("@sv443-network/userutils");
  173. };
  174. declare global {
  175. interface Window {
  176. // to see the expanded type, install the VS Code extension "MylesMurphy.prettify-ts"
  177. // and hover over the property just below:
  178. BYTM: BytmObject;
  179. }
  180. }
  181. //#MARKER features
  182. export type FeatureKey = keyof FeatureConfig;
  183. export type FeatureCategory =
  184. | "layout"
  185. | "volume"
  186. | "songLists"
  187. | "behavior"
  188. | "input"
  189. | "lyrics"
  190. | "general";
  191. type SelectOption = {
  192. value: string | number;
  193. label: string;
  194. };
  195. type FeatureTypeProps = ({
  196. type: "toggle";
  197. default: boolean;
  198. } & FeatureFuncProps)
  199. | ({
  200. type: "number";
  201. default: number;
  202. min: number;
  203. max?: number;
  204. step?: number;
  205. unit?: string | ((val: number) => string);
  206. } & FeatureFuncProps)
  207. | ({
  208. type: "select";
  209. default: string | number;
  210. options: SelectOption[] | (() => SelectOption[]);
  211. } & FeatureFuncProps)
  212. | ({
  213. type: "slider";
  214. default: number;
  215. min: number;
  216. max: number;
  217. step?: number;
  218. unit?: string | ((val: number) => string);
  219. } & FeatureFuncProps)
  220. | ({
  221. type: "hotkey";
  222. default: HotkeyObj;
  223. } & FeatureFuncProps)
  224. | {
  225. type: "text";
  226. default: string;
  227. normalize?: (val: string) => string;
  228. }
  229. | {
  230. type: "button";
  231. default: undefined;
  232. click: () => void;
  233. }
  234. type FeatureFuncProps = {
  235. /** Called to instantiate the feature on the page */
  236. enable: (featCfg: FeatureConfig) => void,
  237. } & (
  238. {
  239. /** Called to remove all traces of the feature from the page and memory (includes event listeners) */
  240. disable?: (feats: FeatureConfig) => void,
  241. }
  242. | {
  243. /** Called to update the feature's behavior when the config changes */
  244. change?: (feats: FeatureConfig) => void,
  245. }
  246. )
  247. /**
  248. * The feature info object that contains all properties necessary to construct the config menu and the feature config object.
  249. * Values are loosely typed so try to only use this with the `satisfies` keyword.
  250. * Use `typeof featInfo` (from `src/features/index.ts`) instead for full type safety.
  251. */
  252. export type FeatureInfo = Record<
  253. keyof FeatureConfig,
  254. {
  255. category: FeatureCategory;
  256. /**
  257. * HTML string that will be the help text for this feature
  258. * Specifying a function is useful for pluralizing or inserting values into the translation at runtime
  259. */
  260. helpText?: string | (() => string);
  261. /** Whether the value should be hidden in the config menu and from plugins */
  262. valueHidden?: boolean;
  263. /**
  264. * HTML string that is appended to the end of a feature's text description
  265. * @deprecated TODO:FIXME: To be removed or changed in the big menu rework
  266. */
  267. textAdornment?: () => (Promise<string | undefined> | string | undefined);
  268. /** Whether to only show this feature when advanced mode is activated (default false) */
  269. advanced?: boolean;
  270. }
  271. & FeatureTypeProps
  272. >;
  273. /** Feature configuration */
  274. export interface FeatureConfig {
  275. //#SECTION layout
  276. /** Show a BetterYTM watermark under the YTM logo */
  277. watermarkEnabled: boolean;
  278. /** Remove the "si" tracking parameter from links in the share popup */
  279. removeShareTrackingParam: boolean;
  280. /** Enable skipping to a specific time in the video by pressing a number key (0-9) */
  281. numKeysSkipToTime: boolean;
  282. /** Fix spacing issues in the layout */
  283. fixSpacing: boolean;
  284. /** Remove the \"Upgrade\" / YT Music Premium tab */
  285. removeUpgradeTab: boolean;
  286. //#SECTION volume
  287. /** Add a percentage label to the volume slider */
  288. volumeSliderLabel: boolean;
  289. /** The width of the volume slider in pixels */
  290. volumeSliderSize: number;
  291. /** Volume slider sensitivity - the smaller this number, the finer the volume control */
  292. volumeSliderStep: number;
  293. /** Volume slider scroll wheel sensitivity */
  294. volumeSliderScrollStep: number;
  295. /** Whether the volume should be locked to the same level across all tabs (changing in one changes in all others too) */
  296. volumeSharedBetweenTabs: boolean;
  297. /** Whether to set an initial volume level for each new session */
  298. setInitialTabVolume: boolean;
  299. /** The initial volume level to set for each new session */
  300. initialTabVolumeLevel: number;
  301. //#SECTION song lists
  302. /** Add a button to each song in the queue to quickly open its lyrics page */
  303. lyricsQueueButton: boolean;
  304. /** Add a button to each song in the queue to quickly remove it */
  305. deleteFromQueueButton: boolean;
  306. /** Where to place the buttons in the queue */
  307. listButtonsPlacement: "queueOnly" | "everywhere";
  308. /** Add a button to the queue to scroll to the currently playing song */
  309. scrollToActiveSongBtn: boolean;
  310. //#SECTION behavior
  311. /** Whether to completely disable the popup that sometimes appears before leaving the site */
  312. disableBeforeUnloadPopup: boolean;
  313. /** After how many milliseconds to close permanent toasts */
  314. closeToastsTimeout: number;
  315. /** Remember the last song's time when reloading or restoring the tab */
  316. rememberSongTime: boolean;
  317. /** Where to remember the song time */
  318. rememberSongTimeSites: Domain | "all";
  319. /** Time in seconds to remember the song time for */
  320. rememberSongTimeDuration: number;
  321. /** Time in seconds to subtract from the remembered song time */
  322. rememberSongTimeReduction: number;
  323. /** Minimum time in seconds the song needs to be played before it is remembered */
  324. rememberSongTimeMinPlayTime: number;
  325. //#SECTION input
  326. /** Arrow keys skip forwards and backwards */
  327. arrowKeySupport: boolean;
  328. /** By how many seconds to skip when pressing the arrow keys */
  329. arrowKeySkipBy: number;
  330. /** Add a hotkey to switch between the YT and YTM sites on a video / song */
  331. switchBetweenSites: boolean;
  332. /** The hotkey that needs to be pressed to initiate the site switch */
  333. switchSitesHotkey: HotkeyObj;
  334. /** Make it so middle clicking a song to open it in a new tab (through thumbnail and song title) is easier */
  335. anchorImprovements: boolean;
  336. //#SECTION lyrics
  337. /** Add a button to the media controls to open the current song's lyrics on genius.com in a new tab */
  338. geniusLyrics: boolean;
  339. /** Base URL to use for GeniURL */
  340. geniUrlBase: string;
  341. /** Token to use for GeniURL */
  342. geniUrlToken: string;
  343. /** Max size of lyrics cache */
  344. lyricsCacheMaxSize: number;
  345. /** Max TTL of lyrics cache entries, in ms */
  346. lyricsCacheTTL: number;
  347. /** Button to clear lyrics cache */
  348. clearLyricsCache: undefined;
  349. /** Whether to use advanced filtering when searching for lyrics (exact, exact-ish) */
  350. advancedLyricsFilter: boolean;
  351. //#SECTION misc
  352. /** The locale to use for translations */
  353. locale: TrLocale;
  354. /** Whether to check for updates to the script */
  355. versionCheck: boolean;
  356. /** Button to check for updates */
  357. checkVersionNow: undefined;
  358. /** The console log level - 0 = Debug, 1 = Info */
  359. logLevel: LogLevel;
  360. /** Whether to show advanced settings in the config menu */
  361. advancedMode: boolean;
  362. }