-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathedirom-verovio-renderer-component.js
More file actions
468 lines (397 loc) · 15.5 KB
/
edirom-verovio-renderer-component.js
File metadata and controls
468 lines (397 loc) · 15.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
/**
* Custom Web Component for rendering MEI files using the Verovio toolkit.
*
* <edirom-verovio-renderer> provides an interface to load, render, and interact with MEI music notation files
* using the Verovio JavaScript toolkit. It supports dynamic attribute changes, zooming, page navigation,
* and measure/movement navigation.
*
* @class
* @extends HTMLElement
*
* @example
* <edirom-verovio-renderer meiurl="path/to/file.mei"></edirom-verovio-renderer>
*
* @attribute {string} meiurl - The URL of the MEI file to render.
* @attribute {number} zoom - The zoom level (scale) for rendering.
* @attribute {number} pagenumber - The current page number to display.
* @attribute {number} height - The height of the rendered page.
* @attribute {number} width - The width of the rendered page.
* @attribute {string} verovio-url - The URL to the Verovio toolkit JS file.
* @attribute {object|string} verovio-options - Options for Verovio rendering.
* @attribute {string} elementid - The element id to navigate to.
* @attribute {string} measurenumber - The measure number to navigate to.
* @attribute {string} mdivname - The name/label of the movement division.
* @attribute {string} movementid - The XML ID of the movement to display.
* @attribute {number} pagewidth - The width of the rendered page in Verovio units.
* @attribute {number} pageheight - The height of the rendered page in Verovio units.
*
* @fires communicate-[property]-update - Fired when a property is updated via attribute change.
* @fires page-info-update - Fired after rendering, with current page and total pages.
*/
class EdiromVerovioRenderer extends HTMLElement {
/**
* Creates an instance of EdiromVerovioRenderer.
* @constructor
*/
constructor() {
super();
/** attach shadow root with mode "open" */
this.attachShadow({ mode: 'open' });
/** global variables */
this.tk = null;
this.totalPages = 0;
/** set global properties */
this.veroviourl = this.getAttribute('verovio-url') || "https://www.verovio.org/javascript/5.3.2/verovio-toolkit-wasm.js";
this.options = this.getAttribute("verovio-options") || {
};
this.meiurl = this.getAttribute('meiurl') || "";
this.zoom = this.getAttribute("zoom") || 20;
this.pageNumber = this.getAttribute("pagenumber") || 1;
this.shadowRoot.innerHTML += `
<div id="verovio-svg"></div>
`;
}
/**
* Lifecycle callback invoked when the custom element is added to the DOM.
*/
connectedCallback() {
/** load the verovio library */
import(this.veroviourl)
.then((module) => {
verovio.module.onRuntimeInitialized = () => {
this.tk = new verovio.toolkit();
/** set rendering options for verovio */
this.tk.setOptions(this.options);
/** fetch the mei file and render svg */
this.fetchAndRenderMEI();
};
})
.catch((err) => {
console.error(err.message);
});
this.verovioElement = this;
}
/**
* Returns the list of observed attributes for the EdiromVerovioRenderer custom element.
* @static
* @returns {Array<string>} The list of observed attributes.
*/
static get observedAttributes() {
return ['zoom', 'pagenumber', 'meiurl', 'elementid', 'measurenumber', 'mdivname', "movementid", "pagewidth", "pageheight", "verovio-url", "verovio-options", "verovio-breaks"];
}
/**
* Invoked when the custom element is disconnected from the document's DOM.
*/
disconnectedCallback() { }
/**
* Invoked when the custom element is moved to a new document.
*/
adoptedCallback() { }
/**
* Invoked when one of the custom element's attributes is added, removed, or changed.
* @param {string} property - The name of the attribute that was changed.
* @param {*} oldValue - The previous value of the attribute.
* @param {*} newValue - The new value of the attribute.
*/
attributeChangedCallback(property, oldValue, newValue) {
// handle property change
this.set(property, newValue);
}
/**
* Sets the value of a global property and triggers property update events.
* @param {string} property - The name of the property to set.
* @param {*} newPropertyValue - The new value to set for the property.
*/
set(property, newPropertyValue) {
/** set internal and html properties */
this[property] = newPropertyValue;
/** custom event for property update */
const event = new CustomEvent('communicate-' + property + '-update', {
detail: {
element: this.tagName.toLowerCase(),
property: property,
value: newPropertyValue
},
bubbles: true
});
this.dispatchEvent(event);
this.handlePropertyChange(property, newPropertyValue)
}
/**
* Handles property changes for the verovio rendering component.
* @param {string} property - The name of the property being changed.
* @param {any} newPropertyValue - The new value of the property.
*/
handlePropertyChange(property, newPropertyValue) {
switch (property) {
case 'zoom':
this.zoom = parseInt(newPropertyValue);
this.options['scale'] = this.zoom;
this.tk?.setOptions(this.options);
this.renderSVG();
break;
case 'pagenumber':
this.pageNumber = parseInt(newPropertyValue);
this.renderSVG();
break;
case 'meiurl':
this.meiurl = newPropertyValue;
this.fetchAndRenderMEI();
break;
case 'elementid':
this.elementid = newPropertyValue;
this.gotoElementId(newPropertyValue);
break;
case 'measurenumber':
this.gotoMeasure(newPropertyValue);
break;
case 'mdivname':
this.mdivname = newPropertyValue;
this.gotoMdiv(newPropertyValue);
break;
case 'movementid':
this.movementid = newPropertyValue;
this.gotoElementId(newPropertyValue);
case 'pagewidth':
this.verovioWidth = parseInt(newPropertyValue);
if(!isNaN(this.verovioWidth) && this.verovioWidth >= 100 && this.verovioWidth <= 100000) {
this.options['pageWidth'] = this.verovioWidth;
this.tk?.setOptions(this.options);
this.tk?.loadData(this.meiData);
this.renderSVG();
}
break;
case 'pageheight':
this.verovioHeight = parseInt(newPropertyValue);
if(!isNaN(this.verovioHeight) && this.verovioHeight >= 100 && this.verovioHeight <= 60000) {
this.options['pageHeight'] = this.verovioHeight;
this.tk?.setOptions(this.options);
this.tk?.loadData(this.meiData);
this.renderSVG();
}
break;
case 'verovio-breaks':
this.options['breaks'] = newPropertyValue;
this.tk?.setOptions(this.options);
this.tk?.loadData(this.meiData);
this.renderSVG();
break;
case 'verovio-options':
try {
const newOptions = typeof newPropertyValue === 'string'
? JSON.parse(newPropertyValue)
: newPropertyValue;
this.options = { ...this.options, ...newOptions };
this.tk?.setOptions(this.options);
this.tk?.loadData(this.meiData);
this.renderSVG();
} catch (e) {
console.error('Invalid verovio-options format:', e);
}
break;
}
}
/**
* Navigates to the page containing the specified element ID, updates the current page number,
* and re-renders the SVG. Logs the navigation action or warns if the element is not found.
*
* @param {string} elementId - The ID of the element to navigate to.
*/
gotoElementId(elementId) {
const page = this.tk.getPageWithElement(elementId);
if (page) {
this.pageNumber = page;
this.renderSVG();
}
}
/**
* Navigates to the measure with the specified measure number.
* If the measure exists, scrolls to its corresponding element and logs the navigation.
* If not found, logs a warning to the console.
*
* @param {number|string} measureNumber - The number of the measure to navigate to.
*/
gotoMeasure(measureNumber) {
const measureId = this.getMeasureIdByNumber(measureNumber);
if (measureId) {
this.gotoElementId(measureId);
} else {
console.warn(`Measure with n="${measureNumber}" not found`);
}
}
/**
* Navigates to a specific movement (mdiv) in the document based on the provided movement label.
*
* @param {string} movementLabel - The label or number identifying the movement to navigate to.
*/
gotoMdiv(movementLabel) {
const mdivid = this.getMeasureIdByNumber(movementLabel);
if (mdivid) {
this.gotoElementId(mdivid);
} else {
console.warn(`Movement with n="${movementLabel}" not found`);
}
}
/**
* Retrieves the XML ID of a <measure> element by its "n" attribute value.
*
* If a specific <mdiv> label is set in `this.mdivname`, the search is limited to that <mdiv>.
* Otherwise, the search is performed across all <measure> elements in the MEI document.
*
* @param {number|string} nValue - The value of the "n" attribute to match in <measure> elements.
* @returns {string|null} The "xml:id" attribute of the matching <measure>, or null if not found.
*/
getMeasureIdByNumber(nValue) {
const parser = new DOMParser();
const xmlDoc = parser.parseFromString(this.meiData, "application/xml");
let measures;
if (this.mdivname) {
// Find the <mdiv> with the label attribute
const mdiv = xmlDoc.querySelector(`mdiv[label="${this.mdivname}"]`);
if (!mdiv) {
console.warn(`No <mdiv> found with label="${this.mdivname}"`);
return null;
}
// Only search within this mdiv
measures = mdiv.querySelectorAll("measure");
} else {
// No mdiv specified, search all measures in the document
measures = xmlDoc.querySelectorAll("measure");
}
// Look for a measure with matching n value
for (let measure of measures) {
if (measure.getAttribute("n") === nValue.toString()) {
return measure.getAttribute("xml:id"); // Verovio needs this
}
}
console.warn(`No <measure n="${nValue}"> found ${this.mdivname ? `in <mdiv label="${this.mdivname}">` : "in the MEI file"}`);
return null;
}
/**
* Adjusts the zoom level of the renderer component.
*
* Increases or decreases the zoom value by 10 based on the provided type ("zoomUp" or "zoomDown").
* Ensures the zoom stays within the range of 10 to 100.
* Updates the rendering options and re-renders the SVG with the new zoom value.
*
* @param {string} type - The type of zoom operation ("zoomUp" to increase, "zoomDown" to decrease).
*/
calculateZoom(type) {
this.zoom = parseInt(this.zoom)
this.zoom += type === "zoomUp" ? 10 : -10;
this.zoom = Math.max(10, Math.min(this.zoom, 100));
if (this.zoom <= 100) {
// Get the current options
let options = this.tk.getOptions();
// Update the zoom value
options.scale = this.zoom;
// Set the updated options
this.tk.setOptions(options);
// Re-render the SVG with the updated options
this.renderSVG();
}
}
/**
* Updates the page dimensions based on the current height, width, and zoom level.
* Calculates and sets the pageHeight and pageWidth properties, updates the options object,
* and triggers reloading and rendering of the MEI data.
* Uses a debounced approach to avoid excessive updates.
*/
updatePageDimensions() {
var timeout;
var context = this;
var later = function() {
timeout = null;
if (context.height != null && context.width != null) {
context.pageHeight = parseInt(context.height.toString().replaceAll("px", "")) * 100 / context.zoom;
context.pageWidth = parseInt(context.width.toString().replaceAll("px", "")) * 100 / context.zoom;
context.options['pageHeight'] = parseInt(context.pageHeight);
context.options['pageWidth'] = parseInt(context.pageWidth);
context.tk?.setOptions(context.options);
context.tk?.loadData(context.meiData);
context.renderSVG();
}
};
clearTimeout(timeout);
timeout = setTimeout(later, 100);
}
/**
* Fetches MEI data from an URL (optionally including a movement ID),
* loads the MEI data into the toolkit, and renders the SVG.
* Handles errors that may occur during the fetch operation.
*/
fetchAndRenderMEI() {
let url;
if (this.movementid) {
url = this.meiurl + "&movementId=" + this.movementid;
} else {
url = this.meiurl;
}
fetch(url)
.then((response) => response.text())
.then((mei) => {
this.meiData = mei;
this.tk.loadData(mei); // Load MEI
this.renderSVG(); // Render
})
.catch((error) => {
console.error("Error fetching MEI:", error);
});
}
/**
* Updates the current page number based on the navigation type ("next" or "previous"),
* ensuring it stays within the valid range [1, totalPages]. Triggers SVG rendering if the new page is valid.
*
* @param {string} type - The navigation type, either "next" to increment or "previous" to decrement the page number.
*/
calculatePageNumber(type) {
this.pageNumber += type === "next" ? 1 : -1;
this.pageNumber = Math.max(1, Math.min(this.pageNumber, this.totalPages));
if (this.pageNumber <= this.totalPages) {
this.renderSVG();
}
}
/**
* Renders the current page as SVG using the Verovio toolkit and updates the component's shadow DOM.
* Ensures the current page number is valid, updates the SVG content, and dispatches a 'page-info-update' event
* with the current page number and total number of pages.
*
* @fires CustomEvent#page-info-update - Dispatched after rendering, contains the current page number and total pages.
*/
renderSVG() {
this.totalPages = this.tk?.getPageCount();
this.pageNumber = (!isNaN(this.pageNumber) && !isNaN(this.totalPages) && this.pageNumber >= 1 && this.pageNumber <= this.totalPages) ? this.pageNumber : 1;
let svg = this.tk?.renderToSVG(this.pageNumber);
this.shadowRoot.getElementById("verovio-svg").innerHTML = svg;
const svgElement = this.shadowRoot.querySelector("svg");
// Calculate SVG dimensions based on viewBox
const viewBox = svgElement.getAttribute('viewBox');
if (viewBox) {
// Parse viewBox string: "minX minY width height"
const viewBoxParts = viewBox.split(' ').map(Number);
const vbWidth = viewBoxParts[2];
const vbHeight = viewBoxParts[3];
if (!isNaN(vbWidth) && !isNaN(vbHeight) && vbWidth > 0 && vbHeight > 0) {
// Calculate aspect ratio
const aspectRatio = vbHeight / vbWidth;
const pxPerVerovioUnit = this.verovioWidth > 0 ? 420 / this.verovioWidth : 0.02;
// Calculate dimensions in pixels based on viewBox and reference width
const width = Math.round(vbWidth * pxPerVerovioUnit);
const height = Math.round(width * aspectRatio);
// Set width and height in pixels
svgElement.setAttribute('width', width + 'px');
svgElement.setAttribute('height', height + 'px');
console.log('ViewBox:', viewBox, '| Calculated SVG: ', width + 'px x ' + height + 'px');
}
}
this.dispatchEvent(new CustomEvent('page-info-update', {
detail: {
pageNumber: this.pageNumber,
totalPages: this.totalPages
},
bubbles: true
}));
}
}
/** Define the custom element */
customElements.define('edirom-verovio-renderer', EdiromVerovioRenderer);