index.js 17 KB

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