All files / jianpu-renderer/core/parser BarlineParser.ts

0% Statements 0/458
0% Branches 0/1
0% Functions 0/1
0% Lines 0/458

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     
/**
 * MusicXML Barline解析器
 * 
 * @description 根据W3C MusicXML 4.0规范解析小节线信息
 * @see https://www.w3.org/2021/06/musicxml40/musicxml-reference/elements/barline/
 * 
 * 支持的bar-style值:
 * - regular: 普通单线(默认)
 * - dotted: 点线
 * - dashed: 虚线
 * - heavy: 粗线
 * - light-light: 双细线
 * - light-heavy: 终止线(左细右粗)
 * - heavy-light: 开始线(左粗右细)
 * - heavy-heavy: 双粗线
 * - tick: 短刻度
 * - short: 短线
 * - none: 无线
 * 
 * 支持的repeat direction:
 * - forward: 向前反复(反复开始)
 * - backward: 向后反复(反复结束)
 */

// ==================== 类型定义 ====================

/**
 * MusicXML bar-style 枚举
 * 对应 MusicXML 4.0 规范中的 bar-style 数据类型
 */
export type MusicXMLBarStyle = 
  | 'regular'      // 普通单线
  | 'dotted'       // 点线
  | 'dashed'       // 虚线
  | 'heavy'        // 粗线
  | 'light-light'  // 双细线
  | 'light-heavy'  // 终止线(左细右粗)
  | 'heavy-light'  // 开始线(左粗右细)
  | 'heavy-heavy'  // 双粗线
  | 'tick'         // 短刻度(仅顶部)
  | 'short'        // 短线
  | 'none';        // 无线

/**
 * MusicXML repeat direction 枚举
 */
export type RepeatDirection = 'forward' | 'backward';

/**
 * MusicXML barline location 枚举
 */
export type BarlineLocation = 'left' | 'middle' | 'right';

/**
 * MusicXML ending type 枚举(跳房子/反复括号)
 */
export type EndingType = 'start' | 'stop' | 'discontinue';

/**
 * 完整的Barline类型(用于渲染)
 * 结合了bar-style和repeat信息
 */
export type BarlineType = 
  | 'none'           // 无小节线
  | 'single'         // 单细线(regular/light)
  | 'double'         // 双细线(light-light)
  | 'final'          // 终止线(light-heavy,无反复)
  | 'heavy'          // 单粗线
  | 'heavy-heavy'    // 双粗线
  | 'dotted'         // 点线
  | 'dashed'         // 虚线
  | 'tick'           // 短刻度
  | 'short'          // 短线
  | 'repeat-start'   // 反复开始(heavy-light + forward repeat)
  | 'repeat-end'     // 反复结束(light-heavy + backward repeat,无终止样式)
  | 'repeat-end-final' // 反复结束+终止(light-heavy + backward repeat)
  | 'repeat-both';   // 双向反复(backward + forward)

/**
 * Repeat信息
 */
export interface RepeatInfo {
  /** 反复方向 */
  direction: RepeatDirection;
  /** 反复次数(可选) */
  times?: number;
  /** 跳转后是否反复 */
  afterJump?: boolean;
  /** 翅膀样式 */
  winged?: 'none' | 'straight' | 'curved' | 'double-straight' | 'double-curved';
}

/**
 * Ending信息(跳房子/反复括号)
 */
export interface EndingInfo {
  /** 类型:开始、结束或断开 */
  type: EndingType;
  /** 房子编号(如 "1" 或 "1, 2") */
  number: string;
  /** 显示文本(可选,如 "1." 或 "2.") */
  text?: string;
}

/**
 * 完整的Barline解析结果
 */
export interface BarlineData {
  /** 位置:左侧、中间或右侧 */
  location: BarlineLocation;
  /** 小节线样式 */
  barStyle: MusicXMLBarStyle;
  /** 映射后的渲染类型 */
  barlineType: BarlineType;
  /** 反复信息(可选) */
  repeat?: RepeatInfo;
  /** 跳房子信息(可选) */
  ending?: EndingInfo;
  /** 是否有segno记号 */
  hasSegno?: boolean;
  /** 是否有coda记号 */
  hasCoda?: boolean;
  /** 是否有fermata(延音记号) */
  hasFermata?: boolean;
}

/**
 * 小节的完整barline信息(包含左右两侧)
 */
export interface MeasureBarlineInfo {
  /** 左侧小节线 */
  left?: BarlineData;
  /** 右侧小节线 */
  right?: BarlineData;
  /** 中间小节线(复杂拍子时可能存在) */
  middle?: BarlineData;
  /** 最终渲染类型(综合左右侧信息) */
  barlineType: BarlineType;
  /** 是否有反复开始 */
  hasRepeatStart: boolean;
  /** 是否有反复结束 */
  hasRepeatEnd: boolean;
  /** 跳房子信息 */
  ending?: EndingInfo;
}

