Skip to content
Snippets Groups Projects
Commit d27ed11c authored by Reiter, Christoph's avatar Reiter, Christoph :snake:
Browse files

Add getAssetURL() to common

This splits things into two phases, initAssetBaseURL() will try to set
a module wide base url for all assets.

The first code to use it successfully will define the asset base url for
all future getAssetURL() calls.
parent 3ad80f20
No related branches found
No related tags found
No related merge requests found
......@@ -32,4 +32,10 @@ describe('utils', () => {
it('setting', () => {
assert(utils.setting('apiBaseUrl').startsWith("http"));
});
it('getAssetURL', () => {
utils.initAssetBaseURL();
assert(utils.getAssetURL("foo/bar") == "foo/bar");
assert(utils.getAssetURL("foo/bar") == "foo/bar");
})
});
......@@ -176,3 +176,53 @@ export const dateToInputTimeString = (date) => {
return `${pad10(date.getHours())}:${pad10(date.getMinutes())}`;
};
let _assetBaseURL = null;
/**
* Set the base url for future calls to getAssetURL()
*
* @param {string} [id] An optional id of the script tag to figure out the
* base bundle URL.
*/
export const initAssetBaseURL = (id) => {
// We don't want future calls to change things
if (_assetBaseURL)
return;
if (id) {
// Find the id added to the script tag
const elm = document.getElementById(id);
if (elm && elm.src) {
_assetBaseURL = elm.src;
}
}
// In the (unlikely) event that we are bundled as a non-module
// we can use the old currentScript API
if (document.currentScript && document.currentScript.src) {
_assetBaseURL = document.currentScript.src;
}
}
/**
* Get an absolute path for assets given a relative path to the js bundle.
* Call initAssetBaseURL() before this.
*
* @param {string} path The relative path based on the js bundle path
*/
export const getAssetURL = (path) => {
// Maybe initScriptURL() can do something without the id
if (!_assetBaseURL) {
initAssetBaseURL();
}
// We already found the path before, just go with it
if (_assetBaseURL) {
return new URL(path, _assetBaseURL).href;
}
// If all fails we just fall back to relative paths and hope the
// html is on the same path as the bundle
return path;
};
\ No newline at end of file
......@@ -2,7 +2,6 @@ import {html, LitElement, css} from 'lit-element';
import * as commonUtils from './utils.js';
import bulmaCSSPath from 'bulma/css/bulma.min.css';
import VPULitElement from './vpu-lit-element.js';
import * as utils from '../../src/utils';
/**
* vpu-button implements a button with Bulma styles and automatic spinner and
......@@ -72,7 +71,7 @@ class Button extends VPULitElement {
}
render() {
const bulmaCSS = utils.getAssetURL(bulmaCSSPath);
const bulmaCSS = commonUtils.getAssetURL(bulmaCSSPath);
return html`
<link rel="stylesheet" href="${bulmaCSS}">
......
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment