Skip to content

Commit

Permalink
feat(lib): initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
vincentbel committed Sep 8, 2017
0 parents commit 54deef1
Show file tree
Hide file tree
Showing 60 changed files with 4,238 additions and 0 deletions.
12 changes: 12 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

# indent
[*.{js, scss}]
indent_style = space
indent_size = 2
35 changes: 35 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
.DS_Store

# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage

# nyc test coverage
.nyc_output

# Dependency directories
node_modules/

# Typescript v1 declaration files
typings/

# Optional npm cache directory
.npm

# Yarn Integrity file
.yarn-integrity
17 changes: 17 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
language: node_js
cache:
yarn: true
directories:
- node_modules
notifications:
email: false
node_js:
- '8'
- '6'
script:
- npm run test -- --coverage
after_success:
- npm run semantic-release
branches:
except:
- /^v\d+\.\d+\.\d+$/
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2017 Vincent Bel

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
33 changes: 33 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
# remark-pangu

[![travis build](https://img.shields.io/travis/VincentBel/remark-pangu.svg?style=flat-square)](https://travis-ci.org/VincentBel/remark-pangu)
[![version](https://img.shields.io/npm/v/remark-pangu.svg?style=flat-square)](http://npm.im/remark-pangu)
[![MIT License](https://img.shields.io/npm/l/remark-pangu.svg?style=flat-square)](http://opensource.org/licenses/MIT)
[![semantic-release](https://img.shields.io/badge/%20%20%F0%9F%93%A6%F0%9F%9A%80-semantic--release-e10079.svg?style=flat-square)](https://github.com/semantic-release/semantic-release)

给 Markdown 中英文自动插入空格的 [Remark](https://github.com/wooorm/remark) 插件(使用 [pangu.js](https://github.com/vinta/pangu.js))。

## Install

```bash
npm install remark-pangu
```

## Usage

```js
remark().use(pangu)
```

```js
const remark = require('remark')
const pangu = require('remark-pangu')

const doc = '中文abc中文';
console.log(remark().use(pangu).process(doc).contents);
// => 中文 abc 中文
```

## LICENSE

MIT
89 changes: 89 additions & 0 deletions index-compiler.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
const pangu = require('pangu')

// List of Markdown AST: <https://github.com/syntax-tree/mdast>
// AST Explorer: <https://astexplorer.net/#/gist/7a794a8fc43b2e75e27024c85fb77aad/0934495eb735dffdf739dc7943f7848940070f8e>
//
// AST we should format:
// 1. text node:
// * paragraph children
// * blockquote children
// * heading children
// * emphasis children
// * strong children
// * listItems children
// * tableCell children
// * delete children
// * link children
// * image children
// * footnote children
// 2. inlineCode value
// 3. link title
// 4. image title/alt
// 5. imageReference alt
// 6. definition title
//
//
// AST we ignored:
// 1. YAML
// 2. html (it can contain link: <a> <img>)
// 3. 临接情况
// 1. 粗体:我的a**粗体**
// 2. 强调:我的a*强调*
// 3. ...

function format(value) {
if (!value) return value
return pangu.spacing(value)
}

function createFormatNodeVisitorCreator(nodeKey) {
return function visitorCreator(originVisitor) {
return function valueVisitor(node, ...args) {
const formattedNode = Object.assign({}, node, {
[nodeKey]: format(node[nodeKey]),
})

return originVisitor.call(this, formattedNode, ...args)
}
}
}

function assignVisitors(visitors, types, createVisitor) {
types.forEach(type => {
visitors[type] = createVisitor(visitors[type])
})
}

function assignValueVisitors(visitors) {
const valueVisitorCreator = createFormatNodeVisitorCreator('value')
assignVisitors(visitors, ['text', 'inlineCode'], valueVisitorCreator)
}

function assignTitleVisitor(visitors) {
const titleVisitorCreator = createFormatNodeVisitorCreator('title')
assignVisitors(visitors, ['link', 'image', 'definition'], titleVisitorCreator)
}

function assignAltVisitor(visitors) {
const altVisitorCreator = createFormatNodeVisitorCreator('alt')
assignVisitors(visitors, ['image', 'imageReference'], altVisitorCreator)
}

function isRemarkCompiler(compiler) {
return Boolean(compiler && compiler.prototype && compiler.prototype.visitors)
}

function attachCompiler(compiler) {
const proto = compiler.prototype
assignValueVisitors(proto.visitors)
assignTitleVisitor(proto.visitors)
assignAltVisitor(proto.visitors)
}

module.exports = function remarkPangu() {
const compiler = this.Compiler

if (isRemarkCompiler(compiler)) {
attachCompiler(compiler)
}
}
61 changes: 61 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
'use strict'

var visit = require('unist-util-visit')
var is = require('unist-util-is')
var pangu = require('pangu')

// List of Markdown AST: <https://github.com/syntax-tree/mdast>
// AST Explorer: <https://astexplorer.net/#/gist/7a794a8fc43b2e75e27024c85fb77aad/0934495eb735dffdf739dc7943f7848940070f8e>
//
// AST we should format:
// 1. text node:
// * paragraph children
// * blockquote children
// * heading children
// * emphasis children
// * strong children
// * listItems children
// * tableCell children
// * delete children
// * link children
// * image children
// * footnote children
// 2. inlineCode value
// 3. link title
// 4. image title/alt
// 5. imageReference alt
// 6. definition title
//
//
// AST we ignored:
// 1. YAML
// 2. html (it can contain link: <a> <img>)
// 3. 临接情况
// 1. 粗体:我的a**粗体**
// 2. 强调:我的a*强调*
// 3. ...

function format(value) {
if (!value) return value
return pangu.spacing(value)
}

function visitor(node) {
if (is('text', node) || is('inlineCode', node)) {
node.value = format(node.value)
}

if (is('link', node) || is('image', node) || is('definition', node)) {
node.title = format(node.title)
}

if (is('image', node) || is('imageReference', node)) {
node.alt = format(node.alt)
}
}

module.exports = function attacher() {
return function transformer(tree, file) {
visit(tree, visitor)
}
}
51 changes: 51 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
{
"name": "remark-pangu",
"version": "0.0.0-development",
"description": "Remark plugin to Automatically insert whitespace between CJK (Chinese, Japanese, Korean) and half-width characters (alphabetical letters, numerical digits and symbols) by using pangu.js",
"main": "index.js",
"scripts": {
"test": "jest",
"semantic-release": "semantic-release pre && npm publish && semantic-release post"
},
"repository": {
"type": "git",
"url": "https://github.com/VincentBel/remark-pangu.git"
},
"keywords": [
"pangu",
"remark",
"plugin",
"spacing"
],
"author": "VincentBel <buaazqh@gmail.com>",
"license": "MIT",
"bugs": {
"url": "https://github.com/VincentBel/remark-pangu/issues"
},
"homepage": "https://github.com/VincentBel/remark-pangu#readme",
"dependencies": {
"pangu": "^3.3.0",
"unist-util-is": "^2.1.1",
"unist-util-visit": "^1.1.3"
},
"devDependencies": {
"jest": "^21.0.1",
"remark-frontmatter": "^1.1.0",
"remark-parse": "^4.0.0",
"remark-stringify": "^4.0.0",
"unified": "^6.1.5",
"semantic-release": "^7.0.2"
},
"jest": {
"setupFiles": [
"<rootDir>/tests-config/setup.js"
],
"snapshotSerializers": [
"<rootDir>/tests-config/raw-serializer.js"
],
"collectCoverageFrom": [
"src/**/*.js",
"index.js"
]
}
}
16 changes: 16 additions & 0 deletions tests-config/raw-serializer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
'use strict'

const RAW = Symbol.for('raw')

module.exports = {
print(val) {
return val[RAW]
},
test(val) {
return (
val &&
Object.prototype.hasOwnProperty.call(val, RAW) &&
typeof val[RAW] === 'string'
)
},
}
50 changes: 50 additions & 0 deletions tests-config/setup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
'use strict'

const fs = require('fs')
const { extname } = require('path')
const unified = require('unified')
const parse = require('remark-parse')
const stringify = require('remark-stringify')
const frontmatter = require('remark-frontmatter')
const pangu = require('../index')

const processor = unified()
.use(parse, { footnotes: true })
.use(stringify)
.use(frontmatter)
.use(pangu)
.freeze()

function formatAsync(source) {
return processor.process(source)
}

function raw(string) {
if (typeof string !== 'string') {
throw new Error('Raw snapshots have to be strings.')
}
return { [Symbol.for('raw')]: string }
}

function runSpec(dirname) {
fs.readdirSync(dirname).forEach(filename => {
const path = dirname + '/' + filename
if (
extname(filename) !== '.snap' &&
fs.lstatSync(path).isFile() &&
filename !== 'run.spec.js'
) {
const source = fs.readFileSync(path)
test(`${filename}`, () => {
return formatAsync(source).then(vfile => {
const output = String(vfile)
return expect(
raw(source + '~'.repeat(80) + '\n' + output),
).toMatchSnapshot(filename)
})
})
}
})
}

global.runSpec = runSpec
Loading

0 comments on commit 54deef1

Please sign in to comment.