diff --git a/files/assets/css/main.css b/files/assets/css/main.css index 82ac91b55..93689c864 100644 --- a/files/assets/css/main.css +++ b/files/assets/css/main.css @@ -6564,8 +6564,11 @@ g { padding-left: 10px; } -#speed-carot-modal +.speed-carot-modal { + position: absolute; + left: 0; + top: 0; background-color: var(--gray-700); max-height: 500px; overflow-y: auto; @@ -6574,31 +6577,34 @@ g { border: 1px solid rgba(255, 255, 255, 0.3); box-shadow: 0px 2px 5px rgba(0, 0, 0, 0.2); z-index: 1000000001; + display: flex; + flex-direction: column; } -#speed-carot-modal .speed-modal-option +.speed-carot-modal .speed-modal-option { + text-align: left; border-bottom: 1px solid #606060; padding: 4px; cursor: pointer; } -#speed-carot-modal .speed-modal-option:hover, -#speed-carot-modal .speed-modal-option:focus, -#speed-carot-modal .speed-modal-option.selected +.speed-carot-modal .speed-modal-option:hover, +.speed-carot-modal .speed-modal-option:focus, +.speed-carot-modal .speed-modal-option.selected { background-color: rgba(255, 255, 255, 0.2); } -#speed-carot-modal .speed-modal-image +.speed-carot-modal .speed-modal-image { object-fit: contain; width: 30px; height: 30px; } -#speed-carot-modal .speed-modal-option span +.speed-carot-modal .speed-modal-option span { overflow: hidden; display: inline-block; @@ -6711,7 +6717,7 @@ div.markdown { } @media (min-width: 768px) { - #speed-carot-modal .speed-modal-image + .speed-carot-modal .speed-modal-image { width: 50px; height: 50px; diff --git a/files/assets/js/core.js b/files/assets/js/core.js index 9b533b5c3..9cf2e64ea 100644 --- a/files/assets/js/core.js +++ b/files/assets/js/core.js @@ -151,10 +151,10 @@ function autoExpand(field) { let computed = window.getComputedStyle(field); let height = parseInt(computed.getPropertyValue('border-top-width'), 10) - + parseInt(computed.getPropertyValue('padding-top'), 10) - + field.scrollHeight - + parseInt(computed.getPropertyValue('padding-bottom'), 10) - + parseInt(computed.getPropertyValue('border-bottom-width'), 10); + + parseInt(computed.getPropertyValue('padding-top'), 10) + + field.scrollHeight + + parseInt(computed.getPropertyValue('padding-bottom'), 10) + + parseInt(computed.getPropertyValue('border-bottom-width'), 10); field.style.height = height + 'px'; if (Math.abs(window.scrollX - xpos) < 1 && Math.abs(window.scrollY - ypos) < 1) return; @@ -471,6 +471,160 @@ function insertText(input, text) { handle_disabled(input) } +/** + * Shamelessly copied from https://github.com/component/textarea-caret-position/blob/master/index.js + * This code makes the assumption that the style of the textarea/input won't change. + * @returns {{top: number, left: number, height: number, bottom: number, right: number, x: number, y: number }} + */ +const getCaretPos = (() => { + // We'll copy the properties below into the mirror div. + // Note that some browsers, such as Firefox, do not concatenate properties + // into their shorthand (e.g. padding-top, padding-bottom etc. -> padding), + // so we have to list every single property explicitly. + const properties = [ + 'direction', // RTL support + 'boxSizing', + 'width', // on Chrome and IE, exclude the scrollbar, so the mirror div wraps exactly as the textarea does + 'height', + 'overflowX', + 'overflowY', // copy the scrollbar for IE + + 'borderTopWidth', + 'borderRightWidth', + 'borderBottomWidth', + 'borderLeftWidth', + 'borderStyle', + + 'paddingTop', + 'paddingRight', + 'paddingBottom', + 'paddingLeft', + + // https://developer.mozilla.org/en-US/docs/Web/CSS/font + 'fontStyle', + 'fontVariant', + 'fontWeight', + 'fontStretch', + 'fontSize', + 'fontSizeAdjust', + 'lineHeight', + 'fontFamily', + + 'textAlign', + 'textTransform', + 'textIndent', + 'textDecoration', // might not make a difference, but better be safe + + 'letterSpacing', + 'wordSpacing', + + 'tabSize', + 'MozTabSize' + + ]; + + const cache = new Map(); + + const isFirefox = window.mozInnerScreenX != null; + + /** @param {HTMLTextAreaElement} element */ + return (element) => { + const position = element.selectionEnd; + const computed = window.getComputedStyle ? window.getComputedStyle(element) : element.currentStyle; // currentStyle for IE < 9 + const isInput = element.nodeName === 'INPUT'; + + let div, style; + if (cache.has(element)) { + div = cache.get(element); + style = div.style; + } else { + // The mirror div will replicate the textarea's style + div = document.createElement('div'); + cache.set(element, div); + div.id = 'input-textarea-caret-position-mirror-div'; + document.body.appendChild(div); + + style = div.style; + + // Default textarea styles + style.whiteSpace = 'pre-wrap'; + if (!isInput) { + style.overflowWrap = 'break-word'; // only for textarea-s + } + + // Position off-screen + style.position = 'absolute'; // required to return coordinates properly + style.visibility = 'hidden'; // not 'display: none' because we want rendering + + // Transfer the element's properties to the div + properties.forEach(function (prop) { + if (isInput && prop === 'lineHeight') { + // Special case for s because text is rendered centered and line height may be != height + if (computed.boxSizing === "border-box") { + var height = parseInt(computed.height); + var outerHeight = + parseInt(computed.paddingTop) + + parseInt(computed.paddingBottom) + + parseInt(computed.borderTopWidth) + + parseInt(computed.borderBottomWidth); + var targetHeight = outerHeight + parseInt(computed.lineHeight); + if (height > targetHeight) { + style.lineHeight = height - outerHeight + "px"; + } else if (height === targetHeight) { + style.lineHeight = computed.lineHeight; + } else { + style.lineHeight = 0; + } + } else { + style.lineHeight = computed.height; + } + } else { + style[prop] = computed[prop]; + } + }); + } + + if (isFirefox) { + // Firefox lies about the overflow property for textareas: https://bugzilla.mozilla.org/show_bug.cgi?id=984275 + if (element.scrollHeight > parseInt(computed.height)) + style.overflowY = 'scroll'; + } else { + style.overflow = 'hidden'; // for Chrome to not render a scrollbar; IE keeps overflowY = 'scroll' + } + + div.textContent = element.value.substring(0, position); + // The second special handling for input type="text" vs textarea: + // spaces need to be replaced with non-breaking spaces - http://stackoverflow.com/a/13402035/1269037 + if (isInput) { + div.textContent = div.textContent.replace(/\s/g, '\u00a0'); + } + + const span = document.createElement('span'); + // Wrapping must be replicated *exactly*, including when a long word gets + // onto the next line, with whitespace at the end of the line before (#7). + // The *only* reliable way to do that is to copy the *entire* rest of the + // textarea's content into the created at the caret position. + // For inputs, just '.' would be enough, but no need to bother. + span.textContent = element.value.substring(position) || '.'; // || because a completely empty faux span doesn't render at all + div.appendChild(span); + + const rect = element.getClientRects()[0]; + const top = rect.top + window.scrollY + span.offsetTop; + const left = rect.left + window.scrollX + span.offsetLeft; + const height = parseInt(computed['lineHeight']); + const coordinates = { + x: left, + y: top, + top, + bottom: top + height, + left, + right: left + 1, + height, + }; + + return coordinates; + } +})(); //FILE SHIT diff --git a/files/assets/js/emoji_modal.js b/files/assets/js/emoji_modal.js index 163b374f0..3639ee4f7 100644 --- a/files/assets/js/emoji_modal.js +++ b/files/assets/js/emoji_modal.js @@ -1,585 +1,444 @@ -/* -This program is free software: you can redistribute it and/or modify -it under the terms of the GNU Affero General Public License as -published by the Free Software Foundation, either version 3 of the -License, or (at your option) any later version. -This program is distributed in the hope that it will be useful, -but WITHOUT ANY WARRANTY; without even the implied warranty of -MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -GNU Affero General Public License for more details. -You should have received a copy of the GNU Affero General Public License -along with this program. If not, see . +// This code isn't for feeble minds, you might not understand it, Dr. Transmisia. +// Lappland, you are an absolute idiot and an embarrassment to the Rhodesian people. +// I have done the very thing that you decried impractical. +// The dainty hands of a trans goddess wrote this code. Watch the way her fingers +// dance across the keyboard and learn. -Copyright (C) 2022 Dr Steven Transmisia, anti-evil engineer, - 2022 Nekobit, king autist -*/ +// MIT License. Written by @transbitch -// Status /** - * inactive - user has not tried using an emoji - * loading - user has tried to use an emoji, and the engine is initializing itself - * ready - engine can handle all emoji usage - * @type {"inactive"|"loading"|"ready"} + * currently unused, the type of each emoji that https://rdrama.net/emojis.json returns. + * @typedef {object} EmojiDef + * @property {number} author_id + * @property {string} author_original_username + * @property {string} author_username + * @property {number} count + * @property {number} created_utc + * @property {string} kind + * @property {string} name + * @property {number | null} submitter_id + * @property {string[]} tags */ -let emojiEngineState = "inactive"; -// DOM stuff -const classesSelectorDOM = document.getElementById("emoji-modal-tabs"); -const emojiButtonTemplateDOM = document.getElementById("emoji-button-template"); -const emojiResultsDOM = document.getElementById("tab-content"); +/** + * @typedef {{[index: string]: [string, number][]}} EmojiTags + * @typedef {{[kind: string]: [string, number][]}} EmojiKinds + */ -const emojiSelectSuffixDOMs = document.getElementsByClassName("emoji-suffix"); -const emojiSelectPostfixDOMs= document.getElementsByClassName("emoji-postfix"); +class EmojiEngine { + _res; + /** @type {Promise} */ + loaded = new Promise(res => this._res = res); + hasLoaded = false; -const emojiNotFoundDOM = document.getElementById("no-emojis-found"); -const emojiWorkingDOM = document.getElementById("emojis-work"); + /** @type {EmojiTags} */ + tags = {}; -const emojiSearchBarDOM = document.getElementById('emoji_search'); + /** @type {EmojiKinds} */ + kinds = {}; -let emojiInputTargetDOM = undefined; + // Memoize this value so we don't have to recompute it. + _tag_entries; -// Emojis usage stats. I don't really like this format but I'll keep it for backward comp. -const favorite_emojis = JSON.parse(localStorage.getItem("favorite_emojis")) || {}; + /** @type {{[index: string]: HTMLDivElement}} */ + emojiDom = {}; -/** Associative array of all the emojis' DOM */ -let emojiDOMs = {}; + /** @type {{[index: string]: number}} */ + emojiNameCount = {}; -let globalEmojis; + /** @type {(name: string) => void} */ + onInsert; -const EMOIJ_SEARCH_ENGINE_MIN_INTERVAL = 350; -let emojiSearcher = { - working: false, - queries: [], + init = async () => { + if (this.hasLoaded) { + return; + } - addQuery: function(query) - { - this.queries.push(query); - if (!this.working) - this.work(); - }, + await Promise.all([ + this.loadTags(), + this.loadKinds(), + ]); - work: async function work() { - this.working = true; + this._tag_entries = Object.entries(this.tags); - while(this.queries.length > 0) - { - const startTime = Date.now(); + this._res(); + this.hasLoaded = true; + } - // Get last input - const query = this.queries[this.queries.length - 1].toLowerCase(); - this.queries = []; + loadTags = async () => { + this.tags = await (await fetch('/emoji_tags.json')).json(); + } - // To improve perf we avoid showing all emojis at the same time. - if (query === "") - { - await classesSelectorDOM.children[0].children[0].click(); - classesSelectorDOM.children[0].children[0].classList.add("active"); + loadKinds = async () => { + this.kinds = await (await fetch('/emoji_kinds.json')).json(); + } + + search = async (query, maxLength = Infinity) => { + await this.loaded; + + const resultsSet = new Set(); + const results = []; + for (const [tag, entries] of this._tag_entries) { + if (!tag.includes(query)) { continue; } - // Search - const resultSet = emojisSearchDictionary.completeSearch(query); + for (const [name, count] of entries) { + if (resultsSet.has(name)) { + continue; + } else if (count < results[maxLength - 1]?.[1]) { + // All the other emojis in this tag have less uses. We can stop here. + break; + } - // update stuff - for(const [emojiName, emojiDOM] of Object.entries(emojiDOMs)) - emojiDOM.hidden = !resultSet.has(emojiName); - - emojiNotFoundDOM.hidden = resultSet.size !== 0; - - let sleepTime = EMOIJ_SEARCH_ENGINE_MIN_INTERVAL - (Date.now() - startTime); - if (sleepTime > 0) - await new Promise(r => setTimeout(r, sleepTime)); + resultsSet.add(name); + // Insert into the array sorted. + let i = results.length; + while (i > 0 && count > results[i - 1][1]) { + i--; + } + results.splice(i, 0, [name, count]); + if (results.length >= maxLength) { + const [name] = results.pop(); + resultsSet.delete(name); + } + } } - this.working = false; + return results.map(([name]) => name); } -}; - -// tags dictionary. KEEP IT SORT -class EmoijsDictNode -{ - constructor(tag, name) { - this.tag = tag; - this.emojiNames = [name]; - } -} -const emojisSearchDictionary = { - dict: [], - - updateTag: function(tag, emojiName) { - if (tag === undefined || emojiName === undefined) - return; - - let low = 0; - let high = this.dict.length; - - while (low < high) { - let mid = (low + high) >>> 1; - if (this.dict[mid].tag < tag) - low = mid + 1; - else - high = mid; - } - - let target = low; - if (this.dict[target] !== undefined && this.dict[target].tag === tag) - this.dict[target].emojiNames.push(emojiName); - else - this.dict.splice(target ,0,new EmoijsDictNode(tag, emojiName)); - }, /** - * We also check for substrings! (sigh) - * @param {String} tag - * @returns {Set} + * Get a dom element for a list of emojis in quick dropdown. + * @param {string[]} emojiNames */ - completeSearch: function(query) { - query = query.toLowerCase() - const result = new Set(); - - for(let i = 0; i < this.dict.length; i++) - if (this.dict[i].tag.startsWith('@')) - { - if (this.dict[i].tag == query) - for(let j = 0; j < this.dict[i].emojiNames.length; j++) - result.add(this.dict[i].emojiNames[j]) - } - else if(this.dict[i].tag.includes(query)) - for(let j = 0; j < this.dict[i].emojiNames.length; j++) - result.add(this.dict[i].emojiNames[j]) - - return result; - } -}; - -// get public emojis list -function fetchEmojis() { - const headers = new Headers({xhr: "xhr"}) - return fetch("/emojis_json", { - headers, - }) - .then(res => res.json()) - .then(emojis => { - if (! (emojis instanceof Array )) - throw new TypeError("[EMOJI DIALOG] rDrama's server should have sent a JSON-coded Array!"); - - globalEmojis = emojis.map(({name, author, count}) => ({name, author, count})); - - let classes = ["Marsey", "Platy", "Wolf", "Donkey Kong", "Tay", "Capy", "Carp", "Marsey Flags", "Marsey Alphabet", "Classic", "Rage", "Wojak", "Misc"] - - const bussyDOM = document.createElement("div"); - - for(let i = 0; i < emojis.length; i++) - { - const emoji = emojis[i]; - - emojisSearchDictionary.updateTag(emoji.name, emoji.name); - - if (emoji.author_username !== undefined && emoji.author_username !== null) - emojisSearchDictionary.updateTag(`@${emoji.author_username.toLowerCase()}`, emoji.name); - - if (emoji.author_original_username !== undefined && emoji.author_original_username !== null) - emojisSearchDictionary.updateTag(`@${emoji.author_original_username.toLowerCase()}`, emoji.name); - - if (emoji.author_prelock_username !== undefined && emoji.author_prelock_username !== null) - emojisSearchDictionary.updateTag(`@${emoji.author_prelock_username.toLowerCase()}`, emoji.name); - - if (emoji.tags instanceof Array) - for(let i = 0; i < emoji.tags.length; i++) - emojisSearchDictionary.updateTag(emoji.tags[i], emoji.name); - - // Create emoji DOM - const emojiDOM = document.importNode(emojiButtonTemplateDOM.content, true).children[0]; - - emojiDOM.title = emoji.name - if (emoji.author_username !== undefined && emoji.author_username !== null) - emojiDOM.title += "\nauthor\t" + emoji.author_username - if (emoji.count !== undefined) - emojiDOM.title += "\nused\t" + emoji.count; - emojiDOM.dataset.className = emoji.kind; - emojiDOM.dataset.emojiName = emoji.name; - emojiDOM.onclick = emojiAddToInput; - emojiDOM.hidden = true; - - const emojiIMGDOM = emojiDOM.children[0]; - emojiIMGDOM.src = `${SITE_FULL_IMAGES}/e/${emoji.name}.webp` - emojiIMGDOM.alt = emoji.name; - /** Disableing lazy loading seems to reduce cpu usage somehow (?) - * idk it is difficult to benchmark */ - emojiIMGDOM.loading = "lazy"; - - // Save reference - emojiDOMs[emoji.name] = emojiDOM; - - // Add to the document! - bussyDOM.appendChild(emojiDOM); - } - - // Create header - for(let className of classes) - { - let classSelectorDOM = document.createElement("li"); - classSelectorDOM.classList.add("nav-item"); - - let classSelectorLinkDOM = document.createElement("button"); - classSelectorLinkDOM.type = "button"; - classSelectorLinkDOM.classList.add("nav-link", "emojitab"); - classSelectorLinkDOM.dataset.bsToggle = "tab"; - classSelectorLinkDOM.dataset.className = className; - classSelectorLinkDOM.textContent = className; - classSelectorLinkDOM.addEventListener('click', switchEmojiTab); - - classSelectorDOM.appendChild(classSelectorLinkDOM); - classesSelectorDOM.appendChild(classSelectorDOM); - } - - // Show favorite for start. - classesSelectorDOM.children[0].children[0].click(); - - // Send it to the render machine! - emojiResultsDOM.appendChild(bussyDOM); - - emojiResultsDOM.hidden = false; - emojiWorkingDOM.hidden = true; - emojiSearchBarDOM.disabled = false; - - emojiEngineState = "ready"; - }) -} - -/** -* -* @param {Event} e -*/ -function switchEmojiTab(e) -{ - const className = e.currentTarget.dataset.className; - - emojiSearchBarDOM.value = ""; - focusSearchBar(emojiSearchBarDOM); - emojiNotFoundDOM.hidden = true; - - // Special case: favorites - if (className === "favorite") - { - for(const emojiDOM of Object.values(emojiDOMs)) - emojiDOM.hidden = true; - - const favs = Object.keys(Object.fromEntries( - Object.entries(favorite_emojis).sort(([,a],[,b]) => b-a) - )).slice(0, 25); - - for (const emoji of favs) - if (emojiDOMs[emoji] instanceof HTMLElement) - emojiDOMs[emoji].hidden = false; - - return; + getQuickDoms = (emojiNames) => { + return emojiNames.map(this.getQuickDom); } - for(const emojiDOM of Object.values(emojiDOMs)) - emojiDOM.hidden = emojiDOM.dataset.className !== className; + /** + * + * @param {*} emojiName + * @returns DOM element for an emoji quick dropdown. + */ + getQuickDom = (emojiName) => { + if (this.emojiDom[emojiName]) { + return this.emojiDom[emojiName]; + } - document.getElementById('emoji-container').scrollTop = 0; -} + const emojiEl = document.createElement('button'); + emojiEl.classList.add('speed-modal-option', 'emoji-option'); + emojiEl.addEventListener('click', (e) => { + this.onInsert(emojiName); + }); -for (const emojitab of document.getElementsByClassName('emojitab')) { - emojitab.addEventListener('click', (e)=>{switchEmojiTab(e)}) -} + const emojiImgEl = document.createElement('img'); + emojiImgEl.classList.add('speed-modal-image', 'emoji-option-image'); + emojiImgEl.src = emojiEngine.src(emojiName); + emojiEl.appendChild(emojiImgEl); -async function start_search() { - emojiSearcher.addQuery(emojiSearchBarDOM.value.trim()); + const emojiNameEl = document.createElement('span'); + emojiNameEl.textContent = emojiName; + emojiEl.appendChild(emojiNameEl); - // Remove any selected tab, now it is meaningless - for(let i = 0; i < classesSelectorDOM.children.length; i++) - classesSelectorDOM.children[i].children[0].classList.remove("active"); -} - -/** -* Add the selected emoji to the targeted text area -* @param {Event} event -*/ -function emojiAddToInput(event) -{ - // This should not happen if used properly but whatever - if (!(emojiInputTargetDOM instanceof HTMLTextAreaElement) && !(emojiInputTargetDOM instanceof HTMLInputElement)) - return; - - let strToInsert = event.currentTarget.dataset.emojiName; - - for(let i = 0; i < emojiSelectPostfixDOMs.length; i++) - if (emojiSelectPostfixDOMs[i].checked) - strToInsert = strToInsert + emojiSelectPostfixDOMs[i].value; - - for(let i = 0; i < emojiSelectSuffixDOMs.length; i++) - if (emojiSelectSuffixDOMs[i].checked) - strToInsert = emojiSelectSuffixDOMs[i].value + strToInsert; - - strToInsert = ":" + strToInsert + ":" - insertText(emojiInputTargetDOM, strToInsert) - - // kick-start the preview - emojiInputTargetDOM.dispatchEvent(new Event('input')); - - // Update favs. from old code - if (favorite_emojis[event.currentTarget.dataset.emojiName]) - favorite_emojis[event.currentTarget.dataset.emojiName] += 1; - else - favorite_emojis[event.currentTarget.dataset.emojiName] = 1; - localStorage.setItem("favorite_emojis", JSON.stringify(favorite_emojis)); -} - -let emoji_typing_state = false; - -function update_ghost_div_textarea(text) -{ - let ghostdiv - - if (location.pathname == '/chat') - ghostdiv = document.getElementById("ghostdiv-chat"); - else - ghostdiv = text.parentNode.getElementsByClassName("ghostdiv")[0]; - - if (!ghostdiv) return; - - ghostdiv.textContent = text.value.substring(0, text.selectionStart); - - ghostdiv.insertAdjacentHTML('beforeend', ""); - - // Now lets get coordinates - - ghostdiv.style.display = "block"; - let end = ghostdiv.querySelector("span"); - const carot_coords = end.getBoundingClientRect(); - const ghostdiv_coords = ghostdiv.getBoundingClientRect(); - ghostdiv.style.display = "none"; - return { pos: text.selectionStart, x: carot_coords.x, y: carot_coords.y - ghostdiv_coords.y }; -} - -// Used for anything where a user is typing, specifically for the emoji modal -// Just leave it global, I don't care -let speed_carot_modal = document.createElement("div"); -speed_carot_modal.id = "speed-carot-modal"; -speed_carot_modal.style.position = "absolute"; -speed_carot_modal.style.left = "0px"; -speed_carot_modal.style.top = "0px"; -speed_carot_modal.style.display = "none"; -document.body.appendChild(speed_carot_modal); - -let e - -let current_word = ""; -let selecting; -let emoji_index = 0; - -function curr_word_is_emoji() -{ - return current_word && current_word.charAt(0) == ":" && - current_word.charAt(current_word.length-1) != ":"; -} - -function close_inline_speed_emoji_modal() { - selecting = false; - speed_carot_modal.style.display = "none"; -} - -function populate_speed_emoji_modal(results, textbox) -{ - selecting = true; - - if (!results || results.size === 0) - { - speed_carot_modal.style.display = "none"; - return -1; + this.emojiDom[emojiName] = emojiEl; + return emojiEl; } - emoji_index = 0; - speed_carot_modal.scrollTop = 0; - speed_carot_modal.innerHTML = ""; - const MAXXX = 50; - // Not sure why the results is a Set... but oh well - let i = 0; - for (let emoji of results) - { - let name = emoji.name + src = (name) => { + return `${SITE_FULL_IMAGES}/e/${name}.webp` + } +} - if (i++ > MAXXX) return i; - let emoji_option = document.createElement("div"); - emoji_option.className = "speed-modal-option emoji-option " + (i === 1 ? "selected" : ""); - emoji_option.tabIndex = 0; - let emoji_option_img = document.createElement("img"); - emoji_option_img.className = "speed-modal-image emoji-option-image"; - // This is a bit - emoji_option_img.src = `${SITE_FULL_IMAGES}/e/${name}.webp` - let emoji_option_text = document.createElement("span"); +const emojiEngine = new EmojiEngine(); - emoji_option_text.title = name; +// Quick emoji dropdown & emoji insertion +{ + const emojiDropdownEl = document.createElement('div'); + emojiDropdownEl.classList.add('speed-carot-modal'); + /** @type {null | HTMLTextAreaElement} */ + let inputEl = null; + let visible = false; + let typingEmojiCanceled = false; + let firstDomEl = null; + let firstEmojiName = null; + let caretPos = 0; - if (emoji.author_username !== undefined && emoji.author_username !== null) - emoji_option_text.title += "\nauthor\t" + emoji.author_username + // Used by onclick attrib of the smile button + window.openEmojiModal = (id) => { + inputEl = document.getElementById(id); + initEmojiModal(); + } - if (emoji.count !== undefined) - emoji_option_text.title += "\nused\t" + emoji.count; + emojiEngine.onInsert = (name) => { + if (!inputEl) { + return; + } + const match = matchTypingEmoji(); + if (match) { + // We are inserting an emoji which we are typing. + inputEl.value = `${inputEl.value.slice(0, match.index)}:${name}:${inputEl.value.slice(match.index + name.length)} `; + // Draw the focus back to this element. + inputEl.focus(); + } else { + // We are inserting a new emoji. + const start = inputEl.value.slice(0, caretPos); + const end = inputEl.value.slice(caretPos); + const insert = `:${name}:${end.length === 0 ? ' ' : ''}`; + inputEl.value = `${start}${insert}${end}`; + caretPos += insert.length; + inputEl.setSelectionRange(caretPos, caretPos); + } - emoji_option_text.textContent = name; + typingEmojiCanceled = false; + update(); - if (current_word.includes("#")) name = `#${name}` - if (current_word.includes("!")) name = `!${name}` + // This updates the preview. + inputEl.dispatchEvent(new Event('input', { bubbles: true })); - emoji_option.addEventListener('click', () => { - close_inline_speed_emoji_modal() - textbox.value = textbox.value.replace(new RegExp(current_word+"(?=\\s|$)", "gi"), `:${name}: `) - textbox.focus() - if (typeof markdown === "function" && textbox.dataset.preview) { - markdown(textbox) + // Update the favorite count. + if (name in favoriteEmojis) { + favoriteEmojis[name]++; + } else { + favoriteEmojis[name] = 1; + } + localStorage.setItem("favorite_emojis", JSON.stringify(favoriteEmojis)); + } + + const inputCanTakeEmojis = (el = inputEl) => { + return el?.dataset && 'emojis' in el.dataset; + } + + const matchTypingEmoji = () => { + return inputEl?.value.substring(0, inputEl.selectionEnd).match(/:([\w!#]+)$/); + } + + const getTypingEmoji = () => { + return matchTypingEmoji()?.[1] ?? null; + } + + const isTypingEmoji = () => { + return inputCanTakeEmojis() && getTypingEmoji(); + } + + const endTypingEmoji = () => { + typingEmojiCanceled = false; + } + + const update = async () => { + const typing = isTypingEmoji(); + visible = typing && !typingEmojiCanceled; + if (!visible) { + emojiDropdownEl.parentElement?.removeChild(emojiDropdownEl); + return; + } + const oldFirst = firstDomEl; + document.body.appendChild(emojiDropdownEl); + const search = await emojiEngine.search(getTypingEmoji(), 15); + firstEmojiName = search[0]; + const domEls = emojiEngine.getQuickDoms(search); + firstDomEl = domEls[0]; + if (oldFirst !== firstDomEl) { + oldFirst?.classList.remove('selected'); + firstDomEl.classList.add('selected'); + } + emojiDropdownEl.replaceChildren(...domEls); + const { left, bottom } = getCaretPos(inputEl); + // Using transform instead of top/left is faster. + emojiDropdownEl.style.transform = `translate(${left}px, ${bottom}px)`; + } + + // Add a listener when we start typing. + /** + * @param {FocusEvent} e + */ + const onKeyStart = (e) => { + if (inputCanTakeEmojis(e.target)) { + inputEl = e.target; + emojiEngine.init(); + window.removeEventListener('keydown', onKeyStart); + } + } + + window.addEventListener('keydown', onKeyStart); + window.addEventListener('keydown', (e) => { + if (!visible) { + return; + } + const isFocused = document.activeElement === inputEl + if (e.key === 'Escape') { + typingEmojiCanceled = true; + update(); + } else if (e.key === 'Enter' && isFocused) { + emojiEngine.onInsert(firstEmojiName); + e.preventDefault(); + } else if (e.key === 'Tab' && isFocused) { + firstDomEl.focus(); + firstDomEl.classList.remove("selected"); + e.preventDefault(); + } + }); + + ['input', 'click', 'focus'].forEach((event) => { + window.addEventListener(event, (e) => { + if (inputCanTakeEmojis(e.target)) { + inputEl = e.target; + caretPos = inputEl.selectionEnd; + } + update(); + if (!isTypingEmoji()) { + endTypingEmoji(); } }); - // Pack - emoji_option.appendChild(emoji_option_img); - emoji_option.appendChild(emoji_option_text); - speed_carot_modal.appendChild(emoji_option); - } - if (i === 0) speed_carot_modal.style.display = "none"; - else speed_carot_modal.style.display = "initial"; - return i; -} - -function update_speed_emoji_modal(event) -{ - const box_coords = update_ghost_div_textarea(event.target); - - box_coords.x = Math.min(box_coords.x, screen_width - 150) - - let text = event.target.value; - - // Unused, but left incase anyone wants to use this more efficient method for emojos - switch (event.data) - { - case ':': - emoji_typing_state = true; - break; - case ' ': - emoji_typing_state = false; - break; - default: - break; - } - - // Get current word at string, such as ":marse" or "word" - let coords = text.indexOf(' ',box_coords.pos); - current_word = /:[!#a-zA-Z0-9_]+(?=\n|$)/.exec(text.slice(0, coords === -1 ? text.length : coords)); - if (current_word) current_word = current_word[0].toLowerCase(); - - /* We could also check emoji_typing_state here, which is less accurate but more efficient. I've - * kept it unless someone wants to provide an option to toggle it for performance */ - if (curr_word_is_emoji() && current_word != ":") - { - loadEmojis(null, null).then( () => { - let modal_pos = event.target.getBoundingClientRect(); - modal_pos.x += window.scrollX; - modal_pos.y += window.scrollY; - - speed_carot_modal.style.display = "initial"; - speed_carot_modal.style.left = box_coords.x - 30 + "px"; - speed_carot_modal.style.top = modal_pos.y + box_coords.y + 14 + "px"; - - // Do the search (and do something with it) - const resultSet = emojisSearchDictionary.completeSearch(current_word.substring(1).replace(/[#!]/g, "")); - - const found = globalEmojis.filter(i => resultSet.has(i.name)); - - populate_speed_emoji_modal(found, event.target); - }); - } - else { - speed_carot_modal.style.display = "none"; - } -} - -function speed_carot_navigate(event) -{ - if (!selecting) return; - - let select_items = speed_carot_modal.querySelectorAll(".speed-modal-option"); - if (!select_items || !curr_word_is_emoji()) return; - - const modal_keybinds = { - // go up one, wrapping around to the bottom if pressed at the top - ArrowUp: () => emoji_index = ((emoji_index - 1) + select_items.length) % select_items.length, - // go down one, wrapping around to the top if pressed at the bottom - ArrowDown: () => emoji_index = ((emoji_index + 1) + select_items.length) % select_items.length, - // select the emoji - Enter: () => select_items[emoji_index].click(), - } - if (event.key in modal_keybinds) - { - select_items[emoji_index].classList.remove("selected"); - modal_keybinds[event.key](); - select_items[emoji_index].classList.add("selected"); - select_items[emoji_index].scrollIntoView({inline: "end", block: "nearest"}); - event.preventDefault(); - } -} - -function insertGhostDivs(element) { - let forms = element.querySelectorAll("textarea, .allow-emojis"); - forms.forEach(i => { - let ghostdiv - if (i.id == 'input-text-chat') { - ghostdiv = document.getElementsByClassName("ghostdiv")[0]; - } - else { - ghostdiv = document.createElement("div"); - ghostdiv.className = "ghostdiv"; - ghostdiv.style.display = "none"; - i.after(ghostdiv); - } - i.addEventListener('input', update_speed_emoji_modal, false); - i.addEventListener('keydown', speed_carot_navigate, false); }); } -const emojiModal = document.getElementById('emojiModal') +/** @type {{ [name: string]: number }} */ +const favoriteEmojis = JSON.parse(localStorage.getItem("favorite_emojis")) || {}; -function loadEmojis(t, inputTargetIDName) -{ - selecting = false; - speed_carot_modal.style.display = "none"; +const initEmojiModal = (() => { + let hasInit = false; + + return async () => { + if (hasInit) { + return; + } + hasInit = true; - if (inputTargetIDName) { - emojiInputTargetDOM = document.getElementById(inputTargetIDName); - emojiModal.addEventListener('hide.bs.modal', () => { - setTimeout(() => { - emojiInputTargetDOM.focus(); - }, 200); - }, {once : true}); + await emojiEngine.init(); + + document.getElementById('emojis-work').style.display = 'none'; + + /** @type {{ [tabName: string]: HTMLDivElement }} */ + const tabContentEls = {} + + /** @type {(kind: string, el: HTMLButtonElement) => void} */ + const addTabClickListener = (kind, el) => { + el.addEventListener('click', (e) => { + setTab(kind); + }); + } + + const favorites = Object.entries(favoriteEmojis).sort((a, b) => b[1] - a[1]); + /** @type {{ [name: string]: HTMLButtonElement }} */ + const favoriteClones = {}; + + const favoriteContentEl = (() => { + const content = document.createElement('div'); + tabContentEls['favorite'] = content; + return content; + })(); + + let currentTab = 'favorite'; + const setTab = (kind) => { + currentTab = kind; + tabContent.replaceChildren(tabContentEls[kind]); + } + + const emojiModal = document.getElementById('emojiModal'); + const emojiTabsEl = document.getElementById('emoji-modal-tabs'); + const tabContent = document.getElementById('emoji-tab-content'); + /** @type {HTMLInputElement} */ + const searchInputEl = document.getElementById('emoji_search'); + searchInputEl.disabled = false; + const searchResultsContainerEl = document.createElement('div'); + let isSearching = false; + /** @type {{ [index: string ]: HTMLButtonElement }} */ + const searchResultsEl = {}; + const favoriteTabEl = document.getElementById('emoji-modal-tabs-favorite'); + addTabClickListener('favorite', favoriteTabEl); + + window.emojiSearch = async () => { + if (searchInputEl.value.length === 0 && isSearching) { + isSearching = false; + setTab(currentTab); + } else if (searchInputEl.value.length > 0 && !isSearching) { + isSearching = true; + tabContent.replaceChildren(searchResultsContainerEl); + } + + if (isSearching) { + const query = searchInputEl.value; + requestIdleCallback(() => { + emojiEngine.search(query).then((results) => { + requestIdleCallback(() => { + searchResultsContainerEl.replaceChildren(...results.map((name) => searchResultsEl[name])); + }, { timeout: 100 }); + }); + }, { timeout: 100 }); + } + } + + const promises = Object.entries(emojiEngine.kinds).map(([kind, emojis]) => new Promise((res) => { + const tabEl = (() => { + const tab = document.createElement('li'); + const button = document.createElement('button'); + button.type = 'button'; + button.classList.add('nav-link', 'emojitab'); + button.dataset.bsToggle = 'tab'; + button.textContent = kind; + tab.appendChild(button); + emojiTabsEl.appendChild(tab); + addTabClickListener(kind, tab); + return tab; + })(); + + const tabContentEl = (() => { + const tabContent = document.createElement('div'); + return tabContent; + })(); + + tabContentEls[kind] = tabContentEl; + + const tick = () => { + for (const [name, count] of emojis) { + const buttonEl = document.createElement('button'); + buttonEl.type = 'button'; + buttonEl.classList.add('btn', 'm-1', 'px-0', 'emoji2'); + buttonEl.title = `${name} (${count})`; + + const imgEl = document.createElement('img'); + imgEl.loading = 'lazy'; + imgEl.src = emojiEngine.src(name); + imgEl.alt = name; + buttonEl.appendChild(imgEl); + + const searchClone = buttonEl.cloneNode(true); + const els = [buttonEl, searchClone]; + + if (name in favoriteEmojis) { + const favoriteClone = buttonEl.cloneNode(true); + favoriteClone.title = `${name} (${favoriteEmojis[name]})`; + els.push(favoriteClone); + favoriteClones[name] = favoriteClone; + } + + els.forEach((el) => { + el.addEventListener('click', (e) => { + emojiEngine.onInsert(name); + }); + }); + + tabContentEl.appendChild(buttonEl); + searchResultsEl[name] = searchClone; + } + + res(); + + } + requestIdleCallback(tick, { timeout: 250 }); + })); + + Promise.all(promises).then(() => { + for (const [name] of favorites) { + if (!(name in favoriteClones)) { + continue; + } + + favoriteContentEl.appendChild(favoriteClones[name]); + } + }); + + setTab(currentTab); } - - if (t && t.dataset.previousModal) { - emojiModal.addEventListener('hide.bs.modal', () => { - bootstrap.Modal.getOrCreateInstance(document.getElementById(t.dataset.previousModal)).show() - }, {once : true}); - } - - switch (emojiEngineState) { - case "inactive": - emojiEngineState = "loading" - return fetchEmojis(); - case "loading": - // this works because once the fetch completes, the first keystroke callback will fire and use the current value - return Promise.reject(); - case "ready": - return Promise.resolve(); - default: - throw Error("Unknown emoji engine state"); - } -} - -document.getElementById('emojiModal').addEventListener('shown.bs.modal', function () { - focusSearchBar(emojiSearchBarDOM); - setTimeout(() => { - focusSearchBar(emojiSearchBarDOM); - }, 200); - setTimeout(() => { - focusSearchBar(emojiSearchBarDOM); - }, 1000); -}); +})(); \ No newline at end of file diff --git a/files/routes/static.py b/files/routes/static.py index d522e5d8d..771b039b7 100644 --- a/files/routes/static.py +++ b/files/routes/static.py @@ -87,7 +87,10 @@ def emoji_list(v, kind): @cache.cached(make_cache_key=lambda nsfw:f"emojis_{nsfw}") -def get_emojis(nsfw): +def get_emojis(nsfw = None): + if nsfw is None: + nsfw = g.show_nsfw + emojis = g.db.query(Emoji, User).join(User, Emoji.author_id == User.id).filter(Emoji.submitter_id == None) if not nsfw: @@ -106,14 +109,79 @@ def get_emojis(nsfw): collected.append(emoji.json()) return collected -@app.get("/emojis_json") +@app.get("/emojis.json") @limiter.limit(DEFAULT_RATELIMIT, deduct_when=lambda response: response.status_code < 400) @limiter.limit(DEFAULT_RATELIMIT, deduct_when=lambda response: response.status_code < 400, key_func=get_ID) @auth_required def emojis(v): - return get_emojis(g.show_nsfw) + return get_emojis() + +@cache.cached(make_cache_key=lambda nsfw:f"emoji_tags_{nsfw}") +@app.get("/emoji_tags.json") +@limiter.limit(DEFAULT_RATELIMIT, deduct_when=lambda response: response.status_code < 400) +@limiter.limit(DEFAULT_RATELIMIT, deduct_when=lambda response: response.status_code < 400, key_func=get_ID) +@auth_required +def emoji_tags(v): + emojis = get_emojis() + + tags = {} + + def add_to_tag(tag: str, emoji: Emoji): + #Do not add empty tags. + if not tag: + return + + if tag not in tags: + tags[tag] = [] + + tags[tag].append([emoji['name'], emoji['count']]) + + for emoji in emojis: + add_to_tag(emoji['name'], emoji) + add_to_tag(emoji['name'][len(emoji['kind'].replace(' ', '')):], emoji) + + for tag in emoji['tags']: + add_to_tag(tag, emoji) + + return tags + +@cache.cached(make_cache_key=lambda nsfw:f"emoji_tags_{nsfw}") +@app.get("/emoji_names_count.json") +@limiter.limit(DEFAULT_RATELIMIT, deduct_when=lambda response: response.status_code < 400) +@limiter.limit(DEFAULT_RATELIMIT, deduct_when=lambda response: response.status_code < 400, key_func=get_ID) +@auth_required +def emoji_names_count(v): + emojis = get_emojis() + + names = {} + + for emoji in emojis: + names[emoji['name']] = emoji['count'] + + return names +@cache.cached(make_cache_key=lambda nsfw:f"emoji_tags_{nsfw}") +@app.get("/emoji_kinds.json") +@limiter.limit(DEFAULT_RATELIMIT, deduct_when=lambda response: response.status_code < 400) +@limiter.limit(DEFAULT_RATELIMIT, deduct_when=lambda response: response.status_code < 400, key_func=get_ID) +@auth_required +def emoji_kinds(v): + order = ["Marsey", "Platy", "Wolf", "Donkey Kong", "Tay", "Capy", "Carp", "Marsey Flags", "Marsey Alphabet", "Classic", "Rage", "Wojak", "Misc"] + emoji_kinds = {} + + for kind in order: + emoji_kinds[kind] = [] + + for emoji in get_emojis(): + kind = emoji['kind'] + if kind not in emoji_kinds: + emoji_kinds[kind] = [] + + emoji_kinds[kind].append([emoji['name'], emoji['count']]) + + # Flask will sort the keys alphabetically, so we need to jsonify this manually. + return json.dumps(emoji_kinds) @app.get('/sidebar') @limiter.limit(DEFAULT_RATELIMIT, deduct_when=lambda response: response.status_code < 400) diff --git a/files/templates/comments.html b/files/templates/comments.html index 4cee3a4a6..de09f5db4 100644 --- a/files/templates/comments.html +++ b/files/templates/comments.html @@ -257,7 +257,7 @@ {% if v and (v.id == c.author_id or v.admin_level >= PERMS['POST_COMMENT_EDITING']) %} - +
diff --git a/files/templates/userpage/banner.html b/files/templates/userpage/banner.html index b316b4ff6..c79da26f8 100644 --- a/files/templates/userpage/banner.html +++ b/files/templates/userpage/banner.html @@ -191,7 +191,7 @@ - +
{{macros.emoji_btn('input-message')}} @@ -208,7 +208,7 @@
- +
{{macros.emoji_btn('coin-transfer-reason')}} {{macros.gif_btn('coin-transfer-reason')}} @@ -221,7 +221,7 @@
- +
{{macros.emoji_btn('bux-transfer-reason')}} {{macros.gif_btn('bux-transfer-reason')}} @@ -508,7 +508,7 @@ {% if v and v.id != u.id %} - +
{{macros.emoji_btn('input-message-mobile')}} @@ -525,7 +525,7 @@
- +
{{macros.emoji_btn('coin-transfer-reason-mobile')}} {{macros.gif_btn('coin-transfer-reason-mobile')}} @@ -538,7 +538,7 @@
- +
{{macros.emoji_btn('bux-transfer-reason-mobile')}} {{macros.gif_btn('bux-transfer-reason-mobile')}} diff --git a/files/templates/util/macros.html b/files/templates/util/macros.html index f44c0369e..92f479551 100644 --- a/files/templates/util/macros.html +++ b/files/templates/util/macros.html @@ -114,7 +114,7 @@ {% macro emoji_btn(textarea_id, previous_modal) %} - {% endmacro %} @@ -136,7 +136,7 @@
- +
@@ -162,7 +162,7 @@
{% else %}
- +
@@ -347,7 +347,7 @@ {{gif_btn('input-text-chat')}} {{file_btn('file', False, True)}} - +