markdown_raw.dart 15 KB
Newer Older
1 2 3 4 5 6
// 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;
import 'package:flutter/widgets.dart';
7
import 'package:flutter/gestures.dart';
8 9
import 'markdown_style_raw.dart';

10 11
typedef void MarkdownLinkCallback(String href);

12 13 14 15 16 17

/// 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.
18
class MarkdownRaw extends StatelessWidget {
19 20 21 22 23 24 25 26 27 28 29 30 31

  /// 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,
32
    this.padding: const EdgeInsets.all(16.0),
33
    this.onTapLink
34 35 36 37 38 39 40 41 42 43 44 45
  });

  /// 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
46
  final EdgeInsets padding;
47

48 49 50
  /// Callback when a link is tapped
  final MarkdownLinkCallback onTapLink;

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

  MarkdownBodyRaw createMarkdownBody({
    String data,
    MarkdownStyleRaw markdownStyle,
68 69
    SyntaxHighlighter syntaxHighlighter,
    MarkdownLinkCallback onTapLink
70 71 72 73
  }) {
    return new MarkdownBodyRaw(
      data: data,
      markdownStyle: markdownStyle,
74 75
      syntaxHighlighter: syntaxHighlighter,
      onTapLink: onTapLink
76 77 78 79 80 81 82 83 84
    );
  }
}

/// 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.
85
class MarkdownBodyRaw extends StatefulWidget {
86 87 88 89 90 91 92 93 94 95 96

  /// 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(
97
  ///         padding: new EdgeInsets.all(16.0),
98 99 100 101 102 103 104 105 106
  ///         child: new MarkdownBodyRaw(
  ///           data: markdownSource,
  ///           markdownStyle: myStyle
  ///         )
  ///       )
  ///     )
  MarkdownBodyRaw({
    this.data,
    this.markdownStyle,
107 108
    this.syntaxHighlighter,
    this.onTapLink
109 110 111 112 113 114 115 116 117 118 119
  });

  /// 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;

120 121 122
  /// Callback when a link is tapped
  final MarkdownLinkCallback onTapLink;

123 124 125 126 127 128 129 130 131
  _MarkdownBodyRawState createState() => new _MarkdownBodyRawState();

  MarkdownStyleRaw createDefaultStyle(BuildContext context) => null;
}

class _MarkdownBodyRawState extends State<MarkdownBodyRaw> {

  void initState() {
    super.initState();
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
    _buildMarkdownCache();
  }

  void dispose() {
    _linkHandler.dispose();
    super.dispose();
  }

  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();
  }
149

150
  void _buildMarkdownCache() {
151 152 153
    MarkdownStyleRaw markdownStyle = config.markdownStyle ?? config.createDefaultStyle(context);
    SyntaxHighlighter syntaxHighlighter = config.syntaxHighlighter ?? new _DefaultSyntaxHighlighter(markdownStyle.code);

154
    _linkHandler?.dispose();
155 156 157 158 159 160 161 162 163 164
    _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);
  }

165
  List<_Block> _cachedBlocks;
166
  _LinkHandler _linkHandler;
167 168 169 170 171 172 173 174

  Widget build(BuildContext context) {
    List<Widget> blocks = <Widget>[];
    for (_Block block in _cachedBlocks) {
      blocks.add(block.build(context));
    }

    return new Column(
175
      crossAxisAlignment: CrossAxisAlignment.stretch,
176 177 178
      children: blocks
    );
  }
179 180 181 182

  void debugFillDescription(List<String> description) {
    description.add('cached blocks identity: ${_cachedBlocks.hashCode}');
  }
183 184 185
}

class _Renderer implements md.NodeVisitor {
186
  List<_Block> render(List<md.Node> nodes, MarkdownStyleRaw markdownStyle, SyntaxHighlighter syntaxHighlighter, _LinkHandler linkHandler) {
187 188 189 190 191 192
    assert(markdownStyle != null);

    _blocks = <_Block>[];
    _listIndents = <String>[];
    _markdownStyle = markdownStyle;
    _syntaxHighlighter = syntaxHighlighter;
193
    _linkHandler = linkHandler;
194 195 196 197 198 199 200 201 202 203 204 205

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

    return _blocks;
  }

