All files / music-core/parser StructureParser.ts

67.58% Statements 246/364
48.71% Branches 19/39
50% Functions 7/14
67.58% Lines 246/364

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 3651x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 2x 2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x               1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                                                               1x 1x 1x 1x 1x                                                   1x 1x 1x 1x                 1x 1x 1x 1x                           1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x   16x 16x 16x 16x 16x   16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 1x 1x 1x                   1x 1x 1x 1x 1x 15x 15x 15x 16x 16x 16x     16x 15x 15x 15x 1x 1x 1x 1x           1x 1x 1x 1x               1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 18x 18x 18x 53x 53x 33x 33x 53x     53x     53x     53x 16x 16x 53x     53x 4x 4x 53x 53x 53x 18x 18x 18x 18x 18x 18x 18x 18x 18x 1x 1x 1x 1x 1x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 1x 1x 1x 1x 1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 16x 16x 16x 16x 15x 15x 15x 15x 16x 16x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x  
/**
 * @file 结构解析器
 * @description 解析 MusicXML 的整体结构(score, part-list, part, measure)
 */
 
import { Score, Work, Identification, Creator, Encoding, Defaults, Credit, PartListItem, PartGroup } from '../models/Score';
import { Part, ScorePartDefinition, ScoreInstrument, MidiInstrument } from '../models/Part';
import { Measure, MeasureElement, Backup, Forward } from '../models/Measure';
import { getChild, getChildren, getTextContent, getIntContent, getNumberContent, getAttribute, hasChild, forEachChild } from '../utils/XMLUtils';
import { parseNote } from './NoteParser';
import { parseAttributes } from './AttributesParser';
import { parseDirection } from './DirectionParser';
import { parseBarline, parseHarmony } from './BarlineParser';
 
/**
 * 解析 work 元素
 */
export function parseWork(element: Element): Work {
  return {
    workNumber: getTextContent(element, 'work-number'),
    workTitle: getTextContent(element, 'work-title'),
    opus: hasChild(element, 'opus') 
      ? { href: getAttribute(getChild(element, 'opus')!, 'href') ?? '' }
      : undefined
  };
}
 
/**
 * 解析 identification 元素
 */
export function parseIdentification(element: Element): Identification {
  // creators
  const creatorElements = getChildren(element, 'creator');
  const creators: Creator[] = creatorElements.map(el => ({
    type: getAttribute(el, 'type'),
    name: el.textContent?.trim() ?? ''
  }));
  
  // rights
  const rightsElements = getChildren(element, 'rights');
  const rights = rightsElements.map(el => el.textContent?.trim() ?? '');
  
  // encoding
  const encodingEl = getChild(element, 'encoding');
  let encoding: Encoding | undefined;
  if (encodingEl) {
    encoding = {
      encodingDate: getTextContent(encodingEl, 'encoding-date'),
      encoder: getTextContent(encodingEl, 'encoder'),
      software: getTextContent(encodingEl, 'software'),
      encodingDescription: getTextContent(encodingEl, 'encoding-description')
    };
  }
  
  // source
  const source = getTextContent(element, 'source');
  
  return {
    creators: creators.length > 0 ? creators : undefined,
    rights: rights.length > 0 ? rights : undefined,
    encoding,
    source
  };
}
 
/**
 * 解析 defaults 元素
 */
export function parseDefaults(element: Element): Defaults {
  const defaults: Defaults = {};
  
  // scaling
  const scalingEl = getChild(element, 'scaling');
  if (scalingEl) {
    defaults.scaling = {
      millimeters: getNumberContent(scalingEl, 'millimeters'),
      tenths: getNumberContent(scalingEl, 'tenths')
    };
  }
  
  // page-layout
  const pageLayoutEl = getChild(element, 'page-layout');
  if (pageLayoutEl) {
    defaults.pageLayout = {
      pageHeight: getNumberContent(pageLayoutEl, 'page-height'),
      pageWidth: getNumberContent(pageLayoutEl, 'page-width')
    };
  }
  
  // system-layout
  const systemLayoutEl = getChild(element, 'system-layout');
  if (systemLayoutEl) {
    defaults.systemLayout = {
      systemDistance: getNumberContent(systemLayoutEl, 'system-distance'),
      topSystemDistance: getNumberContent(systemLayoutEl, 'top-system-distance')
    };
  }
  
  return defaults;
}
 
