markdown_raw.dart 15.2 KB
Newer Older
1 2 3 4 5
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'package:markdown/markdown.dart' as md;
Adam Barth's avatar
Adam Barth committed
6
import 'package:meta/meta.dart';
7
import 'package:flutter/widgets.dart';
8
import 'package:flutter/gestures.dart';
Adam Barth's avatar
Adam Barth committed
9

10 11
import 'markdown_style_raw.dart';

12 13
typedef void MarkdownLinkCallback(String href);

14 15 16 17 18 19

/// A [Widget] that renders markdown formatted text. It supports all standard
/// markdowns from the original markdown specification found here:
/// https://daringfireball.net/projects/markdown/ The rendered markdown is
/// placed in a padded scrolling view port. If you do not want the scrolling
/// behaviour, use the [MarkdownBodyRaw] class instead.
20
class MarkdownRaw extends StatelessWidget {
21 22 23 24 25 26 27 28 29 30 31 32 33

  /// Creates a new Markdown [Widget] that renders the markdown formatted string
  /// passed in as [data]. By default the markdown will be rendered using the
  /// styles from the current theme, but you can optionally pass in a custom
  /// [markdownStyle] that specifies colors and fonts to use. Code blocks are
  /// by default not using syntax highlighting, but it's possible to pass in
  /// a custom [syntaxHighlighter].
  ///
  ///     new MarkdownRaw(data: "Hello _world_!", markdownStyle: myStyle);
  MarkdownRaw({
    this.data,
    this.markdownStyle,
    this.syntaxHighlighter,
34
    this.padding: const EdgeInsets.all(16.0),
35
    this.onTapLink
36 37 38 39 40 41 42 43 44 45 46 47
  });

  /// Markdown styled text
  final String data;

  /// Style used for rendering the markdown
  final MarkdownStyleRaw markdownStyle;

  /// The syntax highlighter used to color text in code blocks
  final SyntaxHighlighter syntaxHighlighter;

  /// Padding used
48
  final EdgeInsets padding;
49

50 51 52
  /// Callback when a link is tapped
  final MarkdownLinkCallback onTapLink;

53
  @override
54 55 56 57 58 59 60
  Widget build(BuildContext context) {
    return new ScrollableViewport(
      child: new Padding(
        padding: padding,
        child: createMarkdownBody(
          data: data,
          markdownStyle: markdownStyle,
61 62
          syntaxHighlighter: syntaxHighlighter,
          onTapLink: onTapLink
63 64 65 66 67 68 69
        )
      )
    );
  }

  MarkdownBodyRaw createMarkdownBody({
    String data,
Adam Barth's avatar
Adam Barth committed
70
    @checked MarkdownStyleRaw markdownStyle,
71 72
    SyntaxHighlighter syntaxHighlighter,
    MarkdownLinkCallback onTapLink
73 74 75 76
  }) {
    return new MarkdownBodyRaw(
      data: data,
      markdownStyle: markdownStyle,
77 78
      syntaxHighlighter: syntaxHighlighter,
      onTapLink: onTapLink
79 80 81 82 83 84 85 86 87
    );
  }
}

/// A [Widget] that renders markdown formatted text. It supports all standard
/// markdowns from the original markdown specification found here:
/// https://daringfireball.net/projects/markdown/ This class doesn't implement
/// any scrolling behavior, if you want scrolling either wrap the widget in
/// a [ScrollableViewport] or use the [MarkdownRaw] widget.
88
class MarkdownBodyRaw extends StatefulWidget {
89 90 91 92 93 94 95 96 97 98 99

  /// Creates a new Markdown [Widget] that renders the markdown formatted string
  /// passed in as [data]. You need to pass in a [markdownStyle] that defines
  /// how the code is rendered. Code blocks are by default not using syntax
  /// highlighting, but it's possible to pass in a custom [syntaxHighlighter].
  ///
  /// Typically, you may want to wrap the [MarkdownBodyRaw] widget in a
  /// [Padding] and a [ScrollableViewport], or use the [Markdown class]
  ///
  ///     new ScrollableViewport(
  ///       child: new Padding(
100
  ///         padding: new EdgeInsets.all(16.0),
101 102 103 104 105 106 107 108 109
  ///         child: new MarkdownBodyRaw(
  ///           data: markdownSource,
  ///           markdownStyle: myStyle
  ///         )
  ///       )
  ///     )
  MarkdownBodyRaw({
    this.data,
    this.markdownStyle,
110 111
    this.syntaxHighlighter,
    this.onTapLink
112 113 114 115 116 117 118 119 120 121 122
  });

  /// Markdown styled text
  final String data;

  /// Style used for rendering the markdown
  final MarkdownStyleRaw markdownStyle;

