]> BookStack Code Mirror - bookstack/blob - resources/assets/js/vues/tag-manager.js
177af681fad09fb73cd306239133f972e9dbf9ef
[bookstack] / resources / assets / js / vues / tag-manager.js
1 const draggable = require('vuedraggable');
2 const autosuggest = require('./components/autosuggest');
3
4 let data = {
5     entityId: false,
6     entityType: null,
7     tags: [],
8 };
9
10 const components = {draggable, autosuggest};
11 const directives = {};
12
13 let methods = {
14
15     addEmptyTag() {
16         this.tags.push({name: '', value: '', key: Math.random().toString(36).substring(7)});
17     },
18
19     /**
20      * When an tag changes check if another empty editable field needs to be added onto the end.
21      * @param tag
22      */
23     tagChange(tag) {
24         let tagPos = this.tags.indexOf(tag);
25         if (tagPos === this.tags.length-1 && (tag.name !== '' || tag.value !== '')) this.addEmptyTag();
26     },
27
28     /**
29      * When an tag field loses focus check the tag to see if its
30      * empty and therefore could be removed from the list.
31      * @param tag
32      */
33     tagBlur(tag) {
34         let isLast = (this.tags.indexOf(tag) === this.tags.length-1);
35         if (tag.name !== '' || tag.value !== '' || isLast) return;
36         let cPos = this.tags.indexOf(tag);
37         this.tags.splice(cPos, 1);
38     },
39
40     removeTag(tag) {
41         let tagPos = this.tags.indexOf(tag);
42         if (tagPos === -1) return;
43         this.tags.splice(tagPos, 1);
44     },
45
46     getTagFieldName(index, key) {
47         return `tags[${index}][${key}]`;
48     },
49 };
50
51 function mounted() {
52     this.entityId = Number(this.$el.getAttribute('entity-id'));
53     this.entityType = this.$el.getAttribute('entity-type');
54
55     let url = window.baseUrl(`/ajax/tags/get/${this.entityType}/${this.entityId}`);
56     this.$http.get(url).then(response => {
57         let tags = response.data;
58         for (let i = 0, len = tags.length; i < len; i++) {
59             tags[i].key = Math.random().toString(36).substring(7);
60         }
61         this.tags = tags;
62         this.addEmptyTag();
63     });
64 }
65
66 module.exports = {
67     data, methods, mounted, components, directives
68 };