media.js 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. import $ from 'jquery';
  2. import request from '../../utils/request';
  3. import FilesField, { UriToMarkdown } from '../../forms/fields/files';
  4. import { config, translations } from 'grav-config';
  5. import { Instance as Editor } from '../../forms/fields/editor';
  6. import Sortable from 'sortablejs';
  7. const previewTemplate = `
  8. <div class="dz-preview dz-file-preview">
  9. <div class="dz-details">
  10. <div class="dz-filename"><span data-dz-name></span></div>
  11. <div class="dz-size" data-dz-size></div>
  12. <img data-dz-thumbnail />
  13. </div>
  14. <div class="dz-progress"><span class="dz-upload" data-dz-uploadprogress></span></div>
  15. <div class="dz-success-mark"><span>✔</span></div>
  16. <div class="dz-error-mark"><span>✘</span></div>
  17. <div class="dz-error-message"><span data-dz-errormessage></span></div>
  18. <a class="dz-remove" title="${translations.PLUGIN_ADMIN.DELETE}" href="javascript:undefined;" data-dz-remove>${translations.PLUGIN_ADMIN.DELETE}</a>
  19. <a class="dz-metadata" title="${translations.PLUGIN_ADMIN.METADATA}" href="#" target="_blank" data-dz-metadata>${translations.PLUGIN_ADMIN.METADATA}</a>
  20. <a class="dz-view" title="${translations.PLUGIN_ADMIN.VIEW}" href="#" target="_blank" data-dz-view>${translations.PLUGIN_ADMIN.VIEW}</a>
  21. <a class="dz-insert" title="${translations.PLUGIN_ADMIN.INSERT}" href="javascript:undefined;" data-dz-insert>${translations.PLUGIN_ADMIN.INSERT}</a>
  22. </div>`.trim();
  23. export default class PageMedia extends FilesField {
  24. constructor({ container = '#grav-dropzone', options = {} } = {}) {
  25. options = Object.assign(options, { previewTemplate });
  26. super({ container, options });
  27. if (!this.container.length) { return; }
  28. this.urls = {
  29. fetch: `${this.container.data('media-url')}/task${config.param_sep}listmedia`,
  30. add: `${this.container.data('media-url')}/task${config.param_sep}addmedia`,
  31. delete: `${this.container.data('media-url')}/task${config.param_sep}delmedia`
  32. };
  33. this.dropzone.options.url = this.urls.add;
  34. if (typeof this.options.fetchMedia === 'undefined' || this.options.fetchMedia) {
  35. this.fetchMedia();
  36. }
  37. if (typeof this.options.attachDragDrop === 'undefined' || this.options.attachDragDrop) {
  38. this.attachDragDrop();
  39. }
  40. const field = $(`[name="${this.container.data('dropzone-field')}"]`);
  41. if (field.length) {
  42. this.sortable = new Sortable(this.container.get(0), {
  43. animation: 150,
  44. // forceFallback: true,
  45. setData: (dataTransfer, target) => {
  46. target = $(target);
  47. let uri = encodeURI(target.find('.dz-filename').text());
  48. let shortcode = UriToMarkdown(uri);
  49. this.dropzone.disable();
  50. target.addClass('hide-backface');
  51. dataTransfer.effectAllowed = 'copy';
  52. dataTransfer.setData('text', shortcode);
  53. },
  54. onSort: () => {
  55. let names = [];
  56. this.container.find('[data-dz-name]').each((index, file) => {
  57. file = $(file);
  58. const name = file.text().trim();
  59. names.push(name);
  60. });
  61. field.val(names.join(','));
  62. }
  63. });
  64. }
  65. }
  66. fetchMedia() {
  67. const body = { uri: this.getURI() };
  68. let url = this.urls.fetch;
  69. request(url, { method: 'post', body }, (response) => {
  70. let results = response.results;
  71. Object.keys(results).forEach((name) => {
  72. let data = results[name];
  73. let mock = { name, size: data.size, accepted: true, extras: data };
  74. this.dropzone.files.push(mock);
  75. this.dropzone.options.addedfile.call(this.dropzone, mock);
  76. this.dropzone.options.thumbnail.call(this.dropzone, mock, data.url);
  77. });
  78. this.container.find('.dz-preview').prop('draggable', 'true');
  79. });
  80. }
  81. onDropzoneSending(file, xhr, formData) {
  82. /*
  83. // Cannot call super because Safari and IE API don't implement `delete`
  84. super.onDropzoneSending(file, xhr, formData);
  85. formData.delete('task');
  86. */
  87. formData.append('name', this.options.dotNotation);
  88. formData.append('admin-nonce', config.admin_nonce);
  89. formData.append('uri', this.getURI());
  90. }
  91. onDropzoneComplete(file) {
  92. super.onDropzoneComplete(file);
  93. this.sortable.options.onSort();
  94. // accepted
  95. $('.dz-preview').prop('draggable', 'true');
  96. }
  97. onDropzoneRemovedFile(file, ...extra) {
  98. super.onDropzoneRemovedFile(file, ...extra);
  99. this.sortable.options.onSort();
  100. }
  101. attachDragDrop() {
  102. this.container.delegate('[data-dz-insert]', 'click', (e) => {
  103. let target = $(e.currentTarget).parent('.dz-preview').find('.dz-filename');
  104. let editor = Editor.editors.filter((index, editor) => $(editor).attr('name') === 'data[content]');
  105. if (editor.length) {
  106. editor = editor.data('codemirror');
  107. editor.focus();
  108. let filename = encodeURI(target.text());
  109. let shortcode = UriToMarkdown(filename);
  110. editor.doc.replaceSelection(shortcode);
  111. }
  112. });
  113. this.container.delegate('[data-dz-view]', 'mouseenter', (e) => {
  114. let target = $(e.currentTarget);
  115. let file = target.parent('.dz-preview').find('.dz-filename');
  116. let filename = encodeURI(file.text());
  117. let URL = target.closest('[data-media-path]').data('media-path');
  118. let original = this.dropzone.files.filter((file) => encodeURIComponent(file.name) === filename).shift().extras.original;
  119. target.attr('href', `${URL}/${original}`);
  120. });
  121. this.container.delegate('[data-dz-metadata]', 'click', (e) => {
  122. e.preventDefault();
  123. const target = $(e.currentTarget);
  124. const file = target.parent('.dz-preview').find('.dz-filename');
  125. const filename = encodeURI(file.text());
  126. let fileObj = this.dropzone.files.filter((file) => file.name === global.decodeURI(filename)).shift() || {};
  127. if (!fileObj.extras) {
  128. fileObj.extras = { metadata: [] };
  129. }
  130. if (Array.isArray(fileObj.extras.metadata) && !fileObj.extras.metadata.length) {
  131. fileObj.extras.metadata = { '': `${global.decodeURI(filename)}.meta.yaml doesn't exist` };
  132. }
  133. fileObj = fileObj.extras;
  134. const modal_element = $('body').find('[data-remodal-id="metadata"]');
  135. const modal = $.remodal.lookup[modal_element.data('remodal')];
  136. modal_element.find('h1 strong').html(filename);
  137. if (fileObj.url) {
  138. modal_element.find('.meta-preview').html(`<img src="${fileObj.url}" />`);
  139. }
  140. const container = modal_element.find('.meta-content').html('<ul />').find('ul');
  141. Object.keys(fileObj.metadata).forEach((meta) => {
  142. container.append(`<li><strong>${meta ? meta + ':' : ''}</strong> ${fileObj.metadata[meta]}</li>`);
  143. });
  144. modal.open();
  145. });
  146. this.container.delegate('.dz-preview', 'dragstart', (e) => {
  147. let target = $(e.currentTarget);
  148. let uri = encodeURI(target.find('.dz-filename').text());
  149. let shortcode = UriToMarkdown(uri);
  150. this.dropzone.disable();
  151. target.addClass('hide-backface');
  152. e.originalEvent.dataTransfer.effectAllowed = 'copy';
  153. e.originalEvent.dataTransfer.setData('text', shortcode);
  154. });
  155. this.container.delegate('.dz-preview', 'dragend', (e) => {
  156. let target = $(e.currentTarget);
  157. this.dropzone.enable();
  158. target.removeClass('hide-backface');
  159. });
  160. }
  161. }
  162. export let Instance = new PageMedia();