// ==================== 主类 ====================

/**
 * Barline解析器
 * 
 * 直接从MusicXML DOM解析barline信息,不依赖OSMD
 */
export class BarlineParser {
  /**
   * 解析单个小节的barline信息
   * 
   * @param measureElement MusicXML measure元素
   * @returns 解析后的barline信息
   */
  parseMeasureBarlines(measureElement: Element): MeasureBarlineInfo {
    const leftBarline = measureElement.querySelector('barline[location="left"]');
    const rightBarline = measureElement.querySelector('barline[location="right"]');
    const middleBarline = measureElement.querySelector('barline[location="middle"]');
    
    const result: MeasureBarlineInfo = {
      barlineType: 'single',
      hasRepeatStart: false,
      hasRepeatEnd: false,
    };
    
    // 解析左侧barline
    if (leftBarline) {
      result.left = this.parseBarlineElement(leftBarline, 'left');
      if (result.left.repeat?.direction === 'forward') {
        result.hasRepeatStart = true;
      }
      if (result.left.ending) {
        result.ending = result.left.ending;
      }
    }
    
    // 解析右侧barline
    if (rightBarline) {
      result.right = this.parseBarlineElement(rightBarline, 'right');
      if (result.right.repeat?.direction === 'backward') {
        result.hasRepeatEnd = true;
      }
      if (result.right.ending && !result.ending) {
        result.ending = result.right.ending;
      }
    }
    
    // 解析中间barline(较少见)
    if (middleBarline) {
      result.middle = this.parseBarlineElement(middleBarline, 'middle');
    }
    
    // 计算最终的barlineType
    result.barlineType = this.calculateFinalBarlineType(result);
    
    return result;
  }
  
  /**
   * 解析单个barline元素
   * 
   * @param barlineElement barline DOM元素
   * @param defaultLocation 默认位置
   * @returns 解析后的barline数据
   */
  parseBarlineElement(barlineElement: Element, defaultLocation: BarlineLocation = 'right'): BarlineData {
    // 获取位置
    const location = (barlineElement.getAttribute('location') as BarlineLocation) || defaultLocation;
    
    // 解析bar-style
    const barStyleEl = barlineElement.querySelector('bar-style');
    const barStyle = this.parseBarStyle(barStyleEl?.textContent);
    
    // 解析repeat
    const repeatEl = barlineElement.querySelector('repeat');
    const repeat = repeatEl ? this.parseRepeat(repeatEl) : undefined;
    
    // 解析ending
    const endingEl = barlineElement.querySelector('ending');
    const ending = endingEl ? this.parseEnding(endingEl) : undefined;
    
    // 检查其他记号
    const hasSegno = !!barlineElement.querySelector('segno');
    const hasCoda = !!barlineElement.querySelector('coda');
    const hasFermata = !!barlineElement.querySelector('fermata');
    
    // 计算渲染类型
    const barlineType = this.mapToBarlineType(barStyle, repeat, location);
    
    return {
      location,
      barStyle,
      barlineType,
      repeat,
      ending,
      hasSegno,
      hasCoda,
      hasFermata,
    };
  }
  
  /**
   * 解析bar-style文本
   * 
   * @param text bar-style文本内容
   * @returns MusicXML bar-style枚举值
   */
  private parseBarStyle(text: string | null | undefined): MusicXMLBarStyle {
    if (!text) return 'regular';
    
    const normalized = text.trim().toLowerCase();
    
    // 验证是否为有效的bar-style值
    const validStyles: MusicXMLBarStyle[] = [
      'regular', 'dotted', 'dashed', 'heavy',
      'light-light', 'light-heavy', 'heavy-light', 'heavy-heavy',
      'tick', 'short', 'none'
    ];
    
    // 处理一些常见的别名
    if (normalized === 'light') {
      return 'regular'; // light等同于regular
    }
    
    if (validStyles.includes(normalized as MusicXMLBarStyle)) {
      return normalized as MusicXMLBarStyle;
    }
    
    // 默认返回regular
    return 'regular';
  }
  
  /**
   * 解析repeat元素
   * 
   * @param repeatElement repeat DOM元素
   * @returns RepeatInfo
   */
  private parseRepeat(repeatElement: Element): RepeatInfo {
    const direction = (repeatElement.getAttribute('direction') as RepeatDirection) || 'backward';
    const timesAttr = repeatElement.getAttribute('times');
    const afterJumpAttr = repeatElement.getAttribute('after-jump');
    const wingedAttr = repeatElement.getAttribute('winged');
    
    return {
      direction,
      times: timesAttr ? parseInt(timesAttr, 10) : undefined,
      afterJump: afterJumpAttr === 'yes',
      winged: wingedAttr as RepeatInfo['winged'],
    };
  }
  
