index.js 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737
  1. import { OpenSheetMusicDisplay } from '../src/OpenSheetMusicDisplay/OpenSheetMusicDisplay';
  2. /*jslint browser:true */
  3. (function () {
  4. "use strict";
  5. var openSheetMusicDisplay;
  6. var sampleFolder = process.env.STATIC_FILES_SUBFOLDER ? process.env.STATIC_FILES_SUBFOLDER + "/" : "",
  7. samples = {
  8. "Beethoven, L.v. - An die ferne Geliebte": "Beethoven_AnDieFerneGeliebte.xml",
  9. "Clementi, M. - Sonatina Op.36 No.1 Pt.1": "MuzioClementi_SonatinaOpus36No1_Part1.xml",
  10. "Clementi, M. - Sonatina Op.36 No.1 Pt.2": "MuzioClementi_SonatinaOpus36No1_Part2.xml",
  11. "Clementi, M. - Sonatina Op.36 No.3 Pt.1": "MuzioClementi_SonatinaOpus36No3_Part1.xml",
  12. "Clementi, M. - Sonatina Op.36 No.3 Pt.2": "MuzioClementi_SonatinaOpus36No3_Part2.xml",
  13. "Bach, J.S. - Praeludium in C-Dur BWV846 1": "JohannSebastianBach_PraeludiumInCDur_BWV846_1.xml",
  14. "Bach, J.S. - Air": "JohannSebastianBach_Air.xml",
  15. "Gounod, C. - Méditation": "CharlesGounod_Meditation.xml",
  16. "Haydn, J. - Concertante Cello": "JosephHaydn_ConcertanteCello.xml",
  17. "Joplin, S. - Elite Syncopations": "ScottJoplin_EliteSyncopations.xml",
  18. "Joplin, S. - The Entertainer": "ScottJoplin_The_Entertainer.xml",
  19. "Mozart, W.A. - An Chloe": "Mozart_AnChloe.xml",
  20. "Mozart, W.A. - Das Veilchen": "Mozart_DasVeilchen.xml",
  21. "Mozart, W.A. - Clarinet Quintet (Excerpt)": "Mozart_Clarinet_Quintet_Excerpt.mxl",
  22. "Mozart, W.A. - String Quartet in G, K. 387, 1st Mvmt Excerpt": "Mozart_String_Quartet_in_G_K._387_1st_Mvmnt_excerpt.musicxml",
  23. "Mozart/Holzer - Land der Berge (national anthem of Austria)": "Land_der_Berge.musicxml",
  24. "OSMD Function Test - All": "OSMD_function_test_all.xml",
  25. "OSMD Function Test - Accidentals": "OSMD_function_test_accidentals.musicxml",
  26. "OSMD Function Test - Autobeam": "OSMD_function_test_autobeam.musicxml",
  27. "OSMD Function Test - Auto-/Custom-Coloring": "OSMD_function_test_auto-custom-coloring-entchen.musicxml",
  28. "OSMD Function Test - Bar lines": "OSMD_function_test_bar_lines.musicxml",
  29. "OSMD Function Test - Color (from XML)": "OSMD_function_test_color.musicxml",
  30. "OSMD Function Test - Drumset": "OSMD_function_test_drumset.musicxml",
  31. "OSMD Function Test - Expressions": "OSMD_function_test_expressions.musicxml",
  32. "OSMD Function Test - Expressions Overlap": "OSMD_function_test_expressions_overlap.musicxml",
  33. "OSMD Function Test - Grace Notes": "OSMD_function_test_GraceNotes.xml",
  34. "OSMD Function Test - Invisible Notes": "OSMD_function_test_invisible_notes.musicxml",
  35. "OSMD Function Test - Selecting Measures To Draw": "OSMD_function_test_measuresToDraw_Beethoven_AnDieFerneGeliebte.xml",
  36. "OSMD Function Test - Notehead Shapes": "OSMD_function_test_noteheadShapes.musicxml",
  37. "OSMD Function Test - Ornaments": "OSMD_function_test_Ornaments.xml",
  38. "OSMD Function Test - Tremolo": "OSMD_Function_Test_Tremolo_2bars.musicxml",
  39. "Schubert, F. - An Die Musik": "Schubert_An_die_Musik.xml",
  40. "Actor, L. - Prelude (Large Sample, loading time)": "ActorPreludeSample.xml",
  41. "Anonymous - Saltarello": "Saltarello.mxl",
  42. "Debussy, C. - Mandoline": "Debussy_Mandoline.xml",
  43. "Levasseur, F. - Parlez Mois": "Parlez-moi.mxl",
  44. "Schumann, R. - Dichterliebe": "Dichterliebe01.xml",
  45. "Telemann, G.P. - Sonate-Nr.1.1-Dolce": "TelemannWV40.102_Sonate-Nr.1.1-Dolce.xml",
  46. "Telemann, G.P. - Sonate-Nr.1.2-Allegro": "TelemannWV40.102_Sonate-Nr.1.2-Allegro-F-Dur.xml",
  47. },
  48. zoom = 1.0,
  49. // HTML Elements in the page
  50. divControls,
  51. zoomControls,
  52. header,
  53. err,
  54. error_tr,
  55. canvas,
  56. selectSample,
  57. selectBounding,
  58. skylineDebug,
  59. bottomlineDebug,
  60. zoomIns,
  61. zoomOuts,
  62. zoomDivs,
  63. custom,
  64. nextCursorBtn,
  65. resetCursorBtn,
  66. followCursorCheckbox,
  67. showCursorBtn,
  68. hideCursorBtn,
  69. backendSelect,
  70. backendSelectDiv,
  71. debugReRenderBtn,
  72. debugClearBtn,
  73. selectPageSize,
  74. printPdfBtn;
  75. // manage option setting and resetting for specific samples, e.g. in the autobeam sample autobeam is set to true, otherwise reset to previous state
  76. // TODO design a more elegant option state saving & restoring system, though that requires saving the options state in OSMD
  77. var minMeasureToDrawStashed = 1;
  78. var maxMeasureToDrawStashed = Number.MAX_SAFE_INTEGER;
  79. var measureToDrawRangeNeedsReset = false;
  80. var autobeamOptionNeedsReset = false;
  81. var autobeamOptionStashedValue = false;
  82. var autoCustomColoringOptionNeedsReset = false;
  83. var autoCustomColoringOptionStashedValue = false;
  84. var drawPartNamesOptionStashedValue = true;
  85. var drawPartAbbreviationsStashedValue = true;
  86. var drawPartNamesOptionNeedsReset = false;
  87. var showControls = true;
  88. var showZoomControl = true;
  89. var showHeader = true;
  90. var showDebugControls = false;
  91. if (process.env.OSMD_DEMO_TITLE) {
  92. document.title = process.env.OSMD_DEMO_TITLE;
  93. }
  94. // Initialization code
  95. function init() {
  96. var name, option;
  97. // Handle window parameter
  98. var paramEmbedded = findGetParameter('embedded');
  99. var paramShowControls = findGetParameter('showControls');
  100. var paramShowZoomControl = findGetParameter('showZoomControl');
  101. var paramShowHeader = findGetParameter('showHeader');
  102. var paramZoom = findGetParameter('zoom');
  103. var paramOverflow = findGetParameter('overflow');
  104. var paramOpenUrl = findGetParameter('openUrl');
  105. var paramDebugControls = findGetParameter('debugControls');
  106. var paramCompactMode = findGetParameter('compactMode');
  107. var paramMeasureRangeStart = findGetParameter('measureRangeStart');
  108. var paramMeasureRangeEnd = findGetParameter('measureRangeEnd');
  109. var paramPageFormat = findGetParameter('pageFormat');
  110. var paramPageBackgroundColor = findGetParameter('pageBackgroundColor');
  111. var paramBackendType = findGetParameter('backendType');
  112. var paramPageWidth = findGetParameter('pageWidth');
  113. var paramPageHeight = findGetParameter('pageHeight');
  114. showHeader = (paramShowHeader !== '0');
  115. showControls = false;
  116. if (paramEmbedded !== undefined) {
  117. showControls = (paramShowControls !== '0');
  118. console.log('show controls: ' + showControls);
  119. showZoomControl = (paramShowZoomControl !== '0');
  120. }
  121. if (paramZoom !== undefined) {
  122. if (paramZoom > 0.1 && paramZoom < 5.0) {
  123. zoom = paramZoom;
  124. console.log('Set zoom to ' + zoom);
  125. }
  126. }
  127. if (paramOverflow !== undefined && typeof paramOverflow === 'string') {
  128. if (paramOverflow === 'hidden' || paramOverflow === 'auto' || paramOverflow === 'scroll' || paramOverflow === 'visible') {
  129. document.body.style.overflow = paramOverflow;
  130. }
  131. }
  132. var compactMode = paramCompactMode && paramCompactMode !== '0';
  133. var measureRangeStart = paramMeasureRangeStart ? Number.parseInt(paramMeasureRangeStart) : 0;
  134. var measureRangeEnd = paramMeasureRangeEnd ? Number.parseInt(paramMeasureRangeEnd) : Number.MAX_SAFE_INTEGER;
  135. if (measureRangeStart && measureRangeEnd && measureRangeEnd < measureRangeStart) {
  136. console.log("[OSMD] warning: measure range end parameter should not be smaller than measure range start. We've set start measure = end measure now.")
  137. measureRangeStart = measureRangeEnd;
  138. }
  139. let pageFormat = paramPageFormat ? paramPageFormat : "Endless";
  140. if (paramPageHeight && paramPageWidth) {
  141. pageFormat = `${paramPageWidth}x${paramPageHeight}`
  142. }
  143. var pageBackgroundColor = paramPageBackgroundColor ? "#" + paramPageBackgroundColor : undefined; // vexflow format, see OSMDOptions. can't use # in parameters.
  144. //console.log("demo: osmd pagebgcolor: " + pageBackgroundColor);
  145. var backendType = (paramBackendType && paramBackendType.toLowerCase) ? paramBackendType : "svg";
  146. // set the backendSelect debug controls dropdown menu selected item
  147. //console.log("true: " + backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas");
  148. // TODO somehow backendSelect becomes undefined here:
  149. /*if (backendSelect && backendType.toLowerCase && backendType.toLowerCase() === "canvas") {
  150. console.log("here1");
  151. for (var i=0; i<backendSelect.options.length; i++) {
  152. if (backendSelect.options[i].value.toLowerCase() === "canvas") {
  153. backendSelect.selectedIndex = i;
  154. }
  155. }
  156. backendSelect.value = "Canvas";
  157. }*/
  158. divControls = document.getElementById('divControls');
  159. zoomControls = document.getElementById('zoomControls');
  160. header = document.getElementById('header');
  161. err = document.getElementById("error-td");
  162. error_tr = document.getElementById("error-tr");
  163. zoomDivs = [];
  164. zoomDivs.push(document.getElementById("zoom-str"));
  165. zoomDivs.push(document.getElementById("zoom-str-optional"));
  166. custom = document.createElement("option");
  167. selectSample = document.getElementById("selectSample");
  168. selectBounding = document.getElementById("selectBounding");
  169. skylineDebug = document.getElementById("skylineDebug");
  170. bottomlineDebug = document.getElementById("bottomlineDebug");
  171. zoomIns = [];
  172. zoomIns.push(document.getElementById("zoom-in-btn"));
  173. zoomIns.push(document.getElementById("zoom-in-btn-optional"));
  174. zoomOuts = [];
  175. zoomOuts.push(document.getElementById("zoom-out-btn"));
  176. zoomOuts.push(document.getElementById("zoom-out-btn-optional"));
  177. canvas = document.createElement("div");
  178. //canvas.id = 'osmdCanvasDiv';
  179. //canvas.style.overflowX = 'auto'; // enable horizontal scrolling
  180. nextCursorBtn = document.getElementById("next-cursor-btn");
  181. resetCursorBtn = document.getElementById("reset-cursor-btn");
  182. followCursorCheckbox = document.getElementById("follow-cursor-checkbox");
  183. showCursorBtn = document.getElementById("show-cursor-btn");
  184. hideCursorBtn = document.getElementById("hide-cursor-btn");
  185. backendSelect = document.getElementById("backend-select");
  186. backendSelectDiv = document.getElementById("backend-select-div");
  187. debugReRenderBtn = document.getElementById("debug-re-render-btn");
  188. debugClearBtn = document.getElementById("debug-clear-btn");
  189. selectPageSize = document.getElementById("selectPageSize");
  190. printPdfBtn = document.getElementById("print-pdf-btn");
  191. //var defaultDisplayVisibleValue = "block"; // TODO in some browsers flow could be the better/default value
  192. var defaultVisibilityValue = "visible";
  193. var devDemoRunning = process.env.OSMD_DEBUG_CONTROLS;
  194. showDebugControls = paramDebugControls === '1' || (devDemoRunning && paramDebugControls !== '0')
  195. if (showDebugControls) {
  196. var elementsToEnable = [
  197. selectSample, selectBounding, selectPageSize, backendSelect, backendSelectDiv, divControls
  198. ];
  199. for (var i=0; i<elementsToEnable.length; i++) {
  200. if (elementsToEnable[i]) { // make sure this element is not null/exists in the index.html, e.g. github.io demo has different index.html
  201. if (elementsToEnable[i].style) {
  202. elementsToEnable[i].style.visibility = defaultVisibilityValue;
  203. elementsToEnable[i].style.opacity = 1.0;
  204. }
  205. }
  206. }
  207. } else {
  208. if (divControls) {
  209. divControls.style.display = "none";
  210. }
  211. }
  212. const optionalControls = document.getElementById('optionalControls');
  213. if (optionalControls) {
  214. if (showControls) {
  215. optionalControls.style.visibility = defaultVisibilityValue;
  216. optionalControls.style.opacity = 0.8;
  217. } else {
  218. optionalControls.style.display = 'none';
  219. }
  220. }
  221. if (!showHeader) {
  222. if (header) {
  223. header.style.display = 'none';
  224. }
  225. } else {
  226. if (header) {
  227. header.style.opacity = 1.0;
  228. }
  229. }
  230. // Hide error
  231. error();
  232. if (showControls && showZoomControl) {
  233. const zoomControlsButtons = document.getElementById('zoomControlsButtons-optional');
  234. const zoomControlsString = document.getElementById('zoom-str-optional'); // actually === zoomDiv above
  235. const optionalControls = document.getElementById('optionalControls');
  236. if (optionalControls) {
  237. optionalControls.appendChild(zoomControlsButtons);
  238. optionalControls.appendChild(zoomControlsString);
  239. optionalControls.style.position = 'absolute';
  240. optionalControls.style.zIndex = '10';
  241. optionalControls.style.right = '10px';
  242. optionalControls.style.padding = '10px';
  243. }
  244. if (zoomControlsString) {
  245. zoomControlsString.style.display = 'inline';
  246. zoomControlsString.style.padding = '10px';
  247. }
  248. }
  249. // Create select
  250. for (name in samples) {
  251. if (samples.hasOwnProperty(name)) {
  252. option = document.createElement("option");
  253. option.value = samples[name];
  254. option.textContent = name;
  255. }
  256. if (selectSample) {
  257. selectSample.appendChild(option);
  258. }
  259. }
  260. if (selectSample) {
  261. selectSample.onchange = selectSampleOnChange;
  262. }
  263. if (selectBounding) {
  264. selectBounding.onchange = selectBoundingOnChange;
  265. }
  266. if (selectPageSize) {
  267. selectPageSize.onchange = function (evt) {
  268. var value = evt.target.value;
  269. openSheetMusicDisplay.setPageFormat(value);
  270. openSheetMusicDisplay.render();
  271. };
  272. }
  273. if (printPdfBtn) {
  274. printPdfBtn.onclick = function () {
  275. openSheetMusicDisplay.createPdf();
  276. }
  277. }
  278. // Pre-select default music piece
  279. custom.appendChild(document.createTextNode("Custom"));
  280. // Create zoom controls
  281. for (const zoomIn of zoomIns) {
  282. if (zoomIn) {
  283. zoomIn.onclick = function () {
  284. zoom *= 1.2;
  285. scale();
  286. };
  287. }
  288. }
  289. for (const zoomOut of zoomOuts) {
  290. if (zoomOut) {
  291. zoomOut.onclick = function () {
  292. zoom /= 1.2;
  293. scale();
  294. };
  295. }
  296. }
  297. if (skylineDebug) {
  298. skylineDebug.onclick = function () {
  299. openSheetMusicDisplay.DrawSkyLine = !openSheetMusicDisplay.DrawSkyLine;
  300. }
  301. }
  302. if (bottomlineDebug) {
  303. bottomlineDebug.onclick = function () {
  304. openSheetMusicDisplay.DrawBottomLine = !openSheetMusicDisplay.DrawBottomLine;
  305. }
  306. }
  307. if (debugReRenderBtn) {
  308. debugReRenderBtn.onclick = function () {
  309. rerender();
  310. }
  311. }
  312. if (debugClearBtn) {
  313. debugClearBtn.onclick = function () {
  314. openSheetMusicDisplay.clear();
  315. }
  316. }
  317. // Create OSMD object and canvas
  318. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, {
  319. autoResize: true,
  320. backend: backendType,
  321. //backend: "canvas",
  322. disableCursor: false,
  323. drawingParameters: compactMode ? "compact" : "default", // try compact (instead of default)
  324. drawPartNames: true, // try false
  325. // drawTitle: false,
  326. // drawSubtitle: false,
  327. drawFingerings: true,
  328. fingeringPosition: "left", // left is default. try right. experimental: auto, above, below.
  329. // fingeringInsideStafflines: "true", // default: false. true draws fingerings directly above/below notes
  330. setWantedStemDirectionByXml: true, // try false, which was previously the default behavior
  331. // drawUpToMeasureNumber: 3, // draws only up to measure 3, meaning it draws measure 1 to 3 of the piece.
  332. drawFromMeasureNumber : measureRangeStart,
  333. drawUpToMeasureNumber : measureRangeEnd,
  334. //drawMeasureNumbers: false, // disable drawing measure numbers
  335. //measureNumberInterval: 4, // draw measure numbers only every 4 bars (and at the beginning of a new system)
  336. // coloring options
  337. coloringEnabled: true,
  338. // defaultColorNotehead: "#CC0055", // try setting a default color. default is black (undefined)
  339. // defaultColorStem: "#BB0099",
  340. autoBeam: false, // try true, OSMD Function Test AutoBeam sample
  341. autoBeamOptions: {
  342. beam_rests: false,
  343. beam_middle_rests_only: false,
  344. //groups: [[3,4], [1,1]],
  345. maintain_stem_directions: false
  346. },
  347. pageFormat: pageFormat,
  348. pageBackgroundColor: pageBackgroundColor,
  349. // tupletsBracketed: true, // creates brackets for all tuplets except triplets, even when not set by xml
  350. // tripletsBracketed: true,
  351. // tupletsRatioed: true, // unconventional; renders ratios for tuplets (3:2 instead of 3 for triplets)
  352. });
  353. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to see more detailed control flow information in console
  354. document.body.appendChild(canvas);
  355. window.addEventListener("keydown", function (e) {
  356. var event = window.event ? window.event : e;
  357. if (event.keyCode === 39) {
  358. openSheetMusicDisplay.cursor.next();
  359. }
  360. });
  361. nextCursorBtn.addEventListener("click", function () {
  362. openSheetMusicDisplay.cursor.next();
  363. });
  364. resetCursorBtn.addEventListener("click", function () {
  365. openSheetMusicDisplay.cursor.reset();
  366. });
  367. if (followCursorCheckbox) {
  368. followCursorCheckbox.onclick = function () {
  369. openSheetMusicDisplay.FollowCursor = !openSheetMusicDisplay.FollowCursor;
  370. }
  371. }
  372. hideCursorBtn.addEventListener("click", function () {
  373. if (openSheetMusicDisplay.cursor) {
  374. openSheetMusicDisplay.cursor.hide();
  375. } else {
  376. console.info("Can't hide cursor, as it was disabled (e.g. by drawingParameters).");
  377. }
  378. });
  379. showCursorBtn.addEventListener("click", function () {
  380. if (openSheetMusicDisplay.cursor) {
  381. openSheetMusicDisplay.cursor.show();
  382. } else {
  383. console.info("Can't show cursor, as it was disabled (e.g. by drawingParameters).");
  384. }
  385. });
  386. backendSelect.addEventListener("change", function (e) {
  387. var value = e.target.value;
  388. var createNewOsmd = true;
  389. if (createNewOsmd) {
  390. // clears the canvas element
  391. canvas.innerHTML = "";
  392. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, { backend: value });
  393. openSheetMusicDisplay.setLogLevel('info'); // set this to 'debug' if you want to get more detailed control flow information
  394. } else {
  395. // alternative, doesn't work yet, see setOptions():
  396. openSheetMusicDisplay.setOptions({ backend: value });
  397. }
  398. console.log("[OSMD] selectSampleOnChange addEventListener change");
  399. // selectSampleOnChange();
  400. });
  401. if (paramOpenUrl !== undefined) {
  402. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  403. console.log("[OSMD] selectSampleOnChange with " + paramOpenUrl);
  404. }
  405. // DEBUG: cause an error for a certain sample, for testing
  406. // if (paramOpenUrl.startsWith("Beethoven")) {
  407. // paramOpenUrl.causeError();
  408. // }
  409. selectSampleOnChange(paramOpenUrl);
  410. } else {
  411. if (openSheetMusicDisplay.getLogLevel() < 2) { // debug or trace
  412. console.log("[OSMD] selectSampleOnChange without param");
  413. }
  414. selectSampleOnChange();
  415. }
  416. }
  417. function findGetParameter(parameterName) {
  418. // special treatment for the openUrl parameter, because different systems attach different arguments to an URL.
  419. // because of CORS (cross-origin safety restrictions), you can only load an xml file from the same origin (server).
  420. // test parameter: ?openUrl=https://opensheetmusiceducation.org/index.php?gf-download=2020%2F01%2FJohannSebastianBach_PraeludiumInCDur_BWV846_1.xml&endUrl&form-id=1&field-id=4&hash=c4ba271ef08204a26cbd4cd2d751c53b78f238c25ddbb1f343e1172f2ce2aa53
  421. // (enable the console.log at the end of this method for testing)
  422. // working test parameter in local demo: ?openUrl=OSMD_function_test_all.xml&endUrl
  423. if (parameterName === 'openUrl') {
  424. let startParameterName = 'openUrl=';
  425. let endParameterName = '&endUrl';
  426. let openUrlIndex = location.search.indexOf(startParameterName);
  427. if (openUrlIndex < 0) {
  428. return undefined;
  429. }
  430. let endIndex = location.search.indexOf(endParameterName) + endParameterName.length;
  431. if (endIndex < 0) {
  432. console.log("[OSMD] If using openUrl as a parameter, you have to end it with '&endUrl'. openUrl parameter omitted.");
  433. return undefined;
  434. }
  435. let urlString = location.search.substring(openUrlIndex + startParameterName.length, endIndex - endParameterName.length);
  436. //console.log("openUrl: " + urlString);
  437. return urlString;
  438. }
  439. let result = undefined;
  440. let tmp = [];
  441. location.search
  442. .substr(1)
  443. .split('&')
  444. .forEach(function (item) {
  445. tmp = item.split('=');
  446. if (tmp[0] === parameterName) {
  447. result = decodeURIComponent(tmp[1]);
  448. //console.log('Found param:' + parameterName + ' = ' + result);
  449. }
  450. });
  451. return result;
  452. }
  453. function selectBoundingOnChange(evt) {
  454. var value = evt.target.value;
  455. openSheetMusicDisplay.DrawBoundingBox = value;
  456. }
  457. function selectSampleOnChange(str) {
  458. error();
  459. disable();
  460. var isCustom = typeof str === "string";
  461. if (!isCustom) {
  462. if (selectSample) {
  463. str = sampleFolder + selectSample.value;
  464. } else {
  465. if (samples && samples.length > 0) {
  466. str = sampleFolder + samples[0];
  467. } else {
  468. return; // no sample to load right now
  469. }
  470. }
  471. }
  472. // zoom = 1.0;
  473. setSampleSpecificOptions(str, isCustom);
  474. openSheetMusicDisplay.load(str).then(
  475. function () {
  476. // This gives you access to the osmd object in the console. Do not use in productive code
  477. window.osmd = openSheetMusicDisplay;
  478. openSheetMusicDisplay.zoom = zoom;
  479. return openSheetMusicDisplay.render();
  480. },
  481. function (e) {
  482. errorLoadingOrRenderingSheet(e, "rendering");
  483. }
  484. ).then(
  485. function () {
  486. return onLoadingEnd(isCustom);
  487. }, function (e) {
  488. errorLoadingOrRenderingSheet(e, "loading");
  489. onLoadingEnd(isCustom);
  490. }
  491. );
  492. }
  493. function setSampleSpecificOptions(str, isCustom) {
  494. if (!isCustom && str.includes("measuresToDraw")) { // set options for measuresToDraw sample
  495. // stash previously set range of measures to draw
  496. if (!measureToDrawRangeNeedsReset) { // only stash once, when measuresToDraw called multiple times in a row
  497. minMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MinMeasureToDrawIndex + 1;
  498. maxMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MaxMeasureToDrawIndex + 1;
  499. }
  500. measureToDrawRangeNeedsReset = true;
  501. // for debugging: draw from a random range of measures
  502. let minMeasureToDraw = Math.ceil(Math.random() * 15); // measures start at 1 (measureIndex = measure number - 1 elsewhere)
  503. let maxMeasureToDraw = Math.ceil(Math.random() * 15);
  504. if (minMeasureToDraw > maxMeasureToDraw) {
  505. minMeasureToDraw = maxMeasureToDraw;
  506. let a = minMeasureToDraw;
  507. maxMeasureToDraw = a;
  508. }
  509. //minMeasureToDraw = 1; // set your custom indexes here. Drawing only one measure can be a special case
  510. //maxMeasureToDraw = 1;
  511. console.log("drawing measures in the range: [" + minMeasureToDraw + "," + maxMeasureToDraw + "]");
  512. openSheetMusicDisplay.setOptions({
  513. drawFromMeasureNumber: minMeasureToDraw,
  514. drawUpToMeasureNumber: maxMeasureToDraw
  515. });
  516. } else if (measureToDrawRangeNeedsReset) { // reset for other samples
  517. openSheetMusicDisplay.setOptions({
  518. drawFromMeasureNumber: minMeasureToDrawStashed,
  519. drawUpToMeasureNumber: maxMeasureToDrawStashed
  520. });
  521. measureToDrawRangeNeedsReset = false;
  522. }
  523. // Enable Boomwhacker-like coloring for OSMD Function Test - Auto-Coloring (Boomwhacker-like, custom color set)
  524. if (!isCustom && str.includes("auto-custom-coloring")) { // set options for auto coloring sample
  525. autoCustomColoringOptionNeedsReset = true;
  526. //openSheetMusicDisplay.setOptions({coloringMode: 1}); // Auto-Coloring with pre-defined colors
  527. openSheetMusicDisplay.setOptions({
  528. coloringMode: 2, // custom coloring set. 0 would be XML, 1 autocoloring
  529. coloringSetCustom: ["#d82c6b", "#F89D15", "#FFE21A", "#4dbd5c", "#009D96", "#43469d", "#76429c", "#ff0000"],
  530. // last color value of coloringSetCustom is for rest notes
  531. colorStemsLikeNoteheads: true
  532. });
  533. } else if (autoCustomColoringOptionNeedsReset) {
  534. openSheetMusicDisplay.setOptions({ // set default values. better would be to restore to stashed values, but unnecessarily complex for demo
  535. coloringMode: 0,
  536. colorStemsLikeNoteheads: false,
  537. coloringSetCustom: null
  538. });
  539. autoCustomColoringOptionNeedsReset = false;
  540. }
  541. if (!isCustom && str.includes("autobeam")) {
  542. autobeamOptionStashedValue = openSheetMusicDisplay.EngravingRules.AutoBeamNotes; // stash previously set value, to restore later
  543. autobeamOptionNeedsReset = true;
  544. openSheetMusicDisplay.setOptions({ autoBeam: true });
  545. } else if (autobeamOptionNeedsReset) {
  546. openSheetMusicDisplay.setOptions({ autoBeam: autobeamOptionStashedValue });
  547. autobeamOptionNeedsReset = false;
  548. }
  549. if (!isCustom && str.includes("Schubert_An_die_Musik")) { // TODO weird layout bug here with part names. but shouldn't be in score anyways
  550. drawPartNamesOptionStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartNames;
  551. drawPartAbbreviationsStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartAbbreviations;
  552. openSheetMusicDisplay.setOptions({ drawPartNames: false, drawPartAbbreviations: false }); // TODO sets osmd.drawingParameters.DrawPartNames! also check EngravingRules.RenderPartAbbreviations, was false
  553. drawPartNamesOptionNeedsReset = true;
  554. } else if (drawPartNamesOptionNeedsReset) {
  555. openSheetMusicDisplay.setOptions({ drawPartNames: drawPartNamesOptionStashedValue, drawPartAbbreviations: drawPartAbbreviationsStashedValue });
  556. drawPartNamesOptionNeedsReset = false;
  557. }
  558. }
  559. function errorLoadingOrRenderingSheet(e, loadingOrRenderingString) {
  560. var errorString = "Error " + loadingOrRenderingString + " sheet: " + e;
  561. // if (process.env.DEBUG) { // people may not set a debug environment variable for the demo.
  562. // Always giving a StackTrace might give us more and better error reports.
  563. // TODO for a release, StackTrace control could be reenabled
  564. errorString += "\n" + "StackTrace: \n" + e.stack;
  565. // }
  566. console.warn(errorString);
  567. }
  568. function onLoadingEnd(isCustom) {
  569. // Remove option from select
  570. if (!isCustom && custom.parentElement === selectSample) {
  571. selectSample.removeChild(custom);
  572. }
  573. // Enable controls again
  574. enable();
  575. }
  576. function logCanvasSize() {
  577. for (const zoomDiv of zoomDivs) {
  578. if (zoomDiv) {
  579. zoomDiv.innerHTML = Math.floor(zoom * 100.0) + "%";
  580. }
  581. }
  582. }
  583. function scale() {
  584. disable();
  585. window.setTimeout(function () {
  586. openSheetMusicDisplay.zoom = zoom;
  587. openSheetMusicDisplay.render();
  588. enable();
  589. }, 0);
  590. }
  591. function rerender() {
  592. disable();
  593. window.setTimeout(function () {
  594. if (openSheetMusicDisplay.IsReadyToRender()) {
  595. openSheetMusicDisplay.render();
  596. } else {
  597. console.log("[OSMD demo] Looses context!"); // TODO not sure that this message is reasonable, renders fine anyways. maybe vexflow context lost?
  598. selectSampleOnChange(); // reload sample e.g. after osmd.clear()
  599. }
  600. enable();
  601. }, 0);
  602. }
  603. function error(errString) {
  604. if (!errString) {
  605. error_tr.style.display = "none";
  606. } else {
  607. console.log("[OSMD demo] error: " + errString)
  608. err.textContent = errString;
  609. error_tr.style.display = "";
  610. canvas.width = canvas.height = 0;
  611. enable();
  612. }
  613. }
  614. // Enable/Disable Controls
  615. function disable() {
  616. document.body.style.opacity = 0.3;
  617. setDisabledForControls("disabled");
  618. }
  619. function enable() {
  620. document.body.style.opacity = 1;
  621. setDisabledForControls("");
  622. logCanvasSize();
  623. }
  624. function setDisabledForControls(disabledValue) {
  625. if (selectSample) {
  626. selectSample.disabled = disabledValue;
  627. }
  628. for (const zoomIn of zoomIns) {
  629. if (zoomIn) {
  630. zoomIn.disabled = disabledValue;
  631. }
  632. }
  633. for (const zoomOut of zoomOuts) {
  634. if (zoomOut) {
  635. zoomOut.disabled = disabledValue;
  636. }
  637. }
  638. }
  639. // Register events: load, drag&drop
  640. window.addEventListener("load", function () {
  641. init();
  642. });
  643. window.addEventListener("dragenter", function (event) {
  644. event.preventDefault();
  645. disable();
  646. });
  647. window.addEventListener("dragover", function (event) {
  648. event.preventDefault();
  649. });
  650. window.addEventListener("dragleave", function (event) {
  651. enable();
  652. });
  653. window.addEventListener("drop", function (event) {
  654. event.preventDefault();
  655. if (!event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) {
  656. return;
  657. }
  658. // Add "Custom..." score
  659. selectSample.appendChild(custom);
  660. custom.selected = "selected";
  661. // Read dragged file
  662. var reader = new FileReader();
  663. reader.onload = function (res) {
  664. selectSampleOnChange(res.target.result);
  665. };
  666. var filename = event.dataTransfer.files[0].name;
  667. if (filename.toLowerCase().indexOf(".xml") > 0
  668. || filename.toLowerCase().indexOf(".musicxml") > 0) {
  669. reader.readAsText(event.dataTransfer.files[0]);
  670. } else if (event.dataTransfer.files[0].name.toLowerCase().indexOf(".mxl") > 0) {
  671. reader.readAsBinaryString(event.dataTransfer.files[0]);
  672. }
  673. else {
  674. alert("No vaild .xml/.mxl/.musicxml file!");
  675. }
  676. });
  677. }());