add method

void add(
  1. MusicalElement element
)

Adds a musical element to the measure.

When a time signature is present, validates capacity before adding to ensure the bar's rhythmic value is not exceeded.

Throws MeasureCapacityException if the element would exceed the measure capacity.

Implementation

void add(MusicalElement element) {
  // Check if the element occupies musical time
  final elementDuration = _getElementDuration(element);

  if (elementDuration > 0) {
    // Retrieve the time signature from the measure or use the inherited one
    final ts = timeSignature ?? inheritedTimeSignature;

    if (ts != null) {
      // calculateTeste available space
      final currentValue = currentMusicalValue;
      final measureCapacity = ts.measureValue;
      final afterAdding = currentValue + elementDuration;

      // Tolerance for floating-point errors
      const tolerance = 0.0001;

      if (afterAdding > measureCapacity + tolerance) {
        final excess = afterAdding - measureCapacity;
        throw MeasureCapacityException(
          'Cannot add ${element.runtimeType} to the measure!\n'
          'Measure ${ts.numerator}/${ts.denominator} (capacity: $measureCapacity units)\n'
          'Current value: $currentValue units\n'
          'Attempting to add: $elementDuration units\n'
          'Total would be: $afterAdding units\n'
          'EXCESS: ${excess.toStringAsFixed(4)} units\n'
          'OPERATION BLOCKED — Remove elements or create a new measure!'
        );
      }
    }
  }

  // Add the element
  elements.add(element);
}