  /// The syntax highlighter used to color text in code blocks
  final SyntaxHighlighter syntaxHighlighter;

123 124 125
  /// Callback when a link is tapped
  final MarkdownLinkCallback onTapLink;

126
  @override
127 128 129 130 131 132 133
  _MarkdownBodyRawState createState() => new _MarkdownBodyRawState();

  MarkdownStyleRaw createDefaultStyle(BuildContext context) => null;
}

class _MarkdownBodyRawState extends State<MarkdownBodyRaw> {

134
  @override
135
  void dependenciesChanged() {
136
    _buildMarkdownCache();
137
    super.dependenciesChanged();
138 139
  }

140
  @override
141 142 143 144 145
  void dispose() {
    _linkHandler.dispose();
    super.dispose();
  }

146
  @override
147 148 149 150 151 152 153 154 155
  void didUpdateConfig(MarkdownBodyRaw oldConfig) {
    super.didUpdateConfig(oldConfig);

    if (oldConfig.data != config.data ||
        oldConfig.markdownStyle != config.markdownStyle ||
        oldConfig.syntaxHighlighter != config.syntaxHighlighter ||
        oldConfig.onTapLink != config.onTapLink)
      _buildMarkdownCache();
  }
156

157
  void _buildMarkdownCache() {
158 159 160
    MarkdownStyleRaw markdownStyle = config.markdownStyle ?? config.createDefaultStyle(context);
    SyntaxHighlighter syntaxHighlighter = config.syntaxHighlighter ?? new _DefaultSyntaxHighlighter(markdownStyle.code);

161
    _linkHandler?.dispose();
162 163 164 165 166 167 168 169 170 171
    _linkHandler = new _LinkHandler(config.onTapLink);

    // TODO: This can be optimized by doing the split and removing \r at the same time
    List<String> lines = config.data.replaceAll('\r\n', '\n').split('\n');
    md.Document document = new md.Document();

    _Renderer renderer = new _Renderer();
    _cachedBlocks = renderer.render(document.parseLines(lines), markdownStyle, syntaxHighlighter, _linkHandler);
  }

172
  List<_Block> _cachedBlocks;
173
  _LinkHandler _linkHandler;
174

175
  @override
176 177 178 179 180 181 182
  Widget build(BuildContext context) {
    List<Widget> blocks = <Widget>[];
    for (_Block block in _cachedBlocks) {
      blocks.add(block.build(context));
    }

    return new Column(
183
      crossAxisAlignment: CrossAxisAlignment.stretch,
184 185 186
      children: blocks
    );
  }
187

188
  @override
189
  void debugFillDescription(List<String> description) {
190
    super.debugFillDescription(description);
191 192
    description.add('cached blocks identity: ${_cachedBlocks.hashCode}');
  }
193 194 195
}

class _Renderer implements md.NodeVisitor {
196
  List<_Block> render(List<md.Node> nodes, MarkdownStyleRaw markdownStyle, SyntaxHighlighter syntaxHighlighter, _LinkHandler linkHandler) {
197 198 199 200 201 202
    assert(markdownStyle != null);

    _blocks = <_Block>[];
    _listIndents = <String>[];
    _markdownStyle = markdownStyle;
    _syntaxHighlighter = syntaxHighlighter;
203
    _linkHandler = linkHandler;
204 205 206 207 208 209 210 211 212 213 214 215

    for (final md.Node node in nodes) {
      node.accept(this);
    }

    return _blocks;
  }

