Adrià Vilanova MartÃnez | 412b758 | 2022-12-30 01:35:30 +0100 | [diff] [blame^] | 1 | export const kAdditionalInfoPrefix = '__TWPT_FLATTENTHREADS_ADDITIONALINFO__'; |
| 2 | export const kAdditionalInfoRegex = |
| 3 | /^__TWPT_FLATTENTHREADS_ADDITIONALINFO__(.*)/; |
| 4 | |
| 5 | export const kReplyPayloadSelector = |
| 6 | '.scTailwindThreadMessageMessagecardcontent:not(.scTailwindThreadMessageMessagecardpromoted) .scTailwindThreadPostcontentroot html-blob'; |
| 7 | |
| 8 | export default class FlattenThreads { |
| 9 | construct() {} |
| 10 | |
| 11 | getExtraInfo(node) { |
| 12 | let rawExtraInfo = null; |
| 13 | const possibleExtraInfoNodes = |
| 14 | node.querySelectorAll('span[style*=\'display\'][style*=\'none\']'); |
| 15 | for (const candidate of possibleExtraInfoNodes) { |
| 16 | const content = candidate.textContent; |
| 17 | const matches = content.match(kAdditionalInfoRegex); |
| 18 | if (matches) { |
| 19 | rawExtraInfo = matches?.[1] ?? null; |
| 20 | break; |
| 21 | } |
| 22 | } |
| 23 | if (!rawExtraInfo) return null; |
| 24 | return JSON.parse(rawExtraInfo); |
| 25 | } |
| 26 | |
| 27 | injectId(node, extraInfo) { |
| 28 | const root = node.closest('.scTailwindThreadMessageMessagecardcontent'); |
| 29 | if (!root) return false; |
| 30 | root.setAttribute('data-twpt-message-id', extraInfo.id); |
| 31 | return true; |
| 32 | } |
| 33 | |
| 34 | injectQuote(node, extraInfo) { |
| 35 | const content = node.closest('.scTailwindThreadPostcontentroot'); |
| 36 | // @TODO: Change this by the actual quote component |
| 37 | const quote = document.createElement('div'); |
| 38 | quote.textContent = 'QUOTE(' + extraInfo.parentMessage.id + ')'; |
| 39 | content.prepend(quote); |
| 40 | } |
| 41 | |
| 42 | injectIfApplicable(node) { |
| 43 | // If we injected the additional information, it means the flatten threads |
| 44 | // feature is enabled and in actual use, so we should inject the quote. |
| 45 | const extraInfo = this.getExtraInfo(node); |
| 46 | if (!extraInfo) return; |
| 47 | |
| 48 | this.injectId(node, extraInfo); |
| 49 | if (extraInfo.isComment) this.injectQuote(node, extraInfo); |
| 50 | } |
| 51 | |
| 52 | shouldInject(node) { |
| 53 | return node.matches(kReplyPayloadSelector); |
| 54 | } |
| 55 | } |