浏览代码

Allow users to specify abcjsParams (#11162)

* Allow users to specify abcjsParams

* Use looseJsonParse and %%params
Clegs 1 年之前
父节点
当前提交
d9dedb5786
共有 1 个文件被更改,包括 28 次插入3 次删除
  1. 28 3
      app/src/protyle/render/abcRender.ts

+ 28 - 3
app/src/protyle/render/abcRender.ts

@@ -2,6 +2,31 @@ import {addScript} from "../util/addScript";
 import {Constants} from "../../constants";
 import {Constants} from "../../constants";
 import {genIconHTML} from "./util";
 import {genIconHTML} from "./util";
 import {hasClosestByClassName} from "../util/hasClosest";
 import {hasClosestByClassName} from "../util/hasClosest";
+import {looseJsonParse} from "../../util/functions";
+
+const ABCJS_PARAMS_KEY = "%%params:";
+
+// Read the abcjsParams from the content if it exists.
+// The params *must* be the first line of the content in the form:
+// %%abcjsParams: {JSON}
+const getAbcParams = (abcString: string): any => {
+    let params = {
+        responsive: 'resize',
+    };
+
+    const firstLine = abcString.substring(0, abcString.indexOf("\n"));
+
+    if (firstLine.startsWith(ABCJS_PARAMS_KEY)) {
+        try {
+            const jsonString = firstLine.substring(ABCJS_PARAMS_KEY.length);
+            params = { ...params, ...looseJsonParse(jsonString) };
+        } catch (e) {
+            console.error(`Failed to parse ABCJS params: ${e}`);
+        }
+    }
+
+    return params;
+};
 
 
 export const abcRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {
 export const abcRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {
     let abcElements: Element[] = [];
     let abcElements: Element[] = [];
@@ -26,9 +51,9 @@ export const abcRender = (element: Element, cdn = Constants.PROTYLE_CDN) => {
                 }
                 }
                 const renderElement = e.firstElementChild.nextElementSibling as HTMLElement;
                 const renderElement = e.firstElementChild.nextElementSibling as HTMLElement;
                 renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div contenteditable="false"></div>`;
                 renderElement.innerHTML = `<span style="position: absolute;left:0;top:0;width: 1px;">${Constants.ZWSP}</span><div contenteditable="false"></div>`;
-                window.ABCJS.renderAbc(renderElement.lastElementChild, Lute.UnEscapeHTMLStr(e.getAttribute("data-content")), {
-                    responsive: "resize"
-                });
+                const abcString = Lute.UnEscapeHTMLStr(e.getAttribute("data-content"));
+                const abcjsParams = getAbcParams(abcString)
+                window.ABCJS.renderAbc(renderElement.lastElementChild, abcString, abcjsParams);
                 e.setAttribute("data-render", "true");
                 e.setAttribute("data-render", "true");
             });
             });
         });
         });