ctucx.git: ctucx.things

simple inventory management web-app

1 
2 
3 
4 
5 
6 
7 
8 
9 
10 
11 
12 
13 
14 
15 
16 
17 
18 
19 
20 
21 
22 
23 
24 
25 
26 
27 
28 
29 
30 
31 
32 
33 
34 
35 
36 
37 
38 
39 
40 
41 
42 
43 
44 
45 
46 
47 
48 
49 
50 
51 
52 
53 
54 
55 
56 
57 
58 
59 
60 
61 
62 
63 
64 
65 
66 
67 
68 
69 
70 
71 
72 
73 
74 
75 
76 
77 
78 
import Vue      from 'vue';
import uniqueId from 'lodash/uniqueId.js';

import store    from '../store.js';

Vue.directive('select-on-focus', {
	inserted(el) {
		el.addEventListener('focus', (evt) => {
			el.select();
		});
	},
});

Vue.directive('focus-on-create', {
	inserted(el, binding) {
		if (binding.expression && binding.value || !binding.expression) {
			el.focus();
		}
	},
});

Vue.directive('focus-on-bus', {
	inserted(el, binding) {
		bus.$on(binding.value, () => {
			el.focus();
		});
	},
});

Vue.directive('select-on-bus', {
	inserted(el, binding) {
		bus.$on(binding.value, () => {
			el.select();
		});
	},
});

Vue.directive('empty-if-zero', {
	inserted(el) {
		el.addEventListener('focus', (evt) => {
			if (el.value === '0' || el.value === '0.00') {
				el.dataset.originalValue = el.value;
				el.value = '';
			}
		});

		el.addEventListener('blur', (evt) => {
			if (el.value === '') {
				el.value = el.dataset.originalValue || '0';
			}
		});
	},
});

Vue.directive('click-outside', {
	inserted(el, binding) {
		const handler = (evt) => {
			if (el.contains(evt.target)) {
				return;
			}
			if (binding && typeof binding.value === 'function') {
				binding.value();
			}
		};

		window.addEventListener('click', handler);

		// Store handler to clean up later
		el.dataset.clickoutside = uniqueId();
		store.commit('addDirectiveInstance', { key: el.dataset.clickoutside, value: handler });
	},
	unbind(el) {
		// clean up event handlers
		const handler = store.state.directiveInstances[el.dataset.clickoutside];
		store.commit('removeDirectiveInstance', el.dataset.clickoutside);
		window.removeEventListener('click', handler);
	},
});