vexflow 5.1.0 → 5.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +18 -6
- package/build/cjs/vexflow-bravura.js +2 -2
- package/build/cjs/vexflow-bravura.js.map +1 -1
- package/build/cjs/vexflow-core.js +2 -2
- package/build/cjs/vexflow-core.js.map +1 -1
- package/build/cjs/vexflow-debug-with-tests.js +427 -83
- package/build/cjs/vexflow-debug-with-tests.js.map +1 -1
- package/build/cjs/vexflow-debug.js +427 -83
- package/build/cjs/vexflow-debug.js.map +1 -1
- package/build/cjs/vexflow.js +2 -2
- package/build/cjs/vexflow.js.map +1 -1
- package/build/esm/src/chordkerning.js +98 -0
- package/build/esm/src/chordsymbol.js +108 -27
- package/build/esm/src/element.js +7 -2
- package/build/esm/src/font.js +3 -1
- package/build/esm/src/metrics.js +4 -3
- package/build/esm/src/textmetricscache.js +93 -0
- package/build/esm/src/version.js +3 -3
- package/build/esm/tests/node/chord-kerning-tests.mjs +173 -0
- package/build/esm/tests/node/metrics-tests.mjs +278 -0
- package/build/esm/tests/node/tool-security-tests.mjs +85 -0
- package/build/types/src/chordkerning.d.ts +42 -0
- package/build/types/src/chordsymbol.d.ts +19 -0
- package/build/types/src/element.d.ts +2 -0
- package/build/types/src/textmetricscache.d.ts +21 -0
- package/changelog/CHANGELOG.md +37 -0
- package/package.json +16 -7
- package/tests/flow.html +10 -3
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
import { Font } from './font.js';
|
|
2
|
+
import { Glyphs } from './glyphs.js';
|
|
3
|
+
function scriptPairs(a, f) {
|
|
4
|
+
const symbols = [Glyphs.csymDiminished, Glyphs.csymHalfDiminished, Glyphs.csymMajorSeventh];
|
|
5
|
+
return symbols.flatMap((right) => [
|
|
6
|
+
{ left: 'A', right, position: 'superscript', adjustmentEm: a },
|
|
7
|
+
{ left: 'F', right, position: 'subscript', adjustmentEm: f },
|
|
8
|
+
]);
|
|
9
|
+
}
|
|
10
|
+
const profiles = [
|
|
11
|
+
{ textFont: 'Academico', musicFont: 'Bravura', pairs: scriptPairs(-0.18, -0.12) },
|
|
12
|
+
{ textFont: 'Petaluma Script', musicFont: 'Petaluma', pairs: scriptPairs(-0.12, -0.08) },
|
|
13
|
+
];
|
|
14
|
+
function normalWeight(weight) {
|
|
15
|
+
return weight === undefined || weight === '' || weight === 'normal' ? '400' : String(weight);
|
|
16
|
+
}
|
|
17
|
+
export function chordKerningProfile(font, custom) {
|
|
18
|
+
var _a;
|
|
19
|
+
const families = ((_a = font.family) !== null && _a !== void 0 ? _a : '').split(',').map((family) => family.trim().replace(/^['"]|['"]$/g, ''));
|
|
20
|
+
return (custom ? [custom] : profiles).find((profile) => families[0] === profile.textFont &&
|
|
21
|
+
families[1] === profile.musicFont &&
|
|
22
|
+
normalWeight(font.weight) === normalWeight(profile.weight) &&
|
|
23
|
+
(font.style || 'normal') === (profile.style || 'normal'));
|
|
24
|
+
}
|
|
25
|
+
function musicCharacter(character) {
|
|
26
|
+
return /[\uE870-\uE87F\uED60-\uED67\uE260-\uE26F]/u.test(character);
|
|
27
|
+
}
|
|
28
|
+
function groups(blocks) {
|
|
29
|
+
const result = [];
|
|
30
|
+
for (const block of blocks) {
|
|
31
|
+
if (!block.text)
|
|
32
|
+
continue;
|
|
33
|
+
const previous = result[result.length - 1];
|
|
34
|
+
if ((previous === null || previous === void 0 ? void 0 : previous.position) === block.position)
|
|
35
|
+
previous.text += block.text;
|
|
36
|
+
else
|
|
37
|
+
result.push(Object.assign({}, block));
|
|
38
|
+
}
|
|
39
|
+
return result;
|
|
40
|
+
}
|
|
41
|
+
function spans(text) {
|
|
42
|
+
const result = [];
|
|
43
|
+
for (const character of text) {
|
|
44
|
+
const music = musicCharacter(character);
|
|
45
|
+
const previous = result[result.length - 1];
|
|
46
|
+
if ((previous === null || previous === void 0 ? void 0 : previous.music) === music)
|
|
47
|
+
previous.text += character;
|
|
48
|
+
else
|
|
49
|
+
result.push({ text: character, music });
|
|
50
|
+
}
|
|
51
|
+
return result;
|
|
52
|
+
}
|
|
53
|
+
function adjustment(profile, left, right, position) {
|
|
54
|
+
var _a, _b;
|
|
55
|
+
const last = Array.from(left).slice(-1)[0];
|
|
56
|
+
const first = Array.from(right)[0];
|
|
57
|
+
return ((_b = (_a = profile.pairs.find((pair) => pair.left === last && pair.right === first && pair.position === position)) === null || _a === void 0 ? void 0 : _a.adjustmentEm) !== null && _b !== void 0 ? _b : 0);
|
|
58
|
+
}
|
|
59
|
+
export function layoutChordRuns(blocks, font, profile, options, measure) {
|
|
60
|
+
var _a, _b;
|
|
61
|
+
const em = Font.convertSizeToPixelValue((_a = font.size) !== null && _a !== void 0 ? _a : 12);
|
|
62
|
+
const runs = [];
|
|
63
|
+
let cursor = 0;
|
|
64
|
+
let previousText = '';
|
|
65
|
+
let stack;
|
|
66
|
+
for (const group of groups(blocks)) {
|
|
67
|
+
const script = group.position !== 'baseline';
|
|
68
|
+
const stacked = script && stack && stack.position !== group.position;
|
|
69
|
+
let x = stacked ? stack.x : cursor;
|
|
70
|
+
if (!stacked && runs.length) {
|
|
71
|
+
x += options.spacing * em + adjustment(profile, previousText, group.text, group.position) * em;
|
|
72
|
+
}
|
|
73
|
+
const anchor = x;
|
|
74
|
+
const y = group.position === 'superscript'
|
|
75
|
+
? options.superscript * em
|
|
76
|
+
: group.position === 'subscript'
|
|
77
|
+
? options.subscript * em
|
|
78
|
+
: 0;
|
|
79
|
+
let previousSpan = '';
|
|
80
|
+
for (const span of spans(group.text)) {
|
|
81
|
+
if (previousSpan)
|
|
82
|
+
x += adjustment(profile, previousSpan, span.text, group.position) * em;
|
|
83
|
+
const runFont = Object.assign(Object.assign({}, font), { family: span.music ? profile.musicFont : profile.textFont, size: script ? Font.scaleSize((_b = font.size) !== null && _b !== void 0 ? _b : 12, options.ratio) : font.size });
|
|
84
|
+
const metrics = measure(span.text, runFont);
|
|
85
|
+
runs.push({ text: span.text, position: group.position, font: runFont, x, y, metrics });
|
|
86
|
+
x += metrics.width;
|
|
87
|
+
previousSpan = span.text;
|
|
88
|
+
}
|
|
89
|
+
cursor = stacked ? Math.max(stack.end, x) : x;
|
|
90
|
+
stack = script && !stacked ? { position: group.position, x: anchor, end: cursor } : undefined;
|
|
91
|
+
previousText = group.text;
|
|
92
|
+
}
|
|
93
|
+
const left = Math.min(0, ...runs.map((run) => run.x - run.metrics.actualBoundingBoxLeft));
|
|
94
|
+
const right = Math.max(cursor, ...runs.map((run) => run.x + run.metrics.actualBoundingBoxRight));
|
|
95
|
+
for (const run of runs)
|
|
96
|
+
run.x -= left;
|
|
97
|
+
return { runs, width: right - left };
|
|
98
|
+
}
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { BoundingBox } from './boundingbox.js';
|
|
2
|
+
import { chordKerningProfile, layoutChordRuns } from './chordkerning.js';
|
|
1
3
|
import { Element } from './element.js';
|
|
2
4
|
import { Font } from './font.js';
|
|
3
5
|
import { Glyphs } from './glyphs.js';
|
|
@@ -5,7 +7,7 @@ import { Metrics } from './metrics.js';
|
|
|
5
7
|
import { Modifier } from './modifier.js';
|
|
6
8
|
import { Tables } from './tables.js';
|
|
7
9
|
import { isStemmableNote } from './typeguard.js';
|
|
8
|
-
import { log } from './util.js';
|
|
10
|
+
import { log, RuntimeError } from './util.js';
|
|
9
11
|
function L(...args) {
|
|
10
12
|
if (ChordSymbol.DEBUG)
|
|
11
13
|
log('VexFlow.ChordSymbol', args);
|
|
@@ -74,26 +76,34 @@ export class ChordSymbol extends Modifier {
|
|
|
74
76
|
for (const symbol of symbols) {
|
|
75
77
|
const note = symbol.checkAttachedNote();
|
|
76
78
|
let lineSpaces = 1;
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
block.setXShift(width);
|
|
82
|
-
if (sup || sub) {
|
|
79
|
+
const kernedWidth = symbol.formatKerning();
|
|
80
|
+
if (kernedWidth !== undefined) {
|
|
81
|
+
width = kernedWidth;
|
|
82
|
+
if (symbol.symbolBlocks.some((block) => block.isSuperscript() || block.isSubscript()))
|
|
83
83
|
lineSpaces = 2;
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
(prev.getWidth() > block.getWidth() ? prev.getWidth() - block.getWidth() : 0);
|
|
84
|
+
}
|
|
85
|
+
else {
|
|
86
|
+
for (let j = 0; j < symbol.symbolBlocks.length; ++j) {
|
|
87
|
+
const block = symbol.symbolBlocks[j];
|
|
88
|
+
const sup = block.isSuperscript();
|
|
89
|
+
const sub = block.isSubscript();
|
|
90
|
+
block.setXShift(width);
|
|
91
|
+
if (sup || sub) {
|
|
92
|
+
lineSpaces = 2;
|
|
94
93
|
}
|
|
94
|
+
if (sub && j > 0) {
|
|
95
|
+
const prev = symbol.symbolBlocks[j - 1];
|
|
96
|
+
if (prev.isSuperscript()) {
|
|
97
|
+
block.setXShift(width - prev.getWidth() - ChordSymbol.minPadding);
|
|
98
|
+
block.vAlign = true;
|
|
99
|
+
width +=
|
|
100
|
+
-prev.getWidth() -
|
|
101
|
+
ChordSymbol.minPadding +
|
|
102
|
+
(prev.getWidth() > block.getWidth() ? prev.getWidth() - block.getWidth() : 0);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
width += block.getWidth() + ChordSymbol.minPadding;
|
|
95
106
|
}
|
|
96
|
-
width += block.getWidth() + ChordSymbol.minPadding;
|
|
97
107
|
}
|
|
98
108
|
if (symbol.getVertical() === ChordSymbolVerticalJustify.TOP) {
|
|
99
109
|
symbol.setTextLine(state.topTextLine);
|
|
@@ -121,8 +131,9 @@ export class ChordSymbol extends Modifier {
|
|
|
121
131
|
maxRightGlyphWidth = Math.max(glyphWidth / 2, maxRightGlyphWidth);
|
|
122
132
|
}
|
|
123
133
|
}
|
|
124
|
-
symbol.width = width;
|
|
125
134
|
}
|
|
135
|
+
if (symbol.getReportWidth() || symbol.kernedRuns)
|
|
136
|
+
symbol.width = width;
|
|
126
137
|
width = 0;
|
|
127
138
|
}
|
|
128
139
|
const rightOverlap = Math.min(Math.max(rightWidth - maxRightGlyphWidth, 0), Math.max(rightWidth - state.rightShift, 0));
|
|
@@ -131,12 +142,58 @@ export class ChordSymbol extends Modifier {
|
|
|
131
142
|
state.rightShift += rightOverlap;
|
|
132
143
|
return true;
|
|
133
144
|
}
|
|
145
|
+
setKerning(mode) {
|
|
146
|
+
if (mode !== 'auto' && mode !== 'none')
|
|
147
|
+
throw new RuntimeError('BadArgument', 'Kerning must be auto or none.');
|
|
148
|
+
this.kerning = mode;
|
|
149
|
+
this.kernedRuns = undefined;
|
|
150
|
+
return this;
|
|
151
|
+
}
|
|
152
|
+
getKerning() {
|
|
153
|
+
return this.kerning;
|
|
154
|
+
}
|
|
155
|
+
setKerningProfile(profile) {
|
|
156
|
+
if (profile &&
|
|
157
|
+
(!profile.textFont.trim() ||
|
|
158
|
+
!profile.musicFont.trim() ||
|
|
159
|
+
profile.pairs.some((pair) => Array.from(pair.left).length !== 1 ||
|
|
160
|
+
Array.from(pair.right).length !== 1 ||
|
|
161
|
+
!['baseline', 'superscript', 'subscript'].includes(pair.position) ||
|
|
162
|
+
!Number.isFinite(pair.adjustmentEm))))
|
|
163
|
+
throw new RuntimeError('BadArgument', 'Invalid chord kerning profile.');
|
|
164
|
+
this.kerningProfile = profile && Object.assign(Object.assign({}, profile), { pairs: profile.pairs.map((pair) => (Object.assign({}, pair))) });
|
|
165
|
+
this.kernedRuns = undefined;
|
|
166
|
+
return this;
|
|
167
|
+
}
|
|
168
|
+
formatKerning() {
|
|
169
|
+
var _a;
|
|
170
|
+
this.kernedRuns = undefined;
|
|
171
|
+
if (this.kerning === 'none')
|
|
172
|
+
return undefined;
|
|
173
|
+
const profile = chordKerningProfile(this.fontInfo, this.kerningProfile);
|
|
174
|
+
if (!profile)
|
|
175
|
+
return undefined;
|
|
176
|
+
const measurement = (_a = this.kerningMeasurement) !== null && _a !== void 0 ? _a : (this.kerningMeasurement = new Element());
|
|
177
|
+
const layout = layoutChordRuns(this.symbolBlocks.map((block) => ({
|
|
178
|
+
text: block.getText(),
|
|
179
|
+
position: block.isSuperscript() ? 'superscript' : block.isSubscript() ? 'subscript' : 'baseline',
|
|
180
|
+
})), this.fontInfo, profile, {
|
|
181
|
+
spacing: ChordSymbol.spacingBetweenBlocks,
|
|
182
|
+
ratio: ChordSymbol.superSubRatio,
|
|
183
|
+
superscript: ChordSymbol.superscriptOffset,
|
|
184
|
+
subscript: ChordSymbol.subscriptOffset,
|
|
185
|
+
}, (text, font) => measurement.setText(text).setFont(font).measureText());
|
|
186
|
+
this.kernedRuns = layout.runs;
|
|
187
|
+
return layout.width;
|
|
188
|
+
}
|
|
134
189
|
constructor() {
|
|
135
190
|
super();
|
|
136
191
|
this.symbolBlocks = [];
|
|
137
192
|
this.horizontal = ChordSymbolHorizontalJustify.LEFT;
|
|
138
193
|
this.vertical = ChordSymbolVerticalJustify.TOP;
|
|
139
194
|
this.reportWidth = true;
|
|
195
|
+
this.kerning = 'none';
|
|
196
|
+
this.kerningOrigin = { x: 0, y: 0 };
|
|
140
197
|
}
|
|
141
198
|
get superscriptOffset() {
|
|
142
199
|
return ChordSymbol.superscriptOffset * Font.convertSizeToPixelValue(this.fontInfo.size);
|
|
@@ -259,7 +316,7 @@ export class ChordSymbol extends Modifier {
|
|
|
259
316
|
x = start.x;
|
|
260
317
|
}
|
|
261
318
|
else if (this.horizontal === ChordSymbolHorizontalJustify.RIGHT) {
|
|
262
|
-
x = start.x + this.getWidth();
|
|
319
|
+
x = this.kernedRuns ? start.x - this.getWidth() : start.x + this.getWidth();
|
|
263
320
|
}
|
|
264
321
|
else if (this.horizontal === ChordSymbolHorizontalJustify.CENTER) {
|
|
265
322
|
x = start.x - this.getWidth() / 2;
|
|
@@ -268,17 +325,41 @@ export class ChordSymbol extends Modifier {
|
|
|
268
325
|
x = note.getStemX() - this.getWidth() / 2;
|
|
269
326
|
}
|
|
270
327
|
L('Rendering ChordSymbol: ', x, y);
|
|
271
|
-
this.
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
328
|
+
if (this.kernedRuns) {
|
|
329
|
+
this.kerningOrigin = { x, y };
|
|
330
|
+
for (const run of this.kernedRuns) {
|
|
331
|
+
ctx.setFont(run.font);
|
|
332
|
+
ctx.fillText(run.text, x + run.x, y + run.y);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
else {
|
|
336
|
+
this.symbolBlocks.forEach((symbol) => {
|
|
337
|
+
L('Rendering Text: ', symbol.getText(), x + symbol.getXShift(), y + symbol.getYShift());
|
|
338
|
+
symbol.setX(x);
|
|
339
|
+
symbol.setY(y);
|
|
340
|
+
symbol.renderText(ctx, 0, 0);
|
|
341
|
+
});
|
|
342
|
+
}
|
|
277
343
|
this.drawPointerRect();
|
|
278
344
|
ctx.closeGroup();
|
|
279
345
|
}
|
|
280
346
|
getBoundingBox() {
|
|
281
|
-
|
|
347
|
+
if (this.kernedRuns) {
|
|
348
|
+
const { x, y } = this.kerningOrigin;
|
|
349
|
+
let box;
|
|
350
|
+
for (const run of this.kernedRuns) {
|
|
351
|
+
const m = run.metrics;
|
|
352
|
+
const ink = new BoundingBox(x + run.x - m.actualBoundingBoxLeft, y + run.y - m.actualBoundingBoxAscent, m.actualBoundingBoxLeft + m.actualBoundingBoxRight, m.actualBoundingBoxAscent + m.actualBoundingBoxDescent);
|
|
353
|
+
if (box)
|
|
354
|
+
box.mergeWith(ink);
|
|
355
|
+
else
|
|
356
|
+
box = ink;
|
|
357
|
+
}
|
|
358
|
+
return box !== null && box !== void 0 ? box : new BoundingBox(x, y, 0, 0);
|
|
359
|
+
}
|
|
360
|
+
if (!this.symbolBlocks.length)
|
|
361
|
+
return new BoundingBox(0, 0, 0, 0);
|
|
362
|
+
const boundingBox = BoundingBox.copy(this.symbolBlocks[0].getBoundingBox());
|
|
282
363
|
for (let i = 1; i < this.symbolBlocks.length; i++) {
|
|
283
364
|
boundingBox.mergeWith(this.symbolBlocks[i].getBoundingBox());
|
|
284
365
|
}
|
package/build/esm/src/element.js
CHANGED
|
@@ -2,6 +2,7 @@ import { BoundingBox } from './boundingbox.js';
|
|
|
2
2
|
import { Font } from './font.js';
|
|
3
3
|
import { Metrics } from './metrics.js';
|
|
4
4
|
import { Registry } from './registry.js';
|
|
5
|
+
import { TextMetricsCache } from './textmetricscache.js';
|
|
5
6
|
import { defined, prefix, RuntimeError } from './util.js';
|
|
6
7
|
export class Element {
|
|
7
8
|
static get CATEGORY() {
|
|
@@ -12,6 +13,10 @@ export class Element {
|
|
|
12
13
|
}
|
|
13
14
|
static setTextMeasurementCanvas(canvas) {
|
|
14
15
|
Element.txtCanvas = canvas;
|
|
16
|
+
Element.clearTextMeasurementCache();
|
|
17
|
+
}
|
|
18
|
+
static clearTextMeasurementCache() {
|
|
19
|
+
TextMetricsCache.clear();
|
|
15
20
|
}
|
|
16
21
|
static getTextMeasurementCanvas() {
|
|
17
22
|
let txtCanvas = Element.txtCanvas;
|
|
@@ -377,7 +382,7 @@ export class Element {
|
|
|
377
382
|
return this._textMetrics;
|
|
378
383
|
}
|
|
379
384
|
context.font = Font.toCSSString(Font.validate(this.fontInfo));
|
|
380
|
-
this._textMetrics =
|
|
385
|
+
this._textMetrics = Object.assign({}, TextMetricsCache.measure(context, this.text));
|
|
381
386
|
this._height = this._textMetrics.actualBoundingBoxAscent + this._textMetrics.actualBoundingBoxDescent;
|
|
382
387
|
this._width = this._textMetrics.width;
|
|
383
388
|
this.metricsValid = true;
|
|
@@ -391,7 +396,7 @@ export class Element {
|
|
|
391
396
|
return 0;
|
|
392
397
|
}
|
|
393
398
|
context.font = Font.toCSSString(Metrics.getFontInfo(key));
|
|
394
|
-
return
|
|
399
|
+
return TextMetricsCache.measure(context, text).width;
|
|
395
400
|
}
|
|
396
401
|
getTextMetrics() {
|
|
397
402
|
return this.textMetrics;
|
package/build/esm/src/font.js
CHANGED
|
@@ -8,6 +8,7 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, ge
|
|
|
8
8
|
});
|
|
9
9
|
};
|
|
10
10
|
import { Metrics } from './metrics.js';
|
|
11
|
+
import { TextMetricsCache } from './textmetricscache.js';
|
|
11
12
|
export var FontWeight;
|
|
12
13
|
(function (FontWeight) {
|
|
13
14
|
FontWeight["NORMAL"] = "normal";
|
|
@@ -185,7 +186,8 @@ export class Font {
|
|
|
185
186
|
fontFaceSet = self.fonts;
|
|
186
187
|
}
|
|
187
188
|
fontFaceSet === null || fontFaceSet === void 0 ? void 0 : fontFaceSet.add(fontFace);
|
|
188
|
-
|
|
189
|
+
TextMetricsCache.clear();
|
|
190
|
+
return fontFaceLoadPromise.finally(() => TextMetricsCache.clear());
|
|
189
191
|
});
|
|
190
192
|
}
|
|
191
193
|
static getURLForFont(fontName) {
|
package/build/esm/src/metrics.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { TextMetricsCache } from './textmetricscache.js';
|
|
2
2
|
export class Metrics {
|
|
3
3
|
static clear(key) {
|
|
4
|
+
TextMetricsCache.clear();
|
|
4
5
|
if (key) {
|
|
5
6
|
this.cacheFont.delete(key);
|
|
6
7
|
this.cacheStyle.delete(key);
|
|
@@ -21,7 +22,7 @@ export class Metrics {
|
|
|
21
22
|
};
|
|
22
23
|
this.cacheFont.set(key, font);
|
|
23
24
|
}
|
|
24
|
-
return
|
|
25
|
+
return Object.assign({}, font);
|
|
25
26
|
}
|
|
26
27
|
static getFontFamily(key) {
|
|
27
28
|
var _a;
|
|
@@ -50,7 +51,7 @@ export class Metrics {
|
|
|
50
51
|
};
|
|
51
52
|
this.cacheStyle.set(key, style);
|
|
52
53
|
}
|
|
53
|
-
return
|
|
54
|
+
return Object.assign({}, style);
|
|
54
55
|
}
|
|
55
56
|
static get(key, defaultValue) {
|
|
56
57
|
var _a;
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
export class TextMetricsCache {
|
|
2
|
+
static clear() {
|
|
3
|
+
this.entries.clear();
|
|
4
|
+
}
|
|
5
|
+
static fontsReady() {
|
|
6
|
+
var _a;
|
|
7
|
+
const fonts = typeof document !== 'undefined'
|
|
8
|
+
? document.fonts
|
|
9
|
+
: globalThis.fonts;
|
|
10
|
+
if (fonts !== this.fonts) {
|
|
11
|
+
for (const type of ['loading', 'loadingdone', 'loadingerror']) {
|
|
12
|
+
(_a = this.fonts) === null || _a === void 0 ? void 0 : _a.removeEventListener(type, this.onFontsChanged);
|
|
13
|
+
fonts === null || fonts === void 0 ? void 0 : fonts.addEventListener(type, this.onFontsChanged);
|
|
14
|
+
}
|
|
15
|
+
this.fonts = fonts;
|
|
16
|
+
this.clear();
|
|
17
|
+
}
|
|
18
|
+
if ((fonts === null || fonts === void 0 ? void 0 : fonts.size) !== this.fontCount || (fonts === null || fonts === void 0 ? void 0 : fonts.status) !== this.fontStatus) {
|
|
19
|
+
this.fontCount = fonts === null || fonts === void 0 ? void 0 : fonts.size;
|
|
20
|
+
this.fontStatus = fonts === null || fonts === void 0 ? void 0 : fonts.status;
|
|
21
|
+
this.clear();
|
|
22
|
+
}
|
|
23
|
+
return (fonts === null || fonts === void 0 ? void 0 : fonts.status) !== 'loading';
|
|
24
|
+
}
|
|
25
|
+
static snapshot(metrics) {
|
|
26
|
+
return Object.freeze({
|
|
27
|
+
width: metrics.width,
|
|
28
|
+
actualBoundingBoxLeft: metrics.actualBoundingBoxLeft,
|
|
29
|
+
actualBoundingBoxRight: metrics.actualBoundingBoxRight,
|
|
30
|
+
actualBoundingBoxAscent: metrics.actualBoundingBoxAscent,
|
|
31
|
+
actualBoundingBoxDescent: metrics.actualBoundingBoxDescent,
|
|
32
|
+
fontBoundingBoxAscent: metrics.fontBoundingBoxAscent,
|
|
33
|
+
fontBoundingBoxDescent: metrics.fontBoundingBoxDescent,
|
|
34
|
+
emHeightAscent: metrics.emHeightAscent,
|
|
35
|
+
emHeightDescent: metrics.emHeightDescent,
|
|
36
|
+
hangingBaseline: metrics.hangingBaseline,
|
|
37
|
+
alphabeticBaseline: metrics.alphabeticBaseline,
|
|
38
|
+
ideographicBaseline: metrics.ideographicBaseline,
|
|
39
|
+
});
|
|
40
|
+
}
|
|
41
|
+
static measure(context, text) {
|
|
42
|
+
var _a, _b, _c;
|
|
43
|
+
if (context !== this.context) {
|
|
44
|
+
this.context = context;
|
|
45
|
+
this.clear();
|
|
46
|
+
}
|
|
47
|
+
const cacheable = this.fontsReady();
|
|
48
|
+
let lang = context.lang;
|
|
49
|
+
let direction = context.direction;
|
|
50
|
+
const canvas = context.canvas;
|
|
51
|
+
if (canvas && 'ownerDocument' in canvas) {
|
|
52
|
+
if (direction === 'inherit') {
|
|
53
|
+
direction = canvas.isConnected
|
|
54
|
+
? ((_a = canvas.ownerDocument.defaultView) === null || _a === void 0 ? void 0 : _a.getComputedStyle(canvas).direction) || 'ltr'
|
|
55
|
+
: canvas.style.direction || canvas.dir || 'ltr';
|
|
56
|
+
}
|
|
57
|
+
if (!lang || lang === 'inherit') {
|
|
58
|
+
lang = (_c = (_b = canvas.closest('[lang]')) === null || _b === void 0 ? void 0 : _b.getAttribute('lang')) !== null && _c !== void 0 ? _c : canvas.ownerDocument.documentElement.lang;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const key = JSON.stringify([
|
|
62
|
+
context.font,
|
|
63
|
+
direction,
|
|
64
|
+
context.textAlign,
|
|
65
|
+
context.textBaseline,
|
|
66
|
+
context.fontKerning,
|
|
67
|
+
context.fontStretch,
|
|
68
|
+
context.fontVariantCaps,
|
|
69
|
+
context.letterSpacing,
|
|
70
|
+
context.wordSpacing,
|
|
71
|
+
context.textRendering,
|
|
72
|
+
lang,
|
|
73
|
+
text,
|
|
74
|
+
]);
|
|
75
|
+
const cached = cacheable ? this.entries.get(key) : undefined;
|
|
76
|
+
if (cached) {
|
|
77
|
+
this.entries.delete(key);
|
|
78
|
+
this.entries.set(key, cached);
|
|
79
|
+
return cached;
|
|
80
|
+
}
|
|
81
|
+
const metrics = this.snapshot(context.measureText(text));
|
|
82
|
+
if (cacheable && key.length <= this.maxKeyLength) {
|
|
83
|
+
if (this.entries.size >= this.maxEntries)
|
|
84
|
+
this.entries.delete(this.entries.keys().next().value);
|
|
85
|
+
this.entries.set(key, metrics);
|
|
86
|
+
}
|
|
87
|
+
return metrics;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
TextMetricsCache.maxEntries = 2048;
|
|
91
|
+
TextMetricsCache.maxKeyLength = 4096;
|
|
92
|
+
TextMetricsCache.entries = new Map();
|
|
93
|
+
TextMetricsCache.onFontsChanged = () => TextMetricsCache.clear();
|
package/build/esm/src/version.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
export const VERSION = '5.1.
|
|
2
|
-
export const ID = '
|
|
3
|
-
export const DATE = '2026-11-
|
|
1
|
+
export const VERSION = '5.1.2';
|
|
2
|
+
export const ID = '419436ad3c5fb5efeb2590a6a88b2a403cbdae64';
|
|
3
|
+
export const DATE = '2026-11-16T14:50:27.719Z';
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
import assert from 'node:assert/strict';
|
|
2
|
+
import test from 'node:test';
|
|
3
|
+
import { createCanvas, registerFont } from 'canvas';
|
|
4
|
+
import { JSDOM } from 'jsdom';
|
|
5
|
+
const VF = await import(new URL('../../build/esm/entry/vexflow-core.js', import.meta.url));
|
|
6
|
+
const { ChordSymbol, Element, StaveNote } = VF;
|
|
7
|
+
const { Glyphs } = VF.VexFlow;
|
|
8
|
+
for (const [family, file] of [
|
|
9
|
+
['Academico', 'academico/academico'],
|
|
10
|
+
['Bravura', 'bravura/bravura'],
|
|
11
|
+
['Petaluma Script', 'petalumascript/petalumascript'],
|
|
12
|
+
['Petaluma', 'petaluma/petaluma'],
|
|
13
|
+
])
|
|
14
|
+
registerFont(new URL(`../../node_modules/@vexflow-fonts/${file}.otf`, import.meta.url).pathname, { family });
|
|
15
|
+
Element.setTextMeasurementCanvas(createCanvas(1, 1));
|
|
16
|
+
const sup = { symbolModifier: ChordSymbol.symbolModifiers.SUPERSCRIPT };
|
|
17
|
+
const sub = { symbolModifier: ChordSymbol.symbolModifiers.SUBSCRIPT };
|
|
18
|
+
const state = () => ({ leftShift: 0, rightShift: 0, topTextLine: 0, textLine: 0 });
|
|
19
|
+
const close = (a, b, tolerance = 0.04) => assert.ok(Math.abs(a - b) < tolerance, `${a} ≈ ${b}`);
|
|
20
|
+
function chord(mode = 'auto', family = 'Academico,Bravura', size = 12) {
|
|
21
|
+
const symbol = new ChordSymbol().setFont(family, size).setKerning(mode);
|
|
22
|
+
new StaveNote({ keys: ['c/5'], duration: 'q' }).addModifier(symbol, 0);
|
|
23
|
+
return symbol;
|
|
24
|
+
}
|
|
25
|
+
function format(symbol) {
|
|
26
|
+
ChordSymbol.format([symbol], state());
|
|
27
|
+
return symbol;
|
|
28
|
+
}
|
|
29
|
+
const diminished = (symbol) => symbol.addText('A').addGlyph('diminished', sup);
|
|
30
|
+
for (const family of ['Academico,Bravura', 'Petaluma Script,Petaluma']) {
|
|
31
|
+
test(`${family}: auto tightens A diminished; none preserves legacy advances`, () => {
|
|
32
|
+
const legacy = format(diminished(chord('none', family)));
|
|
33
|
+
const auto = format(diminished(chord('auto', family)));
|
|
34
|
+
assert.ok(auto.getWidth() < legacy.getWidth());
|
|
35
|
+
assert.equal(legacy.getKerning(), 'none');
|
|
36
|
+
close(legacy.getWidth(), legacy.symbolBlocks.reduce((sum, block) => sum + block.getWidth() + ChordSymbol.minPadding, 0));
|
|
37
|
+
assert.equal(auto.kernedRuns[0].font.family, family.split(',')[0]);
|
|
38
|
+
assert.equal(auto.kernedRuns[1].font.family, family.split(',')[1]);
|
|
39
|
+
});
|
|
40
|
+
test(`${family}: all root/glyph fixtures have finite, contained ink bounds`, () => {
|
|
41
|
+
for (const root of 'ABCDEFG')
|
|
42
|
+
for (const glyph of ['diminished', 'halfDiminished', 'majorSeventh', '#', 'b']) {
|
|
43
|
+
const symbol = format(chord('auto', family).addText(root).addGlyph(glyph, sup));
|
|
44
|
+
const bounds = symbol.getBoundingBox();
|
|
45
|
+
assert.ok([bounds.x, bounds.y, bounds.w, bounds.h, symbol.getWidth()].every(Number.isFinite));
|
|
46
|
+
assert.ok(bounds.x >= -0.001 && bounds.x + bounds.w <= symbol.getWidth() + 0.001);
|
|
47
|
+
}
|
|
48
|
+
});
|
|
49
|
+
test(`${family}: sizes and repeated formatting do not accumulate shifts`, () => {
|
|
50
|
+
const small = format(diminished(chord('auto', family, 12)));
|
|
51
|
+
const large = format(diminished(chord('auto', family, 24)));
|
|
52
|
+
const gap = (symbol) => {
|
|
53
|
+
const [root, script] = symbol.kernedRuns;
|
|
54
|
+
return script.x - root.x - root.metrics.width;
|
|
55
|
+
};
|
|
56
|
+
close(gap(large), gap(small) * 2);
|
|
57
|
+
small.kernedRuns.forEach((run, i) => {
|
|
58
|
+
close(VF.Font.convertSizeToPixelValue(large.kernedRuns[i].font.size), VF.Font.convertSizeToPixelValue(run.font.size) * 2);
|
|
59
|
+
close(large.kernedRuns[i].y, run.y * 2);
|
|
60
|
+
});
|
|
61
|
+
const before = JSON.stringify(large.kernedRuns);
|
|
62
|
+
const box = large.getBoundingBox();
|
|
63
|
+
box.mergeWith(new VF.BoundingBox(-1000, -1000, 1, 1));
|
|
64
|
+
for (let i = 0; i < 3; i++)
|
|
65
|
+
format(large);
|
|
66
|
+
assert.equal(JSON.stringify(large.kernedRuns), before);
|
|
67
|
+
assert.ok(large.getBoundingBox().x >= 0, 'bounds queries never mutate run metrics');
|
|
68
|
+
small.setFontSize(24);
|
|
69
|
+
format(small);
|
|
70
|
+
close(small.getWidth(), large.getWidth());
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
test('text spans retain native shaping and adjacent text fragments can form one run', () => {
|
|
74
|
+
const symbol = format(chord().addText('F').addText('maj7'));
|
|
75
|
+
assert.equal(symbol.kernedRuns.length, 1);
|
|
76
|
+
assert.equal(symbol.kernedRuns[0].text, 'Fmaj7');
|
|
77
|
+
const combined = format(chord().addGlyphOrText('C#7'));
|
|
78
|
+
assert.deepEqual(combined.kernedRuns.map((run) => run.text), ['C', Glyphs.csymAccidentalSharp, '7']);
|
|
79
|
+
});
|
|
80
|
+
test('stacked script groups share an anchor and the next group clears both advances', () => {
|
|
81
|
+
for (const [first, second] of [
|
|
82
|
+
[sup, sub],
|
|
83
|
+
[sub, sup],
|
|
84
|
+
]) {
|
|
85
|
+
const symbol = format(chord().addText('F7').addGlyphOrText('b9', first).addGlyphOrText('#11', second).addText('sus4'));
|
|
86
|
+
const runs = symbol.kernedRuns;
|
|
87
|
+
close(runs[1].x, runs[3].x);
|
|
88
|
+
const end = Math.max(...runs.slice(1, -1).map((run) => run.x + run.metrics.width));
|
|
89
|
+
assert.ok(runs[runs.length - 1].x > end);
|
|
90
|
+
const before = JSON.stringify(runs);
|
|
91
|
+
format(symbol);
|
|
92
|
+
assert.equal(JSON.stringify(symbol.kernedRuns), before);
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
test('unsupported fonts and styles retain the legacy layout', () => {
|
|
96
|
+
for (const [family, weight, style] of [
|
|
97
|
+
['Arial,Bravura', 'normal', 'normal'],
|
|
98
|
+
['Academico,Bravura', 'bold', 'normal'],
|
|
99
|
+
['Academico,Bravura', 'normal', 'italic'],
|
|
100
|
+
]) {
|
|
101
|
+
const make = (mode) => format(diminished(chord(mode, family).setFont(family, 12, weight, style)));
|
|
102
|
+
const auto = make('auto');
|
|
103
|
+
assert.equal(auto.kernedRuns, undefined);
|
|
104
|
+
close(auto.getWidth(), make('none').getWidth());
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
test('reformatting picks up font, content, cache, and mode changes', () => {
|
|
108
|
+
const symbol = format(diminished(chord()));
|
|
109
|
+
symbol.setFont('Petaluma Script,Petaluma', 18).addText('7');
|
|
110
|
+
Element.clearTextMeasurementCache();
|
|
111
|
+
format(symbol);
|
|
112
|
+
const fresh = format(diminished(chord('auto', 'Petaluma Script,Petaluma', 18)).addText('7'));
|
|
113
|
+
assert.deepEqual(symbol.kernedRuns, fresh.kernedRuns);
|
|
114
|
+
format(symbol.setKerning('none'));
|
|
115
|
+
assert.equal(symbol.kernedRuns, undefined);
|
|
116
|
+
close(symbol.getWidth(), symbol.symbolBlocks.reduce((sum, block) => sum + block.getWidth() + ChordSymbol.minPadding, 0));
|
|
117
|
+
format(symbol.setKerning('auto'));
|
|
118
|
+
assert.deepEqual(symbol.kernedRuns, fresh.kernedRuns);
|
|
119
|
+
});
|
|
120
|
+
test('custom profiles are isolated and shift the following advance as well as ink', () => {
|
|
121
|
+
const profile = {
|
|
122
|
+
textFont: 'Academico',
|
|
123
|
+
musicFont: 'Bravura',
|
|
124
|
+
pairs: [{ left: 'A', right: Glyphs.csymDiminished, position: 'superscript', adjustmentEm: 0 }],
|
|
125
|
+
};
|
|
126
|
+
const make = () => diminished(chord()).addText('7');
|
|
127
|
+
const base = format(make().setKerningProfile(profile));
|
|
128
|
+
profile.pairs[0].adjustmentEm = -0.1;
|
|
129
|
+
const adjusted = format(make().setKerningProfile(profile));
|
|
130
|
+
close(base.getWidth() - adjusted.getWidth(), 1.6);
|
|
131
|
+
close(base.kernedRuns[2].x - adjusted.kernedRuns[2].x, 1.6);
|
|
132
|
+
format(base);
|
|
133
|
+
close(base.getWidth() - adjusted.getWidth(), 1.6);
|
|
134
|
+
assert.throws(() => make().setKerningProfile(Object.assign(Object.assign({}, profile), { pairs: [Object.assign(Object.assign({}, profile.pairs[0]), { adjustmentEm: NaN })] })), /Invalid/);
|
|
135
|
+
assert.throws(() => make().setKerning('invalid'), /Kerning/);
|
|
136
|
+
assert.equal(format(chord()).getWidth(), 0);
|
|
137
|
+
});
|
|
138
|
+
test('Canvas and SVG receive identical positioned runs and right alignment uses the computed width', () => {
|
|
139
|
+
const dom = new JSDOM('<div id="svg"></div><canvas id="canvas"></canvas>');
|
|
140
|
+
const previousDocument = globalThis.document;
|
|
141
|
+
globalThis.document = dom.window.document;
|
|
142
|
+
try {
|
|
143
|
+
const results = [];
|
|
144
|
+
for (const backend of [VF.Renderer.Backends.SVG, VF.Renderer.Backends.CANVAS]) {
|
|
145
|
+
const target = document.getElementById(backend === VF.Renderer.Backends.SVG ? 'svg' : 'canvas');
|
|
146
|
+
const renderer = new VF.Renderer(target, backend).resize(600, 240);
|
|
147
|
+
const ctx = renderer.getContext();
|
|
148
|
+
const symbol = diminished(new ChordSymbol().setFont('Academico,Bravura', 18).setKerning('auto'))
|
|
149
|
+
.setHorizontal('right')
|
|
150
|
+
.setReportWidth(false);
|
|
151
|
+
const note = new StaveNote({ keys: ['c/5'], duration: 'q' }).addModifier(symbol, 0);
|
|
152
|
+
const stave = new VF.Stave(30, 80, 500).setContext(ctx);
|
|
153
|
+
note.setStave(stave);
|
|
154
|
+
VF.Formatter.FormatAndDraw(ctx, stave, [note]);
|
|
155
|
+
const calls = [];
|
|
156
|
+
const fillText = ctx.fillText.bind(ctx);
|
|
157
|
+
ctx.fillText = (text, x, y) => {
|
|
158
|
+
calls.push({ text, x, y });
|
|
159
|
+
return fillText(text, x, y);
|
|
160
|
+
};
|
|
161
|
+
symbol.setContext(ctx).draw();
|
|
162
|
+
results.push(calls);
|
|
163
|
+
const anchor = note.getModifierStartXY(VF.Modifier.Position.ABOVE, 0).x;
|
|
164
|
+
const bounds = symbol.getBoundingBox();
|
|
165
|
+
close(bounds.x + bounds.w, anchor);
|
|
166
|
+
}
|
|
167
|
+
assert.deepEqual(results[0], results[1]);
|
|
168
|
+
}
|
|
169
|
+
finally {
|
|
170
|
+
globalThis.document = previousDocument;
|
|
171
|
+
dom.window.close();
|
|
172
|
+
}
|
|
173
|
+
});
|