  List<_Block> _blocks;
  List<String> _listIndents;
  MarkdownStyleRaw _markdownStyle;
  SyntaxHighlighter _syntaxHighlighter;
216
  _LinkHandler _linkHandler;
217

218
  @override
219 220 221 222 223 224 225 226 227 228
  void visitText(md.Text text) {
    _MarkdownNodeList topList = _currentBlock.stack.last;
    List<_MarkdownNode> top = topList.list;

    if (_currentBlock.tag == 'pre')
      top.add(new _MarkdownNodeTextSpan(_syntaxHighlighter.format(text.text)));
    else
      top.add(new _MarkdownNodeString(text.text));
  }

229
  @override
230 231 232 233 234 235 236 237 238 239 240 241 242 243
  bool visitElementBefore(md.Element element) {
    if (_isListTag(element.tag))
      _listIndents.add(element.tag);

    if (_isBlockTag(element.tag)) {
      List<_Block> blockList;
      if (_currentBlock == null)
        blockList = _blocks;
      else
        blockList = _currentBlock.subBlocks;

      _Block newBlock = new _Block(element.tag, element.attributes, _markdownStyle, new List<String>.from(_listIndents), blockList.length);
      blockList.add(newBlock);
    } else {
Ian Hickson's avatar
Ian Hickson committed
244
      _LinkInfo linkInfo;
245 246 247 248
      if (element.tag == 'a') {
        linkInfo = _linkHandler.createLinkInfo(element.attributes['href']);
      }

249
      TextStyle style = _markdownStyle.styles[element.tag] ?? new TextStyle();
250
      List<_MarkdownNode> styleElement = <_MarkdownNode>[new _MarkdownNodeTextStyle(style, linkInfo)];
251 252 253 254 255
      _currentBlock.stack.add(new _MarkdownNodeList(styleElement));
    }
    return true;
  }

256
  @override
257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318
  void visitElementAfter(md.Element element) {
    if (_isListTag(element.tag))
      _listIndents.removeLast();

    if (_isBlockTag(element.tag)) {
      if (_currentBlock.stack.length > 0) {
        _MarkdownNodeList stackList = _currentBlock.stack.first;
        _currentBlock.stack = stackList.list;
        _currentBlock.open = false;
      } else {
        _currentBlock.stack = <_MarkdownNode>[new _MarkdownNodeString('')];
      }
    } else {
      if (_currentBlock.stack.length > 1) {
        _MarkdownNodeList poppedList = _currentBlock.stack.last;
        List<_MarkdownNode> popped = poppedList.list;
        _currentBlock.stack.removeLast();

        _MarkdownNodeList topList = _currentBlock.stack.last;
        List<_MarkdownNode> top = topList.list;
        top.add(new _MarkdownNodeList(popped));
      }
    }
  }

  static const List<String> _kBlockTags = const <String>['p', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'li', 'blockquote', 'img', 'pre', 'ol', 'ul'];
  static const List<String> _kListTags = const <String>['ul', 'ol'];

  bool _isBlockTag(String tag) {
    return _kBlockTags.contains(tag);
  }

  bool _isListTag(String tag) {
    return _kListTags.contains(tag);
  }

  _Block get _currentBlock => _currentBlockInList(_blocks);

  _Block _currentBlockInList(List<_Block> blocks) {
    if (blocks.isEmpty)
      return null;

    if (!blocks.last.open)
      return null;

    _Block childBlock = _currentBlockInList(blocks.last.subBlocks);
    if (childBlock != null)
      return childBlock;

    return blocks.last;
  }
}

abstract class _MarkdownNode {
}

class _MarkdownNodeList extends _MarkdownNode {
  _MarkdownNodeList(this.list);
  List<_MarkdownNode> list;
}

class _MarkdownNodeTextStyle extends _MarkdownNode {
319
  _MarkdownNodeTextStyle(this.style, [this.linkInfo = null]);
320
  TextStyle style;
321
  _LinkInfo linkInfo;
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353
}

class _MarkdownNodeString extends _MarkdownNode {
  _MarkdownNodeString(this.string);
  String string;
}

class _MarkdownNodeTextSpan extends _MarkdownNode {
  _MarkdownNodeTextSpan(this.textSpan);
  TextSpan textSpan;
}

class _Block {
  _Block(this.tag, this.attributes, this.markdownStyle, this.listIndents, this.blockPosition) {
    TextStyle style = markdownStyle.styles[tag];
    if (style == null)
      style = new TextStyle(color: const Color(0xffff0000));

    stack = <_MarkdownNode>[new _MarkdownNodeList(<_MarkdownNode>[new _MarkdownNodeTextStyle(style)])];
    subBlocks = <_Block>[];
  }

  final String tag;
  final Map<String, String> attributes;
  final MarkdownStyleRaw markdownStyle;
  final List<String> listIndents;
  final int blockPosition;

  List<_MarkdownNode> stack;
  List<_Block> subBlocks;

  bool get open => _open;
354
  set open(bool open) {
355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380
    _open = open;
    if (!open && subBlocks.length > 0)
      subBlocks.last.isLast = true;
  }

  bool _open = true;
  bool isLast = false;

