tagsplugin.js 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. /*
  2. * Copyright (c) 2014 Vincent Petry <pvince81@owncloud.com>
  3. *
  4. * This file is licensed under the Affero General Public License version 3
  5. * or later.
  6. *
  7. * See the COPYING-README file.
  8. *
  9. */
  10. /* global Handlebars */
  11. (function (OCA) {
  12. _.extend(OC.Files.Client, {
  13. PROPERTY_TAGS: '{' + OC.Files.Client.NS_OWNCLOUD + '}tags',
  14. PROPERTY_FAVORITE: '{' + OC.Files.Client.NS_OWNCLOUD + '}favorite'
  15. });
  16. /**
  17. * Returns the icon class for the matching state
  18. *
  19. * @param {boolean} state true if starred, false otherwise
  20. * @return {string} icon class for star image
  21. */
  22. function getStarIconClass (state) {
  23. return state ? 'icon-starred' : 'icon-star';
  24. }
  25. /**
  26. * Render the star icon with the given state
  27. *
  28. * @param {boolean} state true if starred, false otherwise
  29. * @return {Object} jQuery object
  30. */
  31. function renderStar (state) {
  32. return OCA.Files.Templates['favorite_mark']({
  33. isFavorite: state,
  34. altText: state ? t('files', 'Favorited') : t('files', 'Not favorited'),
  35. iconClass: getStarIconClass(state)
  36. });
  37. }
  38. /**
  39. * Toggle star icon on favorite mark element
  40. *
  41. * @param {Object} $favoriteMarkEl favorite mark element
  42. * @param {boolean} state true if starred, false otherwise
  43. */
  44. function toggleStar ($favoriteMarkEl, state) {
  45. $favoriteMarkEl.removeClass('icon-star icon-starred').addClass(getStarIconClass(state));
  46. $favoriteMarkEl.toggleClass('permanent', state);
  47. }
  48. /**
  49. * Remove Item from Quickaccesslist
  50. *
  51. * @param {String} appfolder folder to be removed
  52. */
  53. function removeFavoriteFromList (appfolder) {
  54. var quickAccessList = 'sublist-favorites';
  55. var listULElements = document.getElementById(quickAccessList);
  56. if (!listULElements) {
  57. return;
  58. }
  59. var apppath=appfolder;
  60. if(appfolder.startsWith("//")){
  61. apppath=appfolder.substring(1, appfolder.length);
  62. }
  63. $(listULElements).find('[data-dir="' + apppath + '"]').remove();
  64. if (listULElements.childElementCount === 0) {
  65. var collapsibleButton = $(listULElements).parent().find('button.collapse');
  66. collapsibleButton.hide();
  67. $("#button-collapse-parent-favorites").removeClass('collapsible');
  68. }
  69. }
  70. /**
  71. * Add Item to Quickaccesslist
  72. *
  73. * @param {String} appfolder folder to be added
  74. */
  75. function addFavoriteToList (appfolder) {
  76. var quickAccessList = 'sublist-favorites';
  77. var listULElements = document.getElementById(quickAccessList);
  78. if (!listULElements) {
  79. return;
  80. }
  81. var listLIElements = listULElements.getElementsByTagName('li');
  82. var appName = appfolder.substring(appfolder.lastIndexOf("/") + 1, appfolder.length);
  83. var apppath = appfolder;
  84. if(appfolder.startsWith("//")){
  85. apppath = appfolder.substring(1, appfolder.length);
  86. }
  87. var url = OC.generateUrl('/apps/files/?dir=' + apppath + '&view=files');
  88. var innerTagA = document.createElement('A');
  89. innerTagA.setAttribute("href", url);
  90. innerTagA.setAttribute("class", "nav-icon-files svg");
  91. innerTagA.innerHTML = _.escape(appName);
  92. var length = listLIElements.length + 1;
  93. var innerTagLI = document.createElement('li');
  94. innerTagLI.setAttribute("data-id", apppath.replace('/', '-'));
  95. innerTagLI.setAttribute("data-dir", apppath);
  96. innerTagLI.setAttribute("data-view", 'files');
  97. innerTagLI.setAttribute("class", "nav-" + appName);
  98. innerTagLI.setAttribute("folderpos", length.toString());
  99. innerTagLI.appendChild(innerTagA);
  100. $.get(OC.generateUrl("/apps/files/api/v1/quickaccess/get/NodeType"),{folderpath: apppath}, function (data, status) {
  101. if (data === "dir") {
  102. if (listULElements.childElementCount <= 0) {
  103. listULElements.appendChild(innerTagLI);
  104. var collapsibleButton = $(listULElements).parent().find('button.collapse');
  105. collapsibleButton.show();
  106. $(listULElements).parent().addClass('collapsible');
  107. } else {
  108. listLIElements[listLIElements.length - 1].after(innerTagLI);
  109. }
  110. }
  111. }
  112. );
  113. }
  114. OCA.Files = OCA.Files || {};
  115. /**
  116. * Extends the file actions and file list to include a favorite mark icon
  117. * and a favorite action in the file actions menu; it also adds "data-tags"
  118. * and "data-favorite" attributes to file elements.
  119. *
  120. * @namespace OCA.Files.TagsPlugin
  121. */
  122. OCA.Files.TagsPlugin = {
  123. name: 'Tags',
  124. allowedLists: [
  125. 'files',
  126. 'favorites',
  127. 'systemtags',
  128. 'shares.self',
  129. 'shares.others',
  130. 'shares.link'
  131. ],
  132. _extendFileActions: function (fileActions) {
  133. var self = this;
  134. fileActions.registerAction({
  135. name: 'Favorite',
  136. displayName: function (context) {
  137. var $file = context.$file;
  138. var isFavorite = $file.data('favorite') === true;
  139. if (isFavorite) {
  140. return t('files', 'Remove from favorites');
  141. }
  142. // As it is currently not possible to provide a context for
  143. // the i18n strings "Add to favorites" was used instead of
  144. // "Favorite" to remove the ambiguity between verb and noun
  145. // when it is translated.
  146. return t('files', 'Add to favorites');
  147. },
  148. mime: 'all',
  149. order: -100,
  150. permissions: OC.PERMISSION_NONE,
  151. iconClass: function (fileName, context) {
  152. var $file = context.$file;
  153. var isFavorite = $file.data('favorite') === true;
  154. if (isFavorite) {
  155. return 'icon-star-dark';
  156. }
  157. return 'icon-starred';
  158. },
  159. actionHandler: function (fileName, context) {
  160. var $favoriteMarkEl = context.$file.find('.favorite-mark');
  161. var $file = context.$file;
  162. var fileInfo = context.fileList.files[$file.index()];
  163. var dir = context.dir || context.fileList.getCurrentDirectory();
  164. var tags = $file.attr('data-tags');
  165. if (_.isUndefined(tags)) {
  166. tags = '';
  167. }
  168. tags = tags.split('|');
  169. tags = _.without(tags, '');
  170. var isFavorite = tags.indexOf(OC.TAG_FAVORITE) >= 0;
  171. if (isFavorite) {
  172. // remove tag from list
  173. tags = _.without(tags, OC.TAG_FAVORITE);
  174. removeFavoriteFromList(dir + '/' + fileName);
  175. } else {
  176. tags.push(OC.TAG_FAVORITE);
  177. addFavoriteToList(dir + '/' + fileName);
  178. }
  179. // pre-toggle the star
  180. toggleStar($favoriteMarkEl, !isFavorite);
  181. context.fileInfoModel.trigger('busy', context.fileInfoModel, true);
  182. self.applyFileTags(
  183. dir + '/' + fileName,
  184. tags,
  185. $favoriteMarkEl,
  186. isFavorite
  187. ).then(function (result) {
  188. context.fileInfoModel.trigger('busy', context.fileInfoModel, false);
  189. // response from server should contain updated tags
  190. var newTags = result.tags;
  191. if (_.isUndefined(newTags)) {
  192. newTags = tags;
  193. }
  194. context.fileInfoModel.set({
  195. 'tags': newTags,
  196. 'favorite': !isFavorite
  197. });
  198. });
  199. }
  200. });
  201. },
  202. _extendFileList: function (fileList) {
  203. // extend row prototype
  204. var oldCreateRow = fileList._createRow;
  205. fileList._createRow = function (fileData) {
  206. var $tr = oldCreateRow.apply(this, arguments);
  207. var isFavorite = false;
  208. if (fileData.tags) {
  209. $tr.attr('data-tags', fileData.tags.join('|'));
  210. if (fileData.tags.indexOf(OC.TAG_FAVORITE) >= 0) {
  211. $tr.attr('data-favorite', true);
  212. isFavorite = true;
  213. }
  214. }
  215. var $icon = $(renderStar(isFavorite));
  216. $tr.find('td.filename .thumbnail').append($icon);
  217. return $tr;
  218. };
  219. var oldElementToFile = fileList.elementToFile;
  220. fileList.elementToFile = function ($el) {
  221. var fileInfo = oldElementToFile.apply(this, arguments);
  222. var tags = $el.attr('data-tags');
  223. if (_.isUndefined(tags)) {
  224. tags = '';
  225. }
  226. tags = tags.split('|');
  227. tags = _.without(tags, '');
  228. fileInfo.tags = tags;
  229. return fileInfo;
  230. };
  231. var oldGetWebdavProperties = fileList._getWebdavProperties;
  232. fileList._getWebdavProperties = function () {
  233. var props = oldGetWebdavProperties.apply(this, arguments);
  234. props.push(OC.Files.Client.PROPERTY_TAGS);
  235. props.push(OC.Files.Client.PROPERTY_FAVORITE);
  236. return props;
  237. };
  238. fileList.filesClient.addFileInfoParser(function (response) {
  239. var data = {};
  240. var props = response.propStat[0].properties;
  241. var tags = props[OC.Files.Client.PROPERTY_TAGS];
  242. var favorite = props[OC.Files.Client.PROPERTY_FAVORITE];
  243. if (tags && tags.length) {
  244. tags = _.chain(tags).filter(function (xmlvalue) {
  245. return (xmlvalue.namespaceURI === OC.Files.Client.NS_OWNCLOUD && xmlvalue.nodeName.split(':')[1] === 'tag');
  246. }).map(function (xmlvalue) {
  247. return xmlvalue.textContent || xmlvalue.text;
  248. }).value();
  249. }
  250. if (tags) {
  251. data.tags = tags;
  252. }
  253. if (favorite && parseInt(favorite, 10) !== 0) {
  254. data.tags = data.tags || [];
  255. data.tags.push(OC.TAG_FAVORITE);
  256. }
  257. return data;
  258. });
  259. },
  260. attach: function (fileList) {
  261. if (this.allowedLists.indexOf(fileList.id) < 0) {
  262. return;
  263. }
  264. this._extendFileActions(fileList.fileActions);
  265. this._extendFileList(fileList);
  266. },
  267. /**
  268. * Replaces the given files' tags with the specified ones.
  269. *
  270. * @param {String} fileName path to the file or folder to tag
  271. * @param {Array.<String>} tagNames array of tag names
  272. * @param {Object} $favoriteMarkEl favorite mark element
  273. * @param {boolean} isFavorite Was the item favorited before
  274. */
  275. applyFileTags: function (fileName, tagNames, $favoriteMarkEl, isFavorite) {
  276. var encodedPath = OC.encodePath(fileName);
  277. while (encodedPath[0] === '/') {
  278. encodedPath = encodedPath.substr(1);
  279. }
  280. return $.ajax({
  281. url: OC.generateUrl('/apps/files/api/v1/files/') + encodedPath,
  282. contentType: 'application/json',
  283. data: JSON.stringify({
  284. tags: tagNames || []
  285. }),
  286. dataType: 'json',
  287. type: 'POST'
  288. }).fail(function (response) {
  289. var message = '';
  290. // show message if it is available
  291. if (response.responseJSON && response.responseJSON.message) {
  292. message = ': ' + response.responseJSON.message;
  293. }
  294. OC.Notification.show(t('files', 'An error occurred while trying to update the tags' + message), {type: 'error'});
  295. toggleStar($favoriteMarkEl, isFavorite);
  296. });
  297. }
  298. };
  299. })
  300. (OCA);
  301. OC.Plugins.register('OCA.Files.FileList', OCA.Files.TagsPlugin);