isElementVisible function

bool isElementVisible(
  1. ReportElement element,
  2. Map<String, dynamic> data, {
  3. int pageNumber = 1,
  4. int pageCount = 1,
})

Evaluates an element's page and data visibility rules.

Supported data expressions are path == value, path != value, a plain path (present and non-empty), empty(path), and notEmpty(path).

Implementation

bool isElementVisible(
  ReportElement element,
  Map<String, dynamic> data, {
  int pageNumber = 1,
  int pageCount = 1,
}) {
  if (element.hidden) return false;
  if (element.pageVisibility == ElementPageVisibility.first &&
      pageNumber != 1) {
    return false;
  }
  if (element.pageVisibility == ElementPageVisibility.last &&
      pageNumber != pageCount) {
    return false;
  }
  final expression = element.visibilityCondition.trim();
  if (expression.isEmpty) return true;

  bool empty(dynamic value) =>
      value == null ||
      (value is String && value.trim().isEmpty) ||
      (value is Iterable && value.isEmpty) ||
      (value is Map && value.isEmpty);

  final function = RegExp(
    r'^(empty|notEmpty)\s*\(\s*([\w.]+)\s*\)$',
  ).firstMatch(expression);
  if (function != null) {
    final isEmpty = empty(resolvePath(function.group(2)!, data));
    return function.group(1) == 'empty' ? isEmpty : !isEmpty;
  }

  final comparison = RegExp(
    r'^([\w.]+)\s*(==|!=)\s*(.+)$',
  ).firstMatch(expression);
  if (comparison != null) {
    final actual = resolvePath(comparison.group(1)!, data);
    var expected = comparison.group(3)!.trim();
    if ((expected.startsWith('"') && expected.endsWith('"')) ||
        (expected.startsWith("'") && expected.endsWith("'"))) {
      expected = expected.substring(1, expected.length - 1);
    }
    final equal = actual?.toString() == expected;
    return comparison.group(2) == '==' ? equal : !equal;
  }

  return !empty(resolvePath(expression, data));
}