0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2025-12-24 16:22:44 +00:00

Merge branch 'master' into UpdateSolberaImitationFont

This commit is contained in:
Trevor Buckner
2021-03-04 21:44:46 -05:00
committed by GitHub
22 changed files with 3583 additions and 726 deletions

View File

@@ -1,7 +1,7 @@
module.exports = {
root : true,
parserOptions : {
ecmaVersion : 9,
ecmaVersion : 2021,
sourceType : 'module',
ecmaFeatures : {
jsx : true

View File

@@ -18,10 +18,11 @@ const SNIPPETBAR_HEIGHT = 25;
const Editor = createClass({
getDefaultProps : function() {
return {
value : '',
brew : {
text : ''
},
onChange : ()=>{},
metadata : {},
onMetadataChange : ()=>{},
showMetaButton : true,
renderer : 'legacy'
@@ -59,7 +60,7 @@ const Editor = createClass({
this.cursorPosition = curpos;
},
handleInject : function(injectText){
const lines = this.props.value.split('\n');
const lines = this.props.brew.text.split('\n');
lines[this.cursorPosition.line] = splice(lines[this.cursorPosition.line], this.cursorPosition.ch, injectText);
this.handleTextChange(lines.join('\n'));
@@ -72,7 +73,7 @@ const Editor = createClass({
},
getCurrentPage : function(){
const lines = this.props.value.split('\n').slice(0, this.cursorPosition.line + 1);
const lines = this.props.brew.text.split('\n').slice(0, this.cursorPosition.line + 1);
return _.reduce(lines, (r, line)=>{
if(line.indexOf('\\page') !== -1) r++;
return r;
@@ -87,7 +88,7 @@ const Editor = createClass({
const customHighlights = codeMirror.getAllMarks();
for (let i=0;i<customHighlights.length;i++) customHighlights[i].clear();
const lineNumbers = _.reduce(this.props.value.split('\n'), (r, line, lineNumber)=>{
const lineNumbers = _.reduce(this.props.brew.text.split('\n'), (r, line, lineNumber)=>{
//reset custom line styles
codeMirror.removeLineClass(lineNumber, 'background');
@@ -108,21 +109,14 @@ const Editor = createClass({
r.push(lineNumber);
}
if(line.startsWith('\\column')){
if(line.match(/^\\column$/)){
codeMirror.addLineClass(lineNumber, 'text', 'columnSplit');
r.push(lineNumber);
}
if(line.startsWith('{{') || line.startsWith('}}')){
let endCh = line.length+1;
const match = line.match(/{{(?:[\w,#-]|="[\w, ]*")*\s*|}}/);
if(match)
endCh = match.index+match[0].length;
codeMirror.markText({ line: lineNumber, ch: 0 }, { line: lineNumber, ch: endCh }, { className: 'block' });
}
// Highlight inline spans {{content}}
if(line.includes('{{') && line.includes('}}')){
const regex = /{{(?:[\w,#-]|="[\w, ]*")*\s*|}}/g;
const regex = /{{(?:="[\w,\-. ]*"|[^"'\s])*\s*|}}/g;
let match;
let blockCount = 0;
while ((match = regex.exec(line)) != null) {
@@ -137,6 +131,14 @@ const Editor = createClass({
}
codeMirror.markText({ line: lineNumber, ch: match.index }, { line: lineNumber, ch: match.index + match[0].length }, { className: 'inline-block' });
}
} else if(line.trimLeft().startsWith('{{') || line.trimLeft().startsWith('}}')){
// Highlight block divs {{\n Content \n}}
let endCh = line.length+1;
const match = line.match(/^ *{{(?:="[\w,\-. ]*"|[^"'\s])*$|^ *}}$/);
if(match)
endCh = match.index+match[0].length;
codeMirror.markText({ line: lineNumber, ch: 0 }, { line: lineNumber, ch: endCh }, { className: 'block' });
}
}
@@ -159,7 +161,7 @@ const Editor = createClass({
renderMetadataEditor : function(){
if(!this.state.showMetadataEditor) return;
return <MetadataEditor
metadata={this.props.metadata}
metadata={this.props.brew}
onChange={this.props.onMetadataChange}
/>;
},
@@ -169,7 +171,7 @@ const Editor = createClass({
return (
<div className='editor' ref='main'>
<SnippetBar
brew={this.props.value}
brew={this.props.brew}
onInject={this.handleInject}
onToggle={this.handgleToggle}
showmeta={this.state.showMetadataEditor}
@@ -180,7 +182,7 @@ const Editor = createClass({
ref='codeEditor'
wrap={true}
language='gfm'
value={this.props.value}
value={this.props.brew.text}
onChange={this.handleTextChange}
onCursorActivity={this.handleCursorActivty} />

View File

@@ -50,7 +50,7 @@ const MetadataEditor = createClass({
},
handleDelete : function(){
if(this.props.metadata.authors.length <= 1){
if(this.props.metadata.authors && this.props.metadata.authors.length <= 1){
if(!confirm('Are you sure you want to delete this brew? Because you are the only owner of this brew, the document will be deleted permanently.')) return;
if(!confirm('Are you REALLY sure? You will not be able to recover the document.')) return;
} else {
@@ -114,7 +114,7 @@ const MetadataEditor = createClass({
renderAuthors : function(){
let text = 'None.';
if(this.props.metadata.authors.length){
if(this.props.metadata.authors && this.props.metadata.authors.length){
text = this.props.metadata.authors.join(', ');
}
return <div className='field authors'>

View File

@@ -16,7 +16,7 @@ const execute = function(val, brew){
const Snippetbar = createClass({
getDefaultProps : function() {
return {
brew : '',
brew : {},
onInject : ()=>{},
onToggle : ()=>{},
showmeta : false,
@@ -80,7 +80,7 @@ module.exports = Snippetbar;
const SnippetGroup = createClass({
getDefaultProps : function() {
return {
brew : '',
brew : {},
groupName : '',
icon : 'fas fa-rocket',
snippets : [],

View File

@@ -47,6 +47,12 @@ const spellNames = [
'Ultimate Rite of the Confetti Angel',
'Ultimate Ritual of Mouthwash',
];
const itemNames = [
'Doorknob of Niceness',
'Paper Armor of Folding',
'Mixtape of Sadness',
'Staff of Endless Confetti',
];
module.exports = {
@@ -87,5 +93,17 @@ module.exports = {
'A *continual flame* can be covered or hidden but not smothered or quenched.',
'\n\n\n'
].join('\n');
},
item : function() {
return [
`#### ${_.sample(itemNames)}`,
`*${_.sample(['Wondrous item', 'Armor', 'Weapon'])}, ${_.sample(['Common', 'Uncommon', 'Rare', 'Very Rare', 'Legendary', 'Artifact'])} (requires attunement)*`,
`:`,
`This knob is pretty nice. When attached to a door, it allows a user to`,
`open that door with the strength of the nearest animal. For example, if`,
`there is a cow nearby, the user will have the "strength of a cow" while`,
`opening this door.`
].join('\n');
}
};
};

View File

@@ -41,8 +41,21 @@ module.exports = [
},
{
name : 'Background Image',
icon : 'fas fa-times-circle',
gen : ''
icon : 'fas fa-tree',
gen : `<img src='http://i.imgur.com/hMna6G0.png' ` +
`style='position:absolute; top:50px; right:30px; width:280px'/>`
},
{
name : 'QR Code',
icon : 'fas fa-qrcode',
gen : (brew)=>{
return `<img ` +
`src='https://api.qrserver.com/v1/create-qr-code/?data=` +
`https://homebrewery.naturalcrit.com/share/${brew.shareId}` +
`&amp;size=100x100' ` +
`style='width:100px;mix-blend-mode:multiply'/>`;
}
},
{
name : 'Page Number',
@@ -130,6 +143,11 @@ module.exports = [
icon : 'fas fa-file-word',
gen : CoverPageGen,
},
{
name : 'Magic Item',
icon : 'fas fa-hat-wizard',
gen : MagicGen.item,
},
]
},

View File

@@ -48,7 +48,7 @@ const getTOC = (pages)=>{
};
module.exports = function(brew){
const pages = brew.split('\\page');
const pages = brew.text.split('\\page');
const TOC = getTOC(pages);
const markdown = _.reduce(TOC, (r, g1, idx1)=>{
r.push(`- **[${idx1 + 1} ${g1.title}](#p${g1.page})**`);
@@ -69,4 +69,4 @@ module.exports = function(brew){
##### Table Of Contents
${markdown}
</div>\n`;
};
};

View File

@@ -48,7 +48,7 @@ const getTOC = (pages)=>{
};
module.exports = function(brew){
const pages = brew.split('\\page');
const pages = brew.text.split('\\page');
const TOC = getTOC(pages);
const markdown = _.reduce(TOC, (r, g1, idx1)=>{
r.push(`- **[${idx1 + 1} ${g1.title}](#p${g1.page})**`);

View File

@@ -392,9 +392,8 @@ const EditPage = createClass({
<SplitPane onDragFinish={this.handleSplitMove} ref='pane'>
<Editor
ref='editor'
value={this.state.brew.text}
brew={this.state.brew}
onChange={this.handleTextChange}
metadata={this.state.brew}
onMetadataChange={this.handleMetadataChange}
renderer={this.state.brew.renderer}
/>

View File

@@ -21,6 +21,9 @@ const BrewRenderer = require('../../brewRenderer/brewRenderer.jsx');
const HomePage = createClass({
getDefaultProps : function() {
return {
brew : {
text : ''
},
welcomeText : '',
ver : '0.0.0'
};
@@ -29,13 +32,15 @@ const HomePage = createClass({
},
getInitialState : function() {
return {
text : this.props.welcomeText
brew : {
text : this.props.welcomeText
}
};
},
handleSave : function(){
request.post('/api')
.send({
text : this.state.text
text : this.state.brew.text
})
.end((err, res)=>{
if(err) return;
@@ -48,7 +53,7 @@ const HomePage = createClass({
},
handleTextChange : function(text){
this.setState({
text : text
brew : { text: text }
});
},
renderNavbar : function(){
@@ -71,12 +76,12 @@ const HomePage = createClass({
<div className='content'>
<SplitPane onDragFinish={this.handleSplitMove} ref='pane'>
<Editor value={this.state.text} onChange={this.handleTextChange} showMetaButton={false} ref='editor'/>
<BrewRenderer text={this.state.text} />
<Editor brew={this.state.brew} onChange={this.handleTextChange} showMetaButton={false} ref='editor'/>
<BrewRenderer text={this.state.brew.text} />
</SplitPane>
</div>
<div className={cx('floatingSaveButton', { show: this.props.welcomeText != this.state.text })} onClick={this.handleSave}>
<div className={cx('floatingSaveButton', { show: this.props.welcomeText != this.state.brew.text })} onClick={this.handleSave}>
Save current <i className='fas fa-save' />
</div>

View File

@@ -22,7 +22,8 @@ const KEY = 'homebrewery-new';
const NewPage = createClass({
getInitialState : function() {
return {
metadata : {
brew : {
text : '',
gDrive : false,
title : '',
description : '',
@@ -32,7 +33,6 @@ const NewPage = createClass({
systems : []
},
text : '',
isSaving : false,
saveGoogle : (global.account && global.account.googleId ? true : false),
errors : []
@@ -43,7 +43,7 @@ const NewPage = createClass({
const storage = localStorage.getItem(KEY);
if(storage){
this.setState({
text : storage
brew : { text: storage }
});
}
document.addEventListener('keydown', this.handleControlKeys);
@@ -70,13 +70,13 @@ const NewPage = createClass({
handleMetadataChange : function(metadata){
this.setState({
metadata : _.merge({}, this.state.metadata, metadata)
brew : _.merge({}, this.state.brew, metadata)
});
},
handleTextChange : function(text){
this.setState({
text : text,
brew : { text: text },
errors : Markdown.validate(text)
});
localStorage.setItem(KEY, text);
@@ -92,7 +92,7 @@ const NewPage = createClass({
if(this.state.saveGoogle) {
const res = await request
.post('/api/newGoogle/')
.send(_.merge({}, this.state.metadata, { text: this.state.text }))
.send(this.state.brew)
.catch((err)=>{
console.log(err.status === 401
? 'Not signed in!'
@@ -106,9 +106,7 @@ const NewPage = createClass({
window.location = `/edit/${brew.googleId}${brew.editId}`;
} else {
request.post('/api')
.send(_.merge({}, this.state.metadata, {
text : this.state.text
}))
.send(this.state.brew)
.end((err, res)=>{
if(err){
this.setState({
@@ -122,7 +120,6 @@ const NewPage = createClass({
window.location = `/edit/${brew.editId}`;
});
}
},
renderSaveButton : function(){
@@ -138,7 +135,7 @@ const NewPage = createClass({
},
print : function(){
localStorage.setItem('print', this.state.text);
localStorage.setItem('print', this.state.brew.text);
window.open('/print?dialog=true&local=print', '_blank');
},
@@ -152,7 +149,7 @@ const NewPage = createClass({
return <Navbar>
<Nav.section>
<Nav.item className='brewTitle'>{this.state.metadata.title}</Nav.item>
<Nav.item className='brewTitle'>{this.state.brew.title}</Nav.item>
</Nav.section>
<Nav.section>
@@ -172,12 +169,11 @@ const NewPage = createClass({
<SplitPane onDragFinish={this.handleSplitMove} ref='pane'>
<Editor
ref='editor'
value={this.state.text}
brew={this.state.brew}
onChange={this.handleTextChange}
metadata={this.state.metadata}
onMetadataChange={this.handleMetadataChange}
/>
<BrewRenderer text={this.state.text} errors={this.state.errors} />
<BrewRenderer text={this.state.brew.text} errors={this.state.errors} />
</SplitPane>
</div>
</div>;

View File

@@ -4,6 +4,7 @@ const createClass = require('create-react-class');
const _ = require('lodash');
const cx = require('classnames');
const { Meta } = require('vitreum/headtags');
const MarkdownLegacy = require('naturalcrit/markdownLegacy.js');
const Markdown = require('naturalcrit/markdown.js');
const PrintPage = createClass({
@@ -11,7 +12,8 @@ const PrintPage = createClass({
return {
query : {},
brew : {
text : '',
text : '',
renderer : 'legacy'
}
};
},
@@ -33,13 +35,24 @@ const PrintPage = createClass({
},
renderPages : function(){
return _.map(this.state.brewText.split('\\page'), (page, index)=>{
return <div
className='phb'
id={`p${index + 1}`}
dangerouslySetInnerHTML={{ __html: Markdown.render(page) }}
key={index} />;
});
if(this.props.brew.renderer == 'legacy') {
return _.map(this.state.brewText.split('\\page'), (page, index)=>{
return <div
className='phb'
id={`p${index + 1}`}
dangerouslySetInnerHTML={{ __html: MarkdownLegacy.render(page) }}
key={index} />;
});
} else {
return _.map(this.state.brewText.split(/^\\page/gm), (page, index)=>{
return <div
className='phb3'
id={`p${index + 1}`}
dangerouslySetInnerHTML={{ __html: Markdown.render(page) }}
key={index} />;
});
}
},
render : function(){

View File

@@ -60,10 +60,10 @@ body {
// *****************************/
p{
overflow-wrap : break-word;
padding-bottom : 0.8em;
padding-top : 0em;
line-height : 1.3em;
&+p{
margin-top : -0.8em;
padding-top : 0em;
}
}
ul{
@@ -480,3 +480,38 @@ body {
margin-bottom : 10px;
}
}
//*****************************
// * MUSTACHE DIVS/SPANS
// *****************************/
.phb3 {
.inline-block {
display : block;
}
}
//*****************************
// * DEFINITION LISTS
// *****************************/
.phb3 {
// dl {
// margin-top: 10px;
// }
dt {
float: left;
//clear: left; //Doesn't seem necessary
margin-right: 5px;
}
// dd {
// margin-left: 0px;
// }
}
//*****************************
// * BLANK LINE
// *****************************/
.phb3 {
.blank {
height: 0.8em;
}
}

3930
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -3,7 +3,7 @@
"description": "Create authentic looking D&D homebrews using only markdown",
"version": "2.10.7",
"engines": {
"node": "12.16.x"
"node": "14.15.x"
},
"repository": {
"type": "git",
@@ -40,29 +40,29 @@
]
},
"dependencies": {
"@babel/core": "^7.12.10",
"@babel/preset-env": "^7.12.11",
"@babel/preset-react": "^7.12.10",
"@babel/core": "^7.13.1",
"@babel/preset-env": "^7.13.5",
"@babel/preset-react": "^7.12.13",
"body-parser": "^1.19.0",
"classnames": "^2.2.6",
"codemirror": "^5.59.2",
"codemirror": "^5.59.4",
"cookie-parser": "^1.4.5",
"create-react-class": "^15.7.0",
"express": "^4.17.1",
"express-static-gzip": "2.1.1",
"fs-extra": "9.1.0",
"googleapis": "67.0.0",
"googleapis": "67.1.0",
"jwt-simple": "^0.5.6",
"less": "^3.13.1",
"lodash": "^4.17.20",
"lodash": "^4.17.21",
"moment": "^2.29.1",
"mongoose": "^5.11.13",
"mongoose": "^5.11.18",
"nanoid": "3.1.20",
"markedLegacy": "npm:marked@^0.3.19",
"marked": "npm:marked@^1.2.7",
"nconf": "^0.11.1",
"marked": "2.0.0",
"nconf": "^0.11.2",
"prop-types": "15.7.2",
"query-string": "6.13.8",
"query-string": "6.14.0",
"react": "^16.14.0",
"react-dom": "^16.14.0",
"react-frame-component": "4.1.3",
@@ -71,7 +71,7 @@
"vitreum": "github:calculuschild/vitreum#21a8e1c9421f1d3a3b474c12f480feb2fbd28c5b"
},
"devDependencies": {
"eslint": "^7.18.0",
"eslint": "^7.20.0",
"eslint-plugin-react": "^7.22.0",
"pico-check": "^2.0.3"
}

View File

@@ -1,2 +1,4 @@
# Notes
User-agent: *
Disallow: /edit/

View File

@@ -19,7 +19,6 @@ const build = async ({ bundle, render, ssr })=>{
await fs.outputFile('./build/homebrew/bundle.css', css);
await fs.outputFile('./build/homebrew/bundle.js', bundle);
await fs.outputFile('./build/homebrew/ssr.js', ssr);
await fs.outputFile('./build/homebrew/render.js', render);
await fs.copy('./client/homebrew/phbStyle/fonts', './build/fonts');
//compress files in production
@@ -49,6 +48,6 @@ pack('./client/homebrew/homebrew.jsx', {
if(isDev){
livereload('./build');
watchFile('./server.js', {
watch : ['./homebrew'] // Watch additional folders if you want
watch : ['./client'] // Watch additional folders if you want
});
}

View File

@@ -1,18 +1,13 @@
const _ = require('lodash');
const jwt = require('jwt-simple');
const expressStaticGzip = require('express-static-gzip');
const express = require('express');
const app = express();
const homebrewApi = require('./server/homebrew.api.js');
const GoogleActions = require('./server/googleActions.js');
const serveCompressedStaticAssets = require('./server/static-assets.mv.js');
// Serve brotli-compressed static files if available
app.use('/', expressStaticGzip(`${__dirname}/build`, {
enableBrotli : true,
orderPreference : ['br'],
index : false
}));
app.use('/', serveCompressedStaticAssets(`${__dirname}/build`));
process.chdir(__dirname);
@@ -30,7 +25,7 @@ const config = require('nconf')
//DB
const mongoose = require('mongoose');
mongoose.connect(config.get('mongodb_uri') || config.get('mongolab_uri') || 'mongodb://localhost/naturalcrit',
{ retryWrites: false, useNewUrlParser: true });
{ retryWrites: false, useNewUrlParser: true, useCreateIndex: true, useUnifiedTopology: true });
mongoose.connection.on('error', ()=>{
console.log('Error : Could not connect to a Mongo Database.');
console.log(' If you are running locally, make sure mongodb.exe is running.');

View File

@@ -11,9 +11,12 @@ const Markdown = require('../shared/naturalcrit/markdown.js');
// });
// };
const MAX_TITLE_LENGTH = 100;
const getGoodBrewTitle = (text)=>{
const tokens = Markdown.marked.lexer(text);
return title = (tokens.find((token)=>token.type == 'heading' || token.type == 'paragraph') || { text: 'No Title' }).text;
return (tokens.find((token)=>token.type == 'heading' || token.type == 'paragraph')?.text || 'No Title')
.slice(0, MAX_TITLE_LENGTH);
};
const newBrew = (req, res)=>{

View File

@@ -0,0 +1,31 @@
const expressStaticGzip = require('express-static-gzip');
// Serve brotli-compressed static files if available
const customCacheControlHandler=(response, path)=>{
if(path.endsWith('.br')) {
// Drop .br suffix to help mime understand the actual type of the file
path = path.slice(0, -3);
}
if(path.endsWith('.js') || path.endsWith('.css')) {
// .js and .css files are allowed to be cached up to 12 hours, but then
// they must be revalidated to see if there are any updates
response.setHeader('Cache-Control', 'public, max-age: 43200, must-revalidate');
} else {
// Everything else is cached up to a months as we don't update our images
// or fonts frequently
response.setHeader('Cache-Control', 'public, max-age=2592000, must-revalidate');
}
};
const init=(pathToAssets)=>{
return expressStaticGzip(pathToAssets, {
enableBrotli : true,
orderPreference : ['br'],
index : false,
serveStatic : {
cacheControl : false, // we are going to use custom cache-control
setHeaders : customCacheControlHandler
} });
};
module.exports = init;

View File

@@ -34,7 +34,11 @@ const CodeEditor = createClass({
mode : this.props.language,
extraKeys : {
'Ctrl-B' : this.makeBold,
'Ctrl-I' : this.makeItalic
'Cmd-B' : this.makeBold,
'Ctrl-I' : this.makeItalic,
'Cmd-I' : this.makeItalic,
'Ctrl-M' : this.makeSpan,
'Cmd-M' : this.makeSpan,
}
});
@@ -44,8 +48,8 @@ const CodeEditor = createClass({
},
makeBold : function() {
const selection = this.codeMirror.getSelection();
this.codeMirror.replaceSelection(`**${selection}**`, 'around');
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 2) === '**' && selection.slice(-2) === '**';
this.codeMirror.replaceSelection(t ? selection.slice(2, -2) : `**${selection}**`, 'around');
if(selection.length === 0){
const cursor = this.codeMirror.getCursor();
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - 2 });
@@ -53,14 +57,23 @@ const CodeEditor = createClass({
},
makeItalic : function() {
const selection = this.codeMirror.getSelection();
this.codeMirror.replaceSelection(`*${selection}*`, 'around');
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 1) === '_' && selection.slice(-1) === '_';
this.codeMirror.replaceSelection(t ? selection.slice(1, -1) : `_${selection}_`, 'around');
if(selection.length === 0){
const cursor = this.codeMirror.getCursor();
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - 1 });
}
},
makeSpan : function() {
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 2) === '{{' && selection.slice(-2) === '}}';
this.codeMirror.replaceSelection(t ? selection.slice(2, -2) : `{{ ${selection}}}`, 'around');
if(selection.length === 0){
const cursor = this.codeMirror.getCursor();
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - 2 });
}
},
componentDidUpdate : function(prevProps) {
if(this.codeMirror && this.codeMirror.getValue() != this.props.value) {
this.codeMirror.setValue(this.props.value);

View File

@@ -11,56 +11,31 @@ renderer.html = function (html) {
html = html.substring(0, html.lastIndexOf('</div>'));
return `${openTag} ${Markdown(html)} </div>`;
}
// if(_.startsWith(_.trim(html), '<style') && _.endsWith(_.trim(html), '</style>')){
// const openTag = html.substring(0, html.indexOf('>')+1);
// html = html.substring(html.indexOf('>')+1);
// html = html.substring(0, html.lastIndexOf('</style>'));
// html = html.replaceAll(/\s(\.[^{]*)/gm, '.V3 $1');
// return `${openTag} ${html} </style>`;
// }
return html;
};
// Ensure {{ Divs don't confuse paragraph parsing (else it renders empty paragraphs)
// Don't wrap {{ Divs or {{ empty Spans in <p> tags
renderer.paragraph = function(text){
let match;
if(text.startsWith('<div') || text.startsWith('</div'))
return `${text}`;
else if(match = text.match(/(^|^.*?\n)<span class="inline([^>]*><\/span>)$/))
return `<p>${match[1]}</p><span class="inline-block"${match[2]}`;
else
return `<p>${text}</p>\n`;
};
// Mustache-style Divs {{class \n content ... \n}}
let blockCount = 0;
const blockRegex = /^ *{{(?:="[\w, ]*"|[^"'\s])*$|^ *}}$/gm;
const blockRegex = /^ *{{(?:="[\w,\-. ]*"|[^"'\s])*$|^ *}}$/gm;
const inlineFullRegex = /{{[^\n]*}}/g;
const inlineRegex = /{{(?:="[\w, ]*"|[^"'\s])*\s*|}}/g;
const inlineRegex = /{{(?:="[\w,\-. ]*"|[^"'{}}\s])*\s*|}}/g;
renderer.text = function(text){
const newText = text.replaceAll('&quot;', '"');
let matches;
//DIV - BLOCK-LEVEL
if(matches = newText.match(blockRegex)) {
let matchIndex = 0;
const res = _.reduce(newText.split(blockRegex), (r, splitText)=>{
if(splitText) r.push(Markdown.parseInline(splitText, { renderer: renderer }));
const block = matches[matchIndex] ? matches[matchIndex].trimLeft() : '';
if(block && block.startsWith('{')) {
const values = processStyleTags(block.substring(2));
r.push(`<div class="block ${values}">`);
blockCount++;
} else if(block == '}}' && blockCount !== 0){
r.push('</div>');
blockCount--;
}
matchIndex++;
return r;
}, []).join('');
return res;
} else if(matches = newText.match(inlineFullRegex)) {
if(matches = newText.match(inlineFullRegex)) {
//SPAN - INLINE
matches = newText.match(inlineRegex);
@@ -72,7 +47,7 @@ renderer.text = function(text){
const block = matches[matchIndex] ? matches[matchIndex].trimLeft() : '';
if(block && block.startsWith('{{')) {
const values = processStyleTags(block.substring(2));
r.push(`<span class="inline-block ${values}>`);
r.push(`<span class="inline ${values}>`);
blockCount++;
} else if(block == '}}' && blockCount !== 0){
r.push('</span>');
@@ -84,7 +59,28 @@ renderer.text = function(text){
return r;
}, []).join('');
return `${res}`;
} else {
} else if(matches = newText.match(blockRegex)) {
//DIV - BLOCK-LEVEL
let matchIndex = 0;
const res = _.reduce(newText.split(blockRegex), (r, splitText)=>{
if(splitText) r.push(Markdown.parseInline(splitText, { renderer: renderer }));
const block = matches[matchIndex] ? matches[matchIndex].trimLeft() : '';
if(block && block.startsWith('{')) {
const values = processStyleTags(block.substring(2));
r.push(`<div class="block ${values}">`);
blockCount++;
} else if(block == '}}' && blockCount !== 0){
r.push('</div>');
blockCount--;
}
matchIndex++;
return r;
}, []).join('');
return res;
} else {
if(!matches) {
return `${text}`;
}
@@ -188,9 +184,13 @@ module.exports = {
marked : Markdown,
render : (rawBrewText)=>{
blockCount = 0;
rawBrewText = rawBrewText.replace(/^\\column/gm, `<div class='columnSplit'></div>`)
rawBrewText = rawBrewText.replace(/^\\column$/gm, `<div class='columnSplit'></div>`)
.replace(/^(:+)$/gm, (match)=>`${`<div class='blank'></div>`.repeat(match.length)}\n`)
.replace(/(?:^|>) *:([^:\n]*):([^\n]*)\n/gm, (match, term, def)=>`<dt>${Markdown.parseInline(term)}</dt><dd>${def}</dd>`)
.replace(/(<dt>.*<\/dt><dd>.*<\/dd>\n?)+/gm, `<dl>$1</dl>\n\n`)
.replace(/^}}/gm, '\n}}')
.replace(/^({{[^\n]*)$/gm, '$1\n');
console.log(rawBrewText);
return Markdown(
sanatizeScriptTags(rawBrewText),
{ renderer: renderer }