From ce3b53a920ecea27c04bcc7e7954114bcd437a1e Mon Sep 17 00:00:00 2001 From: randellhodges Date: Mon, 17 Sep 2018 14:16:00 -0500 Subject: [PATCH] Image aspect ratio (#1665) * Allow user to specify an aspect ratio for various images * added a comment on what is supported * fixed typo * Fixed lint and test errors --- .gitignore | 3 + src/common/util/parse-aspect-ratio.js | 24 ++++++++ .../lovelace/cards/hui-picture-entity-card.js | 1 + .../lovelace/cards/hui-picture-glance-card.js | 1 + src/panels/lovelace/components/hui-image.js | 60 +++++++++++++++---- .../lovelace/elements/hui-image-element.js | 7 ++- .../common/util/parse_aspect_ratio_test.js | 53 ++++++++++++++++ 7 files changed, 134 insertions(+), 15 deletions(-) create mode 100644 src/common/util/parse-aspect-ratio.js create mode 100644 test-mocha/common/util/parse_aspect_ratio_test.js diff --git a/.gitignore b/.gitignore index 9fa46f4c80..6bfc09e27f 100644 --- a/.gitignore +++ b/.gitignore @@ -21,6 +21,9 @@ lib bin dist +# vscode +.vscode + # Secrets .lokalise_token yarn-error.log diff --git a/src/common/util/parse-aspect-ratio.js b/src/common/util/parse-aspect-ratio.js new file mode 100644 index 0000000000..ea94a46cae --- /dev/null +++ b/src/common/util/parse-aspect-ratio.js @@ -0,0 +1,24 @@ +export default function parseAspectRatio(input) { + // Handle 16x9, 16:9, 1.78x1, 1.78:1, 1.78 + // Ignore everything else + function parseOrThrow(number) { + const parsed = parseFloat(number); + if (isNaN(parsed)) throw new Error(`${number} is not a number`); + return parsed; + } + try { + if (input) { + const arr = input.replace(':', 'x').split('x'); + if (arr.length === 0) { + return null; + } + + return arr.length === 1 ? + { w: parseOrThrow(arr[0]), h: 1 } : + { w: parseOrThrow(arr[0]), h: parseOrThrow(arr[1]) }; + } + } catch (err) { + // Ignore the error + } + return null; +} diff --git a/src/panels/lovelace/cards/hui-picture-entity-card.js b/src/panels/lovelace/cards/hui-picture-entity-card.js index e7f864297e..a9f1611435 100644 --- a/src/panels/lovelace/cards/hui-picture-entity-card.js +++ b/src/panels/lovelace/cards/hui-picture-entity-card.js @@ -58,6 +58,7 @@ class HuiPictureEntityCard extends EventsMixin(LocalizeMixin(PolymerElement)) { state-image="[[_config.state_image]]" camera-image="[[_getCameraImage(_config)]]" entity="[[_config.entity]]" + aspect-ratio="[[_config.aspect_ratio]]" >