index.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  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. err,
  51. error_tr,
  52. canvas,
  53. selectSample,
  54. selectBounding,
  55. skylineDebug,
  56. bottomlineDebug,
  57. zoomIn,
  58. zoomOut,
  59. zoomDiv,
  60. custom,
  61. nextCursorBtn,
  62. resetCursorBtn,
  63. followCursorCheckbox,
  64. showCursorBtn,
  65. hideCursorBtn,
  66. backendSelect,
  67. debugReRenderBtn,
  68. debugClearBtn;
  69. // manage option setting and resetting for specific samples, e.g. in the autobeam sample autobeam is set to true, otherwise reset to previous state
  70. // TODO design a more elegant option state saving & restoring system, though that requires saving the options state in OSMD
  71. var minMeasureToDrawStashed = 1;
  72. var maxMeasureToDrawStashed = Number.MAX_SAFE_INTEGER;
  73. var measureToDrawRangeNeedsReset = false;
  74. var autobeamOptionNeedsReset = false;
  75. var autobeamOptionStashedValue = false;
  76. var autoCustomColoringOptionNeedsReset = false;
  77. var autoCustomColoringOptionStashedValue = false;
  78. var drawPartNamesOptionStashedValue = true;
  79. var drawPartNamesOptionNeedsReset = false;
  80. // Initialization code
  81. function init() {
  82. var name, option;
  83. err = document.getElementById("error-td");
  84. error_tr = document.getElementById("error-tr");
  85. zoomDiv = document.getElementById("zoom-str");
  86. custom = document.createElement("option");
  87. selectSample = document.getElementById("selectSample");
  88. selectBounding = document.getElementById("selectBounding");
  89. skylineDebug = document.getElementById("skylineDebug");
  90. bottomlineDebug = document.getElementById("bottomlineDebug");
  91. zoomIn = document.getElementById("zoom-in-btn");
  92. zoomOut = document.getElementById("zoom-out-btn");
  93. canvas = document.createElement("div");
  94. //canvas.style.overflowX = 'auto'; // enable horizontal scrolling
  95. nextCursorBtn = document.getElementById("next-cursor-btn");
  96. resetCursorBtn = document.getElementById("reset-cursor-btn");
  97. followCursorCheckbox = document.getElementById("follow-cursor-checkbox");
  98. showCursorBtn = document.getElementById("show-cursor-btn");
  99. hideCursorBtn = document.getElementById("hide-cursor-btn");
  100. backendSelect = document.getElementById("backend-select");
  101. debugReRenderBtn = document.getElementById("debug-re-render-btn");
  102. debugClearBtn = document.getElementById("debug-clear-btn");
  103. // Hide error
  104. error();
  105. // Create select
  106. for (name in samples) {
  107. if (samples.hasOwnProperty(name)) {
  108. option = document.createElement("option");
  109. option.value = samples[name];
  110. option.textContent = name;
  111. }
  112. selectSample.appendChild(option);
  113. }
  114. selectSample.onchange = selectSampleOnChange;
  115. if (selectBounding) {
  116. selectBounding.onchange = selectBoundingOnChange;
  117. }
  118. // Pre-select default music piece
  119. custom.appendChild(document.createTextNode("Custom"));
  120. // Create zoom controls
  121. zoomIn.onclick = function () {
  122. zoom *= 1.2;
  123. scale();
  124. };
  125. zoomOut.onclick = function () {
  126. zoom /= 1.2;
  127. scale();
  128. };
  129. if (skylineDebug) {
  130. skylineDebug.onclick = function() {
  131. openSheetMusicDisplay.DrawSkyLine = !openSheetMusicDisplay.DrawSkyLine;
  132. }
  133. }
  134. if (bottomlineDebug) {
  135. bottomlineDebug.onclick = function() {
  136. openSheetMusicDisplay.DrawBottomLine = !openSheetMusicDisplay.DrawBottomLine;
  137. }
  138. }
  139. if (debugReRenderBtn) {
  140. debugReRenderBtn.onclick = function() {
  141. rerender();
  142. }
  143. }
  144. if (debugClearBtn) {
  145. debugClearBtn.onclick = function() {
  146. openSheetMusicDisplay.clear();
  147. }
  148. }
  149. // Create OSMD object and canvas
  150. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, {
  151. autoResize: true,
  152. backend: backendSelect.value,
  153. disableCursor: false,
  154. drawingParameters: "default", // try compact (instead of default)
  155. drawPartNames: true, // try false
  156. // drawTitle: false,
  157. // drawSubtitle: false,
  158. //drawFromMeasureNumber: 4,
  159. //drawUpToMeasureNumber: 8,
  160. drawFingerings: true,
  161. fingeringPosition: "auto", // left is default. try right. experimental: auto, above, below.
  162. // fingeringInsideStafflines: "true", // default: false. true draws fingerings directly above/below notes
  163. setWantedStemDirectionByXml: true, // try false, which was previously the default behavior
  164. // drawUpToMeasureNumber: 3, // draws only up to measure 3, meaning it draws measure 1 to 3 of the piece.
  165. // coloring options
  166. coloringEnabled: true,
  167. // defaultColorNotehead: "#CC0055", // try setting a default color. default is black (undefined)
  168. // defaultColorStem: "#BB0099",
  169. autoBeam: false, // try true, OSMD Function Test AutoBeam sample
  170. autoBeamOptions: {
  171. beam_rests: false,
  172. beam_middle_rests_only: false,
  173. //groups: [[3,4], [1,1]],
  174. maintain_stem_directions: false
  175. },
  176. // tupletsBracketed: true, // creates brackets for all tuplets except triplets, even when not set by xml
  177. // tripletsBracketed: true,
  178. // tupletsRatioed: true, // unconventional; renders ratios for tuplets (3:2 instead of 3 for triplets)
  179. });
  180. openSheetMusicDisplay.setLogLevel('info');
  181. document.body.appendChild(canvas);
  182. window.addEventListener("keydown", function(e) {
  183. var event = window.event ? window.event : e;
  184. if (event.keyCode === 39) {
  185. openSheetMusicDisplay.cursor.next();
  186. }
  187. });
  188. nextCursorBtn.addEventListener("click", function() {
  189. openSheetMusicDisplay.cursor.next();
  190. });
  191. resetCursorBtn.addEventListener("click", function() {
  192. openSheetMusicDisplay.cursor.reset();
  193. });
  194. if (followCursorCheckbox) {
  195. followCursorCheckbox.onclick = function() {
  196. openSheetMusicDisplay.FollowCursor = !openSheetMusicDisplay.FollowCursor;
  197. }
  198. }
  199. hideCursorBtn.addEventListener("click", function() {
  200. openSheetMusicDisplay.cursor.hide();
  201. });
  202. showCursorBtn.addEventListener("click", function() {
  203. if (openSheetMusicDisplay.cursor) {
  204. openSheetMusicDisplay.cursor.show();
  205. } else {
  206. console.info("Can't show cursor, as it was disabled (e.g. by drawingParameters).");
  207. }
  208. });
  209. backendSelect.addEventListener("change", function(e) {
  210. var value = e.target.value;
  211. var createNewOsmd = true;
  212. if (createNewOsmd) {
  213. // clears the canvas element
  214. canvas.innerHTML = "";
  215. openSheetMusicDisplay = new OpenSheetMusicDisplay(canvas, {backend: value});
  216. openSheetMusicDisplay.setLogLevel('info');
  217. } else {
  218. // alternative, doesn't work yet, see setOptions():
  219. openSheetMusicDisplay.setOptions({backend: value});
  220. }
  221. selectSampleOnChange();
  222. });
  223. }
  224. function selectBoundingOnChange(evt) {
  225. var value = evt.target.value;
  226. openSheetMusicDisplay.DrawBoundingBox = value;
  227. }
  228. function selectSampleOnChange(str) {
  229. error();
  230. disable();
  231. var isCustom = typeof str === "string";
  232. if (!isCustom) {
  233. str = sampleFolder + selectSample.value;
  234. }
  235. zoom = 1.0;
  236. setSampleSpecificOptions(str, isCustom);
  237. openSheetMusicDisplay.load(str).then(
  238. function() {
  239. // This gives you access to the osmd object in the console. Do not use in productive code
  240. window.osmd = openSheetMusicDisplay;
  241. return openSheetMusicDisplay.render();
  242. },
  243. function(e) {
  244. errorLoadingOrRenderingSheet(e, "rendering");
  245. }
  246. ).then(
  247. function() {
  248. return onLoadingEnd(isCustom);
  249. }, function(e) {
  250. errorLoadingOrRenderingSheet(e, "loading");
  251. onLoadingEnd(isCustom);
  252. }
  253. );
  254. }
  255. function setSampleSpecificOptions(str, isCustom) {
  256. if (!isCustom && str.includes("measuresToDraw")) { // set options for measuresToDraw sample
  257. // stash previously set range of measures to draw
  258. if (!measureToDrawRangeNeedsReset) { // only stash once, when measuresToDraw called multiple times in a row
  259. minMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MinMeasureToDrawIndex + 1;
  260. maxMeasureToDrawStashed = openSheetMusicDisplay.EngravingRules.MaxMeasureToDrawIndex + 1;
  261. }
  262. measureToDrawRangeNeedsReset = true;
  263. // for debugging: draw from a random range of measures
  264. let minMeasureToDraw = Math.ceil(Math.random() * 15); // measures start at 1 (measureIndex = measure number - 1 elsewhere)
  265. let maxMeasureToDraw = Math.ceil(Math.random() * 15);
  266. if (minMeasureToDraw > maxMeasureToDraw) {
  267. minMeasureToDraw = maxMeasureToDraw;
  268. let a = minMeasureToDraw;
  269. maxMeasureToDraw = a;
  270. }
  271. //minMeasureToDraw = 1; // set your custom indexes here. Drawing only one measure can be a special case
  272. //maxMeasureToDraw = 1;
  273. console.log("drawing measures in the range: [" + minMeasureToDraw + "," + maxMeasureToDraw + "]");
  274. openSheetMusicDisplay.setOptions({
  275. drawFromMeasureNumber: minMeasureToDraw,
  276. drawUpToMeasureNumber: maxMeasureToDraw
  277. });
  278. } else if (measureToDrawRangeNeedsReset) { // reset for other samples
  279. openSheetMusicDisplay.setOptions({
  280. drawFromMeasureNumber: minMeasureToDrawStashed,
  281. drawUpToMeasureNumber: maxMeasureToDrawStashed
  282. });
  283. measureToDrawRangeNeedsReset = false;
  284. }
  285. // Enable Boomwhacker-like coloring for OSMD Function Test - Auto-Coloring (Boomwhacker-like, custom color set)
  286. if (!isCustom && str.includes("auto-custom-coloring")) { // set options for auto coloring sample
  287. autoCustomColoringOptionNeedsReset = true;
  288. //openSheetMusicDisplay.setOptions({coloringMode: 1}); // Auto-Coloring with pre-defined colors
  289. openSheetMusicDisplay.setOptions({
  290. coloringMode: 2, // custom coloring set. 0 would be XML, 1 autocoloring
  291. coloringSetCustom: ["#d82c6b", "#F89D15", "#FFE21A", "#4dbd5c", "#009D96", "#43469d", "#76429c", "#ff0000"],
  292. // last color value of coloringSetCustom is for rest notes
  293. colorStemsLikeNoteheads: true
  294. });
  295. } else if (autoCustomColoringOptionNeedsReset) {
  296. openSheetMusicDisplay.setOptions({ // set default values. better would be to restore to stashed values, but unnecessarily complex for demo
  297. coloringMode: 0,
  298. colorStemsLikeNoteheads: false,
  299. coloringSetCustom: null});
  300. autoCustomColoringOptionNeedsReset = false;
  301. }
  302. if (!isCustom && str.includes("autobeam")) {
  303. autobeamOptionStashedValue = openSheetMusicDisplay.EngravingRules.AutoBeamNotes; // stash previously set value, to restore later
  304. autobeamOptionNeedsReset = true;
  305. openSheetMusicDisplay.setOptions({autoBeam: true});
  306. } else if (autobeamOptionNeedsReset) {
  307. openSheetMusicDisplay.setOptions({autoBeam: autobeamOptionStashedValue});
  308. autobeamOptionNeedsReset = false;
  309. }
  310. if (!isCustom && str.includes("Schubert_An_die_Musik")) { // TODO weird layout bug here with part names. but shouldn't be in score anyways
  311. drawPartNamesOptionStashedValue = openSheetMusicDisplay.EngravingRules.RenderPartNames;
  312. openSheetMusicDisplay.setOptions({drawPartNames: false}); // TODO sets osmd.drawingParameters.DrawPartNames! also check EngravingRules.RenderPartAbbreviations, was false
  313. drawPartNamesOptionNeedsReset = true;
  314. } else if (drawPartNamesOptionNeedsReset) {
  315. openSheetMusicDisplay.setOptions({drawPartNames: drawPartNamesOptionStashedValue});
  316. drawPartNamesOptionNeedsReset = false;
  317. }
  318. }
  319. function errorLoadingOrRenderingSheet(e, loadingOrRenderingString) {
  320. var errorString = "Error " + loadingOrRenderingString + " sheet: " + e;
  321. // if (process.env.DEBUG) { // people may not set a debug environment variable for the demo.
  322. // Always giving a StackTrace might give us more and better error reports.
  323. // TODO for a release, StackTrace control could be reenabled
  324. errorString += "\n" + "StackTrace: \n" + e.stack;
  325. // }
  326. console.warn(errorString);
  327. }
  328. function onLoadingEnd(isCustom) {
  329. // Remove option from select
  330. if (!isCustom && custom.parentElement === selectSample) {
  331. selectSample.removeChild(custom);
  332. }
  333. // Enable controls again
  334. enable();
  335. }
  336. function logCanvasSize() {
  337. zoomDiv.innerHTML = Math.floor(zoom * 100.0) + "%";
  338. }
  339. function scale() {
  340. disable();
  341. window.setTimeout(function(){
  342. openSheetMusicDisplay.zoom = zoom;
  343. openSheetMusicDisplay.render();
  344. enable();
  345. }, 0);
  346. }
  347. function rerender() {
  348. disable();
  349. window.setTimeout(function(){
  350. if (openSheetMusicDisplay.IsReadyToRender()) {
  351. openSheetMusicDisplay.render();
  352. } else {
  353. selectSampleOnChange(); // reload sample e.g. after osmd.clear()
  354. }
  355. enable();
  356. }, 0);
  357. }
  358. function error(errString) {
  359. if (!errString) {
  360. error_tr.style.display = "none";
  361. } else {
  362. err.textContent = errString;
  363. error_tr.style.display = "";
  364. canvas.width = canvas.height = 0;
  365. enable();
  366. }
  367. }
  368. // Enable/Disable Controls
  369. function disable() {
  370. document.body.style.opacity = 0.3;
  371. selectSample.disabled = zoomIn.disabled = zoomOut.disabled = "disabled";
  372. }
  373. function enable() {
  374. document.body.style.opacity = 1;
  375. selectSample.disabled = zoomIn.disabled = zoomOut.disabled = "";
  376. logCanvasSize();
  377. }
  378. // Register events: load, drag&drop
  379. window.addEventListener("load", function() {
  380. init();
  381. selectSampleOnChange();
  382. });
  383. window.addEventListener("dragenter", function(event) {
  384. event.preventDefault();
  385. disable();
  386. });
  387. window.addEventListener("dragover", function(event) {
  388. event.preventDefault();
  389. });
  390. window.addEventListener("dragleave", function(event) {
  391. enable();
  392. });
  393. window.addEventListener("drop", function(event) {
  394. event.preventDefault();
  395. if (!event.dataTransfer || !event.dataTransfer.files || event.dataTransfer.files.length === 0) {
  396. return;
  397. }
  398. // Add "Custom..." score
  399. selectSample.appendChild(custom);
  400. custom.selected = "selected";
  401. // Read dragged file
  402. var reader = new FileReader();
  403. reader.onload = function (res) {
  404. selectSampleOnChange(res.target.result);
  405. };
  406. var filename = event.dataTransfer.files[0].name;
  407. if (filename.toLowerCase().indexOf(".xml") > 0
  408. || filename.toLowerCase().indexOf(".musicxml") > 0) {
  409. reader.readAsText(event.dataTransfer.files[0]);
  410. } else if (event.dataTransfer.files[0].name.toLowerCase().indexOf(".mxl") > 0){
  411. reader.readAsBinaryString(event.dataTransfer.files[0]);
  412. }
  413. else {
  414. alert("No vaild .xml/.mxl/.musicxml file!");
  415. }
  416. });
  417. }());