File: D:/HostingSpaces/SBogers10/shop.komma.nl/resources/js/store/modules/modules/translation.js
import { G11nService } from '../../../../../vendor/komma/kms/resources/js/global/g11nService';
import Vue from 'vue';
const g11nService = new G11nService();
export default {
namespaced: true,
state: {
placeholderType: 'dots',
translations: { },
translationRequests: []
},
mutations: {
storeTranslation(state, {key, translation}) {
// state.translations[key] = translation; //This is wrong. The property won't be reactive
Vue.set(state.translations, key, translation); //This makes the property reactive
const requestKeyIndex = state.translationRequests.indexOf(key);
if(requestKeyIndex !== -1) state.translationRequests.splice(requestKeyIndex, 1);
},
requestedTranslation(state, key) {
if(state.translationRequests.indexOf(key) !== -1) return; //Already loading
state.translationRequests.push(key);
}
},
actions: {
loadTranslations({ commit, state, dispatch }, translationRequestObjects) {
if(!Array.isArray(translationRequestObjects)) throw 'The translationRequestObjects parameter must be an array containing objects';
translationRequestObjects.forEach((translationRequestObject) => dispatch('loadTranslation', translationRequestObject))
},
loadTranslation({ commit, state }, {key, replace, locale}) {
if(
state.translations.hasOwnProperty(key) || //We are not going to do a request
state.translationRequests.indexOf(key) !== -1
) return;
commit('requestedTranslation', key);
g11nService.translation.get(key, replace, locale).then(
translation => commit('storeTranslation', { key, translation })
).catch(function(error) {
console.error('Vuex translations Module: could not get translation for key: ' + key, error);
})
}
},
getters: {
translation: (state, getters) => (key) => {
//Return a placeholder if the text isn't loaded yet
if(!state.translations.hasOwnProperty(key)) {
if(state.placeholderType === 'key') return key;
else return '.'.repeat(key.length);
}
//Or return the translation if it has loaded.
else {
return state.translations[key];
}
}
}
}