From 7af5030f5bc431a019d2594b3fc45b3884594010 Mon Sep 17 00:00:00 2001 From: gabek Date: Tue, 20 Jul 2021 02:23:06 +0000 Subject: [PATCH] Prettified Code! --- webroot/js/app-standalone-chat.js | 2 +- webroot/js/app.js | 36 ++++---- webroot/js/chat/register.js | 32 +++---- webroot/js/components/chat/chat-input.js | 6 +- .../js/components/chat/chat-message-view.js | 14 ++- webroot/js/components/chat/chat.js | 2 +- webroot/js/components/chat/message.js | 87 +++++++++++-------- webroot/js/utils/chat.js | 40 ++++++--- webroot/js/utils/constants.js | 4 +- webroot/js/utils/websocket.js | 12 +-- 10 files changed, 142 insertions(+), 93 deletions(-) diff --git a/webroot/js/app-standalone-chat.js b/webroot/js/app-standalone-chat.js index 7b713b055..bc399b230 100644 --- a/webroot/js/app-standalone-chat.js +++ b/webroot/js/app-standalone-chat.js @@ -40,7 +40,7 @@ export default class StandaloneChat extends Component { async setupChatAuth(force) { var accessToken = getLocalStorage(KEY_EMBED_CHAT_ACCESS_TOKEN); - const randomInt = Math.floor(Math.random() * 100) + 1 + const randomInt = Math.floor(Math.random() * 100) + 1; var username = 'chat-embed-' + randomInt; if (!accessToken || force) { diff --git a/webroot/js/app.js b/webroot/js/app.js index 674b7dc79..552d38b4d 100644 --- a/webroot/js/app.js +++ b/webroot/js/app.js @@ -7,7 +7,10 @@ import SocialIconsList from './components/platform-logos-list.js'; import UsernameForm from './components/chat/username.js'; import VideoPoster from './components/video-poster.js'; import Chat from './components/chat/chat.js'; -import Websocket, { CALLBACKS, SOCKET_MESSAGE_TYPES } from './utils/websocket.js'; +import Websocket, { + CALLBACKS, + SOCKET_MESSAGE_TYPES, +} from './utils/websocket.js'; import { registerChat } from './chat/register.js'; import ExternalActionModal, { @@ -60,7 +63,7 @@ export default class App extends Component { this.state = { websocket: null, canChat: false, // all of chat functionality (panel + username) - displayChatPanel: chatStorage === null ? true : (chatStorage === 'true'), // just the chat panel + displayChatPanel: chatStorage === null ? true : chatStorage === 'true', // just the chat panel chatInputEnabled: false, // chat input box state accessToken: null, username: getLocalStorage(KEY_USERNAME), @@ -519,10 +522,13 @@ export default class App extends Component { if (e.type === SOCKET_MESSAGE_TYPES.ERROR_USER_DISABLED) { // User has been actively disabled on the backend. Turn off chat for them. this.handleBlockedChat(); - } else if (e.type === SOCKET_MESSAGE_TYPES.ERROR_NEEDS_REGISTRATION && !this.isRegistering) { + } else if ( + e.type === SOCKET_MESSAGE_TYPES.ERROR_NEEDS_REGISTRATION && + !this.isRegistering + ) { // User needs an access token, so start the user auth flow. this.state.websocket.shutdown(); - this.setState({websocket: null}); + this.setState({ websocket: null }); this.setupChatAuth(true); } else if (e.type === SOCKET_MESSAGE_TYPES.ERROR_MAX_CONNECTIONS_EXCEEDED) { // Chat server cannot support any more chat clients. Turn off chat for them. @@ -530,10 +536,10 @@ export default class App extends Component { } else if (e.type === SOCKET_MESSAGE_TYPES.CONNECTED_USER_INFO) { // When connected the user will return an event letting us know what our // user details are so we can display them properly. - const {user} = e; - const {displayName} = user; + const { user } = e; + const { displayName } = user; - this.setState({username: displayName}); + this.setState({ username: displayName }); } } @@ -570,7 +576,7 @@ export default class App extends Component { if (this.state.websocket) { this.state.websocket.shutdown(); this.setState({ - websocket: null + websocket: null, }); } @@ -589,14 +595,13 @@ export default class App extends Component { } sendUsernameChange(newName) { - const nameChange = { - type: SOCKET_MESSAGE_TYPES.NAME_CHANGE, - newName, - }; - this.state.websocket.send(nameChange); + const nameChange = { + type: SOCKET_MESSAGE_TYPES.NAME_CHANGE, + newName, + }; + this.state.websocket.send(nameChange); } - render(props, state) { const { chatInputEnabled, @@ -702,7 +707,8 @@ export default class App extends Component { chatInputEnabled=${chatInputEnabled && !chatDisabled} instanceTitle=${name} accessToken=${this.state.accessToken} - inputMaxBytes=${(maxSocketPayloadSize - EST_SOCKET_PAYLOAD_BUFFER) || CHAT_MAX_MESSAGE_LENGTH} + inputMaxBytes=${maxSocketPayloadSize - EST_SOCKET_PAYLOAD_BUFFER || + CHAT_MAX_MESSAGE_LENGTH} /> ` : null; diff --git a/webroot/js/chat/register.js b/webroot/js/chat/register.js index 27e08a7cd..53129046c 100644 --- a/webroot/js/chat/register.js +++ b/webroot/js/chat/register.js @@ -1,19 +1,19 @@ -import {URL_CHAT_REGISTRATION} from "../utils/constants.js"; +import { URL_CHAT_REGISTRATION } from '../utils/constants.js'; export async function registerChat(username) { - const options = { - method: 'POST', - headers: { - 'Content-Type': 'application/json' - }, - body: JSON.stringify({displayName: username}) - } + const options = { + method: 'POST', + headers: { + 'Content-Type': 'application/json', + }, + body: JSON.stringify({ displayName: username }), + }; - try { - const response = await fetch(URL_CHAT_REGISTRATION, options); - const result = await response.json(); - return result; - } catch(e) { - console.error(e); - } -} \ No newline at end of file + try { + const response = await fetch(URL_CHAT_REGISTRATION, options); + const result = await response.json(); + return result; + } catch (e) { + console.error(e); + } +} diff --git a/webroot/js/components/chat/chat-input.js b/webroot/js/components/chat/chat-input.js index 4b17b6408..367fc9bdf 100644 --- a/webroot/js/components/chat/chat-input.js +++ b/webroot/js/components/chat/chat-input.js @@ -167,7 +167,11 @@ export default class ChatInput extends Component { if (possibilities.length > 0) { this.suggestion = possibilities[this.completionIndex]; - const newHTML = inputHTML.substring(0, at + 1) + this.suggestion + ' ' + inputHTML.substring(position); + const newHTML = + inputHTML.substring(0, at + 1) + + this.suggestion + + ' ' + + inputHTML.substring(position); this.setState({ inputHTML: newHTML, diff --git a/webroot/js/components/chat/chat-message-view.js b/webroot/js/components/chat/chat-message-view.js index 02e8813f2..adf7166e2 100644 --- a/webroot/js/components/chat/chat-message-view.js +++ b/webroot/js/components/chat/chat-message-view.js @@ -29,7 +29,7 @@ export default class ChatMessageView extends Component { async componentDidMount() { const { message, username } = this.props; const { body } = message; - + if (message && username) { const formattedMessage = await formatMessageText(body, username); this.setState({ @@ -48,7 +48,9 @@ export default class ChatMessageView extends Component { return null; } const formattedTimestamp = `Sent at ${formatTimestamp(timestamp)}`; - const userMetadata = `${displayName} first joined ${formatTimestamp(createdAt)}`; + const userMetadata = `${displayName} first joined ${formatTimestamp( + createdAt + )}`; const isSystemMessage = message.type === SOCKET_MESSAGE_TYPES.SYSTEM; @@ -69,7 +71,11 @@ export default class ChatMessageView extends Component { title=${formattedTimestamp} >
-
+
${displayName}
`; } else if (type === SOCKET_MESSAGE_TYPES.NAME_CHANGE) { const { oldName, user } = message; - const { displayName } = user; - return ( - html` -
-
-
- ${oldName} is now known as ${displayName}. -
+ const { displayName } = user; + return html` +
+
+
+ ${oldName} is now known as + ${displayName}.
- ` - ); +
+ `; } else if (type === SOCKET_MESSAGE_TYPES.USER_JOINED) { - const { user } = message + const { user } = message; const { displayName } = user; - return ( - html` -
-
-
- ${displayName} joined the chat. -
-
+ return html` +
+
+
+ ${displayName} joined the chat.
- ` - ); +
+
+ `; } else if (type === SOCKET_MESSAGE_TYPES.CHAT_ACTION) { const { body } = message; - const formattedMessage = `${body}` - return ( - html` -
-
-
- -
-
+ const formattedMessage = `${body}`; + return html` +
+
+
+
- ` - ); +
+
+ `; } else if (type === SOCKET_MESSAGE_TYPES.CONNECTED_USER_INFO) { // noop for now } else { - console.log("Unknown message type:", type); + console.log('Unknown message type:', type); } } - diff --git a/webroot/js/utils/chat.js b/webroot/js/utils/chat.js index 9ccd92884..606189e49 100644 --- a/webroot/js/utils/chat.js +++ b/webroot/js/utils/chat.js @@ -4,11 +4,11 @@ import { CHAT_PLACEHOLDER_OFFLINE, } from './constants.js'; - // Taken from https://stackoverflow.com/questions/3972014/get-contenteditable-caret-index-position export function getCaretPosition(editableDiv) { var caretPos = 0, - sel, range; + sel, + range; if (window.getSelection) { sel = window.getSelection(); if (sel.rangeCount) { @@ -20,11 +20,11 @@ export function getCaretPosition(editableDiv) { } else if (document.selection && document.selection.createRange) { range = document.selection.createRange(); if (range.parentElement() == editableDiv) { - var tempEl = document.createElement("span"); + var tempEl = document.createElement('span'); editableDiv.insertBefore(tempEl, editableDiv.firstChild); var tempRange = range.duplicate(); tempRange.moveToElementText(tempEl); - tempRange.setEndPoint("EndToEnd", range); + tempRange.setEndPoint('EndToEnd', range); caretPos = tempRange.text.length; } } @@ -44,10 +44,11 @@ export function setCaretPosition(editableDiv, position) { sel.addRange(range); } - export function generatePlaceholderText(isEnabled, hasSentFirstChatMessage) { if (isEnabled) { - return hasSentFirstChatMessage ? CHAT_PLACEHOLDER_TEXT : CHAT_INITIAL_PLACEHOLDER_TEXT; + return hasSentFirstChatMessage + ? CHAT_PLACEHOLDER_TEXT + : CHAT_INITIAL_PLACEHOLDER_TEXT; } return CHAT_PLACEHOLDER_OFFLINE; } @@ -112,7 +113,7 @@ export function convertToText(str = '') { You would call this when a user pastes from the clipboard into a `contenteditable` area. */ -export function convertOnPaste(event = { preventDefault() { } }, emojiList) { +export function convertOnPaste(event = { preventDefault() {} }, emojiList) { // Prevent paste. event.preventDefault(); @@ -149,17 +150,29 @@ export function convertOnPaste(event = { preventDefault() { } }, emojiList) { 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 ':‌‌' + emojiName + '‌‌:'; + const emojiName = ( + isCustom + ? data.name + : data.url.split('\\').pop().split('/').pop().split('.').shift() + ).toLowerCase(); + return ( + ':‌‌' +
+    emojiName +
+    '‌‌:' + ); } // trim html white space characters from ends of messages for more accurate counting export function trimNbsp(html) { - return html.replace(/^(?: |\s)+|(?: |\s)+$/ig,''); + return html.replace(/^(?: |\s)+|(?: |\s)+$/gi, ''); } export function emojify(HTML, emojiList) { - const textValue = convertToText(HTML) + const textValue = convertToText(HTML); for (var lastPos = textValue.length; lastPos >= 0; lastPos--) { const endPos = textValue.lastIndexOf(':', lastPos); @@ -176,10 +189,9 @@ export function emojify(HTML, emojiList) { }); if (emojiIndex != -1) { - const emojiImgElement = createEmojiMarkup(emojiList[emojiIndex], true) - HTML = HTML.replace(":" + typedEmoji + ":", emojiImgElement) + const emojiImgElement = createEmojiMarkup(emojiList[emojiIndex], true); + HTML = HTML.replace(':' + typedEmoji + ':', emojiImgElement); } } return HTML; - } diff --git a/webroot/js/utils/constants.js b/webroot/js/utils/constants.js index 13219f6ab..d209e2ce1 100644 --- a/webroot/js/utils/constants.js +++ b/webroot/js/utils/constants.js @@ -8,7 +8,9 @@ export const URL_VIEWER_PING = `/api/ping`; // 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_WEBSOCKET = `${ + location.protocol === 'https:' ? 'wss' : 'ws' +}://${location.host}/ws`; export const URL_CHAT_REGISTRATION = `/api/chat/register`; export const TIMER_STATUS_UPDATE = 5000; // ms diff --git a/webroot/js/utils/websocket.js b/webroot/js/utils/websocket.js index 7c64461ff..19ede8902 100644 --- a/webroot/js/utils/websocket.js +++ b/webroot/js/utils/websocket.js @@ -21,7 +21,7 @@ export const SOCKET_MESSAGE_TYPES = { export const CALLBACKS = { RAW_WEBSOCKET_MESSAGE_RECEIVED: 'rawWebsocketMessageReceived', WEBSOCKET_CONNECTED: 'websocketConnected', -} +}; const TIMER_WEBSOCKET_RECONNECT = 5000; // ms @@ -48,7 +48,7 @@ export default class Websocket { createAndConnect() { const url = new URL(URL_WEBSOCKET); url.searchParams.append('accessToken', this.accessToken); - + const ws = new WebSocket(url.toString()); ws.onopen = this.onOpen.bind(this); ws.onclose = this.onClose.bind(this); @@ -161,10 +161,10 @@ export default class Websocket { } if (!model.type) { - console.error("No type provided", model); + console.error('No type provided', model); return; } - + // Send PONGs if (model.type === SOCKET_MESSAGE_TYPES.PING) { this.sendPong(); @@ -182,6 +182,8 @@ export default class Websocket { } handleNetworkingError(error) { - console.error(`Websocket Error. Chat is likely not working. Visit troubleshooting steps to resolve. https://owncast.online/docs/troubleshooting/#chat-is-disabled: ${error}`); + console.error( + `Websocket Error. Chat is likely not working. Visit troubleshooting steps to resolve. https://owncast.online/docs/troubleshooting/#chat-is-disabled: ${error}` + ); } }