index.js 18 KB

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