gooy / aurelia-markdown

A simple markdown custom element for Aurelia
MIT License
8 stars 7 forks source link

Doesn't render exactly as per markup in some cases #4

Open charlespockert opened 8 years ago

charlespockert commented 8 years ago

This is due to the fact that any markup will be parsed by the browser which builds the actual DOM and when you pull innerHTML it doesn't always 100% reflect the text used in the original markup (no closing tags/self closing slashes on inputs for example)

I've tried the same approach but used a <textarea> instead to base the markup inside, since we want markup to be text that gets converted to HTML rather than HTML that gets converted to HTML :)

Here's what I did:

markdown custom attribute:

import { inject, bindable, customAttribute } from 'aurelia-framework';
import showdown from 'github:showdownjs/showdown@1.3.0';

@customAttribute("au-markdown")
@inject(Element)
export class AuMarkdown {

  constructor(element){
    this.parent = element.parentNode; // Keep hold of the fragment for now
    this.text = element.value; // Pull the text from the textarea
    var span = document.createElement("span"); // Add a container for the HTML
    this.parent.appendChild(span); 
    this.converter = new showdown.Converter();
    span.innerHTML = this.converter.makeHtml(this.text); // Fill the container with HTML
    this.parent.removeChild(element); // Remove the original textarea
  }
}

Usage:

          <textarea au-markdown>
`` `
<input au-kendo-autocomplete="data-source.bind: datasource;
                              data-text-field: ProductName;
                              filter: contains;
                              min-length: 3" 
                              value.bind="value" 
                              style="width: 300px" />
`` ` 
          </textarea>

Example image image

(sorry not entirely sure how to escape triple backticks so I've put a space in them in the above example)

Obviously this doesn't respond to changes in the textarea value as the textarea is eaten by the custom attribute, but it could work in a slightly different way where you can add the attribute to an area where you want the markup to appear and point it at a target textarea

This way it could respond to binding changes and actually regenerate the markup as a preview as you type

Something like:

<textarea ref="target">
</textarea>

<p markdown="target.bind: target"></p>