parseTransform function

Matrix4? parseTransform(
  1. String? transform
)

Parses a SVG transform attribute into a Matrix4.

Based on work in the "vi-tool" by @amirh, but extended to support additional transforms and use a Matrix4 rather than Matrix3 for the affine matrices.

Also adds x and y to append as a final translation, e.g. for <use>.

Implementation

Matrix4? parseTransform(String? transform) {
  if (transform == null || transform == '') {
    return null;
  }

  if (!_transformValidator.hasMatch(transform))
    throw StateError('illegal or unsupported transform: $transform');
  final Iterable<Match> matches =
      _transformCommand.allMatches(transform).toList().reversed;
  Matrix4 result = Matrix4.identity();
  for (Match m in matches) {
    final String command = m.group(1)!.trim();
    final String? params = m.group(2);

    final _MatrixParser? transformer = _matrixParsers[command];
    if (transformer == null) {
      throw StateError('Unsupported transform: $command');
    }

    result = transformer(params, result);
  }
  return result;
}