Prevent creating views with duplicate URL (#17871)

This commit is contained in:
karwosts 2023-09-26 13:54:27 -07:00 committed by GitHub
parent 74be4ae20a
commit 0ffc7b59d6
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 45 additions and 14 deletions

View File

@ -3,6 +3,7 @@ import {
LovelaceConfig,
LovelaceViewConfig,
} from "../../../data/lovelace";
import type { HomeAssistant } from "../../../types";
export const addCard = (
config: LovelaceConfig,
@ -253,23 +254,44 @@ export const moveCard = (
};
export const addView = (
hass: HomeAssistant,
config: LovelaceConfig,
viewConfig: LovelaceViewConfig
): LovelaceConfig => ({
...config,
views: config.views.concat(viewConfig),
});
): LovelaceConfig => {
if (viewConfig.path && config.views.some((v) => v.path === viewConfig.path)) {
throw new Error(
hass.localize("ui.panel.lovelace.editor.edit_view.error_same_url")
);
}
return {
...config,
views: config.views.concat(viewConfig),
};
};
export const replaceView = (
hass: HomeAssistant,
config: LovelaceConfig,
viewIndex: number,
viewConfig: LovelaceViewConfig
): LovelaceConfig => ({
...config,
views: config.views.map((origView, index) =>
index === viewIndex ? viewConfig : origView
),
});
): LovelaceConfig => {
if (
viewConfig.path &&
config.views.some(
(v, idx) => v.path === viewConfig.path && idx !== viewIndex
)
) {
throw new Error(
hass.localize("ui.panel.lovelace.editor.edit_view.error_same_url")
);
}
return {
...config,
views: config.views.map((origView, index) =>
index === viewIndex ? viewConfig : origView
),
};
};
export const swapView = (
config: LovelaceConfig,

View File

@ -405,8 +405,13 @@ export class HuiDialogEditView extends LitElement {
try {
await lovelace.saveConfig(
this._creatingView
? addView(lovelace.config, viewConf)
: replaceView(lovelace.config, this._params.viewIndex!, viewConf)
? addView(this.hass!, lovelace.config, viewConf)
: replaceView(
this.hass!,
lovelace.config,
this._params.viewIndex!,
viewConf
)
);
if (this._params.saveCallback) {
this._params.saveCallback(
@ -417,7 +422,9 @@ export class HuiDialogEditView extends LitElement {
this.closeDialog();
} catch (err: any) {
showAlertDialog(this, {
text: `Saving failed: ${err.message}`,
text: `${this.hass!.localize(
"ui.panel.lovelace.editor.edit_view.saving_failed"
)}: ${err.message}`,
});
} finally {
this._saving = false;

View File

@ -4641,7 +4641,9 @@
"subview": "Subview",
"subview_helper": "Subviews don't appear in tabs and have a back button.",
"edit_ui": "Edit in visual editor",
"edit_yaml": "Edit in YAML"
"edit_yaml": "Edit in YAML",
"saving_failed": "Saving failed",
"error_same_url": "You cannot save a view with the same URL as a different existing view."
},
"edit_badges": {
"view_no_badges": "Badges are not be supported by the current view type."