  /**
   * 解析ending元素(跳房子)
   * 
   * @param endingElement ending DOM元素
   * @returns EndingInfo
   */
  private parseEnding(endingElement: Element): EndingInfo {
    const type = (endingElement.getAttribute('type') as EndingType) || 'start';
    const number = endingElement.getAttribute('number') || '1';
    const text = endingElement.textContent?.trim() || undefined;
    
    return {
      type,
      number,
      text,
    };
  }
  
  /**
   * 将bar-style和repeat信息映射到渲染用的BarlineType
   * 
   * @param barStyle MusicXML bar-style
   * @param repeat 反复信息
   * @param location 位置
   * @returns 渲染用的BarlineType
   */
  private mapToBarlineType(
    barStyle: MusicXMLBarStyle,
    repeat?: RepeatInfo,
    location?: BarlineLocation
  ): BarlineType {
    // 如果是none,直接返回
    if (barStyle === 'none') {
      return 'none';
    }
    
    // 处理反复记号
    if (repeat) {
      if (repeat.direction === 'forward') {
        return 'repeat-start';
      }
      if (repeat.direction === 'backward') {
        // 如果是终止线样式的反复结束
        if (barStyle === 'light-heavy') {
          return 'repeat-end-final';
        }
        return 'repeat-end';
      }
    }
    
    // 根据bar-style映射
    switch (barStyle) {
      case 'regular':
        return 'single';
      case 'light-light':
        return 'double';
      case 'light-heavy':
        return 'final';
      case 'heavy-light':
        // 没有repeat但是heavy-light样式,当作反复开始
        return 'repeat-start';
      case 'heavy':
        return 'heavy';
      case 'heavy-heavy':
        return 'heavy-heavy';
      case 'dotted':
        return 'dotted';
      case 'dashed':
        return 'dashed';
      case 'tick':
        return 'tick';
      case 'short':
        return 'short';
      case 'none':
        return 'none';
      default:
        return 'single';
    }
  }
  
  /**
   * 根据左右侧barline信息计算最终的barlineType
   * 
   * @param info 小节barline信息
   * @returns 最终的BarlineType
   */
  private calculateFinalBarlineType(info: MeasureBarlineInfo): BarlineType {
    // 优先使用右侧barline的类型(这是最常见的情况)
    if (info.right) {
      // 如果同时有反复开始和结束(右侧backward,左侧forward在下一小节)
      // 这种情况在实际渲染时需要特殊处理
      return info.right.barlineType;
    }
    
    // 如果只有左侧barline
    if (info.left) {
      return info.left.barlineType;
    }
    
    // 如果只有中间barline
    if (info.middle) {
      return info.middle.barlineType;
    }
    
    // 默认为单线
    return 'single';
  }
  
  /**
   * 从完整的MusicXML文档解析所有小节的barline信息
   * 
   * @param xmlDocument MusicXML文档
   * @returns 小节索引到barline信息的映射
   */
  parseAllBarlines(xmlDocument: Document): Map<number, MeasureBarlineInfo> {
    const result = new Map<number, MeasureBarlineInfo>();
    
    // 获取所有小节(支持partwise和timewise格式)
    const measureElements = xmlDocument.querySelectorAll('measure');
    
    measureElements.forEach((measureEl, index) => {
      // 获取小节号(如果有)
      const measureNumberAttr = measureEl.getAttribute('number');
      const measureNumber = measureNumberAttr ? parseInt(measureNumberAttr, 10) : index + 1;
      
      // 解析barline信息
      const barlineInfo = this.parseMeasureBarlines(measureEl);
      
      // 使用小节号作为key(减1转为索引)
      result.set(measureNumber - 1, barlineInfo);
    });
    
    return result;
  }
  
  /**
   * 便捷方法:从XML字符串解析barline信息
   * 
   * @param xmlString MusicXML字符串
   * @returns 小节索引到barline信息的映射
   */
  parseFromXMLString(xmlString: string): Map<number, MeasureBarlineInfo> {
    const parser = new DOMParser();
    const doc = parser.parseFromString(xmlString, 'application/xml');
    
    // 检查解析错误
    const parserError = doc.querySelector('parsererror');
    if (parserError) {
      console.error('[BarlineParser] XML解析错误:', parserError.textContent);
      return new Map();
    }
    
    return this.parseAllBarlines(doc);
  }
}

// ==================== 导出单例 ====================

/** 默认的Barline解析器实例 */
export const barlineParser = new BarlineParser();