jpfun 0.9.0 → 1.0.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.
Files changed (104) hide show
  1. package/README.md +10 -15
  2. package/dist/diagnostic.d.ts +29 -2
  3. package/dist/diagnostic.js +5 -4
  4. package/dist/functions/arpeggio/index.js +2 -3
  5. package/dist/functions/bar/index.d.ts +3 -0
  6. package/dist/functions/bar/index.js +18 -3
  7. package/dist/functions/beam/layout.js +3 -2
  8. package/dist/functions/box/index.js +1 -0
  9. package/dist/functions/dash/index.js +5 -2
  10. package/dist/functions/div/index.d.ts +1 -1
  11. package/dist/functions/div/index.js +4 -2
  12. package/dist/functions/dyn/index.js +1 -0
  13. package/dist/functions/gliss/index.js +4 -2
  14. package/dist/functions/grace/index.js +3 -5
  15. package/dist/functions/head/index.js +23 -30
  16. package/dist/functions/key/index.js +4 -7
  17. package/dist/functions/meter/index.d.ts +1 -0
  18. package/dist/functions/meter/index.js +3 -0
  19. package/dist/functions/meter/shape.d.ts +1 -1
  20. package/dist/functions/note/accidentals.d.ts +3 -3
  21. package/dist/functions/note/accidentals.js +29 -16
  22. package/dist/functions/note/index.js +11 -13
  23. package/dist/functions/note/source-transform.d.ts +15 -0
  24. package/dist/functions/note/source-transform.js +74 -67
  25. package/dist/functions/ottava/index.js +1 -0
  26. package/dist/functions/page/index.js +4 -3
  27. package/dist/functions/rest/index.js +8 -6
  28. package/dist/functions/slide/index.js +1 -0
  29. package/dist/functions/temporal.d.ts +9 -3
  30. package/dist/functions/temporal.js +15 -2
  31. package/dist/functions/tie/index.js +28 -4
  32. package/dist/functions/tremolo/index.js +1 -0
  33. package/dist/functions/tuplet/index.js +1 -0
  34. package/dist/functions/up/index.js +3 -5
  35. package/dist/functions/voice/connections.d.ts +1 -1
  36. package/dist/functions/voice/lyrics.d.ts +9 -5
  37. package/dist/functions/voice/lyrics.js +148 -44
  38. package/dist/functions/voice/voice.d.ts +6 -2
  39. package/dist/functions/voice/voice.js +49 -17
  40. package/dist/functions/voice/voices.js +2 -1
  41. package/dist/functions/volta/index.js +1 -0
  42. package/dist/index.d.ts +97 -3
  43. package/dist/index.js +97 -3
  44. package/dist/jpfun.min.js +47 -60
  45. package/dist/layout/engine.d.ts +4 -3
  46. package/dist/layout/engine.js +160 -6
  47. package/dist/layout/model.d.ts +12 -3
  48. package/dist/layout/model.js +15 -7
  49. package/dist/layout/page.js +2 -2
  50. package/dist/layout/path.js +1 -1
  51. package/dist/layout/types.d.ts +10 -2
  52. package/dist/parser/grammarType.d.ts +3 -3
  53. package/dist/parser/parse-utils/brace-utils.js +7 -17
  54. package/dist/parser/parse-utils/call-utils.d.ts +3 -1
  55. package/dist/parser/parse-utils/call-utils.js +17 -32
  56. package/dist/parser/parse-utils/note-utils.d.ts +4 -0
  57. package/dist/parser/parse-utils/note-utils.js +8 -12
  58. package/dist/parser/parserContext.d.ts +8 -2
  59. package/dist/parser/parserContext.js +57 -55
  60. package/dist/parser/preprocess.d.ts +7 -0
  61. package/dist/parser/preprocess.js +21 -19
  62. package/dist/pipeline.d.ts +1 -1
  63. package/dist/playback/compile.js +1 -1
  64. package/dist/render/canvas.js +50 -35
  65. package/dist/render/index.d.ts +1 -1
  66. package/dist/render/index.js +1 -1
  67. package/dist/render/paint.d.ts +7 -0
  68. package/dist/render/paint.js +70 -20
  69. package/dist/render/recording.d.ts +8 -1
  70. package/dist/render/recording.js +12 -0
  71. package/dist/render/svg.d.ts +5 -1
  72. package/dist/render/svg.js +37 -17
  73. package/dist/render/text.d.ts +2 -2
  74. package/dist/render/text.js +7 -6
  75. package/dist/render/translate.d.ts +3 -1
  76. package/dist/render/translate.js +6 -0
  77. package/dist/render/types.d.ts +9 -0
  78. package/grammar.md +6 -5
  79. package/package.json +8 -18
  80. package/dist/converter/midi/convert.d.ts +0 -42
  81. package/dist/converter/midi/convert.js +0 -682
  82. package/dist/converter/midi/index.d.ts +0 -5
  83. package/dist/converter/midi/index.js +0 -11
  84. package/dist/converter/midi/json.d.ts +0 -38
  85. package/dist/converter/midi/json.js +0 -1
  86. package/dist/converter/midi/triplet.d.ts +0 -30
  87. package/dist/converter/midi/triplet.js +0 -75
  88. package/dist/converter/musicxml/dom.d.ts +0 -25
  89. package/dist/converter/musicxml/dom.js +0 -65
  90. package/dist/converter/musicxml/features.d.ts +0 -114
  91. package/dist/converter/musicxml/features.js +0 -501
  92. package/dist/converter/musicxml/index.d.ts +0 -14
  93. package/dist/converter/musicxml/index.js +0 -1285
  94. package/dist/converter/musicxml/model.d.ts +0 -176
  95. package/dist/converter/musicxml/model.js +0 -1
  96. package/dist/converter/musicxml/resolve.d.ts +0 -10
  97. package/dist/converter/musicxml/resolve.js +0 -152
  98. package/dist/converter/source.d.ts +0 -19
  99. package/dist/converter/source.js +0 -53
  100. package/dist/core.d.ts +0 -24
  101. package/dist/core.js +0 -24
  102. package/dist/jpfun.core.min.js +0 -132
  103. package/dist/jpfun.from-midi.min.js +0 -9
  104. package/dist/jpfun.from-musicxml.min.js +0 -12
