|
| 1 | +// Copyright 2025 The Flutter Authors. All rights reserved. |
| 2 | +// Use of this source code is governed by a BSD-style license that can be |
| 3 | +// found in the LICENSE file. |
| 4 | + |
| 5 | +import 'package:jaspr/jaspr.dart'; |
| 6 | +import 'package:jaspr_content/jaspr_content.dart'; |
| 7 | + |
| 8 | +import '../../util.dart'; |
| 9 | +import 'wrapped_code_block.dart'; |
| 10 | + |
| 11 | +/// A component that displays a preview area alongside a code block. |
| 12 | +/// |
| 13 | +/// The `<CodePreview>` component takes in standard markdown content, but |
| 14 | +/// expects at least two children, with the last child being a code block. |
| 15 | +/// Any content before the last child is treated as the preview area. |
| 16 | +class CodePreview extends CustomComponent { |
| 17 | + const CodePreview() : super.base(); |
| 18 | + |
| 19 | + @override |
| 20 | + Component? create(Node node, NodesBuilder builder) { |
| 21 | + if (node case ElementNode( |
| 22 | + tag: 'CodePreview', |
| 23 | + :final attributes, |
| 24 | + :final children?, |
| 25 | + )) { |
| 26 | + if (children.length < 2) { |
| 27 | + throw Exception('CodePreview requires at least two child elements.'); |
| 28 | + } |
| 29 | + final lastChild = children.last; |
| 30 | + if (lastChild is! ComponentNode || |
| 31 | + lastChild.component is! WrappedCodeBlock) { |
| 32 | + throw Exception( |
| 33 | + 'The last child of CodePreview must be a code block.', |
| 34 | + ); |
| 35 | + } |
| 36 | + |
| 37 | + final previewChildren = <Node>[]; |
| 38 | + |
| 39 | + for (var i = 0; i < children.length - 1; i++) { |
| 40 | + if (children[i] case ElementNode(tag: 'p', :final children?)) { |
| 41 | + // Unwrap paragraph nodes to avoid extra spacing. |
| 42 | + previewChildren.addAll(children); |
| 43 | + } else { |
| 44 | + previewChildren.add(children[i]); |
| 45 | + } |
| 46 | + } |
| 47 | + |
| 48 | + final direction = attributes['direction'] ?? 'column'; |
| 49 | + final previewColor = attributes['previewcolor']; |
| 50 | + |
| 51 | + return div( |
| 52 | + classes: 'code-preview', |
| 53 | + attributes: {'data-direction': direction}, |
| 54 | + [ |
| 55 | + div( |
| 56 | + classes: [ |
| 57 | + 'preview-area', |
| 58 | + if (previewColor != null) 'fixed-bg', |
| 59 | + ].toClasses, |
| 60 | + styles: previewColor != null |
| 61 | + ? Styles(backgroundColor: Color(previewColor)) |
| 62 | + : null, |
| 63 | + [ |
| 64 | + builder.build(previewChildren), |
| 65 | + ], |
| 66 | + ), |
| 67 | + lastChild.component, |
| 68 | + ], |
| 69 | + ); |
| 70 | + } |
| 71 | + |
| 72 | + return null; |
| 73 | + } |
| 74 | +} |
0 commit comments