guidex 0.2.5 → 0.3.0
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 +239 -3
- package/dist/lib/app/ControlsRow.d.ts +1 -0
- package/dist/lib/app/Editor.d.ts +1 -0
- package/dist/lib/app/EditorContext.d.ts +17 -0
- package/dist/lib/app/EditorTextarea.d.ts +1 -0
- package/dist/lib/app/ExportSettings.d.ts +1 -0
- package/dist/lib/app/FeedbackSpan.d.ts +5 -0
- package/dist/lib/app/RenderSettings.d.ts +1 -0
- package/dist/lib/app/SamplesRow.d.ts +1 -0
- package/dist/lib/app/SettingsMenu.d.ts +1 -0
- package/dist/lib/app/SettingsPanel.d.ts +1 -0
- package/dist/lib/app/SyllablesTable.d.ts +1 -0
- package/dist/lib/app/WordCheckPanel.d.ts +1 -0
- package/dist/lib/app/WordCopyControls.d.ts +1 -0
- package/dist/lib/app/chantLibrary.d.ts +11 -0
- package/dist/lib/app/editorState.d.ts +159 -0
- package/dist/lib/app/samples.d.ts +10 -0
- package/dist/lib/app/wordCopy.d.ts +30 -0
- package/dist/lib/chantLayout-GAfg2iKS.js +1042 -0
- package/dist/lib/chantLayout.d.ts +169 -0
- package/dist/lib/chantMarkup.d.ts +36 -0
- package/dist/lib/editorStorage.d.ts +179 -0
- package/dist/lib/embed/index.d.ts +1 -0
- package/dist/lib/embed/index.js +2 -2
- package/dist/lib/embed/manual.d.ts +19 -1
- package/dist/lib/embed/manual.js +43 -2
- package/dist/lib/guidoRender.d.ts +22 -29
- package/dist/lib/guidoScript.d.ts +31 -3
- package/dist/lib/guidoScriptTransforms.d.ts +5 -4
- package/dist/lib/guidoStyles.d.ts +23 -5
- package/dist/lib/main.d.ts +0 -1
- package/dist/lib/react/GuidexScore.d.ts +1 -1
- package/dist/lib/react/index.d.ts +1 -0
- package/dist/lib/react/index.js +2 -2
- package/dist/lib/scoreImage-DnFIbtF_.js +951 -0
- package/dist/lib/scoreImage.d.ts +63 -0
- package/dist/lib/word/index.d.ts +17 -0
- package/dist/lib/word/index.js +2 -0
- package/dist/lib/wordChecker-C3nJrk_j.js +1042 -0
- package/dist/lib/wordChecker.d.ts +66 -0
- package/dist/lib/wordClipboard.d.ts +25 -0
- package/dist/lib/wordExport.d.ts +244 -0
- package/dist-embed/guidex-embed.min.js +1 -1
- package/package.json +8 -1
- package/dist/lib/core-CmzGmufM.js +0 -1262
- package/dist/lib/settingsMenu.d.ts +0 -1
|
@@ -0,0 +1,1042 @@
|
|
|
1
|
+
import { a as measure, i as layoutScore, l as measurementFont, n as SCORE_MARKERS, r as SPECIAL_NOTES, t as NOTE_MODIFIERS } from "./chantLayout-GAfg2iKS.js";
|
|
2
|
+
//#region src/wordExport.ts
|
|
3
|
+
var PT_PER_PX = .75;
|
|
4
|
+
var PX_PER_PT = 4 / 3;
|
|
5
|
+
/** Exact line heights in the target document: 1.2 × the font size, the
|
|
6
|
+
* ratio of the established BNS-nota (20pt/24pt) and BNS-textus (10pt/12pt)
|
|
7
|
+
* styles the export round-trips with. */
|
|
8
|
+
var LINE_HEIGHT_RATIO = 1.2;
|
|
9
|
+
/** The hallmark red behind the style sets' `var(--red)`; CSS variables do
|
|
10
|
+
* not survive a Word paste, so colors are resolved to literals.
|
|
11
|
+
*
|
|
12
|
+
* Future expansion — color choosing for the Word flavor: documents whose
|
|
13
|
+
* own marker convention is Word's plain `red` (#ff0000) see the hallmark
|
|
14
|
+
* #d40000 as a visibly darker crimson beside their native runs (the two
|
|
15
|
+
* differ only in that shade; the browser preview keeps #d40000 either
|
|
16
|
+
* way). A per-export color mapping (e.g. reds → `red`) would let such
|
|
17
|
+
* documents match without touching the app palette. */
|
|
18
|
+
var CSS_VAR_COLORS = { "--red": "#d40000" };
|
|
19
|
+
/** The chant font's real family name (guidohu.ttf): Word resolves
|
|
20
|
+
* installed fonts by name, not by the browser stylesheets' @font-face
|
|
21
|
+
* alias. */
|
|
22
|
+
var NOTES_FONT_FAMILY = "Guido HU";
|
|
23
|
+
/** 0.5 mm, the issue's example of a fixed small tab unit. */
|
|
24
|
+
var DEFAULT_TAB_INTERVAL_PT = 36 / 25.4;
|
|
25
|
+
/** The default spacer: a no-break space at its natural advance. The
|
|
26
|
+
* natural advance is proportional to the inherited font size, so the gaps
|
|
27
|
+
* scale with Word's rendering of the destination styles, and no-break
|
|
28
|
+
* spaces are plain characters — nothing mso-* that a paste path could
|
|
29
|
+
* strip. Tabs (interval-tuned) and tuned space characters remain the
|
|
30
|
+
* explicit choices. */
|
|
31
|
+
var DEFAULT_SPACER = { character: "nbsp" };
|
|
32
|
+
function defaultStyleNames(styleName) {
|
|
33
|
+
return {
|
|
34
|
+
nota: `${styleName}-nota`,
|
|
35
|
+
textus: `${styleName}-textus`,
|
|
36
|
+
textusChar: `${styleName}-textus Char1`
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
var SPACER_CHARS$1 = {
|
|
40
|
+
tab: " ",
|
|
41
|
+
en: " ",
|
|
42
|
+
em: " ",
|
|
43
|
+
nbsp: "\xA0",
|
|
44
|
+
space: " "
|
|
45
|
+
};
|
|
46
|
+
/**
|
|
47
|
+
* The self-correcting spacer meter: converts ideal px anchors into
|
|
48
|
+
* `unit × count` spacer runs. `advance` targets absolute positions, so
|
|
49
|
+
* quantization error never accumulates — each anchor lands within ½ unit.
|
|
50
|
+
* Tabs use the absolute-grid variant: Word places k consecutive tabs at
|
|
51
|
+
* (floor(current ÷ interval) + k) × interval. The width kinds and the
|
|
52
|
+
* spacer characters are validated against each other: the tab interval is
|
|
53
|
+
* the tab's own grid unit, so a tab takes no other width kind and no
|
|
54
|
+
* other character takes the interval — its accounting would advance on a
|
|
55
|
+
* grid the emitted character never lands on.
|
|
56
|
+
*/
|
|
57
|
+
var SpacerMeter = class {
|
|
58
|
+
character;
|
|
59
|
+
/** The spacer character's natural advance in the text font, px */
|
|
60
|
+
naturalPx;
|
|
61
|
+
/** One unit's effective width in our measured px */
|
|
62
|
+
unitPx;
|
|
63
|
+
/** Letter-spacing to emit on spacer runs, pt (0 = none) */
|
|
64
|
+
letterSpacingPt;
|
|
65
|
+
grid;
|
|
66
|
+
constructor(config, spaceFont) {
|
|
67
|
+
this.character = config.character;
|
|
68
|
+
const width = config.width;
|
|
69
|
+
if (this.character === "tab" && width !== void 0 && width.kind !== "tabInterval") throw new TypeError("The 'tab' spacer advances on Word's interval grid: only the 'tabInterval' width applies (or none, for the default interval)");
|
|
70
|
+
if (this.character !== "tab" && width?.kind === "tabInterval") throw new TypeError("Width kind 'tabInterval' only applies to the 'tab' spacer character — a non-tab character never lands on the interval grid its counts would assume");
|
|
71
|
+
if (this.character === "tab") {
|
|
72
|
+
const pt = width?.kind === "tabInterval" ? width.pt : DEFAULT_TAB_INTERVAL_PT;
|
|
73
|
+
this.naturalPx = 0;
|
|
74
|
+
this.unitPx = pt * PX_PER_PT;
|
|
75
|
+
this.letterSpacingPt = 0;
|
|
76
|
+
this.grid = true;
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
this.grid = false;
|
|
80
|
+
const char = SPACER_CHARS$1[this.character] ?? this.character;
|
|
81
|
+
this.naturalPx = measure(char, spaceFont);
|
|
82
|
+
if (!width || width.kind === "scale") {
|
|
83
|
+
const factor = width?.kind === "scale" ? width.factor : 1;
|
|
84
|
+
this.unitPx = this.naturalPx * factor;
|
|
85
|
+
this.letterSpacingPt = (this.unitPx - this.naturalPx) * PT_PER_PX;
|
|
86
|
+
} else if (width.kind === "absolute") {
|
|
87
|
+
this.unitPx = width.pt * PX_PER_PT;
|
|
88
|
+
this.letterSpacingPt = (this.unitPx - this.naturalPx) * PT_PER_PX;
|
|
89
|
+
} else {
|
|
90
|
+
this.letterSpacingPt = width.pt;
|
|
91
|
+
this.unitPx = this.naturalPx + width.pt * PX_PER_PT;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** The spacer character as it appears in plain text. */
|
|
95
|
+
get char() {
|
|
96
|
+
return SPACER_CHARS$1[this.character] ?? this.character;
|
|
97
|
+
}
|
|
98
|
+
/** Advances the emitted position to `targetPx`, returning the unit
|
|
99
|
+
* count to emit and the new (quantized) emitted position. */
|
|
100
|
+
advance(targetPx, emittedPx) {
|
|
101
|
+
if (this.grid) {
|
|
102
|
+
const gridPos = Math.floor(emittedPx / this.unitPx);
|
|
103
|
+
const count = Math.max(0, Math.round(targetPx / this.unitPx - gridPos));
|
|
104
|
+
return {
|
|
105
|
+
count,
|
|
106
|
+
emittedPx: (gridPos + count) * this.unitPx
|
|
107
|
+
};
|
|
108
|
+
}
|
|
109
|
+
const count = Math.max(0, Math.round((targetPx - emittedPx) / this.unitPx));
|
|
110
|
+
return {
|
|
111
|
+
count,
|
|
112
|
+
emittedPx: emittedPx + count * this.unitPx
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
function escapeHtml(text) {
|
|
117
|
+
return text.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">");
|
|
118
|
+
}
|
|
119
|
+
/** The style name as it lands in the style block's `mso-style-name:"…"`
|
|
120
|
+
* strings: Word style names cannot contain angle brackets (Word forbids
|
|
121
|
+
* them), so those are dropped rather than escaped into the name; quotes
|
|
122
|
+
* and backslashes are CSS-escaped so the name cannot break out of its
|
|
123
|
+
* string. Class attributes additionally use the sanitized class below,
|
|
124
|
+
* so a caller-supplied name never reaches markup-sensitive positions. */
|
|
125
|
+
function safeStyleName(name) {
|
|
126
|
+
return name.replace(/[<>]/g, "").replaceAll("\\", "\\\\").replaceAll("\"", "\\\"");
|
|
127
|
+
}
|
|
128
|
+
/** The CSS class for a style name: every character outside CSS
|
|
129
|
+
* identifier syntax is dropped (then underscore-prefixed when nothing
|
|
130
|
+
* valid remains or a digit would lead), so the name is safe in both a
|
|
131
|
+
* quoted HTML attribute and a class selector. Names differing only by
|
|
132
|
+
* dropped characters share a class — Word maps the styles by
|
|
133
|
+
* mso-style-name, so such near-duplicates were ambiguous anyway. */
|
|
134
|
+
function styleClass(name) {
|
|
135
|
+
const safe = name.replace(/[^A-Za-z0-9_-]/g, "");
|
|
136
|
+
return /^[A-Za-z_-]/.test(safe) ? safe : `_${safe}`;
|
|
137
|
+
}
|
|
138
|
+
function resolveColor(color) {
|
|
139
|
+
if (!color) return null;
|
|
140
|
+
const m = /^var\((--[^)]+)\)$/.exec(color);
|
|
141
|
+
if (m) return CSS_VAR_COLORS[m[1]] ?? null;
|
|
142
|
+
return color;
|
|
143
|
+
}
|
|
144
|
+
/** Characters the destination's text fonts have no glyph for, mapped to
|
|
145
|
+
* their Word-safe symbol-font stand-ins. U+2217 (the `**` star) exists in
|
|
146
|
+
* no Times-family font, so Word substitutes per run — Cambria Math on one
|
|
147
|
+
* line, a Symbol remap on the next — and neither looks like the score.
|
|
148
|
+
* The old workflow's answer, the Symbol font's asterisk, is what Word
|
|
149
|
+
* documents already carry and what the checker recognizes as a marker
|
|
150
|
+
* glyph, so the export pins the star to that run shape. */
|
|
151
|
+
var WORD_SYMBOL_SUBSTITUTES = { "∗": "*" };
|
|
152
|
+
/** The first family of a CSS font stack, unquoted (Word styles name one
|
|
153
|
+
* font). */
|
|
154
|
+
function firstFontFamily(stack) {
|
|
155
|
+
return stack.split(",")[0].trim().replace(/^['"]|['"]$/g, "");
|
|
156
|
+
}
|
|
157
|
+
function fmtPt(pt) {
|
|
158
|
+
return String(parseFloat(pt.toFixed(2)));
|
|
159
|
+
}
|
|
160
|
+
/** One syllable run as Word HTML: a `<b>` wrapper for weight, inline
|
|
161
|
+
* styles for family, size, color, and raise. Characters with no glyph in
|
|
162
|
+
* the destination fonts (the `**` star) ride the Symbol font as their
|
|
163
|
+
* Word-safe stand-ins instead. */
|
|
164
|
+
function partHtml(part, textPx) {
|
|
165
|
+
const style = part.style;
|
|
166
|
+
const css = [];
|
|
167
|
+
if (style.fontFamily) css.push(`font-family:'${firstFontFamily(style.fontFamily)}'`);
|
|
168
|
+
if (style.italic) css.push("font-style:italic");
|
|
169
|
+
if (style.scale !== void 0 && style.scale !== 1) css.push(`font-size:${fmtPt(textPx * style.scale * PT_PER_PX)}pt`);
|
|
170
|
+
const color = resolveColor(style.color);
|
|
171
|
+
if (color) css.push(`color:${color}`);
|
|
172
|
+
if (style.raise) css.push(`vertical-align:${fmtPt(textPx * style.raise * PT_PER_PX)}pt`);
|
|
173
|
+
const inner = [...part.text].some((ch) => WORD_SYMBOL_SUBSTITUTES[ch] !== void 0) ? [...part.text].map((ch) => {
|
|
174
|
+
const standIn = WORD_SYMBOL_SUBSTITUTES[ch];
|
|
175
|
+
if (standIn === void 0) return escapeHtml(ch);
|
|
176
|
+
return `<span style="${[
|
|
177
|
+
"font-family:Symbol",
|
|
178
|
+
"mso-char-type:symbol",
|
|
179
|
+
"mso-symbol-font-family:Symbol",
|
|
180
|
+
...css.slice(style.fontFamily ? 1 : 0).filter((c) => !c.startsWith("vertical-align:"))
|
|
181
|
+
].join(";")}">${standIn}</span>`;
|
|
182
|
+
}).join("") : css.length ? `<span style="${css.join(";")}">${escapeHtml(part.text)}</span>` : escapeHtml(part.text);
|
|
183
|
+
return style.weight === "700" ? `<b>${inner}</b>` : inner;
|
|
184
|
+
}
|
|
185
|
+
function sylHtml(seg, textPx) {
|
|
186
|
+
return seg.parts.map((p) => partHtml(p, textPx)).join("");
|
|
187
|
+
}
|
|
188
|
+
/**
|
|
189
|
+
* Walks one text line's segments in order, tracking the emitted position
|
|
190
|
+
* and faking every gap with the meter. `emitSpacer` renders `count` units;
|
|
191
|
+
* the emitters differ only in their piece renderers.
|
|
192
|
+
*/
|
|
193
|
+
function walkTextLine(line, meter, pieces) {
|
|
194
|
+
let emitted = 0;
|
|
195
|
+
let out = "";
|
|
196
|
+
const spacerTo = (targetPx) => {
|
|
197
|
+
const { count, emittedPx } = meter.advance(targetPx, emitted);
|
|
198
|
+
emitted = emittedPx;
|
|
199
|
+
if (count > 0) out += pieces.spacer(count);
|
|
200
|
+
};
|
|
201
|
+
for (const seg of line.segments) switch (seg.kind) {
|
|
202
|
+
case "gap":
|
|
203
|
+
spacerTo(seg.endPx);
|
|
204
|
+
break;
|
|
205
|
+
case "connector":
|
|
206
|
+
spacerTo(seg.dashStartPx);
|
|
207
|
+
out += pieces.dash();
|
|
208
|
+
emitted += seg.dashWidth;
|
|
209
|
+
spacerTo(seg.nextAnchorPx);
|
|
210
|
+
break;
|
|
211
|
+
case "syl":
|
|
212
|
+
out += pieces.syl(seg);
|
|
213
|
+
emitted += seg.textWidth;
|
|
214
|
+
break;
|
|
215
|
+
case "word-space":
|
|
216
|
+
out += " ";
|
|
217
|
+
emitted += seg.width;
|
|
218
|
+
break;
|
|
219
|
+
case "line-end-dash":
|
|
220
|
+
spacerTo(seg.dashStartPx);
|
|
221
|
+
out += pieces.dash();
|
|
222
|
+
emitted += seg.dashWidth;
|
|
223
|
+
spacerTo(seg.trailEndPx);
|
|
224
|
+
}
|
|
225
|
+
return out;
|
|
226
|
+
}
|
|
227
|
+
/** The notes line's raw Guido text: the renderer's own notes model is
|
|
228
|
+
* already the Word representation. */
|
|
229
|
+
function notesText(layout, line) {
|
|
230
|
+
return layout.clefPrefix + line.notesParts.join("");
|
|
231
|
+
}
|
|
232
|
+
/** Spaces faking one tab's width for browser display; Word reads the
|
|
233
|
+
* mso-tab-count, not the padding. */
|
|
234
|
+
function tabDisplayPadding(meter, spacePx) {
|
|
235
|
+
return " ".repeat(Math.max(1, Math.round(meter.unitPx / spacePx)));
|
|
236
|
+
}
|
|
237
|
+
function buildMeter(layout, config) {
|
|
238
|
+
return new SpacerMeter(config, measurementFont({ weight: layout.bold ? "700" : "400" }, layout.textPx, layout.styleSet.textFontStack));
|
|
239
|
+
}
|
|
240
|
+
function resolveStyleNames(layout, option) {
|
|
241
|
+
const defaults = defaultStyleNames(layout.styleName);
|
|
242
|
+
return {
|
|
243
|
+
nota: option?.nota ?? defaults.nota,
|
|
244
|
+
textus: option?.textus ?? defaults.textus,
|
|
245
|
+
textusChar: option?.textusChar ?? defaults.textusChar
|
|
246
|
+
};
|
|
247
|
+
}
|
|
248
|
+
/** Resolves the layout sizes: the destination-document pt options take
|
|
249
|
+
* precedence over their px counterparts (px = pt × 4/3, so the layout
|
|
250
|
+
* runs at the size Word will render); with textPt given the notes default
|
|
251
|
+
* to twice the text size, the established BNS ratio. */
|
|
252
|
+
function resolveSizing(options) {
|
|
253
|
+
const textPt = options.textPt;
|
|
254
|
+
const notesPt = options.notesPt ?? (textPt !== void 0 ? textPt * 2 : void 0);
|
|
255
|
+
return {
|
|
256
|
+
style: options.style,
|
|
257
|
+
bold: options.bold,
|
|
258
|
+
textPx: textPt !== void 0 ? textPt * PX_PER_PT : options.textPx,
|
|
259
|
+
notesPx: notesPt !== void 0 ? notesPt * PX_PER_PT : options.notesPx,
|
|
260
|
+
maxWidthPx: options.maxWidthPt !== void 0 ? options.maxWidthPt * PX_PER_PT : options.maxWidthPx
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Renders the score as Word-flavoured HTML: one `nota` paragraph (notes)
|
|
265
|
+
* followed by one `textus` paragraph (text) per rendered line, the
|
|
266
|
+
* declared styles mapping onto the target document's own definitions by
|
|
267
|
+
* mso-style-name. Broken lines end with a tab + the Guido `*` glyph,
|
|
268
|
+
* right-aligned to the paragraph style's tab stop (the style block's stop
|
|
269
|
+
* at finite width; an inline per-line stop at natural width, where no
|
|
270
|
+
* shared star target exists).
|
|
271
|
+
*/
|
|
272
|
+
async function toWordHtml(source, options = {}) {
|
|
273
|
+
const layout = await layoutScore(source, resolveSizing(options));
|
|
274
|
+
const spacerConfig = options.spacer ?? DEFAULT_SPACER;
|
|
275
|
+
const meter = buildMeter(layout, spacerConfig);
|
|
276
|
+
const names = resolveStyleNames(layout, options.styleNames);
|
|
277
|
+
const notaClass = styleClass(names.nota);
|
|
278
|
+
const textusClass = styleClass(names.textus);
|
|
279
|
+
const charClass = styleClass(names.textusChar);
|
|
280
|
+
const notesPt = layout.notesPx * PT_PER_PX;
|
|
281
|
+
const textPt = layout.textPx * PT_PER_PX;
|
|
282
|
+
const textFamily = firstFontFamily(layout.styleSet.textFontStack);
|
|
283
|
+
const spacePx = measure(" ", measurementFont({ weight: layout.bold ? "700" : "400" }, layout.textPx, layout.styleSet.textFontStack));
|
|
284
|
+
const tabInterval = spacerConfig.character === "tab" ? spacerConfig.width?.kind === "tabInterval" ? spacerConfig.width.pt : DEFAULT_TAB_INTERVAL_PT : null;
|
|
285
|
+
const styleBlock = [
|
|
286
|
+
`p.${notaClass} {mso-style-name:"${safeStyleName(names.nota)}";margin:0cm;mso-pagination:none;mso-line-height-rule:exactly;line-height:${fmtPt(notesPt * LINE_HEIGHT_RATIO)}pt;font-size:${fmtPt(notesPt)}pt;font-family:"${NOTES_FONT_FAMILY}";letter-spacing:-.1pt;` + (layout.maxWidthPx !== Infinity ? `tab-stops:right ${fmtPt(layout.starTarget * PT_PER_PX)}pt;` : "") + "}",
|
|
287
|
+
`p.${textusClass} {mso-style-name:"${safeStyleName(names.textus)}";mso-style-link:"${safeStyleName(names.textusChar)}";margin:0cm;mso-pagination:none;mso-line-height-rule:exactly;line-height:${fmtPt(textPt * LINE_HEIGHT_RATIO)}pt;font-size:${fmtPt(textPt)}pt;` + (layout.bold ? "font-weight:bold;" : "") + `font-family:"${textFamily}";mso-ansi-language:HU;}`,
|
|
288
|
+
`span.${charClass} {mso-style-name:"${safeStyleName(names.textusChar)}";mso-ansi-language:HU;}`
|
|
289
|
+
].join("\n");
|
|
290
|
+
const spacerHtml = (count) => {
|
|
291
|
+
if (meter.character === "tab") {
|
|
292
|
+
const pad = tabDisplayPadding(meter, spacePx);
|
|
293
|
+
return `<span style="mso-tab-count:${count}">${" ".repeat(count * pad.length)}</span>`;
|
|
294
|
+
}
|
|
295
|
+
if (meter.character === "space") return `<span style="mso-spacerun:yes${meter.letterSpacingPt ? `;letter-spacing:${fmtPt(meter.letterSpacingPt)}pt` : ""}" xml:space="preserve">${" ".repeat(count)}</span>`;
|
|
296
|
+
const char = escapeHtml(meter.char);
|
|
297
|
+
if (meter.letterSpacingPt) return `<span style="letter-spacing:${fmtPt(meter.letterSpacingPt)}pt">${char.repeat(count)}</span>`;
|
|
298
|
+
return char.repeat(count);
|
|
299
|
+
};
|
|
300
|
+
const paragraphs = [];
|
|
301
|
+
for (const line of layout.lines) {
|
|
302
|
+
const markerStop = line.breakMarkerLeftPx !== void 0 && layout.maxWidthPx === Infinity ? ` style="tab-stops:right ${fmtPt((line.notesEnd + line.breakMarkerLeftPx + layout.starWidth) * PT_PER_PX)}pt"` : "";
|
|
303
|
+
const marker = line.breakMarkerLeftPx !== void 0 ? `<span style="mso-tab-count:1">${" ".repeat(Math.max(1, Math.round((line.breakMarkerLeftPx + layout.starWidth) / spacePx)))}</span>*` : "";
|
|
304
|
+
paragraphs.push(`<p class="${notaClass}"${markerStop}><span style="letter-spacing:-.1pt">${escapeHtml(notesText(layout, line))}</span>${marker}</p>`);
|
|
305
|
+
paragraphs.push(`<p class="${textusClass}">` + walkTextLine(line, meter, {
|
|
306
|
+
spacer: spacerHtml,
|
|
307
|
+
dash: () => "-",
|
|
308
|
+
syl: (seg) => sylHtml(seg, layout.textPx)
|
|
309
|
+
}) + "</p>");
|
|
310
|
+
}
|
|
311
|
+
return [
|
|
312
|
+
"<html xmlns:o=\"urn:schemas-microsoft-com:office:office\"",
|
|
313
|
+
"xmlns:w=\"urn:schemas-microsoft-com:office:word\"",
|
|
314
|
+
"xmlns=\"http://www.w3.org/TR/REC-html40\">",
|
|
315
|
+
"<head>",
|
|
316
|
+
"<meta http-equiv=Content-Type content=\"text/html; charset=utf-8\">",
|
|
317
|
+
"<meta name=ProgId content=Word.Document>",
|
|
318
|
+
"<meta name=Generator content=\"Microsoft Word 15\">",
|
|
319
|
+
"<meta name=Originator content=\"Microsoft Word 15\">",
|
|
320
|
+
"<!--[if gte mso 9]><xml>",
|
|
321
|
+
" <w:WordDocument>",
|
|
322
|
+
" <w:View>Print</w:View>",
|
|
323
|
+
" <w:Zoom>100</w:Zoom>",
|
|
324
|
+
" <w:DoNotOptimizeForBrowser/>",
|
|
325
|
+
" </w:WordDocument>",
|
|
326
|
+
"</xml><![endif]-->",
|
|
327
|
+
"<title>Guidex score</title>",
|
|
328
|
+
"<style>",
|
|
329
|
+
"<!--",
|
|
330
|
+
styleBlock,
|
|
331
|
+
"-->",
|
|
332
|
+
"</style>",
|
|
333
|
+
"</head>",
|
|
334
|
+
`<body lang=HU style="word-wrap:break-word${tabInterval !== null ? `;tab-interval:${fmtPt(tabInterval)}pt` : ""}">`,
|
|
335
|
+
"<!--StartFragment-->",
|
|
336
|
+
...paragraphs,
|
|
337
|
+
"<!--EndFragment-->",
|
|
338
|
+
"</body>",
|
|
339
|
+
"</html>"
|
|
340
|
+
].join("\n");
|
|
341
|
+
}
|
|
342
|
+
/** A syllable's parts as Word runs; characters with Word symbol
|
|
343
|
+
* stand-ins split into runs of their own. */
|
|
344
|
+
function wordRuns(part, textPx) {
|
|
345
|
+
const style = part.style;
|
|
346
|
+
const base = {
|
|
347
|
+
text: "",
|
|
348
|
+
bold: style.weight === "700",
|
|
349
|
+
italic: !!style.italic
|
|
350
|
+
};
|
|
351
|
+
if (style.fontFamily) base.fontFamily = firstFontFamily(style.fontFamily);
|
|
352
|
+
if (style.scale !== void 0 && style.scale !== 1) base.sizePt = textPx * style.scale * PT_PER_PX;
|
|
353
|
+
const color = resolveColor(style.color);
|
|
354
|
+
if (color) base.color = color;
|
|
355
|
+
if (style.raise) base.raisePt = textPx * style.raise * PT_PER_PX;
|
|
356
|
+
if (part.kind) base.kind = part.kind;
|
|
357
|
+
if (style.initial) base.initial = true;
|
|
358
|
+
const runs = [];
|
|
359
|
+
let plain = "";
|
|
360
|
+
const flush = () => {
|
|
361
|
+
if (plain) runs.push({
|
|
362
|
+
...base,
|
|
363
|
+
text: plain
|
|
364
|
+
});
|
|
365
|
+
plain = "";
|
|
366
|
+
};
|
|
367
|
+
for (const ch of part.text) {
|
|
368
|
+
const standIn = WORD_SYMBOL_SUBSTITUTES[ch];
|
|
369
|
+
if (standIn === void 0) {
|
|
370
|
+
plain += ch;
|
|
371
|
+
continue;
|
|
372
|
+
}
|
|
373
|
+
flush();
|
|
374
|
+
const symbolRun = {
|
|
375
|
+
...base,
|
|
376
|
+
text: ch,
|
|
377
|
+
symbol: {
|
|
378
|
+
char: standIn,
|
|
379
|
+
font: "Symbol"
|
|
380
|
+
}
|
|
381
|
+
};
|
|
382
|
+
delete symbolRun.fontFamily;
|
|
383
|
+
delete symbolRun.raisePt;
|
|
384
|
+
runs.push(symbolRun);
|
|
385
|
+
}
|
|
386
|
+
flush();
|
|
387
|
+
return runs;
|
|
388
|
+
}
|
|
389
|
+
/**
|
|
390
|
+
* Lays the score out for Word as structured lines: per line pair, the
|
|
391
|
+
* notes text and the text line as styled runs, dashes, word spaces, and
|
|
392
|
+
* self-correcting spacer counts (with absolute end positions) — exactly
|
|
393
|
+
* the layout toWordHtml/toWordText emit, for consumers building `.docx`
|
|
394
|
+
* paragraphs directly instead of parsing HTML.
|
|
395
|
+
*
|
|
396
|
+
* Browser-only: the layout measures with canvas and loaded webfonts.
|
|
397
|
+
*/
|
|
398
|
+
async function layoutForWord(source, options = {}) {
|
|
399
|
+
const layout = await layoutScore(source, resolveSizing(options));
|
|
400
|
+
const meter = buildMeter(layout, options.spacer ?? DEFAULT_SPACER);
|
|
401
|
+
const notesPt = layout.notesPx * PT_PER_PX;
|
|
402
|
+
const textPt = layout.textPx * PT_PER_PX;
|
|
403
|
+
const finite = layout.maxWidthPx !== Infinity;
|
|
404
|
+
return {
|
|
405
|
+
lines: layout.lines.map((line) => {
|
|
406
|
+
const text = [];
|
|
407
|
+
let emitted = 0;
|
|
408
|
+
const spacerTo = (targetPx) => {
|
|
409
|
+
const { count, emittedPx } = meter.advance(targetPx, emitted);
|
|
410
|
+
emitted = emittedPx;
|
|
411
|
+
if (count > 0) text.push({
|
|
412
|
+
type: "spacer",
|
|
413
|
+
count,
|
|
414
|
+
endPt: emitted * PT_PER_PX
|
|
415
|
+
});
|
|
416
|
+
};
|
|
417
|
+
for (const seg of line.segments) switch (seg.kind) {
|
|
418
|
+
case "gap":
|
|
419
|
+
spacerTo(seg.endPx);
|
|
420
|
+
break;
|
|
421
|
+
case "connector":
|
|
422
|
+
case "line-end-dash":
|
|
423
|
+
spacerTo(seg.dashStartPx);
|
|
424
|
+
text.push({ type: "dash" });
|
|
425
|
+
emitted += seg.dashWidth;
|
|
426
|
+
spacerTo(seg.kind === "connector" ? seg.nextAnchorPx : seg.trailEndPx);
|
|
427
|
+
break;
|
|
428
|
+
case "syl":
|
|
429
|
+
for (const part of seg.parts) for (const run of wordRuns(part, layout.textPx)) text.push({
|
|
430
|
+
type: "run",
|
|
431
|
+
run
|
|
432
|
+
});
|
|
433
|
+
emitted += seg.textWidth;
|
|
434
|
+
break;
|
|
435
|
+
case "word-space":
|
|
436
|
+
text.push({ type: "space" });
|
|
437
|
+
emitted += seg.width;
|
|
438
|
+
}
|
|
439
|
+
const out = {
|
|
440
|
+
notes: notesText(layout, line),
|
|
441
|
+
breakMarker: line.breakMarkerLeftPx !== void 0,
|
|
442
|
+
text
|
|
443
|
+
};
|
|
444
|
+
if (line.breakMarkerLeftPx !== void 0) out.breakMarkerTabStopPt = finite ? layout.starTarget * PT_PER_PX : (line.notesEnd + line.breakMarkerLeftPx + layout.starWidth) * PT_PER_PX;
|
|
445
|
+
return out;
|
|
446
|
+
}),
|
|
447
|
+
style: layout.styleName,
|
|
448
|
+
styleNames: resolveStyleNames(layout, options.styleNames),
|
|
449
|
+
bold: layout.bold,
|
|
450
|
+
textPt,
|
|
451
|
+
notesPt,
|
|
452
|
+
notesLineHeightPt: notesPt * LINE_HEIGHT_RATIO,
|
|
453
|
+
textLineHeightPt: textPt * LINE_HEIGHT_RATIO,
|
|
454
|
+
textFontFamily: firstFontFamily(layout.styleSet.textFontStack),
|
|
455
|
+
notesFontFamily: NOTES_FONT_FAMILY,
|
|
456
|
+
maxWidthPt: layout.maxWidthPx * PT_PER_PX,
|
|
457
|
+
breakTabStopPt: finite ? layout.starTarget * PT_PER_PX : null,
|
|
458
|
+
spacer: {
|
|
459
|
+
character: meter.character,
|
|
460
|
+
char: meter.char,
|
|
461
|
+
unitPt: meter.unitPx * PT_PER_PX,
|
|
462
|
+
letterSpacingPt: meter.letterSpacingPt,
|
|
463
|
+
tabIntervalPt: meter.character === "tab" ? meter.unitPx * PT_PER_PX : null
|
|
464
|
+
}
|
|
465
|
+
};
|
|
466
|
+
}
|
|
467
|
+
/** Serializes a structured Word layout to the plain-text export:
|
|
468
|
+
* alternating notes / text lines, `\t*` after broken notes lines. */
|
|
469
|
+
function wordLayoutText(layout) {
|
|
470
|
+
const pieceText = (piece) => {
|
|
471
|
+
switch (piece.type) {
|
|
472
|
+
case "spacer": return layout.spacer.char.repeat(piece.count);
|
|
473
|
+
case "run": return piece.run.text;
|
|
474
|
+
case "dash": return "-";
|
|
475
|
+
case "space": return " ";
|
|
476
|
+
}
|
|
477
|
+
};
|
|
478
|
+
return layout.lines.flatMap((line) => [line.notes + (line.breakMarker ? " *" : ""), line.text.map(pieceText).join("")]).join("\n");
|
|
479
|
+
}
|
|
480
|
+
/**
|
|
481
|
+
* Renders the score as the plain-text equivalent of the Word export: the
|
|
482
|
+
* notes verbatim and the same self-correcting spacer counts, but no HTML
|
|
483
|
+
* envelope, no letter-spacing tuning, and no mso runs. The clipboard
|
|
484
|
+
* writer sends this as the text/plain fallback.
|
|
485
|
+
*/
|
|
486
|
+
async function toWordText(source, options = {}) {
|
|
487
|
+
return wordLayoutText(await layoutForWord(source, options));
|
|
488
|
+
}
|
|
489
|
+
//#endregion
|
|
490
|
+
//#region src/wordClipboard.ts
|
|
491
|
+
function clipboardSupported() {
|
|
492
|
+
return typeof navigator !== "undefined" && !!navigator.clipboard && typeof ClipboardItem !== "undefined";
|
|
493
|
+
}
|
|
494
|
+
/** The execCommand fallback for non-secure contexts and missing async
|
|
495
|
+
* clipboard APIs: copies the plain text only. Returns the copied text or
|
|
496
|
+
* null when the copy failed. */
|
|
497
|
+
function copyViaExecCommand(text) {
|
|
498
|
+
if (typeof document === "undefined") return null;
|
|
499
|
+
const textarea = document.createElement("textarea");
|
|
500
|
+
textarea.value = text;
|
|
501
|
+
textarea.setAttribute("readonly", "");
|
|
502
|
+
textarea.style.position = "fixed";
|
|
503
|
+
textarea.style.opacity = "0";
|
|
504
|
+
document.body.appendChild(textarea);
|
|
505
|
+
textarea.select();
|
|
506
|
+
let ok;
|
|
507
|
+
try {
|
|
508
|
+
ok = document.execCommand("copy");
|
|
509
|
+
} catch {
|
|
510
|
+
ok = false;
|
|
511
|
+
}
|
|
512
|
+
textarea.remove();
|
|
513
|
+
return ok ? text : null;
|
|
514
|
+
}
|
|
515
|
+
/**
|
|
516
|
+
* Copies the score for pasting into Word: text/html (the Word export)
|
|
517
|
+
* with text/plain as the fallback flavour. Returns what was prepared.
|
|
518
|
+
* Throws when no clipboard path works.
|
|
519
|
+
*/
|
|
520
|
+
async function copyWordHtml(source, options = {}) {
|
|
521
|
+
const htmlPromise = toWordHtml(source, options);
|
|
522
|
+
const textPromise = toWordText(source, options);
|
|
523
|
+
if (clipboardSupported()) try {
|
|
524
|
+
await navigator.clipboard.write([new ClipboardItem({
|
|
525
|
+
"text/html": htmlPromise.then((html) => new Blob([html], { type: "text/html" })),
|
|
526
|
+
"text/plain": textPromise.then((text) => new Blob([text], { type: "text/plain" }))
|
|
527
|
+
})]);
|
|
528
|
+
return {
|
|
529
|
+
html: await htmlPromise,
|
|
530
|
+
text: await textPromise
|
|
531
|
+
};
|
|
532
|
+
} catch {}
|
|
533
|
+
const copied = copyViaExecCommand(await textPromise);
|
|
534
|
+
if (copied === null) throw new Error("Could not write to the clipboard");
|
|
535
|
+
return {
|
|
536
|
+
html: await htmlPromise,
|
|
537
|
+
text: copied
|
|
538
|
+
};
|
|
539
|
+
}
|
|
540
|
+
/**
|
|
541
|
+
* The deliberate plain-text-only copy: the same layout and spacer counts
|
|
542
|
+
* without the HTML envelope, for workflows that want the raw text.
|
|
543
|
+
*/
|
|
544
|
+
async function copyWordPlainText(source, options = {}) {
|
|
545
|
+
return copyPlainText(await toWordText(source, options));
|
|
546
|
+
}
|
|
547
|
+
/**
|
|
548
|
+
* Copies raw text with no export flavour — the same write path as the
|
|
549
|
+
* Word copy's plain fallback, for copies of the script source itself.
|
|
550
|
+
* Returns the copied text; throws when no clipboard path works.
|
|
551
|
+
*/
|
|
552
|
+
async function copyPlainText(text) {
|
|
553
|
+
if (typeof navigator !== "undefined" && navigator.clipboard) try {
|
|
554
|
+
await navigator.clipboard.writeText(text);
|
|
555
|
+
return text;
|
|
556
|
+
} catch {}
|
|
557
|
+
const copied = copyViaExecCommand(text);
|
|
558
|
+
if (copied === null) throw new Error("Could not write to the clipboard");
|
|
559
|
+
return copied;
|
|
560
|
+
}
|
|
561
|
+
//#endregion
|
|
562
|
+
//#region src/wordChecker.ts
|
|
563
|
+
/**
|
|
564
|
+
* Class & construction checker for Word-pasted HTML (issue #28): the user
|
|
565
|
+
* copies from Word and pastes; the checker reads the HTML clipboard flavour
|
|
566
|
+
* (style names survive only there) and diagnoses it.
|
|
567
|
+
*
|
|
568
|
+
* Three checks run over the artifact-stripped document:
|
|
569
|
+
* - class check: every character classified into its expected role — the
|
|
570
|
+
* Guido HU neume repertoire on notes lines, text characters and marker
|
|
571
|
+
* glyphs on text lines — with unknown characters reported at position;
|
|
572
|
+
* - construction check: alternating nota/textus paragraphs, a clef
|
|
573
|
+
* starting each notes line, legal group syntax, spacer structure, and
|
|
574
|
+
* the tab + `*` break marker on broken notes lines;
|
|
575
|
+
* - gap census: which spacer mechanism the pasted text uses and the
|
|
576
|
+
* effective width Word gave each gap class, so the tuning loop is
|
|
577
|
+
* informed by measurement rather than eyeballing.
|
|
578
|
+
*
|
|
579
|
+
* The declared/used Word style names are extracted so the export can
|
|
580
|
+
* target the user's own styles. The demo UI is a consumer of this engine,
|
|
581
|
+
* never its home.
|
|
582
|
+
*/
|
|
583
|
+
var NOTES_MARKER = "*";
|
|
584
|
+
/** The spacer characters recognized inside raw text (Word also wraps them
|
|
585
|
+
* in runs; those are recognized by their styles). */
|
|
586
|
+
var SPACER_CHARS = /* @__PURE__ */ new Set([
|
|
587
|
+
"\xA0",
|
|
588
|
+
" ",
|
|
589
|
+
" "
|
|
590
|
+
]);
|
|
591
|
+
/** Characters allowed on a notes line besides the Guido HU repertoire. */
|
|
592
|
+
var NOTES_EXTRA = /* @__PURE__ */ new Set([
|
|
593
|
+
"-",
|
|
594
|
+
"¨",
|
|
595
|
+
"<",
|
|
596
|
+
">"
|
|
597
|
+
]);
|
|
598
|
+
/** Explicit punctuation allowed on text lines (besides Unicode
|
|
599
|
+
* letters/marks/numbers); anything else is out of repertoire. */
|
|
600
|
+
var TEXT_PUNCT = /* @__PURE__ */ new Set([
|
|
601
|
+
".",
|
|
602
|
+
",",
|
|
603
|
+
";",
|
|
604
|
+
":",
|
|
605
|
+
"!",
|
|
606
|
+
"?",
|
|
607
|
+
"'",
|
|
608
|
+
"\"",
|
|
609
|
+
"(",
|
|
610
|
+
")",
|
|
611
|
+
"[",
|
|
612
|
+
"]",
|
|
613
|
+
"{",
|
|
614
|
+
"}",
|
|
615
|
+
"-",
|
|
616
|
+
"–",
|
|
617
|
+
"—",
|
|
618
|
+
"*",
|
|
619
|
+
"†",
|
|
620
|
+
"∗",
|
|
621
|
+
"=",
|
|
622
|
+
"+",
|
|
623
|
+
"/",
|
|
624
|
+
"\\",
|
|
625
|
+
"%",
|
|
626
|
+
"§",
|
|
627
|
+
"·",
|
|
628
|
+
"«",
|
|
629
|
+
"»",
|
|
630
|
+
"‹",
|
|
631
|
+
"›",
|
|
632
|
+
"„",
|
|
633
|
+
"“",
|
|
634
|
+
"”",
|
|
635
|
+
"‘",
|
|
636
|
+
"’",
|
|
637
|
+
"…",
|
|
638
|
+
"°",
|
|
639
|
+
"≈"
|
|
640
|
+
]);
|
|
641
|
+
function buildNotesRepertoire() {
|
|
642
|
+
const chars = new Set(NOTES_EXTRA);
|
|
643
|
+
for (const c of SCORE_MARKERS) chars.add(c);
|
|
644
|
+
for (const c of SPECIAL_NOTES) chars.add(c);
|
|
645
|
+
for (const c of NOTE_MODIFIERS) chars.add(c);
|
|
646
|
+
for (let i = 0; i < 10; i++) chars.add(String(i));
|
|
647
|
+
for (let i = 0; i < 26; i++) {
|
|
648
|
+
chars.add(String.fromCharCode(97 + i));
|
|
649
|
+
chars.add(String.fromCharCode(65 + i));
|
|
650
|
+
}
|
|
651
|
+
return chars;
|
|
652
|
+
}
|
|
653
|
+
var NOTES_REPERTOIRE = buildNotesRepertoire();
|
|
654
|
+
var styleOf = (el) => el.getAttribute("style") ?? "";
|
|
655
|
+
var isElement = (node) => node.nodeType === Node.ELEMENT_NODE;
|
|
656
|
+
/** Collects the paragraph's content as an ordered token stream, recording
|
|
657
|
+
* spacer runs from their mso styles and splitting raw spacer characters
|
|
658
|
+
* out of text. Word serialization artifacts (comments, o:p, conditional
|
|
659
|
+
* xml) never become tokens. */
|
|
660
|
+
function collectTokens(el) {
|
|
661
|
+
const tokens = [];
|
|
662
|
+
const walk = (node) => {
|
|
663
|
+
if (!isElement(node)) {
|
|
664
|
+
const text = node.textContent ?? "";
|
|
665
|
+
if (text) tokens.push({
|
|
666
|
+
kind: "text",
|
|
667
|
+
text
|
|
668
|
+
});
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
if (node.nodeType === Node.COMMENT_NODE) return;
|
|
672
|
+
const tag = node.tagName.toLowerCase();
|
|
673
|
+
if (tag === "o:p" || tag === "o:smarttagtype") return;
|
|
674
|
+
const style = styleOf(node);
|
|
675
|
+
const tabCount = /mso-tab-count:\s*(\d+)/.exec(style);
|
|
676
|
+
if (tabCount) {
|
|
677
|
+
tokens.push({
|
|
678
|
+
kind: "spacer",
|
|
679
|
+
mechanism: "tab",
|
|
680
|
+
character: " ",
|
|
681
|
+
units: Number(tabCount[1]),
|
|
682
|
+
letterSpacingPt: 0
|
|
683
|
+
});
|
|
684
|
+
return;
|
|
685
|
+
}
|
|
686
|
+
if (/mso-spacerun:\s*yes/.test(style)) {
|
|
687
|
+
const spaces = node.textContent ?? "";
|
|
688
|
+
tokens.push({
|
|
689
|
+
kind: "spacer",
|
|
690
|
+
mechanism: "spacerun",
|
|
691
|
+
character: " ",
|
|
692
|
+
units: spaces.length,
|
|
693
|
+
letterSpacingPt: letterSpacingOf(style)
|
|
694
|
+
});
|
|
695
|
+
return;
|
|
696
|
+
}
|
|
697
|
+
if (/mso-char-type:\s*symbol/.test(style)) {
|
|
698
|
+
tokens.push({
|
|
699
|
+
kind: "symbol",
|
|
700
|
+
text: node.textContent ?? ""
|
|
701
|
+
});
|
|
702
|
+
return;
|
|
703
|
+
}
|
|
704
|
+
const ls = letterSpacingOf(style);
|
|
705
|
+
if (ls !== 0) {
|
|
706
|
+
const chars = [...node.textContent ?? ""];
|
|
707
|
+
if (chars.length > 0 && new Set(chars).size === 1 && (SPACER_CHARS.has(chars[0]) || chars[0] === " ")) {
|
|
708
|
+
tokens.push({
|
|
709
|
+
kind: "spacer",
|
|
710
|
+
mechanism: "char",
|
|
711
|
+
character: chars[0],
|
|
712
|
+
units: chars.length,
|
|
713
|
+
letterSpacingPt: ls
|
|
714
|
+
});
|
|
715
|
+
return;
|
|
716
|
+
}
|
|
717
|
+
}
|
|
718
|
+
const own = node.childNodes;
|
|
719
|
+
if (own.length === 0) {
|
|
720
|
+
const text = node.textContent ?? "";
|
|
721
|
+
if (text) tokens.push({
|
|
722
|
+
kind: "text",
|
|
723
|
+
text
|
|
724
|
+
});
|
|
725
|
+
return;
|
|
726
|
+
}
|
|
727
|
+
own.forEach(walk);
|
|
728
|
+
};
|
|
729
|
+
el.childNodes.forEach(walk);
|
|
730
|
+
const split = [];
|
|
731
|
+
for (const token of tokens) {
|
|
732
|
+
if (token.kind !== "text") {
|
|
733
|
+
split.push(token);
|
|
734
|
+
continue;
|
|
735
|
+
}
|
|
736
|
+
let run = "";
|
|
737
|
+
for (const ch of token.text) if (SPACER_CHARS.has(ch)) {
|
|
738
|
+
if (run) {
|
|
739
|
+
split.push({
|
|
740
|
+
kind: "text",
|
|
741
|
+
text: run
|
|
742
|
+
});
|
|
743
|
+
run = "";
|
|
744
|
+
}
|
|
745
|
+
split.push({
|
|
746
|
+
kind: "spacer",
|
|
747
|
+
mechanism: "char",
|
|
748
|
+
character: ch,
|
|
749
|
+
units: 1,
|
|
750
|
+
letterSpacingPt: 0
|
|
751
|
+
});
|
|
752
|
+
} else run += ch;
|
|
753
|
+
if (run) split.push({
|
|
754
|
+
kind: "text",
|
|
755
|
+
text: run
|
|
756
|
+
});
|
|
757
|
+
}
|
|
758
|
+
return mergeAdjacentSpacers(split);
|
|
759
|
+
}
|
|
760
|
+
function letterSpacingOf(style) {
|
|
761
|
+
const m = /letter-spacing:\s*(-?[\d.]+)pt/.exec(style);
|
|
762
|
+
return m ? parseFloat(m[1]) : 0;
|
|
763
|
+
}
|
|
764
|
+
function mergeAdjacentSpacers(tokens) {
|
|
765
|
+
const merged = [];
|
|
766
|
+
for (const token of tokens) {
|
|
767
|
+
const last = merged[merged.length - 1];
|
|
768
|
+
if (token.kind === "spacer" && last?.kind === "spacer" && token.mechanism === last.mechanism && token.character === last.character && token.letterSpacingPt === last.letterSpacingPt) {
|
|
769
|
+
last.units += token.units;
|
|
770
|
+
continue;
|
|
771
|
+
}
|
|
772
|
+
merged.push(token);
|
|
773
|
+
}
|
|
774
|
+
return merged;
|
|
775
|
+
}
|
|
776
|
+
var visibleText = (tokens) => tokens.map((t) => t.kind === "text" || t.kind === "symbol" ? t.text : "").join("");
|
|
777
|
+
function classifyKind(styleName) {
|
|
778
|
+
if (!styleName) return "unknown";
|
|
779
|
+
if (/nota/i.test(styleName)) return "nota";
|
|
780
|
+
if (/textus/i.test(styleName)) return "textus";
|
|
781
|
+
return "unknown";
|
|
782
|
+
}
|
|
783
|
+
/** Content-based kind guess for style-stripped paragraphs: the fonts Word
|
|
784
|
+
* inlined when the style failed to map are the strongest signal (Guidohu
|
|
785
|
+
* → notes, Book Antiqua/Times → text); the clef-prefix shape is the
|
|
786
|
+
* fallback. Empty paragraphs stay unknown. */
|
|
787
|
+
function guessKind(para) {
|
|
788
|
+
if (para.text.trim() === "") return null;
|
|
789
|
+
let styleText = para.el.getAttribute("style") ?? "";
|
|
790
|
+
para.el.querySelectorAll("[style]").forEach((el) => {
|
|
791
|
+
styleText += `;${el.getAttribute("style")}`;
|
|
792
|
+
});
|
|
793
|
+
if (/font-family:[^;]*guido/i.test(styleText)) return "nota";
|
|
794
|
+
if (/font-family:[^;]*(book antiqua|times new roman)/i.test(styleText)) return "textus";
|
|
795
|
+
if (/^[A-Za-z<=]{1,3}-/.test(para.text) && (para.text.match(/-/g) ?? []).length >= 2) return "nota";
|
|
796
|
+
return null;
|
|
797
|
+
}
|
|
798
|
+
/** The gap class of a spacer run inside a textus paragraph: the first run
|
|
799
|
+
* is the lead-in; runs flanked by the connector dash are connector pads
|
|
800
|
+
* (a pair that closes the paragraph is the line-end dash); the rest are
|
|
801
|
+
* word gaps. */
|
|
802
|
+
var textOf = (token) => {
|
|
803
|
+
if (!token) return null;
|
|
804
|
+
return token.kind === "text" || token.kind === "symbol" ? token.text : null;
|
|
805
|
+
};
|
|
806
|
+
function gapClassOf(tokens, index) {
|
|
807
|
+
if (tokens.findIndex((t) => t.kind === "spacer") === index) return "lead-in";
|
|
808
|
+
let prevText = null;
|
|
809
|
+
for (let i = index - 1; i >= 0; i--) {
|
|
810
|
+
const text = textOf(tokens[i]);
|
|
811
|
+
if (text !== null) {
|
|
812
|
+
prevText = text;
|
|
813
|
+
break;
|
|
814
|
+
}
|
|
815
|
+
}
|
|
816
|
+
let nextText = null;
|
|
817
|
+
for (let i = index + 1; i < tokens.length; i++) {
|
|
818
|
+
const text = textOf(tokens[i]);
|
|
819
|
+
if (text !== null) {
|
|
820
|
+
nextText = text;
|
|
821
|
+
break;
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
if (prevText?.endsWith("-") || nextText?.startsWith("-")) return tokens.slice(index + 1).every((t) => t.kind === "spacer" || (textOf(t) ?? "").trim() === "") ? "line-end" : "connector";
|
|
825
|
+
return "word-gap";
|
|
826
|
+
}
|
|
827
|
+
function estimateUnitWidthPt(mechanism, character, letterSpacingPt, unitPt, textusFont) {
|
|
828
|
+
if (mechanism === "tab") return unitPt;
|
|
829
|
+
return measure(character, textusFont) * .75 + letterSpacingPt;
|
|
830
|
+
}
|
|
831
|
+
/**
|
|
832
|
+
* The census measures gap characters in the TEXT font: the declared
|
|
833
|
+
* textus rule is picked explicitly, because the nota style is usually
|
|
834
|
+
* declared first and would hand back the larger chant-font metrics.
|
|
835
|
+
* Falls back to the first font-bearing rule that is not the notes style,
|
|
836
|
+
* and to a default serif when nothing identifiable remains.
|
|
837
|
+
*/
|
|
838
|
+
function pickTextusFont(styleText) {
|
|
839
|
+
const rules = [];
|
|
840
|
+
for (const m of styleText.matchAll(/([^{}]+)\{([^{}]*)\}/g)) rules.push({
|
|
841
|
+
selector: m[1],
|
|
842
|
+
body: m[2]
|
|
843
|
+
});
|
|
844
|
+
const fontOf = (body) => {
|
|
845
|
+
const size = /font-size:\s*([\d.]+)pt/.exec(body);
|
|
846
|
+
const family = /font-family:\s*(?:"([^"]+)"|'([^']+)'|([^;{}]+))/.exec(body);
|
|
847
|
+
const name = family ? (family[1] ?? family[2] ?? family[3]).split(",")[0].trim().replace(/^['"]+|['"]+$/g, "") : null;
|
|
848
|
+
return size && name ? `${parseFloat(size[1]) * 4 / 3}px "${name}"` : null;
|
|
849
|
+
};
|
|
850
|
+
const matches = (rule, re) => re.test(rule.selector) || re.test(rule.body);
|
|
851
|
+
for (const rule of rules) if (matches(rule, /textus/i)) {
|
|
852
|
+
const font = fontOf(rule.body);
|
|
853
|
+
if (font) return font;
|
|
854
|
+
}
|
|
855
|
+
for (const rule of rules) if (!matches(rule, /nota/i)) {
|
|
856
|
+
const font = fontOf(rule.body);
|
|
857
|
+
if (font) return font;
|
|
858
|
+
}
|
|
859
|
+
return "12px serif";
|
|
860
|
+
}
|
|
861
|
+
/**
|
|
862
|
+
* Checks a pasted Word HTML document (the text/html clipboard flavour).
|
|
863
|
+
* Returns the positioned issues, the paragraph structure, the style names
|
|
864
|
+
* in use, and the gap census. `ok` is false when any error-level issue
|
|
865
|
+
* was found; warnings alone keep it true.
|
|
866
|
+
*/
|
|
867
|
+
function checkWordHtml(html) {
|
|
868
|
+
const issues = [];
|
|
869
|
+
const error = (message, paragraph, offset) => issues.push({
|
|
870
|
+
severity: "error",
|
|
871
|
+
message,
|
|
872
|
+
paragraph,
|
|
873
|
+
offset
|
|
874
|
+
});
|
|
875
|
+
const warn = (message, paragraph, offset) => issues.push({
|
|
876
|
+
severity: "warning",
|
|
877
|
+
message,
|
|
878
|
+
paragraph,
|
|
879
|
+
offset
|
|
880
|
+
});
|
|
881
|
+
const doc = new DOMParser().parseFromString(html, "text/html");
|
|
882
|
+
const styleText = [...doc.querySelectorAll("style")].map((s) => s.textContent ?? "").join("\n");
|
|
883
|
+
const styleNames = /* @__PURE__ */ new Set();
|
|
884
|
+
for (const m of styleText.matchAll(/mso-style-name:\s*"([^"]+)"/g)) styleNames.add(m[1]);
|
|
885
|
+
const classToName = /* @__PURE__ */ new Map();
|
|
886
|
+
for (const m of styleText.matchAll(/p\.([A-Za-z0-9_-]+)\s*\{([^}]*)\}/g)) {
|
|
887
|
+
const name = /mso-style-name:\s*"([^"]+)"/.exec(m[2])?.[1];
|
|
888
|
+
if (name) classToName.set(m[1], name);
|
|
889
|
+
}
|
|
890
|
+
const bodyStyle = doc.body?.getAttribute("style") ?? "";
|
|
891
|
+
const unitPt = /tab-interval:\s*([\d.]+)pt/.exec(bodyStyle)?.[1] ? parseFloat(/tab-interval:\s*([\d.]+)pt/.exec(bodyStyle)[1]) : null;
|
|
892
|
+
const textusFont = pickTextusFont(styleText);
|
|
893
|
+
const paragraphs = [];
|
|
894
|
+
[...doc.body?.querySelectorAll("p") ?? []].filter((el) => el.tagName.toLowerCase() === "p").forEach((p, index) => {
|
|
895
|
+
const cls = p.getAttribute("class") ?? "";
|
|
896
|
+
const styleName = classToName.get(cls) ?? (cls || null);
|
|
897
|
+
const tokens = collectTokens(p);
|
|
898
|
+
paragraphs.push({
|
|
899
|
+
index,
|
|
900
|
+
kind: classifyKind(styleName),
|
|
901
|
+
styleName,
|
|
902
|
+
text: visibleText(tokens),
|
|
903
|
+
tokens,
|
|
904
|
+
el: p
|
|
905
|
+
});
|
|
906
|
+
if (styleName) styleNames.add(styleName);
|
|
907
|
+
});
|
|
908
|
+
if (paragraphs.length === 0) error("No paragraphs found — paste the HTML clipboard flavour copied from Word");
|
|
909
|
+
for (const para of paragraphs) {
|
|
910
|
+
if (para.kind !== "unknown") continue;
|
|
911
|
+
const guessed = guessKind(para);
|
|
912
|
+
if (!guessed) continue;
|
|
913
|
+
para.kind = guessed;
|
|
914
|
+
warn(`Paragraph ${para.index + 1} carries direct formatting (${para.styleName ?? "no style"}) — the ${guessed === "nota" ? "notes" : "text"} style did not apply in Word`, para.index);
|
|
915
|
+
}
|
|
916
|
+
paragraphs.forEach((para, i) => {
|
|
917
|
+
if (para.kind === "unknown") {
|
|
918
|
+
error(`Paragraph ${i + 1} has an unknown style (${para.styleName ?? "none"}) — expected a nota/textus style name`, i);
|
|
919
|
+
return;
|
|
920
|
+
}
|
|
921
|
+
const prev = paragraphs[i - 1];
|
|
922
|
+
if (i === 0 && para.kind !== "nota") error("The first paragraph must be the notes line (the nota style)", i);
|
|
923
|
+
if (prev && prev.kind === para.kind) error(`Paragraphs ${i} and ${i + 1} are both ${para.kind} — the notes and text lines must alternate`, i);
|
|
924
|
+
});
|
|
925
|
+
paragraphs.forEach((para, i) => {
|
|
926
|
+
if (para.kind !== "nota") return;
|
|
927
|
+
const next = paragraphs[i + 1];
|
|
928
|
+
if (next === void 0 || next.kind !== "textus") error(`Paragraph ${i + 1} is a notes line without a text line after it — every notes line pairs with a text line`, i);
|
|
929
|
+
});
|
|
930
|
+
for (const para of paragraphs) if (para.kind === "nota") checkNotesParagraph(para, error, warn);
|
|
931
|
+
else if (para.kind === "textus") checkTextParagraph(para, error, warn);
|
|
932
|
+
const gapMap = /* @__PURE__ */ new Map();
|
|
933
|
+
let letterSpacingPt = null;
|
|
934
|
+
for (const para of paragraphs) {
|
|
935
|
+
if (para.kind !== "textus") continue;
|
|
936
|
+
para.tokens.forEach((token, ti) => {
|
|
937
|
+
if (token.kind !== "spacer") return;
|
|
938
|
+
const gapClass = gapClassOf(para.tokens, ti);
|
|
939
|
+
if (token.letterSpacingPt) letterSpacingPt = Math.max(letterSpacingPt ?? 0, token.letterSpacingPt);
|
|
940
|
+
const key = `${gapClass}:${token.mechanism}:${token.character}:${token.letterSpacingPt}`;
|
|
941
|
+
const stat = gapMap.get(key) ?? {
|
|
942
|
+
gapClass,
|
|
943
|
+
mechanism: token.mechanism,
|
|
944
|
+
character: token.character,
|
|
945
|
+
letterSpacingPt: token.letterSpacingPt,
|
|
946
|
+
runs: 0,
|
|
947
|
+
units: 0,
|
|
948
|
+
effectiveWidthPt: null
|
|
949
|
+
};
|
|
950
|
+
stat.runs += 1;
|
|
951
|
+
stat.units += token.units;
|
|
952
|
+
gapMap.set(key, stat);
|
|
953
|
+
});
|
|
954
|
+
}
|
|
955
|
+
const gaps = [...gapMap.values()].map((stat) => {
|
|
956
|
+
const unitWidthPt = estimateUnitWidthPt(stat.mechanism, stat.character, stat.letterSpacingPt, unitPt, textusFont);
|
|
957
|
+
return {
|
|
958
|
+
...stat,
|
|
959
|
+
effectiveWidthPt: unitWidthPt === null || stat.runs === 0 ? null : unitWidthPt * (stat.units / stat.runs)
|
|
960
|
+
};
|
|
961
|
+
});
|
|
962
|
+
const mechanisms = new Set(gaps.map((g) => g.mechanism));
|
|
963
|
+
return {
|
|
964
|
+
ok: !issues.some((i) => i.severity === "error"),
|
|
965
|
+
issues,
|
|
966
|
+
paragraphs: paragraphs.map((para) => ({
|
|
967
|
+
index: para.index,
|
|
968
|
+
kind: para.kind,
|
|
969
|
+
styleName: para.styleName,
|
|
970
|
+
text: para.text
|
|
971
|
+
})),
|
|
972
|
+
styleNames: [...styleNames].sort(),
|
|
973
|
+
gapCensus: {
|
|
974
|
+
mechanism: mechanisms.size === 1 ? [...mechanisms][0] : null,
|
|
975
|
+
letterSpacingPt,
|
|
976
|
+
unitPt,
|
|
977
|
+
gaps
|
|
978
|
+
}
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
function checkNotesParagraph(para, error, warn) {
|
|
982
|
+
const text = para.text;
|
|
983
|
+
if (text.length === 0) {
|
|
984
|
+
warn("Empty notes line", para.index);
|
|
985
|
+
return;
|
|
986
|
+
}
|
|
987
|
+
if (!/[A-Za-z<=]/.test(text[0])) error(`Notes line does not start with a clef (found ${JSON.stringify(text[0])})`, para.index, 0);
|
|
988
|
+
const isNotesWhitespace = (ch) => ch === " " || ch === "\xA0" || ch === " ";
|
|
989
|
+
const MARKER_TAIL = /* @__PURE__ */ new Set([
|
|
990
|
+
...SCORE_MARKERS,
|
|
991
|
+
NOTES_MARKER,
|
|
992
|
+
"†",
|
|
993
|
+
"-",
|
|
994
|
+
"¨",
|
|
995
|
+
" "
|
|
996
|
+
]);
|
|
997
|
+
let offset = 0;
|
|
998
|
+
while (offset < text.length) {
|
|
999
|
+
const ch = text[offset];
|
|
1000
|
+
if (isNotesWhitespace(ch)) {
|
|
1001
|
+
let end = offset;
|
|
1002
|
+
while (end < text.length && isNotesWhitespace(text[end])) end++;
|
|
1003
|
+
if (![...text.slice(end)].every((c) => MARKER_TAIL.has(c))) error("Whitespace inside the notes line — a spacer collapsed where a note belongs; the notes no longer align with their syllables", para.index, offset);
|
|
1004
|
+
offset = end;
|
|
1005
|
+
continue;
|
|
1006
|
+
}
|
|
1007
|
+
if (ch !== NOTES_MARKER && !NOTES_REPERTOIRE.has(ch)) error(`Unknown character ${JSON.stringify(ch)} in the notes line — outside the Guido HU repertoire`, para.index, offset);
|
|
1008
|
+
offset += ch.length;
|
|
1009
|
+
}
|
|
1010
|
+
if (text.endsWith(NOTES_MARKER)) {
|
|
1011
|
+
const last = para.tokens[para.tokens.length - 1];
|
|
1012
|
+
const before = para.tokens[para.tokens.length - 2];
|
|
1013
|
+
const beforeIsTab = before?.kind === "spacer" && /[\s\u00A0\u2002\u2003]/.test(before.character) || before?.kind === "text" && /^[\s\u00A0\t]+$/.test(before.text);
|
|
1014
|
+
if (last?.kind !== "text" || !last.text.endsWith(NOTES_MARKER)) warn("Break marker found in an unexpected token position", para.index);
|
|
1015
|
+
else if (!beforeIsTab) error("The line-end break marker must follow a tab (the right-aligned tab stop)", para.index);
|
|
1016
|
+
}
|
|
1017
|
+
if (/-{4,}/.test(text) && !text.endsWith(NOTES_MARKER)) warn("More than three consecutive staff dashes — staff fill dashes belong on broken lines only", para.index);
|
|
1018
|
+
}
|
|
1019
|
+
function checkTextParagraph(para, error, warn) {
|
|
1020
|
+
let offset = 0;
|
|
1021
|
+
for (const token of para.tokens) {
|
|
1022
|
+
if (token.kind === "symbol") {
|
|
1023
|
+
for (const ch of token.text) {
|
|
1024
|
+
if (!"*†·".includes(ch)) warn(`Symbol-font run carries ${JSON.stringify(ch)} — expected a marker glyph`, para.index, offset);
|
|
1025
|
+
offset += ch.length;
|
|
1026
|
+
}
|
|
1027
|
+
continue;
|
|
1028
|
+
}
|
|
1029
|
+
if (token.kind !== "text") continue;
|
|
1030
|
+
for (const ch of token.text) {
|
|
1031
|
+
if (!(/[\p{L}\p{M}\p{N}]/u.test(ch) || TEXT_PUNCT.has(ch) || ch === " " || NOTES_REPERTOIRE.has(ch))) error(`Unknown character ${JSON.stringify(ch)} in the text line`, para.index, offset);
|
|
1032
|
+
offset += ch.length;
|
|
1033
|
+
}
|
|
1034
|
+
}
|
|
1035
|
+
for (const token of para.tokens) {
|
|
1036
|
+
if (token.kind !== "spacer") continue;
|
|
1037
|
+
if (token.units <= 0) warn("Empty spacer run — the gap carries no units", para.index);
|
|
1038
|
+
if (token.mechanism === "spacerun" && token.units > 40) warn(`Spacerun of ${token.units} spaces — Word may not preserve runs this long; prefer tabs or tuned spacer characters`, para.index);
|
|
1039
|
+
}
|
|
1040
|
+
}
|
|
1041
|
+
//#endregion
|
|
1042
|
+
export { DEFAULT_TAB_INTERVAL_PT as a, toWordHtml as c, DEFAULT_SPACER as i, toWordText as l, copyWordHtml as n, SpacerMeter as o, copyWordPlainText as r, layoutForWord as s, checkWordHtml as t, wordLayoutText as u };
|