@@ -1,13 +1,15 @@
1
1
  import { deSugarAtomFunction, deSugarRelationFunction, LengthValue, SourceSpan } from "./types.js";
2
2
  import { Diagnostic } from "../diagnostic.js";
3
- import { GrammarCallNode, GrammarNode, type SyntaxAnalysis } from "./grammarType.js";
3
+ import { GrammarCallNode, GrammarCallNodeRaw, GrammarNode, type SyntaxAnalysis } from "./grammarType.js";
4
4
  import { ASTFunctionClass, ASTFunctionNode, ASTNodeBase, paramType, paramValue } from "../functions/ASTtypes.js";
5
- export declare const DEFAULT_FONT_SIZE = 22;
5
+ export declare const DEFAULT_FONT_SIZE = 18;
6
+ export declare const DEFAULT_NUMBER_WEIGHT = 700;
6
7
  export declare class ParserContext {
7
8
  /** 系统变量,供 `@set` 读取 */
8
9
  static systemVariables: Record<string, {
9
10
  type: paramType;
10
11
  default: paramValue;
12
+ description: string;
11
13
  }>;
12
14
  /** 根解析器为 0,内容参数和大括号子解析器依次加一 */
13
15
  readonly scopeDepth: number;
@@ -31,6 +33,8 @@ export declare class ParserContext {
31
33
  deSugarRelationFns: deSugarRelationFunction[];
32
34
  /** .labelable() 返回的承载节点;null 是边界标记,标签绑定不能越过它 */
33
35
  labelableNodes: (ASTFunctionNode | null)[];
36
+ /** 当前正在实例化的显式函数调用节点,供构造函数按需读取原始参数区间 */
37
+ callNode?: GrammarCallNodeRaw;
34
38
  nodes: ASTNodeBase[];
35
39
  constructor(ctx: ParserContext | {
36
40
  source: string;
@@ -75,6 +79,8 @@ export declare class ParserContext {
75
79
  * 有副作用 会修改 nodes 和 labelableNodes 等上下文属性
76
80
  */
77
81
  makeNodes(nodes: (GrammarNode | number)[], i?: number, end?: number): number;
82
+ /** 追加文本,与紧邻的上一个文本节点合并;新建区间对象,避免改写语法节点的 span */
83
+ private pushText;
78
84
  /**
79
85
  * 识别核心语法: 大括号/函数调用/标签,其余尝试语法糖,失败的字符以索引的形式存在于返回值中,供第二轮识别终止符或合并为 TextNode
80
86
  * 即使是关系型的语法糖,这一阶段也要将依赖的字符提取为 GrammarSugarNode,供下一阶段处理
@@ -1,6 +1,7 @@
1
1
  import { Diagnostic } from "../diagnostic.js";
2
2
  import { DEFAULT_TEXT_FONT, JIANPU_NUMBER_FONT } from "../render/text.js";
3
- import { readCall, trimRange } from "./parse-utils/call-utils.js";
3
+ import { isNonLineWhitespace } from "./preprocess.js";
4
+ import { callArgName, readCall, trimRange } from "./parse-utils/call-utils.js";
4
5
  import { parseString } from "./parse-utils/string-utils.js";
5
6
  import { readBrace } from "./parse-utils/brace-utils.js";
6
7
  import { readLabel } from "./parse-utils/label-utils.js";
@@ -22,15 +23,37 @@ function classifySyntaxValue(type, text) {
22
23
  return "length";
23
24
  return undefined;
24
25
  }
25
- export const DEFAULT_FONT_SIZE = 22;
26
+ export const DEFAULT_FONT_SIZE = 18;
27
+ export const DEFAULT_NUMBER_WEIGHT = 700;
26
28
  // 解析上下文
27
29
  export class ParserContext {
28
30
  /** 系统变量,供 `@set` 读取 */
29
31
  static systemVariables = {
30
- fontsize: { type: "length", default: DEFAULT_FONT_SIZE },
31
- font: { type: "string", default: DEFAULT_TEXT_FONT },
32
- numberfont: { type: "string", default: JIANPU_NUMBER_FONT },
33
- strict: { type: "boolean", default: false },
32
+ fontsize: {
33
+ type: "length",
34
+ default: DEFAULT_FONT_SIZE,
35
+ description: "基准字号,也是 `em` 长度的换算基准"
36
+ },
37
+ font: {
38
+ type: "string",
39
+ default: DEFAULT_TEXT_FONT,
40
+ description: "普通文字字体"
41
+ },
42
+ numberfont: {
43
+ type: "string",
44
+ default: JIANPU_NUMBER_FONT,
45
+ description: "音符及同类谱面数字字体"
46
+ },
47
+ numberweight: {
48
+ type: "number",
49
+ default: DEFAULT_NUMBER_WEIGHT,
50
+ description: "主谱面数字字重,仅控制 `note`、`meter`、`rest`"
51
+ },
52
+ strict: {
53
+ type: "boolean",
54
+ default: false,
55
+ description: "开启严格的语法检查"
56
+ }
34
57
  };
35
58
  /** 根解析器为 0,内容参数和大括号子解析器依次加一 */
36
59
  scopeDepth;
@@ -54,6 +77,8 @@ export class ParserContext {
54
77
  deSugarRelationFns;
55
78
  /** .labelable() 返回的承载节点;null 是边界标记,标签绑定不能越过它 */
56
79
  labelableNodes;
80
+ /** 当前正在实例化的显式函数调用节点,供构造函数按需读取原始参数区间 */
81
+ callNode;
57
82
  nodes; // 解析结果
58
83
  constructor(ctx) {
59
84
  if (ctx instanceof ParserContext) {
@@ -200,7 +225,12 @@ export class ParserContext {
200
225
  return;
201
226
  }
202
227
  if (node.kind === "sugar" || node.typed) {
203
- this.addSyntax(node.syntaxKind ?? "operator", node.span);
228
+ if (Array.isArray(node.syntaxKind)) {
229
+ for (const token of node.syntaxKind)
230
+ this.addSyntax(token.kind, token.span);
231
+ }
232
+ else
233
+ this.addSyntax(node.syntaxKind ?? "operator", node.span);
204
234
  return;
205
235
  }
206
236
  // syntax.calls 只暴露源码结构,不带 grammar 阶段的字段
@@ -213,10 +243,7 @@ export class ParserContext {
213
243
  const arg = call.args[index];
214
244
  this.addSyntax("property", arg.nameSpan);
215
245
  this.addSyntax("punctuation", arg.equalsSpan);
216
- const name = arg.nameSpan
217
- ? this.source.slice(arg.nameSpan.start, arg.nameSpan.end).toLowerCase()
218
- : void 0;
219
- const type = def && resolveArgType(def, name, index);
246
+ const type = def && resolveArgType(def, callArgName(this.source, arg), index);
220
247
  if (type === "content") {
221
248
  new ParserContext(this).parseSyntax(arg.valueSpan.start, arg.valueSpan.end);
222
249
  }
@@ -291,13 +318,7 @@ export class ParserContext {
291
318
  outer: for (; i < end; i++) {
292
319
  const node = nodes[i];
293
320
  if (typeof node === "number") {
294
- // 合并多个连续文本为一个
295
- const prev = this.nodes.at(-1);
296
- if (prev instanceof ASTTextNode && prev.sourceSpan.end === node) {
297
- prev.sourceSpan.end = node + 1;
298
- }
299
- else
300
- this.nodes.push(new ASTTextNode({ start: node, end: node + 1 }, null));
321
+ this.pushText(node, node + 1);
301
322
  continue;
302
323
  }
303
324
  switch (node.kind) {
@@ -332,18 +353,20 @@ export class ParserContext {
332
353
  continue outer;
333
354
  }
334
355
  }
335
- // 匹配失败,保留为文本
336
- const prev = this.nodes.at(-1);
337
- if (prev instanceof ASTTextNode && prev.sourceSpan.end === node.span.start) {
338
- prev.sourceSpan.end = node.span.end;
339
- }
340
- else
341
- this.nodes.push(new ASTTextNode(node.span, null));
356
+ this.pushText(node.span.start, node.span.end); // 匹配失败,保留为文本
342
357
  break;
343
358
  }
344
359
  }
345
360
  return i;
346
361
  }
362
+ /** 追加文本,与紧邻的上一个文本节点合并;新建区间对象,避免改写语法节点的 span */
363
+ pushText(start, end) {
364
+ const prev = this.nodes.at(-1);
365
+ if (prev instanceof ASTTextNode && prev.sourceSpan.end === start)
366
+ prev.sourceSpan.end = end;
367
+ else
368
+ this.nodes.push(new ASTTextNode({ start, end }, null));
369
+ }
347
370
  /**
348
371
  * 识别核心语法: 大括号/函数调用/标签,其余尝试语法糖,失败的字符以索引的形式存在于返回值中,供第二轮识别终止符或合并为 TextNode
349
372
  * 即使是关系型的语法糖,这一阶段也要将依赖的字符提取为 GrammarSugarNode,供下一阶段处理
@@ -409,11 +432,8 @@ export class ParserContext {
409
432
  // 找到结尾
410
433
  let braceEnd = readBrace(this.source, p, end);
411
434
  // 大括号不匹配 报警 但继续解析 相当于补了一个右大括号
412
- if (braceEnd < 0 || braceEnd >= end || braceEnd <= p) {
413
- this.diagnostics.push(Diagnostic.warning.UnmatchedBrace({
414
- start: p,
415
- end: end
416
- }));
435
+ if (braceEnd < 0) {
436
+ this.diagnostics.push(Diagnostic.warning.UnmatchedBrace({ start: p, end }));
417
437
  braceEnd = end;
418
438
  }
419
439
  emit({
@@ -434,11 +454,8 @@ export class ParserContext {
434
454
  }
435
455
  }
436
456
  catch (e) {
437
- // 原子级去糖一般不出错。出错肯定是原则性问题
438
- if (e instanceof Diagnostic) {
439
- this.diagnostics.push(e);
440
- }
441
- else
457
+ // 原子级去糖一般不出错。Diagnostic 交给捕获方记录,避免内容参数恢复时重复
458
+ if (!(e instanceof Diagnostic))
442
459
  this.diagnostics.push(Diagnostic.error.Bug(e.toString(), { start: p, end }));
443
460
  throw e;
444
461
  }
@@ -466,9 +483,7 @@ export class ParserContext {
466
483
  const args = new Map();
467
484
  for (let i = 0; i < callNode.args.length; i++) {
468
485
  const arg = callNode.args[i];
469
- const name = arg.nameSpan
470
- ? this.source.slice(arg.nameSpan.start, arg.nameSpan.end).toLowerCase()
471
- : void 0;
486
+ const name = callArgName(this.source, arg);
472
487
  const type = resolveArgType(def, name, i);
473
488
  const key = name ?? i;
474
489
  if (type === void 0) {
@@ -483,8 +498,10 @@ export class ParserContext {
483
498
  if (value !== null)
484
499
  args.set(key, value);
485
500
  }
501
+ this.callNode = callNode;
486
502
  return new callFNClass(callNode.span, args, this, null);
487
503
  } // 完全信任 typed 时的 arg
504
+ this.callNode = undefined;
488
505
  // 构造函数内用定义查询实际传参
489
506
  return new callFNClass(callNode.span, callNode.args, this, null);
490
507
  }
@@ -593,28 +610,13 @@ export class ParserContext {
593
610
  }
594
611
  // 换行转义已经在预处理解决了,这里不用再跳过了
595
612
  export function skipSpaces(s, i, end) {
596
- while (i < end && isWhitespaceButNotNewline(s[i]))
613
+ while (i < end && isNonLineWhitespace(s.charCodeAt(i)))
597
614
  i++;
598
615
  return i;
599
616
  }
600
617
  /** 反向跳过非换行空白,越界返回 -1 */
601
618
  export function skipSpacesBack(s, i, start = 0) {
602
- while (i >= start && isWhitespaceButNotNewline(s[i]))
619
+ while (i >= start && isNonLineWhitespace(s.charCodeAt(i)))
603
620
  i--;
604
621
  return i;
605
622
  }
606
- function isWhitespaceButNotNewline(ch) {
607
- switch (ch) {
608
- case ' ':
609
- case '\t':
610
- case '\v': // 垂直制表符
611
- case '\f': // 换页符
612
- case '\u00A0': // 不间断空格
613
- case '\uFEFF': // 零宽不连字空格
614
- case '\u3000': // 中文全角空格
615
- return true;
616
- default:
617
- return false;
618
- // \n 和 \r 不算
619
- }
620
- }
@@ -1,4 +1,11 @@
1
1
  import type { SourceSpan } from "./types.js";
2
+ /**
3
+ * 判断非换行空白(对齐 ECMAScript `\s` 中除 `\r`/`\n`/`\u2028`/`\u2029` 外的全部空白字符):
4
+ * - ASCII 空白:`' '` (32)、`'\t'` (9)、`'\v'` (11)、`'\f'` (12)
5
+ * - Unicode 空白:`'\u00A0'` 不间断空格、`'\u1680'` 欧甘空格、`'\u2000'`..`'\u200A'` (8192..8202) 排版空格族、
6
+ * `'\u202F'` 窄不间断空格、`'\u205F'` 中等数学空格、`'\u3000'` 中文全角空格、`'\uFEFF'` BOM
7
+ */
8
+ export declare function isNonLineWhitespace(ch: number): boolean;
2
9
  export declare function preprocessSource(source: string): {
3
10
  maskedSource: string;
4
11
  lineStarts: number[];
@@ -9,21 +9,21 @@ import { findClosingQuote } from "./parse-utils/string-utils.js";
9
9
  * - 若 n 为奇数,则该行换行符也替换为空格(续行)
10
10
  * 4. 字符串外 CRLF 中的 CR 等长替换为空格,词法层只消费 LF
11
11
  */
12
- const CHAR_LF = 10;
13
- const CHAR_CR = 13;
14
- const CHAR_TAB = 9;
15
- const CHAR_VTAB = 11;
16
- const CHAR_FF = 12;
17
- const CHAR_SPACE = 32;
18
- const CHAR_NBSP = 160;
19
- const CHAR_OGHAM_SPACE_MARK = 5760;
20
- const CHAR_NARROW_NO_BREAK_SPACE = 8239;
21
- const CHAR_MEDIUM_MATHEMATICAL_SPACE = 8287;
22
- const CHAR_IDEOGRAPHIC_SPACE = 12288;
23
- const CHAR_BOM = 65279;
24
- const CHAR_QUOTE_DOUBLE = 34;
25
- const CHAR_BACKSLASH = 92;
26
- const CHAR_PERCENT = 37;
12
+ const CHAR_LF = 10; // \n 换行
13
+ const CHAR_CR = 13; // \r 回车
14
+ const CHAR_TAB = 9; // \t 水平制表符
15
+ const CHAR_VTAB = 11; // \v 垂直制表符
16
+ const CHAR_FF = 12; // \f 换页符
17
+ const CHAR_SPACE = 32; // ' ' 普通空格
18
+ const CHAR_NBSP = 160; // \u00A0 不间断空格
19
+ const CHAR_OGHAM_SPACE_MARK = 5760; // \u1680 欧甘空格
20
+ const CHAR_NARROW_NO_BREAK_SPACE = 8239; // \u202F 窄不间断空格
21
+ const CHAR_MEDIUM_MATHEMATICAL_SPACE = 8287; // \u205F 中等数学空格
22
+ const CHAR_IDEOGRAPHIC_SPACE = 12288; // \u3000 中文全角空格
23
+ const CHAR_BOM = 65279; // \uFEFF 零宽不连字空格 (BOM)
24
+ const CHAR_QUOTE_DOUBLE = 34; // '"'
25
+ const CHAR_BACKSLASH = 92; // '\\'
26
+ const CHAR_PERCENT = 37; // '%'
27
27
  // 掩码几乎都是短注释和续行反斜杠,长的既少重复又要一直占着内存,所以只缓存短的
28
28
  const MAX_CACHED_SPACES = 32;
29
29
  const SHORT_SPACES = [];
@@ -33,10 +33,12 @@ function getSpaces(length) {
33
33
  return SHORT_SPACES[length] ??= " ".repeat(length);
34
34
  }
35
35
  /**
36
- * 判断 非换行空白
37
- * 说明:CR/LF 由主循环单独处理,这里只负责可被“行尾回看”忽略的空白
36
+ * 判断非换行空白(对齐 ECMAScript `\s` 中除 `\r`/`\n`/`\u2028`/`\u2029` 外的全部空白字符):
37
+ * - ASCII 空白:`' '` (32)、`'\t'` (9)、`'\v'` (11)、`'\f'` (12)
38
+ * - Unicode 空白:`'\u00A0'` 不间断空格、`'\u1680'` 欧甘空格、`'\u2000'`..`'\u200A'` (8192..8202) 排版空格族、
39
+ * `'\u202F'` 窄不间断空格、`'\u205F'` 中等数学空格、`'\u3000'` 中文全角空格、`'\uFEFF'` BOM
38
40
  */
39
- function isNonLineWhitespace(ch) {
41
+ export function isNonLineWhitespace(ch) {
40
42
  // 热路径优先处理 ASCII
41
43
  if (ch === CHAR_SPACE || ch === CHAR_TAB || ch === CHAR_VTAB || ch === CHAR_FF)
42
44
  return true;
@@ -44,7 +46,7 @@ function isNonLineWhitespace(ch) {
44
46
  return false;
45
47
  return (ch === CHAR_NBSP ||
46
48
  ch === CHAR_OGHAM_SPACE_MARK ||
47
- (ch >= 8192 && ch <= 8202) ||
49
+ (ch >= 8192 && ch <= 8202) || // \u2000..\u200A:En/Em Quad、En/Em/Three-Per-Em/Four-Per-Em/Six-Per-Em/Figure/Punctuation/Thin/Hair Space
48
50
  ch === CHAR_NARROW_NO_BREAK_SPACE ||
49
51
  ch === CHAR_MEDIUM_MATHEMATICAL_SPACE ||
50
52
  ch === CHAR_IDEOGRAPHIC_SPACE ||
@@ -32,6 +32,6 @@ export declare function compileScore(source: string, options?: CompileScoreOptio
32
32
  * 该入口会把这些问题记录到 diagnostics,并尽量返回已经识别的 call/token,供高亮和补全继续工作
33
33
  */
34
34
  export declare function analyzeScoreSyntax(source: string, functions?: ASTFunctionClass[]): {
35
- syntax: import("./core.js").SyntaxAnalysis;
35
+ syntax: import("./index.js").SyntaxAnalysis;
36
36
  diagnostics: Diagnostic[];
37
37
  };
@@ -8,7 +8,7 @@ import { isPlaybackRelation } from "./types.js";
8
8
  * 按控制流声明展开出实际访问的列顺序
9
9
  *
10
10
  * 核心只维护游标、到达次数和标记表,跳转规则全部由函数在自己的 `playbackFlow` 里写:
11
- * 反复线找最近的段起点标记,房子按段起点被访问过几次决定本遍演不演。
11
+ * 反复线找最近的段起点标记,房子按本段已回跳过几次决定本遍演不演。
12
12
  * 本阶段只产生列索引;游标计数和标记索引每次编译重新建立,不会回写 lowering。
13
13
  */
14
14
  function linearizeColumns(lowering, diagnostics, maxFlowSteps) {
@@ -3,27 +3,31 @@ import { canvasFont } from "./text.js";
3
3
  function tracePath(context, commands, x = 0, y = 0, scaleX = 1, scaleY = 1) {
4
4
  context.beginPath();
5
5
  for (const command of commands) {
6
- if (command.op === "Z") {
7
- context.closePath();
8
- continue;
6
+ switch (command.op) {
7
+ case "M":
8
+ context.moveTo(x + command.x * scaleX, y + command.y * scaleY);
9
+ break;
10
+ case "L":
11
+ context.lineTo(x + command.x * scaleX, y + command.y * scaleY);
12
+ break;
13
+ case "Q":
14
+ context.quadraticCurveTo(x + command.cx * scaleX, y + command.cy * scaleY, x + command.x * scaleX, y + command.y * scaleY);
15
+ break;
16
+ case "C":
17
+ context.bezierCurveTo(x + command.cx1 * scaleX, y + command.cy1 * scaleY, x + command.cx2 * scaleX, y + command.cy2 * scaleY, x + command.x * scaleX, y + command.y * scaleY);
18
+ break;
19
+ case "Z":
20
+ context.closePath();
21
+ break;
22
+ default:
23
+ command;
9
24
  }
10
- if (command.op === "M") {
11
- context.moveTo(x + command.x * scaleX, y + command.y * scaleY);
12
- continue;
13
- }
14
- if (command.op === "L") {
15
- context.lineTo(x + command.x * scaleX, y + command.y * scaleY);
16
- continue;
17
- }
18
- if (command.op === "Q") {
19
- context.quadraticCurveTo(x + command.cx * scaleX, y + command.cy * scaleY, x + command.x * scaleX, y + command.y * scaleY);
20
- continue;
21
- }
22
- if (!("cx1" in command))
23
- continue;
24
- context.bezierCurveTo(x + command.cx1 * scaleX, y + command.cy1 * scaleY, x + command.cx2 * scaleX, y + command.cy2 * scaleY, x + command.x * scaleX, y + command.y * scaleY);
25
25
  }
26
26
  }
27
+ /** Canvas 会忽略 "none" 这类非法颜色并沿用上一次的样式,因此按“不绘制”处理 */
28
+ function paint(color) {
29
+ return color === "none" ? undefined : color;
30
+ }
27
31
  /**
28
32
  * CanvasRenderingContext2D 的 Painter 适配器
29
33
  *
@@ -36,17 +40,23 @@ export class CanvasPainter {
36
40
  this.context = context;
37
41
  }
38
42
  drawText(text, x, y, style) {
39
- this.context.fillStyle = style.fill ?? "#000";
43
+ const fill = paint(style.fill ?? "#000");
44
+ if (!fill)
45
+ return;
46
+ this.context.fillStyle = fill;
40
47
  this.context.font = canvasFont(style);
41
48
  this.context.textAlign = style.textAlign ?? "left";
42
49
  this.context.textBaseline = "alphabetic";
43
50
  this.context.fillText(text, x, y);
44
51
  }
45
52
  drawLine(x1, y1, x2, y2, style) {
53
+ const stroke = paint(style?.stroke ?? style?.fill ?? "#000");
54
+ if (!stroke)
55
+ return;
46
56
  this.context.beginPath();
47
57
  this.context.moveTo(x1, y1);
48
58
  this.context.lineTo(x2, y2);
49
- this.context.strokeStyle = style?.stroke ?? style?.fill ?? "#000";
59
+ this.context.strokeStyle = stroke;
50
60
  this.context.lineWidth = style?.strokeWidth ?? 1;
51
61
  this.context.lineCap = "round";
52
62
  this.context.stroke();
@@ -54,13 +64,15 @@ export class CanvasPainter {
54
64
  drawRect(x, y, w, h, style) {
55
65
  if (w < 0 || h < 0)
56
66
  return;
57
- if (style?.fill) {
58
- this.context.fillStyle = style.fill;
67
+ const fill = paint(style?.fill);
68
+ if (fill) {
69
+ this.context.fillStyle = fill;
59
70
  this.context.fillRect(x, y, w, h);
60
71
  }
61
- if (style?.stroke) {
62
- this.context.strokeStyle = style.stroke;
63
- this.context.lineWidth = style.strokeWidth ?? 1;
72
+ const stroke = paint(style?.stroke);
73
+ if (stroke) {
74
+ this.context.strokeStyle = stroke;
75
+ this.context.lineWidth = style?.strokeWidth ?? 1;
64
76
  this.context.lineJoin = "miter";
65
77
  this.context.strokeRect(x, y, w, h);
66
78
  }
@@ -70,14 +82,15 @@ export class CanvasPainter {
70
82
  return;
71
83
  this.context.beginPath();
72
84
  this.context.arc(cx, cy, r, 0, Math.PI * 2);
73
- const fill = style?.fill ?? "#000";
74
- if (fill && fill !== "none") {
85
+ const fill = paint(style?.fill ?? "#000");
86
+ if (fill) {
75
87
  this.context.fillStyle = fill;
76
88
  this.context.fill();
77
89
  }
78
- if (style?.stroke) {
79
- this.context.strokeStyle = style.stroke;
80
- this.context.lineWidth = style.strokeWidth ?? 1;
90
+ const stroke = paint(style?.stroke);
91
+ if (stroke) {
92
+ this.context.strokeStyle = stroke;
93
+ this.context.lineWidth = style?.strokeWidth ?? 1;
81
94
  this.context.stroke();
82
95
  }
83
96
  }
@@ -85,13 +98,15 @@ export class CanvasPainter {
85
98
  if (commands.length === 0)
86
99
  return;
87
100
  tracePath(this.context, commands, transform?.x, transform?.y, transform?.scaleX, transform?.scaleY);
88
- if (style?.fill) {
89
- this.context.fillStyle = style.fill;
101
+ const fill = paint(style?.fill);
102
+ if (fill) {
103
+ this.context.fillStyle = fill;
90
104
  this.context.fill();
91
105
  }
92
- if (style?.stroke) {
93
- this.context.strokeStyle = style.stroke;
94
- this.context.lineWidth = style.strokeWidth ?? 1;
106
+ const stroke = paint(style?.stroke);
107
+ if (stroke) {
108
+ this.context.strokeStyle = stroke;
109
+ this.context.lineWidth = style?.strokeWidth ?? 1;
95
110
  this.context.lineCap = "round";
96
111
  this.context.lineJoin = "round";
97
112
  this.context.stroke();
@@ -1,5 +1,5 @@
1
1
  export * from "./types.js";
2
- export { layoutPageBounds, paintLayout, paintLayoutPages } from "./paint.js";
2
+ export { layoutPageBounds, paintLayout, paintLayoutPages, paintVisual } from "./paint.js";
3
3
  export * from "./text.js";
4
4
  export * from "./recording.js";
5
5
  export * from "./svg.js";
@@ -1,5 +1,5 @@
1
1
  export * from "./types.js";
2
- export { layoutPageBounds, paintLayout, paintLayoutPages } from "./paint.js";
2
+ export { layoutPageBounds, paintLayout, paintLayoutPages, paintVisual } from "./paint.js";
3
3
  export * from "./text.js";
4
4
  export * from "./recording.js";
5
5
  export * from "./svg.js";
@@ -1,7 +1,14 @@
1
1
  import type { DocumentLayoutResult } from "../layout/engine.js";
2
2
  import type { Rect } from "../layout/types.js";
3
+ import type { VisualTemporalNode } from "../functions/temporal.js";
3
4
  import type { Painter } from "./types.js";
4
5
  export declare function layoutPageBounds(result: DocumentLayoutResult): readonly Rect[];
6
+ /**
7
+ * 绘制一个可见时值对象:主体后接装饰,整体放进 node.kind 分组
8
+ *
9
+ * up、grace、arpeggio 等容器绘制成员时也应调用它,成员的组因此嵌套在容器组内
10
+ */
11
+ export declare function paintVisual(painter: Painter, node: VisualTemporalNode): void;
5
12
  /** 按固定层级把布局结果绘制到一个 Painter */
6
13
  export declare function paintLayout(result: DocumentLayoutResult, painter: Painter): void;
7
14
  /** 用一个代理 Painter 把一次完整绘制分发到多个页面 Painter */
@@ -3,29 +3,68 @@ export function layoutPageBounds(result) {
3
3
  ? result.pages.map(page => page.bounds)
4
4
  : [result.bounds];
5
5
  }
6
+ /**
7
+ * 绘制一个可见时值对象:主体后接装饰,整体放进 node.kind 分组
8
+ *
9
+ * up、grace、arpeggio 等容器绘制成员时也应调用它,成员的组因此嵌套在容器组内
10
+ */
11
+ export function paintVisual(painter, node) {
12
+ const kind = node.kind;
13
+ if (kind)
14
+ painter.beginGroup?.({ kind });
15
+ node.paint(painter);
16
+ for (const decoration of node.decorations)
17
+ decoration.paint?.(painter);
18
+ if (kind)
19
+ painter.endGroup?.();
20
+ }
21
+ function paintAttachments(painter, attachments, layer) {
22
+ for (const attachment of attachments) {
23
+ if (attachment.layer !== layer)
24
+ continue;
25
+ const kind = attachment.kind;
26
+ if (kind)
27
+ painter.beginGroup?.({ kind });
28
+ attachment.paint(painter);
29
+ if (kind)
30
+ painter.endGroup?.();
31
+ }
32
+ }
6
33
  /** 按固定层级把布局结果绘制到一个 Painter */
7
34
  export function paintLayout(result, painter) {
8
- for (const attachment of result.attachments) {
9
- if (attachment.layer === "background")
10
- attachment.paint(painter);
11
- }
12
- for (const node of result.objects) {
13
- node.paint(painter);
14
- for (const decoration of node.decorations)
15
- decoration.paint?.(painter);
16
- }
17
- for (const attachment of result.attachments) {
18
- if (attachment.layer === "foreground")
19
- attachment.paint(painter);
20
- }
35
+ paintAttachments(painter, result.attachments, "background");
36
+ for (const node of result.objects)
37
+ paintVisual(painter, node);
38
+ paintAttachments(painter, result.attachments, "foreground");
21
39
  }
22
40
  class PagePainter {
23
41
  pages;
24
42
  painters;
43
+ /** 当前打开的分组,由外到内 */
44
+ groups = [];
45
+ /** 页下标 → 该页已补开的层数;只记录有未结束分组的页,没有图元的页不开组 */
46
+ opened = new Map();
25
47
  constructor(pages, painters) {
26
48
  this.pages = pages;
27
49
  this.painters = painters;
28
50
  }
51
+ beginGroup(group) {
52
+ this.groups.push(group);
53
+ }
54
+ endGroup() {
55
+ const depth = this.groups.length;
56
+ this.groups.pop();
57
+ // 各页层数不超过 depth,等于 depth 的页才打开过这一组
58
+ for (const [index, opened] of this.opened) {
59
+ if (opened < depth)
60
+ continue;
61
+ this.painters[index].endGroup?.();
62
+ if (depth > 1)
63
+ this.opened.set(index, depth - 1);
64
+ else
65
+ this.opened.delete(index);
66
+ }
67
+ }
29
68
  route(top, bottom, paint) {
30
69
  let low = 0;
31
70
  let high = this.pages.length;
@@ -37,8 +76,16 @@ class PagePainter {
37
76
  else
38
77
  high = middle;
39
78
  }
79
+ const depth = this.groups.length;
40
80
  for (let index = low; index < this.pages.length && this.pages[index].y <= bottom; index++) {
41
- paint(this.painters[index]);
81
+ const painter = this.painters[index];
82
+ const opened = this.opened.get(index) ?? 0;
83
+ if (opened < depth) {
84
+ for (let level = opened; level < depth; level++)
85
+ painter.beginGroup?.(this.groups[level]);
86
+ this.opened.set(index, depth);
87
+ }
88
+ paint(painter);
42
89
  }
43
90
  }
44
91
  drawText(text, x, y, style) {
@@ -62,15 +109,11 @@ class PagePainter {
62
109
  drawPath(commands, style, transform) {
63
110
  if (commands.length === 0)
64
111
  return;
65
- const y = transform
66
- ? (value) => transform.y + value * transform.scaleY
67
- : (value) => value;
68
112
  let top = Infinity;
69
113
  let bottom = -Infinity;
70
114
  const include = (value) => {
71
- const transformed = y(value);
72
- top = Math.min(top, transformed);
73
- bottom = Math.max(bottom, transformed);
115
+ top = Math.min(top, value);
116
+ bottom = Math.max(bottom, value);
74
117
  };
75
118
  for (const command of commands) {
76
119
  if (command.op === "Z")
@@ -83,6 +126,13 @@ class PagePainter {
83
126
  }
84
127
  include(command.y);
85
128
  }
129
+ if (transform) {
130
+ // 仿射变换单调,变换端点即可;scaleY 为负时上下互换
131
+ const a = transform.y + top * transform.scaleY;
132
+ const b = transform.y + bottom * transform.scaleY;
133
+ top = Math.min(a, b);
134
+ bottom = Math.max(a, b);
135
+ }
86
136
  if (!Number.isFinite(top))
87
137
  return;
88
138
  const halfStroke = style?.stroke ? (style.strokeWidth ?? 1) / 2 : 0;
@@ -1,4 +1,4 @@
1
- import type { PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
1
+ import type { PaintGroup, PaintStyle, Painter, PathCommand, PathTransform, TextStyle } from "./types.js";
2
2
  export type RecordedPaintCommand = {
3
3
  kind: "text";
4
4
  text: string;
@@ -29,6 +29,11 @@ export type RecordedPaintCommand = {
29
29
  kind: "path";
30
30
  commands: PathCommand[];
31
31
  style?: PaintStyle;
32
+ } | {
33
+ kind: "begin-group";
34
+ group: PaintGroup;
35
+ } | {
36
+ kind: "end-group";
32
37
  };
33
38
  /**
34
39
  * 记录通用绘制命令而不产生图像
@@ -39,6 +44,8 @@ export type RecordedPaintCommand = {
39
44
  export declare class RecordingPainter implements Painter {
40
45
  commands: RecordedPaintCommand[];
41
46
  replay(painter: Painter): void;
47
+ beginGroup(group: PaintGroup): void;
48
+ endGroup(): void;
42
49
  drawText(text: string, x: number, y: number, style: TextStyle): void;
43
50
  drawLine(x1: number, y1: number, x2: number, y2: number, style?: PaintStyle): void;
44
51
  drawRect(x: number, y: number, w: number, h: number, style?: PaintStyle): void;