Cleanup unused Javascript (#3027)

* chore(js): be stricter about dead code warnings

* chore(js): remove dead code and unused exports

* rebase

* chore: remove unused files

* chore(deps): remove unused prop-types dep

* chore(js): remove unused function

* chore(deps): remove + check unused deps

* chore(js): remove unused exports. Closes #3036
This commit is contained in:
Gabe Kangas
2023-05-20 21:15:25 -07:00
committed by GitHub
parent 429289d508
commit e50b23d081
55 changed files with 1187 additions and 1071 deletions

View File

@@ -2,8 +2,7 @@ import React, { useState, FC, ReactElement } from 'react';
export const AlertMessageContext = React.createContext({
message: null,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setMessage: (text?: string) => null,
setMessage: (_text?: string) => null,
});
export type AlertMessageProviderProps = {

View File

@@ -10,12 +10,6 @@ export const FETCH_INTERVAL = 15000;
// Current inbound broadcaster info
export const STATUS = `${API_LOCATION}status`;
// Disconnect inbound stream
export const DISCONNECT = `${API_LOCATION}disconnect`;
// Change the current streaming key in memory
export const STREAMKEY_CHANGE = `${API_LOCATION}changekey`;
// Current server config
export const SERVER_CONFIG = `${API_LOCATION}serverconfig`;
@@ -91,9 +85,6 @@ export const CREATE_WEBHOOK = `${API_LOCATION}webhooks/create`;
// hard coded social icons list
export const SOCIAL_PLATFORMS_LIST = `${NEXT_PUBLIC_API_HOST}api/socialplatforms`;
// set external action links
export const EXTERNAL_ACTIONS = `${API_LOCATION}api/externalactions`;
// send a message to the fediverse
export const FEDERATION_MESSAGE_SEND = `${API_LOCATION}federation/send`;
@@ -119,8 +110,6 @@ export const UPDATE_STREAM_KEYS = `${API_LOCATION}config/streamkeys`;
export const API_YP_RESET = `${API_LOCATION}yp/reset`;
export const TEMP_UPDATER_API = LOGS_ALL;
const GITHUB_RELEASE_URL = 'https://api.github.com/repos/owncast/owncast/releases/latest';
interface FetchOptions {

View File

@@ -3,7 +3,7 @@ import { fetchData, SERVER_CONFIG_UPDATE_URL } from './apis';
import { ApiPostArgs, VideoVariant, SocialHandle } from '../types/config-section';
import { DEFAULT_TEXTFIELD_URL_PATTERN } from './validators';
export const TEXT_MAXLENGTH = 255;
const TEXT_MAXLENGTH = 255;
export const RESET_TIMEOUT = 3000;
@@ -11,41 +11,42 @@ export const RESET_TIMEOUT = 3000;
export const API_CUSTOM_CONTENT = '/pagecontent';
export const API_CUSTOM_CSS_STYLES = '/customstyles';
export const API_CUSTOM_JAVASCRIPT = '/customjavascript';
export const API_FFMPEG = '/ffmpegpath';
export const API_INSTANCE_URL = '/serverurl';
export const API_LOGO = '/logo';
export const API_NSFW_SWITCH = '/nsfw';
export const API_RTMP_PORT = '/rtmpserverport';
export const API_S3_INFO = '/s3';
export const API_SERVER_SUMMARY = '/serversummary';
export const API_SERVER_WELCOME_MESSAGE = '/welcomemessage';
export const API_SERVER_OFFLINE_MESSAGE = '/offlinemessage';
export const API_SERVER_NAME = '/name';
export const API_SOCIAL_HANDLES = '/socialhandles';
export const API_STREAM_KEY = '/adminpass';
export const API_STREAM_TITLE = '/streamtitle';
export const API_TAGS = '/tags';
export const API_USERNAME = '/name';
export const API_VIDEO_SEGMENTS = '/video/streamlatencylevel';
export const API_VIDEO_VARIANTS = '/video/streamoutputvariants';
export const API_WEB_PORT = '/webserverport';
export const API_YP_SWITCH = '/directoryenabled';
export const API_HIDE_VIEWER_COUNT = '/hideviewercount';
export const API_CHAT_DISABLE = '/chat/disable';
export const API_CHAT_JOIN_MESSAGES_ENABLED = '/chat/joinmessagesenabled';
export const API_CHAT_ESTABLISHED_MODE = '/chat/establishedusermode';
export const API_CHAT_FORBIDDEN_USERNAMES = '/chat/forbiddenusernames';
export const API_CHAT_SUGGESTED_USERNAMES = '/chat/suggestedusernames';
export const API_EXTERNAL_ACTIONS = '/externalactions';
export const API_VIDEO_CODEC = '/video/codec';
export const API_SOCKET_HOST_OVERRIDE = '/sockethostoverride';
const API_FFMPEG = '/ffmpegpath';
const API_INSTANCE_URL = '/serverurl';
const API_LOGO = '/logo';
const API_NSFW_SWITCH = '/nsfw';
const API_RTMP_PORT = '/rtmpserverport';
const API_SERVER_SUMMARY = '/serversummary';
const API_SERVER_WELCOME_MESSAGE = '/welcomemessage';
const API_SERVER_NAME = '/name';
const API_STREAM_KEY = '/adminpass';
const API_STREAM_TITLE = '/streamtitle';
const API_TAGS = '/tags';
const API_WEB_PORT = '/webserverport';
const API_HIDE_VIEWER_COUNT = '/hideviewercount';
const API_CHAT_DISABLE = '/chat/disable';
const API_CHAT_JOIN_MESSAGES_ENABLED = '/chat/joinmessagesenabled';
const API_CHAT_ESTABLISHED_MODE = '/chat/establishedusermode';
const API_SOCKET_HOST_OVERRIDE = '/sockethostoverride';
// Federation
export const API_FEDERATION_ENABLED = '/federation/enable';
export const API_FEDERATION_PRIVATE = '/federation/private';
export const API_FEDERATION_USERNAME = '/federation/username';
export const API_FEDERATION_GOLIVE_MESSAGE = '/federation/livemessage';
export const API_FEDERATION_SHOW_ENGAGEMENT = '/federation/showengagement';
const API_FEDERATION_ENABLED = '/federation/enable';
const API_FEDERATION_PRIVATE = '/federation/private';
const API_FEDERATION_USERNAME = '/federation/username';
const API_FEDERATION_GOLIVE_MESSAGE = '/federation/livemessage';
const API_FEDERATION_SHOW_ENGAGEMENT = '/federation/showengagement';
export const API_FEDERATION_BLOCKED_DOMAINS = '/federation/blockdomains';
const TEXTFIELD_TYPE_URL = 'url';
@@ -467,10 +468,6 @@ export const DEFAULT_SOCIAL_HANDLE: SocialHandle = {
export const OTHER_SOCIAL_HANDLE_OPTION = 'OTHER_SOCIAL_HANDLE_OPTION';
export const TEXTFIELD_PROPS_S3_COMMON = {
maxLength: 255,
};
export const S3_TEXT_FIELDS_INFO = {
accessKey: {
fieldName: 'accessKey',

View File

@@ -1,78 +1 @@
// misc constants used throughout the app
export const URL_STATUS = `/api/status`;
export const URL_CHAT_HISTORY = `/api/chat`;
export const URL_CUSTOM_EMOJIS = `/api/emoji`;
export const URL_CONFIG = `/api/config`;
export const URL_VIEWER_PING = `/api/ping`;
// inline moderation actions
export const URL_HIDE_MESSAGE = `/api/chat/messagevisibility`;
export const URL_BAN_USER = `/api/chat/users/setenabled`;
// TODO: This directory is customizable in the config. So we should expose this via the config API.
export const URL_STREAM = `/hls/stream.m3u8`;
// export const URL_WEBSOCKET = `${location.protocol === 'https:' ? 'wss' : 'ws'}://${
// location.host
// }/ws`;
export const URL_CHAT_REGISTRATION = `/api/chat/register`;
export const URL_FOLLOWERS = `/api/followers`;
export const URL_PLAYBACK_METRICS = `/api/metrics/playback`;
export const URL_REGISTER_NOTIFICATION = `/api/notifications/register`;
export const URL_REGISTER_EMAIL_NOTIFICATION = `/api/notifications/register/email`;
export const URL_CHAT_INDIEAUTH_BEGIN = `/api/auth/indieauth`;
export const TIMER_STATUS_UPDATE = 5000; // ms
export const TIMER_DISABLE_CHAT_AFTER_OFFLINE = 5 * 60 * 1000; // 5 mins
export const TIMER_STREAM_DURATION_COUNTER = 1000;
export const TEMP_IMAGE =
'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7';
export const OWNCAST_LOGO_LOCAL = '/img/logo.svg';
export const MESSAGE_OFFLINE = 'Stream is offline.';
export const MESSAGE_ONLINE = 'Stream is online.';
export const URL_OWNCAST = 'https://owncast.online'; // used in footer
export const PLAYER_VOLUME = 'owncast_volume';
export const KEY_ACCESS_TOKEN = 'owncast_access_token';
export const KEY_EMBED_CHAT_ACCESS_TOKEN = 'owncast_embed_chat_access_token';
export const KEY_USERNAME = 'owncast_username';
export const KEY_CUSTOM_USERNAME_SET = 'owncast_custom_username_set';
export const KEY_CHAT_DISPLAYED = 'owncast_chat';
export const KEY_CHAT_FIRST_MESSAGE_SENT = 'owncast_first_message_sent';
export const CHAT_INITIAL_PLACEHOLDER_TEXT = 'Type here to chat, no account necessary.';
export const CHAT_PLACEHOLDER_TEXT = 'Message';
export const CHAT_PLACEHOLDER_OFFLINE = 'Chat is offline.';
export const CHAT_MAX_MESSAGE_LENGTH = 500;
export const EST_SOCKET_PAYLOAD_BUFFER = 512;
export const CHAT_CHAR_COUNT_BUFFER = 20;
export const CHAT_OK_KEYCODES = [
'ArrowLeft',
'ArrowUp',
'ArrowRight',
'ArrowDown',
'Shift',
'Meta',
'Alt',
'Delete',
'Backspace',
];
export const CHAT_KEY_MODIFIERS = ['Control', 'Shift', 'Meta', 'Alt'];
export const MESSAGE_JUMPTOBOTTOM_BUFFER = 500;
// app styling
export const WIDTH_SINGLE_COL = 780;
export const HEIGHT_SHORT_WIDE = 500;
export const ORIENTATION_PORTRAIT = 'portrait';
export const ORIENTATION_LANDSCAPE = 'landscape';
// localstorage keys
export const HAS_DISPLAYED_NOTIFICATION_MODAL_KEY = 'HAS_DISPLAYED_NOTIFICATION_MODAL';
export const USER_VISIT_COUNT_KEY = 'USER_VISIT_COUNT';
export const USER_DISMISSED_ANNOYING_NOTIFICATION_POPUP_KEY =
'USER_DISMISSED_ANNOYING_NOTIFICATION_POPUP_KEY';
export const DYNAMIC_PADDING_VALUE = '320px';

View File

@@ -20,7 +20,7 @@ export function isEmptyObject(obj) {
return !obj || (Object.keys(obj).length === 0 && obj.constructor === Object);
}
export function padLeft(text, pad, size) {
function padLeft(text, pad, size) {
return String(pad.repeat(size) + text).slice(-size);
}
@@ -42,13 +42,6 @@ export function parseSecondsToDurationString(seconds = 0) {
return daysString + hoursString + minString + secsString;
}
export function makeAndStringFromArray(arr: string[]): string {
if (arr.length === 1) return arr[0];
const firsts = arr.slice(0, arr.length - 1);
const last = arr[arr.length - 1];
return `${firsts.join(', ')} and ${last}`;
}
export function formatUAstring(uaString: string) {
const parser = UAParser(uaString);
const { device, os, browser } = parser;

View File

@@ -1,8 +1,3 @@
// convert newlines to <br>s
export function addNewlines(str) {
return str.replace(/(?:\r\n|\r|\n)/g, '<br />');
}
export function pluralize(string, count) {
if (count === 1) {
return string;
@@ -10,149 +5,11 @@ export function pluralize(string, count) {
return `${string}s`;
}
// Trying to determine if browser is mobile/tablet.
// Source: https://developer.mozilla.org/en-US/docs/Web/HTTP/Browser_detection_using_the_user_agent
export function hasTouchScreen() {
let hasTouch = false;
if ('maxTouchPoints' in navigator) {
hasTouch = navigator.maxTouchPoints > 0;
} else if ('msMaxTouchPoints' in navigator) {
hasTouch = navigator.msMaxTouchPoints > 0;
} else {
const mQ = window.matchMedia && matchMedia('(pointer:coarse)');
if (mQ && mQ.media === '(pointer:coarse)') {
hasTouch = !!mQ.matches;
} else if ('orientation' in window) {
hasTouch = true; // deprecated, but good fallback
} else {
// Only as a last resort, fall back to user agent sniffing
hasTouch = navigator.userAgentData.mobile;
}
}
return hasTouch;
}
export function padLeft(text, pad, size) {
return String(pad.repeat(size) + text).slice(-size);
}
export function parseSecondsToDurationString(seconds = 0) {
const finiteSeconds = Number.isFinite(+seconds) ? Math.abs(seconds) : 0;
const days = Math.floor(finiteSeconds / 86400);
const daysString = days > 0 ? `${days} day${days > 1 ? 's' : ''} ` : '';
const hours = Math.floor((finiteSeconds / 3600) % 24);
const hoursString = hours || days ? padLeft(`${hours}:`, '0', 3) : '';
const mins = Math.floor((finiteSeconds / 60) % 60);
const minString = padLeft(`${mins}:`, '0', 3);
const secs = Math.floor(finiteSeconds % 60);
const secsString = padLeft(`${secs}`, '0', 2);
return daysString + hoursString + minString + secsString;
}
export function setVHvar() {
const vh = window.innerHeight * 0.01;
// Then we set the value in the --vh custom property to the root of the document
document.documentElement.style.setProperty('--vh', `${vh}px`);
}
export function doesObjectSupportFunction(object, functionName) {
return typeof object[functionName] === 'function';
}
// return a string of css classes
export function classNames(json) {
const classes = [];
Object.entries(json).map(item => {
const [key, value] = item;
if (value) {
classes.push(key);
}
return null;
});
return classes.join(' ');
}
// taken from
// https://medium.com/@TCAS3/debounce-deep-dive-javascript-es6-e6f8d983b7a1
export function debounce(fn, time) {
let timeout;
return function () {
// eslint-disable-next-line prefer-rest-params
const functionCall = () => fn.apply(this, arguments);
clearTimeout(timeout);
timeout = setTimeout(functionCall, time);
};
}
export function getDiffInDaysFromNow(timestamp) {
const time = typeof timestamp === 'string' ? new Date(timestamp) : timestamp;
return (new Date() - time) / (24 * 3600 * 1000);
}
// "Last live today at [time]" or "last live [date]"
export function makeLastOnlineString(timestamp) {
if (!timestamp) {
return '';
}
let string = '';
const time = new Date(timestamp);
const comparisonDate = new Date(time).setHours(0, 0, 0, 0);
if (comparisonDate === new Date().setHours(0, 0, 0, 0)) {
const atTime = time.toLocaleTimeString([], {
hour: '2-digit',
minute: '2-digit',
});
string = `Today ${atTime}`;
} else {
string = time.toLocaleDateString();
}
return `Last live: ${string}`;
}
// Routing & Tabs
export const ROUTE_RECORDINGS = 'recordings';
export const ROUTE_SCHEDULE = 'schedule';
// looks for `/recording|schedule/id` pattern to determine what to display from the tab view
export function checkUrlPathForDisplay() {
const pathTest = [ROUTE_RECORDINGS, ROUTE_SCHEDULE];
const pathParts = window.location.pathname.split('/');
if (pathParts.length >= 2) {
const part = pathParts[1].toLowerCase();
if (pathTest.includes(part)) {
return {
section: part,
sectionId: pathParts[2] || '',
};
}
}
return null;
}
export function paginateArray(items, page, perPage) {
const offset = perPage * (page - 1);
const totalPages = Math.ceil(items.length / perPage);
const paginatedItems = items.slice(offset, perPage * page);
return {
previousPage: page - 1 ? page - 1 : null,
nextPage: totalPages > page ? page + 1 : null,
total: items.length,
totalPages,
items: paginatedItems,
};
}
// Take a nested object of state metadata and merge it into
// a single flattened node.
export function mergeMeta(meta) {

View File

@@ -1,32 +0,0 @@
import { useState, useEffect } from 'react';
export default function useWindowSize() {
// Initialize state with undefined width/height so server and client renders match
// Learn more here: https://joshwcomeau.com/react/the-perils-of-rehydration/
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
// Handler to call on window resize
function handleResize() {
// Set window width/height to state
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
// Add event listener
window.addEventListener('resize', handleResize);
// Call handler right away so state gets updated with initial window size
handleResize();
// Remove event listener on cleanup
return () => window.removeEventListener('resize', handleResize);
}, []); // Empty array ensures that effect is only run on mount
return windowSize;
}

View File

@@ -18,14 +18,13 @@ const WarningOutlined = dynamic(() => import('@ant-design/icons/WarningOutlined'
ssr: false,
});
export const STATUS_RESET_TIMEOUT = 3000;
export const STATUS_ERROR = 'error';
export const STATUS_INVALID = 'invalid';
export const STATUS_PROCESSING = 'proessing';
export const STATUS_SUCCESS = 'success';
export const STATUS_WARNING = 'warning';
const STATUS_INVALID = 'invalid';
export type InputStatusTypes = 'error' | 'invalid' | 'proessing' | 'success' | 'warning';
export interface StatusState {
@@ -37,7 +36,7 @@ interface InputStates {
[key: string]: StatusState;
}
export const INPUT_STATES: InputStates = {
const INPUT_STATES: InputStates = {
[STATUS_SUCCESS]: {
type: STATUS_SUCCESS,
icon: <CheckCircleFilled style={{ color: 'green' }} />,

View File

@@ -7,7 +7,9 @@ export const LOCAL_STORAGE_KEYS = {
export function getLocalStorage(key) {
try {
return localStorage.getItem(key);
} catch (e) {}
} catch (e) {
console.error(e);
}
return null;
}
@@ -19,31 +21,8 @@ export function setLocalStorage(key, value) {
localStorage.removeItem(key);
}
return true;
} catch (e) {}
} catch (e) {
console.error(e);
}
return false;
}
export function clearLocalStorage(key) {
localStorage.removeItem(key);
}
// jump down to the max height of a div, with a slight delay
export function jumpToBottom(element, behavior) {
if (!element) return;
if (!behavior) {
behavior = document.visibilityState === 'visible' ? 'smooth' : 'instant';
}
setTimeout(
() => {
element.scrollTo({
top: element.scrollHeight,
left: 0,
behavior,
});
},
50,
element,
);
}

View File

@@ -6,7 +6,7 @@ import { STATUS, fetchData, FETCH_INTERVAL, SERVER_CONFIG } from './apis';
import { ConfigDetails, UpdateArgs } from '../types/config-section';
import { DEFAULT_VARIANT_STATE } from './config-constants';
export const initialServerConfigState: ConfigDetails = {
const initialServerConfigState: ConfigDetails = {
streamKeys: [],
streamKeyOverridden: false,
adminPassword: '',
@@ -102,7 +102,7 @@ export const ServerStatusContext = React.createContext({
serverConfig: initialServerConfigState,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
setFieldInConfigState: (args: UpdateArgs) => null,
setFieldInConfigState: (_args: UpdateArgs) => null,
});
export type ServerStatusProviderProps = {