0

Prettified Code!

This commit is contained in:
gabek 2021-07-20 02:23:06 +00:00 committed by GitHub Action
parent b6f68628c0
commit 7af5030f5b
10 changed files with 142 additions and 93 deletions

View File

@ -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) {

View File

@ -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,7 +522,10 @@ 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 });
@ -570,7 +576,7 @@ export default class App extends Component {
if (this.state.websocket) {
this.state.websocket.shutdown();
this.setState({
websocket: null
websocket: null,
});
}
@ -596,7 +602,6 @@ export default class App extends Component {
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;

View File

@ -1,13 +1,13 @@
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'
'Content-Type': 'application/json',
},
body: JSON.stringify({displayName: username})
}
body: JSON.stringify({ displayName: username }),
};
try {
const response = await fetch(URL_CHAT_REGISTRATION, options);

View File

@ -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,

View File

@ -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}
>
<div class="message-content break-words w-full">
<div style=${authorTextColor} class="message-author font-bold" title=${userMetadata}>
<div
style=${authorTextColor}
class="message-author font-bold"
title=${userMetadata}
>
${displayName}
</div>
<div

View File

@ -9,54 +9,71 @@ import { SOCKET_MESSAGE_TYPES } from '../../utils/websocket.js';
export default function Message(props) {
const { message } = props;
const { type } = message;
if (type === SOCKET_MESSAGE_TYPES.CHAT || type === SOCKET_MESSAGE_TYPES.SYSTEM) {
if (
type === SOCKET_MESSAGE_TYPES.CHAT ||
type === SOCKET_MESSAGE_TYPES.SYSTEM
) {
return html`<${ChatMessageView} ...${props} />`;
} else if (type === SOCKET_MESSAGE_TYPES.NAME_CHANGE) {
const { oldName, user } = message;
const { displayName } = user;
return (
html`
<div class="message message-name-change flex items-center justify-start p-3">
<div class="message-content flex flex-row items-center justify-center text-sm w-full">
<div class="text-white text-center opacity-50 overflow-hidden break-words">
<span class="font-bold">${oldName}</span> is now known as <span class="font-bold">${displayName}</span>.
return html`
<div
class="message message-name-change flex items-center justify-start p-3"
>
<div
class="message-content flex flex-row items-center justify-center text-sm w-full"
>
<div
class="text-white text-center opacity-50 overflow-hidden break-words"
>
<span class="font-bold">${oldName}</span> is now known as
<span class="font-bold">${displayName}</span>.
</div>
</div>
</div>
`
);
`;
} else if (type === SOCKET_MESSAGE_TYPES.USER_JOINED) {
const { user } = message
const { user } = message;
const { displayName } = user;
return (
html`
<div class="message message-user-joined flex items-center justify-start p-3">
<div class="message-content flex flex-row items-center justify-center text-sm w-full">
<div class="text-white text-center opacity-50 overflow-hidden break-words">
return html`
<div
class="message message-user-joined flex items-center justify-start p-3"
>
<div
class="message-content flex flex-row items-center justify-center text-sm w-full"
>
<div
class="text-white text-center opacity-50 overflow-hidden break-words"
>
<span class="font-bold">${displayName}</span> joined the chat.
</div>
</div>
</div>
`
);
`;
} else if (type === SOCKET_MESSAGE_TYPES.CHAT_ACTION) {
const { body } = message;
const formattedMessage = `${body}`
return (
html`
<div class="message message-user-joined flex items-center justify-start p-3">
<div class="message-content flex flex-row items-center justify-center text-sm w-full">
<div class="text-white text-center opacity-50 overflow-hidden break-words">
<span dangerouslySetInnerHTML=${{ __html: formattedMessage }}></span>
const formattedMessage = `${body}`;
return html`
<div
class="message message-user-joined flex items-center justify-start p-3"
>
<div
class="message-content flex flex-row items-center justify-center text-sm w-full"
>
<div
class="text-white text-center opacity-50 overflow-hidden break-words"
>
<span
dangerouslySetInnerHTML=${{ __html: formattedMessage }}
></span>
</div>
</div>
</div>
`
);
`;
} 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);
}
}

View File

@ -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;
}
@ -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 '<img class="emoji" alt=":' + emojiName + ':" title=":' + emojiName + ':" src="' + emojiUrl + '"/>';
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)+$/ig,'');
return html.replace(/^(?:&nbsp;|\s)+|(?:&nbsp;|\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;
}

View File

@ -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

View File

@ -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
@ -161,7 +161,7 @@ export default class Websocket {
}
if (!model.type) {
console.error("No type provided", model);
console.error('No type provided', model);
return;
}
@ -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}`
);
}
}