/**
 * 解析 credit 元素
 */
export function parseCredit(element: Element): Credit {
  const page = getIntContent(element, 'page');
  
  // credit-words
  const creditWordsElements = getChildren(element, 'credit-words');
  const creditWords = creditWordsElements.map(el => ({
    text: el.textContent?.trim() ?? '',
    defaultX: getNumberContent(el, 'default-x'),
    defaultY: getNumberContent(el, 'default-y'),
    fontSize: getAttribute(el, 'font-size'),
    fontWeight: getAttribute(el, 'font-weight') as 'normal' | 'bold' | undefined,
    fontStyle: getAttribute(el, 'font-style') as 'normal' | 'italic' | undefined,
    justify: getAttribute(el, 'justify') as 'left' | 'center' | 'right' | undefined,
    valign: getAttribute(el, 'valign') as 'top' | 'middle' | 'bottom' | 'baseline' | undefined
  }));
  
  // credit-type
  const creditTypeElements = getChildren(element, 'credit-type');
  const creditType = creditTypeElements.map(el => el.textContent?.trim() ?? '');
  
  return {
    page,
    creditWords: creditWords.length > 0 ? creditWords : undefined,
    creditType: creditType.length > 0 ? creditType : undefined
  };
}
 
/**
 * 解析 score-instrument 元素
 */
function parseScoreInstrument(element: Element): ScoreInstrument {
  return {
    id: getAttribute(element, 'id') ?? '',
    instrumentName: getTextContent(element, 'instrument-name') ?? '',
    instrumentAbbreviation: getTextContent(element, 'instrument-abbreviation'),
    instrumentSound: getTextContent(element, 'instrument-sound')
  };
}
 
/**
 * 解析 midi-instrument 元素
 */
function parseMidiInstrument(element: Element): MidiInstrument {
  return {
    id: getAttribute(element, 'id') ?? '',
    midiChannel: getIntContent(element, 'midi-channel'),
    midiName: getTextContent(element, 'midi-name'),
    midiBank: getIntContent(element, 'midi-bank'),
    midiProgram: getIntContent(element, 'midi-program'),
    midiUnpitched: getIntContent(element, 'midi-unpitched'),
    volume: getNumberContent(element, 'volume'),
    pan: getNumberContent(element, 'pan'),
    elevation: getNumberContent(element, 'elevation')
  };
}
 
/**
 * 解析 score-part 元素
 */
export function parseScorePart(element: Element): ScorePartDefinition {
  const id = getAttribute(element, 'id') ?? '';
  const partName = getTextContent(element, 'part-name') ?? '';
  const partAbbreviation = getTextContent(element, 'part-abbreviation');
  const group = getTextContent(element, 'group');
  
  // score-instruments
  const scoreInstrumentElements = getChildren(element, 'score-instrument');
  const scoreInstruments = scoreInstrumentElements.length > 0
    ? scoreInstrumentElements.map(parseScoreInstrument)
    : undefined;
  
  // midi-instruments
  const midiInstrumentElements = getChildren(element, 'midi-instrument');
  const midiInstruments = midiInstrumentElements.length > 0
    ? midiInstrumentElements.map(parseMidiInstrument)
    : undefined;
  
  return {
    id,
    partName,
    partAbbreviation,
    group,
    scoreInstruments,
    midiInstruments
  };
}
 
/**
 * 解析 part-group 元素
 */
export function parsePartGroup(element: Element): PartGroup {
  return {
    type: getAttribute(element, 'type') as 'start' | 'stop',
    number: getAttribute(element, 'number'),
    groupName: getTextContent(element, 'group-name'),
    groupAbbreviation: getTextContent(element, 'group-abbreviation'),
    groupSymbol: getTextContent(element, 'group-symbol') as PartGroup['groupSymbol'],
    groupBarline: getTextContent(element, 'group-barline') as PartGroup['groupBarline']
  };
}
 
/**
 * 解析 part-list 元素
 */
