Configure Typescript (#19774)

Co-authored-by: Michael Geers <michael@geers.tv>
This commit is contained in:
Maschga 2025-03-21 15:00:50 +01:00 • committed by GitHub
parent 29c4bc6279
commit b937e131f9
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
68 changed files with 1709 additions and 2196 deletions

2
.gitignore vendored
View file

@ -43,5 +43,5 @@ asset-stats.html
/playwright/.cache/
.gitpod.yml
/evcc.db
/tsconfig.tsbuildinfo
*storybook.log

View file

@ -4,5 +4,6 @@
"vitest.explorer",
"golang.go",
"esbenp.prettier-vscode",
"yoavbls.pretty-ts-errors",
]
}

View file

@ -22,12 +22,12 @@ const app = createApp({
return { notifications: [], offline: false };
},
watch: {
offline: function (value) {
offline(value) {
console.log(`we are ${value ? "offline" : "online"}`);
},
},
methods: {
raise: function (msg) {
raise(msg) {
if (this.offline) return;
if (!msg.level) msg.level = "error";
const now = new Date();
@ -46,19 +46,19 @@ const app = createApp({
];
}
},
clear: function () {
clear() {
this.notifications = [];
},
setOnline: function () {
setOnline() {
this.offline = false;
sendToApp({ type: "online" });
},
setOffline: function () {
setOffline() {
this.offline = true;
sendToApp({ type: "offline" });
},
},
render: function () {
render() {
return h(App, { notifications: this.notifications, offline: this.offline });
},
});

View file

@ -1,75 +0,0 @@
import { reactive } from "vue";
// alternatives
// const COLORS = [ "#40916C", "#52B788", "#74C69D", "#95D5B2", "#B7E4C7", "#D8F3DC", "#081C15", "#1B4332", "#2D6A4F"];
// const COLORS = ["#577590", "#43AA8B", "#90BE6D", "#F9C74F", "#F8961E", "#F3722C", "#F94144"];
// const COLORS = ["#0077b6", "#00b4d8", "#90e0ef", "#caf0f8", "#03045e"];
// const COLORS = [ "#0077B6FF", "#0096C7FF", "#00B4D8FF", "#48CAE4FF", "#90E0EFFF", "#ADE8F4FF", "#CAF0F8FF", "#03045EFF", "#023E8AFF",
// const COLORS = [ "#0077B6FF", "#00B4D8FF", "#90E0EFFF", "#40A578FF", "#9DDE8BFF", "#F8961EFF", "#F9C74FFF", "#E6FF94FF"];
const colors = reactive({
text: null,
muted: null,
border: null,
self: null,
grid: null,
co2PerKWh: null,
pricePerKWh: null,
price: null,
co2: null,
background: null,
light: null,
selfPalette: ["#0FDE41FF", "#FFBD2FFF", "#FD6158FF", "#03C1EFFF", "#0F662DFF", "#FF922EFF"],
palette: [
"#03C1EFFF",
"#FD6158FF",
"#31AB4AFF",
"#41517AFF",
"#FF922EFF",
"#0F662DFF",
"#0470D4FF",
"#FFBD2FFF",
"#77C93EFF",
"#4E1D10FF",
"#0AAFBFFF",
"#813504FF",
],
});
export const dimColor = (color) => {
return color.toLowerCase().replace(/ff$/, "20");
};
export const lighterColor = (color) => {
return color.toLowerCase().replace(/ff$/, "aa");
};
export const fullColor = (color) => {
return color.toLowerCase().replace(/20$/, "ff");
};
function updateCssColors() {
const style = window.getComputedStyle(document.documentElement);
colors.text = style.getPropertyValue("--evcc-default-text");
colors.muted = style.getPropertyValue("--bs-gray-medium");
colors.border = style.getPropertyValue("--bs-border-color-translucent");
colors.self = style.getPropertyValue("--evcc-self");
colors.grid = style.getPropertyValue("--evcc-grid");
colors.price = style.getPropertyValue("--evcc-price");
colors.co2 = style.getPropertyValue("--evcc-co2");
colors.background = style.getPropertyValue("--evcc-background");
colors.pricePerKWh = style.getPropertyValue("--bs-gray-medium");
colors.co2PerKWh = style.getPropertyValue("--bs-gray-medium");
colors.light = style.getPropertyValue("--bs-gray-light");
}
// update colors on theme change
const darkModeMatcher = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)");
if (darkModeMatcher && darkModeMatcher.addEventListener) {
darkModeMatcher.addEventListener("change", updateCssColors);
}
// initialize colors
updateCssColors();
window.requestAnimationFrame(updateCssColors);
export default colors;

89
assets/js/colors.ts Normal file
View file

@ -0,0 +1,89 @@
import { reactive } from "vue";
// alternatives
// const COLORS = [ "#40916C", "#52B788", "#74C69D", "#95D5B2", "#B7E4C7", "#D8F3DC", "#081C15", "#1B4332", "#2D6A4F"];
// const COLORS = ["#577590", "#43AA8B", "#90BE6D", "#F9C74F", "#F8961E", "#F3722C", "#F94144"];
// const COLORS = ["#0077b6", "#00b4d8", "#90e0ef", "#caf0f8", "#03045e"];
// const COLORS = [ "#0077B6FF", "#0096C7FF", "#00B4D8FF", "#48CAE4FF", "#90E0EFFF", "#ADE8F4FF", "#CAF0F8FF", "#03045EFF", "#023E8AFF",
// const COLORS = [ "#0077B6FF", "#00B4D8FF", "#90E0EFFF", "#40A578FF", "#9DDE8BFF", "#F8961EFF", "#F9C74FFF", "#E6FF94FF"];
const colors: {
text: string | null;
muted: string | null;
border: string | null;
self: string | null;
grid: string | null;
co2PerKWh: string | null;
pricePerKWh: string | null;
price: string | null;
co2: string | null;
background: string | null;
light: string | null;
selfPalette: string[];
palette: string[];
} = reactive({
text: null,
muted: null,
border: null,
self: null,
grid: null,
co2PerKWh: null,
pricePerKWh: null,
price: null,
co2: null,
background: null,
light: null,
selfPalette: ["#0FDE41FF", "#FFBD2FFF", "#FD6158FF", "#03C1EFFF", "#0F662DFF", "#FF922EFF"],
palette: [
"#03C1EFFF",
"#FD6158FF",
"#31AB4AFF",
"#41517AFF",
"#FF922EFF",
"#0F662DFF",
"#0470D4FF",
"#FFBD2FFF",
"#77C93EFF",
"#4E1D10FF",
"#0AAFBFFF",
"#813504FF",
],
});
export const dimColor = (color: string | null) => {
return color?.toLowerCase().replace(/ff$/, "20");
};
export const lighterColor = (color: string | null) => {
return color?.toLowerCase().replace(/ff$/, "aa");
};
export const fullColor = (color: string | null) => {
return color?.toLowerCase().replace(/20$/, "ff");
};
function updateCssColors() {
const style = window.getComputedStyle(document.documentElement);
colors.text = style.getPropertyValue("--evcc-default-text");
colors.muted = style.getPropertyValue("--bs-gray-medium");
colors.border = style.getPropertyValue("--bs-border-color-translucent");
colors.self = style.getPropertyValue("--evcc-self");
colors.grid = style.getPropertyValue("--evcc-grid");
colors.price = style.getPropertyValue("--evcc-price");
colors.co2 = style.getPropertyValue("--evcc-co2");
colors.background = style.getPropertyValue("--evcc-background");
colors.pricePerKWh = style.getPropertyValue("--bs-gray-medium");
colors.co2PerKWh = style.getPropertyValue("--bs-gray-medium");
colors.light = style.getPropertyValue("--bs-gray-light");
}
// update colors on theme change
const darkModeMatcher = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)");
if (darkModeMatcher && darkModeMatcher.addEventListener) {
darkModeMatcher.addEventListener("change", updateCssColors);
}
// initialize colors
updateCssColors();
window.requestAnimationFrame(updateCssColors);
export default colors;

View file

@ -85,7 +85,7 @@
</GenericModal>
</template>
<script>
<script type="js">
import GenericModal from "../Helper/GenericModal.vue";
import FormRow from "../Helper/FormRow.vue";
import api from "../../api.js";
@ -106,31 +106,31 @@ export default {
};
},
computed: {
passwordsMatch: function () {
passwordsMatch() {
return this.passwordNew === this.passwordRepeat;
},
passwordEmpty: function () {
passwordEmpty() {
return this.passwordNew.length === 0;
},
updateMode: function () {
updateMode() {
return isConfigured();
},
title: function () {
title() {
return this.updateMode
? this.$t("passwordModal.titleUpdate")
: this.$t("passwordModal.titleNew");
},
submitText: function () {
submitText() {
return this.updateMode
? this.$t("passwordModal.updatePassword")
: this.$t("passwordModal.newPassword");
},
},
methods: {
open: function () {
open() {
this.modalVisible = true;
},
closed: function () {
closed() {
this.modalVisible = false;
this.passwordCurrent = "";
this.passwordNew = "";
@ -139,7 +139,7 @@ export default {
this.loading = false;
this.showValidation = false;
},
setPassword: async function (e) {
async setPassword(e) {
this.$refs.passwordRepeat.setCustomValidity(
this.passwordsMatch && !this.passwordEmpty ? "" : "invalid"
);
@ -153,7 +153,7 @@ export default {
await updateAuthStatus();
}
},
savePassword: async function () {
async savePassword() {
this.loading = true;
this.error = null;
try {

View file

@ -278,7 +278,7 @@ export default {
tariffGrid: Number,
currency: String,
},
data: function () {
data() {
return {
isModalVisible: false,
selectedBufferSoc: 100,
@ -429,10 +429,10 @@ export default {
this.gridTabActive = false;
}
},
modalVisible: function () {
modalVisible() {
this.isModalVisible = true;
},
modalInvisible: function () {
modalInvisible() {
this.isModalVisible = false;
},
changeBufferStart($event) {

View file

@ -75,7 +75,7 @@ export default {
rangePerSoc: Number,
},
emits: ["minsoc-updated", "limitsoc-updated"],
data: function () {
data() {
return { selectedMinSoc: this.minSoc, selectedLimitSoc: this.limitSoc };
},
computed: {
@ -93,27 +93,27 @@ export default {
},
},
watch: {
minSoc: function (value) {
minSoc(value) {
this.selectedMinSoc = value;
},
limitSoc: function (value) {
limitSoc(value) {
this.selectedLimitSoc = value;
},
},
methods: {
socOption: function (soc) {
socOption(soc) {
return {
value: soc,
name: soc === 0 ? "---" : this.fmtSocOption(soc, this.rangePerSoc, distanceUnit()),
};
},
formId: function (name) {
formId(name) {
return `chargingplan_${this.id}_${name}`;
},
changeMinSoc: function () {
changeMinSoc() {
this.$emit("minsoc-updated", this.selectedMinSoc);
},
changeLimitSoc: function () {
changeLimitSoc() {
this.$emit("limitsoc-updated", this.selectedLimitSoc);
},
},

View file

@ -147,7 +147,7 @@ export default {
vehicleSoc: Number,
vehicleLimitSoc: Number,
},
data: function () {
data() {
return {
modal: null,
isModalVisible: false,
@ -157,7 +157,7 @@ export default {
};
},
computed: {
buttonColor: function () {
buttonColor() {
if (this.planTimeUnreachable) {
return "text-warning";
}
@ -166,13 +166,13 @@ export default {
}
return "evcc-default-text";
},
minSoc: function () {
minSoc() {
return this.vehicle?.minSoc;
},
limitSoc: function () {
limitSoc() {
return this.vehicle?.limitSoc;
},
staticPlan: function () {
staticPlan() {
if (this.socBasedPlanning) {
return this.vehicle?.plan;
}
@ -181,31 +181,31 @@ export default {
}
return null;
},
repeatingPlans: function () {
repeatingPlans() {
if (this.vehicle?.repeatingPlans.length > 0) {
return [...this.vehicle.repeatingPlans];
}
return [];
},
enabled: function () {
enabled() {
return this.effectivePlanTime;
},
modalId: function () {
modalId() {
return `chargingPlanModal_${this.id}`;
},
departureTabActive: function () {
departureTabActive() {
return this.activeTab === "departure";
},
arrivalTabActive: function () {
arrivalTabActive() {
return this.activeTab === "arrival";
},
chargingPlansSettingsProps: function () {
chargingPlansSettingsProps() {
return this.collectProps(PlansSettings);
},
chargingPlanArrival: function () {
chargingPlanArrival() {
return this.collectProps(Arrival);
},
targetSocLabel: function () {
targetSocLabel() {
if (this.socBasedPlanning) {
return this.fmtPercentage(this.effectivePlanSoc);
}
@ -216,10 +216,10 @@ export default {
this.$t("main.targetEnergy.noLimit")
);
},
apiVehicle: function () {
apiVehicle() {
return `vehicles/${this.vehicle?.name}/`;
},
apiLoadpoint: function () {
apiLoadpoint() {
return `loadpoints/${this.id}/`;
},
},
@ -248,7 +248,7 @@ export default {
clearInterval(this.interval);
},
methods: {
checkUnsavedOnClose: function () {
checkUnsavedOnClose() {
const $applyButton = this.$refs.modal.querySelector("[data-testid=plan-apply]");
if ($applyButton) {
if (confirm(this.$t("main.chargingPlan.unsavedChanges"))) {
@ -256,10 +256,10 @@ export default {
}
}
},
modalVisible: function () {
modalVisible() {
this.isModalVisible = true;
},
modalInvisible: function () {
modalInvisible() {
this.isModalVisible = false;
},
openModal() {
@ -274,18 +274,18 @@ export default {
}
this.modal.show();
},
updateTargetTimeLabel: function () {
updateTargetTimeLabel() {
if (!this.effectivePlanTime) return "";
const targetDate = new Date(this.effectivePlanTime);
this.targetTimeLabel = this.fmtAbsoluteDate(targetDate);
},
showDeatureTab: function () {
showDeatureTab() {
this.activeTab = "departure";
},
showArrivalTab: function () {
showArrivalTab() {
this.activeTab = "arrival";
},
updateStaticPlan: function ({ soc, time, energy }) {
updateStaticPlan({ soc, time, energy }) {
const timeISO = time.toISOString();
if (this.socBasedPlanning) {
api.post(`${this.apiVehicle}plan/soc/${soc}/${timeISO}`);
@ -293,20 +293,20 @@ export default {
api.post(`${this.apiLoadpoint}plan/energy/${energy}/${timeISO}`);
}
},
removeStaticPlan: function () {
removeStaticPlan() {
if (this.socBasedPlanning) {
api.delete(`${this.apiVehicle}plan/soc`);
} else {
api.delete(`${this.apiLoadpoint}plan/energy`);
}
},
updateRepeatingPlans: function (plans) {
updateRepeatingPlans(plans) {
api.post(`${this.apiVehicle}plan/repeating`, { plans });
},
setMinSoc: function (soc) {
setMinSoc(soc) {
api.post(`${this.apiVehicle}minsoc/${soc}`);
},
setLimitSoc: function (soc) {
setLimitSoc(soc) {
api.post(`${this.apiVehicle}limitsoc/${soc}`);
},
},

View file

@ -159,7 +159,7 @@ export default {
formIdPrefix: String,
},
emits: ["updated", "removed"],
data: function () {
data() {
return {
selectedWeekdays: this.weekdays,
selectedTime: this.time,
@ -168,7 +168,7 @@ export default {
};
},
computed: {
dataChanged: function () {
dataChanged() {
return (
!deepEqual(this.weekdays, this.selectedWeekdays) ||
this.time !== this.selectedTime ||
@ -176,19 +176,19 @@ export default {
this.active !== this.selectedActive
);
},
showApply: function () {
showApply() {
return this.dataChanged && this.selectedActive;
},
weekdaysLabel: function () {
weekdaysLabel() {
return this.getShortenedWeekdaysLabel(this.selectedWeekdays);
},
socOptions: function () {
socOptions() {
// a list of entries from 5 to 100 with a step of 5
return Array.from(Array(20).keys())
.map((i) => 5 + i * 5)
.map(this.socOption);
},
dayOptions: function () {
dayOptions() {
return this.getWeekdaysList("long");
},
},
@ -209,18 +209,18 @@ export default {
},
},
methods: {
changeSelectedWeekdays: function (weekdays) {
changeSelectedWeekdays(weekdays) {
this.selectedWeekdays = weekdays;
this.update();
},
formId: function (name) {
formId(name) {
return `${this.formIdPrefix}-${this.number}-${name}`;
},
socOption: function (value) {
socOption(value) {
const name = this.fmtSocOption(value, this.rangePerSoc, distanceUnit());
return { value, name };
},
update: function (forceSave = false) {
update(forceSave = false) {
const plan = {
weekdays: this.selectedWeekdays,
time: this.selectedTime,

View file

@ -173,7 +173,7 @@ export default {
multiplePlans: Boolean,
},
emits: ["static-plan-updated", "static-plan-removed", "plan-preview"],
data: function () {
data() {
return {
selectedDay: null,
selectedTime: null,
@ -183,16 +183,16 @@ export default {
};
},
computed: {
selectedDate: function () {
selectedDate() {
return new Date(`${this.selectedDay}T${this.selectedTime || "00:00"}`);
},
socOptions: function () {
socOptions() {
// a list of entries from 5 to 100 with a step of 5
return Array.from(Array(20).keys())
.map((i) => 5 + i * 5)
.map(this.socOption);
},
energyOptions: function () {
energyOptions() {
const options = energyOptions(
0,
this.capacity || 100,
@ -204,7 +204,7 @@ export default {
// remove the first entry (0)
return options.slice(1);
},
originalData: function () {
originalData() {
if (this.isNew) {
return {};
}
@ -215,7 +215,7 @@ export default {
time: this.fmtTimeString(new Date(this.time)),
};
},
dataChanged: function () {
dataChanged() {
const dateChanged =
this.originalData.day != this.selectedDay ||
this.originalData.time != this.selectedTime;
@ -224,10 +224,10 @@ export default {
: this.originalData.energy != this.selectedEnergy;
return dateChanged || goalChanged;
},
isNew: function () {
isNew() {
return !this.time && (!this.soc || !this.energy);
},
timeInThePast: function () {
timeInThePast() {
const now = new Date();
return now >= this.selectedDate;
},
@ -255,14 +255,14 @@ export default {
this.preview();
},
methods: {
formId: function (name) {
formId(name) {
return `chargingplan-${this.id}-${name}`;
},
socOption: function (value) {
socOption(value) {
const name = this.fmtSocOption(value, this.rangePerSoc, distanceUnit());
return { value, name };
},
initInputFields: function () {
initInputFields() {
if (!this.selectedSoc) {
this.selectedSoc = window.localStorage[LAST_SOC_GOAL_KEY] || 100;
}
@ -283,7 +283,7 @@ export default {
this.selectedDay = this.fmtDayString(date);
this.selectedTime = this.fmtTimeString(date);
},
dayOptions: function () {
dayOptions() {
const options = [];
const date = new Date();
const labels = [
@ -305,7 +305,7 @@ export default {
}
return options;
},
update: function () {
update() {
try {
const hours = this.selectedDate.getHours();
const minutes = this.selectedDate.getMinutes();
@ -325,7 +325,7 @@ export default {
energy: this.selectedEnergy,
});
},
preview: function (force = false) {
preview(force = false) {
if (!this.isNew && !force) {
return false;
}
@ -335,7 +335,7 @@ export default {
energy: this.selectedEnergy,
});
},
toggle: function (e) {
toggle(e) {
const { checked } = e.target;
if (checked) {
this.update();
@ -345,7 +345,7 @@ export default {
}
this.active = checked;
},
defaultTime: function () {
defaultTime() {
const [hours, minutes] = (
window.localStorage[LAST_TARGET_TIME_KEY] || DEFAULT_TARGET_TIME
).split(":");

View file

@ -50,13 +50,13 @@ export default {
},
emits: ["updated"],
computed: {
formIdPrefix: function () {
formIdPrefix() {
return `chargingplan-lp${this.id}`;
},
},
methods: {
deepEqual,
addPlan: function () {
addPlan() {
const newPlan = {
weekdays: DEFAULT_WEEKDAYS,
time: DEFAULT_TARGET_TIME,
@ -70,15 +70,15 @@ export default {
plans.push(newPlan);
this.updatePlans(plans);
},
updatePlan: function (index, plan) {
updatePlan(index, plan) {
const plans = [...this.plans]; // clone array
plans.splice(index, 1, plan);
this.updatePlans(plans);
},
updatePlans: function (plans) {
updatePlans(plans) {
this.$emit("updated", plans);
},
removePlan: function (index) {
removePlan(index) {
const plans = [...this.plans]; // clone array
plans.splice(index, 1);
this.updatePlans(plans);

View file

@ -106,7 +106,7 @@ export default {
planOverrun: Number,
},
emits: ["static-plan-removed", "static-plan-updated", "repeating-plans-updated"],
data: function () {
data() {
return {
staticPlanPreview: {},
tariff: {},
@ -118,19 +118,19 @@ export default {
};
},
computed: {
noActivePlan: function () {
noActivePlan() {
return !this.staticPlan && this.repeatingPlans.every((plan) => !plan.active);
},
multiplePlans: function () {
multiplePlans() {
return this.repeatingPlans.length !== 0;
},
selectedPreviewPlanTitle: function () {
selectedPreviewPlanTitle() {
return this.previewPlanOptions[this.selectedPreviewId - 1]?.name;
},
chargingPlanWarningsProps: function () {
chargingPlanWarningsProps() {
return this.collectProps(Warnings);
},
chargingPlanPreviewProps: function () {
chargingPlanPreviewProps() {
const { rates } = this.tariff;
const { duration, plan, power, planTime } = this.plan;
const targetTime = planTime ? new Date(planTime) : null;
@ -139,7 +139,7 @@ export default {
? { duration, plan, power, rates, targetTime, currency, smartCostType }
: null;
},
previewPlanOptions: function () {
previewPlanOptions() {
const name = (number) => `${this.$t("main.targetCharge.preview")} #${number}`;
// static plan
@ -157,7 +157,7 @@ export default {
return options;
},
nextPlanTitle: function () {
nextPlanTitle() {
return `${this.$t("main.targetCharge.nextPlan")} #${this.nextPlanId}`;
},
},
@ -169,7 +169,7 @@ export default {
},
staticPlan: {
deep: true,
handler: function (vNew, vOld) {
handler(vNew, vOld) {
if (!deepEqual(vNew, vOld)) {
this.fetchPlanDebounced();
}
@ -177,7 +177,7 @@ export default {
},
repeatingPlans: {
deep: true,
handler: function (vNew, vOld) {
handler(vNew, vOld) {
if (!deepEqual(vNew, vOld)) {
this.adjustPreviewId();
this.fetchPlanDebounced();
@ -189,23 +189,23 @@ export default {
this.fetchPlanDebounced();
},
methods: {
selectPreviewPlan: function (id) {
selectPreviewPlan(id) {
this.selectedPreviewId = id;
this.fetchPlanPreviewDebounced();
},
fetchPlanDebounced: async function () {
async fetchPlanDebounced() {
if (this.noActivePlan) {
await this.fetchPlanPreviewDebounced();
} else {
await this.fetchActivePlanDebounced();
}
},
adjustPreviewId: function () {
adjustPreviewId() {
if (this.selectedPreviewId > this.previewPlanOptions.length) {
this.selectedPreviewId = this.previewPlanOptions.length;
}
},
fetchActivePlan: async function () {
async fetchActivePlan() {
try {
const res = await this.apiFetchPlan(`loadpoints/${this.id}/plan`);
this.plan = res.data.result;
@ -215,24 +215,24 @@ export default {
}
await this.updateTariff();
},
fetchStaticPreviewSoc: async function (soc, time) {
async fetchStaticPreviewSoc(soc, time) {
const timeISO = time.toISOString();
return await this.apiFetchPlan(
`loadpoints/${this.id}/plan/static/preview/soc/${soc}/${timeISO}`
);
},
fetchRepeatingPreview: async function (weekdays, soc, time, tz) {
async fetchRepeatingPreview(weekdays, soc, time, tz) {
return await this.apiFetchPlan(
`loadpoints/${this.id}/plan/repeating/preview/${soc}/${weekdays}/${time}/${encodeURIComponent(tz)}`
);
},
fetchStaticPreviewEnergy: async function (energy, time) {
async fetchStaticPreviewEnergy(energy, time) {
const timeISO = time.toISOString();
return await this.apiFetchPlan(
`loadpoints/${this.id}/plan/static/preview/energy/${energy}/${timeISO}`
);
},
apiFetchPlan: async function (url) {
async apiFetchPlan(url) {
try {
const res = await api.get(url, {
validateStatus: (code) => [200, 404].includes(code),
@ -245,7 +245,7 @@ export default {
console.error(e);
}
},
fetchPreviewPlan: async function () {
async fetchPreviewPlan() {
// only show preview of no plan is active
if (!this.noActivePlan) return;
@ -278,7 +278,7 @@ export default {
console.error(e);
}
},
updateTariff: async function () {
async updateTariff() {
// cache tariff for 5 minutes
if (
this.tariff?.lastUpdate &&
@ -288,7 +288,7 @@ export default {
}
const tariffRes = await api.get(`tariff/planner`, {
validateStatus: function (status) {
validateStatus(status) {
return status >= 200 && status < 500;
},
});
@ -299,7 +299,7 @@ export default {
this.tariff.lastUpdate = new Date();
}
},
fetchPlanPreviewDebounced: async function () {
async fetchPlanPreviewDebounced() {
if (!this.debounceTimer) {
await this.fetchPreviewPlan();
return;
@ -307,7 +307,7 @@ export default {
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(async () => await this.fetchPreviewPlan(), 1000);
},
fetchActivePlanDebounced: async function () {
async fetchActivePlanDebounced() {
if (!this.debounceTimer) {
await this.fetchActivePlan();
return;
@ -315,16 +315,16 @@ export default {
clearTimeout(this.debounceTimer);
this.debounceTimer = setTimeout(async () => await this.fetchActivePlan(), 1000);
},
removeStaticPlan: function (index) {
removeStaticPlan(index) {
this.$emit("static-plan-removed", index);
},
updateStaticPlan: function (data) {
updateStaticPlan(data) {
this.$emit("static-plan-updated", data);
},
updateRepeatingPlans: function (plans) {
updateRepeatingPlans(plans) {
this.$emit("repeating-plans-updated", plans);
},
previewStaticPlan: function (plan) {
previewStaticPlan(plan) {
this.staticPlanPreview = plan;
this.fetchPlanPreviewDebounced();
},

View file

@ -41,20 +41,20 @@ export default {
planOverrun: Number,
},
computed: {
endTime: function () {
endTime() {
if (!this.plan?.plan?.length) {
return null;
}
const { plan } = this.plan;
return plan[plan.length - 1].end;
},
overrunFmt: function () {
overrunFmt() {
if (!this.planOverrun) {
return "";
}
return this.fmtDuration(this.planOverrun, true, "m");
},
timeTooFarInTheFuture: function () {
timeTooFarInTheFuture() {
if (!this.effectivePlanTime) {
return false;
}
@ -67,7 +67,7 @@ export default {
}
return false;
},
notReachableInTime: function () {
notReachableInTime() {
const { planTime } = this.plan || {};
if (planTime && this.endTime) {
const dateWanted = new Date(planTime);
@ -77,25 +77,25 @@ export default {
}
return false;
},
targetIsAboveLimit: function () {
targetIsAboveLimit() {
if (this.socBasedPlanning) {
return this.effectivePlanSoc > this.effectiveLimitSoc;
}
return this.limitEnergy && this.planEnergy > this.limitEnergy;
},
targetIsAboveVehicleLimit: function () {
targetIsAboveVehicleLimit() {
if (this.socBasedPlanning) {
return this.effectivePlanSoc > (this.vehicleLimitSoc || 100);
}
return false;
},
limitFmt: function () {
limitFmt() {
if (this.socBasedPlanning) {
return this.fmtSoc(this.effectiveLimitSoc);
}
return this.fmtWh(this.limitEnergy * 1e3);
},
goalFmt: function () {
goalFmt() {
if (this.socBasedPlanning) {
return this.fmtSoc(this.effectivePlanSoc);
}

View file

@ -279,57 +279,57 @@ export default {
return { detailsOpen: false, detailsCompleteHeight: null, ready: false };
},
computed: {
gridImport: function () {
gridImport() {
return Math.max(0, this.gridPower);
},
pvProduction: function () {
pvProduction() {
return Math.abs(this.pvPower);
},
batteryDischarge: function () {
batteryDischarge() {
return this.dischargePower(this.batteryPower);
},
batteryCharge: function () {
batteryCharge() {
return this.chargePower(this.batteryPower);
},
batteryChargeLabel: function () {
batteryChargeLabel() {
return this.$t(`main.energyflow.battery${this.batteryHold ? "Hold" : "Charge"}`);
},
batteryDischargeLabel: function () {
batteryDischargeLabel() {
return this.$t(`main.energyflow.battery${this.batteryHold ? "Hold" : "Discharge"}`);
},
batteryHold: function () {
batteryHold() {
return this.batteryMode === "hold";
},
consumption: function () {
consumption() {
return this.homePower + this.batteryCharge + this.loadpointsPower;
},
selfPv: function () {
selfPv() {
return Math.min(this.pvProduction, this.consumption);
},
selfBattery: function () {
selfBattery() {
return Math.min(this.batteryDischarge, this.consumption - this.selfPv);
},
activeLoadpoints: function () {
activeLoadpoints() {
return this.loadpointsCompact.filter((lp) => lp.charging);
},
activeLoadpointsCount: function () {
activeLoadpointsCount() {
return this.activeLoadpoints.length;
},
vehicleIcons: function () {
vehicleIcons() {
if (this.activeLoadpointsCount > 0) {
return this.activeLoadpoints.map((lp) => lp.icon);
}
return ["car"];
},
loadpointsPower: function () {
loadpointsPower() {
return this.loadpointsCompact.reduce((sum, lp) => {
return sum + (lp.power || 0);
}, 0);
},
pvExport: function () {
pvExport() {
return Math.max(0, this.gridPower * -1);
},
powerUnit: function () {
powerUnit() {
const watt = Math.max(this.gridImport, this.selfPv, this.selfBattery, this.pvExport);
if (watt >= 1_000_000) {
return POWER_UNIT.MW;
@ -339,13 +339,13 @@ export default {
return POWER_UNIT.W;
}
},
inPower: function () {
inPower() {
return this.gridImport + this.pvProduction + this.batteryDischarge;
},
outPower: function () {
outPower() {
return this.homePower + this.loadpointsPower + this.pvExport + this.batteryCharge;
},
detailsHeight: function () {
detailsHeight() {
return this.detailsOpen ? this.detailsCompleteHeight + "px" : 0;
},
pvTooltip() {
@ -467,15 +467,15 @@ export default {
}
return `${this.fmtWh(value, POWER_UNIT.KW)}`;
},
kw: function (watt) {
kw(watt) {
return this.fmtW(watt, this.powerUnit);
},
toggleDetails: function () {
toggleDetails() {
this.updateHeight();
this.detailsOpen = !this.detailsOpen;
settings.energyflowDetails = this.detailsOpen;
},
updateHeight: function () {
updateHeight() {
this.detailsCompleteHeight = this.$refs.detailsInner.offsetHeight;
},
openBatterySettingsModal() {

View file

@ -73,13 +73,13 @@ export default {
return { powerTooltipInstance: null, detailsTooltipInstance: null };
},
computed: {
active: function () {
active() {
return this.power > 10;
},
isBattery: function () {
isBattery() {
return this.icon === "battery";
},
isVehicle: function () {
isVehicle() {
return this.icon === "vehicle";
},
},
@ -101,12 +101,12 @@ export default {
}
},
},
mounted: function () {
mounted() {
this.updatePowerTooltip();
this.updateDetailsTooltip();
},
methods: {
kw: function (watt) {
kw(watt) {
return this.fmtW(watt, this.powerUnit);
},
updatePowerTooltip() {
@ -123,7 +123,7 @@ export default {
this.$refs.details
);
},
updateTooltip: function (instance, content, ref) {
updateTooltip(instance, content, ref) {
if (!Array.isArray(content) || !content.length) {
if (instance) {
instance.dispose();
@ -138,12 +138,12 @@ export default {
newInstance.setContent({ ".tooltip-inner": html });
return newInstance;
},
powerClicked: function ($event) {
powerClicked($event) {
if (this.powerTooltip) {
$event.stopPropagation();
}
},
detailsClicked: function ($event) {
detailsClicked($event) {
if (this.detailsClickable || this.detailsTooltip) {
$event.stopPropagation();
}

View file

@ -137,29 +137,29 @@ export default {
inPower: { type: Number, default: 0 },
outPower: { type: Number, default: 0 },
},
data: function () {
data() {
return { width: 0 };
},
computed: {
gridExport: function () {
gridExport() {
return this.applyThreshold(this.pvExport);
},
totalRaw: function () {
totalRaw() {
return this.gridImport + this.selfPv + this.selfBattery + this.pvExport;
},
gridImportAdjusted: function () {
gridImportAdjusted() {
return this.applyThreshold(this.gridImport);
},
selfPvAdjusted: function () {
selfPvAdjusted() {
return this.applyThreshold(this.selfPv);
},
selfBatteryAdjusted: function () {
selfBatteryAdjusted() {
return this.applyThreshold(this.selfBattery);
},
pvExportAdjusted: function () {
pvExportAdjusted() {
return this.applyThreshold(this.pvExport);
},
totalAdjusted: function () {
totalAdjusted() {
return (
this.gridImportAdjusted +
this.selfPvAdjusted +
@ -167,27 +167,27 @@ export default {
this.pvExportAdjusted
);
},
unknownImport: function () {
unknownImport() {
// input/output mismatch > 10%
return this.applyThreshold(Math.max(0, this.outPower - this.inPower), 10);
},
unknownOutput: function () {
unknownOutput() {
// input/output mismatch > 10%
return this.applyThreshold(Math.max(0, this.inPower - this.outPower), 10);
},
unknownPower: function () {
unknownPower() {
if (this.unknownImport || this.unknownOutput) {
const total = Math.max(this.inPower, this.outPower);
return Math.abs(total - this.totalAdjusted);
}
return 0;
},
visualizationReady: function () {
visualizationReady() {
return this.totalAdjusted > 0 && this.width > 0;
},
},
mounted: function () {
mounted() {
this.$nextTick(function () {
window.addEventListener("resize", this.updateElementWidth);
this.updateElementWidth();
@ -197,11 +197,11 @@ export default {
window.removeEventListener("resize", this.updateElementWidth);
},
methods: {
widthTotal: function (power) {
widthTotal(power) {
if (this.totalAdjusted === 0 || power === 0) return "0";
return (100 / this.totalAdjusted) * power + "%";
},
fmtBarValue: function (watt) {
fmtBarValue(watt) {
if (!this.enoughSpaceForValue(watt)) {
return "";
}

View file

@ -117,7 +117,7 @@ export default {
},
},
watch: {
offline: function () {
offline() {
if (!this.offline) {
restartComplete();
this.dismissed = false;

View file

@ -144,17 +144,17 @@ export default {
uploadMessage: String,
uploadProgress: Number,
},
data: function () {
data() {
return {
updateStarted: false,
updateStatus: "",
};
},
computed: {
githubHashUrl: function () {
githubHashUrl() {
return `https://github.com/evcc-io/evcc/commit/${this.commit}`;
},
newVersionAvailable: function () {
newVersionAvailable() {
return (
this.available && // available version already computed?
this.installed != "[[.Version]]" && // go template parsed?
@ -164,7 +164,7 @@ export default {
},
},
methods: {
update: async function () {
async update() {
try {
await api.post("update");
this.updateStatus = this.$t("footer.version.modalUpdateStatusStart");
@ -173,7 +173,7 @@ export default {
this.updateStatus = `${this.$t("footer.version.modalUpdateStatusStart")} ${e}`;
}
},
releaseNotesUrl: function (version) {
releaseNotesUrl(version) {
return version == "0.0.0"
? `https://github.com/evcc-io/evcc/releases`
: `https://github.com/evcc-io/evcc/releases/tag/${version}`;

View file

@ -11,8 +11,8 @@
<script lang="ts">
import { defineComponent } from "vue";
import type { PropType } from "vue";
import { type PriceSlot, type TimeseriesEntry } from "../../utils/forecast.ts";
import formatter from "../../mixins/formatter";
import { isPriceSlot, type PriceSlot, type TimeseriesEntry } from "../../utils/forecast.ts";
import formatter from "../../mixins/formatter.ts";
export default defineComponent({
name: "ForecastActiveSlot",
@ -22,25 +22,25 @@ export default defineComponent({
},
computed: {
isSlot() {
return this.activeSlot?.start && this.activeSlot?.end;
return this.activeSlot !== null && isPriceSlot(this.activeSlot);
},
isTimeseries() {
return this.activeSlot?.ts;
return this.activeSlot !== null && !isPriceSlot(this.activeSlot);
},
day() {
const startDate = new Date(this.activeSlot!.start);
const startDate = new Date((this.activeSlot! as PriceSlot).start);
return this.weekdayShort(startDate);
},
start() {
const startDate = new Date(this.activeSlot!.start);
const startDate = new Date((this.activeSlot! as PriceSlot).start);
return this.hourShort(startDate);
},
end() {
const endDate = new Date(this.activeSlot!.end);
const endDate = new Date((this.activeSlot! as PriceSlot).end);
return this.hourShort(endDate);
},
time() {
const time = new Date(this.activeSlot!.ts);
const time = new Date((this.activeSlot! as TimeseriesEntry).ts);
return `${this.weekdayShort(time)} ${this.hourShort(time)}`;
},
},

View file

@ -5,6 +5,7 @@
@mouseleave="onMouseLeave"
>
<div style="position: relative; height: 220px" class="chart user-select-none">
<!-- @vue-ignore -->
<Bar ref="chart" :data="chartData" :options="options" />
</div>
</div>
@ -25,12 +26,15 @@ import {
Tooltip,
PointElement,
Filler,
type ChartEvent,
type ActiveElement,
Chart,
} from "chart.js";
import ChartDataLabels from "chartjs-plugin-datalabels";
import ChartDataLabels, { type Context } from "chartjs-plugin-datalabels";
import "chartjs-adapter-dayjs-4/dist/chartjs-adapter-dayjs-4.esm";
import { registerChartComponents, commonOptions } from "../Sessions/chartConfig";
import formatter, { POWER_UNIT } from "../../mixins/formatter";
import colors, { lighterColor } from "../../colors";
import formatter, { POWER_UNIT } from "../../mixins/formatter.ts";
import colors, { lighterColor } from "../../colors.ts";
import {
highestSlotIndexByDay,
ForecastType,
@ -38,6 +42,7 @@ import {
type SolarDetails,
type TimeseriesEntry,
} from "../../utils/forecast.ts";
import type { CURRENCY } from "assets/js/types/evcc.ts";
registerChartComponents([
BarController,
@ -61,7 +66,7 @@ export default defineComponent({
grid: { type: Array as PropType<PriceSlot[]> },
solar: { type: Object as PropType<SolarDetails> },
co2: { type: Array as PropType<PriceSlot[]> },
currency: { type: String as PropType<string> },
currency: { type: String as PropType<CURRENCY> },
selected: { type: String as PropType<ForecastType> },
},
emits: ["selected"],
@ -130,7 +135,7 @@ export default defineComponent({
];
},
chartData() {
const datasets: unknown[] = [];
const datasets = [];
if (this.solarEntries.length > 0) {
const active = this.selected === ForecastType.Solar;
const color = active ? colors.self : colors.border;
@ -239,13 +244,13 @@ export default defineComponent({
},
categoryPercentage: 0.7,
events: ["mousemove", "click", "touchstart", "touchend"],
onHover: function (event, active) {
onHover(event: ChartEvent, active: ActiveElement[], chart: Chart) {
if (["touchend", "click"].includes(event.type)) {
vThis.selectIndex(null, true);
return;
}
const element = active.find(({ datasetIndex }) => {
const { label } = event.chart.getDatasetMeta(datasetIndex);
const { label } = chart.getDatasetMeta(datasetIndex);
return label === vThis.selected;
});
vThis.selectIndex(element ? element.index : null);
@ -253,12 +258,13 @@ export default defineComponent({
plugins: {
...commonOptions.plugins,
datalabels: {
backgroundColor: function (context) {
backgroundColor(context: Context) {
return context.dataset.borderColor;
},
align: function ({ chart, dataset, dataIndex }) {
const { min, max } = chart.scales.x;
const time = new Date(dataset.data[dataIndex].x).getTime();
align({ chart, dataset, dataIndex }: Context) {
const { min, max } = chart.scales["x"];
// @ts-expect-error no-explicit-any
const time = new Date(dataset.data[dataIndex]?.x).getTime();
// percent along the x axis (0: start, 1: end)
const percent = (time - min) / (max - min);
@ -280,8 +286,9 @@ export default defineComponent({
},
anchor: "end",
offset: 8,
padding: function (context) {
padding(context: Context) {
const data = context.dataset.data[context.dataIndex];
// @ts-expect-error no-explicit-any
const x = typeof data.highlight === "number" ? 32 : 8;
return {
x,
@ -291,23 +298,24 @@ export default defineComponent({
borderRadius: 4,
color: colors.background,
font: { weight: "bold" },
formatter: function (data, ctx) {
if (data.highlight) {
switch (ctx.dataset.label) {
// @ts-expect-error no-explicit-any
formatter(value, context: Context) {
if (value.highlight) {
switch (context.dataset.label) {
case ForecastType.Price:
return vThis.fmtPricePerKWh(
data.y,
value.y,
vThis.currency,
true,
true
);
case ForecastType.Co2:
return vThis.fmtGrams(data.y);
return vThis.fmtGrams(value.y);
case ForecastType.Solar:
if (data.highlight === true) {
return vThis.fmtW(data.y, POWER_UNIT.AUTO);
if (value.highlight === true) {
return vThis.fmtW(value.y, POWER_UNIT.AUTO);
} else {
return vThis.fmtWh(data.highlight, POWER_UNIT.AUTO);
return vThis.fmtWh(value.highlight, POWER_UNIT.AUTO);
}
default:
return null;
@ -328,7 +336,8 @@ export default defineComponent({
display: true,
color: colors.border,
offset: false,
lineWidth: function (context) {
// @ts-expect-error no-explicit-any
lineWidth(context) {
if (context.type !== "tick") {
return 0;
}
@ -345,7 +354,7 @@ export default defineComponent({
minRotation: 0,
source: "data",
align: "center",
callback: function (value) {
callback(value: number) {
const date = new Date(value);
const hour = date.getHours();
const minute = date.getMinutes();
@ -401,7 +410,9 @@ export default defineComponent({
}, 1000);
},
beforeUnmount() {
clearTimeout(this.interval);
if (this.interval) {
clearTimeout(this.interval);
}
},
methods: {
updateStartDate() {

View file

@ -65,8 +65,9 @@
<script lang="ts">
import { defineComponent, type PropType } from "vue";
import { ForecastType, type PriceSlot, type SolarDetails } from "../../utils/forecast.ts";
import formatter, { POWER_UNIT } from "../../mixins/formatter";
import formatter, { POWER_UNIT } from "../../mixins/formatter.ts";
import AnimatedNumber from "../Helper/AnimatedNumber.vue";
import type { CURRENCY } from "assets/js/types/evcc.ts";
const LOCALES_WITHOUT_DAY_AFTER_TOMORROW = ["en", "tr"];
export interface Energy {
@ -91,9 +92,9 @@ export default defineComponent({
grid: { type: Array as PropType<PriceSlot[]> },
co2: { type: Array as PropType<PriceSlot[]> },
solar: { type: Object as PropType<SolarDetails> },
currency: { type: String },
currency: { type: String as PropType<CURRENCY> },
},
data: function () {
data() {
return {
now: new Date(),
interval: null as ReturnType<typeof setInterval> | null,
@ -135,11 +136,14 @@ export default defineComponent({
return `${this.weekdayShort(start)} ${this.hourShort(start)} – ${this.hourShort(end)}`;
},
highlightColor() {
const colors = {
[ForecastType.Price]: "text-price",
[ForecastType.Co2]: "text-co2",
};
return colors[this.type];
switch (this.type) {
case ForecastType.Price:
return "text-price";
case ForecastType.Co2:
return "text-co2";
default:
return "";
}
},
},
mounted() {

View file

@ -65,8 +65,9 @@ import {
ForecastType,
adjustedSolar,
} from "../../utils/forecast.ts";
import formatter from "../../mixins/formatter";
import formatter from "../../mixins/formatter.ts";
import settings from "../../settings";
import type { CURRENCY } from "assets/js/types/evcc.ts";
export default defineComponent({
name: "ForecastModal",
components: {
@ -79,9 +80,9 @@ export default defineComponent({
mixins: [formatter],
props: {
forecast: { type: Object as PropType<Forecast>, default: () => ({}) },
currency: { type: String },
currency: { type: String as PropType<CURRENCY> },
},
data: function (): {
data(): {
isModalVisible: boolean;
selectedType: ForecastType;
selectedSlot: PriceSlot | TimeseriesEntry | null;
@ -117,7 +118,7 @@ export default defineComponent({
},
},
watch: {
isModalVisible: function (newVal) {
isModalVisible(newVal) {
if (newVal) {
this.updateSelectedType();
}

View file

@ -40,9 +40,9 @@ export default defineComponent({
},
availableTypes() {
return {
[ForecastType.Solar]: !!this.forecast.solar,
[ForecastType.Price]: !!this.forecast.grid,
[ForecastType.Co2]: !!this.forecast.co2,
[ForecastType.Solar]: !!this.forecast["solar"],
[ForecastType.Price]: !!this.forecast["grid"],
[ForecastType.Co2]: !!this.forecast["co2"],
};
},
typeIcons() {

View file

@ -97,7 +97,7 @@ export default {
props: {
sponsor: Object,
},
data: function () {
data() {
return {
theme: getThemePreference(),
language: getLocalePreference() || "",

View file

@ -48,7 +48,7 @@ export default {
size: String,
},
emits: ["open", "opened", "close", "closed"],
data: function () {
data() {
return {
isModalVisible: false,
};

View file

@ -215,70 +215,70 @@ export default {
};
},
computed: {
vehicle: function () {
vehicle() {
return this.vehicles?.find((v) => v.name === this.vehicleName);
},
vehicleTitle: function () {
vehicleTitle() {
return this.vehicle?.title;
},
loadpointTitle: function () {
loadpointTitle() {
return this.title || this.$t("main.loadpoint.fallbackName");
},
integratedDevice: function () {
integratedDevice() {
return this.chargerFeatureIntegratedDevice;
},
heating: function () {
heating() {
return this.chargerFeatureHeating;
},
phasesProps: function () {
phasesProps() {
return this.collectProps(Phases);
},
modeProps: function () {
modeProps() {
return this.collectProps(Mode);
},
sessionInfoProps: function () {
sessionInfoProps() {
return this.collectProps(SessionInfo);
},
settingsModal: function () {
settingsModal() {
return this.collectProps(SettingsModal);
},
vehicleProps: function () {
vehicleProps() {
return this.collectProps(Vehicle);
},
showChargingIndicator: function () {
showChargingIndicator() {
return this.charging && this.chargePower > 0;
},
vehicleKnown: function () {
vehicleKnown() {
return !!this.vehicleName;
},
vehicleHasSoc: function () {
vehicleHasSoc() {
return this.vehicleKnown && !this.vehicle?.features?.includes("Offline");
},
vehicleNotReachable: function () {
vehicleNotReachable() {
// online vehicle that was not reachable at startup
const features = this.vehicle?.features || [];
return features.includes("Offline") && features.includes("Retryable");
},
planTimeUnreachable: function () {
planTimeUnreachable() {
// 1 minute tolerance
return this.planOverrun > 60;
},
socBasedCharging: function () {
socBasedCharging() {
return this.vehicleHasSoc || this.vehicleSoc > 0;
},
socBasedPlanning: function () {
socBasedPlanning() {
return this.socBasedCharging && this.vehicle?.capacity > 0;
},
pvPossible: function () {
pvPossible() {
return this.pvConfigured || this.gridConfigured;
},
hasSmartCost: function () {
hasSmartCost() {
return smartCostAvailable(this.smartCostType);
},
batteryBoostAvailable: function () {
batteryBoostAvailable() {
return this.batteryConfigured && this.$hiddenFeatures();
},
batteryBoostActive: function () {
batteryBoostActive() {
return this.batteryBoost && this.charging && !["off", "now"].includes(this.mode);
},
},
@ -317,25 +317,25 @@ export default {
this.chargeRemainingDurationInterpolated--;
}
},
apiPath: function (func) {
apiPath(func) {
return "loadpoints/" + this.id + "/" + func;
},
setTargetMode: function (mode) {
setTargetMode(mode) {
api.post(this.apiPath("mode") + "/" + mode);
},
setLimitSoc: function (soc) {
setLimitSoc(soc) {
api.post(this.apiPath("limitsoc") + "/" + soc);
},
setLimitEnergy: function (kWh) {
setLimitEnergy(kWh) {
api.post(this.apiPath("limitenergy") + "/" + kWh);
},
setMaxCurrent: function (maxCurrent) {
setMaxCurrent(maxCurrent) {
api.post(this.apiPath("maxcurrent") + "/" + maxCurrent);
},
setMinCurrent: function (minCurrent) {
setMinCurrent(minCurrent) {
api.post(this.apiPath("mincurrent") + "/" + minCurrent);
},
setPhasesConfigured: function (phases) {
setPhasesConfigured(phases) {
api.post(this.apiPath("phases") + "/" + phases);
},
changeVehicle(name) {
@ -344,7 +344,7 @@ export default {
removeVehicle() {
api.delete(this.apiPath("vehicle"));
},
setBatteryBoost: function (batteryBoost) {
setBatteryBoost(batteryBoost) {
api.post(this.apiPath("batteryboost") + `/${batteryBoost ? "1" : "0"}`);
},
fmtPower(value) {

View file

@ -80,7 +80,7 @@ export default {
return { snapTimeout: null, scrollTimeout: null, highlightedIndex: 0 };
},
watch: {
selectedIndex: function (newIndex) {
selectedIndex(newIndex) {
this.scrollTo(newIndex);
},
},

View file

@ -25,7 +25,7 @@ export default {
emits: ["updated"],
computed: {
modes: function () {
modes() {
if (this.pvPossible) {
return ["off", "pv", "minpv", "now"];
}
@ -36,7 +36,7 @@ export default {
},
},
methods: {
label: function (mode) {
label(mode) {
// rename pv mode to smart for non-pv and dynamic tariffs scenarios
// TODO: rollout smart name for everyting later
if (mode === "pv" && !this.pvPossible && this.hasSmartCost) {
@ -44,10 +44,10 @@ export default {
}
return this.$t(`main.mode.${mode}`);
},
isActive: function (mode) {
isActive(mode) {
return this.mode === mode;
},
setTargetMode: function (mode) {
setTargetMode(mode) {
this.$emit("updated", mode);
},
},

View file

@ -25,9 +25,9 @@
<script>
import LabelAndValue from "../Helper/LabelAndValue.vue";
import formatter from "../../mixins/formatter.js";
import CustomSelect from "../Helper/CustomSelect.vue";
import { getSessionInfo, setSessionInfo } from "./sessionInfo.js";
import formatter from "../../mixins/formatter.ts";
import { getSessionInfo, setSessionInfo } from "./session.ts";
export default {
name: "LoadpointSessionInfo",
@ -54,7 +54,7 @@ export default {
};
},
computed: {
options: function () {
options() {
const result = [
{
key: "remaining",

View file

@ -0,0 +1,12 @@
import settings from "../../settings.js";
export function getSessionInfo(index: number, fallback: string) {
return settings.sessionInfo[index - 1] || fallback;
}
export function setSessionInfo(index: number, value: string) {
const clone = [...settings.sessionInfo];
clone[index - 1] = value;
clone.map((v) => v || "");
settings.sessionInfo = clone;
}

View file

@ -1,12 +0,0 @@
import settings from "../../settings.js";
export function getSessionInfo(index, fallback) {
return settings.sessionInfo[index - 1] || fallback;
}
export function setSessionInfo(index, value) {
const clone = [...settings.sessionInfo];
clone[index - 1] = value;
clone.map((v) => v || "");
settings.sessionInfo = clone;
}

View file

@ -33,7 +33,7 @@ export default {
size: { type: String, default: "s" },
},
computed: {
icon: function () {
icon() {
return this.count > 9 ? Plus : icons[`_${this.count}`];
},
},

View file

@ -319,7 +319,7 @@ export default {
this.selectedRegion = region;
settings.savingsRegion = region;
},
updateReferenceGrid: async function () {
async updateReferenceGrid() {
try {
const res = await api.get(`tariff/grid`, {
validateStatus: (status) => status >= 200 && status < 500,

View file

@ -93,7 +93,7 @@ export default {
},
},
methods: {
surprise: function () {
surprise() {
const $el = this.$refs.confetti;
const angle = 45 + Math.random() * 90;
const drift = 0;

View file

@ -276,7 +276,7 @@ export default {
},
labelColor: tooltipLabelColor(false),
},
itemSort: function (a, b) {
itemSort(a, b) {
return b.datasetIndex - a.datasetIndex;
},
},
@ -288,7 +288,7 @@ export default {
grid: { display: false },
ticks: {
color: colors.muted,
callback: function (value) {
callback(value) {
return vThis.period === PERIODS.YEAR
? vThis.fmtMonth(new Date(vThis.year, value, 1), true)
: this.getLabelForValue(value);

View file

@ -193,13 +193,13 @@ export default {
: null;
},
labelColor: tooltipLabelColor(false),
labelPointStyle: function () {
labelPointStyle() {
return {
pointStyle: "circle",
};
},
},
itemSort: function (a, b) {
itemSort(a, b) {
return b.datasetIndex - a.datasetIndex;
},
},
@ -211,7 +211,7 @@ export default {
grid: { display: false },
ticks: {
color: colors.muted,
callback: function (value) {
callback(value) {
return vThis.period === PERIODS.YEAR
? vThis.fmtMonth(new Date(vThis.year, value, 1), true)
: this.getLabelForValue(value);

View file

@ -215,23 +215,23 @@ export default {
},
emits: ["session-changed"],
computed: {
chargedEnergy: function () {
chargedEnergy() {
return this.session.chargedEnergy * 1e3;
},
avgPower: function () {
avgPower() {
const hours = this.session.chargeDuration / 1e9 / 3600;
return this.chargedEnergy / hours;
},
solarEnergy: function () {
solarEnergy() {
return this.chargedEnergy * (this.session.solarPercentage / 100);
},
vehicleOptions: function () {
vehicleOptions() {
return this.vehicles.map((v) => ({
name: v.title,
title: v.title,
}));
},
loadpointOptions: function () {
loadpointOptions() {
return this.loadpoints.map((loadpoint) => ({
value: loadpoint,
name: loadpoint,
@ -249,7 +249,7 @@ export default {
);
modal.show();
},
formatKm: function (value) {
formatKm(value) {
return `${this.fmtNumber(distanceValue(value), 0)} ${distanceUnit()}`;
},
async changeVehicle(title) {

View file

@ -134,22 +134,22 @@ export default {
forecast: Object,
},
computed: {
batteryConfigured: function () {
batteryConfigured() {
return this.battery?.length > 0;
},
pvConfigured: function () {
pvConfigured() {
return this.pv?.length > 0;
},
gridPower: function () {
gridPower() {
return this.grid?.power || 0;
},
energyflow: function () {
energyflow() {
return this.collectProps(Energyflow);
},
loadpointTitles: function () {
loadpointTitles() {
return this.loadpoints.map((lp) => lp.title);
},
loadpointsCompact: function () {
loadpointsCompact() {
return this.loadpoints.map((lp) => {
const vehicleIcon = this.vehicles?.[lp.vehicleName]?.icon;
const icon = lp.chargerIcon || vehicleIcon || "car";
@ -158,22 +158,22 @@ export default {
return { icon, charging, power };
});
},
vehicleList: function () {
vehicleList() {
const vehicles = this.vehicles || {};
return Object.entries(vehicles).map(([name, vehicle]) => ({ name, ...vehicle }));
},
topNavigation: function () {
topNavigation() {
const vehicleLogins = this.auth ? this.auth.vehicles : {};
return { vehicleLogins, ...this.collectProps(Navigation) };
},
showParkingLot: function () {
showParkingLot() {
// work in progess
return false;
},
isInitialSetup: function () {
isInitialSetup() {
return this.loadpoints.length === 0;
},
footer: function () {
footer() {
return {
version: {
installed: window.evcc.version,

View file

@ -101,7 +101,7 @@ export default {
multipleLoadpoints: Boolean,
possible: Boolean,
},
data: function () {
data() {
return {
selectedSmartCostLimit: null,
tariff: null,
@ -256,7 +256,7 @@ export default {
this.isCo2 ? this.fmtCo2Medium(limit) : this.fmtPricePerKWh(limit, this.currency)
}`;
},
updateTariff: async function () {
async updateTariff() {
try {
this.tariff = (await api.get(`tariff/planner`)).data.result;
this.startTime = new Date();

View file

@ -39,7 +39,7 @@ export default {
title: String,
},
computed: {
topNavigation: function () {
topNavigation() {
const vehicleLogins = store.state.auth ? store.state.auth.vehicles : {};
return { vehicleLogins, ...this.collectProps(Navigation, store.state) };
},

View file

@ -162,7 +162,7 @@ export default {
};
},
computed: {
batteryConfigured: function () {
batteryConfigured() {
return this.battery?.length;
},
logoutCount() {
@ -211,7 +211,7 @@ export default {
this.dropdown?.dispose();
},
methods: {
handleProviderAuthorization: async function (provider) {
async handleProviderAuthorization(provider) {
if (!provider.loggedIn) {
baseAPI.post(provider.loginPath).then(function (response) {
window.location.href = response.data.loginUri;

View file

@ -98,21 +98,21 @@ export default {
loadpointTitles: Array,
},
computed: {
iconVisible: function () {
iconVisible() {
return this.notifications.length > 0;
},
iconClass: function () {
iconClass() {
return this.notifications.find((m) => m.level === "error")
? "text-danger"
: "text-warning";
},
},
created: function () {
created() {
this.interval = setInterval(() => {
this.$forceUpdate();
}, 10 * 1000);
},
unmounted: function () {
unmounted() {
clearTimeout(this.interval);
},
methods: {
@ -124,7 +124,7 @@ export default {
}
return lines;
},
clear: function () {
clear() {
window.app?.clear();
},
},

View file

@ -95,16 +95,16 @@ export default {
size: { type: String, default: "s" },
},
computed: {
uniqueNames: function () {
uniqueNames() {
return [...new Set(this.names || [this.name])];
},
count: function () {
count() {
return this.names?.length || 0;
},
single: function () {
single() {
return this.uniqueNames.length == 1;
},
singleIcon: function () {
singleIcon() {
return icons[this.uniqueNames[0]] || `shopicon-regular-car3`;
},
},

View file

@ -51,7 +51,7 @@ export default {
},
emits: ["limit-energy-updated"],
computed: {
options: function () {
options() {
return energyOptions(
this.chargedEnergy,
this.capacity || 100,
@ -64,18 +64,18 @@ export default {
step() {
return optionStep(this.capacity || 100);
},
estimated: function () {
estimated() {
return estimatedSoc(this.limitEnergy, this.socPerKwh);
},
},
methods: {
change: function (e) {
change(e) {
return this.$emit("limit-energy-updated", parseFloat(e.target.value));
},
fmtEnergy: function (value) {
fmtEnergy(value) {
return fmtEnergy(value, this.step, this.fmtWh, this.$t("main.targetEnergy.noLimit"));
},
fmtSoc: function (value) {
fmtSoc(value) {
return `+${this.fmtPercentage(value)}`;
},
},

View file

@ -36,7 +36,7 @@ export default {
},
emits: ["limit-soc-updated"],
computed: {
options: function () {
options() {
const result = [];
for (let soc = 20; soc <= 100; soc += this.step) {
const text = this.fmtSocOption(soc, this.rangePerSoc, distanceUnit(), this.heating);
@ -44,32 +44,32 @@ export default {
}
return result;
},
step: function () {
step() {
return this.heating ? 1 : 5;
},
title: function () {
title() {
return this.heating
? this.$t("main.vehicle.tempLimit")
: this.$t("main.vehicle.targetSoc");
},
estimatedTargetRange: function () {
estimatedTargetRange() {
return this.estimatedRange(this.limitSoc);
},
},
methods: {
change: function (e) {
change(e) {
return this.$emit("limit-soc-updated", parseInt(e.target.value, 10));
},
estimatedRange: function (soc) {
estimatedRange(soc) {
if (this.rangePerSoc) {
return Math.round(soc * this.rangePerSoc);
}
return null;
},
formatSoc: function (value) {
formatSoc(value) {
return this.heating ? this.fmtTemperature(value) : this.fmtPercentage(value);
},
formatKm: function (value) {
formatKm(value) {
return `${this.fmtNumber(value, 0)} ${distanceUnit()}`;
},
},

View file

@ -94,7 +94,7 @@ export default {
socBasedPlanning: Boolean,
},
emits: ["limit-soc-drag", "limit-soc-updated", "plan-clicked"],
data: function () {
data() {
return {
selectedLimitSoc: null,
interactionStartScreenY: null,
@ -103,10 +103,10 @@ export default {
};
},
computed: {
step: function () {
step() {
return this.heating ? 1 : 5;
},
vehicleSocDisplayWidth: function () {
vehicleSocDisplayWidth() {
if (this.socBasedCharging) {
if (this.vehicleSoc >= 0) {
return this.vehicleSoc;
@ -119,19 +119,19 @@ export default {
return 100;
}
},
transition: function () {
transition() {
if (this.dragging) {
return { transition: "none" };
}
return { transition: "width var(--evcc-transition-fast) linear" };
},
maxEnergy: function () {
maxEnergy() {
return Math.max(this.planEnergy, this.limitEnergy, this.chargedEnergy / 1e3);
},
vehicleLimitSocActive: function () {
vehicleLimitSocActive() {
return this.vehicleLimitSoc > 0 && this.vehicleLimitSoc > this.vehicleSoc;
},
planMarkerPosition: function () {
planMarkerPosition() {
if (this.socBasedPlanning) {
return this.effectivePlanSoc;
}
@ -141,14 +141,14 @@ export default {
}
return 0;
},
planMarkerAvailable: function () {
planMarkerAvailable() {
if (this.socBasedCharging && !this.socBasedPlanning) {
// mixed mode (% limit and kWh plan): hide marker
return false;
}
return this.planMarkerPosition > 0;
},
energyLimitMarkerPosition: function () {
energyLimitMarkerPosition() {
if (this.socBasedCharging) {
return null;
}
@ -157,7 +157,7 @@ export default {
}
return 100;
},
energyLimitMarkerActive: function () {
energyLimitMarkerActive() {
if (this.socBasedCharging) {
return false;
}
@ -166,21 +166,21 @@ export default {
}
return true;
},
sliderActive: function () {
sliderActive() {
const isBelowVehicleLimit = this.visibleLimitSoc <= (this.vehicleLimitSoc || 100);
const isAbovePlanLimit = this.visibleLimitSoc >= (this.effectivePlanSoc || 0);
return isBelowVehicleLimit && isAbovePlanLimit;
},
progressColor: function () {
progressColor() {
if (this.minSocActive) {
return "bg-danger";
}
return "bg-primary";
},
minSocActive: function () {
minSocActive() {
return this.minSoc > 0 && this.vehicleSoc < this.minSoc;
},
remainingSocWidth: function () {
remainingSocWidth() {
if (this.socBasedCharging) {
if (this.vehicleSocDisplayWidth === 100) {
return null;
@ -201,27 +201,27 @@ export default {
return null;
},
visibleLimitSoc: function () {
visibleLimitSoc() {
return Number(this.selectedLimitSoc || this.effectiveLimitSoc);
},
},
watch: {
effectiveLimitSoc: function () {
effectiveLimitSoc() {
this.selectedLimitSoc = this.effectiveLimitSoc;
},
vehicleLimitSoc: function () {
vehicleLimitSoc() {
this.updateTooltip();
},
},
mounted: function () {
mounted() {
this.updateTooltip();
},
methods: {
changeLimitSocStart: function (e) {
changeLimitSocStart(e) {
this.dragging = true;
e.stopPropagation();
},
changeLimitSocEnd: function (e) {
changeLimitSocEnd(e) {
this.dragging = false;
const value = parseInt(e.target.value, 10);
// value changed
@ -229,7 +229,7 @@ export default {
this.$emit("limit-soc-updated", value);
}
},
movedLimitSoc: function (e) {
movedLimitSoc(e) {
const value = parseInt(e.target.value, 10);
e.stopPropagation();
const minLimit = 20;
@ -244,7 +244,7 @@ export default {
this.$emit("limit-soc-drag", this.selectedLimitSoc);
return true;
},
updateTooltip: function () {
updateTooltip() {
if (!this.tooltip) {
this.tooltip = new Tooltip(this.$refs.vehicleLimitSoc);
}

View file

@ -735,7 +735,7 @@ export default {
this.$refs.disconnectRequired
);
},
updateTooltip: function (instance, content, ref, hoverOnly = false) {
updateTooltip(instance, content, ref, hoverOnly = false) {
if (!content || !ref) {
if (instance) {
instance.dispose();

View file

@ -76,7 +76,7 @@ export default {
title: String,
},
emits: ["change-vehicle", "remove-vehicle"],
data: function () {
data() {
return {
refreshTooltip: null,
notReachableTooltip: null,
@ -107,16 +107,16 @@ export default {
showOptions() {
return this.vehicleKnown || this.vehicles.length;
},
vehicleOptionsProps: function () {
vehicleOptionsProps() {
return this.collectProps(Options);
},
},
watch: {
iconType: function () {
iconType() {
this.initTooltip();
},
},
mounted: function () {
mounted() {
this.initTooltip();
},
methods: {

View file

@ -151,31 +151,31 @@ export default {
};
},
computed: {
title: function () {
title() {
return this.vehicle?.title || "";
},
capacity: function () {
capacity() {
return this.vehicle?.capacity || 0;
},
icon: function () {
icon() {
return this.vehicle?.icon || "";
},
minSoc: function () {
minSoc() {
return this.vehicle?.minSoc || 0;
},
vehicleSocProps: function () {
vehicleSocProps() {
return this.collectProps(Soc);
},
vehicleStatus: function () {
vehicleStatus() {
return this.collectProps(Status);
},
vehicleTitleProps: function () {
vehicleTitleProps() {
return this.collectProps(Title);
},
chargingPlan: function () {
chargingPlan() {
return this.collectProps(ChargingPlan);
},
formattedSoc: function () {
formattedSoc() {
if (!this.vehicleSoc) {
return "--";
}
@ -184,55 +184,55 @@ export default {
}
return this.fmtPercentage(this.vehicleSoc);
},
vehicleSocTitle: function () {
vehicleSocTitle() {
if (this.heating) {
return this.$t("main.vehicle.temp");
}
return this.$t("main.vehicle.vehicleSoc");
},
range: function () {
range() {
return distanceValue(this.vehicleRange);
},
rangeUnit: function () {
rangeUnit() {
return distanceUnit();
},
rangePerSoc: function () {
rangePerSoc() {
if (this.vehicleSoc > 10 && this.range) {
return Math.round((this.range / this.vehicleSoc) * 1e2) / 1e2;
}
return null;
},
socPerKwh: function () {
socPerKwh() {
if (this.capacity > 0) {
return 100 / this.capacity;
}
return null;
},
chargedSoc: function () {
chargedSoc() {
const value = this.socPerKwh * (this.chargedEnergy / 1e3);
return value > 1 ? `+${this.fmtPercentage(value)}` : null;
},
chargingPlanDisabled: function () {
chargingPlanDisabled() {
return ["off", "now"].includes(this.mode);
},
smartCostDisabled: function () {
smartCostDisabled() {
return ["off", "now"].includes(this.mode);
},
},
watch: {
effectiveLimitSoc: function () {
effectiveLimitSoc() {
this.displayLimitSoc = this.effectiveLimitSoc;
},
},
methods: {
limitSocDrag: function (limitSoc) {
limitSocDrag(limitSoc) {
this.displayLimitSoc = limitSoc;
},
limitSocUpdated: function (limitSoc) {
limitSocUpdated(limitSoc) {
this.displayLimitSoc = limitSoc;
this.$emit("limit-soc-updated", limitSoc);
},
limitEnergyUpdated: function (limitEnergy) {
limitEnergyUpdated(limitEnergy) {
this.$emit("limit-energy-updated", limitEnergy);
},
changeVehicle(name) {

View file

@ -1,7 +1,7 @@
export default {
methods: {
// collect all target component properties from current instance
collectProps: function (component, state) {
collectProps(component, state) {
let data = {};
for (var p in component.props) {
// check in optional state

View file

@ -1,418 +0,0 @@
// list of currencies where energy price should be displayed in subunits (factor 100)
const ENERGY_PRICE_IN_SUBUNIT = {
AUD: "c", // Australian cent
BGN: "st", // Bulgarian stotinka
BRL: "¢", // Brazilian centavo
CAD: "¢", // Canadian cent
CHF: "rp", // Swiss Rappen
CNY: "f", // Chinese fen
EUR: "ct", // Euro cent
GBP: "p", // GB pence
ILS: "ag", // Israeli agora
NZD: "c", // New Zealand cent
PLN: "gr", // Polish grosz
USD: "¢", // US cent
};
export const POWER_UNIT = Object.freeze({
W: "W",
KW: "kW",
MW: "MW",
AUTO: "",
});
export default {
data: function () {
return {
POWER_UNIT,
fmtLimit: 100,
fmtDigits: 1,
};
},
methods: {
round: function (num, precision) {
var base = 10 ** precision;
return (Math.round(num * base) / base).toFixed(precision);
},
fmt: function (val) {
if (val === undefined || val === null) {
return 0;
}
let absVal = Math.abs(val);
return absVal >= this.fmtLimit
? this.round(absVal / 1e3, this.fmtDigits)
: this.round(absVal, 0);
},
fmtW: function (watt = 0, format = POWER_UNIT.KW, withUnit = true, digits) {
let unit = format;
let d = digits;
if (POWER_UNIT.AUTO === unit) {
if (watt >= 10_000_000) {
unit = POWER_UNIT.MW;
} else if (watt >= 1000 || 0 === watt) {
unit = POWER_UNIT.KW;
} else {
unit = POWER_UNIT.W;
}
}
let value = watt;
if (POWER_UNIT.KW === unit) {
value = watt / 1000;
} else if (POWER_UNIT.MW === unit) {
value = watt / 1_000_000;
}
if (d === undefined) {
d = POWER_UNIT.KW === unit || POWER_UNIT.MW === unit || 0 === watt ? 1 : 0;
}
return `${new Intl.NumberFormat(this.$i18n?.locale, {
style: "decimal",
minimumFractionDigits: d,
maximumFractionDigits: d,
}).format(value)}${withUnit ? ` ${unit}` : ""}`;
},
fmtWh: function (watt, format = POWER_UNIT.KW, withUnit = true, digits) {
return this.fmtW(watt, format, withUnit, digits) + (withUnit ? "h" : "");
},
fmtNumber: function (number, decimals, unit) {
const style = unit ? "unit" : "decimal";
return new Intl.NumberFormat(this.$i18n?.locale, {
style,
unit,
minimumFractionDigits: decimals,
maximumFractionDigits: decimals,
}).format(number);
},
fmtGrams: function (gramms, withUnit = true) {
let unit = "gram";
let value = gramms;
if (gramms >= 1000) {
unit = "kilogram";
value = gramms / 1000;
}
return new Intl.NumberFormat(this.$i18n?.locale, {
style: withUnit ? "unit" : "decimal",
unit,
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
},
fmtCo2Short: function (gramms) {
return `${this.fmtNumber(gramms, 0)} g`;
},
fmtCo2Medium: function (gramms) {
return `${this.fmtNumber(gramms, 0)} g/kWh`;
},
fmtCo2Long: function (gramms) {
return `${this.fmtNumber(gramms, 0)} gCO₂e/kWh`;
},
fmtUnit: function (val) {
return Math.abs(val) >= this.fmtLimit ? "k" : "";
},
fmtNumberToLocale(val, pad = 0) {
return val.toLocaleString(this.$i18n?.locale).padStart(pad, "0");
},
fmtDurationToTime(date) {
const diff = date - new Date();
return this.fmtDuration(diff / 1000, true, "h");
},
fmtDurationNs(duration = 0, withUnit = true, minUnit = "s") {
return this.fmtDuration(duration / 1e9, withUnit, minUnit);
},
fmtDuration: function (duration = 0, withUnit = true, minUnit = "s") {
if (duration <= 0) {
return "—";
}
let roundedDuration = Math.round(duration);
var seconds = roundedDuration % 60;
var minutes = Math.floor(roundedDuration / 60) % 60;
var hours = Math.floor(roundedDuration / 3600);
var result = "";
let unit = "";
if (hours >= 1 || minUnit === "h") {
result = `${this.fmtNumberToLocale(hours)}:${this.fmtNumberToLocale(minutes, 2)}`;
unit = "h";
} else if (minutes >= 1 || minUnit === "m") {
result = `${this.fmtNumberToLocale(minutes)}:${this.fmtNumberToLocale(seconds, 2)}`;
unit = "m";
} else {
result = `${this.fmtNumberToLocale(seconds)}`;
unit = "s";
}
if (withUnit) {
result += `\u202F${unit}`;
}
return result;
},
fmtDayString: function (date) {
const YY = `${date.getFullYear()}`;
const MM = `${date.getMonth() + 1}`.padStart(2, "0");
const DD = `${date.getDate()}`.padStart(2, "0");
return `${YY}-${MM}-${DD}`;
},
fmtTimeString: function (date) {
const HH = `${date.getHours()}`.padStart(2, "0");
const mm = `${date.getMinutes()}`.padStart(2, "0");
return `${HH}:${mm}`;
},
isToday: function (date) {
const today = new Date();
return today.toDateString() === date.toDateString();
},
isTomorrow: function (date) {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
return tomorrow.toDateString() === date.toDateString();
},
weekdayPrefix: function (date) {
if (this.isToday(date)) {
return "";
}
if (this.isTomorrow(date)) {
try {
const rtf = new Intl.RelativeTimeFormat(this.$i18n?.locale, { numeric: "auto" });
return rtf.formatToParts(1, "day")[0].value;
} catch (e) {
console.warn("weekdayPrefix: Intl.RelativeTimeFormat not supported", e);
return "tomorrow";
}
}
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: "short",
}).format(date);
},
weekdayTime: function (date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: "short",
hour: "numeric",
minute: "numeric",
}).format(date);
},
hourShort: function (date) {
const locale = this.$i18n?.locale;
// special: use shorter german format
if (locale === "de") return date.getHours();
return new Intl.DateTimeFormat(locale, {
hour: "numeric",
}).format(date);
},
weekdayShort: function (date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: "short",
}).format(date);
},
fmtAbsoluteDate: function (date) {
const weekday = this.weekdayPrefix(date);
const hour = new Intl.DateTimeFormat(this.$i18n?.locale, {
hour: "numeric",
minute: "numeric",
}).format(date);
return `${weekday} ${hour}`.trim();
},
fmtFullDateTime: function (date, short) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: short ? undefined : "short",
month: short ? "numeric" : "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
}).format(date);
},
fmtWeekdayTime: function (date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: "short",
hour: "numeric",
minute: "numeric",
}).format(date);
},
fmtMonthYear: function (date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
month: "long",
year: "numeric",
}).format(date);
},
fmtMonth: function (date, short) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
month: short ? "short" : "long",
}).format(date);
},
fmtYear: function (date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
year: "numeric",
}).format(date);
},
fmtDayMonthYear: function (date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
day: "numeric",
month: "long",
year: "numeric",
}).format(date);
},
fmtDayMonth: function (date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: "short",
day: "numeric",
month: "short",
}).format(date);
},
fmtDayOfMonth: function (date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: "short",
day: "numeric",
}).format(date);
},
fmtDurationUnit: function (value, unit = "second") {
return new Intl.NumberFormat(this.$i18n?.locale, {
style: "unit",
unit,
unitDisplay: "long",
})
.formatToParts(value)
.find((part) => part.type === "unit").value;
},
fmtMoney: function (amout = 0, currency = "EUR", decimals = true, withSymbol = false) {
const currencyDisplay = withSymbol ? "narrowSymbol" : "code";
const digits = decimals ? undefined : 0;
const result = new Intl.NumberFormat(this.$i18n?.locale, {
style: "currency",
currency,
currencyDisplay,
minimumFractionDigits: digits,
maximumFractionDigits: digits,
}).format(amout);
return withSymbol ? result : result.replace(currency, "").trim();
},
fmtCurrencySymbol: function (currency = "EUR") {
const symbols = { EUR: "€", USD: "$" };
return symbols[currency] || currency;
},
fmtPricePerKWh: function (amout = 0, currency = "EUR", short = false, withUnit = true) {
let value = amout;
let minimumFractionDigits = 1;
let maximumFractionDigits = 3;
if (ENERGY_PRICE_IN_SUBUNIT[currency]) {
value *= 100;
minimumFractionDigits = 1;
maximumFractionDigits = 1;
}
const price = new Intl.NumberFormat(this.$i18n?.locale, {
style: "decimal",
minimumFractionDigits,
maximumFractionDigits,
}).format(value);
if (withUnit) {
return `${price} ${this.pricePerKWhUnit(currency, short)}`;
}
return price;
},
timezone: function () {
return Intl?.DateTimeFormat?.().resolvedOptions?.().timeZone || "UTC";
},
pricePerKWhUnit: function (currency = "EUR", short = false) {
const unit = ENERGY_PRICE_IN_SUBUNIT[currency] || currency;
return `${unit}${short ? "" : "/kWh"}`;
},
fmtTimeAgo: function (elapsed) {
const units = {
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
second: 1000,
};
// "Math.abs" accounts for both "past" & "future" scenarios
for (var u in units)
if (Math.abs(elapsed) > units[u] || u == "second") {
try {
const rtf = new Intl.RelativeTimeFormat(this.$i18n?.locale, { numeric: "auto" });
return rtf.format(Math.round(elapsed / units[u]), u);
} catch (e) {
console.warn("fmtTimeAgo: Intl.RelativeTimeFormat not supported", e);
return `${elapsed} ${u}s ago`;
}
}
},
fmtSocOption: function (soc, rangePerSoc, distanceUnit, heating) {
let result = heating ? this.fmtTemperature(soc) : `${this.fmtPercentage(soc)}`;
if (rangePerSoc && distanceUnit) {
const range = soc * rangePerSoc;
result += ` (${this.fmtNumber(range, 0)} ${distanceUnit})`;
}
return result;
},
fmtPercentage: function (value, digits = 0, forceSign = false) {
const sign = forceSign && value > 0 ? "+" : "";
return `${sign}${new Intl.NumberFormat(this.$i18n?.locale, {
style: "percent",
minimumFractionDigits: digits,
maximumFractionDigits: digits,
}).format(value / 100)}`;
},
hasLeadingPercentageSign: function () {
return ["tr", "ar"].includes(this.$i18n?.locale);
},
fmtTemperature: function (value) {
// TODO: handle fahrenheit
return this.fmtNumber(value, 1, "celsius");
},
getWeekdaysList: function (weekdayFormat) {
const { format } = new Intl.DateTimeFormat(this.$i18n?.locale, { weekday: weekdayFormat });
const mondayToSaturday = [7, 8, 9, 10, 11, 12].map((day, index) => {
return { name: format(new Date(Date.UTC(2021, 5, day))), value: index + 1 };
});
const sunday = { name: format(new Date(Date.UTC(2021, 5, 6))), value: 0 };
return [...mondayToSaturday, sunday];
},
getShortenedWeekdaysLabel: function (selectedWeekdays) {
if (0 === selectedWeekdays.length) {
return "–";
}
const weekdays = this.getWeekdaysList("short");
let label = "";
// the week in the input-parameter starts with 0 for sunday and ends with 6 for saturday
// this algorithms works only if the week starts with 1 for monday and ends with 7 for sunday because
// then we are able to count from 1 to 7 by incrementing the number
// so we have to transform the input accordingly
const selectedWeekdaysTransformed = selectedWeekdays.map(function (dayIndex) {
return 0 === dayIndex ? 7 : dayIndex;
});
function getWeekdayName(dayIndex) {
return weekdays.find((day) => day.value === (7 === dayIndex ? 0 : dayIndex)).name;
}
let maxWeekday = Math.max(...selectedWeekdaysTransformed);
for (let weekdayRangeStart = 1; weekdayRangeStart < 8; weekdayRangeStart++) {
if (selectedWeekdaysTransformed.includes(weekdayRangeStart)) {
label += getWeekdayName(weekdayRangeStart);
let weekdayRangeEnd = weekdayRangeStart;
while (selectedWeekdaysTransformed.includes(weekdayRangeEnd + 1)) {
weekdayRangeEnd++;
}
if (weekdayRangeEnd - weekdayRangeStart > 1) {
// more than 2 consecutive weekdays selected
label += " – " + getWeekdayName(weekdayRangeEnd);
weekdayRangeStart = weekdayRangeEnd;
if (maxWeekday !== weekdayRangeEnd) {
label += ", ";
}
} else if (weekdayRangeStart !== weekdayRangeEnd) {
// exactly 2 consecutive weekdays selected
label += ", ";
} else {
// exactly 1 single day selected
if (maxWeekday !== weekdayRangeEnd) {
label += ", ";
}
}
}
}
return label;
},
},
};

View file

@ -0,0 +1,394 @@
import { defineComponent } from "vue";
import { CURRENCY } from "../types/evcc";
// list of currencies where energy price should be displayed in subunits (factor 100)
const ENERGY_PRICE_IN_SUBUNIT = {
AUD: "c", // Australian cent
BGN: "st", // Bulgarian stotinka
BRL: "¢", // Brazilian centavo
CAD: "¢", // Canadian cent
CHF: "rp", // Swiss Rappen
CNY: "f", // Chinese fen
EUR: "ct", // Euro cent
GBP: "p", // GB pence
ILS: "ag", // Israeli agora
NZD: "c", // New Zealand cent
PLN: "gr", // Polish grosz
USD: "¢", // US cent
};
export enum POWER_UNIT {
W = "W",
KW = "kW",
MW = "MW",
AUTO = "",
}
export default defineComponent({
data() {
return {
POWER_UNIT,
fmtLimit: 100,
fmtDigits: 1,
};
},
methods: {
round(num: number, precision: number) {
const base = 10 ** precision;
return (Math.round(num * base) / base).toFixed(precision);
},
fmtW(watt = 0, format = POWER_UNIT.KW, withUnit = true, digits?: number) {
let unit = format;
let d = digits;
if (POWER_UNIT.AUTO === unit) {
if (watt >= 10_000_000) {
unit = POWER_UNIT.MW;
} else if (watt >= 1000 || 0 === watt) {
unit = POWER_UNIT.KW;
} else {
unit = POWER_UNIT.W;
}
}
let value = watt;
if (POWER_UNIT.KW === unit) {
value = watt / 1000;
} else if (POWER_UNIT.MW === unit) {
value = watt / 1_000_000;
}
if (d === undefined) {
d = POWER_UNIT.KW === unit || POWER_UNIT.MW === unit || 0 === watt ? 1 : 0;
}
return `${new Intl.NumberFormat(this.$i18n?.locale, {
style: "decimal",
minimumFractionDigits: d,
maximumFractionDigits: d,
}).format(value)}${withUnit ? ` ${unit}` : ""}`;
},
fmtWh(watt: number, format = POWER_UNIT.KW, withUnit = true, digits?: number) {
return this.fmtW(watt, format, withUnit, digits) + (withUnit ? "h" : "");
},
fmtNumber(number: number, decimals: number, unit?: string) {
const style = unit ? "unit" : "decimal";
return new Intl.NumberFormat(this.$i18n?.locale, {
style,
unit,
minimumFractionDigits: decimals,
maximumFractionDigits: decimals,
}).format(number);
},
fmtGrams(gramms: number, withUnit = true) {
let unit = "gram";
let value = gramms;
if (gramms >= 1000) {
unit = "kilogram";
value = gramms / 1000;
}
return new Intl.NumberFormat(this.$i18n?.locale, {
style: withUnit ? "unit" : "decimal",
unit,
minimumFractionDigits: 0,
maximumFractionDigits: 0,
}).format(value);
},
fmtCo2Short(gramms: number) {
return `${this.fmtNumber(gramms, 0)} g`;
},
fmtCo2Medium(gramms: number) {
return `${this.fmtNumber(gramms, 0)} g/kWh`;
},
fmtCo2Long(gramms: number) {
return `${this.fmtNumber(gramms, 0)} gCO₂e/kWh`;
},
fmtNumberToLocale(val: number, pad = 0) {
return val.toLocaleString(this.$i18n?.locale).padStart(pad, "0");
},
fmtDurationToTime(date: Date) {
const diff = date.getTime() - new Date().getTime();
return this.fmtDuration(diff / 1000, true, "h");
},
fmtDurationNs(duration = 0, withUnit = true, minUnit = "s") {
return this.fmtDuration(duration / 1e9, withUnit, minUnit);
},
fmtDuration(duration = 0, withUnit = true, minUnit = "s") {
if (duration <= 0) {
return "—";
}
const roundedDuration = Math.round(duration);
const seconds = roundedDuration % 60;
const minutes = Math.floor(roundedDuration / 60) % 60;
const hours = Math.floor(roundedDuration / 3600);
let result = "";
let unit = "";
if (hours >= 1 || minUnit === "h") {
result = `${this.fmtNumberToLocale(hours)}:${this.fmtNumberToLocale(minutes, 2)}`;
unit = "h";
} else if (minutes >= 1 || minUnit === "m") {
result = `${this.fmtNumberToLocale(minutes)}:${this.fmtNumberToLocale(seconds, 2)}`;
unit = "m";
} else {
result = `${this.fmtNumberToLocale(seconds)}`;
unit = "s";
}
if (withUnit) {
result += `\u202F${unit}`;
}
return result;
},
fmtDayString(date: Date) {
const YY = `${date.getFullYear()}`;
const MM = `${date.getMonth() + 1}`.padStart(2, "0");
const DD = `${date.getDate()}`.padStart(2, "0");
return `${YY}-${MM}-${DD}`;
},
fmtTimeString(date: Date) {
const HH = `${date.getHours()}`.padStart(2, "0");
const mm = `${date.getMinutes()}`.padStart(2, "0");
return `${HH}:${mm}`;
},
isToday(date: Date) {
const today = new Date();
return today.toDateString() === date.toDateString();
},
isTomorrow(date: Date) {
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
return tomorrow.toDateString() === date.toDateString();
},
weekdayPrefix(date: Date) {
if (this.isToday(date)) {
return "";
}
if (this.isTomorrow(date)) {
try {
const rtf = new Intl.RelativeTimeFormat(this.$i18n?.locale, {
numeric: "auto",
});
return rtf.formatToParts(1, "day")[0].value;
} catch (e) {
console.warn("weekdayPrefix: Intl.RelativeTimeFormat not supported", e);
return "tomorrow";
}
}
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: "short",
}).format(date);
},
hourShort(date: Date) {
const locale = this.$i18n?.locale;
// special: use shorter german format
if (locale === "de") return date.getHours();
return new Intl.DateTimeFormat(locale, {
hour: "numeric",
}).format(date);
},
weekdayShort(date: Date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: "short",
}).format(date);
},
fmtAbsoluteDate(date: Date) {
const weekday = this.weekdayPrefix(date);
const hour = new Intl.DateTimeFormat(this.$i18n?.locale, {
hour: "numeric",
minute: "numeric",
}).format(date);
return `${weekday} ${hour}`.trim();
},
fmtFullDateTime(date: Date, short: boolean) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: short ? undefined : "short",
month: short ? "numeric" : "short",
day: "numeric",
hour: "numeric",
minute: "numeric",
}).format(date);
},
fmtWeekdayTime(date: Date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: "short",
hour: "numeric",
minute: "numeric",
}).format(date);
},
fmtMonthYear(date: Date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
month: "long",
year: "numeric",
}).format(date);
},
fmtMonth(date: Date, short: boolean) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
month: short ? "short" : "long",
}).format(date);
},
fmtDayMonth(date: Date) {
return new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: "short",
day: "numeric",
month: "short",
}).format(date);
},
fmtDurationUnit(value: number, unit = "second") {
return new Intl.NumberFormat(this.$i18n?.locale, {
style: "unit",
unit,
unitDisplay: "long",
})
.formatToParts(value)
.find((part) => part.type === "unit")?.value;
},
fmtMoney(amout = 0, currency = CURRENCY.EUR, decimals = true, withSymbol = false) {
const currencyDisplay = withSymbol ? "narrowSymbol" : "code";
const digits = decimals ? undefined : 0;
const result = new Intl.NumberFormat(this.$i18n?.locale, {
style: "currency",
currency,
currencyDisplay,
minimumFractionDigits: digits,
maximumFractionDigits: digits,
}).format(amout);
return withSymbol ? result : result.replace(currency, "").trim();
},
fmtCurrencySymbol(currency = CURRENCY.EUR) {
const symbols = { EUR: "€", USD: "$" };
return symbols[currency] || currency;
},
fmtPricePerKWh(amout = 0, currency = CURRENCY.EUR, short = false, withUnit = true) {
let value = amout;
let minimumFractionDigits = 1;
let maximumFractionDigits = 3;
if (ENERGY_PRICE_IN_SUBUNIT[currency]) {
value *= 100;
minimumFractionDigits = 1;
maximumFractionDigits = 1;
}
const price = new Intl.NumberFormat(this.$i18n?.locale, {
style: "decimal",
minimumFractionDigits,
maximumFractionDigits,
}).format(value);
if (withUnit) {
return `${price} ${this.pricePerKWhUnit(currency, short)}`;
}
return price;
},
timezone() {
return Intl?.DateTimeFormat?.().resolvedOptions?.().timeZone || "UTC";
},
pricePerKWhUnit(currency = CURRENCY.EUR, short = false) {
const unit = ENERGY_PRICE_IN_SUBUNIT[currency] || currency;
return `${unit}${short ? "" : "/kWh"}`;
},
fmtTimeAgo(elapsed: number) {
const units = {
day: 24 * 60 * 60 * 1000,
hour: 60 * 60 * 1000,
minute: 60 * 1000,
second: 1000,
};
// "Math.abs" accounts for both "past" & "future" scenarios
for (const u in units) {
const unitKey = u as keyof typeof units;
if (Math.abs(elapsed) > units[unitKey] || u == "second") {
try {
const rtf = new Intl.RelativeTimeFormat(this.$i18n?.locale, {
numeric: "auto",
});
return rtf.format(Math.round(elapsed / units[unitKey]), unitKey);
} catch (e) {
console.warn("fmtTimeAgo: Intl.RelativeTimeFormat not supported", e);
return `${elapsed} ${u}s ago`;
}
}
}
return "";
},
fmtSocOption(soc: number, rangePerSoc: number, distanceUnit: string, heating?: boolean) {
let result = heating ? this.fmtTemperature(soc) : `${this.fmtPercentage(soc)}`;
if (rangePerSoc && distanceUnit) {
const range = soc * rangePerSoc;
result += ` (${this.fmtNumber(range, 0)} ${distanceUnit})`;
}
return result;
},
fmtPercentage(value: number, digits = 0, forceSign = false) {
const sign = forceSign && value > 0 ? "+" : "";
return `${sign}${new Intl.NumberFormat(this.$i18n?.locale, {
style: "percent",
minimumFractionDigits: digits,
maximumFractionDigits: digits,
}).format(value / 100)}`;
},
hasLeadingPercentageSign() {
return ["tr", "ar"].includes(this.$i18n?.locale);
},
fmtTemperature(value: number) {
// TODO: handle fahrenheit
return this.fmtNumber(value, 1, "celsius");
},
getWeekdaysList(weekdayFormat: Intl.DateTimeFormatOptions["weekday"]) {
const { format } = new Intl.DateTimeFormat(this.$i18n?.locale, {
weekday: weekdayFormat,
});
const mondayToSaturday = [7, 8, 9, 10, 11, 12].map((day, index) => {
return { name: format(new Date(Date.UTC(2021, 5, day))), value: index + 1 };
});
const sunday = { name: format(new Date(Date.UTC(2021, 5, 6))), value: 0 };
return [...mondayToSaturday, sunday];
},
getShortenedWeekdaysLabel(selectedWeekdays: number[]) {
if (0 === selectedWeekdays.length) {
return "–";
}
const weekdays = this.getWeekdaysList("short");
let label = "";
// the week in the input-parameter starts with 0 for sunday and ends with 6 for saturday
// this algorithms works only if the week starts with 1 for monday and ends with 7 for sunday because
// then we are able to count from 1 to 7 by incrementing the number
// so we have to transform the input accordingly
const selectedWeekdaysTransformed = selectedWeekdays.map(function (dayIndex) {
return 0 === dayIndex ? 7 : dayIndex;
});
function getWeekdayName(dayIndex: number) {
return weekdays.find((day) => day.value === (7 === dayIndex ? 0 : dayIndex))?.name;
}
const maxWeekday = Math.max(...selectedWeekdaysTransformed);
for (let weekdayRangeStart = 1; weekdayRangeStart < 8; weekdayRangeStart++) {
if (selectedWeekdaysTransformed.includes(weekdayRangeStart)) {
label += getWeekdayName(weekdayRangeStart);
let weekdayRangeEnd = weekdayRangeStart;
while (selectedWeekdaysTransformed.includes(weekdayRangeEnd + 1)) {
weekdayRangeEnd++;
}
if (weekdayRangeEnd - weekdayRangeStart > 1) {
// more than 2 consecutive weekdays selected
label += " – " + getWeekdayName(weekdayRangeEnd);
weekdayRangeStart = weekdayRangeEnd;
if (maxWeekday !== weekdayRangeEnd) {
label += ", ";
}
} else if (weekdayRangeStart !== weekdayRangeEnd) {
// exactly 2 consecutive weekdays selected
label += ", ";
} else {
// exactly 1 single day selected
if (maxWeekday !== weekdayRangeEnd) {
label += ", ";
}
}
}
}
return label;
},
},
});

View file

@ -2,7 +2,7 @@ export default {
props: {
size: {
type: String,
validator: function (value) {
validator(value) {
return ["xs", "s", "m", "l", "xl"].includes(value);
},
},

View file

@ -1,57 +0,0 @@
import { reactive } from "vue";
function setProperty(obj, props, value) {
const prop = props.shift();
if (!obj[prop]) {
obj[prop] = {};
}
if (!props.length) {
if (value && typeof value === "object" && !Array.isArray(value)) {
obj[prop] = { ...obj[prop], ...value };
} else {
obj[prop] = value;
}
return;
}
setProperty(obj[prop], props, value);
}
const initialState = {
offline: false,
loadpoints: [], // ensure array type
};
const state = reactive(initialState);
const store = {
state,
offline: function (value) {
state.offline = value;
},
update: function (msg) {
Object.keys(msg).forEach(function (k) {
if (k === "log") {
window.app.raise(msg[k]);
} else {
setProperty(state, k.split("."), msg[k]);
}
});
},
reset: function () {
console.log("resetting state");
// reset to initial state
Object.keys(initialState).forEach(function (k) {
if (k === "offline") return;
if (Array.isArray(initialState[k])) {
state[k] = [];
} else {
state[k] = undefined;
}
});
},
};
export default store;

66
assets/js/store.ts Normal file
View file

@ -0,0 +1,66 @@
import { reactive } from "vue";
function setProperty(obj: object, props: string[], value: any) {
const prop = props.shift();
// @ts-expect-error no-explicit-any
if (!obj[prop]) {
// @ts-expect-error no-explicit-any
obj[prop] = {};
}
if (!props.length) {
if (value && typeof value === "object" && !Array.isArray(value)) {
// @ts-expect-error no-explicit-any
obj[prop] = { ...obj[prop], ...value };
} else {
// @ts-expect-error no-explicit-any
obj[prop] = value;
}
return;
}
// @ts-expect-error no-explicit-any
setProperty(obj[prop], props, value);
}
const initialState: State = {
offline: false,
loadpoints: [], // ensure array type
};
const state = reactive(initialState);
const store = {
state,
offline(value: boolean) {
state.offline = value;
},
// @ts-expect-error no-explicit-any
update(msg) {
Object.keys(msg).forEach(function (k) {
if (k === "log") {
window.app.raise(msg[k]);
} else {
setProperty(state, k.split("."), msg[k]);
}
});
},
reset() {
console.log("resetting state");
// reset to initial state
Object.keys(initialState).forEach(function (k) {
if (k === "offline") return;
// @ts-expect-error no-explicit-any
if (Array.isArray(initialState[k])) {
// @ts-expect-error no-explicit-any
state[k] = [];
} else {
// @ts-expect-error no-explicit-any
state[k] = undefined;
}
});
},
};
export default store;

17
assets/js/types/evcc.ts Normal file
View file

@ -0,0 +1,17 @@
declare global {
interface State {
offline: boolean;
loadpoints: [];
forecast?: any;
currency?: CURRENCY;
}
interface Window {
app: any;
}
}
export enum CURRENCY {
EUR = "EUR",
USD = "USD",
}

10
assets/js/types/vue.d.ts vendored Normal file
View file

@ -0,0 +1,10 @@
import { ComponentCustomProperties } from "vue";
declare module "vue" {
interface ComponentCustomProperties {
/**
* Whether experimental UI features should be shown.
*/
$hiddenFeatures: () => boolean;
}
}

View file

@ -1,3 +0,0 @@
export default function (obj) {
return JSON.parse(JSON.stringify(obj));
}

View file

@ -0,0 +1,3 @@
export default function <T>(obj: T): T {
return JSON.parse(JSON.stringify(obj));
}

View file

@ -11,6 +11,10 @@ export interface PriceSlot {
price: number;
}
export function isPriceSlot(obj?: TimeseriesEntry | PriceSlot): obj is PriceSlot {
return (obj as PriceSlot).start !== undefined;
}
export interface EnergyByDay {
energy: number;
complete: boolean;
@ -73,15 +77,22 @@ export function highestSlotIndexByDay(entries: TimeseriesEntry[], day: number =
return entries.findIndex((entry) => entry.ts === highestEntry.ts);
}
export function adjustedSolar(solar: SolarDetails | undefined): SolarDetails | undefined {
export function adjustedSolar(solar?: SolarDetails): SolarDetails | undefined {
if (!solar?.scale) return solar;
const { scale } = solar;
const result = deepCopy(solar);
result.today.energy *= scale;
result.tomorrow.energy *= scale;
result.dayAfterTomorrow.energy *= scale;
result.timeseries?.forEach((entry) => (entry.val *= scale));
let result = deepCopy(solar);
if (result.today) result.today.energy *= scale;
if (result.tomorrow) result.tomorrow.energy *= scale;
if (result.dayAfterTomorrow) result.dayAfterTomorrow.energy *= scale;
if (result.timeseries) {
result.timeseries.forEach((entry) => {
entry.val *= scale;
});
}
result.scale = 1 / scale; // invert to allow back-adjustment
return result;
}

View file

@ -57,13 +57,13 @@ export default {
return { title: siteTitle ? `${siteTitle} | evcc` : "evcc" };
},
computed: {
version: function () {
version() {
return store.state.version;
},
batteryModalAvailabe: function () {
batteryModalAvailabe() {
return store.state.battery?.length;
},
globalSettingsProps: function () {
globalSettingsProps() {
return this.collectProps(GlobalSettingsModal, store.state);
},
batterySettingsProps() {
@ -77,30 +77,30 @@ export default {
},
},
watch: {
version: function (now, prev) {
version(now, prev) {
if (!!prev && !!now) {
console.log("new version detected. reloading browser", { now, prev });
this.reload();
}
},
offline: function (offline) {
offline(offline) {
store.offline(offline);
if (offline) {
this.reconnect();
}
},
},
mounted: function () {
mounted() {
this.connect();
document.addEventListener("visibilitychange", this.pageVisibilityChanged, false);
},
unmounted: function () {
unmounted() {
this.disconnect();
window.clearTimeout(this.reconnectTimeout);
document.removeEventListener("visibilitychange", this.pageVisibilityChanged, false);
},
methods: {
pageVisibilityChanged: function () {
pageVisibilityChanged() {
if (document.hidden) {
window.clearTimeout(this.reconnectTimeout);
this.disconnect();
@ -108,14 +108,14 @@ export default {
this.connect();
}
},
reconnect: function () {
reconnect() {
window.clearTimeout(this.reconnectTimeout);
this.reconnectTimeout = window.setTimeout(() => {
this.disconnect();
this.connect();
}, 2500);
},
disconnect: function () {
disconnect() {
if (this.ws) {
this.ws.onerror = null;
this.ws.onopen = null;
@ -125,7 +125,7 @@ export default {
this.ws = null;
}
},
connect: function () {
connect() {
console.log("websocket connect");
const supportsWebSockets = "WebSocket" in window;
if (!supportsWebSockets) {

View file

@ -47,22 +47,16 @@ import Chart from "../components/Forecast/Chart.vue";
import IconSelectItem from "../components/Helper/IconSelectItem.vue";
import IconSelectGroup from "../components/Helper/IconSelectGroup.vue";
import DynamicPriceIcon from "../components/MaterialIcon/DynamicPrice.vue";
import { type PriceSlot } from "../utils/forecast";
import formatter from "../mixins/formatter";
import store from "../store";
import { ForecastType, type PriceSlot, type SolarDetails } from "../utils/forecast";
import formatter from "../mixins/formatter.ts";
import store from "../store.ts";
interface Forecast {
grid?: PriceSlot[];
solar?: PriceSlot[];
solar?: SolarDetails;
co2?: PriceSlot[];
}
export const TYPES = {
SOLAR: "solar",
PRICE: "price",
CO2: "co2",
};
export default defineComponent({
name: "Energy",
components: {
@ -74,8 +68,8 @@ export default defineComponent({
mixins: [formatter],
data() {
return {
selectedType: TYPES.PRICE,
types: Object.values(TYPES),
selectedType: ForecastType.Price,
types: Object.values(ForecastType),
};
},
head() {
@ -84,9 +78,9 @@ export default defineComponent({
computed: {
typeIcons() {
return {
[TYPES.SOLAR]: "shopicon-regular-sun",
[TYPES.PRICE]: DynamicPriceIcon,
[TYPES.CO2]: "shopicon-regular-eco1",
[ForecastType.Solar]: "shopicon-regular-sun",
[ForecastType.Price]: DynamicPriceIcon,
[ForecastType.Co2]: "shopicon-regular-eco1",
};
},
forecastAvailable() {
@ -101,7 +95,7 @@ export default defineComponent({
},
},
methods: {
updateType(type: string) {
updateType(type: ForecastType) {
this.selectedType = type;
},
},

View file

@ -17,7 +17,7 @@ export default {
notifications: Array,
selectedLoadpointIndex: Number,
},
data: function () {
data() {
return store;
},
};

View file

@ -439,7 +439,7 @@ export default {
startDate() {
return new Date(this.sessions[0]?.created || Date.now());
},
topNavigation: function () {
topNavigation() {
const vehicleLogins = store.state.auth ? store.state.auth.vehicles : {};
return { vehicleLogins, ...this.collectProps(TopNavigation, store.state) };
},
@ -642,7 +642,7 @@ export default {
},
},
watch: {
offline: function () {
offline() {
this.loadSessions();
},
},

1896
package-lock.json generated

File diff suppressed because it is too large Load diff

View file

@ -5,7 +5,7 @@
"scripts": {
"build": "vite build",
"test": "TZ=Europe/Berlin vitest",
"lint": "prettier assets './**/*.{yml,yaml,sh}' --write && eslint assets/**/*.js assets/**/*.vue --fix --max-warnings=0",
"lint": "prettier assets './**/*.{yml,yaml,sh}' --write && eslint assets/**/*.js assets/**/*.vue --fix --max-warnings=0 && vue-tsc --noEmit",
"dev": "vite",
"playwright": "playwright test --ui",
"simulator": "vite tests/simulator",
@ -54,6 +54,7 @@
"smoothscroll-polyfill": "^0.4.4",
"snarkdown": "^2.0.0",
"typescript": "^5.2.2",
"typescript-eslint-language-service": "^5.0.5",
"vite": "^6.1.0",
"vite-plugin-toml": "^0.7.0",
"vitest": "^3.0.5",
@ -63,6 +64,7 @@
"vue-hot-reload-api": "^2.3.4",
"vue-i18n": "^11.1.0",
"vue-router": "^4.0.12",
"vue-tsc": "^2.2.8",
"wait-on": "^8.0.0"
},
"engines": {

View file

@ -1,19 +1,24 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": [
"env.d.ts",
"assets/js/**/*",
"assets/js/src/**/*.vue"
],
"compilerOptions": {
"composite": true,
"noImplicitAny": false,
"allowJs": true,
"baseUrl": ".",
"paths": {
"@/*": [
"./src/*"
]
}
}
}
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "assets/js/**/*"],
"compilerOptions": {
"allowUnreachableCode": false,
"allowUnusedLabels": false,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"noPropertyAccessFromIndexSignature": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"composite": true,
"allowJs": true,
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
},
"plugins": [
{
"name": "typescript-eslint-language-service"
}
]
}
}