import { createApp } from 'vue'; import PickEntity from 'ChillMainAssets/vuejs/PickEntity/PickEntity.vue'; import { _createI18n } from 'ChillMainAssets/vuejs/_js/i18n'; import { appMessages } from 'ChillMainAssets/vuejs/PickEntity/i18n'; const i18n = _createI18n(appMessages); let appsOnPage = new Map(); let appsPerInput = new Map(); function loadDynamicPicker(element) { let apps = element.querySelectorAll('[data-module="pick-dynamic"]'); apps.forEach(function(el) { const isMultiple = parseInt(el.dataset.multiple) === 1, uniqId = el.dataset.uniqid, input = element.querySelector('[data-input-uniqid="'+ el.dataset.uniqid +'"]'), picked = isMultiple ? JSON.parse(input.value) : ( (input.value === '[]' || input.value === '') ? null : [ JSON.parse(input.value) ] ) suggested = null !== JSON.parse(el.dataset.suggested) ? JSON.parse(el.dataset.suggested) : null ; console.log('suggested', suggested) if (!isMultiple) { if (input.value === '[]'){ input.value = null; } } const app = createApp({ template: '', components: { PickEntity, }, data() { return { multiple: isMultiple, types: JSON.parse(el.dataset.types), picked: picked === null ? [] : picked, uniqid: el.dataset.uniqid, suggested: suggested } }, methods: { addNewEntity(entity) { if (this.multiple) { if (!this.picked.some(el => { return el.type === entity.type && el.id === entity.id; })) { this.picked.push(entity); input.value = JSON.stringify(this.picked); } } else { if (!this.picked.some(el => { return el.type === entity.type && el.id === entity.id; })) { this.picked.splice(0, this.picked.length); this.picked.push(entity); input.value = JSON.stringify(this.picked[0]); } } }, removeEntity(entity) { this.picked = this.picked.filter(e => !(e.type === entity.type && e.id === entity.id)); input.value = JSON.stringify(this.picked); }, } }) .use(i18n) .mount(el); appsOnPage.set(uniqId, app); appsPerInput.set(input.name, app); }); } document.addEventListener('show-hide-show', function(e) { loadDynamicPicker(e.detail.container) }); document.addEventListener('show-hide-hide', function(e) { console.log('hiding event caught') e.detail.container.querySelectorAll('[data-module="pick-dynamic"]').forEach((el) => { let uniqId = el.dataset.uniqid; if (appsOnPage.has(uniqId)) { appsOnPage.get(uniqId).unmount(); appsOnPage.delete(uniqId); } }) }); document.addEventListener('pick-entity-type-action', function (e) { console.log('pick entity event', e); if (!appsPerInput.has(e.detail.name)) { console.error('no app with this name'); return; } const app = appsPerInput.get(e.detail.name); if (e.detail.action === 'add') { app.addNewEntity(e.detail.entity); } else if (e.detail.action === 'remove') { app.removeEntity(e.detail.entity); } else { console.error('action not supported: '+e.detail.action); } }); document.addEventListener('DOMContentLoaded', function(e) { loadDynamicPicker(document) })