diff --git a/assets/js/theme.js b/assets/js/theme.js
index 7512c2ed..5c3739c7 100644
--- a/assets/js/theme.js
+++ b/assets/js/theme.js
@@ -1,3 +1,4 @@
+// TODO use ESLint to check the code style
import Util from './util';
class FixIt {
@@ -686,12 +687,20 @@ class FixIt {
if ($echarts.nextElementSibling.tagName === 'TEMPLATE') {
const chart = echarts.init($echarts, this.isDark ? 'dark' : 'light', { renderer: 'svg' });
stagingDOM.stage($echarts.nextElementSibling.content.cloneNode(true));
- // support both JSON and JS object literal
+ let option;
if ($echarts.nextElementSibling.dataset.fmt === 'js') {
- eval(`chart.setOption(${stagingDOM.contentAsText()})`);
+ // support JS object literal or JS code
+ const jsCodes = stagingDOM.contentAsText();
+ option = new Function(
+ this.util.isObjectString(jsCodes)
+ ? `return ${jsCodes}`
+ : `${jsCodes} return option`
+ )();
} else {
- chart.setOption(stagingDOM.contentAsJson());
+ // support JSON
+ option = stagingDOM.contentAsJson();
}
+ chart.setOption(option);
this._echartsArr.push(chart);
}
});
diff --git a/assets/js/util.js b/assets/js/util.js
index 6fabd153..af8bad43 100644
--- a/assets/js/util.js
+++ b/assets/js/util.js
@@ -42,7 +42,7 @@ export default class Util {
isValidDate(date) {
return date instanceof Date && !isNaN(date.getTime());
}
-
+
/**
* scroll some element into view
* @param {String} selector element to scroll
@@ -109,6 +109,23 @@ export default class Util {
reject();
}
});
- return this.copyText(text);
+ return this.copyText(text);
+ }
+
+ /**
+ * check if a string is a JS object string
+ * @example isObjectString("{a:1,b:2}") // true
+ * @param {String} str
+ * @returns
+ */
+ isObjectString(str) {
+ if (typeof str !== 'string') {
+ return false;
+ }
+ str = str.replace(/\s+/g, ' ').trim();
+ if (str.startsWith('{') && str.endsWith('}')) {
+ return true;
+ }
+ return false;
}
}
diff --git a/layouts/partials/init/index.html b/layouts/partials/init/index.html
index c66bd8e8..79384638 100644
--- a/layouts/partials/init/index.html
+++ b/layouts/partials/init/index.html
@@ -1,4 +1,4 @@
-{{- .Scratch.Set "version" "v0.3.20-662a7d57" -}}
+{{- .Scratch.Set "version" "v0.3.20-d41e53bb" -}}
{{- .Scratch.Set "this" dict -}}
{{- partial "init/detection-env.html" . -}}
diff --git a/layouts/partials/plugin/echarts.html b/layouts/partials/plugin/echarts.html
index f220732b..3be9e778 100644
--- a/layouts/partials/plugin/echarts.html
+++ b/layouts/partials/plugin/echarts.html
@@ -9,9 +9,6 @@
{{- if hugo.IsProduction -}}
{{- $content = replaceRE `[\s]+` " " $content -}}
{{- end -}}
- {{- if not ((hasPrefix $content "{") | and (hasSuffix $content "}")) -}}
- {{- errorf "ECharts format error\nPlease use JS object literal for Echarts, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#object_literals" -}}
- {{- end -}}
{{ $content | safeJS }}
{{- else -}}
{{ .Inner | transform.Unmarshal | jsonify }}