markdown_raw.dart 15.1 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
  @override
52 53 54 55 56 57 58
  Widget build(BuildContext context) {
    return new ScrollableViewport(
      child: new Padding(
        padding: padding,
        child: createMarkdownBody(
          data: data,
          markdownStyle: markdownStyle,
59 60
          syntaxHighlighter: syntaxHighlighter,
          onTapLink: onTapLink
61 62 63 64 65 66 67 68
        )
      )
    );
  }

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

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

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

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

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

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

  MarkdownStyleRaw createDefaultStyle(BuildContext context) => null;
}

class _MarkdownBodyRawState extends State<MarkdownBodyRaw> {

132
  @override
133 134
  void initState() {
    super.initState();
135 136 137
    _buildMarkdownCache();
  }

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

144
  @override
145 146 147 148 149 150 151 152 153
  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();
  }
154

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

159
    _linkHandler?.dispose();
160 161 162 163 164 165 166 167 168 169
    _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);
  }

170
  List<_Block> _cachedBlocks;
171
  _LinkHandler _linkHandler;
172

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

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

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

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

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

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

    return _blocks;
  }

  List<_Block> _blocks;
  List<String> _listIndents;
  MarkdownStyleRaw _markdownStyle;
  SyntaxHighlighter _syntaxHighlighter;
213
  _LinkHandler _linkHandler;
214

215
  @override
216 217 218 219 220 221 222 223 224 225
  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));
  }

226
  @override
227 228 229 230 231 232 233 234 235 236 237 238 239 240
  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
241
      _LinkInfo linkInfo;
242 243 244 245
      if (element.tag == 'a') {
        linkInfo = _linkHandler.createLinkInfo(element.attributes['href']);
      }

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

253
  @override
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 306 307 308 309 310 311 312 313 314 315
  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 {
316
  _MarkdownNodeTextStyle(this.style, [this.linkInfo = null]);
317
  TextStyle style;
318
  _LinkInfo linkInfo;
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 368 369 370 371 372 373 374 375 376 377
}

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(
378
        crossAxisAlignment: CrossAxisAlignment.stretch,
379 380 381
        children: subWidgets
      );
    } else {
382 383
      TextSpan span = _stackToTextSpan(new _MarkdownNodeList(stack));
      contents = new RichText(text: span);
384 385 386 387 388 389 390 391 392 393 394

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

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

    BoxDecoration decoration;
417
    EdgeInsets padding;
418 419 420

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

    return new Container(
      padding: padding,
429
      margin: new EdgeInsets.only(bottom: spacing),
430 431 432 433 434 435 436 437 438 439 440 441
      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];
442
      _LinkInfo linkInfo = styleNode.linkInfo;
443 444 445 446 447 448
      TextStyle style = styleNode.style;

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

Ian Hickson's avatar
Ian Hickson committed
450
      String text;
451 452 453 454 455 456 457 458
      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);
459 460 461 462 463 464 465 466 467
    }

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

    return null;
  }

468 469 470 471
  bool _isPlainText(TextSpan span) {
    return (span.text != null && span.style == null && span.recognizer == null && span.children == null);
  }

472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490
  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);
  }
}

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
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
524
abstract class SyntaxHighlighter { // ignore: one_member_abstracts
525 526 527 528 529
  TextSpan format(String source);
}

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

531 532
  final TextStyle style;

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