├── .babelrc
├── .editorconfig
├── .eslintignore
├── .eslintrc.js
├── .gitignore
├── .stylelintrc
├── CONTRIBUTING.md
├── LICENSE
├── README.md
├── build
├── utils
│ ├── index.js
│ ├── log.js
│ ├── style.js
│ └── write.js
├── webpack.config.base.js
├── webpack.config.browser.js
├── webpack.config.common.js
├── webpack.config.dev.js
└── webpack.config.dll.js
├── package.json
├── src
├── index.js
├── rules
│ ├── emoji.js
│ ├── heading.js
│ ├── highlight.js
│ ├── horizontal-line.js
│ ├── img.js
│ ├── index.js
│ ├── inline-code.js
│ ├── italic.js
│ ├── link.js
│ ├── linkify.js
│ ├── lists.js
│ ├── quote.js
│ ├── strong.js
│ └── table.js
├── utils
│ ├── index.js
│ └── utils.js
├── vue-simple-markdown-parser.js
└── vue-simple-markdown.component.vue
├── test
├── .eslintrc
├── helpers
│ ├── Test.vue
│ ├── index.js
│ ├── utils.js
│ └── wait-for-update.js
├── index.js
├── karma.conf.js
└── visual.js
└── yarn.lock
/.babelrc:
--------------------------------------------------------------------------------
1 | {
2 | "presets": [
3 | [
4 | "env",
5 | {
6 | "targets": {
7 | "browsers": [
8 | "last 2 versions"
9 | ]
10 | }
11 | }
12 | ]
13 | ],
14 | "plugins": [
15 | "transform-vue-jsx",
16 | "transform-object-rest-spread"
17 | ],
18 | "env": {
19 | "test": {
20 | "plugins": [
21 | "istanbul"
22 | ]
23 | }
24 | }
25 | }
26 |
--------------------------------------------------------------------------------
/.editorconfig:
--------------------------------------------------------------------------------
1 | root = true
2 |
3 | [*]
4 | charset = utf-8
5 | indent_style = space
6 | indent_size = 2
7 | end_of_line = lf
8 | insert_final_newline = true
9 | trim_trailing_whitespace = true
10 |
--------------------------------------------------------------------------------
/.eslintignore:
--------------------------------------------------------------------------------
1 | dist/*.js
2 |
--------------------------------------------------------------------------------
/.eslintrc.js:
--------------------------------------------------------------------------------
1 | module.exports = {
2 | root: true,
3 | parser: 'babel-eslint',
4 | parserOptions: {
5 | sourceType: 'module'
6 | },
7 | extends: 'vue',
8 | // add your custom rules here
9 | 'rules': {
10 | // allow async-await
11 | 'generator-star-spacing': 0,
12 | // allow debugger during development
13 | 'no-debugger': process.env.NODE_ENV === 'production' ? 2 : 0
14 | },
15 | globals: {
16 | requestAnimationFrame: true,
17 | performance: true
18 | }
19 | }
20 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .DS_Store
2 | node_modules/
3 | npm-debug.log
4 | test/coverage
5 | dist
6 | yarn-error.log
7 | reports
8 |
--------------------------------------------------------------------------------
/.stylelintrc:
--------------------------------------------------------------------------------
1 | {
2 | "processors": ["stylelint-processor-html"],
3 | "extends": "stylelint-config-standard",
4 | "rules": {
5 | "no-empty-source": null
6 | }
7 | }
8 |
--------------------------------------------------------------------------------
/CONTRIBUTING.md:
--------------------------------------------------------------------------------
1 | # Contributing
2 |
3 | Contributions are **welcome** and will be fully **credited**.
4 |
5 | We accept contributions via Pull Requests on [Github](https://github.com/mbackonja/vue-simple-markdown).
6 |
7 |
8 | ## Pull Requests
9 |
10 | - **Keep the same style** - eslint will automatically be ran before committing
11 |
12 | - **Tip** to pass lint tests easier use the `npm run lint:fix` command
13 |
14 | - **Add tests!** - Your patch won't be accepted if it doesn't have tests.
15 |
16 | - **Document any change in behaviour** - Make sure the `README.md` and any other relevant documentation are kept up-to-date.
17 |
18 | - **Consider our release cycle** - We try to follow [SemVer v2.0.0](http://semver.org/). Randomly breaking public APIs is not an option.
19 |
20 | - **Create feature branches** - Don't ask us to pull from your master branch.
21 |
22 | - **One pull request per feature** - If you want to do more than one thing, send multiple pull requests.
23 |
24 | - **Send coherent history** - Make sure your commits message means something
25 |
26 |
27 | ## Running Tests
28 |
29 | Launch visual tests and watch the components at the same time
30 |
31 | ``` bash
32 | $ npm run dev
33 | ```
34 |
35 |
36 | **Happy coding**!
37 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2017 Milan Bačkonja
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy of
6 | this software and associated documentation files (the "Software"), to deal in
7 | the Software without restriction, including without limitation the rights to
8 | use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9 | the Software, and to permit persons to whom the Software is furnished to do so,
10 | subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17 | FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18 | COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19 | IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20 | CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # VueSimpleMarkdown
2 |
3 | [](https://www.npmjs.com/package/vue-simple-markdown) [](https://vuejs.org/)
4 |
5 | > A Simple and Highspeed Markdown Parser for Vue
6 |
7 | ## Installation
8 |
9 | ```bash
10 | npm install --save vue-simple-markdown
11 | ```
12 |
13 | ## Usage
14 |
15 | ### Bundler (Webpack, Rollup)
16 |
17 | ```js
18 | import Vue from 'vue'
19 | import VueSimpleMarkdown from 'vue-simple-markdown'
20 | // You need a specific loader for CSS files like https://github.com/webpack/css-loader
21 | import 'vue-simple-markdown/dist/vue-simple-markdown.css'
22 |
23 | Vue.use(VueSimpleMarkdown)
24 | ```
25 |
26 | ### Browser
27 |
28 | ```html
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 | ```
38 |
39 | ### Syntax
40 | ```
41 |
42 | ```
43 | ### Props
44 |
45 | | Prop | Type | Default | Describe |
46 | | ---- | ---- | ------- | ------- |
47 | | source | String | '' | The markdown source code |
48 | | emoji | Boolean | `true` | `:)` => `😃` |
49 | | heading | Boolean | `true` | `#` => `
`, `##` => ``... |
50 | | highlight | Boolean | `true` | SyntaxHighlighter ([highlightjs](https://www.npmjs.com/package/highlightjs)) |
51 | | horizontal-line | Boolean | `true` | `***` or `___` or `---` => `
` |
52 | | image | Boolean | `true` | `` |
53 | | inline-code | Boolean | `true` | \`someCode\` => `someCode` |
54 | | italic | Boolean | `true` | `*text*` or `_text_` => *text* |
55 | | linkify | Boolean | `true` | Autoconvert URL-like text to link |
56 | | link | Boolean | `true` | `[Github](https://github.com/)` => [Github](https://github.com/) |
57 | | lists | Boolean | `true` | Lists, see [here](#lists) |
58 | | strong | Boolean | `true` | `**text**` or `__text__` => __text__ |
59 | | blockquote | Boolean | `true` | Blockquotes, see [here](#blockquotes) |
60 | | table | Boolean | `true` | Tables, see [here](#tables) |
61 | | prerender | Function | `(source) => return { source }` | Function executed before rendering process |
62 | | postrender | Function | `(html) => { return html }` | Function executed after rendering process |
63 |
64 | ### Lists
65 | #### Unordered list
66 |
67 | Start list with characters `*`, `+` or `-`
68 | Number of spaces before that character => nesting level
69 |
70 | ```
71 | * First nesting level
72 | * Second nesting level
73 | * Third nesting level
74 | * Tenth nesting level
75 | * Again third nesting level
76 | ```
77 | #### Ordered list
78 |
79 | Start list with number and dot. At example `1.`
80 | Number of spaces before that character => nesting level
81 |
82 | ```
83 | 1. First nesting level
84 | 1. Second nesting level
85 | 1. Third nesting level
86 | 1. Tenth nesting level
87 | 2. Again third nesting level
88 | ```
89 |
90 | ### Blockquotes
91 | ```
92 | > First nesting level
93 | >> Second nesting level
94 | >>> Third nesting level
95 | >>>>>>>>>> Tenth nesting level
96 | >>> Again third nesting level
97 | ```
98 |
99 | ### Tables
100 | A table is an arrangement of data with rows and columns, consisting of a single header row, a delimiter row separating the header from the data, and zero or more data rows.
101 | Each row must start and end with pipes (`|`) and it consists of cells containing arbitrary text, in which inlines are parsed, separated by pipes (`|`). Spaces between pipes and cell content are trimmed. Block-level elements cannot be inserted in a table.
102 | Example:
103 | ```
104 | | Foo | Bar |
105 | |-----|-----|
106 | | Bam | Baz |
107 | ```
108 | | Foo | Bar |
109 | |-----|-----|
110 | | Baz | Bim |
111 |
112 | You can use colon (`:`) in the delimiter row to determine content alignment of the corresponding column.
113 | Example:
114 | ```
115 | | Align left | Align Right | Align Center | Default |
116 | |:-----------|-:|:---:|--|
117 | | Some text| Some text | Some | alignment |
118 | | aligned to| aligned to | text |
119 | | the left side| the right side| in the center |
120 | ```
121 | | Align left | Align Right | Align Center | Default |
122 | |:-----------|-:|:---:|--|
123 | | Some text| Some text | Some | alignment |
124 | | aligned to| aligned to | text |
125 | | the left side| the right side| in the center |
126 |
127 | Number of columns in each row in the body of the table may vary.
128 | Example:
129 | ```
130 | | Column A | Column B | Column C |
131 | |-|-|-|
132 | | You can have | | empty cells |
133 | | This row | is too short |
134 | | This row | has | too many | cells |
135 | ```
136 | | Column A | Column B | Column C |
137 | |-|-|-|
138 | | You can have | | empty cells |
139 | | This row | is too short |
140 | | This row | has | too many | cells |
141 |
142 |
143 | ## Development
144 |
145 | ### Launch visual tests
146 |
147 | ```bash
148 | npm run dev
149 | ```
150 |
151 | ### Launch Karma with coverage
152 |
153 | ```bash
154 | npm run dev:coverage
155 | ```
156 |
157 | ### Build
158 |
159 | Bundle the js and css of to the `dist` folder:
160 |
161 | ```bash
162 | npm run build
163 | ```
164 |
165 |
166 | ## Publishing
167 |
168 | The `prepublish` hook will ensure dist files are created before publishing. This
169 | way you don't need to commit them in your repository.
170 |
171 | ```bash
172 | # Bump the version first
173 | # It'll also commit it and create a tag
174 | npm version
175 | # Push the bumped package and tags
176 | git push --follow-tags
177 | # Ship it 🚀
178 | npm publish
179 | ```
180 |
181 | ## License
182 |
183 | [MIT](http://opensource.org/licenses/MIT)
184 |
--------------------------------------------------------------------------------
/build/utils/index.js:
--------------------------------------------------------------------------------
1 | const ExtractTextPlugin = require('extract-text-webpack-plugin')
2 | const { join } = require('path')
3 |
4 | const {
5 | red,
6 | logError
7 | } = require('./log')
8 |
9 | const {
10 | processStyle
11 | } = require('./style')
12 |
13 | const uppercamelcase = require('uppercamelcase')
14 |
15 | exports.write = require('./write')
16 |
17 | const {
18 | author,
19 | name,
20 | version,
21 | dllPlugin
22 | } = require('../../package.json')
23 |
24 | const authorName = author.replace(/\s+<.*/, '')
25 | const minExt = process.env.NODE_ENV === 'production' ? '.min' : ''
26 |
27 | exports.author = authorName
28 | exports.version = version
29 | exports.dllName = dllPlugin.name
30 | exports.moduleName = uppercamelcase(name)
31 | exports.name = name
32 | exports.filename = name + minExt
33 | exports.banner = `/*!
34 | * ${name} v${version}
35 | * (c) ${new Date().getFullYear()} ${authorName}
36 | * Released under the MIT License.
37 | */
38 | `
39 |
40 | // log.js
41 | exports.red = red
42 | exports.logError = logError
43 |
44 | // It'd be better to add a sass property to the vue-loader options
45 | // but it simply don't work
46 | const sassOptions = {
47 | includePaths: [
48 | join(__dirname, '../../node_modules')
49 | ]
50 | }
51 |
52 | // don't extract css in test mode
53 | const nullLoader = process.env.NODE_ENV === 'common' ? 'null-loader!' : ''
54 | exports.vueLoaders =
55 | process.env.BABEL_ENV === 'test' ? {
56 | css: 'css-loader',
57 | scss: `css-loader!sass-loader?${JSON.stringify(sassOptions)}`
58 | } : {
59 | css: ExtractTextPlugin.extract(`${nullLoader}css-loader`),
60 | scss: ExtractTextPlugin.extract(
61 | `${nullLoader}css-loader!sass-loader?${JSON.stringify(sassOptions)}`
62 | )
63 | }
64 |
65 | // style.js
66 | exports.processStyle = processStyle
67 |
--------------------------------------------------------------------------------
/build/utils/log.js:
--------------------------------------------------------------------------------
1 | function logError (e) {
2 | console.log(e)
3 | }
4 |
5 | function blue (str) {
6 | return `\x1b[1m\x1b[34m${str}\x1b[39m\x1b[22m`
7 | }
8 |
9 | function green (str) {
10 | return `\x1b[1m\x1b[32m${str}\x1b[39m\x1b[22m`
11 | }
12 |
13 | function red (str) {
14 | return `\x1b[1m\x1b[31m${str}\x1b[39m\x1b[22m`
15 | }
16 |
17 | function yellow (str) {
18 | return `\x1b[1m\x1b[33m${str}\x1b[39m\x1b[22m`
19 | }
20 |
21 | module.exports = {
22 | blue,
23 | green,
24 | red,
25 | yellow,
26 | logError
27 | }
28 |
--------------------------------------------------------------------------------
/build/utils/style.js:
--------------------------------------------------------------------------------
1 | const path = require('path')
2 | const postcss = require('postcss')
3 | const cssnext = require('postcss-cssnext')
4 | const CleanCSS = require('clean-css')
5 | const { logError } = require('./log.js')
6 | const write = require('./write.js')
7 |
8 | function processCss (style) {
9 | const componentName = path.basename(style.id, '.vue')
10 | return postcss([cssnext()])
11 | .process(style.code, {})
12 | .then(result => {
13 | return {
14 | name: componentName,
15 | css: result.css,
16 | map: result.map
17 | }
18 | })
19 | }
20 |
21 | let stylus
22 | function processStylus (style) {
23 | try {
24 | stylus = stylus || require('stylus')
25 | } catch (e) {
26 | logError(e)
27 | }
28 | const componentName = path.basename(style.id, '.vue')
29 | return new Promise((resolve, reject) => {
30 | stylus.render(style.code, function (err, css) {
31 | if (err) return reject(err)
32 | resolve({
33 | original: {
34 | code: style.code,
35 | ext: 'styl'
36 | },
37 | name: componentName,
38 | css
39 | })
40 | })
41 | })
42 | }
43 |
44 | function processStyle (style) {
45 | if (style.lang === 'css') {
46 | return processCss(style)
47 | } else if (style.lang === 'stylus') {
48 | return processStylus(style)
49 | } else {
50 | throw new Error(`Unknown style language '${style.lang}'`)
51 | }
52 | }
53 |
54 | function writeCss (style) {
55 | write(`dist/${style.name}.css`, style.css)
56 | if (style.original) {
57 | write(`dist/${style.name}.${style.original.ext}`, style.original.code)
58 | }
59 | if (style.map) write(`dist/${style.name}.css.map`, style.map)
60 | write(`dist/${style.name}.min.css`, new CleanCSS().minify(style.css).styles)
61 | }
62 |
63 | module.exports = {
64 | writeCss,
65 | processStyle
66 | }
67 |
--------------------------------------------------------------------------------
/build/utils/write.js:
--------------------------------------------------------------------------------
1 | const fs = require('fs')
2 |
3 | const { blue } = require('./log.js')
4 |
5 | function write (dest, code) {
6 | return new Promise(function (resolve, reject) {
7 | fs.writeFile(dest, code, function (err) {
8 | if (err) return reject(err)
9 | console.log(blue(dest) + ' ' + getSize(code))
10 | resolve(code)
11 | })
12 | })
13 | }
14 |
15 | function getSize (code) {
16 | return (code.length / 1024).toFixed(2) + 'kb'
17 | }
18 |
19 | module.exports = write
20 |
--------------------------------------------------------------------------------
/build/webpack.config.base.js:
--------------------------------------------------------------------------------
1 | const webpack = require('webpack')
2 | const ExtractTextPlugin = require('extract-text-webpack-plugin')
3 | const { resolve } = require('path')
4 |
5 | const {
6 | banner,
7 | filename,
8 | version,
9 | vueLoaders
10 | } = require('./utils')
11 |
12 | const plugins = [
13 | new webpack.DefinePlugin({
14 | '__VERSION__': JSON.stringify(version),
15 | 'process.env.NODE_ENV': '"test"'
16 | }),
17 | new webpack.BannerPlugin({ banner, raw: true, entryOnly: true }),
18 | new ExtractTextPlugin({
19 | filename: `${filename}.css`,
20 | // Don't extract css in test mode
21 | disable: /^(common|test)$/.test(process.env.NODE_ENV)
22 | })
23 | ]
24 |
25 | module.exports = {
26 | output: {
27 | path: resolve(__dirname, '../dist'),
28 | filename: `${filename}.common.js`
29 | },
30 | entry: './src/index.js',
31 | resolve: {
32 | extensions: ['.js', '.vue', '.jsx', 'css'],
33 | alias: {
34 | 'src': resolve(__dirname, '../src')
35 | }
36 | },
37 | module: {
38 | rules: [
39 | {
40 | test: /.jsx?$/,
41 | use: 'babel-loader',
42 | exclude: /node_modules/
43 | },
44 | {
45 | test: /\.vue$/,
46 | loader: 'vue-loader',
47 | options: {
48 | loaders: vueLoaders,
49 | postcss: [require('postcss-cssnext')()]
50 | }
51 | }
52 | ]
53 | },
54 | externals: /highlightjs|node-emoji/,
55 | plugins
56 | }
57 |
--------------------------------------------------------------------------------
/build/webpack.config.browser.js:
--------------------------------------------------------------------------------
1 | const merge = require('webpack-merge')
2 | const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
3 | const base = require('./webpack.config.base')
4 | const { resolve } = require('path')
5 | const {
6 | filename,
7 | moduleName,
8 | vueLoaders
9 | } = require('./utils')
10 |
11 | module.exports = merge(base, {
12 | output: {
13 | filename: `${filename}.js`,
14 | library: moduleName,
15 | libraryTarget: 'umd'
16 | },
17 | module: {
18 | rules: [
19 | {
20 | test: /.scss$/,
21 | use: vueLoaders.scss,
22 | include: [
23 | resolve(__dirname, '../node_modules/@material'),
24 | resolve(__dirname, '../src')
25 | ]
26 | }
27 | ]
28 | },
29 | plugins: [
30 | new BundleAnalyzerPlugin({
31 | analyzerMode: 'static',
32 | openAnalyzer: false,
33 | reportFilename: resolve(__dirname, `../reports/${process.env.NODE_ENV}.html`)
34 | })
35 | ]
36 | })
37 |
--------------------------------------------------------------------------------
/build/webpack.config.common.js:
--------------------------------------------------------------------------------
1 | const merge = require('webpack-merge')
2 | const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
3 | const base = require('./webpack.config.base')
4 | const { resolve } = require('path')
5 | const { vueLoaders } = require('./utils')
6 |
7 | module.exports = merge(base, {
8 | output: {
9 | libraryTarget: 'commonjs2'
10 | },
11 | target: 'node',
12 | module: {
13 | rules: [
14 | {
15 | test: /.scss$/,
16 | use: vueLoaders.scss,
17 | include: [
18 | resolve(__dirname, '../node_modules/@material'),
19 | resolve(__dirname, '../src')
20 | ]
21 | }
22 | ]
23 | },
24 | plugins: [
25 | new BundleAnalyzerPlugin({
26 | analyzerMode: 'static',
27 | openAnalyzer: false,
28 | reportFilename: resolve(__dirname, `../reports/${process.env.NODE_ENV}.html`)
29 | })
30 | ]
31 | })
32 |
--------------------------------------------------------------------------------
/build/webpack.config.dev.js:
--------------------------------------------------------------------------------
1 | const webpack = require('webpack')
2 | const merge = require('webpack-merge')
3 | const HtmlWebpackPlugin = require('html-webpack-plugin')
4 | const AddAssetHtmlPlugin = require('add-asset-html-webpack-plugin')
5 | const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
6 | const DashboardPlugin = require('webpack-dashboard/plugin')
7 | const base = require('./webpack.config.base')
8 | const { resolve, join } = require('path')
9 | const { existsSync } = require('fs')
10 | const {
11 | dllName,
12 | logError,
13 | red,
14 | vueLoaders
15 | } = require('./utils')
16 |
17 | const rootDir = resolve(__dirname, '../test')
18 | const buildPath = resolve(rootDir, 'dist')
19 |
20 | if (!existsSync(join(buildPath, dllName) + '.dll.js')) {
21 | logError(red('The DLL manifest is missing. Please run `npm run build:dll` (Quit this with `q`)'))
22 | process.exit(1)
23 | }
24 |
25 | const dllManifest = require(
26 | join(buildPath, dllName) + '.json'
27 | )
28 |
29 | module.exports = merge(base, {
30 | entry: {
31 | tests: resolve(rootDir, 'visual.js')
32 | },
33 | output: {
34 | path: buildPath,
35 | filename: '[name].js',
36 | chunkFilename: '[id].js'
37 | },
38 | module: {
39 | rules: [
40 | {
41 | test: /.scss$/,
42 | loader: vueLoaders.scss,
43 | include: [
44 | resolve(__dirname, '../node_modules/@material'),
45 | resolve(__dirname, '../src')
46 | ]
47 | }
48 | ]
49 | },
50 | plugins: [
51 | new webpack.DllReferencePlugin({
52 | context: join(__dirname, '..'),
53 | manifest: dllManifest
54 | }),
55 | new HtmlWebpackPlugin({
56 | chunkSortMode: 'dependency'
57 | }),
58 | new AddAssetHtmlPlugin({
59 | filepath: require.resolve(
60 | join(buildPath, dllName) + '.dll.js'
61 | )
62 | }),
63 | new webpack.optimize.CommonsChunkPlugin({
64 | name: 'vendor',
65 | minChunks (module, count) {
66 | return (
67 | module.resource &&
68 | /\.js$/.test(module.resource) &&
69 | module.resource.indexOf(join(__dirname, '../node_modules/')) === 0
70 | )
71 | }
72 | }),
73 | new webpack.optimize.CommonsChunkPlugin({
74 | name: 'manifest',
75 | chunks: ['vendor']
76 | }),
77 | new DashboardPlugin(),
78 | new BundleAnalyzerPlugin({
79 | analyzerMode: 'static',
80 | openAnalyzer: false,
81 | reportFilename: resolve(__dirname, `../reports/${process.env.NODE_ENV}.html`)
82 | })
83 | ],
84 | devtool: '#eval-source-map',
85 | devServer: {
86 | inline: true,
87 | stats: {
88 | colors: true,
89 | chunks: false,
90 | cached: false
91 | },
92 | contentBase: buildPath
93 | },
94 | performance: {
95 | hints: false
96 | }
97 | })
98 |
--------------------------------------------------------------------------------
/build/webpack.config.dll.js:
--------------------------------------------------------------------------------
1 | const { resolve, join } = require('path')
2 | const webpack = require('webpack')
3 | const pkg = require('../package.json')
4 |
5 | const rootDir = resolve(__dirname, '../test')
6 | const buildPath = resolve(rootDir, 'dist')
7 |
8 | const entry = {}
9 | entry[pkg.dllPlugin.name] = pkg.dllPlugin.include
10 |
11 | module.exports = {
12 | devtool: '#source-map',
13 | entry,
14 | output: {
15 | path: buildPath,
16 | filename: '[name].dll.js',
17 | library: '[name]'
18 | },
19 | plugins: [
20 | new webpack.DllPlugin({
21 | name: '[name]',
22 | path: join(buildPath, '[name].json')
23 | })
24 | ],
25 | performance: {
26 | hints: false
27 | }
28 | }
29 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "vue-simple-markdown",
3 | "version": "1.1.5",
4 | "description": "A Simple and Highspeed Markdown Parser for Vue",
5 | "author": "Milan Bačkonja ",
6 | "main": "dist/vue-simple-markdown.common.js",
7 | "module": "dist/vue-simple-markdown.esm.js",
8 | "browser": "dist/vue-simple-markdown.js",
9 | "unpkg": "dist/vue-simple-markdown.js",
10 | "style": "dist/vue-simple-markdown.css",
11 | "files": [
12 | "dist",
13 | "src"
14 | ],
15 | "scripts": {
16 | "clean": "rimraf dist",
17 | "build": "yon run build:common && yon run build:browser && yon run build:browser:min",
18 | "build:common": "cross-env NODE_ENV=common webpack --config build/webpack.config.common.js --progress --hide-modules",
19 | "build:browser:base": "webpack --config build/webpack.config.browser.js --progress --hide-modules",
20 | "build:browser": "cross-env NODE_ENV=browser yon run build:browser:base",
21 | "build:browser:min": "cross-env NODE_ENV=production yon run build:browser:base -- -p",
22 | "build:dll": "webpack --progress --config build/webpack.config.dll.js",
23 | "lint": "yon run lint:js && yon run lint:css",
24 | "lint:js": "eslint --ext js --ext jsx --ext vue src test/**/*.spec.js test/*.js build",
25 | "lint:js:fix": "yon run lint:js -- --fix",
26 | "lint:css": "stylelint src/**/*.{vue,css}",
27 | "lint:staged": "lint-staged",
28 | "pretest": "yon run lint",
29 | "test": "cross-env BABEL_ENV=test karma start test/karma.conf.js --single-run",
30 | "dev": "webpack-dashboard -- webpack-dev-server --config build/webpack.config.dev.js --open",
31 | "dev:coverage": "cross-env BABEL_ENV=test karma start test/karma.conf.js",
32 | "prepublish": "yon run build"
33 | },
34 | "lint-staged": {
35 | "*.{vue,jsx,js}": [
36 | "eslint --fix"
37 | ],
38 | "*.{vue,css}": [
39 | "stylefmt",
40 | "stylelint"
41 | ]
42 | },
43 | "pre-commit": "lint:staged",
44 | "devDependencies": {
45 | "add-asset-html-webpack-plugin": "^2.0.0",
46 | "babel-core": "^6.24.0",
47 | "babel-eslint": "^7.2.0",
48 | "babel-helper-vue-jsx-merge-props": "^2.0.0",
49 | "babel-loader": "^7.0.0",
50 | "babel-plugin-istanbul": "^4.1.0",
51 | "babel-plugin-syntax-jsx": "^6.18.0",
52 | "babel-plugin-transform-object-rest-spread": "^6.23.0",
53 | "babel-plugin-transform-runtime": "^6.23.0",
54 | "babel-plugin-transform-vue-jsx": "^3.4.0",
55 | "babel-preset-env": "^1.4.0",
56 | "chai": "^3.5.0",
57 | "chai-dom": "^1.4.0",
58 | "cross-env": "^4.0.0",
59 | "css-loader": "^0.28.0",
60 | "eslint": "^3.19.0",
61 | "eslint-config-vue": "^2.0.0",
62 | "eslint-plugin-vue": "^2.0.0",
63 | "extract-text-webpack-plugin": "^2.1.0",
64 | "html-webpack-plugin": "^2.28.0",
65 | "karma": "^1.7.0",
66 | "karma-chai-dom": "^1.1.0",
67 | "karma-chrome-launcher": "^2.1.0",
68 | "karma-coverage": "^1.1.0",
69 | "karma-mocha": "^1.3.0",
70 | "karma-sinon-chai": "^1.3.0",
71 | "karma-sourcemap-loader": "^0.3.7",
72 | "karma-spec-reporter": "^0.0.31",
73 | "karma-webpack": "^2.0.0",
74 | "lint-staged": "^3.4.0",
75 | "mocha": "^3.3.0",
76 | "mocha-css": "^1.0.1",
77 | "node-sass": "^4.5.3",
78 | "null-loader": "^0.1.1",
79 | "postcss": "^6.0.0",
80 | "postcss-cssnext": "^2.10.0",
81 | "pre-commit": "^1.2.0",
82 | "rimraf": "^2.6.0",
83 | "sass-loader": "^6.0.6",
84 | "sinon": "2.2.0",
85 | "sinon-chai": "^2.10.0",
86 | "style-loader": "^0.17.0",
87 | "stylefmt": "^5.3.0",
88 | "stylelint": "^7.10.0",
89 | "stylelint-config-standard": "^16.0.0",
90 | "stylelint-processor-html": "^1.0.0",
91 | "uppercamelcase": "^3.0.0",
92 | "vue": "^2.3.0",
93 | "vue-loader": "^12.0.0",
94 | "vue-template-compiler": "^2.3.0",
95 | "webpack": "^2.5.0",
96 | "webpack-bundle-analyzer": "^2.4.0",
97 | "webpack-dashboard": "^0.4.0",
98 | "webpack-dev-server": "^2.4.0",
99 | "webpack-merge": "^4.0.0",
100 | "yarn-or-npm": "^2.0.0"
101 | },
102 | "peerDependencies": {
103 | "vue": "^2.3.0"
104 | },
105 | "dllPlugin": {
106 | "name": "vuePluginTemplateDeps",
107 | "include": [
108 | "mocha/mocha.js",
109 | "style-loader!css-loader!mocha-css",
110 | "html-entities",
111 | "vue/dist/vue.js",
112 | "chai",
113 | "core-js/library",
114 | "url",
115 | "sockjs-client",
116 | "vue-style-loader/lib/addStylesClient.js",
117 | "events",
118 | "ansi-html",
119 | "style-loader/addStyles.js"
120 | ]
121 | },
122 | "repository": {
123 | "type": "git",
124 | "url": "git+https://github.com/Vivify-Ideas/vue-simple-markdown.git"
125 | },
126 | "bugs": {
127 | "url": "https://github.com/Vivify-Ideas/vue-simple-markdown/issues"
128 | },
129 | "homepage": "https://github.com/Vivify-Ideas/vue-simple-markdown#readme",
130 | "license": {
131 | "type": "MIT",
132 | "url": "http://www.opensource.org/licenses/mit-license.php"
133 | },
134 | "dependencies": {
135 | "github-markdown-css": "^2.8.0",
136 | "highlightjs": "^9.10.0",
137 | "node-emoji": "^1.8.1"
138 | }
139 | }
140 |
--------------------------------------------------------------------------------
/src/index.js:
--------------------------------------------------------------------------------
1 | import VueSimpleMarkdown from './vue-simple-markdown.component.vue'
2 |
3 | function plugin (Vue) {
4 | Vue.component('vue-simple-markdown', VueSimpleMarkdown)
5 | }
6 |
7 | // Install by default if using the script tag
8 | if (typeof window !== 'undefined' && window.Vue) {
9 | window.Vue.use(plugin)
10 | }
11 |
12 | export default plugin
13 | const version = '__VERSION__'
14 | // Export all components too
15 | export {
16 | VueSimpleMarkdown,
17 | version
18 | }
19 |
--------------------------------------------------------------------------------
/src/rules/emoji.js:
--------------------------------------------------------------------------------
1 | import NodeEmoji from 'node-emoji'
2 |
3 | const SHORTCUTS = {
4 | angry: ['>:(', '>:-('],
5 | blush: [':")', ':-")'],
6 | broken_heart: ['3', '<\\3'],
7 | confused: [':/', ':-/', ':\\', ':-\\'],
8 | cry: [":'(", ":'-(", ':,(', ':,-('],
9 | frowning: [':(', ':-('],
10 | heart: ['<3'],
11 | imp: [']:(', ']:-('],
12 | innocent: ['o:)', 'O:)', 'o:-)', 'O:-)', '0:)', '0:-)'],
13 | joy: [":')", ":'-)", ':,)', ':,-)', ":'D", ":'-D", ':,D', ':,-D'],
14 | kissing: [':*', ':-*'],
15 | laughing: ['x-)', 'X-)'],
16 | neutral_face: [':|', ':-|'],
17 | open_mouth: [':o', ':-o', ':O', ':-O'],
18 | rage: [':@', ':-@'],
19 | smile: [':D', ':-D'],
20 | smiley: [':)', ':-)'],
21 | smiling_imp: [']:)', ']:-)'],
22 | sob: [":,'(", ":,'-(", ';(', ';-('],
23 | stuck_out_tongue: [':P', ':-P'],
24 | sunglasses: ['8-)', 'B-)'],
25 | sweat: [',:(', ',:-('],
26 | sweat_smile: [',:)', ',:-)'],
27 | unamused: [':s', ':-S', ':z', ':-Z', ':$', ':-$'],
28 | wink: [';)', ';-)']
29 | }
30 |
31 | export class Emoji {
32 | static get RULE_NAME () { return 'emoji' }
33 |
34 | static parse (source) {
35 | for (const emoji in SHORTCUTS) {
36 | SHORTCUTS[emoji].forEach((shortcut) => {
37 | shortcut = shortcut.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g, '\\$&')
38 | let regex = `(^|\\s)${shortcut}(?![\\w\\/])`
39 | regex = new RegExp(regex, 'g')
40 |
41 | source = source.replace(regex, (all, before) => {
42 | return `${before}:${emoji}:`
43 | })
44 | })
45 | }
46 |
47 | return NodeEmoji.emojify(source)
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/src/rules/heading.js:
--------------------------------------------------------------------------------
1 | const HEADINGS_REGEX = /^(#{1,6}) (.+)$/
2 |
3 | export class Heading {
4 | static get RULE_NAME () { return 'heading' }
5 |
6 | static parse (source) {
7 | const lines = source.split('\n')
8 | lines.forEach((line, index, lines) => {
9 | if (HEADINGS_REGEX.test(line)) {
10 | const match = HEADINGS_REGEX.exec(line)
11 | lines[index] = line.replace(HEADINGS_REGEX, '$2')
12 | }
13 | })
14 |
15 | return lines.join('\n')
16 | }
17 | }
18 |
--------------------------------------------------------------------------------
/src/rules/highlight.js:
--------------------------------------------------------------------------------
1 | import { Utils } from './../utils'
2 | import highlightjs from 'highlightjs'
3 |
4 | const CODE_BLOCK_REGEX = /([^```]*)``` ?(\w*)([\s\S]+?)```([^```]*)/g
5 |
6 | export class Highlight {
7 | static get RULE_NAME () { return 'highlight' }
8 |
9 | static parse (source) {
10 | if (!source.match(CODE_BLOCK_REGEX)) {
11 | return Utils.escapeTagStart(source)
12 | }
13 |
14 | return source.replace(CODE_BLOCK_REGEX, (all, sourceBeforeCode, language, source, sourceAfterCode) => {
15 | source = source.replace(/^\n+|\n+$/g, '')
16 |
17 | if (language && highlightjs.getLanguage(language)) {
18 | return `${Utils.escapeTagStart(sourceBeforeCode)}${Utils.escapeContent(highlightjs.highlight(language, source).value)}
${Utils.escapeTagStart(sourceAfterCode)}`
19 | }
20 |
21 | return `${Utils.escapeTagStart(sourceBeforeCode)}${Utils.escapeContent(highlightjs.highlightAuto(source).value)}
${Utils.escapeTagStart(sourceAfterCode)}`
22 | })
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/src/rules/horizontal-line.js:
--------------------------------------------------------------------------------
1 | const HORIZONTAL_LINE_REGEX = /^(\*{3}|_{3}|-{3})$/
2 |
3 | export class HorizontalLine {
4 | static get RULE_NAME () { return 'horizontalLine' }
5 |
6 | static parse (source) {
7 | const lines = source.split('\n')
8 | lines.forEach((line, index, lines) => {
9 | lines[index] = line.replace(HORIZONTAL_LINE_REGEX, '
')
10 | })
11 |
12 | return lines.join('\n')
13 | }
14 | }
15 |
--------------------------------------------------------------------------------
/src/rules/img.js:
--------------------------------------------------------------------------------
1 | import { Utils } from './../utils'
2 |
3 | const IMG_REGEX = /!\[(.*)\]\(((?:(http[s]?|ftp)?:?\/{0,2})[\w\/\-+?#=.:]+)\)/g
4 |
5 | export class Img {
6 | static get RULE_NAME () { return 'images' }
7 |
8 | static parse (source) {
9 | return source.replace(IMG_REGEX, (match, alt, src) => {
10 | return `
`
11 | })
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/rules/index.js:
--------------------------------------------------------------------------------
1 | import { Strong } from './strong'
2 | import { Italic } from './italic'
3 | import { Img } from './img'
4 | import { Link } from './link'
5 | import { Heading } from './heading'
6 | import { HorizontalLine } from './horizontal-line'
7 | import { Lists } from './lists'
8 | import { Emoji } from './emoji'
9 | import { InlineCode } from './inline-code'
10 | import { Highlight } from './highlight'
11 | import { Linkify } from './linkify'
12 | import { Quote } from './quote'
13 | import { Table } from './table'
14 |
15 | const RULES = [
16 | Highlight,
17 | InlineCode,
18 | HorizontalLine,
19 | Lists,
20 | Quote,
21 | Strong,
22 | Italic,
23 | Img,
24 | Link,
25 | Linkify,
26 | Heading,
27 | Emoji,
28 | InlineCode,
29 | Table
30 | ]
31 |
32 | export {
33 | RULES,
34 | Highlight,
35 | InlineCode,
36 | HorizontalLine,
37 | Lists,
38 | Quote,
39 | Strong,
40 | Italic,
41 | Img,
42 | Link,
43 | Linkify,
44 | Heading,
45 | Emoji,
46 | Table
47 | }
48 |
--------------------------------------------------------------------------------
/src/rules/inline-code.js:
--------------------------------------------------------------------------------
1 | import { Utils } from './../utils'
2 |
3 | const INLINE_CODE_REGEX = /`(.+?)`/g
4 |
5 | export class InlineCode {
6 | static get RULE_NAME () { return 'inlineCode' }
7 |
8 | static parse (source) {
9 | return source.replace(INLINE_CODE_REGEX, (all, content) => {
10 | return `${Utils.escapeContent(content)}
`
11 | })
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/rules/italic.js:
--------------------------------------------------------------------------------
1 | const ITALIC_REGEX_1 = /(^|\s|"|')(?:_)(.+?)(?:_)/g
2 | const ITALIC_REGEX_2 = /(^|\s|"|')(?:\*)(.+?)(?:\*)/g
3 |
4 | export class Italic {
5 | static get RULE_NAME () { return 'italic' }
6 |
7 | static parse (source) {
8 | source = source.replace(ITALIC_REGEX_1, '$1$2')
9 | return source.replace(ITALIC_REGEX_2, '$1$2')
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/rules/link.js:
--------------------------------------------------------------------------------
1 | const LINK_REGEX = /\[(.+?)\]\(((?:(?:http[s]?|ftp):\/{2})?)([\w\/\-+?#=.:;!%&]+)\)/g
2 | export class Link {
3 | static get RULE_NAME () { return 'link' }
4 |
5 | static parse (source) {
6 | return source.replace(LINK_REGEX, (match, linkName, urlProtocolDomain, urlPath) => {
7 | const url = urlProtocolDomain.trim() + urlPath.trim().replace(/:/g, '%3A')
8 |
9 | return `${linkName}`
10 | })
11 | }
12 | }
13 |
--------------------------------------------------------------------------------
/src/rules/linkify.js:
--------------------------------------------------------------------------------
1 | const LINK_REGEX = /(^|\s|>)((?:http(?:s)?:\/\/.)(?:www\.)?[-a-zA-Z0-9@:%._\+~#=]{2,256}\.[a-z]{2,6}(?::\d+)?)\b([-a-zA-Z0-9@:;%_\+.~#?!&//=]*)/g
2 | export class Linkify {
3 | static get RULE_NAME () { return 'linkify' }
4 |
5 | static parse (source) {
6 | return source.replace(LINK_REGEX, (all, before, urlProtocolDomain, urlPath) => {
7 | const url = urlProtocolDomain.trim() + urlPath.trim().replace(/:/g, '%3A')
8 | const href = url.substr(0, 4) !== 'http' ? `http://${url}` : url
9 |
10 | return `${before}${url}`
11 | })
12 | }
13 | }
14 |
--------------------------------------------------------------------------------
/src/rules/lists.js:
--------------------------------------------------------------------------------
1 | const UNORDERED_LIST_REGEX = /^( *)[\*\+\-] +(.*)/
2 | const ORDERED_LIST_REGEX = /^( *)\d+\. (.+)/
3 |
4 | export class Lists {
5 | static get RULE_NAME () { return 'lists' }
6 |
7 | static parse (source) {
8 | source = this.parseList(source, UNORDERED_LIST_REGEX, 'ul')
9 | source = this.parseList(source, ORDERED_LIST_REGEX, 'ol')
10 | return source
11 | }
12 |
13 | static parseList (source, regex, tag) {
14 | const lines = source.split('\n')
15 | let inList = false
16 | let listNestingLevel = 0
17 |
18 | lines.forEach((line, index) => {
19 | if (regex.test(line)) {
20 | const match = regex.exec(line)
21 | const currentLineNestingLevel = match[1].length
22 |
23 | if (!inList) {
24 | if (currentLineNestingLevel > 0) {
25 | return
26 | }
27 |
28 | inList = true
29 | lines[index] = line.replace(regex, `<${tag}>$2`)
30 | } else {
31 | if (currentLineNestingLevel > listNestingLevel) {
32 | let lineStart = ''
33 | const nestingLevelDifference = currentLineNestingLevel - listNestingLevel
34 |
35 | for (let i = 0; i < nestingLevelDifference; i++) {
36 | lineStart += `<${tag}>`
37 | }
38 |
39 | listNestingLevel = currentLineNestingLevel
40 | lines[index] = line.replace(regex, lineStart + '$2')
41 | } else if (currentLineNestingLevel < listNestingLevel) {
42 | const lineStart = this.closeList(listNestingLevel - currentLineNestingLevel - 1, tag)
43 | listNestingLevel = currentLineNestingLevel
44 | lines[index] = line.replace(regex, lineStart + '$2')
45 | } else {
46 | lines[index] = line.replace(regex, '$2')
47 | }
48 | }
49 | } else {
50 | if (inList) {
51 | inList = false
52 | lines[index - 1] += this.closeList(listNestingLevel, tag)
53 | listNestingLevel = 0
54 | }
55 | }
56 | })
57 |
58 | if (inList) {
59 | lines[lines.length - 1] += this.closeList(listNestingLevel, tag)
60 | listNestingLevel = 0
61 | }
62 |
63 | inList = false
64 | return lines.join('\n')
65 | }
66 |
67 | static closeList (listNestingLevel, tag) {
68 | let closeLine = `${tag}>`
69 |
70 | for (listNestingLevel; listNestingLevel !== 0; listNestingLevel--) {
71 | closeLine += `${tag}>`
72 | }
73 | return closeLine
74 | }
75 | }
76 |
77 |
--------------------------------------------------------------------------------
/src/rules/quote.js:
--------------------------------------------------------------------------------
1 | const QUOTE_REGEX = /^(>+)(.*)/
2 |
3 | export class Quote {
4 | static get RULE_NAME () { return 'blockquote' }
5 |
6 | static parse (source) {
7 | const lines = source.split('\n')
8 | let inQuote = false
9 | let qouteNestingLevel = 0
10 |
11 | lines.forEach((line, index) => {
12 | if (QUOTE_REGEX.test(line)) {
13 | const match = QUOTE_REGEX.exec(line)
14 | const currentQuoteNestingLevel = match[1].length
15 |
16 | if (!inQuote) {
17 | if (currentQuoteNestingLevel > 1) {
18 | return
19 | }
20 |
21 | lines[index] = `${match[2]}`
22 | inQuote = true
23 | qouteNestingLevel = currentQuoteNestingLevel
24 | } else {
25 | if (currentQuoteNestingLevel > qouteNestingLevel) {
26 | let lineStart = ''
27 | const nestingLevelDifference = currentQuoteNestingLevel - qouteNestingLevel
28 | for (let i = 0; i < nestingLevelDifference; i++) {
29 | lineStart += ``
30 | }
31 |
32 | qouteNestingLevel = currentQuoteNestingLevel
33 | lines[index] = `${lineStart}${match[2]}`
34 | } else if (currentQuoteNestingLevel < qouteNestingLevel) {
35 | const lineStart = this.closeQuote(qouteNestingLevel - currentQuoteNestingLevel)
36 | qouteNestingLevel = currentQuoteNestingLevel
37 | lines[index] = `${lineStart}${match[2]}`
38 | } else {
39 | lines[index] = match[2]
40 | }
41 | }
42 | } else {
43 | if (inQuote) {
44 | inQuote = false
45 | lines[index - 1] += this.closeQuote(qouteNestingLevel)
46 | }
47 | }
48 | })
49 |
50 | if (inQuote) {
51 | lines[lines.length - 1] += this.closeQuote(qouteNestingLevel)
52 | }
53 |
54 | inQuote = false
55 | return lines.join('\n')
56 | }
57 |
58 | static closeQuote (qouteNestingLevel) {
59 | let closeLine = ''
60 |
61 | for (qouteNestingLevel; qouteNestingLevel !== 0; qouteNestingLevel--) {
62 | closeLine += `
`
63 | }
64 |
65 | return closeLine
66 | }
67 | }
68 |
--------------------------------------------------------------------------------
/src/rules/strong.js:
--------------------------------------------------------------------------------
1 | const STRONG_REGEX_1 = /(^|\s|"|')(?:__)(.+?)(?:__)/g
2 | const STRONG_REGEX_2 = /(^|\s|"|')(?:\*\*)(.+?)(?:\*\*)/g
3 |
4 | export class Strong {
5 | static get RULE_NAME () { return 'strong' }
6 |
7 | static parse (source) {
8 | source = source.replace(STRONG_REGEX_1, '$1$2')
9 | return source.replace(STRONG_REGEX_2, '$1$2')
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/src/rules/table.js:
--------------------------------------------------------------------------------
1 | const TABLE_REGEX = /(\|[^\r\n]*\|)\r?\n(\|(?::?[-]+:?\|)+)\r?\n((?:\|[^\r\n]*\|\r?\n)*)/g
2 |
3 | export class Table {
4 | static get RULE_NAME () { return 'table' }
5 |
6 | static parse (source) {
7 | return source.replace(TABLE_REGEX, (table, headers, columnAlignments, dataRows) => {
8 | headers = headers.slice(1, -1).split('|')
9 |
10 | columnAlignments = columnAlignments
11 | .slice(1, -1)
12 | .split('|')
13 | .map(col => {
14 | let alignment = ''
15 | if (col.startsWith(':')) {
16 | alignment = 'left'
17 | }
18 | if (col.endsWith(':')) {
19 | alignment = 'right'
20 | }
21 | if (col.startsWith(':') && col.endsWith(':')) {
22 | alignment = 'center'
23 | }
24 |
25 | return alignment ? ` align="${alignment}"` : ''
26 | })
27 |
28 | if (columnAlignments.length !== headers.length) {
29 | return table
30 | }
31 |
32 | dataRows = dataRows ? dataRows.trim().split('\n') : []
33 | dataRows = dataRows.map(row => row.trim().slice(1, -1).split('|'))
34 |
35 | const tableHeaderHtml = headers
36 | .map((header, columnIndex) => ` ${header.trim()} | `)
37 | .join('')
38 |
39 | const tableRowsHtml = dataRows.map(dataRow => {
40 | const cells = []
41 | for (let column = 0; column < headers.length; column++) {
42 | cells.push(
43 | ` ${dataRow[column] ? dataRow[column].trim() : ''} | `
44 | )
45 | }
46 | return ` ${cells.join('\n')}
`
47 | })
48 | return ` ${tableHeaderHtml}
${tableRowsHtml.join(
49 | '\n'
50 | )}
`
51 | })
52 | }
53 | }
54 |
--------------------------------------------------------------------------------
/src/utils/index.js:
--------------------------------------------------------------------------------
1 | import { Utils } from './utils'
2 |
3 | export {
4 | Utils
5 | }
6 |
--------------------------------------------------------------------------------
/src/utils/utils.js:
--------------------------------------------------------------------------------
1 | export class Utils {
2 | static escapeContent (source) {
3 | return source.replace(/\*|_|-|#|`/gm, (s) => {
4 | return `${s.charCodeAt(0)};`
5 | })
6 | }
7 |
8 | static escapeTagStart (source) {
9 | return source.replace(/\ {
6 | if (options[parser.RULE_NAME] !== undefined && !options[parser.RULE_NAME]) {
7 | return
8 | }
9 |
10 | source = parser.parse(source)
11 | })
12 |
13 | return source
14 | }
15 | }
16 |
17 | const vueSimpleMarkdownParser = new VueSimpleMarkdownParser()
18 | export { vueSimpleMarkdownParser as VueSimpleMarkdownParser }
19 |
--------------------------------------------------------------------------------
/src/vue-simple-markdown.component.vue:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
101 |
108 |
--------------------------------------------------------------------------------
/test/.eslintrc:
--------------------------------------------------------------------------------
1 | {
2 | "env": {
3 | "mocha": true
4 | },
5 | "globals": {
6 | "expect": true,
7 | "sinon": true
8 | }
9 | }
10 |
--------------------------------------------------------------------------------
/test/helpers/Test.vue:
--------------------------------------------------------------------------------
1 |
2 |
12 |
13 |
14 |
39 |
40 |
108 |
--------------------------------------------------------------------------------
/test/helpers/index.js:
--------------------------------------------------------------------------------
1 | import camelcase from 'camelcase'
2 | import { createVM, Vue } from './utils'
3 | import { nextTick } from './wait-for-update'
4 |
5 | export function dataPropagationTest (Component) {
6 | return function () {
7 | const spy = sinon.spy()
8 | const vm = createVM(this, function (h) {
9 | return (
10 | Hello
11 | )
12 | })
13 | spy.should.have.not.been.called
14 | vm.$('.custom').should.exist
15 | vm.$('.custom').click()
16 | spy.should.have.been.calledOnce
17 | }
18 | }
19 |
20 | export function attrTest (it, base, Component, attr) {
21 | const attrs = Array.isArray(attr) ? attr : [attr]
22 |
23 | attrs.forEach(attr => {
24 | it(attr, function (done) {
25 | const vm = createVM(this, function (h) {
26 | const opts = {
27 | props: {
28 | [camelcase(attr)]: this.active
29 | }
30 | }
31 | return (
32 | {attr}
33 | )
34 | }, {
35 | data: { active: true }
36 | })
37 | vm.$(`.${base}`).should.have.class(`${base}--${attr}`)
38 | vm.active = false
39 | nextTick().then(() => {
40 | vm.$(`.${base}`).should.not.have.class(`${base}--${attr}`)
41 | vm.active = true
42 | }).then(done)
43 | })
44 | })
45 | }
46 |
47 | export {
48 | createVM,
49 | Vue,
50 | nextTick
51 | }
52 |
--------------------------------------------------------------------------------
/test/helpers/utils.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue/dist/vue.js'
2 | import Test from './Test.vue'
3 |
4 | Vue.config.productionTip = false
5 | const isKarma = !!window.__karma__
6 |
7 | export function createVM (context, template, opts = {}) {
8 | return isKarma
9 | ? createKarmaTest(context, template, opts)
10 | : createVisualTest(context, template, opts)
11 | }
12 |
13 | const emptyNodes = document.querySelectorAll('nonexistant')
14 | Vue.prototype.$$ = function $$ (selector) {
15 | const els = document.querySelectorAll(selector)
16 | const vmEls = this.$el.querySelectorAll(selector)
17 | const fn = vmEls.length
18 | ? el => vmEls.find(el)
19 | : el => this.$el === el
20 | const found = Array.from(els).filter(fn)
21 | return found.length
22 | ? found
23 | : emptyNodes
24 | }
25 |
26 | Vue.prototype.$ = function $ (selector) {
27 | const els = document.querySelectorAll(selector)
28 | const vmEl = this.$el.querySelector(selector)
29 | const fn = vmEl
30 | ? el => el === vmEl
31 | : el => el === this.$el
32 | // Allow should chaining for tests
33 | return Array.from(els).find(fn) || emptyNodes
34 | }
35 |
36 | export function createKarmaTest (context, template, opts) {
37 | const el = document.createElement('div')
38 | document.getElementById('tests').appendChild(el)
39 | const render = typeof template === 'string'
40 | ? { template: `${template}
` }
41 | : { render: template }
42 | return new Vue({
43 | el,
44 | name: 'Test',
45 | ...render,
46 | ...opts
47 | })
48 | }
49 |
50 | export function createVisualTest (context, template, opts) {
51 | let vm
52 | if (typeof template === 'string') {
53 | opts.components = opts.components || {}
54 | // Let the user define a test component
55 | if (!opts.components.Test) {
56 | opts.components.Test = Test
57 | }
58 | vm = new Vue({
59 | name: 'TestContainer',
60 | el: context.DOMElement,
61 | template: `${template}`,
62 | ...opts
63 | })
64 | } else {
65 | // TODO allow redefinition of Test component
66 | vm = new Vue({
67 | name: 'TestContainer',
68 | el: context.DOMElement,
69 | render (h) {
70 | return h(Test, {
71 | attrs: {
72 | id: context.DOMElement.id
73 | }
74 | // render the passed component with this scope
75 | }, [template.call(this, h)])
76 | },
77 | ...opts
78 | })
79 | }
80 |
81 | context.DOMElement.vm = vm
82 | return vm
83 | }
84 |
85 | export function register (name, component) {
86 | Vue.component(name, component)
87 | }
88 |
89 | export { isKarma, Vue }
90 |
--------------------------------------------------------------------------------
/test/helpers/wait-for-update.js:
--------------------------------------------------------------------------------
1 | import Vue from 'vue/dist/vue.js'
2 |
3 | // Testing helper
4 | // nextTick().then(() => {
5 | //
6 | // Automatically waits for nextTick
7 | // }).then(() => {
8 | // return a promise or value to skip the wait
9 | // })
10 | function nextTick () {
11 | const jobs = []
12 | let done
13 |
14 | const chainer = {
15 | then (cb) {
16 | jobs.push(cb)
17 | return chainer
18 | }
19 | }
20 |
21 | function shift (...args) {
22 | const job = jobs.shift()
23 | let result
24 | try {
25 | result = job(...args)
26 | } catch (e) {
27 | jobs.length = 0
28 | done(e)
29 | }
30 |
31 | // wait for nextTick
32 | if (result !== undefined) {
33 | if (result.then) {
34 | result.then(shift)
35 | } else {
36 | shift(result)
37 | }
38 | } else if (jobs.length) {
39 | requestAnimationFrame(() => Vue.nextTick(shift))
40 | }
41 | }
42 |
43 | // First time
44 | Vue.nextTick(() => {
45 | done = jobs[jobs.length - 1]
46 | if (done.toString().slice(0, 14) !== 'function (err)') {
47 | throw new Error('waitForUpdate chain is missing .then(done)')
48 | }
49 | shift()
50 | })
51 |
52 | return chainer
53 | }
54 |
55 | exports.nextTick = nextTick
56 | exports.delay = time => new Promise(resolve => setTimeout(resolve, time))
57 |
--------------------------------------------------------------------------------
/test/index.js:
--------------------------------------------------------------------------------
1 | // Polyfill fn.bind() for PhantomJS
2 | import bind from 'function-bind'
3 | /* eslint-disable no-extend-native */
4 | Function.prototype.bind = bind
5 |
6 | // Polyfill Object.assign for PhantomJS
7 | import objectAssign from 'object-assign'
8 | Object.assign = objectAssign
9 |
10 | // require all src files for coverage.
11 | // you can also change this to match only the subset of files that
12 | // you want coverage for.
13 | const srcContext = require.context('../src', true, /^\.\/(?!index(\.js)?$)/)
14 | srcContext.keys().forEach(srcContext)
15 |
16 | // Use a div to insert elements
17 | before(function () {
18 | const el = document.createElement('DIV')
19 | el.id = 'tests'
20 | document.body.appendChild(el)
21 | })
22 |
23 | // Remove every test html scenario
24 | afterEach(function () {
25 | const el = document.getElementById('tests')
26 | for (let i = 0; i < el.children.length; ++i) {
27 | el.removeChild(el.children[i])
28 | }
29 | })
30 |
31 | const specsContext = require.context('./specs', true)
32 | specsContext.keys().forEach(specsContext)
33 |
--------------------------------------------------------------------------------
/test/karma.conf.js:
--------------------------------------------------------------------------------
1 | const merge = require('webpack-merge')
2 | const baseConfig = require('../build/webpack.config.dev.js')
3 |
4 | const webpackConfig = merge(baseConfig, {
5 | // use inline sourcemap for karma-sourcemap-loader
6 | devtool: '#inline-source-map'
7 | })
8 |
9 | webpackConfig.plugins = []
10 |
11 | const vueRule = webpackConfig.module.rules.find(rule => rule.loader === 'vue-loader')
12 | vueRule.options = vueRule.options || {}
13 | vueRule.options.loaders = vueRule.options.loaders || {}
14 | vueRule.options.loaders.js = 'babel-loader'
15 |
16 | // no need for app entry during tests
17 | delete webpackConfig.entry
18 |
19 | module.exports = function (config) {
20 | config.set({
21 | // to run in additional browsers:
22 | // 1. install corresponding karma launcher
23 | // http://karma-runner.github.io/0.13/config/browsers.html
24 | // 2. add it to the `browsers` array below.
25 | browsers: ['Chrome'],
26 | frameworks: ['mocha', 'chai-dom', 'sinon-chai'],
27 | reporters: ['spec', 'coverage'],
28 | files: ['./index.js'],
29 | preprocessors: {
30 | './index.js': ['webpack', 'sourcemap']
31 | },
32 | webpack: webpackConfig,
33 | webpackMiddleware: {
34 | noInfo: true
35 | },
36 | coverageReporter: {
37 | dir: './coverage',
38 | reporters: [
39 | { type: 'lcov', subdir: '.' },
40 | { type: 'text-summary' }
41 | ]
42 | }
43 | })
44 | }
45 |
--------------------------------------------------------------------------------
/test/visual.js:
--------------------------------------------------------------------------------
1 | import 'style-loader!css-loader!mocha-css'
2 |
3 | // create a div where mocha can add its stuff
4 | const mochaDiv = document.createElement('DIV')
5 | mochaDiv.id = 'mocha'
6 | document.body.appendChild(mochaDiv)
7 |
8 | import 'mocha/mocha.js'
9 | import sinon from 'sinon'
10 | import chai from 'chai'
11 | window.mocha.setup({
12 | ui: 'bdd',
13 | slow: 750,
14 | timeout: 5000,
15 | globals: [
16 | '__VUE_DEVTOOLS_INSTANCE_MAP__',
17 | 'script',
18 | 'inject',
19 | 'originalOpenFunction'
20 | ]
21 | })
22 | window.sinon = sinon
23 | chai.use(require('chai-dom'))
24 | chai.use(require('sinon-chai'))
25 | chai.should()
26 |
27 | let vms = []
28 | let testId = 0
29 |
30 | beforeEach(function () {
31 | this.DOMElement = document.createElement('DIV')
32 | this.DOMElement.id = `test-${++testId}`
33 | document.body.appendChild(this.DOMElement)
34 | })
35 |
36 | afterEach(function () {
37 | const testReportElements = document.getElementsByClassName('test')
38 | const lastReportElement = testReportElements[testReportElements.length - 1]
39 |
40 | if (!lastReportElement) return
41 | const el = document.getElementById(this.DOMElement.id)
42 | if (el) lastReportElement.appendChild(el)
43 | // Save the vm to hide it later
44 | if (this.DOMElement.vm) vms.push(this.DOMElement.vm)
45 | })
46 |
47 | // Hide all tests at the end to prevent some weird bugs
48 | before(function () {
49 | vms = []
50 | testId = 0
51 | })
52 | after(function () {
53 | requestAnimationFrame(function () {
54 | setTimeout(function () {
55 | vms.forEach(vm => {
56 | // Hide if test passed
57 | if (!vm.$el.parentElement.classList.contains('fail')) {
58 | vm.$children[0].visible = false
59 | }
60 | })
61 | }, 100)
62 | })
63 | })
64 |
65 | const specsContext = require.context('./specs', true)
66 | specsContext.keys().forEach(specsContext)
67 |
68 | window.mocha.checkLeaks()
69 | window.mocha.run()
70 |
--------------------------------------------------------------------------------