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
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
55 changed files with 1187 additions and 1071 deletions

View file

@ -67,3 +67,30 @@ jobs:
- name: Lint - name: Lint
run: npm run lint run: npm run lint
unused-code:
name: Test for unused code
runs-on: ubuntu-latest
defaults:
run:
working-directory: ./web
steps:
- id: skip_check
uses: fkirc/skip-duplicate-actions@v5
with:
concurrent_skipping: 'same_content_newer'
- name: Checkout
uses: actions/checkout@v3
with:
# Make sure the actual branch is checked out when running on pull requests
ref: ${{ github.event.pull_request.head.ref }}
repository: ${{ github.event.pull_request.head.repo.full_name }}
fetch-depth: 0
- name: Install Dependencies
run: npm install
- name: Check for unused JS code and dependencies
run: npx knip --include dependencies,files,exports

View file

@ -19,7 +19,7 @@ module.exports = {
ecmaVersion: 12, ecmaVersion: 12,
sourceType: 'module', sourceType: 'module',
}, },
plugins: ['react', 'prettier', '@typescript-eslint'], plugins: ['react', 'prettier', '@typescript-eslint', 'import'],
ignorePatterns: ['!./storybook/**'], ignorePatterns: ['!./storybook/**'],
rules: { rules: {
'prettier/prettier': 'error', 'prettier/prettier': 'error',
@ -75,6 +75,7 @@ module.exports = {
peerDependencies: true, peerDependencies: true,
}, },
], ],
'import/no-unused-modules': [1, { unusedExports: true }],
}, },
settings: { settings: {
'import/resolver': { 'import/resolver': {

72
web/.knip.json Normal file
View file

@ -0,0 +1,72 @@
{
"ignore": [
"**/.eslintrc.js",
".storybook/**",
"**/*config.?s",
"**/*mock.?s",
"**/*fixture.?s",
"next-env.d.ts",
"public/**"
],
"ignoreDependencies": [
"@fontsource/inter",
"@fontsource/poppins",
"@next/bundle-analyzer",
"autoprefixer",
"webpack-deadcode-plugin",
"yaml",
"postcss-flexbugs-fixes",
"sharp",
"next-with-less",
"next-pwa",
"workbox-precaching",
"workbox-window",
"@storybook/addon-a11y",
"@storybook/addon-docs",
"@storybook/addon-essentials",
"@storybook/addon-links",
"@storybook/addon-postcss",
"@storybook/addon-viewport",
"@storybook/builder-webpack5",
"@storybook/cli",
"@storybook/manager-webpack5",
"@storybook/mdx2-csf",
"@storybook/preset-scss",
"@mdx-js/react",
"@storybook/testing-library",
"@svgr/webpack",
"@types/jest",
"@types/markdown-it",
"@types/prop-types",
"@typescript-eslint/eslint-plugin",
"@typescript-eslint/parser",
"babel-loader",
"chromatic",
"css-loader",
"cypress",
"eslint-config-airbnb",
"eslint-config-next",
"eslint-config-prettier",
"eslint-plugin-import",
"eslint-plugin-jsx-a11y",
"eslint-plugin-prettier",
"eslint-plugin-react",
"eslint-plugin-react-hooks",
"eslint-plugin-storybook",
"handlebars",
"html-webpack-plugin",
"install",
"less",
"less-loader",
"mdx-mermaid",
"mermaid",
"prettier",
"sass-loader",
"sb",
"storybook-addon-designs",
"storybook-addon-fetch-mock",
"storybook-preset-less",
"style-loader",
"ts-jest"
]
}

View file

@ -1,71 +0,0 @@
// Note: references to "yp" in the app are likely related to Owncast Directory
import React, { useState, useContext, useEffect, FC } from 'react';
import { Typography } from 'antd';
import { ToggleSwitch } from './ToggleSwitch';
import { ServerStatusContext } from '../../utils/server-status-context';
import { FIELD_PROPS_NSFW, FIELD_PROPS_YP } from '../../utils/config-constants';
const { Title } = Typography;
// eslint-disable-next-line import/prefer-default-export
export const EditYPDetails: FC = () => {
const [formDataValues, setFormDataValues] = useState(null);
const serverStatusData = useContext(ServerStatusContext);
const { serverConfig } = serverStatusData || {};
const { yp, instanceDetails } = serverConfig;
const { nsfw } = instanceDetails;
const { enabled, instanceUrl } = yp;
useEffect(() => {
setFormDataValues({
...yp,
enabled,
nsfw,
});
}, [yp, instanceDetails]);
const hasInstanceUrl = instanceUrl !== '';
if (!formDataValues) {
return null;
}
return (
<div className="config-directory-details-form">
<Title level={3} className="section-title">
Owncast Directory Settings
</Title>
<p className="description">
Would you like to appear in the{' '}
<a href="https://directory.owncast.online" target="_blank" rel="noreferrer">
<strong>Owncast Directory</strong>
</a>
?
</p>
<p style={{ backgroundColor: 'black', fontSize: '.75rem', padding: '5px' }}>
<em>
NOTE: You will need to have a URL specified in the <code>Instance URL</code> field to be
able to use this.
</em>
</p>
<div className="config-yp-container">
<ToggleSwitch
fieldName="enabled"
{...FIELD_PROPS_YP}
checked={formDataValues.enabled}
disabled={!hasInstanceUrl}
/>
<ToggleSwitch
fieldName="nsfw"
{...FIELD_PROPS_NSFW}
checked={formDataValues.nsfw}
disabled={!hasInstanceUrl}
/>
</div>
</div>
);
};

View file

@ -1,27 +0,0 @@
import { Tooltip } from 'antd';
import dynamic from 'next/dynamic';
import { FC } from 'react';
// Lazy loaded components
const InfoCircleOutlined = dynamic(() => import('@ant-design/icons/InfoCircleOutlined'), {
ssr: false,
});
export type InfoTipProps = {
tip: string | null;
};
export const InfoTip: FC<InfoTipProps> = ({ tip }) => {
if (tip === '' || tip === null) {
return null;
}
return (
<span className="info-tip">
<Tooltip title={tip}>
<InfoCircleOutlined />
</Tooltip>
</span>
);
};

View file

@ -1,31 +0,0 @@
import { Table, Typography } from 'antd';
import { FC } from 'react';
const { Title } = Typography;
export type KeyValueTableProps = {
title: string;
data: any;
};
export const KeyValueTable: FC<KeyValueTableProps> = ({ title, data }) => {
const columns = [
{
title: 'Name',
dataIndex: 'name',
key: 'name',
},
{
title: 'Value',
dataIndex: 'value',
key: 'value',
},
];
return (
<>
<Title level={2}>{title}</Title>
<Table pagination={false} columns={columns} dataSource={data} rowKey="name" />
</>
);
};

View file

@ -174,4 +174,3 @@ export const Offline: FC<OfflineProps> = ({ logs = [], config }) => {
</> </>
); );
}; };
export default Offline;

View file

@ -212,7 +212,6 @@ export const TextField: FC<TextFieldProps> = ({
</div> </div>
); );
}; };
export default TextField;
TextField.defaultProps = { TextField.defaultProps = {
className: '', className: '',

View file

@ -14,9 +14,6 @@ import { ServerStatusContext } from '../../utils/server-status-context';
import { FormStatusIndicator } from './FormStatusIndicator'; import { FormStatusIndicator } from './FormStatusIndicator';
import { TextField, TextFieldProps } from './TextField'; import { TextField, TextFieldProps } from './TextField';
export const TEXTFIELD_TYPE_TEXT = 'default';
export const TEXTFIELD_TYPE_PASSWORD = 'password'; // Input.Password
export const TEXTFIELD_TYPE_NUMBER = 'numeric';
export const TEXTFIELD_TYPE_TEXTAREA = 'textarea'; export const TEXTFIELD_TYPE_TEXTAREA = 'textarea';
export const TEXTFIELD_TYPE_URL = 'url'; export const TEXTFIELD_TYPE_URL = 'url';

View file

@ -106,7 +106,6 @@ export const ToggleSwitch: FC<ToggleSwitchProps> = ({
</div> </div>
); );
}; };
export default ToggleSwitch;
ToggleSwitch.defaultProps = { ToggleSwitch.defaultProps = {
apiPath: '', apiPath: '',

View file

@ -1,15 +1,10 @@
import { Table } from 'antd'; import { Table } from 'antd';
import format from 'date-fns/format';
import { SortOrder } from 'antd/lib/table/interface'; import { SortOrder } from 'antd/lib/table/interface';
import { formatDistanceToNow } from 'date-fns'; import { formatDistanceToNow } from 'date-fns';
import { FC } from 'react'; import { FC } from 'react';
import { User } from '../../types/chat'; import { User } from '../../types/chat';
import { formatUAstring } from '../../utils/format'; import { formatUAstring } from '../../utils/format';
export function formatDisplayDate(date: string | Date) {
return format(new Date(date), 'MMM d H:mma');
}
export type ViewerTableProps = { export type ViewerTableProps = {
data: User[]; data: User[];
}; };

View file

@ -214,7 +214,7 @@ export default function EditSocialLinks() {
title: 'Social Link', title: 'Social Link',
dataIndex: '', dataIndex: '',
key: 'combo', key: 'combo',
render: (data, record) => { render: (_, record) => {
const { platform, url } = record; const { platform, url } = record;
const platformInfo = isPredefinedSocial(platform); const platformInfo = isPredefinedSocial(platform);
@ -251,7 +251,7 @@ export default function EditSocialLinks() {
title: '', title: '',
dataIndex: '', dataIndex: '',
key: 'edit', key: 'edit',
render: (data, record, index) => ( render: (_, _record, index) => (
<div className="actions"> <div className="actions">
<Button <Button
size="small" size="small"

View file

@ -19,7 +19,7 @@ import { FormStatusIndicator } from '../FormStatusIndicator';
const { Title } = Typography; const { Title } = Typography;
export const ConfigNotify = () => { export const BrowserNotify = () => {
const serverStatusData = useContext(ServerStatusContext); const serverStatusData = useContext(ServerStatusContext);
const { serverConfig, setFieldInConfigState } = serverStatusData || {}; const { serverConfig, setFieldInConfigState } = serverStatusData || {};
const { notifications } = serverConfig || {}; const { notifications } = serverConfig || {};
@ -127,4 +127,3 @@ export const ConfigNotify = () => {
</> </>
); );
}; };
export default ConfigNotify;

View file

@ -19,7 +19,7 @@ import { UpdateArgs } from '../../../types/config-section';
const { Title } = Typography; const { Title } = Typography;
export const ConfigNotify = () => { export const DiscordNotify = () => {
const serverStatusData = useContext(ServerStatusContext); const serverStatusData = useContext(ServerStatusContext);
const { serverConfig, setFieldInConfigState } = serverStatusData || {}; const { serverConfig, setFieldInConfigState } = serverStatusData || {};
const { notifications } = serverConfig || {}; const { notifications } = serverConfig || {};
@ -151,4 +151,3 @@ export const ConfigNotify = () => {
</> </>
); );
}; };
export default ConfigNotify;

View file

@ -5,7 +5,7 @@ import { ServerStatusContext } from '../../../utils/server-status-context';
const { Title } = Typography; const { Title } = Typography;
export const ConfigNotify = () => { export const FediverseNotify = () => {
const serverStatusData = useContext(ServerStatusContext); const serverStatusData = useContext(ServerStatusContext);
const { serverConfig } = serverStatusData || {}; const { serverConfig } = serverStatusData || {};
const { federation } = serverConfig || {}; const { federation } = serverConfig || {};
@ -49,4 +49,3 @@ export const ConfigNotify = () => {
</> </>
); );
}; };
export default ConfigNotify;

View file

@ -139,7 +139,7 @@ export const ChatModerationDetailsModal: FC<ChatModerationDetailsModalProps> = (
{ {
title: 'Delete', title: 'Delete',
key: 'delete', key: 'delete',
render: (text, record) => ( render: (_text, record) => (
<Button <Button
type="primary" type="primary"
ghost ghost

View file

@ -1,8 +1,5 @@
import { convertToText } from '../chat';
import { getDiffInDaysFromNow } from '../../../utils/helpers'; import { getDiffInDaysFromNow } from '../../../utils/helpers';
const convertToMarkup = (str = '') => convertToText(str).replace(/\n/g, '<p></p>');
export function formatTimestamp(sentAt: Date) { export function formatTimestamp(sentAt: Date) {
const now = new Date(sentAt); const now = new Date(sentAt);
if (Number.isNaN(now)) return ''; if (Number.isNaN(now)) return '';
@ -18,14 +15,3 @@ export function formatTimestamp(sentAt: Date) {
return `${now.toLocaleTimeString()}`; return `${now.toLocaleTimeString()}`;
} }
/*
You would call this when receiving a plain text
value back from an API, and before inserting the
text into the `contenteditable` area on a page.
*/
export function formatMessageText(message: string) {
const formattedText = convertToMarkup(message);
return formattedText;
}

View file

@ -1,142 +0,0 @@
// import {
// CHAT_INITIAL_PLACEHOLDER_TEXT,
// CHAT_PLACEHOLDER_TEXT,
// CHAT_PLACEHOLDER_OFFLINE,
// } from './constants.js';
// Taken from https://stackoverflow.com/a/46902361
export function getCaretPosition(node) {
const selection = window.getSelection();
if (selection.rangeCount === 0) {
return 0;
}
const range = selection.getRangeAt(0);
const preCaretRange = range.cloneRange();
const tempElement = document.createElement('div');
preCaretRange.selectNodeContents(node);
preCaretRange.setEnd(range.endContainer, range.endOffset);
tempElement.appendChild(preCaretRange.cloneContents());
return tempElement.innerHTML.length;
}
// Might not need this anymore
// Pieced together from parts of https://stackoverflow.com/questions/6249095/how-to-set-caretcursor-position-in-contenteditable-element-div
export function setCaretPosition(editableDiv, position) {
const range = document.createRange();
const sel = window.getSelection();
range.selectNode(editableDiv);
range.setStart(editableDiv.childNodes[0], position);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
// export function generatePlaceholderText(isEnabled, hasSentFirstChatMessage) {
// if (isEnabled) {
// return hasSentFirstChatMessage
// ? CHAT_PLACEHOLDER_TEXT
// : CHAT_INITIAL_PLACEHOLDER_TEXT;
// }
// return CHAT_PLACEHOLDER_OFFLINE;
// }
export function extraUserNamesFromMessageHistory(messages) {
const list = [];
if (messages) {
messages
.filter(m => m.user && m.user.displayName)
.forEach(message => {
if (!list.includes(message.user.displayName)) {
list.push(message.user.displayName);
}
});
}
return list;
}
// utils from https://gist.github.com/nathansmith/86b5d4b23ed968a92fd4
/*
You would call this after getting an element's
`.innerHTML` value, while the user is typing.
*/
export function convertToText(str = '') {
// Ensure string.
let value = String(str);
// Convert encoding.
value = value.replace(/&nbsp;/gi, ' ');
value = value.replace(/&amp;/gi, '&');
// Replace `<br>`.
value = value.replace(/<br>/gi, '\n');
// Replace `<div>` (from Chrome).
value = value.replace(/<div>/gi, '\n');
// Replace `<p>` (from IE).
value = value.replace(/<p>/gi, '\n');
// Cleanup the emoji titles.
value = value.replace(/\u200C{2}/gi, '');
// Trim each line.
value = value
.split('\n')
.map((line = '') => line.trim())
.join('\n');
// No more than 2x newline, per "paragraph".
value = value.replace(/\n\n+/g, '\n\n');
// Clean up spaces.
value = value.replace(/[ ]+/g, ' ');
value = value.trim();
// Expose string.
return value;
}
export function createEmojiMarkup(data, isCustom) {
const emojiUrl = isCustom ? data.emoji : data.url;
const emojiName = (
isCustom ? data.name : data.url.split('\\').pop().split('/').pop().split('.').shift()
).toLowerCase();
return `<img class="emoji" alt=":${emojiName}:" title=":${emojiName}:" src="${emojiUrl}"/>`;
}
// trim html white space characters from ends of messages for more accurate counting
export function trimNbsp(html) {
return html.replace(/^(?:&nbsp;|\s)+|(?:&nbsp;|\s)+$/gi, '');
}
export function emojify(HTML, emojiList) {
const textValue = convertToText(HTML);
// eslint-disable-next-line no-plusplus
for (let lastPos = textValue.length; lastPos >= 0; lastPos--) {
const endPos = textValue.lastIndexOf(':', lastPos);
if (endPos <= 0) {
break;
}
const startPos = textValue.lastIndexOf(':', endPos - 1);
if (startPos === -1) {
break;
}
const typedEmoji = textValue.substring(startPos + 1, endPos).trim();
const emojiIndex = emojiList.findIndex(
emojiItem => emojiItem.name.toLowerCase() === typedEmoji.toLowerCase(),
);
if (emojiIndex !== -1) {
const emojiImgElement = createEmojiMarkup(emojiList[emojiIndex], true);
// eslint-disable-next-line no-param-reassign
HTML = HTML.replace(`:${typedEmoji}:`, emojiImgElement);
}
}
return HTML;
}

View file

@ -34,7 +34,7 @@ export default {
} as ComponentMeta<typeof BrowserNotifyModal>; } as ComponentMeta<typeof BrowserNotifyModal>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
const Template: ComponentStory<typeof BrowserNotifyModal> = args => ( const Template: ComponentStory<typeof BrowserNotifyModal> = () => (
<RecoilRoot> <RecoilRoot>
<Example /> <Example />
</RecoilRoot> </RecoilRoot>

View file

@ -32,7 +32,7 @@ export default {
} as ComponentMeta<typeof FollowModal>; } as ComponentMeta<typeof FollowModal>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
const Template: ComponentStory<typeof FollowModal> = args => <Example />; const Template: ComponentStory<typeof FollowModal> = () => <Example />;
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
export const Basic = Template.bind({}); export const Basic = Template.bind({});

View file

@ -22,7 +22,7 @@ export default {
} as ComponentMeta<typeof IndieAuthModal>; } as ComponentMeta<typeof IndieAuthModal>;
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
const Template: ComponentStory<typeof IndieAuthModal> = args => <Example />; const Template: ComponentStory<typeof IndieAuthModal> = () => <Example />;
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
export const Basic = Template.bind({}); export const Basic = Template.bind({});

View file

@ -55,7 +55,7 @@ export const NameChangeModal: FC = () => {
}; };
const maxColor = 8; // 0...n const maxColor = 8; // 0...n
const colorOptions = [...Array(maxColor)].map((e, i) => i); const colorOptions = [...Array(maxColor)].map((_, i) => i);
const saveButton = ( const saveButton = (
<Button <Button

View file

@ -23,9 +23,9 @@ import {
FediverseEvent, FediverseEvent,
} from '../../interfaces/socket-events'; } from '../../interfaces/socket-events';
import { mergeMeta } from '../../utils/helpers'; import { mergeMeta } from '../../utils/helpers';
import handleConnectedClientInfoMessage from './eventhandlers/connected-client-info-handler'; import { handleConnectedClientInfoMessage } from './eventhandlers/connected-client-info-handler';
import { ServerStatusServiceContext } from '../../services/status-service'; import { ServerStatusServiceContext } from '../../services/status-service';
import handleNameChangeEvent from './eventhandlers/handleNameChangeEvent'; import { handleNameChangeEvent } from './eventhandlers/handleNameChangeEvent';
import { DisplayableError } from '../../types/displayable-error'; import { DisplayableError } from '../../types/displayable-error';
RecoilEnv.RECOIL_DUPLICATE_ATOM_KEY_CHECKING_ENABLED = false; RecoilEnv.RECOIL_DUPLICATE_ATOM_KEY_CHECKING_ENABLED = false;
@ -108,7 +108,7 @@ export const clockSkewAtom = atom<Number>({
default: 0.0, default: 0.0,
}); });
export const removedMessageIdsAtom = atom<string[]>({ const removedMessageIdsAtom = atom<string[]>({
key: 'removedMessageIds', key: 'removedMessageIds',
default: [], default: [],
}); });

View file

@ -16,4 +16,3 @@ export function handleConnectedClientInfoMessage(
isModerator: scopes?.includes('MODERATOR'), isModerator: scopes?.includes('MODERATOR'),
}); });
} }
export default handleConnectedClientInfoMessage;

View file

@ -3,4 +3,3 @@ import { ChatEvent } from '../../../interfaces/socket-events';
export function handleNameChangeEvent(message: ChatEvent, setChatMessages) { export function handleNameChangeEvent(message: ChatEvent, setChatMessages) {
setChatMessages(currentState => [...currentState, message]); setChatMessages(currentState => [...currentState, message]);
} }
export default handleNameChangeEvent;

View file

@ -308,4 +308,3 @@ export const Content: FC = () => {
</> </>
); );
}; };
export default Content;

View file

@ -70,7 +70,6 @@ export const CrossfadeImage: FC<CrossfadeImageProps> = ({
</span> </span>
); );
}; };
export default CrossfadeImage;
CrossfadeImage.defaultProps = { CrossfadeImage.defaultProps = {
objectFit: 'fill', objectFit: 'fill',

View file

@ -33,4 +33,3 @@ export const Footer: FC<FooterProps> = ({ dynamicPaddingValue }) => {
</footer> </footer>
); );
}; };
export default Footer;

