const fetchAllButton = document.getElementById("fetch-quotes");
const fetchRandomButton = document.getElementById("fetch-random");
const fetchByAuthorButton = document.getElementById("fetch-by-author");
const updateById = document.getElementById("update-by-id")
const quoteContainer = document.getElementById("quote-container");
const quoteText = document.querySelector(".quote");
const attributionText = document.querySelector(".attribution");
const updateContainer = document.querySelector(".request-buttons");
const idTextField = document.getElementById("identification");
const resetQuotes = () => {
quoteContainer.innerHTML = "";
};
const renderError = (response) => {
quoteContainer.innerHTML = `<p>Your request returned an error from the server: </p>
<p>Code: ${response.status}</p>
<p>${response.statusText}</p>`;
};
const renderQuotes = (quotes = []) => {
resetQuotes();
if (quotes.length > 0) {
quotes.forEach((quote) => {
const newQuote = document.createElement("div");
newQuote.className = "single-quote";
newQuote.innerHTML = `<div class="quote-text">${quote.quote}</div>
<div class="attribution">- ${quote.person}</div><button class="delete-btn" data-id=${quote.id}>Delete Quote</button><button class="update-btn" data-id=${quote.id}>Change Quote</button>`;
quoteContainer.appendChild(newQuote);
});
} else {
quoteContainer.innerHTML = "<p>Your request returned no quotes.</p>";
}
};
//Bubbling event for deleting quote
quoteContainer.addEventListener("click", (e) => {
if (e.target.classList.contains("delete-btn")) {
const id = e.target.dataset.id;
idTextField.value = id;
idTextField.disabled = true;
// alert(e.target.dataset.id)
fetch(`/api/quotes/${id}`, {
method: "DELETE",
})
.then((response) => {
if (response.ok) {
return response.json();
} else {
renderError(response);
}
})
.then((response) => {
renderQuotes(response.quotes);
});
}
});
//Bubbling event for updating quote
quoteContainer.addEventListener("click", (e) => {
if (e.target.classList.contains("update-btn")) {
let quoteToUpdate;
const id = e.target.dataset.id;
idTextField.value = id
idTextField.disabled = true
console.log(id);
fetch(`/api/quotes/${id}`)
.then((response) => {
if (response.ok) {
return response.json();
} else {
renderError(response);
}
})
.then((response) => {
// console.log(response.quote)
quoteToUpdate = response.quote;
const quoteDiv = document.createElement('div')
quoteDiv.className = 'update-stuff'
const quote = document.createElement("textarea");
quote.className = 'dynamic-quote'
quote.rows = "5"
quote.columns = "6"
quote.value = quoteToUpdate.quote;
const person = document.createElement("input");
person.className = 'dynamic-person'
person.type = "text";
person.value = quoteToUpdate.person;
quoteDiv.append(quote)
quoteDiv.append(person)
if(updateContainer.length === 4){
updateContainer.removeChild(updateContainer.lastChild)
updateContainer.append(quoteDiv);
}
else{
updateContainer.append(quoteDiv)
}
});
}
});
updateById.addEventListener('click', () => {
const id = idTextField.value
const quote = document.querySelector('.dynamic-quote').value
const person = document.querySelector('.dynamic-person').value
fetch(`/api/quotes/${id}?quote=${quote}&person=${person}`, {
method: "PUT"
})
.then(response => {
if(response.ok){
return response.json()
}else{
renderError(response)
}
})
.then(response => {
renderQuotes([response.quote])
updateContainer.removeChild(updateContainer.lastChild)
})
})
fetchAllButton.addEventListener("click", () => {
fetch("/api/quotes")
.then((response) => {
if (response.ok) {
return response.json();
} else {
renderError(response);
}
})
.then((response) => {
renderQuotes(response.quotes);
if(updateContainer.length > 3){
updateContainer.removeChild(updateContainer.lastChild)
}
});
});
fetchRandomButton.addEventListener("click", () => {
fetch("/api/quotes/random")
.then((response) => {
if (response.ok) {
return response.json();
} else {
renderError(response);
}
})
.then((response) => {
renderQuotes([response.quote]);
});
});
fetchByAuthorButton.addEventListener("click", () => {
const author = document.getElementById("author").value;
fetch(`/api/quotes?person=${author}`)
.then((response) => {
if (response.ok) {
return response.json();
} else {
renderError(response);
}
})
.then((response) => {
renderQuotes(response.quotes);
});
});
var WPML_Media_Posts_Media_Flag = WPML_Media_Posts_Media_Flag || {};
jQuery(function ($) {
"use strict";
var updateContainer = $('#wpml-media-posts-media-flag');
var updateButton = updateContainer.find('.button-primary');
var spinner = updateContainer.find('.spinner');
var prepareAction = updateContainer.data('prepareAction');
var prepareNonce = updateContainer.data('prepareNonce');
var processAction = updateContainer.data('processAction');
var processNonce = updateContainer.data('processNonce');
var statusContainer = updateContainer.find('.status');
function getQueryParams(qs) {
qs = qs.split('+').join(' ');
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
var queryParams = getQueryParams(location.search);
if (queryParams.run_setup) {
showProgress();
runSetup();
}
updateButton.on("click", function () {
showProgress();
runSetup();
});
function showProgress() {
spinner.css({visibility: "visible"});
updateButton.prop("disabled", true);
}
function hideProgress() {
spinner.css({visibility: "hidden"});
updateButton.prop("disabled", false);
}
function setStatus(statusText) {
statusContainer.html(statusText);
}
function runSetup() {
var data = {
action: prepareAction,
nonce: prepareNonce
};
$.ajax({
url: ajaxurl,
type: "POST",
dataType: "json",
data: data,
success: function (response) {
handleResponse(response);
if (!response.success) {
return;
}
if (response.data.status) {
setStatus(response.data.status);
}
setInitialLanguage();
},
error: function (jqXHR, status, error) {
statusContainer.html(jqXHR.statusText || status || error);
}
});
}
function handleResponse(response) {
var error = [];
if (response.error) {
error.push(response.error);
}
if (!response.success && response.data) {
error.push(response.data);
}
if (error.length) {
statusContainer.html('<pre>' + error.join('</pre><pre>') + '</pre>');
}
}
function setInitialLanguage() {
var data = {
action: processAction,
nonce: processNonce
};
$.ajax({
url: ajaxurl,
type: "POST",
dataType: "json",
data: data,
success: function (response) {
handleResponse(response);
if (!response.success) {
return;
}
var message = response.message ? response.message : response.data.message;
setStatus(message);
setHasMediaFlag(0);
},
error: function (jqXHR, status, error) {
statusContainer.html(jqXHR.statusText || status || error);
}
});
}
function setHasMediaFlag(offset) {
var data = {
action: processAction,
nonce: processNonce,
offset: offset
};
$.ajax({
url: ajaxurl,
type: "POST",
dataType: "json",
data: data,
success: function (response) {
handleResponse(response);
if (!response.success) {
return;
}
if (response.data.status) {
setStatus(response.data.status);
}
if (response.data.continue) {
setHasMediaFlag(response.data.offset);
} else {
if (queryParams.redirect_to) {
location.href = queryParams.redirect_to;
} else {
location.reload();
}
}
},
error: function (jqXHR, status, error) {
statusContainer.html(jqXHR.statusText || status || error);
}
});
}
});
import MockAdapter from 'axios-mock-adapter';
import { loadHTMLFixture } from 'helpers/fixtures';
import { useMockLocationHelper } from 'helpers/mock_window_location_helper';
import { setTestTimeout } from 'helpers/timeout';
import Clusters from '~/clusters/clusters_bundle';
import axios from '~/lib/utils/axios_utils';
import initProjectSelectDropdown from '~/project_select';
jest.mock('~/lib/utils/poll');
jest.mock('~/project_select');
useMockLocationHelper();
describe('Clusters', () => {
setTestTimeout(1000);
let cluster;
let mock;
const mockGetClusterStatusRequest = () => {
const { statusPath } = document.querySelector('.js-edit-cluster-form').dataset;
mock = new MockAdapter(axios);
mock.onGet(statusPath).reply(200);
};
beforeEach(() => {
loadHTMLFixture('clusters/show_cluster.html');
});
beforeEach(() => {
mockGetClusterStatusRequest();
});
beforeEach(() => {
cluster = new Clusters();
});
afterEach(() => {
cluster.destroy();
mock.restore();
});
describe('class constructor', () => {
beforeEach(() => {
jest.spyOn(Clusters.prototype, 'initPolling');
cluster = new Clusters();
});
it('should call initPolling on construct', () => {
expect(cluster.initPolling).toHaveBeenCalled();
});
it('should call initProjectSelectDropdown on construct', () => {
expect(initProjectSelectDropdown).toHaveBeenCalled();
});
});
describe('updateContainer', () => {
describe('when creating cluster', () => {
it('should show the creating container', () => {
cluster.updateContainer(null, 'creating');
expect(cluster.creatingContainer.classList.contains('hidden')).toBeFalsy();
expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
expect(window.location.reload).not.toHaveBeenCalled();
});
it('should continue to show `creating` banner with subsequent updates of the same status', () => {
cluster.updateContainer(null, 'creating');
cluster.updateContainer('creating', 'creating');
expect(cluster.creatingContainer.classList.contains('hidden')).toBeFalsy();
expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
expect(window.location.reload).not.toHaveBeenCalled();
});
});
describe('when cluster is created', () => {
it('should hide the "creating" banner and refresh the page', () => {
jest.spyOn(cluster, 'setClusterNewlyCreated');
cluster.updateContainer(null, 'creating');
cluster.updateContainer('creating', 'created');
expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
expect(window.location.reload).toHaveBeenCalled();
expect(cluster.setClusterNewlyCreated).toHaveBeenCalledWith(true);
});
it('when the page is refreshed, it should show the "success" banner', () => {
jest.spyOn(cluster, 'setClusterNewlyCreated');
jest.spyOn(cluster, 'isClusterNewlyCreated').mockReturnValue(true);
cluster.updateContainer(null, 'created');
cluster.updateContainer('created', 'created');
expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
expect(cluster.successContainer.classList.contains('hidden')).toBeFalsy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
expect(window.location.reload).not.toHaveBeenCalled();
expect(cluster.setClusterNewlyCreated).toHaveBeenCalledWith(false);
});
it('should not show a banner when status is already `created`', () => {
jest.spyOn(cluster, 'setClusterNewlyCreated');
jest.spyOn(cluster, 'isClusterNewlyCreated').mockReturnValue(false);
cluster.updateContainer(null, 'created');
cluster.updateContainer('created', 'created');
expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeTruthy();
expect(window.location.reload).not.toHaveBeenCalled();
expect(cluster.setClusterNewlyCreated).not.toHaveBeenCalled();
});
});
describe('when cluster has error', () => {
it('should show the error container', () => {
cluster.updateContainer(null, 'errored', 'this is an error');
expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeFalsy();
expect(cluster.errorReasonContainer.textContent).toContain('this is an error');
});
it('should show `error` banner when previously `creating`', () => {
cluster.updateContainer('creating', 'errored');
expect(cluster.creatingContainer.classList.contains('hidden')).toBeTruthy();
expect(cluster.successContainer.classList.contains('hidden')).toBeTruthy();
expect(cluster.errorContainer.classList.contains('hidden')).toBeFalsy();
});
});
describe('when cluster is unreachable', () => {
it('should show the unreachable warning container', () => {
cluster.updateContainer(null, 'unreachable');
expect(cluster.unreachableContainer.classList.contains('hidden')).toBe(false);
});
});
describe('when cluster has an authentication failure', () => {
it('should show the authentication failure warning container', () => {
cluster.updateContainer(null, 'authentication_failure');
expect(cluster.authenticationFailureContainer.classList.contains('hidden')).toBe(false);
});
});
});
describe('fetch cluster environments success', () => {
beforeEach(() => {
jest.spyOn(cluster.store, 'toggleFetchEnvironments').mockReturnThis();
jest.spyOn(cluster.store, 'updateEnvironments').mockReturnThis();
cluster.handleClusterEnvironmentsSuccess({ data: {} });
});
it('toggles the cluster environments loading icon', () => {
expect(cluster.store.toggleFetchEnvironments).toHaveBeenCalled();
});
it('updates the store when cluster environments is retrieved', () => {
expect(cluster.store.updateEnvironments).toHaveBeenCalled();
});
});
describe('handleClusterStatusSuccess', () => {
beforeEach(() => {
jest.spyOn(cluster.store, 'updateStateFromServer').mockReturnThis();
jest.spyOn(cluster, 'updateContainer').mockReturnThis();
cluster.handleClusterStatusSuccess({ data: {} });
});
it('updates clusters store', () => {
expect(cluster.store.updateStateFromServer).toHaveBeenCalled();
});
it('updates message containers', () => {
expect(cluster.updateContainer).toHaveBeenCalled();
});
});
});