2020-07-17 13:42:45 +00:00
|
|
|
import Service from '@ember/service';
|
2020-12-09 09:22:46 +00:00
|
|
|
import { get } from '@ember/object';
|
|
|
|
import { runInDebug } from '@ember/debug';
|
2020-07-17 13:42:45 +00:00
|
|
|
import atob from 'consul-ui/utils/atob';
|
|
|
|
import btoa from 'consul-ui/utils/btoa';
|
|
|
|
|
2022-09-15 08:43:17 +00:00
|
|
|
const createRegExpEncoder = function (re, encoder = (str) => str, strict = true) {
|
2020-12-09 09:22:46 +00:00
|
|
|
return (template = '', vars = {}) => {
|
|
|
|
if (template !== '') {
|
|
|
|
return template.replace(re, (match, group) => {
|
|
|
|
const value = get(vars, group);
|
|
|
|
runInDebug(() => {
|
|
|
|
if (strict && typeof value === 'undefined') {
|
|
|
|
console.error(new Error(`${group} is undefined in ${template}`));
|
|
|
|
}
|
|
|
|
});
|
|
|
|
return encoder(value || '');
|
|
|
|
});
|
|
|
|
}
|
|
|
|
return '';
|
|
|
|
};
|
|
|
|
};
|
2020-11-09 09:25:35 +00:00
|
|
|
export default class EncoderService extends Service {
|
|
|
|
uriComponent = encodeURIComponent;
|
|
|
|
|
2020-12-09 09:22:46 +00:00
|
|
|
createRegExpEncoder(re, encoder) {
|
|
|
|
return createRegExpEncoder(re, encoder);
|
|
|
|
}
|
|
|
|
|
2020-11-09 09:25:35 +00:00
|
|
|
atob() {
|
2020-07-17 13:42:45 +00:00
|
|
|
return atob(...arguments);
|
2020-11-09 09:25:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
btoa() {
|
2020-07-17 13:42:45 +00:00
|
|
|
return btoa(...arguments);
|
2020-11-09 09:25:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
uriJoin() {
|
2020-07-17 13:42:45 +00:00
|
|
|
return this.joiner(this.uriComponent, '/', '')(...arguments);
|
2020-11-09 09:25:35 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
uriTag() {
|
2020-07-17 13:42:45 +00:00
|
|
|
return this.tag(this.uriJoin.bind(this));
|
2020-11-09 09:25:35 +00:00
|
|
|
}
|
|
|
|
|
2022-09-15 08:43:17 +00:00
|
|
|
joiner =
|
|
|
|
(encoder, joiner = '', defaultValue = '') =>
|
|
|
|
(values, strs) =>
|
|
|
|
(strs || Array(values.length).fill(joiner)).reduce(
|
|
|
|
(prev, item, i) => `${prev}${item}${encoder(values[i] || defaultValue)}`,
|
|
|
|
''
|
|
|
|
);
|
2020-11-09 09:25:35 +00:00
|
|
|
|
|
|
|
tag(join) {
|
2020-07-17 13:42:45 +00:00
|
|
|
return (strs, ...values) => join(values, strs);
|
2020-11-09 09:25:35 +00:00
|
|
|
}
|
|
|
|
}
|