View file

@ -12,4 +12,3 @@ export const Logo: FC<LogoProps> = ({ src }) => (
</div> </div>
</div> </div>
); );
export default Logo;

View file

@ -1,29 +0,0 @@
import { CSSProperties, FC } from 'react';
export type ModIconProps = {
style?: CSSProperties;
fill?: string;
stroke?: string;
};
export const ModIcon: FC<ModIconProps> = ({
style = { width: '1rem', height: '1rem' },
fill = 'none',
stroke = 'var(--color-owncast-gray-300)',
}: ModIconProps) => (
<svg
fill={fill}
stroke={stroke}
style={style}
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<title>This user has moderation rights</title>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"
/>
</svg>
);

View file

@ -84,7 +84,6 @@ export const Statusbar: FC<StatusbarProps> = ({
</div> </div>
); );
}; };
export default Statusbar;
Statusbar.defaultProps = { Statusbar.defaultProps = {
lastConnectTime: null, lastConnectTime: null,

View file

@ -9,7 +9,7 @@ import { VideoPoster } from '../VideoPoster/VideoPoster';
import { getLocalStorage, setLocalStorage } from '../../../utils/localStorage'; import { getLocalStorage, setLocalStorage } from '../../../utils/localStorage';
import { isVideoPlayingAtom, clockSkewAtom } from '../../stores/ClientConfigStore'; import { isVideoPlayingAtom, clockSkewAtom } from '../../stores/ClientConfigStore';
import PlaybackMetrics from '../metrics/playback'; import PlaybackMetrics from '../metrics/playback';
import createVideoSettingsMenuButton from '../settings-menu'; import { createVideoSettingsMenuButton } from '../settings-menu';
import LatencyCompensator from '../latencyCompensator'; import LatencyCompensator from '../latencyCompensator';
import styles from './OwncastPlayer.module.scss'; import styles from './OwncastPlayer.module.scss';
import { VideoSettingsServiceContext } from '../../../services/video-settings-service'; import { VideoSettingsServiceContext } from '../../../services/video-settings-service';

View file

@ -58,5 +58,3 @@ export const VideoJS: FC<VideoJSProps> = ({ options, onReady }) => {
</div> </div>
); );
}; };
export default VideoJS;

View file

@ -111,5 +111,3 @@ export function createVideoSettingsMenuButton(player, videojs, qualities, latenc
// eslint-disable-next-line consistent-return // eslint-disable-next-line consistent-return
return menuButton; return menuButton;
} }
export default createVideoSettingsMenuButton;

View file

@ -2,6 +2,7 @@ const withLess = require('next-with-less');
const withBundleAnalyzer = require('@next/bundle-analyzer')({ const withBundleAnalyzer = require('@next/bundle-analyzer')({
enabled: process.env.ANALYZE === 'true', enabled: process.env.ANALYZE === 'true',
}); });
const DeadCodePlugin = require('webpack-deadcode-plugin');
const runtimeCaching = require('next-pwa/cache'); const runtimeCaching = require('next-pwa/cache');
@ -39,6 +40,19 @@ module.exports = withPWA(
use: ['@svgr/webpack'], use: ['@svgr/webpack'],
}); });
config.plugins.push(
new DeadCodePlugin({
detectUnusedFiles: false,
patterns: ['**/*.(js|jsx|tsx|css)'],
exclude: [
'**/*.(stories|spec).(js|jsx|tsx)',
'node_modules/**/*',
'storybook-static/**/*',
'out/**/*',
],
}),
);
return config; return config;
}, },
async rewrites() { async rewrites() {

1357
web/package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -26,31 +26,25 @@
"@uiw/react-codemirror": "4.19.16", "@uiw/react-codemirror": "4.19.16",
"@xstate/react": "3.2.2", "@xstate/react": "3.2.2",
"antd": "4.24.10", "antd": "4.24.10",
"autoprefixer": "10.4.14", "autoprefixer": "^10.4.14",
"chart.js": "^4.2.0", "chart.js": "^4.2.0",
"classnames": "2.3.2", "classnames": "2.3.2",
"date-fns": "^2.29.3", "date-fns": "^2.29.3",
"interweave": "^13.0.0", "interweave": "^13.0.0",
"interweave-autolink": "^5.1.0", "interweave-autolink": "^5.1.0",
"linkifyjs": "^4.1.0",
"lodash": "4.17.21", "lodash": "4.17.21",
"next": "13.3.0", "next": "13.3.0",
"next-pwa": "^5.6.0", "next-pwa": "^5.6.0",
"next-with-less": "2.0.5", "next-with-less": "2.0.5",
"next-with-workbox": "^3.0.5",
"picmo": "5.8.4", "picmo": "5.8.4",
"postcss-flexbugs-fixes": "5.0.2", "postcss-flexbugs-fixes": "5.0.2",
"prop-types": "15.8.1",
"react": "18.2.0", "react": "18.2.0",
"react-chartjs-2": "^5.2.0", "react-chartjs-2": "^5.2.0",
"react-chartkick": "^0.5.3",
"react-crossfade-img": "1.0.0",
"react-dom": "18.2.0", "react-dom": "18.2.0",
"react-error-boundary": "^4.0.0", "react-error-boundary": "^4.0.0",
"react-hotkeys-hook": "4.4.0", "react-hotkeys-hook": "4.4.0",
"react-linkify": "1.0.0-alpha", "react-linkify": "1.0.0-alpha",
"react-markdown": "8.0.7", "react-markdown": "8.0.7",
"react-use": "^17.4.0",
"react-virtuoso": "4.3.6", "react-virtuoso": "4.3.6",
"recoil": "0.7.7", "recoil": "0.7.7",
"sharp": "0.32.1", "sharp": "0.32.1",
@ -58,6 +52,7 @@
"slate-react": "0.94.2", "slate-react": "0.94.2",
"ua-parser-js": "1.0.35", "ua-parser-js": "1.0.35",
"video.js": "^8.3.0", "video.js": "^8.3.0",
"webpack-deadcode-plugin": "^0.1.17",
"workbox-precaching": "^6.5.4", "workbox-precaching": "^6.5.4",
"workbox-window": "^6.5.4", "workbox-window": "^6.5.4",
"xstate": "4.37.2", "xstate": "4.37.2",
@ -101,7 +96,7 @@
"eslint-config-airbnb": "19.0.4", "eslint-config-airbnb": "19.0.4",
"eslint-config-next": "13.3.0", "eslint-config-next": "13.3.0",
"eslint-config-prettier": "8.8.0", "eslint-config-prettier": "8.8.0",
"eslint-plugin-import": "2.27.5", "eslint-plugin-import": "^2.27.5",
"eslint-plugin-jsx-a11y": "6.7.1", "eslint-plugin-jsx-a11y": "6.7.1",
"eslint-plugin-prettier": "4.2.1", "eslint-plugin-prettier": "4.2.1",
"eslint-plugin-react": "7.32.2", "eslint-plugin-react": "7.32.2",
@ -110,6 +105,7 @@
"handlebars": "^4.7.7", "handlebars": "^4.7.7",
"html-webpack-plugin": "5.5.1", "html-webpack-plugin": "5.5.1",
"install": "^0.13.0", "install": "^0.13.0",
"knip": "^2.11.0",
"less": "4.1.3", "less": "4.1.3",
"less-loader": "11.1.0", "less-loader": "11.1.0",
"mdx-mermaid": "^1.3.2", "mdx-mermaid": "^1.3.2",

View file

@ -189,7 +189,7 @@ const AccessTokens = () => {
{ {
title: '', title: '',
key: 'delete', key: 'delete',
render: (text, record) => ( render: (_, record) => (
<Space size="middle"> <Space size="middle">
<Button onClick={() => handleDeleteToken(record.accessToken)} icon={<DeleteOutlined />} /> <Button onClick={() => handleDeleteToken(record.accessToken)} icon={<DeleteOutlined />} />
</Space> </Space>

View file

@ -256,7 +256,7 @@ const Actions = () => {
}); });
} }
async function handleDelete(action, index) { async function handleDelete(index) {
const actionsData = [...actions]; const actionsData = [...actions];
actionsData.splice(index, 1); actionsData.splice(index, 1);
@ -269,7 +269,7 @@ const Actions = () => {
} }
async function handleSave( async function handleSave(
oldAction: ExternalAction | null, _oldAction: ExternalAction | null,
oldActionIndex: number, oldActionIndex: number,
url: string, url: string,
html: string, html: string,
@ -353,9 +353,9 @@ const Actions = () => {
{ {
title: '', title: '',
key: 'delete-edit', key: 'delete-edit',
render: (text, record, index) => ( render: (_, record, index) => (
<Space size="middle"> <Space size="middle">
<Button onClick={() => handleDelete(record, index)} icon={<DeleteOutlined />} /> <Button onClick={() => handleDelete(index)} icon={<DeleteOutlined />} />
<Button onClick={() => handleEdit(record, index)} icon={<EditOutlined />} /> <Button onClick={() => handleEdit(record, index)} icon={<EditOutlined />} />
</Space> </Space>
), ),
@ -374,7 +374,7 @@ const Actions = () => {
title: 'URL / Embed', title: 'URL / Embed',
key: 'url', key: 'url',
dataIndex: 'url', dataIndex: 'url',
render: (text, record) => (record.html ? 'HTML embed' : record.url), render: (_, record) => (record.html ? 'HTML embed' : record.url),
}, },
{ {
title: 'Icon', title: 'Icon',

View file

@ -12,9 +12,10 @@ import {
STATUS_SUCCESS, STATUS_SUCCESS,
} from '../../../utils/input-statuses'; } from '../../../utils/input-statuses';
import { RESET_TIMEOUT } from '../../../utils/config-constants'; import { RESET_TIMEOUT } from '../../../utils/config-constants';
import { URL_CUSTOM_EMOJIS } from '../../../utils/constants';
import { AdminLayout } from '../../../components/layouts/AdminLayout'; import { AdminLayout } from '../../../components/layouts/AdminLayout';
const URL_CUSTOM_EMOJIS = `/api/emoji`;
const { Meta } = Card; const { Meta } = Card;
// Lazy loaded components // Lazy loaded components

View file

@ -2,9 +2,9 @@ import { Alert, Button, Col, Row, Typography } from 'antd';
import React, { ReactElement, useContext, useEffect, useState } from 'react'; import React, { ReactElement, useContext, useEffect, useState } from 'react';
import Link from 'next/link'; import Link from 'next/link';
import Discord from '../../components/admin/notification/discord'; import { DiscordNotify as Discord } from '../../components/admin/notification/discord';
import Browser from '../../components/admin/notification/browser'; import { BrowserNotify as Browser } from '../../components/admin/notification/browser';
import Federation from '../../components/admin/notification/federation'; import { FediverseNotify as Federation } from '../../components/admin/notification/federation';
import { import {
TextFieldWithSubmit, TextFieldWithSubmit,
TEXTFIELD_TYPE_URL, TEXTFIELD_TYPE_URL,

View file

@ -195,7 +195,7 @@ const Webhooks = () => {
{ {
title: '', title: '',
key: 'delete', key: 'delete',
render: (text, record) => ( render: (_, record) => (
<Space size="middle"> <Space size="middle">
<Button onClick={() => handleDelete(record.id)} icon={<DeleteOutlined />} /> <Button onClick={() => handleDelete(record.id)} icon={<DeleteOutlined />} />
</Space> </Space>

View file

@ -13,10 +13,6 @@ export async function saveNotificationRegistration(channel, destination, accessT
await fetch(`${URL_REGISTER_NOTIFICATION}?accessToken=${accessToken}`, options); await fetch(`${URL_REGISTER_NOTIFICATION}?accessToken=${accessToken}`, options);
} }
export function isPushNotificationSupported() {
return 'serviceWorker' in navigator && 'PushManager' in window;
}
function urlBase64ToUint8Array(base64String: string) { function urlBase64ToUint8Array(base64String: string) {
const padding = '='.repeat((4 - (base64String.length % 4)) % 4); const padding = '='.repeat((4 - (base64String.length % 4)) % 4);
const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/'); const base64 = (base64String + padding).replace(/-/g, '+').replace(/_/g, '/');

View file

@ -1,4 +1,5 @@
import { generateRndKey } from '../components/admin/config/server/StreamKeys'; import { generateRndKey } from '../components/admin/config/server/StreamKeys';
describe('generateRndKey', () => { describe('generateRndKey', () => {
test('should generate a key that matches the regular expression', () => { test('should generate a key that matches the regular expression', () => {
const key = generateRndKey(); const key = generateRndKey();

View file

@ -13,8 +13,10 @@
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": true, "isolatedModules": true,
"jsx": "preserve", "jsx": "preserve",
"incremental": true "incremental": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "utils/constants.js"],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }

View file

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

View file

@ -10,12 +10,6 @@ export const FETCH_INTERVAL = 15000;
// Current inbound broadcaster info // Current inbound broadcaster info
export const STATUS = `${API_LOCATION}status`; 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 // Current server config
export const SERVER_CONFIG = `${API_LOCATION}serverconfig`; export const SERVER_CONFIG = `${API_LOCATION}serverconfig`;
@ -91,9 +85,6 @@ export const CREATE_WEBHOOK = `${API_LOCATION}webhooks/create`;
// hard coded social icons list // hard coded social icons list
export const SOCIAL_PLATFORMS_LIST = `${NEXT_PUBLIC_API_HOST}api/socialplatforms`; 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 // send a message to the fediverse
export const FEDERATION_MESSAGE_SEND = `${API_LOCATION}federation/send`; 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 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'; const GITHUB_RELEASE_URL = 'https://api.github.com/repos/owncast/owncast/releases/latest';
interface FetchOptions { 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 { ApiPostArgs, VideoVariant, SocialHandle } from '../types/config-section';
import { DEFAULT_TEXTFIELD_URL_PATTERN } from './validators'; import { DEFAULT_TEXTFIELD_URL_PATTERN } from './validators';
export const TEXT_MAXLENGTH = 255; const TEXT_MAXLENGTH = 255;
export const RESET_TIMEOUT = 3000; export const RESET_TIMEOUT = 3000;
@ -11,41 +11,42 @@ export const RESET_TIMEOUT = 3000;
export const API_CUSTOM_CONTENT = '/pagecontent'; export const API_CUSTOM_CONTENT = '/pagecontent';
export const API_CUSTOM_CSS_STYLES = '/customstyles'; export const API_CUSTOM_CSS_STYLES = '/customstyles';
export const API_CUSTOM_JAVASCRIPT = '/customjavascript'; 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_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_OFFLINE_MESSAGE = '/offlinemessage';
export const API_SERVER_NAME = '/name';
export const API_SOCIAL_HANDLES = '/socialhandles'; 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_SEGMENTS = '/video/streamlatencylevel';
export const API_VIDEO_VARIANTS = '/video/streamoutputvariants'; export const API_VIDEO_VARIANTS = '/video/streamoutputvariants';
export const API_WEB_PORT = '/webserverport';
export const API_YP_SWITCH = '/directoryenabled'; 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_FORBIDDEN_USERNAMES = '/chat/forbiddenusernames';
export const API_CHAT_SUGGESTED_USERNAMES = '/chat/suggestedusernames'; export const API_CHAT_SUGGESTED_USERNAMES = '/chat/suggestedusernames';
export const API_EXTERNAL_ACTIONS = '/externalactions'; export const API_EXTERNAL_ACTIONS = '/externalactions';
export const API_VIDEO_CODEC = '/video/codec'; 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 // Federation
export const API_FEDERATION_ENABLED = '/federation/enable'; const API_FEDERATION_ENABLED = '/federation/enable';
export const API_FEDERATION_PRIVATE = '/federation/private'; const API_FEDERATION_PRIVATE = '/federation/private';
export const API_FEDERATION_USERNAME = '/federation/username'; const API_FEDERATION_USERNAME = '/federation/username';
export const API_FEDERATION_GOLIVE_MESSAGE = '/federation/livemessage'; const API_FEDERATION_GOLIVE_MESSAGE = '/federation/livemessage';
export const API_FEDERATION_SHOW_ENGAGEMENT = '/federation/showengagement'; const API_FEDERATION_SHOW_ENGAGEMENT = '/federation/showengagement';
export const API_FEDERATION_BLOCKED_DOMAINS = '/federation/blockdomains'; export const API_FEDERATION_BLOCKED_DOMAINS = '/federation/blockdomains';
const TEXTFIELD_TYPE_URL = 'url'; 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 OTHER_SOCIAL_HANDLE_OPTION = 'OTHER_SOCIAL_HANDLE_OPTION';
export const TEXTFIELD_PROPS_S3_COMMON = {
maxLength: 255,
};
export const S3_TEXT_FIELDS_INFO = { export const S3_TEXT_FIELDS_INFO = {
accessKey: { accessKey: {
fieldName: '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'; 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); 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); return String(pad.repeat(size) + text).slice(-size);
} }
@ -42,13 +42,6 @@ export function parseSecondsToDurationString(seconds = 0) {
return daysString + hoursString + minString + secsString; 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) { export function formatUAstring(uaString: string) {
const parser = UAParser(uaString); const parser = UAParser(uaString);
const { device, os, browser } = parser; 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) { export function pluralize(string, count) {
if (count === 1) { if (count === 1) {
return string; return string;
@ -10,149 +5,11 @@ export function pluralize(string, count) {
return `${string}s`; 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) { export function getDiffInDaysFromNow(timestamp) {
const time = typeof timestamp === 'string' ? new Date(timestamp) : timestamp; const time = typeof timestamp === 'string' ? new Date(timestamp) : timestamp;
return (new Date() - time) / (24 * 3600 * 1000); 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 // Take a nested object of state metadata and merge it into
// a single flattened node. // a single flattened node.
export function mergeMeta(meta) { 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, ssr: false,
}); });
export const STATUS_RESET_TIMEOUT = 3000;
export const STATUS_ERROR = 'error'; export const STATUS_ERROR = 'error';
export const STATUS_INVALID = 'invalid';
export const STATUS_PROCESSING = 'proessing'; export const STATUS_PROCESSING = 'proessing';
export const STATUS_SUCCESS = 'success'; export const STATUS_SUCCESS = 'success';
export const STATUS_WARNING = 'warning'; export const STATUS_WARNING = 'warning';
const STATUS_INVALID = 'invalid';
export type InputStatusTypes = 'error' | 'invalid' | 'proessing' | 'success' | 'warning'; export type InputStatusTypes = 'error' | 'invalid' | 'proessing' | 'success' | 'warning';
export interface StatusState { export interface StatusState {
@ -37,7 +36,7 @@ interface InputStates {
[key: string]: StatusState; [key: string]: StatusState;
} }
export const INPUT_STATES: InputStates = { const INPUT_STATES: InputStates = {
[STATUS_SUCCESS]: { [STATUS_SUCCESS]: {
type: STATUS_SUCCESS, type: STATUS_SUCCESS,
icon: <CheckCircleFilled style={{ color: 'green' }} />, icon: <CheckCircleFilled style={{ color: 'green' }} />,

View file

@ -7,7 +7,9 @@ export const LOCAL_STORAGE_KEYS = {
export function getLocalStorage(key) { export function getLocalStorage(key) {
try { try {
return localStorage.getItem(key); return localStorage.getItem(key);
} catch (e) {} } catch (e) {
console.error(e);
}
return null; return null;
} }
@ -19,31 +21,8 @@ export function setLocalStorage(key, value) {
localStorage.removeItem(key); localStorage.removeItem(key);
} }
return true; return true;
} catch (e) {} } catch (e) {
console.error(e);
}
return false; 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 { ConfigDetails, UpdateArgs } from '../types/config-section';
import { DEFAULT_VARIANT_STATE } from './config-constants'; import { DEFAULT_VARIANT_STATE } from './config-constants';
export const initialServerConfigState: ConfigDetails = { const initialServerConfigState: ConfigDetails = {
streamKeys: [], streamKeys: [],
streamKeyOverridden: false, streamKeyOverridden: false,
adminPassword: '', adminPassword: '',
@ -102,7 +102,7 @@ export const ServerStatusContext = React.createContext({
serverConfig: initialServerConfigState, serverConfig: initialServerConfigState,
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
setFieldInConfigState: (args: UpdateArgs) => null, setFieldInConfigState: (_args: UpdateArgs) => null,
}); });
export type ServerStatusProviderProps = { export type ServerStatusProviderProps = {