|
| 1 | +// Copyright 2022 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 | +import 'package:source_span/source_span.dart'; |
| 9 | + |
| 10 | +import '../migration_visitor.dart'; |
| 11 | +import '../migrator.dart'; |
| 12 | +import '../patch.dart'; |
| 13 | + |
| 14 | +/// Migrates deprecated `@media` query syntax to use interpolation. |
| 15 | +class MediaLogicMigrator extends Migrator { |
| 16 | + final name = 'media-logic'; |
| 17 | + final description = r'Migrates deprecated `@media` query syntax.\n' |
| 18 | + 'See https://sass-lang.com/d/media-logic.'; |
| 19 | + |
| 20 | + /// For each stylesheet URL, the set of relevant spans that require migration. |
| 21 | + final _expressionsToMigrate = <Uri, Set<FileSpan>>{}; |
| 22 | + |
| 23 | + @override |
| 24 | + void handleDeprecation(String message, FileSpan? span) { |
| 25 | + if (span == null) return; |
| 26 | + if (!message.startsWith('Starting a @media query with ')) return; |
| 27 | + _expressionsToMigrate.putIfAbsent(span.sourceUrl!, () => {}).add(span); |
| 28 | + } |
| 29 | + |
| 30 | + @override |
| 31 | + Map<Uri, String> migrateFile( |
| 32 | + ImportCache importCache, Stylesheet stylesheet, Importer importer) { |
| 33 | + var visitor = _MediaLogicVisitor( |
| 34 | + importCache, migrateDependencies, _expressionsToMigrate); |
| 35 | + var result = visitor.run(stylesheet, importer); |
| 36 | + missingDependencies.addAll(visitor.missingDependencies); |
| 37 | + return result; |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +class _MediaLogicVisitor extends MigrationVisitor { |
| 42 | + /// For each stylesheet URL, the set of relevant spans that require migration. |
| 43 | + final Map<Uri, Set<FileSpan>> _expressionsToMigrate; |
| 44 | + |
| 45 | + _MediaLogicVisitor(ImportCache importCache, bool migrateDependencies, |
| 46 | + this._expressionsToMigrate) |
| 47 | + : super(importCache, migrateDependencies); |
| 48 | + |
| 49 | + @override |
| 50 | + void beforePatch(Stylesheet node) { |
| 51 | + var expressions = _expressionsToMigrate[node.span.sourceUrl] ?? {}; |
| 52 | + for (var expression in expressions) { |
| 53 | + addPatch(Patch.insert(expression.start, '#{')); |
| 54 | + addPatch(Patch.insert(expression.end, '}')); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
0 commit comments