Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Issue 8 - Add support for markdown heading h1-h6, p #9

Merged
merged 8 commits into from
Sep 24, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 5 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ Options:
-v, --version Show version number [boolean]
```

## Features

- Accept .txt and .md files (Currently .md only support heading h1-h6, and p)

## Example

Install `ts-node` with:
Expand All @@ -32,18 +36,13 @@ npm install -g ts-node
exe

```
ts-node src/index.ts -i Sherlock\ Holmes\ Selected\ Stories\ / -r -e -s src/styles/retro.css
ts-node src/index.ts -i Sherlock\ Holmes\ Selected\ Stories\ / -r -e -s src/styles/retro.css
```




## Authors

- [@Dukemanh](https://www.github.com/dukemanh)


## License

[![MIT License](https://img.shields.io/apm/l/atomic-design-ui.svg?)](https://github.com/tterb/atomic-design-ui/blob/master/LICENSEs)

23 changes: 23 additions & 0 deletions Sherlock-Holmes-Selected-Stories/a/markdown.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
# This is the title h1

## This is the title h2

### This is the title h3

#### This is the title h4

##### This is the title h5

###### This is the title h6

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus viverra nulla vitae mattis egestas. Suspendisse efficitur congue hendrerit. Integer congue tristique dui, at viverra nisl aliquam id. Suspendisse commodo feugiat nibh non accumsan. Maecenas hendrerit, purus quis placerat faucibus, sem sem aliquet magna, eu dignissim libero tellus at ante. Maecenas est libero, fermentum quis eros maximus, ultrices ornare massa. Morbi pharetra venenatis lectus id molestie. Cras pharetra ipsum velit, ut tristique dui semper vulputate. Donec vulputate lectus sed lorem venenatis, at sollicitudin massa pretium. Nam bibendum vestibulum blandit.

#Ut in magna non orci bibendum commodo. Nullam nisi nunc, condimentum a lacus fermentum, pulvinar condimentum massa. Nam venenatis aliquet neque nec tristique. Nulla blandit mi et metus sollicitudin, eget maximus felis volutpat. Cras at neque mi. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur suscipit dapibus sem, at porta sem lacinia in. Sed at ante porttitor, tempor magna in, sodales justo.

## This is the title h2

# #Morbi faucibus lorem in nulla finibus, vitae interdum ante consequat. Aliquam mollis justo non mi venenatis, ullamcorper aliquam enim iaculis. Quisque diam lectus, tempor tristique massa dapibus, iaculis aliquam turpis. Pellentesque iaculis, erat eget scelerisque viverra, sapien quam pulvinar turpis, non vehicula enim mi nec lacus. Sed ac purus lorem.

## ##Pellentesque fermentum ante at tellus pellentesque dignissim. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse mattis eu dolor non feugiat. Maecenas efficitur pellentesque massa vel commodo. Duis viverra justo et neque hendrerit, at consectetur elit pretium. Aliquam nec felis feugiat.

Duis magna arcu, auctor ut tincidunt eget, posuere eu urna. Ut ipsum magna, consequat at quam sit amet, ornare posuere lorem. Nam metus libero, lobortis nec vestibulum et, feugiat id elit. Nam maximus justo quis nulla rhoncus consequat. Donec auctor elementum est nec sagittis. Integer sed massa risus. Vivamus feugiat nunc et congue pulvinar.
71 changes: 61 additions & 10 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,45 @@ if (stylesheet) {
fs.copyFileSync('src/styles/index.css', `${output}/index.css`);
}

/**
* Process markdown for heading 1-6
* @param data Data to be processed
* @return return array where h1 markdown is processed
*/
const processHeadingMarkdown = (data: string[]): string[] => {
return data.map((text) => {
return text.replace(/^\s*(#{1,6})\s+(.+)$/gm, (match, hash, title) => {
const tag = `h${hash.length}`;
return `<${tag}>${title}</${tag}>`;
});
});
};

/**
* Process markdown for P
* @param data Data to be processed
* @return return array where p markdown is processed
*/
const processPMarkdown = (data: string[]): string[] => {
return data.map((text) => {
if (text.substr(0, 1) !== '<' && text.substr(text.length - 1) !== '>') return `<p>${text}</p>`;
return text;
});
};

/**
* Process markdown
* It only support markdown for heading 1-6, and P
* @param data Data to be processed
* @return return array of HTML
*/
const processMarkdown = (data: string[]): string[] => {
let treatedDataList: string[] = [];
treatedDataList = processHeadingMarkdown(data);
treatedDataList = processPMarkdown(treatedDataList);
return treatedDataList;
};

/**
* Generate HTML mark up from .txt file
* @param fileName File to be parsed
Expand All @@ -86,17 +125,17 @@ if (stylesheet) {
*/
const processFile = (filePath: string, isIndex: boolean): string => {
const extension = path.extname(filePath).toLowerCase();
if (extension !== '.txt') {
if (extension !== '.txt' && extension !== '.md') {
return '';
}

const isMd = extension === '.md';
const text = fs.readFileSync(filePath, 'utf-8');

// title is before the first 2 blank lines of the text
const titleAndContent = text.split(/\n\n\n/);
Kevan-Y marked this conversation as resolved.
Show resolved Hide resolved
let title = '';
let content = '';

if (titleAndContent.length >= 2) {
[title] = titleAndContent;
content = titleAndContent.slice(1).join('\n\n\n');
Expand All @@ -110,7 +149,7 @@ const processFile = (filePath: string, isIndex: boolean): string => {
<link rel="stylesheet" href="${
path.relative(path.dirname(filePath), input) || './'
}/index.css">
<title>${title || path.basename(filePath, '.txt')}</title>`;
<title>${title || path.parse(filePath).name}</title>`;

const body = `
${
Expand All @@ -121,10 +160,17 @@ const processFile = (filePath: string, isIndex: boolean): string => {
: ''
}
${title ? `<h1 class="text-center">${title}</h1>` : ''}
${content
.split(/\r?\n\r?\n/)
.map((para) => `<p>${para.replace(/\r?\n/, ' ')}</p>`)
.join('\n')}

${
isMd
? processMarkdown(
content.split(/\r?\n\r?\n/).map((para) => `${para.replace(/\r?\n/g, ' ')}`)
).join('\n')
: content
.split(/\r?\n\r?\n/)
.map((para) => `<p>${para.replace(/\r?\n/, ' ')}</p>`)
.join('\n')
}
`;

const markup = `<!DOCTYPE html>
Expand Down Expand Up @@ -156,7 +202,10 @@ const generateHTMLs = (pathName: string): string[] => {
const markup = processFile(filePath, false);
if (markup) {
const relativeFolder = relative ? `/${path.relative(input, path.dirname(filePath))}` : '';
const dist = `${output}${relativeFolder}/${path.basename(filePath, '.txt')}.html`;
const dist = `${output}${relativeFolder}/${path.basename(
filePath,
path.extname(filePath)
)}.html`;

fs.ensureFileSync(dist);
fs.writeFileSync(dist, markup, { flag: 'w' });
Expand Down Expand Up @@ -196,10 +245,12 @@ try {
if (inputPath.isFile()) {
const markup = processFile(input, true);
if (!markup) {
logError('Input file must be .txt');
logError('Input file must be .txt or .md');
}

fs.writeFileSync(`${output}/${path.basename(input, '.txt')}.html`, markup, { flag: 'w' });
fs.writeFileSync(`${output}/${path.basename(input, path.extname(input))}.html`, markup, {
flag: 'w',
});
} else if (inputPath.isDirectory()) {
const dists = generateHTMLs(input);

Expand Down