export function parsePartList(element: Element): PartListItem[] {
  const items: PartListItem[] = [];
  
  for (const child of element.children) {
    if (child.tagName === 'score-part') {
      items.push({ type: 'part', data: parseScorePart(child) });
    } else if (child.tagName === 'part-group') {
      items.push({ type: 'group', data: parsePartGroup(child) });
    }
  }
  
  return items;
}
 
/**
 * 解析 backup 元素
 */
function parseBackup(element: Element): Backup {
  return {
    duration: getIntContent(element, 'duration') ?? 0
  };
}
 
/**
 * 解析 forward 元素
 */
function parseForward(element: Element): Forward {
  return {
    duration: getIntContent(element, 'duration') ?? 0,
    voice: getIntContent(element, 'voice'),
    staff: getIntContent(element, 'staff')
  };
}
 
/**
 * 解析 measure 元素
 */
export function parseMeasure(element: Element): Measure {
  const number = getAttribute(element, 'number') ?? '1';
  const width = getNumberContent(element, 'width');
  const implicit = getAttribute(element, 'implicit') === 'yes';
  const nonControlling = getAttribute(element, 'non-controlling') === 'yes';
  
  const elements: MeasureElement[] = [];
  
  for (const child of element.children) {
    switch (child.tagName) {
      case 'note':
        elements.push({ type: 'note', data: parseNote(child) });
        break;
      case 'backup':
        elements.push({ type: 'backup', data: parseBackup(child) });
        break;
      case 'forward':
        elements.push({ type: 'forward', data: parseForward(child) });
        break;
      case 'direction':
        elements.push({ type: 'direction', data: parseDirection(child) });
        break;
      case 'attributes':
        elements.push({ type: 'attributes', data: parseAttributes(child) });
        break;
      case 'harmony':
        elements.push({ type: 'harmony', data: parseHarmony(child) });
        break;
      case 'barline':
        elements.push({ type: 'barline', data: parseBarline(child) });
        break;
      // 忽略其他元素(print, sound 等已在其他地方处理)
    }
  }
  
  return new Measure({
    number,
    elements,
    width,
    implicit,
    nonControlling
  });
}
 
/**
 * 解析 part 元素
 */
export function parsePart(element: Element, definition?: ScorePartDefinition): Part {
  const id = getAttribute(element, 'id') ?? '';
  
  // 解析所有小节
  const measureElements = getChildren(element, 'measure');
  const measures = measureElements.map(parseMeasure);
  
  return new Part({
    id,
    definition,
    measures
  });
}
 
/**
 * 解析 score-partwise 格式的乐谱
 */
export function parseScorePartwise(root: Element): Score {
  // 版本
  const version = getAttribute(root, 'version');
  
  // work
  const workEl = getChild(root, 'work');
  const work = workEl ? parseWork(workEl) : undefined;
  
  // movement-number, movement-title
  const movementNumber = getTextContent(root, 'movement-number');
  const movementTitle = getTextContent(root, 'movement-title');
  
  // identification
  const identificationEl = getChild(root, 'identification');
  const identification = identificationEl ? parseIdentification(identificationEl) : undefined;
  
  // defaults
  const defaultsEl = getChild(root, 'defaults');
  const defaults = defaultsEl ? parseDefaults(defaultsEl) : undefined;
  
  // credits
  const creditElements = getChildren(root, 'credit');
  const credits = creditElements.length > 0 ? creditElements.map(parseCredit) : undefined;
  
  // part-list
  const partListEl = getChild(root, 'part-list');
  const partList = partListEl ? parsePartList(partListEl) : [];
  
  // 构建声部定义映射
  const partDefinitionMap = new Map<string, ScorePartDefinition>();
  for (const item of partList) {
    if (item.type === 'part') {
      partDefinitionMap.set(item.data.id, item.data);
    }
  }
  
  // parts
  const partElements = getChildren(root, 'part');
  const parts = partElements.map(el => {
    const partId = getAttribute(el, 'id') ?? '';
    return parsePart(el, partDefinitionMap.get(partId));
  });
  
  return new Score({
    version,
    work,
    movementNumber,
    movementTitle,
    identification,
    defaults,
    credits,
    partList,
    parts
  });
}