  Widget build(BuildContext context) {

    if (tag == 'img') {
      return _buildImage(context, attributes['src']);
    }

    double spacing = markdownStyle.blockSpacing;
    if (isLast) spacing = 0.0;

    Widget contents;

    if (subBlocks.length > 0) {
      List<Widget> subWidgets = <Widget>[];
      for (_Block subBlock in subBlocks) {
        subWidgets.add(subBlock.build(context));
      }

      contents = new Column(
381
        crossAxisAlignment: CrossAxisAlignment.stretch,
382 383 384
        children: subWidgets
      );
    } else {
385 386
      TextSpan span = _stackToTextSpan(new _MarkdownNodeList(stack));
      contents = new RichText(text: span);
387 388 389 390 391 392

      if (listIndents.length > 0) {
        Widget bullet;
        if (listIndents.last == 'ul') {
          bullet = new Text(
            '•',
393
            textAlign: TextAlign.center
394 395 396 397
          );
        }
        else {
          bullet = new Padding(
398
            padding: new EdgeInsets.only(right: 5.0),
399 400
            child: new Text(
              "${blockPosition + 1}.",
401
              textAlign: TextAlign.right
402 403 404 405 406
            )
          );
        }

        contents = new Row(
407
          crossAxisAlignment: CrossAxisAlignment.start,
408 409 410 411 412 413 414 415 416 417 418 419
          children: <Widget>[
            new SizedBox(
              width: listIndents.length * markdownStyle.listIndent,
              child: bullet
            ),
            new Flexible(child: contents)
          ]
        );
      }
    }

    BoxDecoration decoration;
420
    EdgeInsets padding;
421 422 423

    if (tag == 'blockquote') {
      decoration = markdownStyle.blockquoteDecoration;
424
      padding = new EdgeInsets.all(markdownStyle.blockquotePadding);
425 426
    } else if (tag == 'pre') {
      decoration = markdownStyle.codeblockDecoration;
427
      padding = new EdgeInsets.all(markdownStyle.codeblockPadding);
428 429 430 431
    }

    return new Container(
      padding: padding,
432
      margin: new EdgeInsets.only(bottom: spacing),
433 434 435 436 437 438 439 440 441 442 443 444
      child: contents,
      decoration: decoration
    );
  }

  TextSpan _stackToTextSpan(_MarkdownNode stack) {
    if (stack is _MarkdownNodeTextSpan)
      return stack.textSpan;

    if (stack is _MarkdownNodeList) {
      List<_MarkdownNode> list = stack.list;
      _MarkdownNodeTextStyle styleNode = list[0];
445
      _LinkInfo linkInfo = styleNode.linkInfo;
446 447 448 449 450 451
      TextStyle style = styleNode.style;

      List<TextSpan> children = <TextSpan>[];
      for (int i = 1; i < list.length; i++) {
        children.add(_stackToTextSpan(list[i]));
      }
452

Ian Hickson's avatar
Ian Hickson committed
453
      String text;
454 455 456 457 458 459 460 461
      if (children.length == 1 && _isPlainText(children[0])) {
        text = children[0].text;
        children = null;
      }

      TapGestureRecognizer recognizer = linkInfo?.recognizer;

      return new TextSpan(style: style, children: children, recognizer: recognizer, text: text);
462 463 464 465 466 467 468 469 470
    }

    if (stack is _MarkdownNodeString) {
      return new TextSpan(text: stack.string);
    }

    return null;
  }

471 472 473 474
  bool _isPlainText(TextSpan span) {
    return (span.text != null && span.style == null && span.recognizer == null && span.children == null);
  }

475 476 477 478 479 480 481 482 483 484 485 486 487 488 489
  Widget _buildImage(BuildContext context, String src) {
    List<String> parts = src.split('#');
    if (parts.length == 0) return new Container();

    String path = parts.first;
    double width;
    double height;
    if (parts.length == 2) {
      List<String> dimensions = parts.last.split('x');
      if (dimensions.length == 2) {
        width = double.parse(dimensions[0]);
        height = double.parse(dimensions[1]);
      }
    }

490
    return new Image.network(path, width: width, height: height);
491 492 493
  }
}

494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526
class _LinkInfo {
  _LinkInfo(this.href, this.recognizer);

  final String href;
  final TapGestureRecognizer recognizer;
}

class _LinkHandler {
  _LinkHandler(this.onTapLink);

  List<_LinkInfo> links = <_LinkInfo>[];
  MarkdownLinkCallback onTapLink;

  _LinkInfo createLinkInfo(String href) {
    TapGestureRecognizer recognizer = new TapGestureRecognizer();
    recognizer.onTap = () {
      if (onTapLink != null)
        onTapLink(href);
    };

    _LinkInfo linkInfo = new _LinkInfo(href, recognizer);
    links.add(linkInfo);

    return linkInfo;
  }

  void dispose() {
    for (_LinkInfo linkInfo in links) {
      linkInfo.recognizer.dispose();
    }
  }
}

Ian Hickson's avatar
Ian Hickson committed
527
abstract class SyntaxHighlighter { // ignore: one_member_abstracts
528 529 530 531 532
  TextSpan format(String source);
}

class _DefaultSyntaxHighlighter extends SyntaxHighlighter{
  _DefaultSyntaxHighlighter(this.style);
Ian Hickson's avatar
Ian Hickson committed
533

534 535
  final TextStyle style;

536
  @override
537 538 539 540
  TextSpan format(String source) {
    return new TextSpan(style: style, children: <TextSpan>[new TextSpan(text: source)]);
  }
}