  List<_Block> _blocks;
  List<String> _listIndents;
  MarkdownStyleRaw _markdownStyle;
  SyntaxHighlighter _syntaxHighlighter;
206
  _LinkHandler _linkHandler;
207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231

  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));
  }

  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
232
      _LinkInfo linkInfo;
233 234 235 236
      if (element.tag == 'a') {
        linkInfo = _linkHandler.createLinkInfo(element.attributes['href']);
      }

237
      TextStyle style = _markdownStyle.styles[element.tag] ?? new TextStyle();
238
      List<_MarkdownNode> styleElement = <_MarkdownNode>[new _MarkdownNodeTextStyle(style, linkInfo)];
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 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
      _currentBlock.stack.add(new _MarkdownNodeList(styleElement));
    }
    return true;
  }

  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 {
306
  _MarkdownNodeTextStyle(this.style, [this.linkInfo = null]);
307
  TextStyle style;
308
  _LinkInfo linkInfo;
309 310 311 312 313 314 315 316 317 318 319 320 321 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 354 355 356 357 358 359 360 361 362 363 364 365 366 367
}

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;
  void set open(bool open) {
    _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(
368
        crossAxisAlignment: CrossAxisAlignment.stretch,
369 370 371
        children: subWidgets
      );
    } else {
372 373
      TextSpan span = _stackToTextSpan(new _MarkdownNodeList(stack));
      contents = new RichText(text: span);
374 375 376 377 378 379 380 381 382 383 384

      if (listIndents.length > 0) {
        Widget bullet;
        if (listIndents.last == 'ul') {
          bullet = new Text(
            '•',
            style: new TextStyle(textAlign: TextAlign.center)
          );
        }
        else {
          bullet = new Padding(
385
            padding: new EdgeInsets.only(right: 5.0),
386 387 388 389 390 391 392 393
            child: new Text(
              "${blockPosition + 1}.",
              style: new TextStyle(textAlign: TextAlign.right)
            )
          );
        }

        contents = new Row(
394
          crossAxisAlignment: CrossAxisAlignment.start,
395 396 397 398 399 400 401 402 403 404 405 406
          children: <Widget>[
            new SizedBox(
              width: listIndents.length * markdownStyle.listIndent,
              child: bullet
            ),
            new Flexible(child: contents)
          ]
        );
      }
    }

    BoxDecoration decoration;
407
    EdgeInsets padding;
408 409 410

    if (tag == 'blockquote') {
      decoration = markdownStyle.blockquoteDecoration;
411
      padding = new EdgeInsets.all(markdownStyle.blockquotePadding);
412 413
    } else if (tag == 'pre') {
      decoration = markdownStyle.codeblockDecoration;
414
      padding = new EdgeInsets.all(markdownStyle.codeblockPadding);
415 416 417 418
    }

    return new Container(
      padding: padding,
419
      margin: new EdgeInsets.only(bottom: spacing),
420 421 422 423 424 425 426 427 428 429 430 431
      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];
432
      _LinkInfo linkInfo = styleNode.linkInfo;
433 434 435 436 437 438
      TextStyle style = styleNode.style;

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

Ian Hickson's avatar
Ian Hickson committed
440
      String text;
441 442 443 444 445 446 447 448
      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);
449 450 451 452 453 454 455 456 457
    }

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

    return null;
  }

458 459 460 461
  bool _isPlainText(TextSpan span) {
    return (span.text != null && span.style == null && span.recognizer == null && span.children == null);
  }

462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
  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]);
      }
    }

    return new NetworkImage(src: path, width: width, height: height);
  }
}

481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513
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
514
abstract class SyntaxHighlighter { // ignore: one_member_abstracts
515 516 517 518 519
  TextSpan format(String source);
}

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

521 522 523 524 525 526
  final TextStyle style;

  TextSpan format(String source) {
    return new TextSpan(style: style, children: <TextSpan>[new TextSpan(text: source)]);
  }
}