i18next.services.pluralResolver.addRule returns undefined for addRule - i18next

import i18next from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
const locales = ['en-GB', 'pl-PL'];
export const supportedLanguages = locales;
const localeResources = {
'en-GB': {
common: require('./locales/en-GB/common.json'),
},
'pl-PL': {
common: require('./locales/pl-PL/common.json'),
},
};
const frozenLocales = Object.freeze(locales);
export function localesImmutable() {
return frozenLocales;
}
const fallbackLanguages = {
pl: ['pl-PL'],
default: ['en-GB'],
};
i18next.services.pluralResolver.addRule('pl', {
numbers: [1, 2, 3],
plurals: function (n) {
return Number(
n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
);
},
});
const i18n = i18next;
i18n.use(LanguageDetector).init({
resources: localeResources,
fallbackLng: fallbackLanguages,
ns: 'common',
defaultNS: 'common',
react: { wait: true },
debug: false,
cache: { enabled: true },
});
export default i18n;
I followed this link to override plural rule for my project.
When I try to override the plural rule, I can't. pluralResolver doesn't seem to have addRule method. I get TypeError: Cannot read property 'addRule' of undefined. What am I missing? The translation is for Polish plurals.

You should call addRule only after the init is done.
i18n
.use(LanguageDetector)
.init({
resources: localeResources,
fallbackLng: fallbackLanguages,
ns: 'common',
defaultNS: 'common',
react: { wait: true },
debug: false,
cache: { enabled: true },
})
.then(() => {
// this called after the init finished
i18n.services.pluralResolver.addRule('pl', {
numbers: [1, 2, 3],
plurals: function (n) {
return Number(
n === 1 ? 0 : n % 10 >= 2 && n % 10 <= 4 && (n % 100 < 10 || n % 100 >= 20) ? 1 : 2
);
},
});
});

Related

Making a web component using Vue

I am currently working on web components and shadow DOM.
I can see that it is possible to create a native web component using Vue3 here
Vue docs. But I am currently facing issues building the native component file from vuejs files. I have googled for some time and found there are not many helpful content for it.
Building Web Components with Vue 3.2 is by far the most helpful blog I have found. Still I am unable to do production build of my files.
Currently I am getting 2 files after build.
import {
r as c,
c as l,
o as a,
a as u,
b as d,
d as f,
t as m,
u as p,
e as g,
} from "./vendor.21fe8919.js";
const y = function () {
const r = document.createElement("link").relList;
if (r && r.supports && r.supports("modulepreload")) return;
for (const e of document.querySelectorAll('link[rel="modulepreload"]')) o(e);
new MutationObserver((e) => {
for (const t of e)
if (t.type === "childList")
for (const s of t.addedNodes)
s.tagName === "LINK" && s.rel === "modulepreload" && o(s);
}).observe(document, { childList: !0, subtree: !0 });
function i(e) {
const t = {};
return (
e.integrity && (t.integrity = e.integrity),
e.referrerpolicy && (t.referrerPolicy = e.referrerpolicy),
e.crossorigin === "use-credentials"
? (t.credentials = "include")
: e.crossorigin === "anonymous"
? (t.credentials = "omit")
: (t.credentials = "same-origin"),
t
);
}
function o(e) {
if (e.ep) return;
e.ep = !0;
const t = i(e);
fetch(e.href, t);
}
};
y();
const h = {
props: { timeZone: { type: String, default: "America/Los_Angeles" } },
emits: ["datechange"],
setup(n, { emit: r }) {
const i = n,
o = c(new Date()),
e = l(() => o.value.toLocaleString("en-US", { timeZone: i.timeZone }));
return (
setInterval(() => {
(o.value = new Date()), r("datechange", e);
}, 1e3),
(t, s) => (
a(), u("div", null, [d(t.$slots, "prefix"), f(" " + m(p(e)), 1)])
)
);
},
},
v = g(h);
customElements.define("current-time", v);
document.querySelector("current-time").addEventListener("datechange", L);
function L(n) {
console.log(n.detail[0].value);
}
But i would like the build file to be in following format for my use case.
class CurrentTime extends HTMLElement {
connectedCallback() {
this.innerHTML = new Date();
setInterval(() => this.innerHTML = new Date(), 1000)
}
}
// Define it as a custom element
customElements.define('current-time', CurrentTime);
vite config file
import { defineConfig } from "vite";
import vue from "#vitejs/plugin-vue";
export default defineConfig({
plugins: [vue({ customElement: true })],
});

Minimize Pagination Vue.js

