|
| 1 | +// Copyright 2023 Google LLC |
| 2 | +// |
| 3 | +// Use of this source code is governed by an MIT-style |
| 4 | +// license that can be found in the LICENSE file or at |
| 5 | +// https://opensource.org/licenses/MIT. |
| 6 | + |
| 7 | +import 'package:sass_api/sass_api.dart'; |
| 8 | + |
| 9 | +import '../migration_visitor.dart'; |
| 10 | +import '../migrator.dart'; |
| 11 | +import '../patch.dart'; |
| 12 | + |
| 13 | +/// Removes interpolation in calculation functions. |
| 14 | +class CalculationInterpolationMigrator extends Migrator { |
| 15 | + final name = "calc-interpolation"; |
| 16 | + final description = r"Removes interpolation in calculation functions" |
| 17 | + r"`calc()`, `clamp()`, `min()`, and `max()`"; |
| 18 | + |
| 19 | + @override |
| 20 | + Map<Uri, String> migrateFile( |
| 21 | + ImportCache importCache, Stylesheet stylesheet, Importer importer) { |
| 22 | + var visitor = |
| 23 | + _CalculationInterpolationVisitor(importCache, migrateDependencies); |
| 24 | + var result = visitor.run(stylesheet, importer); |
| 25 | + missingDependencies.addAll(visitor.missingDependencies); |
| 26 | + return result; |
| 27 | + } |
| 28 | +} |
| 29 | + |
| 30 | +class _CalculationInterpolationVisitor extends MigrationVisitor { |
| 31 | + _CalculationInterpolationVisitor( |
| 32 | + ImportCache importCache, bool migrateDependencies) |
| 33 | + : super(importCache, migrateDependencies); |
| 34 | + |
| 35 | + @override |
| 36 | + void visitCalculationExpression(CalculationExpression node) { |
| 37 | + const calcFunctions = ['calc', 'clamp', 'min', 'max']; |
| 38 | + final interpolation = RegExp(r'^#{.*\s*}'); |
| 39 | + if (calcFunctions.contains(node.name)) { |
| 40 | + for (var arg in node.arguments) { |
| 41 | + for (var match in interpolation.allMatches(arg.toString())) { |
| 42 | + var noInterpolation = match[0].toString().substring(2, match.end - 1); |
| 43 | + var interpolationSpan = |
| 44 | + node.span.file.span(arg.span.start.offset, arg.span.end.offset); |
| 45 | + if (interpolationSpan.text == match[0].toString()) { |
| 46 | + addPatch(Patch(interpolationSpan, noInterpolation)); |
| 47 | + } |
| 48 | + } |
| 49 | + } |
| 50 | + } |
| 51 | + super.visitCalculationExpression(node); |
| 52 | + } |
| 53 | +} |
0 commit comments