jquery.galleryManager.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. (function ($) {
  2. 'use strict';
  3. var galleryDefaults = {
  4. csrfToken: $('meta[name=csrf-token]').attr('content'),
  5. csrfTokenName: $('meta[name=csrf-param]').attr('content'),
  6. nameLabel: 'Name',
  7. descriptionLabel: 'Description',
  8. hasName: true,
  9. hasDesc: true,
  10. uploadUrl: '',
  11. deleteUrl: '',
  12. updateUrl: '',
  13. arrangeUrl: '',
  14. photos: []
  15. };
  16. function galleryManager(el, options) {
  17. //Extending options:
  18. var opts = $.extend({}, galleryDefaults, options);
  19. //code
  20. var csrfParams = opts.csrfToken ? '&' + opts.csrfTokenName + '=' + opts.csrfToken : '';
  21. var photos = {}; // photo elements by id
  22. var $gallery = $(el);
  23. if (!opts.hasName) {
  24. if (!opts.hasDesc) {
  25. $gallery.addClass('no-name-no-desc');
  26. $('.edit_selected', $gallery).hide();
  27. }
  28. else $gallery.addClass('no-name');
  29. } else if (!opts.hasDesc)
  30. $gallery.addClass('no-desc');
  31. var $sorter = $('.sorter', $gallery);
  32. var $images = $('.images', $sorter);
  33. var $editorModal = $('.editor-modal', $gallery);
  34. var $progressOverlay = $('.progress-overlay', $gallery);
  35. var $uploadProgress = $('.upload-progress', $progressOverlay);
  36. var $editorForm = $('.form', $editorModal);
  37. function htmlEscape(str) {
  38. return String(str)
  39. .replace(/&/g, '&')
  40. .replace(/"/g, '"')
  41. .replace(/'/g, ''')
  42. .replace(/</g, '&lt;')
  43. .replace(/>/g, '&gt;');
  44. }
  45. function createEditorElement(id, src, name, description) {
  46. var html = '<div class="photo-editor row">';
  47. if( typeof src === 'string' || src instanceof String ){
  48. html += '<div class="col-xs-4">' +
  49. '<img src="' + htmlEscape(src) + '" style="max-width:100%;">' +
  50. '</div>';
  51. }
  52. html += '<div class="col-xs-8">' +
  53. (opts.hasName
  54. ?
  55. '<div class="form-group">' +
  56. '<label class="control-label" for="photo_name_' + id + '">' + opts.nameLabel + ':</label>' +
  57. '<input class="form-control" type="text" name="photo[' + id + '][name]" class="input-xlarge" value="' + htmlEscape(name) + '" id="photo_name_' + id + '"/>' +
  58. '</div>' : '') +
  59. (opts.hasDesc
  60. ?
  61. '<div class="form-group">' +
  62. '<label class="control-label" for="photo_description_' + id + '">' + opts.descriptionLabel + ':</label>' +
  63. '<textarea class="form-control" name="photo[' + id + '][description]" rows="3" cols="40" class="input-xlarge" id="photo_description_' + id + '">' + htmlEscape(description) + '</textarea>' +
  64. '</div>' : '') +
  65. '</div>' +
  66. '</div>';
  67. return $(html);
  68. }
  69. var photoTemplate = '<div class="photo">' + '<div class="image-preview"><img src=""/></div><div class="caption">';
  70. if (opts.hasName) {
  71. photoTemplate += '<h5></h5>';
  72. }
  73. if (opts.hasDesc) {
  74. photoTemplate += '<p></p>';
  75. }
  76. photoTemplate += '</div><div class="actions">';
  77. if (opts.hasName || opts.hasDesc) {
  78. photoTemplate += '<span class="editPhoto btn btn-primary btn-xs"><i class="fas fa-edit"></i></span> ';
  79. }
  80. photoTemplate += '<span class="deletePhoto btn btn-danger btn-xs"><i class="fas fa-trash"></i></span>' +
  81. '</div><input type="checkbox" class="photo-select"/></div>';
  82. function addPhoto(id, src, name, description, rank) {
  83. var photo = $(photoTemplate);
  84. photos[id] = photo;
  85. photo.data('id', id);
  86. photo.data('rank', rank);
  87. if( typeof src === 'string' || src instanceof String ){
  88. $('img', photo).attr('src', src);
  89. }else{
  90. $('.image-preview', photo).css('display', 'none');
  91. $('.caption p', photo).css('height', '9em');
  92. }
  93. if (opts.hasName){
  94. // name = '';
  95. $('.caption h5', photo).text(name);
  96. }
  97. if (opts.hasDesc){
  98. $('.caption p', photo).text(description);
  99. }
  100. $images.append(photo);
  101. return photo;
  102. }
  103. function editPhotos(ids) {
  104. var l = ids.length;
  105. var form = $editorForm.empty();
  106. for (var i = 0; i < l; i++) {
  107. var id = ids[i];
  108. var photo = photos[id],
  109. src = $('img', photo).attr('src'),
  110. name = $('.caption h5', photo).text(),
  111. description = $('.caption p', photo).text();
  112. form.append(createEditorElement(id, src, name, description));
  113. }
  114. if (l > 0){
  115. $editorModal.modal('show');
  116. }
  117. }
  118. function removePhotos(ids) {
  119. $.ajax({
  120. type: 'POST',
  121. url: opts.deleteUrl,
  122. data: 'id[]=' + ids.join('&id[]=') + csrfParams,
  123. success: function (t) {
  124. if (t == 'OK') {
  125. for (var i = 0, l = ids.length; i < l; i++) {
  126. photos[ids[i]].remove();
  127. delete photos[ids[i]];
  128. }
  129. } else {
  130. alert(t);
  131. }
  132. }
  133. });
  134. }
  135. function deleteClick(e) {
  136. e.preventDefault();
  137. var photo = $(this).closest('.photo');
  138. var id = photo.data('id');
  139. // here can be question to confirm delete
  140. // if (!confirm(deleteConfirmation)) return false;
  141. removePhotos([id]);
  142. return false;
  143. }
  144. function editClick(e) {
  145. e.preventDefault();
  146. var photo = $(this).closest('.photo');
  147. var id = photo.data('id');
  148. editPhotos([id]);
  149. return false;
  150. }
  151. function updateButtons() {
  152. var selectedCount = $('.photo.selected', $sorter).length;
  153. $('.select_all', $gallery).prop('checked', $('.photo', $sorter).length == selectedCount);
  154. if (selectedCount == 0) {
  155. $('.edit_selected, .remove_selected', $gallery).addClass('disabled');
  156. } else {
  157. $('.edit_selected, .remove_selected', $gallery).removeClass('disabled');
  158. }
  159. }
  160. function selectChanged() {
  161. var $this = $(this);
  162. if ($this.is(':checked'))
  163. $this.closest('.photo').addClass('selected');
  164. else
  165. $this.closest('.photo').removeClass('selected');
  166. updateButtons();
  167. }
  168. function sending(xhr, fd, fixer){
  169. console.log(fixer);
  170. if( fixer.CurUploaded <= fixer.MaxUploaded ){
  171. xhr.send(fd);
  172. fixer.CurUploaded++;
  173. }else{
  174. setTimeout( sending,5000, xhr, fd, fixer);
  175. }
  176. }
  177. $images
  178. .on('click', '.photo .deletePhoto', deleteClick)
  179. .on('click', '.photo .editPhoto', editClick)
  180. .on('click', '.photo .photo-select', selectChanged);
  181. $('.images', $sorter).sortable({tolerance: "pointer"}).disableSelection().bind("sortstop", function () {
  182. var data = [];
  183. $('.photo', $sorter).each(function () {
  184. var t = $(this);
  185. data.push('order[' + t.data('id') + ']=' + t.data('rank'));
  186. });
  187. $.ajax({
  188. type: 'POST',
  189. url: opts.arrangeUrl,
  190. data: data.join('&') + csrfParams,
  191. dataType: "json"
  192. }).done(function (data) {
  193. for (var id in data[id]) {
  194. photos[id].data('rank', data[id]);
  195. }
  196. // order saved!
  197. // we can inform user that order saved
  198. });
  199. });
  200. if (window.FormData !== undefined) { // if XHR2 available
  201. var uploadFileName = $('.afile', $gallery).attr('name');
  202. var multiUpload = function (files) {
  203. if (files.length == 0) return;
  204. $progressOverlay.show();
  205. $uploadProgress.css('width', '5%');
  206. var filesCount = files.length;
  207. var uploadedCount = 0;
  208. var ids = [];
  209. var poper = new Map();
  210. var fixer = {MaxUploaded:3, CurUploaded:0, MaxScreen:12};
  211. for (var i = 0; i < filesCount; i++) {
  212. var fd = new FormData();
  213. fd.append(uploadFileName, files[i]);
  214. if (opts.csrfToken) {
  215. fd.append(opts.csrfTokenName, opts.csrfToken);
  216. }
  217. let xhr = new XMLHttpRequest();
  218. xhr.open('POST', opts.uploadUrl, true);
  219. xhr.onload = function () {
  220. uploadedCount++;
  221. fixer.CurUploaded--;
  222. if (this.status == 200) {
  223. var resp = JSON.parse(this.response);
  224. addPhoto(resp['id'], resp['preview'], '', resp['description'], resp['rank']);
  225. ids.push(resp['id']);
  226. var poperm = poper.get(resp['name']);
  227. poperm.toast('hide');
  228. setTimeout(() => {
  229. poperm.remove();
  230. },2000, poperm);
  231. } else {
  232. // exception !!!
  233. }
  234. $uploadProgress.css('width', '' + (5 + 95 * uploadedCount / filesCount) + '%');
  235. if (uploadedCount === filesCount) {
  236. $uploadProgress.css('width', '100%');
  237. $progressOverlay.hide();
  238. if (opts.hasName || opts.hasDesc) editPhotos(ids);
  239. }
  240. };
  241. var templ = $("#noty0").clone();
  242. var fname = files[i].name;
  243. xhr.nn = fname;
  244. $(xhr.upload).bind('progress', function (e) {
  245. // xhr.upload.addEventListener("progress", (event) => {
  246. let percent = Math.round(event.loaded *100/ event.total);
  247. // console.log(xhr.nn);
  248. // console.log(xhr);
  249. // console.log(percent);
  250. var el = poper.get(xhr.nn);
  251. el.find(".progress-bar").css("width", percent+"%");
  252. if( percent > 98 ){
  253. el.find(".text-muted").text("Обработка");
  254. }
  255. });
  256. templ.find(".toast-body").text(files[i].name);
  257. $("#notycont").prepend(templ);
  258. templ.toast('show');
  259. poper.set(files[i].name, templ);
  260. console.log(fixer);
  261. if( fixer.CurUploaded >= fixer.MaxUploaded ){
  262. console.log("pause");
  263. setTimeout( sending,5000, xhr, fd, fixer);
  264. }else{
  265. fixer.CurUploaded ++;
  266. xhr.send(fd);
  267. }
  268. }
  269. };
  270. (function () { // add drag and drop
  271. var el = $gallery[0];
  272. var isOver = false;
  273. var lastIsOver = false;
  274. setInterval(function () {
  275. if (isOver != lastIsOver) {
  276. if (isOver) el.classList.add('over');
  277. else el.classList.remove('over');
  278. lastIsOver = isOver
  279. }
  280. }, 30);
  281. function handleDragOver(e) {
  282. e.preventDefault();
  283. isOver = true;
  284. return false;
  285. }
  286. function handleDragLeave() {
  287. isOver = false;
  288. return false;
  289. }
  290. function handleDrop(e) {
  291. e.preventDefault();
  292. e.stopPropagation();
  293. var files = e.dataTransfer.files;
  294. multiUpload(files);
  295. isOver = false;
  296. return false;
  297. }
  298. function handleDragEnd() {
  299. isOver = false;
  300. }
  301. el.addEventListener('dragover', handleDragOver, false);
  302. el.addEventListener('dragleave', handleDragLeave, false);
  303. el.addEventListener('drop', handleDrop, false);
  304. el.addEventListener('dragend', handleDragEnd, false);
  305. })();
  306. $('.afile', $gallery).attr('multiple', 'true').on('change', function (e) {
  307. e.preventDefault();
  308. multiUpload(this.files);
  309. $(this).val(null);
  310. });
  311. } else {
  312. $('.afile', $gallery).on('change', function (e) {
  313. e.preventDefault();
  314. var ids = [];
  315. $progressOverlay.show();
  316. $uploadProgress.css('width', '5%');
  317. var data = {};
  318. if (opts.csrfToken)
  319. data[opts.csrfTokenName] = opts.csrfToken;
  320. $.ajax({
  321. type: 'POST',
  322. url: opts.uploadUrl,
  323. data: data,
  324. files: $(this),
  325. iframe: true,
  326. processData: false,
  327. dataType: "json"
  328. }).done(function (resp) {
  329. addPhoto(resp['id'], resp['preview'], '', resp['description'], resp['rank']);
  330. ids.push(resp['id']);
  331. $uploadProgress.css('width', '100%');
  332. $progressOverlay.hide();
  333. if (opts.hasName || opts.hasDesc) editPhotos(ids);
  334. });
  335. });
  336. }
  337. $('.save-changes', $editorModal).click(function (e) {
  338. e.preventDefault();
  339. $.post(opts.updateUrl, $('input, textarea', $editorForm).serialize() + csrfParams, function (data) {
  340. var count = data.length;
  341. for (var key = 0; key < count; key++) {
  342. var p = data[key];
  343. var photo = photos[p.id];
  344. $('img', photo).attr('src', p['src']);
  345. if (opts.hasName)
  346. $('.caption h5', photo).text(p['name']);
  347. if (opts.hasDesc)
  348. $('.caption p', photo).text(p['description']);
  349. }
  350. $editorModal.modal('hide');
  351. //deselect all items after editing
  352. $('.photo.selected', $sorter).each(function () {
  353. $('.photo-select', this).prop('checked', false)
  354. }).removeClass('selected');
  355. $('.select_all', $gallery).prop('checked', false);
  356. updateButtons();
  357. }, 'json');
  358. });
  359. $('.edit_selected', $gallery).click(function (e) {
  360. e.preventDefault();
  361. var ids = [];
  362. $('.photo.selected', $sorter).each(function () {
  363. ids.push($(this).data('id'));
  364. });
  365. editPhotos(ids);
  366. return false;
  367. });
  368. $('.remove_selected', $gallery).click(function (e) {
  369. e.preventDefault();
  370. var ids = [];
  371. $('.photo.selected', $sorter).each(function () {
  372. ids.push($(this).data('id'));
  373. });
  374. removePhotos(ids);
  375. });
  376. $('.select_all', $gallery).change(function () {
  377. if ($(this).prop('checked')) {
  378. $('.photo', $sorter).each(function () {
  379. $('.photo-select', this).prop('checked', true)
  380. }).addClass('selected');
  381. } else {
  382. $('.photo.selected', $sorter).each(function () {
  383. $('.photo-select', this).prop('checked', false)
  384. }).removeClass('selected');
  385. }
  386. updateButtons();
  387. });
  388. for (var i = 0, l = opts.photos.length; i < l; i++) {
  389. var resp = opts.photos[i];
  390. addPhoto(resp['id'], resp['preview'], resp['name'], resp['description'], resp['rank']);
  391. }
  392. let selfo = addPhoto;
  393. $('.savehtml', $gallery).click(function (e) {
  394. slSave($(e.target).attr('rel-mid'),$(e.target).attr('rel-id'), selfo);
  395. ids,push($(e.target).attr('rel-id'));
  396. });
  397. }
  398. // The actual plugin
  399. $.fn.galleryManager = function (options) {
  400. if (this.length) {
  401. this.each(function () {
  402. galleryManager(this, options);
  403. });
  404. }
  405. };
  406. })(jQuery);