Adrià Vilanova Martínez | 72a4ea4 | 2024-02-09 22:35:32 +0100 | [diff] [blame] | 1 | import {waitFor} from 'poll-until-promise'; |
| 2 | |
| 3 | import {parseUrl} from '../../../common/commonUtils'; |
Adrià Vilanova Martínez | b523be9 | 2024-05-25 19:14:19 +0200 | [diff] [blame] | 4 | import {getOptions} from '../../../common/options/optionsUtils'; |
Adrià Vilanova Martínez | 72a4ea4 | 2024-02-09 22:35:32 +0100 | [diff] [blame] | 5 | |
| 6 | const kOpenReplyEditorIntervalInMs = 500; |
| 7 | const kOpenReplyEditorTimeoutInMs = 10 * 1000; |
| 8 | |
| 9 | // @TODO: Handle observing when the hash is added after the page has loaded. |
| 10 | export default class FlattenThreadsReplyActionHandler { |
| 11 | /** |
| 12 | * @param {Object} options Options object which at least includes the |
| 13 | * |flattenthreads| and |flattenthreads_switch_enabled| options. |
| 14 | */ |
| 15 | constructor(options = null) { |
| 16 | this.options = options; |
| 17 | } |
| 18 | |
| 19 | async handleIfApplicable() { |
| 20 | if (await this.isFeatureEnabled()) this.handle(); |
| 21 | } |
| 22 | |
| 23 | async handle() { |
| 24 | const hash = window.location.hash; |
| 25 | if (hash === '#action=reply') await this.openReplyEditor(); |
| 26 | } |
| 27 | |
| 28 | async openReplyEditor() { |
| 29 | // We erase the hash so the Community Console doesn't open the reply |
| 30 | // editor, since we're going to do that instead. |
| 31 | window.location.hash = ''; |
| 32 | |
| 33 | const messageId = this.getCurrentMessageId(); |
| 34 | if (messageId === null) { |
| 35 | console.error( |
| 36 | '[FlattenThreadsReplyActionHandler] Could not parse current message id.'); |
| 37 | return; |
| 38 | } |
| 39 | |
| 40 | const replyButton = await waitFor(async () => { |
| 41 | const replyButton = document.querySelector( |
| 42 | '[data-twpt-message-id="' + messageId + |
| 43 | '"] twpt-flatten-thread-reply-button'); |
| 44 | if (replyButton === null) throw new Error('Reply button not found.'); |
| 45 | return replyButton; |
| 46 | }, { |
| 47 | interval: kOpenReplyEditorIntervalInMs, |
| 48 | timeout: kOpenReplyEditorTimeoutInMs, |
| 49 | }); |
| 50 | |
| 51 | const e = new Event('twpt-click'); |
| 52 | replyButton.dispatchEvent(e); |
| 53 | } |
| 54 | |
| 55 | async isFeatureEnabled() { |
| 56 | let options; |
| 57 | if (this.options !== null) { |
| 58 | options = this.options; |
| 59 | } else { |
| 60 | options = |
| 61 | await getOptions(['flattenthreads', 'flattenthreads_switch_enabled']); |
| 62 | } |
| 63 | return options['flattenthreads'] && |
| 64 | options['flattenthreads_switch_enabled']; |
| 65 | } |
| 66 | |
| 67 | getCurrentMessageId() { |
| 68 | const thread = parseUrl(window.location.href); |
| 69 | if (thread === false || thread.message === null) { |
| 70 | return null; |
| 71 | } |
| 72 | return thread.message; |
| 73 | } |
| 74 | } |