docbrown/app/javascript/actionsPanel/actionsPanel.js
Lisa Sy 7475716662
Make small CSS improvements to mod center (#9315) [deploy]
* Update mod center layout & color fixes

* Update SVG for external link

* - Update external link svg to use
- Remove scrollbar in actions menu
- Move action panel styling from `articles.scss` to `moderators.scss`

* Delete schema.rb

* Add back schema file

* SiteConfig view refactoring (#9286)

* Clean up payment pointer in top shell

* Simplify handling of social media icons

* Also guard against empty strings

* Only traverse hash once

* Adds a default value to the shell version cache response in case it returns undefined (#9250)

* [deploy] 🐞 Hotfix Real time chat was broken  (#9293)

* Feature 🚀 : Ability to delete messages in chat channels

- Sending message ID to frontend
- Deleting Message
- Use pusher to delete message realtime

* Minor Bug 🐞: Show message action only for current user

- User can delete or edit their own messages

* Test cases added

* Bug 🐞: Update message id for receiver

Message id was not sent to receiver by pusher

* Refactoring🛠: Message controller refactoring

* Test Cases📝 : Specs for Delete message added

* Feature 🚀 : Ability to edit messages

* Test Cases📝 : Specs for Edit message added

* Merge conflict resolved

* 🐞Hotfix: Findinder error in chat

Co-authored-by: Narender Singh <narender2031@gmail.com>

* Bump jsdom from 16.2.2 to 16.3.0 (#9279)

* Fix TypeError: userData is null in blockButton.js (#9299)

Should fix https://app.honeybadger.io/fault/67192/ed6f6b392b5bd791d6dc04732f125123.

* Fix TypeError: userData is null in initializeOnboardingTaskCard.js (#9298) [deploy]

* Fix TypeError: userData is null in initializeOnboardingTaskCard.js

Should fix https://app.honeybadger.io/fault/67192/65045742fda3390a067960f53a894e87.

* Combine return statements in initializeOnboardingTaskCard

* Fix TypeError: null is not an object in initializeArticleReactions.js (#9297) [deploy]

* Fix TypeError: null is not an object in initializeArticleReactions.js

Should fix https://app.honeybadger.io/fault/67192/6f9b4fdf475e2229c968fa26d785b90f

* Return 0 rather than undefined if reactionEl doesn't exist

* Routine Rubocop fixes (#9302)

* rubocop -A

* rubocop --auto-gen-config

* Fix sorting in Bundler/OrderedGems to consider punctuation

* Rubocop: activate Layout/ClassStructure (#9304)

* change Label Follow Weight Scale for Tags in Dashboard (#9247)

* [deploy] Remove codeql analysis for right now (#9308)

* Update Readme Headline (#9309)

* [deploy] Fix TypeError: Cannot set property 'innerHTML' of null (#9306)

Should fix https://app.honeybadger.io/fault/67192/f79e24dfb4e4364da09dda6380e9d2ff.

* Add /forem redirect (#9317)

* [deploy] Make sidebar sponsor headline configurable (#9251)

* Make sidebar sponsor headline configurable

* Fix spec

* Fix spec typo

* Create profile image generator (#8695)

* Create profile image generator

* Update spec/services/users/profile_image_generator_spec.rb

Co-authored-by: Mac Siri <krairit.siri@gmail.com>

* Remove difficult cloudinary dependency

Co-authored-by: Mac Siri <krairit.siri@gmail.com>

Co-authored-by: Michael Kohl <citizen428@gmail.com>
Co-authored-by: Fernando Valverde <fdov88@gmail.com>
Co-authored-by: Sarthak Sharma <7lovesharma7@gmail.com>
Co-authored-by: Narender Singh <narender2031@gmail.com>
Co-authored-by: dependabot-preview[bot] <27856297+dependabot-preview[bot]@users.noreply.github.com>
Co-authored-by: Vaidehi Joshi <vaidehi.sj@gmail.com>
Co-authored-by: rhymes <rhymesete@gmail.com>
Co-authored-by: Veggier <47649859+Veggier@users.noreply.github.com>
Co-authored-by: Molly Struve <mollylbs@gmail.com>
Co-authored-by: Ben Halpern <bendhalpern@gmail.com>
Co-authored-by: Jacob Herrington <jacobherringtondeveloper@gmail.com>
Co-authored-by: Mac Siri <krairit.siri@gmail.com>
2020-07-15 09:54:19 -07:00

372 lines
11 KiB
JavaScript

import { request } from '@utilities/http';
export function addCloseListener() {
const button = document.querySelector('.close-actions-panel');
button.addEventListener('click', () => {
// getting the article show page document because this is called within an iframe
// eslint-disable-next-line no-restricted-globals
const articleDocument = top.document;
articleDocument
.querySelector('.mod-actions-menu')
.classList.toggle('showing');
articleDocument
.querySelector('.mod-actions-menu-btn')
.classList.toggle('hidden');
});
}
export function initializeHeight() {
document.documentElement.style.height = '100%';
document.body.style.cssText = 'height: 100%; margin: 0; padding-top: 0; overflow-y: hidden';
document.getElementById('page-content').style.cssText =
'margin-top: 0 !important; margin-bottom: 0;';
}
function toggleDropdown(type) {
if (type === 'set-experience') {
document
.querySelector('.set-experience-options')
.classList.toggle('hidden');
} else if (type === 'adjust-tags') {
document.querySelector('.adjust-tags-options').classList.toggle('hidden');
}
}
function applyReactedClass(category) {
const upVote = document.querySelector("[data-category='thumbsup']");
const downVote = document.querySelector("[data-category='thumbsdown']");
const vomitVote = document.querySelector("[data-category='vomit']");
if (category === 'thumbsup') {
downVote.classList.remove('reacted');
vomitVote.classList.remove('reacted');
} else {
upVote.classList.remove('reacted');
}
}
export function addReactionButtonListeners() {
const butts = Array.from(
document.querySelectorAll('.reaction-button, .reaction-vomit-button'),
);
/* eslint-disable camelcase */
butts.forEach((butt) => {
butt.addEventListener('click', async (event) => {
event.preventDefault();
const {
reactableType: reactable_type,
category,
reactableId: reactable_id,
} = butt.dataset;
applyReactedClass(category);
butt.classList.toggle('reacted');
try {
const response = await request('/reactions', {
method: 'POST',
body: { reactable_type, category, reactable_id },
});
const outcome = await response.json();
let message;
/* eslint-disable no-restricted-globals */
if (outcome.result === 'create' && outcome.category === 'thumbsup') {
message = 'This post will be more visible.';
} else if (
outcome.result === 'create' &&
outcome.category === 'thumbsdown'
) {
message = 'This post will be less visible.';
} else if (
outcome.result === 'create' &&
outcome.category === 'vomit'
) {
message = "You've flagged this post as abusive or spam.";
} else if (outcome.result === 'destroy') {
message = 'Your quality rating was removed.';
} else if (outcome.error) {
message = `Error: ${outcome.error}`;
}
top.addSnackbarItem({
message,
addCloseButton: true,
});
/* eslint-enable no-restricted-globals */
} catch (error) {
// eslint-disable-next-line no-alert
alert(error);
}
});
});
/* eslint-enable camelcase */
}
function clearExpLevels() {
Array.from(
document.getElementsByClassName('level-rating-button selected'),
).forEach((el) => {
el.classList.remove('selected');
});
}
async function updateExperienceLevel(currentUserId, articleId, rating, group) {
try {
const response = await request('/rating_votes', {
method: 'POST',
body: JSON.stringify({
user_id: currentUserId,
article_id: articleId,
rating,
group,
}),
});
const outcome = await response.json();
if (outcome.result === 'Success') {
clearExpLevels();
document
.getElementById(`js__rating__vote__${rating}`)
.classList.add('selected');
} else {
// eslint-disable-next-line no-alert
alert(outcome.error);
}
} catch (error) {
// eslint-disable-next-line no-alert
alert(error);
}
}
function toggleSubmitContainer() {
document
.getElementById('adjustment-reason-container')
.classList.toggle('hidden');
}
function clearAdjustmentReason() {
document.getElementById('tag-adjustment-reason').value = '';
}
function renderTagOnArticle(tagName, colors) {
/* eslint-disable no-restricted-globals */
let articleTagsContainer;
if (top.document.location.pathname.endsWith('/mod')) {
[articleTagsContainer] = top.document
.getElementById('quick-mod-article')
.contentDocument.getElementsByClassName('tags');
} else {
[articleTagsContainer] = top.document.getElementsByClassName('spec__tags');
}
/* eslint-enable no-restricted-globals */
const newTag = document.createElement('a');
newTag.innerText = `#${tagName}`;
newTag.setAttribute('class', 'crayons-tag mr-1');
newTag.setAttribute('href', `/t/${tagName}`);
newTag.style = `background-color: ${colors.bg}; color: ${colors.text};`;
articleTagsContainer.appendChild(newTag);
}
async function adjustTag(el) {
const reasonForAdjustment = document.getElementById('tag-adjustment-reason')
.value;
const body = {
tag_adjustment: {
// TODO: change to tag ID
tag_name: el.dataset.tagName || el.value,
article_id: el.dataset.articleId,
adjustment_type:
el.dataset.adjustmentType === 'subtract' ? 'removal' : 'addition',
reason_for_adjustment: reasonForAdjustment,
},
};
try {
const response = await request('/tag_adjustments', {
method: 'POST',
body: JSON.stringify(body),
});
const outcome = await response.json();
if (outcome.status === 'Success') {
let adjustedTagName;
if (el.tagName === 'BUTTON') {
adjustedTagName = el.dataset.tagName;
el.remove();
} else {
adjustedTagName = el.value;
// eslint-disable-next-line no-param-reassign, require-atomic-updates
el.value = '';
}
toggleSubmitContainer();
clearAdjustmentReason();
if (outcome.result === 'addition') {
renderTagOnArticle(adjustedTagName, outcome.colors);
} else {
// eslint-disable-next-line no-restricted-globals
const tagOnArticle = top.document.querySelector(
`.crayons-tag[href="/t/${adjustedTagName}"]`,
);
tagOnArticle.remove();
}
// eslint-disable-next-line no-restricted-globals
top.addSnackbarItem({
message: `The #${adjustedTagName} tag was ${
outcome.result === 'addition' ? 'added' : 'removed'
}.`,
addCloseButton: true,
});
} else {
// eslint-disable-next-line no-restricted-globals
top.addSnackbarItem({
message: `An error occurred: ${outcome.error}`,
addCloseButton: true,
});
}
} catch (error) {
// eslint-disable-next-line no-alert
alert(error);
}
}
export function handleAdjustTagBtn(btn) {
const currentActiveTags = document.querySelectorAll(
'button.adjustable-tag.active',
);
const adminTagInput = document.getElementById('admin-add-tag');
/* eslint-disable no-restricted-globals */
/* eslint-disable no-alert */
if (
adminTagInput &&
adminTagInput.value !== '' &&
confirm(
'This will clear your current "Add a tag" input. Do you want to continue?',
)
) {
/* eslint-enable no-restricted-globals */
/* eslint-enable no-alert */
adminTagInput.value = '';
} else if (currentActiveTags.length > 0) {
currentActiveTags.forEach((tag) => {
if (tag !== btn) {
tag.classList.remove('active');
}
btn.classList.toggle('active');
});
if (btn.classList.contains('active')) {
document
.getElementById('adjustment-reason-container')
.classList.remove('hidden');
} else {
document
.getElementById('adjustment-reason-container')
.classList.add('hidden');
}
} else {
btn.classList.toggle('active');
toggleSubmitContainer();
}
}
function handleAdminInput() {
const addTagInput = document.getElementById('admin-add-tag');
if (addTagInput) {
addTagInput.addEventListener('focus', () => {
document
.getElementById('adjustment-reason-container')
.classList.remove('hidden');
const activeTagBtns = Array.from(
document.querySelectorAll('button.adjustable-tag.active'),
);
activeTagBtns.forEach((btn) => {
btn.classList.remove('active');
});
});
addTagInput.addEventListener('focusout', () => {
if (addTagInput.value === '') {
toggleSubmitContainer();
}
});
}
}
export function addAdjustTagListeners() {
Array.from(document.getElementsByClassName('adjustable-tag')).forEach(
(btn) => {
btn.addEventListener('click', () => {
handleAdjustTagBtn(btn);
});
},
);
const adjustTagSubmitBtn = document.getElementById('tag-adjust-submit');
if (adjustTagSubmitBtn) {
adjustTagSubmitBtn.addEventListener('click', (e) => {
e.preventDefault();
const textArea = document.getElementById('tag-adjustment-reason');
const dataSource =
document.querySelector('button.adjustable-tag.active') ||
document.getElementById('admin-add-tag');
if (textArea.checkValidity()) {
adjustTag(dataSource);
}
});
handleAdminInput();
}
}
export function addBottomActionsListeners() {
addAdjustTagListeners();
Array.from(document.getElementsByClassName('other-things-btn')).forEach(
(btn) => {
btn.addEventListener('click', () => {
btn.classList.toggle('active');
const otherBtns = Array.from(
document.getElementsByClassName('other-things-btn'),
).filter((otherBtn) => otherBtn !== btn);
otherBtns.forEach((otherBtn) => {
otherBtn.classList.toggle('inactive');
});
btn.querySelector('.label-wrapper > .icon').classList.toggle('hidden');
btn
.querySelector('.toggle-chevron-container')
.classList.toggle('rotated');
toggleDropdown(btn.dataset.otherThingsType);
});
},
);
document.querySelectorAll('.level-rating-button').forEach((btn) => {
btn.addEventListener('click', () => {
updateExperienceLevel(
btn.dataset.userId,
btn.dataset.articleId,
btn.value,
btn.dataset.group,
);
});
});
}
export function initializeActionsPanel() {
initializeHeight();
addCloseListener();
addReactionButtonListeners();
addBottomActionsListeners();
}