openwebrx/htdocs/lib/settings/ProfileList.js

66 lines
2.7 KiB
JavaScript
Raw Normal View History

2023-05-16 03:25:25 +02:00
$.fn.profileList = function() {
2023-05-18 19:35:09 +02:00
var dataType = 'application/x-profile';
var isValidDrag = function(event) {
// check and avoid external drags
if (!event.originalEvent.dataTransfer.types.includes(dataType)) return false;
var $target = $(event.target).closest('.profile');
// check if we are a valid drop target
return !!$target.length;
}
2023-05-18 21:03:23 +02:00
var moveProfile = function(profileId, index) {
return $.ajax(document.location.href + '/moveprofile', {
data: JSON.stringify({profile_id: profileId, index: index}),
contentType: 'application/json',
method: 'POST'
});
2023-05-18 19:35:09 +02:00
}
2023-05-16 03:25:25 +02:00
this.each(function () {
var $profileList = $(this);
var $profiles = $profileList.find('.profile');
$profiles.attr('draggable', 'true');
$profiles.find('a').attr('draggable', 'false');
var $profileEl;
var originalIndex;
$profileList.on('dragstart', '.profile', function(event){
$profileEl = $(event.originalEvent.target);
originalIndex = $profileEl.index();
event.originalEvent.dataTransfer.effectAllowed = 'move';
2023-05-18 19:35:09 +02:00
event.originalEvent.dataTransfer.setData(dataType, $profileEl.data('profile-id'));
2023-05-16 03:25:25 +02:00
}).on('dragenter', function(event) {
2023-05-18 19:35:09 +02:00
if (!isValidDrag(event)) return;
2023-05-16 03:25:25 +02:00
event.preventDefault();
2023-05-18 19:35:09 +02:00
2023-05-16 03:25:25 +02:00
var $target = $(event.target).closest('.profile');
if ($profileEl.index() < $target.index()) {
$profileEl.insertAfter($target);
} else {
$profileEl.insertBefore($target);
}
}).on('dragover', function(event) {
2023-05-18 19:35:09 +02:00
if (!isValidDrag(event)) return;
2023-05-16 03:25:25 +02:00
event.preventDefault();
2023-05-18 19:35:09 +02:00
}).on('drop', function(event) {
2023-05-18 21:03:23 +02:00
if (!isValidDrag(event)) return;
2023-05-18 19:35:09 +02:00
var $target = $(event.target).closest('.profile');
var index = $profileList.find('.profile').index($target);
2023-05-18 21:03:23 +02:00
moveProfile(event.originalEvent.dataTransfer.getData(dataType), index).done(function() {
// done
}).fail(function() {
// backend reported error, restore original position
$profileEl.remove().insertBefore($profileList.children().eq(originalIndex));
}).always(function() {
$profileEl = undefined;
});
}).on('dragend', '.profile', function(event) {
2023-05-16 03:25:25 +02:00
if (event.originalEvent.dataTransfer.dropEffect === 'none') {
// drag was aborted - restore original position
$profileEl.remove().insertBefore($profileList.children().eq(originalIndex));
}
});
});
}