I have a pagination and it looks like this: < 1 2 3 4 5 6 7 8 9 >
But it's too big, so I need to display them like this: < 1 2 3 4 ... 21>
This is my template:
ul.pagination.float-right
li.page-item
a.page-link(v-on:click="prevPage()")
i.icon.ion-ios-arrow-back
li(v-for="n in numberOfPages")
a.page-link(#click="goToPage(n)", :limit="3" :style= "[actualPage == n && {backgroundColor: '#d3d3d3'}]") {{n}}
li.page-item
a.page-link(v-on:click="nextPage()")
i.icon.ion-ios-arrow-forward
and my script:
data () {
return {
numberOfPages: 0,
roles: [],
rolesInPage: [],
actualPage: 1,
elementsByPage: 10,
prevPage () {
if (this.actualPage > 1) {
this.actualPage = this.actualPage - 1
}
const from = this.elementsByPage * (this.actualPage - 1)
this.rolesInPage = this.roles.slice(from, from + 10)
},
nextPage () {
if (this.actualPage < this.numberOfPages) {
this.actualPage = this.actualPage + 1
}
const from = this.elementsByPage * (this.actualPage - 1)
this.rolesInPage = this.roles.slice(from, from + 10)
},
getNumberOfPages () {
return Math.ceil(this.roles.length / this.elementsByPage)
},
goToPage (page) {
this.actualPage = page
const from = this.elementsByPage * (this.actualPage - 1)
this.rolesInPage = this.roles.slice(from, from + this.elementsByPage)
},
Any help will be much appreciated
I wrote a basic solution, but needs some improvements and you'll need to validate in your frontend what's the limit of pages to show and place those dots between them.
The basic solution
That function returns an array with just the indexes you want and an extra index with the total of pages you already had.

Vue Leaflet Get Color Function

I am using VueLeaflet to create a map like in this example: https://vue2-leaflet.netlify.com/examples/geo-json.html
I like to add some colors to the polygons like in this example: https://leafletjs.com/examples/choropleth/
This is my try here: https://codesandbox.io/s/old-framework-mlc7b
getcolorFunction(d) {
return d > 1000
? "#800026"
: d > 500
? "#BD0026"
: d > 200
? "#E31A1C"
: d > 100
? "#FC4E2A"
: d > 50
? "#FD8D3C"
: d > 20
? "#FEB24C"
: d > 10
? "#FED976"
: "#FFEDA0";
},
styleFunction() {
const fillColor = this.fillColor; // important! need touch fillColor in computed for re-calculate when change fillColor
return () => {
return {
weight: 2,
color: "#ECEFF1",
opacity: 1,
fillColor: getColor(feature.properties.sales),
fillOpacity: 1
};
};
},
onEachFeatureFunction() {
if (!this.enableTooltip) {
return () => {};
}
return (feature, layer) => {
layer.bindTooltip(
"<div>Name Province:" +
feature.properties.varname_1 +
"</div><div>Sales: " +
feature.properties.sales +
"</div>",
{ permanent: false, sticky: true }
);
};
}
},
How could I Get work that function getColor in Vue.js ?
onEachFeatureFunction() {
return (feature, layer) => {
layer.options.fillColor = this.getcolorFunction(
feature.properties.sales
?feature.properties.sales
: 0
);
layer.on("click", function (e) {
console.log(e, feature);
})
};
}

how can i set ID of qty in nativescript

I have button + - and i want to save the result of that butotn + -. But i have no idea id of the button/qty. First, variable in run debug android is empty. And when i insert qty:1, the result is "variables: {qty_used: 1}". Here is the code
data() {
return {
pageData: this.tempData,
list: {},
is_checked_all: false,
is_saving: false,
is_completed: false,
qty: 1
}
},
and here is the method
methods: {
toggleSelectAll() {
if (this.is_completed) return
this.is_checked_all = true
},
save(qty) {
if (this.is_saving) return
this.is_saving = true
var vm = this
this.$apollo.query({
query: gqlUseVoucher,
variables: {
id: this.pageData.id,
qty_used: qty
},
fetchPolicy: 'no-cache'
}).then((resp) => {
if (resp.room.AuthorizeVoucherUsingID) {
vm.is_saving = false
vm.$modal.close()
vm.$store.commit('setSuccess', 'Voucher breakfast berhasil divalidasi')
} else {
vm.is_saving = false
errorHandler(vm, null, 'Voucher breakfast tidak dapat digunakan')
}
}).catch((error) => {
vm.is_saving = false
console.log(error)
errorHandler(vm, error)
})
},
now, what should i do to get the ID of that button/qty. Am new in nativescript xoxo. thank you

setInterval doesn't fire in vue

im learning vue and setInterval doesn't work like in normal javascript? the problem is that my update function doesn't get fired.
start gets fired from a button, and hours/minutes/seconds are bound to input fields with v-model, i get all console.logs before the setInterval.
export default Vue.extend({
name: "timer-c",
data() {
return {
startDate: undefined,
hours: "",
minutes: "",
seconds: "",
timeLeft: undefined,
endDate: undefined,
interval: undefined,
text: "00:00:00",
sub: undefined,
};
},
methods: {
start: function() {
if (this.sub === undefined) {
let sum = 0;
if (this.seconds.match(/^\d+$/)) {
sum = sum + this.seconds * 1000;
console.log(sum);
}
if (this.minutes.match(/^\d+$/)) {
sum = sum + this.minutes * 60 * 1000;
}
if (this.hours.match(/^\d+$/)) {
sum = sum + this.hours * 60 * 60 * 1000;
}
if (sum === 0) {
console.log(this.$refs.br_start);
this.failed = true;
} else {
console.log(sum);
this.failed = false;
this.endDate = new Date(Date.now() + sum);
console.log(this.endDate);
this.startDate = new Date(Date.now());
console.log(this.startDate);
this.interval = setInterval(time => this.update, 1000);
//this.sub = this.interval.subscribe(time => this.update(time));
}
}
},
update: function() {
console.log('test');
const timeRemaining = Math.round((Date.now() - this.endDate) / 1000);
this.text = timeRemaining;
if (new Date(Date.now()) >= this.endDate) {
console.log("test");
}
},
Try to not return the function but execute it
this.interval = setInterval(time => { this.update(time) }, 1000);