Skip to content

Commit

Permalink
Issue Rewrite JavaScript for Tiny #191
Browse files Browse the repository at this point in the history
  • Loading branch information
Oni01110011 committed Oct 6, 2024
1 parent 021a268 commit 82e2a2b
Show file tree
Hide file tree
Showing 11 changed files with 650 additions and 650 deletions.
130 changes: 67 additions & 63 deletions amd/src/approve.js
Original file line number Diff line number Diff line change
@@ -1,69 +1,73 @@
define(['jquery'], function($) {
export default {
init(approvedIcon, disapprovedIcon) {
// After initialization, loop through all elements for subscribe/unsubscribe.
document.querySelectorAll(".datalynxfield__approve").forEach(element => {
const href = element.href;
const params = extractParams(href.split('?')[1]);

return {
init: function(approvedicon, disapprovedicon) {
// After initialisation we loop through all links for subscribe / unsubscribe.
$( ".datalynxfield__approve" ).each(function () {
var href = this.href;
var params = extractParams(href.split('?')[1]);
// Add new click event listener
element.addEventListener('click', (e) => {
e.preventDefault(); // Don't follow hrefs.

$(this).off( "click" );
$(this).click(function(e) {
e.preventDefault(); // Don't follow hrefs.
// AJAX call
var actionurl = "field/_approve/ajax.php";
$.ajax(
{
method: "POST",
url: actionurl,
data: params,
context: this,
success: function(data) {
if (data && $(this).children().hasClass('approved')) {
$(this).children().removeClass('approved');
$(this).children().prop('src', disapprovedicon);
$(this).children().prop('alt', 'approve');
$(this).children().prop('title', 'approve');
params.action = 'approve';
} else if (data && !$(this).children().hasClass('approved')) {
$(this).children().addClass('approved');
$(this).children().prop('src', approvedicon);
$(this).children().prop('alt', 'disapprove');
$(this).children().prop('title', 'disapprove');
params.action = 'disapprove';
}
},
}
);
// AJAX call
const actionUrl = "field/_approve/ajax.php";
fetch(actionUrl, {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: new URLSearchParams(params)
})
.then(response => {
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
return response.json();
})
.then(data => {
const imgElement = element.querySelector('img');
if (data && imgElement.classList.contains('approved')) {
imgElement.classList.remove('approved');
imgElement.src = disapprovedIcon;
imgElement.alt = 'approve';
imgElement.title = 'approve';
params.action = 'approve';
} else if (data && !imgElement.classList.contains('approved')) {
imgElement.classList.add('approved');
imgElement.src = approvedIcon;
imgElement.alt = 'disapprove';
imgElement.title = 'disapprove';
params.action = 'disapprove';
}
return null;
})
.catch((error) => {
throw error;
});

});
});

// Extract params from a query string.
const extractParams = (paramString) => {
const params = new URLSearchParams(paramString);
const output = {};

/**
* Extract params.
*
* @param {string} paramstring
* @returns {{}}
*/
function extractParams(paramstring) {
let params = paramstring.split("&");
let output = {}; // Create an object.
for (var i = 0; i < params.length; i++) {
var param = params[i];
output[param.split("=")[0]] = param.split("=")[1];
}
if ('approve' in output) {
output.entryid = output.approve;
output.action = 'approve';
} else if ('disapprove' in output) {
output.entryid = output.disapprove;
output.action = 'disapprove';
} else {
output.entryid = output.approve;
output.action = 'approve';
}
return output;
for (const [key, value] of params.entries()) {
output[key] = value;
}
}
};
});

if ('approve' in output) {
output.entryid = output.approve;
output.action = 'approve';
} else if ('disapprove' in output) {
output.entryid = output.disapprove;
output.action = 'disapprove';
} else {
output.entryid = output.approve;
output.action = 'approve';
}

return output;
};
}
};
118 changes: 58 additions & 60 deletions amd/src/behavior.js
Original file line number Diff line number Diff line change
@@ -1,68 +1,66 @@
define(['jquery'], function($) {
export default {
init() {
document.querySelectorAll('img[data-for]').forEach((img) => {
img.addEventListener("click", (event) => {
const clickedImg = event.target;
const behaviorid = clickedImg.getAttribute('data-behavior-id');
const permissionid = clickedImg.getAttribute('data-permission-id');
const forproperty = clickedImg.getAttribute('data-for');
const sesskey = document.querySelector('table.datalynx-behaviors')?.getAttribute('data-sesskey') || M.cfg.sesskey;
const actionurl = "behavior_edit_ajax.php";

return {
init: function() {
$('img[data-for]').on( "click", function ( event ) {
// Construct the object
const obj = {
behaviorid,
permissionid,
forproperty,
sesskey
};

var img = event.target;
var behaviorid = img.getAttribute('data-behavior-id');
var permissionid = img.getAttribute('data-permission-id');
var forproperty = img.getAttribute('data-for');
var sesskey = $('table.datalynx-behaviors').attr('data-sesskey'); // Maybe M.cfg.sesskey.
var actionurl = "behavior_edit_ajax.php";


// This was in javascript-static.js in lib.
var obj = {
behaviorid: behaviorid,
permissionid: permissionid,
forproperty: forproperty,
sesskey: sesskey
};

var list = [];
for(var k in obj) {
k = encodeURIComponent(k);
var value = obj[k];
if(obj[k] instanceof Array) {
for(var i in value) {
list.push(k+'[]='+encodeURIComponent(value[i]));
}
// Serialize the object to a query string
const list = Object.keys(obj).map((k) => {
const encodedKey = encodeURIComponent(k);
const value = obj[k];
if (Array.isArray(value)) {
return value.map(v => `${encodedKey}[]=${encodeURIComponent(v)}`).join('&');
} else {
list.push(k+'='+encodeURIComponent(value));
return `${encodedKey}=${encodeURIComponent(value)}`;
}
}
obj = list.join('&');
}).join('&');

// Ajax request to get current options.
$.ajax(
{
method: "POST",
timeout: 5000,
url: actionurl,
data: obj,
context: this,
dataType: "text",
success: function(data) {
if (data != '') {
// console.log("RAW JSON DATA: " + data);
var src = img.getAttribute("src");
if (src.search("-enabled") !== -1) {
src = src.replace("-enabled", "-n");
} else {
src = src.replace("-n", "-enabled");
}
img.setAttribute("src", src);
}
},
error: function() {
alert("Error");
// Create an AbortController to implement timeout
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);

// Fetch API request with abort signal
fetch(actionurl, {
method: "POST",
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: list,
signal: controller.signal
})
.then(response => {
clearTimeout(timeoutId);
return response.text(); // Ensure that you return the result of response.text()
})
.then(data => {
if (data !== '') {
let src = clickedImg.getAttribute("src");
if (src.includes("-enabled")) {
src = src.replace("-enabled", "-n");
} else if (src.includes("-n")) {
src = src.replace("-n", "-enabled");
}
clickedImg.setAttribute("src", src);
}
);


return true; // Return a value to satisfy the ESLint rule
})
.catch((err) => {
throw err;
});
});
}
};
});
});
}
};
96 changes: 50 additions & 46 deletions amd/src/coursegroup.js
Original file line number Diff line number Diff line change
@@ -1,47 +1,51 @@
define(['jquery'], function($) {

return {
init: function(options) {
var coursefield = options.coursefield;
var groupfield = options.groupfield;
var actionurl = options.acturl; // Points to loadgroups.php.

// Read groupid from second select and enter in input field.
$("#id_"+groupfield).on( "change", function () {
$("#id_"+groupfield + 'id').val($( "#id_"+groupfield+" option:selected" ).val());
});

// Read courseid and call ajax at change to receive all groups in course.
$("#id_"+coursefield).on( "change", function () {
var group = $( "#id_"+groupfield ); // Get group select.
var courseid = $( "#id_"+coursefield+" option:selected" ).val(); // Get the courseid.
group.find('option').remove().end(); // Remove current options.

// Load groups from course.
if (courseid != 0) {
// Ajax request to get current options.
$.ajax(
{
method: "POST",
url: actionurl,
data: 'courseid=' + courseid,
context: this,
dataType: "text",
success: function(data) {
if (data != '') {
// Add Group to options, value is groupid.
$.each(data.split(','), function(key, value) {
group.append($("<option></option>").attr("value",value.split(" ",1)).text(value));
});
}
},
error: function() {
alert("Error");
}
}
);
}
}); // End on change _course.
export default {
init(options) {
const {coursefield, groupfield, acturl: actionurl} = options;
// Update input field with the selected group id
document.getElementById(`id_${groupfield}`).addEventListener('change', function() {
const selectedValue = document.querySelector(`#id_${groupfield} option:checked`).value;
document.getElementById(`id_${groupfield}id`).value = selectedValue;
});
// When the course is changed, fetch groups using AJAX
document.getElementById(`id_${coursefield}`).addEventListener('change', function() {
const groupSelect = document.getElementById(`id_${groupfield}`);
const selectedCourseId = document.querySelector(`#id_${coursefield} option:checked`).value;
// Remove current options
groupSelect.innerHTML = '';
// Load groups for selected course
if (selectedCourseId !== '0') {
// Fetch groups via fetch API
return fetch(actionurl, {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: `courseid=${selectedCourseId}`
})
.then(response => {
// Return the response text to the next .then()
return response.text();
})
.then(data => {
if (data) {
// Populate group options
data.split(',').forEach(group => {
const value = group.split(' ', 1)[0];
const option = document.createElement('option');
option.value = value;
option.textContent = group;
groupSelect.appendChild(option);
});
}
// Return null if there's nothing further to do
return null;
})
.catch(() => {
throw new Error('Group loading failed');
});
} else {
return Promise.resolve(); // Return a resolved promise if no action is needed
}
};
});
});
}
};
Loading

0 comments on commit 82e2a2b

Please sign in to comment.