mirror of
https://github.com/naturalcrit/homebrewery.git
synced 2026-01-20 07:32:43 +00:00
Merge branch 'master' into document-tags
# Conflicts: # client/homebrew/editor/metadataEditor/metadataEditor.jsx # server/homebrew.api.js
This commit is contained in:
@@ -2,17 +2,23 @@
|
||||
#
|
||||
# Check https://circleci.com/docs/2.0/language-javascript/ for more details
|
||||
#
|
||||
version: 2
|
||||
version: 2.1
|
||||
|
||||
orbs:
|
||||
node: circleci/node@3.0.0
|
||||
|
||||
jobs:
|
||||
build:
|
||||
docker:
|
||||
- image: circleci/node:16.10.0
|
||||
- image: circleci/mongo:4.4
|
||||
- image: cimg/node:16.11.0
|
||||
- image: mongo:4.4
|
||||
|
||||
working_directory: ~/repo
|
||||
working_directory: ~/homebrewery
|
||||
executor: node/default
|
||||
|
||||
steps:
|
||||
- checkout
|
||||
- checkout:
|
||||
path: ~/homebrewery
|
||||
|
||||
# Download and cache dependencies
|
||||
- restore_cache:
|
||||
@@ -21,12 +27,48 @@ jobs:
|
||||
# fallback to using the latest cache if no exact match is found
|
||||
- v1-dependencies-
|
||||
|
||||
- run: npm install
|
||||
- node/install-npm
|
||||
- node/install-packages:
|
||||
app-dir: ~/homebrewery
|
||||
cache-path: node_modules
|
||||
override-ci-command: npm i
|
||||
|
||||
- save_cache:
|
||||
paths:
|
||||
- node_modules
|
||||
key: v1-dependencies-{{ checksum "package.json" }}
|
||||
|
||||
- persist_to_workspace:
|
||||
root: .
|
||||
paths:
|
||||
- .
|
||||
|
||||
test:
|
||||
docker:
|
||||
- image: cimg/node:16.11.0
|
||||
|
||||
working_directory: ~/homebrewery
|
||||
parallelism: 4
|
||||
|
||||
steps:
|
||||
- attach_workspace:
|
||||
at: .
|
||||
|
||||
# run tests!
|
||||
- run: npm run circleci
|
||||
- run:
|
||||
name: Test - Basic
|
||||
command: npm run test:basic
|
||||
- run:
|
||||
name: Test - Mustache Spans
|
||||
command: npm run test:mustache-span
|
||||
- run:
|
||||
name: Test - Routes
|
||||
command: npm run test:route
|
||||
|
||||
workflows:
|
||||
build_and_test:
|
||||
jobs:
|
||||
- build
|
||||
- test:
|
||||
requires:
|
||||
- build
|
||||
57
README.md
57
README.md
@@ -9,37 +9,37 @@ using [Markdown][markdown-url]. It is distributed under the terms of the [MIT Li
|
||||
[markdown-url]: https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet
|
||||
|
||||
## Quick Start
|
||||
The easiest way to get started using the Homebrewery is to use it
|
||||
The easiest way to get started using The Homebrewery is to use it
|
||||
[on our website][homebrewery-url]. The code is open source, so feel free to
|
||||
clone it, tinker with it. If you want to make changes to the code, you can run
|
||||
clone it and tinker with it. If you want to make changes to the code, you can run
|
||||
your own local version for testing by following the installation instructions
|
||||
below.
|
||||
|
||||
[homebrewery-url]: https://homebrewery.naturalcrit.com
|
||||
|
||||
### Installation
|
||||
First, install three programs that the Homebrewery requires to run and retrieve
|
||||
First, install three programs that The Homebrewery requires to run and retrieve
|
||||
updates:
|
||||
|
||||
1. install [node](https://nodejs.org/en/)
|
||||
1. install [mongodb](https://www.mongodb.com/try/download/community) (Community version)
|
||||
|
||||
For easiest installation, follow these steps:
|
||||
1. In the installer, uncheck the option to run as a service
|
||||
1. You can install MongoDB Compass if you want a GUI to view your database documents
|
||||
1. Go to the C drive and create a folder called "data"
|
||||
1. Inside the "data" folder, create a new folder called "db"
|
||||
1. Open a command prompt or other terminal and navigate to your mongodb install folder (c:program files\mongo\server\4.4\bin)
|
||||
1. In the command prompt, run "mongod", which will start up your local database server
|
||||
1. While MongoD is running, open a second command prompt and navigate to the mongodb install folder
|
||||
1. In the second command prompt, run "mongo", which allows you to edit the database
|
||||
1. Type `use homebrewery` to create the homebrewery database. You should see `switched to db homebrewery`
|
||||
1. Type `db.brews.insert({"title":"test"})` to create a blank document. You should see `WriteResult({ "nInserted" : 1 })`
|
||||
1. Search in Windows for "Advanced system settings" and open it
|
||||
1. Click "Environment variables", find the "path" variable, and double-click to open it
|
||||
1. Click "New" and paste in the path to the mongodb "bin" folder
|
||||
1. Click "OK", "OK", "OK" to close all the windows
|
||||
1. install [git](https://git-scm.com/downloads) (select the option that allows Git to run from the command prompt)
|
||||
For the easiest installation, follow these steps:
|
||||
1. In the installer, uncheck the option to run as a service.
|
||||
1. You can install MongoDB Compass if you want a GUI to view your database documents.
|
||||
1. Go to the C:\ drive and create a folder called "data".
|
||||
1. Inside the "data" folder, create a new folder called "db".
|
||||
1. Open a command prompt or other terminal and navigate to your MongoDB install folder (C:\Program Files\Mongo\Server\4.4\bin).
|
||||
1. In the command prompt, run "mongod", which will start up your local database server.
|
||||
1. While MongoD is running, open a second command prompt and navigate to the MongoDB install folder.
|
||||
1. In the second command prompt, run "mongo", which allows you to edit the database.
|
||||
1. Type `use homebrewery` to create The Homebrewery database. You should see `switched to db homebrewery`.
|
||||
1. Type `db.brews.insert({"title":"test"})` to create a blank document. You should see `WriteResult({ "nInserted" : 1 })`.
|
||||
1. Search in Windows for "Advanced system settings" and open it.
|
||||
1. Click "Environment variables", find the "path" variable, and double-click to open it.
|
||||
1. Click "New" and paste in the path to the MongoDB "bin" folder.
|
||||
1. Click "OK" three times to close all the windows.
|
||||
1. install [git](https://git-scm.com/downloads) (select the option that allows Git to run from the command prompt).
|
||||
|
||||
Checkout the repo ([documentation][github-clone-repo-docs-url]):
|
||||
```
|
||||
@@ -54,7 +54,7 @@ the project to run locally.
|
||||
You can set this temporarily in your shell of choice:
|
||||
* Windows Powershell: `$env:NODE_ENV="local"`
|
||||
* Windows CMD: `set NODE_ENV=local`
|
||||
* Linux / OSX: `export NODE_ENV=local`
|
||||
* Linux / macOS: `export NODE_ENV=local`
|
||||
|
||||
Third, you will need to install the Node dependencies, compile the app, and run
|
||||
it using the two commands:
|
||||
@@ -63,7 +63,7 @@ it using the two commands:
|
||||
1. `npm start`
|
||||
|
||||
You should now be able to go to [http://localhost:8000](http://localhost:8000)
|
||||
in your browser and use the Homebrewery offline.
|
||||
in your browser and use The Homebrewery offline.
|
||||
|
||||
### Running the application via Docker
|
||||
|
||||
@@ -95,11 +95,11 @@ You can check out the [changelog](./changelog.md).
|
||||
|
||||
## License
|
||||
|
||||
This project is licensed under the [MIT license](./license). Which means you
|
||||
This project is licensed under the [MIT license](./license), which means you
|
||||
are free to use The Homebrewery in any way that you want, except for claiming
|
||||
that you made it yourself.
|
||||
|
||||
If you wish to sell or in some way gain profit for what's created on this site,
|
||||
If you wish to sell, or in some way gain profit for, what's created on this site,
|
||||
it's your responsibility to ensure you have the proper licenses/rights for any
|
||||
images or resources used.
|
||||
|
||||
@@ -108,13 +108,12 @@ images or resources used.
|
||||
You are welcome to contribute to the development and maintenance of the
|
||||
project! There are several ways of doing that:
|
||||
- At the moment, we have a huge backlog of [issues][repo-issues-url] and some
|
||||
of them are outdated, duplicates or doesn't contain any useful info. In order
|
||||
to help you can [mark duplicates][github-mark-duplicate-url], try to
|
||||
reproduce some complex or weird issues, try with finding a workaround for a
|
||||
reported bug or just mention issue managers team to let them know about
|
||||
outdated issue via `@naturalcrit/issue-managers`.
|
||||
of them are outdated, duplicates, or don't contain any useful info. To help, you can [mark duplicates][github-mark-duplicate-url], try to
|
||||
reproduce some complex or weird issues, try finding a workaround for a
|
||||
reported bug, or just mention our issue managers team to let them know about
|
||||
outdated issues via `@naturalcrit/issue-managers`.
|
||||
- Our [subreddit][subreddit-url] is constantly growing and there are number of
|
||||
bug reports: any help with sorting them out is very welcome.
|
||||
bug reports. Any help with sorting them out is very welcome.
|
||||
- And of course you can contribute by fixing a bug or implementing a new
|
||||
feature by yourself, we are waiting for your
|
||||
[pull requests][github-pr-docs-url]!
|
||||
|
||||
162
changelog.md
162
changelog.md
@@ -3,11 +3,12 @@ h5 {
|
||||
font-size: .35cm !important;
|
||||
}
|
||||
|
||||
.taskList li {
|
||||
list-style-type : none;
|
||||
.page ul ul {
|
||||
margin-left: 0px;
|
||||
}
|
||||
|
||||
.taskList li input {
|
||||
list-style-type : none;
|
||||
margin-left : -0.52cm;
|
||||
transform: translateY(.05cm);
|
||||
filter: brightness(1.1) drop-shadow(1px 2px 1px #222);
|
||||
@@ -28,11 +29,162 @@ pre {
|
||||
.page p + pre {
|
||||
margin-top : 0.1cm;
|
||||
}
|
||||
|
||||
.page .openSans {
|
||||
font-family: 'Open Sans';
|
||||
font-size: 0.9em;
|
||||
}
|
||||
```
|
||||
|
||||
## changelog
|
||||
For a full record of development, visit our [Github Page](https://github.com/naturalcrit/homebrewery).
|
||||
|
||||
### Thursday 09/06/2022 - v3.1.1
|
||||
{{taskList
|
||||
|
||||
##### Calculuschild:
|
||||
|
||||
* [x] Fixed class table decorations appearing on top of the table in PDF output.
|
||||
|
||||
Fixes issues: [#1784](https://github.com/naturalcrit/homebrewery/issues/1784)
|
||||
|
||||
* [x] Fix bottom decoration on half class tables disappearing when the table is too short.
|
||||
|
||||
Fixes issues: [#2202](https://github.com/naturalcrit/homebrewery/issues/2202)
|
||||
}}
|
||||
|
||||
### Monday 06/06/2022 - v3.1.0
|
||||
{{taskList
|
||||
|
||||
##### G-Ambatte:
|
||||
|
||||
* [x] "Jump to Preview/Editor" buttons added to the divider bar. Easily sync between the editor and preview panels!
|
||||
|
||||
Fixes issues: [#1756](https://github.com/naturalcrit/homebrewery/issues/1756)
|
||||
|
||||
* [x] Speedups to the user page for users with large and/or many brews.
|
||||
|
||||
Fixes issues: [#2147](https://github.com/naturalcrit/homebrewery/issues/2147)
|
||||
|
||||
* [x] Search text on the user page is saved to the URL for easy bookmarking in your browser
|
||||
|
||||
Fixes issues: [#1858](https://github.com/naturalcrit/homebrewery/issues/1858)
|
||||
|
||||
* [x] Added easy login system for offline installs.
|
||||
|
||||
Fixes issues: [#269](https://github.com/naturalcrit/homebrewery/issues/269)
|
||||
|
||||
* [x] New **THUMBNAIL** option in the {{fa,fa-info-circle}} **Properties** menu. This image will show up in social media links.
|
||||
|
||||
Fixes issues: [#820](https://github.com/naturalcrit/homebrewery/issues/820)
|
||||
}}
|
||||
|
||||
### Wednesday 27/03/2022 - v3.0.8
|
||||
{{taskList
|
||||
* [x] Style updates to user page.
|
||||
|
||||
* [x] Added a logout button (finally)! You can find it under {{openSans **USERNAME {{fa,fa-user}} → LOGOUT {{fas,fa-power-off}}**}}
|
||||
|
||||
Fixes issues: [#303](https://github.com/naturalcrit/homebrewery/issues/303)
|
||||
|
||||
* [x] Clarified the default text when submitting an issue via Reddit post.
|
||||
|
||||
* [x] Fixed broken Table of Contents links in PDFs. (Thanks lucastucious!)
|
||||
|
||||
Fixes issues: [#1749](https://github.com/naturalcrit/homebrewery/issues/1749)
|
||||
|
||||
* [x] Fixed window resizing causing the edit page divider to get lost off of the edge of the page.
|
||||
|
||||
Fixes issues: [#2053](https://github.com/naturalcrit/homebrewery/issues/2053)
|
||||
|
||||
* [x] Fixed Class Table decorations overlapping main text.
|
||||
|
||||
Fixes issues: [#1985](https://github.com/naturalcrit/homebrewery/issues/1985)
|
||||
|
||||
* [x] Updated {{openSans **STYLE EDITOR {{fa,fa-pencil-alt}} → REMOVE DROP CAP {{fas,fa-remove-format}}**}} snippet to also remove small-caps first line font.
|
||||
|
||||
* [x] Background work in preparation for brew themes.
|
||||
}}
|
||||
|
||||
### Wednesday 02/02/2022 - v3.0.7
|
||||
{{taskList
|
||||
* [x] Revert active line highlighting.
|
||||
|
||||
Fixes issues: [#1913](https://github.com/naturalcrit/homebrewery/issues/1913)
|
||||
|
||||
* [x] Added install steps for Ubuntu. [HERE](https://github.com/naturalcrit/homebrewery/blob/master/install/README.UBUNTU.md)
|
||||
|
||||
Fixes issues: [#1900](https://github.com/naturalcrit/homebrewery/issues/1900)
|
||||
|
||||
* [x] Added social media links to home page.
|
||||
|
||||
* [x] Increase brews visible on the user page to 1,000.
|
||||
|
||||
Fixes issues: [#1943](https://github.com/naturalcrit/homebrewery/issues/1943)
|
||||
|
||||
* [x] Added a Legacy to V3 migration guide under {{openSans **NEED HELP? {{fa,fa-question-circle}} → MIGRATE {{fas,fa-file-import}}**}}
|
||||
|
||||
* [x] Background refactoring and unit tests.
|
||||
}}
|
||||
|
||||
### Saturday 18/12/2021 - v3.0.6
|
||||
{{taskList
|
||||
* [x] Fixed text wrapping for long strings in code blocks.
|
||||
|
||||
Fixes issues: [#1736](https://github.com/naturalcrit/homebrewery/issues/1736)
|
||||
|
||||
* [x] Code search/replace PC: `CTRL F / CTRL SHIFT F` / Mac: `CMD F / OPTION CMD F`
|
||||
|
||||
Fixes issues: [#1201](https://github.com/naturalcrit/homebrewery/issues/1201)
|
||||
|
||||
* [x] Auto-closing HTML tags and curly braces `{{ }}`
|
||||
* [x] Highlight current active line
|
||||
|
||||
Fixes issues: [#1202](https://github.com/naturalcrit/homebrewery/issues/1202)
|
||||
|
||||
* [x] Display tabs and trailing spaces
|
||||
|
||||
Fixes issues: [#1622](https://github.com/naturalcrit/homebrewery/issues/1622)
|
||||
|
||||
* [x] Make columns even in V3 Table of Contents.
|
||||
|
||||
Fixes issues: [#1671](https://github.com/naturalcrit/homebrewery/issues/1671)
|
||||
|
||||
* [x] Fix `CTRL P` failing to print from `/new` pages.
|
||||
|
||||
Fixes issues: [#1815](https://github.com/naturalcrit/homebrewery/issues/1815)
|
||||
}}
|
||||
|
||||
\page
|
||||
|
||||
### Tuesday 07/12/2021 - v3.0.5
|
||||
{{taskList
|
||||
* [x] Fixed paragraph spacing for **note** and **descriptive** boxes in V3.
|
||||
|
||||
Fixes issues: [#1836](https://github.com/naturalcrit/homebrewery/issues/1836)
|
||||
|
||||
* [x] Added a whole bunch of hotkeys:
|
||||
|
||||
* Page Break `CTRL + ENTER`
|
||||
* Column Break `CTRL + SHIFT + ENTER`
|
||||
* Bulleted Lists `CTRL + L`
|
||||
* Numbered Lists `CTRL + SHIFT + L`
|
||||
* Headers `CTRL + SHIFT + (1-6)`
|
||||
* Underline `CTRL + U`
|
||||
* Link `CTRL + K`
|
||||
* Non-breaking space (\ ) `CTRL + .`
|
||||
* Add Horizontal Space `CTRL + SHIFT + .`
|
||||
* Remove Horizontal Space `CTRL + SHIFT + ,`
|
||||
* Curly Span `CTRL + M`
|
||||
* Curly Div `CTRL + SHIFT + M`
|
||||
|
||||
* [x] Fixed page numbers in the editor panel getting scrambled when scrolling up and down.
|
||||
|
||||
* [x] Faster swapping between tabs on long brews.
|
||||
|
||||
* [x] Better error messages for common issue with Google Drive credentials expiring.
|
||||
}}
|
||||
|
||||
### Wednesday 17/11/2021 - v3.0.4
|
||||
{{taskList
|
||||
* [x] Fixed incorrect sorting of Google brews by page count and views on the user page.
|
||||
@@ -69,6 +221,12 @@ For a full record of development, visit our [Github Page](https://github.com/nat
|
||||
|
||||
* [x] Added {{fa,fa-undo}} **Undo** and {{fa,fa-redo}} **Redo** buttons to the snippet bar.
|
||||
|
||||
}}
|
||||
|
||||
\column
|
||||
|
||||
{{taskList
|
||||
|
||||
* [x] Switching between the {{fa,fa-beer}} **Brew** and {{fa,fa-paint-brush}} **Style** tabs no longer loses your scroll position or undo history.
|
||||
|
||||
Fixes issues: [#1735](https://github.com/naturalcrit/homebrewery/issues/1735)
|
||||
|
||||
@@ -17,6 +17,7 @@ const PAGE_HEIGHT = 1056;
|
||||
const PPR_THRESHOLD = 50;
|
||||
|
||||
const BrewRenderer = createClass({
|
||||
displayName : 'BrewRenderer',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
text : '',
|
||||
@@ -187,7 +188,7 @@ const BrewRenderer = createClass({
|
||||
</div>
|
||||
: null}
|
||||
|
||||
<Frame initialContent={this.state.initialContent}
|
||||
<Frame id='BrewRenderer' initialContent={this.state.initialContent}
|
||||
style={{ width: '100%', height: '100%', visibility: this.state.visibility }}
|
||||
contentDidMount={this.frameDidMount}>
|
||||
<div className={'brewRenderer'}
|
||||
|
||||
@@ -5,6 +5,7 @@ const _ = require('lodash');
|
||||
const cx = require('classnames');
|
||||
|
||||
const ErrorBar = createClass({
|
||||
displayName : 'ErrorBar',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
errors : []
|
||||
|
||||
@@ -7,6 +7,7 @@ const cx = require('classnames'); //Unused variable
|
||||
const DISMISS_KEY = 'dismiss_notification09-9-21';
|
||||
|
||||
const NotificationPopup = createClass({
|
||||
displayName : 'NotificationPopup',
|
||||
getInitialState : function() {
|
||||
return {
|
||||
notifications : {}
|
||||
|
||||
@@ -26,6 +26,7 @@ const splice = function(str, index, inject){
|
||||
|
||||
|
||||
const Editor = createClass({
|
||||
displayName : 'Editor',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
brew : {
|
||||
@@ -60,8 +61,14 @@ const Editor = createClass({
|
||||
window.removeEventListener('resize', this.updateEditorSize);
|
||||
},
|
||||
|
||||
componentDidUpdate : function() {
|
||||
componentDidUpdate : function(prevProps, prevState, snapshot) {
|
||||
this.highlightCustomMarkdown();
|
||||
if(prevProps.moveBrew !== this.props.moveBrew) {
|
||||
this.brewJump();
|
||||
};
|
||||
if(prevProps.moveSource !== this.props.moveSource) {
|
||||
this.sourceJump();
|
||||
};
|
||||
},
|
||||
|
||||
updateEditorSize : function() {
|
||||
@@ -89,15 +96,20 @@ const Editor = createClass({
|
||||
},
|
||||
|
||||
handleViewChange : function(newView){
|
||||
this.props.setMoveArrows(newView === 'text');
|
||||
this.setState({
|
||||
view : newView
|
||||
}, this.updateEditorSize); //TODO: not sure if updateeditorsize needed
|
||||
},
|
||||
|
||||
getCurrentPage : function(){
|
||||
const lines = this.props.brew.text.split('\n').slice(0, this.cursorPosition.line + 1);
|
||||
const lines = this.props.brew.text.split('\n').slice(0, this.refs.codeEditor.getCursorPosition().line + 1);
|
||||
return _.reduce(lines, (r, line)=>{
|
||||
if(line.indexOf('\\page') !== -1) r++;
|
||||
if(
|
||||
(this.props.renderer == 'legacy' && line.indexOf('\\page') !== -1)
|
||||
||
|
||||
(this.props.renderer == 'V3' && line.match(/^\\page$/))
|
||||
) r++;
|
||||
return r;
|
||||
}, 1);
|
||||
},
|
||||
@@ -107,73 +119,143 @@ const Editor = createClass({
|
||||
if(this.state.view === 'text') {
|
||||
const codeMirror = this.refs.codeEditor.codeMirror;
|
||||
|
||||
//reset custom text styles
|
||||
const customHighlights = codeMirror.getAllMarks().filter((mark)=>!mark.__isFold); //Don't undo code folding
|
||||
for (let i=0;i<customHighlights.length;i++) customHighlights[i].clear();
|
||||
codeMirror.operation(()=>{ // Batch CodeMirror styling
|
||||
//reset custom text styles
|
||||
const customHighlights = codeMirror.getAllMarks().filter((mark)=>!mark.__isFold); //Don't undo code folding
|
||||
for (let i=customHighlights.length - 1;i>=0;i--) customHighlights[i].clear();
|
||||
|
||||
const lineNumbers = _.reduce(this.props.brew.text.split('\n'), (r, line, lineNumber)=>{
|
||||
let editorPageCount = 2; // start page count from page 2
|
||||
|
||||
//reset custom line styles
|
||||
codeMirror.removeLineClass(lineNumber, 'background');
|
||||
codeMirror.removeLineClass(lineNumber, 'text');
|
||||
_.forEach(this.props.brew.text.split('\n'), (line, lineNumber)=>{
|
||||
|
||||
// Legacy Codemirror styling
|
||||
if(this.props.renderer == 'legacy') {
|
||||
if(line.includes('\\page')){
|
||||
//reset custom line styles
|
||||
codeMirror.removeLineClass(lineNumber, 'background', 'pageLine');
|
||||
codeMirror.removeLineClass(lineNumber, 'text');
|
||||
codeMirror.removeLineClass(lineNumber, 'wrap', 'sourceMoveFlash');
|
||||
|
||||
// Styling for \page breaks
|
||||
if((this.props.renderer == 'legacy' && line.includes('\\page')) ||
|
||||
(this.props.renderer == 'V3' && line.match(/^\\page$/))) {
|
||||
|
||||
// add back the original class 'background' but also add the new class '.pageline'
|
||||
codeMirror.addLineClass(lineNumber, 'background', 'pageLine');
|
||||
r.push(lineNumber);
|
||||
}
|
||||
}
|
||||
const pageCountElement = Object.assign(document.createElement('span'), {
|
||||
className : 'editor-page-count',
|
||||
textContent : editorPageCount
|
||||
});
|
||||
codeMirror.setBookmark({ line: lineNumber, ch: line.length }, pageCountElement);
|
||||
|
||||
// New Codemirror styling for V3 renderer
|
||||
if(this.props.renderer == 'V3') {
|
||||
if(line.match(/^\\page$/)){
|
||||
codeMirror.addLineClass(lineNumber, 'background', 'pageLine');
|
||||
r.push(lineNumber);
|
||||
}
|
||||
editorPageCount += 1;
|
||||
};
|
||||
|
||||
if(line.match(/^\\column$/)){
|
||||
codeMirror.addLineClass(lineNumber, 'text', 'columnSplit');
|
||||
r.push(lineNumber);
|
||||
}
|
||||
|
||||
// Highlight inline spans {{content}}
|
||||
if(line.includes('{{') && line.includes('}}')){
|
||||
const regex = /{{(?::(?:"[\w,\-()#%. ]*"|[\w\,\-()#%.]*)|[^"'{}\s])*\s*|}}/g;
|
||||
let match;
|
||||
let blockCount = 0;
|
||||
while ((match = regex.exec(line)) != null) {
|
||||
if(match[0].startsWith('{')) {
|
||||
blockCount += 1;
|
||||
} else {
|
||||
blockCount -= 1;
|
||||
}
|
||||
if(blockCount < 0) {
|
||||
blockCount = 0;
|
||||
continue;
|
||||
}
|
||||
codeMirror.markText({ line: lineNumber, ch: match.index }, { line: lineNumber, ch: match.index + match[0].length }, { className: 'inline-block' });
|
||||
// New Codemirror styling for V3 renderer
|
||||
if(this.props.renderer == 'V3') {
|
||||
if(line.match(/^\\column$/)){
|
||||
codeMirror.addLineClass(lineNumber, 'text', 'columnSplit');
|
||||
}
|
||||
} else if(line.trimLeft().startsWith('{{') || line.trimLeft().startsWith('}}')){
|
||||
// Highlight block divs {{\n Content \n}}
|
||||
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])*\s*|}}/g;
|
||||
let match;
|
||||
let blockCount = 0;
|
||||
while ((match = regex.exec(line)) != null) {
|
||||
if(match[0].startsWith('{')) {
|
||||
blockCount += 1;
|
||||
} else {
|
||||
blockCount -= 1;
|
||||
}
|
||||
if(blockCount < 0) {
|
||||
blockCount = 0;
|
||||
continue;
|
||||
}
|
||||
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,\-()#%. ]*"|[\w\,\-()#%.]*)|[^"'{}\s])* *$|^ *}}$/);
|
||||
if(match)
|
||||
endCh = match.index+match[0].length;
|
||||
codeMirror.markText({ line: lineNumber, ch: 0 }, { line: lineNumber, ch: endCh }, { className: 'block' });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return r;
|
||||
}, []);
|
||||
return lineNumbers;
|
||||
});
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
brewJump : function(){
|
||||
const currentPage = this.getCurrentPage();
|
||||
window.location.hash = `p${currentPage}`;
|
||||
brewJump : function(targetPage=this.getCurrentPage()){
|
||||
if(!window) return;
|
||||
// console.log(`Scroll to: p${targetPage}`);
|
||||
const brewRenderer = window.frames['BrewRenderer'].contentDocument.getElementsByClassName('brewRenderer')[0];
|
||||
const currentPos = brewRenderer.scrollTop;
|
||||
const targetPos = window.frames['BrewRenderer'].contentDocument.getElementById(`p${targetPage}`).getBoundingClientRect().top;
|
||||
const interimPos = targetPos >= 0 ? -30 : 30;
|
||||
|
||||
const bounceDelay = 100;
|
||||
const scrollDelay = 500;
|
||||
|
||||
if(!this.throttleBrewMove) {
|
||||
this.throttleBrewMove = _.throttle((currentPos, interimPos, targetPos)=>{
|
||||
brewRenderer.scrollTo({ top: currentPos + interimPos, behavior: 'smooth' });
|
||||
setTimeout(()=>{
|
||||
brewRenderer.scrollTo({ top: currentPos + targetPos, behavior: 'smooth', block: 'start' });
|
||||
}, bounceDelay);
|
||||
}, scrollDelay, { leading: true, trailing: false });
|
||||
};
|
||||
this.throttleBrewMove(currentPos, interimPos, targetPos);
|
||||
|
||||
// const hashPage = (page != 1) ? `p${page}` : '';
|
||||
// window.location.hash = hashPage;
|
||||
},
|
||||
|
||||
sourceJump : function(targetLine=null){
|
||||
if(this.isText()) {
|
||||
if(targetLine == null) {
|
||||
targetLine = 0;
|
||||
|
||||
const pageCollection = window.frames['BrewRenderer'].contentDocument.getElementsByClassName('page');
|
||||
const brewRendererHeight = window.frames['BrewRenderer'].contentDocument.getElementsByClassName('brewRenderer').item(0).getBoundingClientRect().height;
|
||||
|
||||
let currentPage = 1;
|
||||
for (const page of pageCollection) {
|
||||
if(page.getBoundingClientRect().bottom > (brewRendererHeight / 2)) {
|
||||
currentPage = parseInt(page.id.slice(1)) || 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const textSplit = this.props.renderer == 'V3' ? /^\\page$/gm : /\\page/;
|
||||
const textString = this.props.brew.text.split(textSplit).slice(0, currentPage-1).join(textSplit);
|
||||
const textPosition = textString.length;
|
||||
const lineCount = textString.match('\n') ? textString.slice(0, textPosition).split('\n').length : 0;
|
||||
|
||||
targetLine = lineCount - 1; //Scroll to `\page`, which is one line back.
|
||||
|
||||
let currentY = this.refs.codeEditor.codeMirror.getScrollInfo().top;
|
||||
let targetY = this.refs.codeEditor.codeMirror.heightAtLine(targetLine, 'local', true);
|
||||
|
||||
//Scroll 1/10 of the way every 10ms until 1px off.
|
||||
const incrementalScroll = setInterval(()=>{
|
||||
currentY += (targetY - currentY) / 10;
|
||||
this.refs.codeEditor.codeMirror.scrollTo(null, currentY);
|
||||
|
||||
// Update target: target height is not accurate until within +-10 lines of the visible window
|
||||
if(Math.abs(targetY - currentY > 100))
|
||||
targetY = this.refs.codeEditor.codeMirror.heightAtLine(targetLine, 'local', true);
|
||||
|
||||
// End when close enough
|
||||
if(Math.abs(targetY - currentY) < 1) {
|
||||
this.refs.codeEditor.codeMirror.scrollTo(null, targetY); // Scroll any remaining difference
|
||||
this.refs.codeEditor.setCursorPosition({ line: targetLine + 1, ch: 0 });
|
||||
this.refs.codeEditor.codeMirror.addLineClass(targetLine + 1, 'wrap', 'sourceMoveFlash');
|
||||
clearInterval(incrementalScroll);
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
//Called when there are changes to the editor's dimensions
|
||||
@@ -206,6 +288,7 @@ const Editor = createClass({
|
||||
view={this.state.view}
|
||||
value={this.props.brew.style ?? DEFAULT_STYLE_TEXT}
|
||||
onChange={this.props.onStyleChange}
|
||||
enableFolding={false}
|
||||
rerenderParent={this.rerenderParent} />
|
||||
</>;
|
||||
}
|
||||
|
||||
@@ -5,17 +5,13 @@
|
||||
|
||||
.codeEditor{
|
||||
height : 100%;
|
||||
counter-reset : page;
|
||||
counter-increment : page;
|
||||
.pageLine{
|
||||
background : #33333328;
|
||||
border-top : #339 solid 1px;
|
||||
&:after{
|
||||
content : counter(page);
|
||||
counter-increment : page;
|
||||
float : right;
|
||||
color : gray;
|
||||
}
|
||||
}
|
||||
.editor-page-count{
|
||||
color : grey;
|
||||
float : right;
|
||||
}
|
||||
.columnSplit{
|
||||
font-style : italic;
|
||||
|
||||
@@ -8,7 +8,10 @@ const request = require('superagent');
|
||||
|
||||
const SYSTEMS = ['5e', '4e', '3.5e', 'Pathfinder'];
|
||||
|
||||
const homebreweryThumbnail = require('../../thumbnail.png');
|
||||
|
||||
const MetadataEditor = createClass({
|
||||
displayName : 'MetadataEditor',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
metadata : {
|
||||
@@ -57,6 +60,23 @@ const MetadataEditor = createClass({
|
||||
}
|
||||
},
|
||||
|
||||
getInitialState : function(){
|
||||
return {
|
||||
showThumbnail : true
|
||||
};
|
||||
},
|
||||
|
||||
toggleThumbnailDisplay : function(){
|
||||
this.setState({
|
||||
showThumbnail : !this.state.showThumbnail
|
||||
});
|
||||
},
|
||||
|
||||
renderThumbnail : function(){
|
||||
if(!this.state.showThumbnail) return;
|
||||
return <img className='thumbnail-preview' src={this.props.metadata.thumbnail || homebreweryThumbnail}></img>;
|
||||
},
|
||||
|
||||
handleFieldChange : function(name, e){
|
||||
this.props.onChange(_.merge({}, this.props.metadata, {
|
||||
[name] : e.target.value
|
||||
@@ -91,7 +111,7 @@ const MetadataEditor = createClass({
|
||||
if(!confirm('Are you REALLY sure? You will lose editor access to this document.')) return;
|
||||
}
|
||||
|
||||
request.delete(`/api/${this.props.metadata.editId}`)
|
||||
request.delete(`/api/${this.props.metadata.googleId ?? ''}${this.props.metadata.editId}`)
|
||||
.send()
|
||||
.end(function(err, res){
|
||||
window.location.href = '/';
|
||||
@@ -256,6 +276,18 @@ const MetadataEditor = createClass({
|
||||
<textarea value={this.props.metadata.description} className='value'
|
||||
onChange={(e)=>this.handleFieldChange('description', e)} />
|
||||
</div>
|
||||
<div className='field thumbnail'>
|
||||
<label>thumbnail</label>
|
||||
<input type='text'
|
||||
value={this.props.metadata.thumbnail}
|
||||
placeholder='my.thumbnail.url'
|
||||
className='value'
|
||||
onChange={(e)=>this.handleFieldChange('thumbnail', e)} />
|
||||
<button className='display' onClick={this.toggleThumbnailDisplay}>
|
||||
<i className={`fas fa-caret-${this.state.showThumbnail ? 'right' : 'left'}`} />
|
||||
</button>
|
||||
{this.renderThumbnail()}
|
||||
</div>
|
||||
|
||||
{this.renderTags()}
|
||||
|
||||
|
||||
@@ -24,6 +24,33 @@
|
||||
flex : 1 1 auto;
|
||||
min-width : 200px;
|
||||
}
|
||||
&.thumbnail{
|
||||
height : 1.4em;
|
||||
label{
|
||||
line-height: 2.0em;
|
||||
}
|
||||
.value{
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
}
|
||||
button{
|
||||
border: 1px solid #999;
|
||||
color: white;
|
||||
padding: 0px 5px;
|
||||
background-color: black;
|
||||
&:hover{
|
||||
background-color: #777;
|
||||
}
|
||||
}
|
||||
.thumbnail-preview{
|
||||
position : relative;
|
||||
width : 80px;
|
||||
height : min-content;
|
||||
border : 2px solid white;
|
||||
margin-left : 5px;
|
||||
max-height : 115px;
|
||||
}
|
||||
}
|
||||
}
|
||||
.description.field textarea.value{
|
||||
resize : none;
|
||||
|
||||
@@ -14,6 +14,7 @@ const execute = function(val, brew){
|
||||
};
|
||||
|
||||
const Snippetbar = createClass({
|
||||
displayName : 'SnippetBar',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
brew : {},
|
||||
@@ -103,6 +104,7 @@ module.exports = Snippetbar;
|
||||
|
||||
|
||||
const SnippetGroup = createClass({
|
||||
displayName : 'SnippetGroup',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
brew : {},
|
||||
|
||||
@@ -9,6 +9,7 @@ module.exports = function(classname){
|
||||
classname = classname.toLowerCase();
|
||||
|
||||
const hitDie = _.sample([4, 6, 8, 10, 12]);
|
||||
const spellSkill = _.sample(['Wisdom', 'Charisma', 'Intelligence']);
|
||||
|
||||
const abilityList = ['Strength', 'Dexerity', 'Constitution', 'Wisdom', 'Charisma', 'Intelligence'];
|
||||
const skillList = ['Acrobatics', 'Animal Handling', 'Arcana', 'Athletics', 'Deception', 'History', 'Insight', 'Intimidation', 'Investigation', 'Medicine', 'Nature', 'Perception', 'Performance', 'Persuasion', 'Religion', 'Sleight of Hand', 'Stealth', 'Survival'];
|
||||
@@ -27,11 +28,19 @@ module.exports = function(classname){
|
||||
|
||||
**Armor:** :: ${_.sampleSize(['Light armor', 'Medium armor', 'Heavy armor', 'Shields'], _.random(0, 3)).join(', ') || 'None'}
|
||||
**Weapons:** :: ${_.sampleSize(['Squeegee', 'Rubber Chicken', 'Simple weapons', 'Martial weapons'], _.random(0, 2)).join(', ') || 'None'}
|
||||
**Tools:** :: ${_.sampleSize(['Artian\'s tools', 'one musical instrument', 'Thieve\'s tools'], _.random(0, 2)).join(', ') || 'None'}
|
||||
**Tools:** :: ${_.sampleSize(['Artisan\'s tools', 'one musical instrument', 'Thieves\' tools'], _.random(0, 2)).join(', ') || 'None'}
|
||||
|
||||
**Saving Throws:** :: ${_.sampleSize(abilityList, 2).join(', ')}
|
||||
**Skills:** :: Choose two from ${_.sampleSize(skillList, _.random(4, 6)).join(', ')}
|
||||
|
||||
#### Spellcasting Ability
|
||||
|
||||
{{text-align:center
|
||||
**Spell save DC**:: = ${_.sample([6, 8, 10])} + your proficiency bonus + your ${spellSkill} modifier
|
||||
|
||||
**Spell attack modifier**:: = your proficiency bonus + your ${spellSkill} modifier
|
||||
}}
|
||||
|
||||
#### Equipment
|
||||
You start with the following equipment, in addition to the equipment granted by your background:
|
||||
- *(a)* a martial weapon and a shield or *(b)* two martial weapons
|
||||
|
||||
@@ -100,25 +100,25 @@ const subtitles = [
|
||||
|
||||
module.exports = ()=>{
|
||||
return `<style>
|
||||
.phb#p1{ text-align:center; }
|
||||
.phb#p1:after{ display:none; }
|
||||
.phb#p2 { counter-reset:phb-page-numbers; }
|
||||
.phb:nth-child(2n) .pageNumber { left: inherit !important; right: 2px !important; }
|
||||
.phb:nth-child(2n+1) .pageNumber { right: inherit !important; left: 2px !important; }
|
||||
.phb:nth-child(2n)::after { transform: scaleX(1); }
|
||||
.phb:nth-child(2n+1)::after { transform: scaleX(-1); }
|
||||
.phb:nth-child(2n) .footnote { left: inherit; text-align: right; }
|
||||
.phb:nth-child(2n+1) .footnote { left: 80px; text-align: left; }
|
||||
.page#p1{ text-align:center; counter-increment: none; }
|
||||
.page#p1:after{ display:none; }
|
||||
.page:nth-child(2n) .pageNumber { left: inherit !important; right: 2px !important; }
|
||||
.page:nth-child(2n+1) .pageNumber { right: inherit !important; left: 2px !important; }
|
||||
.page:nth-child(2n)::after { transform: scaleX(1); }
|
||||
.page:nth-child(2n+1)::after { transform: scaleX(-1); }
|
||||
.page:nth-child(2n) .footnote { left: inherit; text-align: right; }
|
||||
.page:nth-child(2n+1) .footnote { left: 80px; text-align: left; }
|
||||
</style>
|
||||
|
||||
<div style='margin-top:450px;'></div>
|
||||
{{margin-top:225px}}
|
||||
|
||||
# ${_.sample(titles)}
|
||||
|
||||
<div style='margin-top:25px'></div>
|
||||
<div class='wide'>
|
||||
{{margin-top:25px}}
|
||||
|
||||
{{wide
|
||||
##### ${_.sample(subtitles)}
|
||||
</div>
|
||||
}}
|
||||
|
||||
\\page`;
|
||||
};
|
||||
@@ -97,7 +97,11 @@ module.exports = [
|
||||
gen : dedent`/* Removes Drop Caps */
|
||||
.page h1+p:first-letter {
|
||||
all: unset;
|
||||
}\n\n`
|
||||
}\n\n
|
||||
/* Removes Small-Caps in first line */
|
||||
.page h1+p:first-line {
|
||||
all: unset;
|
||||
}`
|
||||
},
|
||||
{
|
||||
name : 'Tweak Drop Cap',
|
||||
|
||||
@@ -8,6 +8,7 @@ module.exports = function(classname){
|
||||
classname = classname.toLowerCase();
|
||||
|
||||
const hitDie = _.sample([4, 6, 8, 10, 12]);
|
||||
const spellSkill = _.sample(['Wisdom', 'Charisma', 'Intelligence']);
|
||||
|
||||
const abilityList = ['Strength', 'Dexerity', 'Constitution', 'Wisdom', 'Charisma', 'Intelligence'];
|
||||
const skillList = ['Acrobatics ', 'Animal Handling', 'Arcana', 'Athletics', 'Deception', 'History', 'Insight', 'Intimidation', 'Investigation', 'Medicine', 'Nature', 'Perception', 'Performance', 'Persuasion', 'Religion', 'Sleight of Hand', 'Stealth', 'Survival'];
|
||||
@@ -26,12 +27,21 @@ module.exports = function(classname){
|
||||
'___',
|
||||
`- **Armor:** ${_.sampleSize(['Light armor', 'Medium armor', 'Heavy armor', 'Shields'], _.random(0, 3)).join(', ') || 'None'}`,
|
||||
`- **Weapons:** ${_.sampleSize(['Squeegee', 'Rubber Chicken', 'Simple weapons', 'Martial weapons'], _.random(0, 2)).join(', ') || 'None'}`,
|
||||
`- **Tools:** ${_.sampleSize(['Artian\'s tools', 'one musical instrument', 'Thieve\'s tools'], _.random(0, 2)).join(', ') || 'None'}`,
|
||||
`- **Tools:** ${_.sampleSize(['Artisan\'s tools', 'one musical instrument', 'Thieves\' tools'], _.random(0, 2)).join(', ') || 'None'}`,
|
||||
'',
|
||||
'___',
|
||||
`- **Saving Throws:** ${_.sampleSize(abilityList, 2).join(', ')}`,
|
||||
`- **Skills:** Choose two from ${_.sampleSize(skillList, _.random(4, 6)).join(', ')}`,
|
||||
'',
|
||||
'#### Spellcasting Ability',
|
||||
'',
|
||||
`<div style=text-align:center>`,
|
||||
'___',
|
||||
`- **Spell save DC** = ${_.sample([6, 8, 10])} + your proficiency bonus + your ${spellSkill} modifier`,
|
||||
'',
|
||||
`- **Spell attack modifier** = your proficiency bonus + your ${spellSkill} modifier`,
|
||||
`</div>`,
|
||||
'',
|
||||
'#### Equipment',
|
||||
'You start with the following equipment, in addition to the equipment granted by your background:',
|
||||
'- *(a)* a martial weapon and a shield or *(b)* two martial weapons',
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
require('./homebrew.less');
|
||||
const React = require('react');
|
||||
const createClass = require('create-react-class');
|
||||
const { StaticRouter:Router, Switch, Route } = require('react-router-dom');
|
||||
const queryString = require('query-string');
|
||||
const { StaticRouter:Router } = require('react-router-dom/server');
|
||||
const { Route, Routes, useParams, useSearchParams } = require('react-router-dom');
|
||||
|
||||
const HomePage = require('./pages/homePage/homePage.jsx');
|
||||
const EditPage = require('./pages/editPage/editPage.jsx');
|
||||
@@ -12,7 +12,21 @@ const NewPage = require('./pages/newPage/newPage.jsx');
|
||||
//const ErrorPage = require('./pages/errorPage/errorPage.jsx');
|
||||
const PrintPage = require('./pages/printPage/printPage.jsx');
|
||||
|
||||
const WithRoute = (props)=>{
|
||||
const params = useParams();
|
||||
const searchParams = useSearchParams();
|
||||
const Element = props.el;
|
||||
const allProps = {
|
||||
...props,
|
||||
...params,
|
||||
...searchParams,
|
||||
el : undefined
|
||||
};
|
||||
return <Element {...allProps} />;
|
||||
};
|
||||
|
||||
const Homebrew = createClass({
|
||||
displayName : 'Homebrewery',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
url : '',
|
||||
@@ -31,31 +45,35 @@ const Homebrew = createClass({
|
||||
}
|
||||
};
|
||||
},
|
||||
componentWillMount : function() {
|
||||
|
||||
getInitialState : function() {
|
||||
global.account = this.props.account;
|
||||
global.version = this.props.version;
|
||||
global.enable_v3 = this.props.enable_v3;
|
||||
global.config = this.props.config;
|
||||
|
||||
return {};
|
||||
},
|
||||
|
||||
render : function (){
|
||||
return (
|
||||
<Router location={this.props.url}>
|
||||
<div className='homebrew'>
|
||||
<Switch>
|
||||
<Route path='/edit/:id' component={(routeProps)=><EditPage id={routeProps.match.params.id} brew={this.props.brew} />}/>
|
||||
<Route path='/share/:id' component={(routeProps)=><SharePage id={routeProps.match.params.id} brew={this.props.brew} />}/>
|
||||
<Route path='/new/:id' component={(routeProps)=><NewPage id={routeProps.match.params.id} brew={this.props.brew} />}/>
|
||||
<Route path='/new' exact component={(routeProps)=><NewPage />}/>
|
||||
<Route path='/user/:username' component={(routeProps)=><UserPage username={routeProps.match.params.username} brews={this.props.brews} />}/>
|
||||
<Route path='/print/:id' component={(routeProps)=><PrintPage brew={this.props.brew} query={queryString.parse(routeProps.location.search)} />}/>
|
||||
<Route path='/print' exact component={(routeProps)=><PrintPage query={queryString.parse(routeProps.location.search)} />}/>
|
||||
<Route path='/changelog' exact component={()=><SharePage brew={this.props.brew} />}/>
|
||||
<Route path='/faq' exact component={()=><SharePage brew={this.props.brew} />}/>
|
||||
<Route path='/v3_preview' exact component={()=><HomePage brew={this.props.brew} />}/>
|
||||
<Route path='/' component={()=><HomePage brew={this.props.brew} />}/>
|
||||
</Switch>
|
||||
</div>
|
||||
</Router>
|
||||
);
|
||||
return <Router location={this.props.url}>
|
||||
<div className='homebrew'>
|
||||
<Routes>
|
||||
<Route path='/edit/:id' element={<WithRoute el={EditPage} brew={this.props.brew} />} />
|
||||
<Route path='/share/:id' element={<WithRoute el={SharePage} brew={this.props.brew} />} />
|
||||
<Route path='/new/:id' element={<WithRoute el={NewPage} brew={this.props.brew} />} />
|
||||
<Route path='/new' element={<WithRoute el={NewPage}/>} />
|
||||
<Route path='/user/:username' element={<WithRoute el={UserPage} brews={this.props.brews} />} />
|
||||
<Route path='/print/:id' element={<WithRoute el={PrintPage} brew={this.props.brew} />} />
|
||||
<Route path='/print' element={<WithRoute el={PrintPage} />} />
|
||||
<Route path='/changelog' element={<WithRoute el={SharePage} brew={this.props.brew} />} />
|
||||
<Route path='/faq' element={<WithRoute el={SharePage} brew={this.props.brew} />} />
|
||||
<Route path='/v3_preview' element={<WithRoute el={HomePage} brew={this.props.brew} />} />
|
||||
<Route path='/' element={<WithRoute el={HomePage} brew={this.props.brew} />} />
|
||||
<Route path='/*' element={<WithRoute el={HomePage} brew={this.props.brew} />} />
|
||||
</Routes>
|
||||
</div>
|
||||
</Router>;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
const React = require('react');
|
||||
const createClass = require('create-react-class');
|
||||
const Nav = require('naturalcrit/nav/nav.jsx');
|
||||
const request = require('superagent');
|
||||
|
||||
const Account = createClass({
|
||||
|
||||
displayName : 'AccountNavItem',
|
||||
getInitialState : function() {
|
||||
return {
|
||||
url : ''
|
||||
@@ -18,13 +19,84 @@ const Account = createClass({
|
||||
}
|
||||
},
|
||||
|
||||
handleLogout : function(){
|
||||
if(confirm('Are you sure you want to log out?')) {
|
||||
// Reset divider position
|
||||
window.localStorage.removeItem('naturalcrit-pane-split');
|
||||
// Clear login cookie
|
||||
let domain = '';
|
||||
if(window.location?.hostname) {
|
||||
let domainArray = window.location.hostname.split('.');
|
||||
if(domainArray.length > 2){
|
||||
domainArray = [''].concat(domainArray.slice(-2));
|
||||
}
|
||||
domain = domainArray.join('.');
|
||||
}
|
||||
document.cookie = `nc_session=;expires=Thu, 01 Jan 1970 00:00:01 GMT;path=/;samesite=lax;${domain ? `domain=${domain}` : ''}`;
|
||||
window.location = '/';
|
||||
}
|
||||
},
|
||||
|
||||
localLogin : async function(){
|
||||
const username = prompt('Enter username:');
|
||||
if(!username) {return;}
|
||||
|
||||
const expiry = new Date;
|
||||
expiry.setFullYear(expiry.getFullYear() + 1);
|
||||
|
||||
const token = await request.post('/local/login')
|
||||
.send({ username })
|
||||
.then((response)=>{
|
||||
return response.body;
|
||||
})
|
||||
.catch((err)=>{
|
||||
console.warn(err);
|
||||
});
|
||||
if(!token) return;
|
||||
|
||||
document.cookie = `nc_session=${token};expires=${expiry};path=/;samesite=lax;${window.domain ? `domain=${window.domain}` : ''}`;
|
||||
window.location.reload(true);
|
||||
},
|
||||
|
||||
render : function(){
|
||||
// Logged in
|
||||
if(global.account){
|
||||
return <Nav.item href={`/user/${global.account.username}`} color='yellow' icon='fas fa-user'>
|
||||
{global.account.username}
|
||||
</Nav.item>;
|
||||
return <Nav.dropdown>
|
||||
<Nav.item
|
||||
className='account'
|
||||
color='orange'
|
||||
icon='fas fa-user'
|
||||
>
|
||||
{global.account.username}
|
||||
</Nav.item>
|
||||
<Nav.item
|
||||
href={`/user/${global.account.username}`}
|
||||
color='yellow'
|
||||
icon='fas fa-beer'
|
||||
>
|
||||
brews
|
||||
</Nav.item>
|
||||
<Nav.item
|
||||
className='logout'
|
||||
color='red'
|
||||
icon='fas fa-power-off'
|
||||
onClick={this.handleLogout}
|
||||
>
|
||||
logout
|
||||
</Nav.item>
|
||||
</Nav.dropdown>;
|
||||
}
|
||||
|
||||
// Logged out
|
||||
// LOCAL ONLY
|
||||
if(global.config.local) {
|
||||
return <Nav.item color='teal' icon='fas fa-sign-in-alt' onClick={this.localLogin}>
|
||||
login
|
||||
</Nav.item>;
|
||||
};
|
||||
|
||||
// Logged out
|
||||
// Production site
|
||||
return <Nav.item href={`https://www.naturalcrit.com/login?redirect=${this.state.url}`} color='teal' icon='fas fa-sign-in-alt'>
|
||||
login
|
||||
</Nav.item>;
|
||||
|
||||
@@ -7,6 +7,7 @@ const MAX_TITLE_LENGTH = 50;
|
||||
|
||||
|
||||
const EditTitle = createClass({
|
||||
displayName : 'EditTitleNavItem',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
title : '',
|
||||
|
||||
30
client/homebrew/navbar/help.navitem.jsx
Normal file
30
client/homebrew/navbar/help.navitem.jsx
Normal file
@@ -0,0 +1,30 @@
|
||||
const React = require('react');
|
||||
const createClass = require('create-react-class');
|
||||
const _ = require('lodash');
|
||||
const dedent = require('dedent-tabs').default;
|
||||
|
||||
const Nav = require('naturalcrit/nav/nav.jsx');
|
||||
|
||||
module.exports = function(props){
|
||||
return <Nav.dropdown>
|
||||
<Nav.item color='grey' icon='fas fa-question-circle'>
|
||||
need help?
|
||||
</Nav.item>
|
||||
<Nav.item color='red' icon='fas fa-fw fa-bug'
|
||||
href={`https://www.reddit.com/r/homebrewery/submit?selftext=true&text=${encodeURIComponent(dedent`
|
||||
**Browser(s)** :
|
||||
**Operating System** :
|
||||
**Legacy or v3 Renderer** :
|
||||
**Issue** : `)}`}
|
||||
newTab={true}
|
||||
rel='noopener noreferrer'>
|
||||
report issue
|
||||
</Nav.item>
|
||||
<Nav.item color='blue' icon='fas fa-fw fa-file-import'
|
||||
href='/migrate'
|
||||
newTab={true}
|
||||
rel='noopener noreferrer'>
|
||||
migrate
|
||||
</Nav.item>
|
||||
</Nav.dropdown>;
|
||||
};
|
||||
@@ -1,13 +0,0 @@
|
||||
const React = require('react');
|
||||
const createClass = require('create-react-class');
|
||||
const Nav = require('naturalcrit/nav/nav.jsx');
|
||||
|
||||
module.exports = function(props){
|
||||
return <Nav.item
|
||||
newTab={true}
|
||||
color='red'
|
||||
icon='fas fa-bug'
|
||||
href={`https://www.reddit.com/r/homebrewery/submit?selftext=true&title=${encodeURIComponent('[Issue] Describe Your Issue Here')}`} >
|
||||
report issue
|
||||
</Nav.item>;
|
||||
};
|
||||
@@ -6,6 +6,7 @@ const Nav = require('naturalcrit/nav/nav.jsx');
|
||||
const PatreonNavItem = require('./patreon.navitem.jsx');
|
||||
|
||||
const Navbar = createClass({
|
||||
displayName : 'Navbar',
|
||||
getInitialState : function() {
|
||||
return {
|
||||
//showNonChromeWarning : false,
|
||||
@@ -13,12 +14,10 @@ const Navbar = createClass({
|
||||
};
|
||||
},
|
||||
|
||||
componentDidMount : function() {
|
||||
//const isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
|
||||
this.setState({
|
||||
//showNonChromeWarning : !isChrome,
|
||||
ver : window.version
|
||||
});
|
||||
getInitialState : function() {
|
||||
return {
|
||||
ver : global.version
|
||||
};
|
||||
},
|
||||
|
||||
/*
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
@import 'naturalcrit/styles/colors.less';
|
||||
@navbarHeight : 28px;
|
||||
@keyframes coloring {
|
||||
@keyframes pinkColoring {
|
||||
//from {color: white;}
|
||||
//to {color: red;}
|
||||
0% {color: pink;}
|
||||
@@ -62,19 +63,21 @@
|
||||
}
|
||||
i{
|
||||
.animate(color);
|
||||
animation-name: coloring;
|
||||
animation-name: pinkColoring;
|
||||
animation-duration: 2s;
|
||||
color: pink;
|
||||
}
|
||||
}
|
||||
.recent.navItem{
|
||||
.recent.navItem {
|
||||
position : relative;
|
||||
.dropdown{
|
||||
position : absolute;
|
||||
top : 28px;
|
||||
left : 0px;
|
||||
z-index : 10000;
|
||||
width : 100%;
|
||||
position : absolute;
|
||||
top : 28px;
|
||||
left : 0px;
|
||||
z-index : 10000;
|
||||
width : 100%;
|
||||
overflow : hidden auto;
|
||||
max-height : ~"calc(100vh - 28px)";
|
||||
h4{
|
||||
display : block;
|
||||
box-sizing : border-box;
|
||||
@@ -88,11 +91,12 @@
|
||||
&:nth-of-type(2){ background-color: darken(@purple, 30%); }
|
||||
}
|
||||
.item{
|
||||
#backgroundColors;
|
||||
.animate(background-color);
|
||||
position : relative;
|
||||
display : block;
|
||||
box-sizing : border-box;
|
||||
padding : 13px 5px;
|
||||
padding : 8px 5px 13px;
|
||||
background-color : #333;
|
||||
color : white;
|
||||
text-decoration : none;
|
||||
@@ -138,4 +142,7 @@
|
||||
text-align : center;
|
||||
}
|
||||
}
|
||||
.account.navItem{
|
||||
min-width: 100px;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ const VIEW_KEY = 'homebrewery-recently-viewed';
|
||||
|
||||
|
||||
const RecentItems = createClass({
|
||||
|
||||
DisplayName : 'RecentItems',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
storageKey : '',
|
||||
@@ -123,8 +123,8 @@ const RecentItems = createClass({
|
||||
if(!this.state.showDropdown) return null;
|
||||
|
||||
const makeItems = (brews)=>{
|
||||
return _.map(brews, (brew)=>{
|
||||
return <a href={brew.url} className='item' key={brew.id} target='_blank' rel='noopener noreferrer' title={brew.title || '[ no title ]'}>
|
||||
return _.map(brews, (brew, i)=>{
|
||||
return <a href={brew.url} className='item' key={`${brew.id}-${i}`} target='_blank' rel='noopener noreferrer' title={brew.title || '[ no title ]'}>
|
||||
<span className='title'>{brew.title || '[ no title ]'}</span>
|
||||
<span className='time'>{Moment(brew.ts).fromNow()}</span>
|
||||
</a>;
|
||||
|
||||
@@ -8,6 +8,7 @@ const MAIN_URL = 'https://www.reddit.com/r/UnearthedArcana/submit?selftext=true'
|
||||
|
||||
|
||||
const RedditShare = createClass({
|
||||
displayName : 'RedditShareNavItem',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
brew : {
|
||||
|
||||
@@ -6,17 +6,18 @@ const cx = require('classnames');
|
||||
const moment = require('moment');
|
||||
const request = require('superagent');
|
||||
|
||||
const googleDriveIcon = require('../../../googleDrive.png');
|
||||
const googleDriveIcon = require('../../../../googleDrive.png');
|
||||
const dedent = require('dedent-tabs').default;
|
||||
|
||||
const BrewItem = createClass({
|
||||
displayName : 'BrewItem',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
brew : {
|
||||
title : '',
|
||||
description : '',
|
||||
|
||||
authors : []
|
||||
authors : [],
|
||||
stubbed : true
|
||||
}
|
||||
};
|
||||
},
|
||||
@@ -30,25 +31,17 @@ const BrewItem = createClass({
|
||||
if(!confirm('Are you REALLY sure? You will lose editor access to this document.')) return;
|
||||
}
|
||||
|
||||
if(this.props.brew.googleId) {
|
||||
request.get(`/api/removeGoogle/${this.props.brew.googleId}${this.props.brew.editId}`)
|
||||
.send()
|
||||
.end(function(err, res){
|
||||
location.reload();
|
||||
});
|
||||
} else {
|
||||
request.delete(`/api/${this.props.brew.editId}`)
|
||||
.send()
|
||||
.end(function(err, res){
|
||||
location.reload();
|
||||
});
|
||||
}
|
||||
request.delete(`/api/${this.props.brew.googleId ?? ''}${this.props.brew.editId}`)
|
||||
.send()
|
||||
.end(function(err, res){
|
||||
location.reload();
|
||||
});
|
||||
},
|
||||
|
||||
renderDeleteBrewLink : function(){
|
||||
if(!this.props.brew.editId) return;
|
||||
|
||||
return <a onClick={this.deleteBrew}>
|
||||
return <a className='deleteLink' onClick={this.deleteBrew}>
|
||||
<i className='fas fa-trash-alt' title='Delete' />
|
||||
</a>;
|
||||
},
|
||||
@@ -57,11 +50,11 @@ const BrewItem = createClass({
|
||||
if(!this.props.brew.editId) return;
|
||||
|
||||
let editLink = this.props.brew.editId;
|
||||
if(this.props.brew.googleId) {
|
||||
if(this.props.brew.googleId && !this.props.brew.stubbed) {
|
||||
editLink = this.props.brew.googleId + editLink;
|
||||
}
|
||||
|
||||
return <a href={`/edit/${editLink}`} target='_blank' rel='noopener noreferrer'>
|
||||
return <a className='editLink' href={`/edit/${editLink}`} target='_blank' rel='noopener noreferrer'>
|
||||
<i className='fas fa-pencil-alt' title='Edit' />
|
||||
</a>;
|
||||
},
|
||||
@@ -70,11 +63,11 @@ const BrewItem = createClass({
|
||||
if(!this.props.brew.shareId) return;
|
||||
|
||||
let shareLink = this.props.brew.shareId;
|
||||
if(this.props.brew.googleId) {
|
||||
if(this.props.brew.googleId && !this.props.brew.stubbed) {
|
||||
shareLink = this.props.brew.googleId + shareLink;
|
||||
}
|
||||
|
||||
return <a href={`/share/${shareLink}`} target='_blank' rel='noopener noreferrer'>
|
||||
return <a className='shareLink' href={`/share/${shareLink}`} target='_blank' rel='noopener noreferrer'>
|
||||
<i className='fas fa-share-alt' title='Share' />
|
||||
</a>;
|
||||
},
|
||||
@@ -83,17 +76,17 @@ const BrewItem = createClass({
|
||||
if(!this.props.brew.shareId) return;
|
||||
|
||||
let shareLink = this.props.brew.shareId;
|
||||
if(this.props.brew.googleId) {
|
||||
if(this.props.brew.googleId && !this.props.brew.stubbed) {
|
||||
shareLink = this.props.brew.googleId + shareLink;
|
||||
}
|
||||
|
||||
return <a href={`/download/${shareLink}`}>
|
||||
return <a className='downloadLink' href={`/download/${shareLink}`}>
|
||||
<i className='fas fa-download' title='Download' />
|
||||
</a>;
|
||||
},
|
||||
|
||||
renderGoogleDriveIcon : function(){
|
||||
if(!this.props.brew.gDrive) return;
|
||||
if(!this.props.brew.googleId) return;
|
||||
|
||||
return <span>
|
||||
<img className='googleDriveIcon' src={googleDriveIcon} alt='googleDriveIcon' />
|
||||
@@ -111,8 +104,8 @@ const BrewItem = createClass({
|
||||
</div>
|
||||
<hr />
|
||||
<div className='info'>
|
||||
<span title={`Authors:\n${brew.authors.join('\n')}`}>
|
||||
<i className='fas fa-user'/> {brew.authors.join(', ')}
|
||||
<span title={`Authors:\n${brew.authors?.join('\n')}`}>
|
||||
<i className='fas fa-user'/> {brew.authors?.join(', ')}
|
||||
</span>
|
||||
<br />
|
||||
<span title={`Last viewed: ${moment(brew.lastViewed).local().format(dateFormatString)}`}>
|
||||
@@ -17,6 +17,8 @@
|
||||
-webkit-column-break-inside : avoid;
|
||||
page-break-inside : avoid;
|
||||
break-inside : avoid;
|
||||
box-shadow : 0px 4px 5px 0px #333;
|
||||
background-color : #cab2802e;
|
||||
.text {
|
||||
min-height : 54px;
|
||||
h4{
|
||||
177
client/homebrew/pages/basePages/listPage/listPage.jsx
Normal file
177
client/homebrew/pages/basePages/listPage/listPage.jsx
Normal file
@@ -0,0 +1,177 @@
|
||||
require('./listPage.less');
|
||||
const React = require('react');
|
||||
const createClass = require('create-react-class');
|
||||
const _ = require('lodash');
|
||||
const moment = require('moment');
|
||||
|
||||
const BrewItem = require('./brewItem/brewItem.jsx');
|
||||
|
||||
const ListPage = createClass({
|
||||
displayName : 'ListPage',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
brewCollection : [
|
||||
{
|
||||
title : '',
|
||||
class : '',
|
||||
brews : []
|
||||
}
|
||||
],
|
||||
navItems : <></>
|
||||
};
|
||||
},
|
||||
getInitialState : function() {
|
||||
return {
|
||||
sortType : 'alpha',
|
||||
sortDir : 'asc',
|
||||
filterString : this.props.query?.filter || '',
|
||||
query : this.props.query
|
||||
};
|
||||
},
|
||||
|
||||
renderBrews : function(brews){
|
||||
if(!brews || !brews.length) return <div className='noBrews'>No Brews.</div>;
|
||||
|
||||
return _.map(brews, (brew, idx)=>{
|
||||
return <BrewItem brew={brew} key={idx}/>;
|
||||
});
|
||||
},
|
||||
|
||||
sortBrewOrder : function(brew){
|
||||
if(!brew.title){brew.title = 'No Title';}
|
||||
const mapping = {
|
||||
'alpha' : _.deburr(brew.title.toLowerCase()),
|
||||
'created' : moment(brew.createdAt).format(),
|
||||
'updated' : moment(brew.updatedAt).format(),
|
||||
'views' : brew.views,
|
||||
'latest' : moment(brew.lastViewed).format()
|
||||
};
|
||||
return mapping[this.state.sortType];
|
||||
},
|
||||
|
||||
handleSortOptionChange : function(event){
|
||||
this.setState({
|
||||
sortType : event.target.value
|
||||
});
|
||||
},
|
||||
|
||||
handleSortDirChange : function(event){
|
||||
this.setState({
|
||||
sortDir : `${(this.state.sortDir == 'asc' ? 'desc' : 'asc')}`
|
||||
});
|
||||
},
|
||||
|
||||
renderSortOption : function(sortTitle, sortValue){
|
||||
return <td>
|
||||
<button
|
||||
value={`${sortValue}`}
|
||||
onClick={this.handleSortOptionChange}
|
||||
className={`${(this.state.sortType == sortValue ? 'active' : '')}`}
|
||||
>
|
||||
{`${sortTitle}`}
|
||||
</button>
|
||||
</td>;
|
||||
},
|
||||
|
||||
handleFilterTextChange : function(e){
|
||||
this.setState({
|
||||
filterString : e.target.value,
|
||||
});
|
||||
this.updateUrl(e.target.value);
|
||||
return;
|
||||
},
|
||||
|
||||
updateUrl : function(filterTerm){
|
||||
const url = new URL(window.location.href);
|
||||
const urlParams = new URLSearchParams(url.search);
|
||||
if(urlParams.get('filter') == filterTerm)
|
||||
return;
|
||||
if(!filterTerm)
|
||||
urlParams.delete('filter');
|
||||
else
|
||||
urlParams.set('filter', filterTerm);
|
||||
url.search = urlParams;
|
||||
window.history.replaceState(null, null, url);
|
||||
},
|
||||
|
||||
renderFilterOption : function(){
|
||||
return <td>
|
||||
<label>
|
||||
<i className='fas fa-search'></i>
|
||||
<input
|
||||
type='search'
|
||||
autoFocus={true}
|
||||
placeholder='filter title/description'
|
||||
onChange={this.handleFilterTextChange}
|
||||
value={this.state.filterString}
|
||||
/>
|
||||
</label>
|
||||
</td>;
|
||||
},
|
||||
|
||||
renderSortOptions : function(){
|
||||
return <div className='sort-container'>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<h6>Sort by :</h6>
|
||||
</td>
|
||||
{this.renderSortOption('Title', 'alpha')}
|
||||
{this.renderSortOption('Created Date', 'created')}
|
||||
{this.renderSortOption('Updated Date', 'updated')}
|
||||
{this.renderSortOption('Views', 'views')}
|
||||
{/* {this.renderSortOption('Latest', 'latest')} */}
|
||||
<td>
|
||||
<h6>Direction :</h6>
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
onClick={this.handleSortDirChange}
|
||||
className='sortDir'
|
||||
>
|
||||
{`${(this.state.sortDir == 'asc' ? '\u25B2 ASC' : '\u25BC DESC')}`}
|
||||
</button>
|
||||
</td>
|
||||
{this.renderFilterOption()}
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>;
|
||||
},
|
||||
|
||||
getSortedBrews : function(brews){
|
||||
const testString = _.deburr(this.state.filterString).toLowerCase();
|
||||
brews = _.filter(brews, (brew)=>{
|
||||
return (_.deburr(brew.title).toLowerCase().includes(testString)) ||
|
||||
(_.deburr(brew.description).toLowerCase().includes(testString));
|
||||
});
|
||||
|
||||
return _.orderBy(brews, (brew)=>{ return this.sortBrewOrder(brew); }, this.state.sortDir);
|
||||
},
|
||||
|
||||
renderBrewCollection : function(brewCollection){
|
||||
return _.map(brewCollection, (brewGroup, idx)=>{
|
||||
return <div key={idx} className={`brewCollection ${brewGroup.class ?? ''}`}>
|
||||
<h1>{brewGroup.title || 'No Title'}</h1>
|
||||
{this.renderBrews(this.getSortedBrews(brewGroup.brews))}
|
||||
</div>;
|
||||
});
|
||||
},
|
||||
|
||||
render : function(){
|
||||
return <div className='listPage sitePage'>
|
||||
<link href='/themes/5ePhbLegacy.style.css' rel='stylesheet'/>
|
||||
{this.props.navItems}
|
||||
|
||||
<div className='content V3'>
|
||||
<div className='phb'>
|
||||
{this.renderSortOptions()}
|
||||
{this.renderBrewCollection(this.props.brewCollection)}
|
||||
</div>
|
||||
</div>
|
||||
</div>;
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = ListPage;
|
||||
@@ -11,7 +11,7 @@
|
||||
-webkit-column-gap : auto;
|
||||
-moz-column-gap : auto;
|
||||
}
|
||||
.userPage{
|
||||
.listPage{
|
||||
.content{
|
||||
overflow-y : scroll;
|
||||
.phb{
|
||||
@@ -10,7 +10,7 @@ const Nav = require('naturalcrit/nav/nav.jsx');
|
||||
const Navbar = require('../../navbar/navbar.jsx');
|
||||
|
||||
const NewBrew = require('../../navbar/newbrew.navitem.jsx');
|
||||
const ReportIssue = require('../../navbar/issue.navitem.jsx');
|
||||
const HelpNavItem = require('../../navbar/help.navitem.jsx');
|
||||
const PrintLink = require('../../navbar/print.navitem.jsx');
|
||||
const Account = require('../../navbar/account.navitem.jsx');
|
||||
const RecentNavItem = require('../../navbar/recent.navitem.jsx').both;
|
||||
@@ -27,6 +27,7 @@ const googleDriveInactive = require('../../googleDriveMono.png');
|
||||
const SAVE_TIMEOUT = 3000;
|
||||
|
||||
const EditPage = createClass({
|
||||
displayName : 'EditPage',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
brew : {
|
||||
@@ -199,74 +200,17 @@ const EditPage = createClass({
|
||||
const brew = this.state.brew;
|
||||
brew.pageCount = ((brew.renderer=='legacy' ? brew.text.match(/\\page/g) : brew.text.match(/^\\page$/gm)) || []).length + 1;
|
||||
|
||||
if(this.state.saveGoogle) {
|
||||
if(transfer) {
|
||||
const res = await request
|
||||
.post('/api/newGoogle/')
|
||||
.send(brew)
|
||||
.catch((err)=>{
|
||||
console.log(err.status === 401
|
||||
? 'Not signed in!'
|
||||
: 'Error Transferring to Google!');
|
||||
this.setState({ errors: err, saveGoogle: false });
|
||||
});
|
||||
const params = `${transfer ? `?${this.state.saveGoogle ? 'saveToGoogle' : 'removeFromGoogle'}=true` : ''}`;
|
||||
const res = await request
|
||||
.put(`/api/update/${brew.editId}${params}`)
|
||||
.send(brew)
|
||||
.catch((err)=>{
|
||||
console.log('Error Updating Local Brew');
|
||||
this.setState({ errors: err });
|
||||
});
|
||||
|
||||
if(!res) { return; }
|
||||
|
||||
console.log('Deleting Local Copy');
|
||||
await request.delete(`/api/${brew.editId}`)
|
||||
.send()
|
||||
.catch((err)=>{
|
||||
console.log('Error deleting Local Copy');
|
||||
});
|
||||
|
||||
this.savedBrew = res.body;
|
||||
history.replaceState(null, null, `/edit/${this.savedBrew.googleId}${this.savedBrew.editId}`); //update URL to match doc ID
|
||||
} else {
|
||||
const res = await request
|
||||
.put(`/api/updateGoogle/${brew.editId}`)
|
||||
.send(brew)
|
||||
.catch((err)=>{
|
||||
console.log(err.status === 401
|
||||
? 'Not signed in!'
|
||||
: 'Error Saving to Google!');
|
||||
this.setState({ errors: err });
|
||||
return;
|
||||
});
|
||||
|
||||
this.savedBrew = res.body;
|
||||
}
|
||||
} else {
|
||||
if(transfer) {
|
||||
const res = await request.post('/api')
|
||||
.send(brew)
|
||||
.catch((err)=>{
|
||||
console.log('Error creating Local Copy');
|
||||
this.setState({ errors: err });
|
||||
return;
|
||||
});
|
||||
|
||||
await request.get(`/api/removeGoogle/${brew.googleId}${brew.editId}`)
|
||||
.send()
|
||||
.catch((err)=>{
|
||||
console.log('Error Deleting Google Brew');
|
||||
});
|
||||
|
||||
this.savedBrew = res.body;
|
||||
history.replaceState(null, null, `/edit/${this.savedBrew.editId}`); //update URL to match doc ID
|
||||
} else {
|
||||
const res = await request
|
||||
.put(`/api/update/${brew.editId}`)
|
||||
.send(brew)
|
||||
.catch((err)=>{
|
||||
console.log('Error Updating Local Brew');
|
||||
this.setState({ errors: err });
|
||||
return;
|
||||
});
|
||||
|
||||
this.savedBrew = res.body;
|
||||
}
|
||||
}
|
||||
this.savedBrew = res.body;
|
||||
history.replaceState(null, null, `/edit/${this.savedBrew.editId}`);
|
||||
|
||||
this.setState((prevState)=>({
|
||||
brew : _.merge({}, prevState.brew, {
|
||||
@@ -330,33 +274,33 @@ const EditPage = createClass({
|
||||
console.log(errMsg);
|
||||
} catch (e){}
|
||||
|
||||
if(this.state.errors.status == '401'){
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Oops!
|
||||
<div className='errorContainer' onClick={this.clearErrors}>
|
||||
You must be signed in to a Google account
|
||||
to save this to<br />Google Drive!<br />
|
||||
<a target='_blank' rel='noopener noreferrer'
|
||||
href={`https://www.naturalcrit.com/login?redirect=${this.state.url}`}>
|
||||
<div className='confirm'>
|
||||
Sign In
|
||||
</div>
|
||||
</a>
|
||||
<div className='deny'>
|
||||
Not Now
|
||||
</div>
|
||||
</div>
|
||||
</Nav.item>;
|
||||
}
|
||||
// if(this.state.errors.status == '401'){
|
||||
// return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
// Oops!
|
||||
// <div className='errorContainer' onClick={this.clearErrors}>
|
||||
// You must be signed in to a Google account
|
||||
// to save this to<br />Google Drive!<br />
|
||||
// <a target='_blank' rel='noopener noreferrer'
|
||||
// href={`https://www.naturalcrit.com/login?redirect=${this.state.url}`}>
|
||||
// <div className='confirm'>
|
||||
// Sign In
|
||||
// </div>
|
||||
// </a>
|
||||
// <div className='deny'>
|
||||
// Not Now
|
||||
// </div>
|
||||
// </div>
|
||||
// </Nav.item>;
|
||||
// }
|
||||
|
||||
if(this.state.errors.status == '403' && this.state.errors.response.body.errors[0].reason == 'insufficientPermissions'){
|
||||
if(this.state.errors.response.req.url.match(/^\/api.*Google.*$/m)){
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Oops!
|
||||
<div className='errorContainer' onClick={this.clearErrors}>
|
||||
Looks like your Google credentials have
|
||||
expired! Visit the log in page to sign out
|
||||
and sign back in with Google
|
||||
to save this to Google Drive!
|
||||
expired! Visit our log in page to sign out
|
||||
and sign back in with Google,
|
||||
then try saving again!
|
||||
<a target='_blank' rel='noopener noreferrer'
|
||||
href={`https://www.naturalcrit.com/login?redirect=${this.state.url}`}>
|
||||
<div className='confirm'>
|
||||
@@ -394,7 +338,7 @@ const EditPage = createClass({
|
||||
},
|
||||
|
||||
processShareId : function() {
|
||||
return this.state.brew.googleId ?
|
||||
return this.state.brew.googleId && !this.state.brew.stubbed ?
|
||||
this.state.brew.googleId + this.state.brew.shareId :
|
||||
this.state.brew.shareId;
|
||||
},
|
||||
@@ -406,7 +350,7 @@ const EditPage = createClass({
|
||||
const title = `${this.props.brew.title} ${systems}`;
|
||||
const text = `Hey guys! I've been working on this homebrew. I'd love your feedback. Check it out.
|
||||
|
||||
**[Homebrewery Link](https://homebrewery.naturalcrit.com/share/${shareLink})**`;
|
||||
**[Homebrewery Link](${global.config.publicUrl}/share/${shareLink})**`;
|
||||
|
||||
return `https://www.reddit.com/r/UnearthedArcana/submit?title=${encodeURIComponent(title)}&text=${encodeURIComponent(text)}`;
|
||||
},
|
||||
@@ -433,7 +377,7 @@ const EditPage = createClass({
|
||||
{this.renderGoogleDriveIcon()}
|
||||
{this.renderSaveButton()}
|
||||
<NewBrew />
|
||||
<ReportIssue />
|
||||
<HelpNavItem/>
|
||||
<Nav.dropdown>
|
||||
<Nav.item color='teal' icon='fas fa-share-alt'>
|
||||
share
|
||||
@@ -441,7 +385,7 @@ const EditPage = createClass({
|
||||
<Nav.item color='blue' href={`/share/${shareLink}`}>
|
||||
view
|
||||
</Nav.item>
|
||||
<Nav.item color='blue' onClick={()=>{navigator.clipboard.writeText(`https://homebrewery.naturalcrit.com/share/${shareLink}`);}}>
|
||||
<Nav.item color='blue' onClick={()=>{navigator.clipboard.writeText(`${global.config.publicUrl}/share/${shareLink}`);}}>
|
||||
copy url
|
||||
</Nav.item>
|
||||
<Nav.item color='blue' href={this.getRedditLink()} newTab={true} rel='noopener noreferrer'>
|
||||
|
||||
@@ -7,8 +7,8 @@ const cx = require('classnames');
|
||||
const Nav = require('naturalcrit/nav/nav.jsx');
|
||||
const Navbar = require('../../navbar/navbar.jsx');
|
||||
const PatreonNavItem = require('../../navbar/patreon.navitem.jsx');
|
||||
const IssueNavItem = require('../../navbar/issue.navitem.jsx');
|
||||
const RecentNavItem = require('../../navbar/recent.navitem.jsx').both;
|
||||
const HelpNavItem = require('../../navbar/help.navitem.jsx');
|
||||
|
||||
const BrewRenderer = require('../../brewRenderer/brewRenderer.jsx');
|
||||
|
||||
@@ -33,7 +33,7 @@ const ErrorPage = createClass({
|
||||
|
||||
<Nav.section>
|
||||
<PatreonNavItem />
|
||||
<IssueNavItem />
|
||||
<HelpNavItem />
|
||||
<RecentNavItem />
|
||||
</Nav.section>
|
||||
</Navbar>
|
||||
|
||||
@@ -9,7 +9,7 @@ const { Meta } = require('vitreum/headtags');
|
||||
const Nav = require('naturalcrit/nav/nav.jsx');
|
||||
const Navbar = require('../../navbar/navbar.jsx');
|
||||
const NewBrewItem = require('../../navbar/newbrew.navitem.jsx');
|
||||
const IssueNavItem = require('../../navbar/issue.navitem.jsx');
|
||||
const HelpNavItem = require('../../navbar/help.navitem.jsx');
|
||||
const RecentNavItem = require('../../navbar/recent.navitem.jsx').both;
|
||||
const AccountNavItem = require('../../navbar/account.navitem.jsx');
|
||||
|
||||
@@ -21,6 +21,7 @@ const BrewRenderer = require('../../brewRenderer/brewRenderer.jsx');
|
||||
|
||||
|
||||
const HomePage = createClass({
|
||||
displayName : 'HomePage',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
brew : {
|
||||
@@ -58,7 +59,7 @@ const HomePage = createClass({
|
||||
return <Navbar ver={this.props.ver}>
|
||||
<Nav.section>
|
||||
<NewBrewItem />
|
||||
<IssueNavItem />
|
||||
<HelpNavItem />
|
||||
<RecentNavItem />
|
||||
<AccountNavItem />
|
||||
</Nav.section>
|
||||
|
||||
202
client/homebrew/pages/homePage/migrate.md
Normal file
202
client/homebrew/pages/homePage/migrate.md
Normal file
@@ -0,0 +1,202 @@
|
||||
# How to Convert a Legacy Document to v3
|
||||
Here you will find a number of steps to guide you through converting a Legacy document into a Homebrewery v3 document.
|
||||
|
||||
**The first thing you'll want to do is switch the editor's rendering engine from `Legacy` to `v3`.** This will be the renderer we design features for moving forward.
|
||||
|
||||
There are some examples of Legacy code in the code pane if you need more context behind some of the changes.
|
||||
|
||||
**This document will evolve as users like yourself inform us of issues with it, or areas of conversion that it does not cover. _Please_ reach out if you have any suggestions for this document.**
|
||||
|
||||
## Simple Replacements
|
||||
To make your life a little easier with this section, a text editor like [VSCode](https://code.visualstudio.com/) or Notepad will help a lot.
|
||||
|
||||
The following table describes Legacy and other document elements and their Homebrewery counterparts. A simple find/replace should get these in working order.
|
||||
|
||||
| Legacy / Other | Homebrewery |
|
||||
|:----------------|:-----------------------------|
|
||||
| `\pagebreak` | `\page` |
|
||||
| `======` | `\page` |
|
||||
| `\pagebreaknum` | `{{pageNumber,auto}}\n\page` |
|
||||
| `@=====` | `{{pageNumber,auto}}\n\page` |
|
||||
| `\columnbreak` | `\column` |
|
||||
| `.phb` | `.page` |
|
||||
|
||||
## Classed or Styled Divs
|
||||
Anything that relies on the following syntax can be changed to the new Homebrewery v3 curly brace syntax:
|
||||
|
||||
```
|
||||
<div class="classTable wide">
|
||||
...
|
||||
</div>
|
||||
```
|
||||
:
|
||||
The above example is equivalent to the following in v3 syntax.
|
||||
|
||||
```
|
||||
{{classTable,wide
|
||||
...
|
||||
}}
|
||||
```
|
||||
:
|
||||
Some examples of this include class tables (as shown above), descriptive blocks, notes, and spell lists.
|
||||
|
||||
\column
|
||||
|
||||
## Margins and Padding
|
||||
Any manual margins and padding to push text down the page will likely need to be updated. Colons can be used on lines by themselves to push things down the page vertically if you'd rather not set pixel-perfect margins or padding.
|
||||
|
||||
## Notes
|
||||
|
||||
In Legacy, notes are denoted using markdown blockquote syntax. In Homebrewery v3, this is replaced by the curly brace syntax.
|
||||
|
||||
<!--
|
||||
> ##### Catchy Title
|
||||
> Useful Information
|
||||
-->
|
||||
|
||||
{{note
|
||||
##### Title
|
||||
Information
|
||||
}}
|
||||
|
||||
## Split Tables
|
||||
Split tables also use the curly brace syntax, as the new renderer can handle style values separately from class names.
|
||||
|
||||
<!--
|
||||
<div style='column-count:2'>
|
||||
|
||||
| d8 | Loot |
|
||||
|:---:|:-----------:|
|
||||
| 1 | 100gp |
|
||||
| 2 | 200gp |
|
||||
| 3 | 300gp |
|
||||
| 4 | 400gp |
|
||||
|
||||
| d8 | Loot |
|
||||
|:---:|:-----------:|
|
||||
| 5 | 500gp |
|
||||
| 6 | 600gp |
|
||||
| 7 | 700gp |
|
||||
| 8 | 1000gp |
|
||||
|
||||
</div>
|
||||
-->
|
||||
|
||||
##### Typical Difficulty Classes
|
||||
{{column-count:2
|
||||
| Task Difficulty | DC |
|
||||
|:----------------|:--:|
|
||||
| Very easy | 5 |
|
||||
| Easy | 10 |
|
||||
| Medium | 15 |
|
||||
|
||||
| Task Difficulty | DC |
|
||||
|:------------------|:--:|
|
||||
| Hard | 20 |
|
||||
| Very hard | 25 |
|
||||
| Nearly impossible | 30 |
|
||||
}}
|
||||
|
||||
## Blockquotes
|
||||
Blockquotes are denoted by the `>` character at the beginning of the line. In Homebrewery's v3 renderer, they hold virtually no meaning and have no CSS styling. You are free to use blockquotes when styling your document or creating themes without needing to worry about your CSS affecting other parts of the document.
|
||||
|
||||
{{pageNumber,auto}}
|
||||
|
||||
\page
|
||||
|
||||
## Stat Blocks
|
||||
|
||||
There are pretty significant differences between stat blocks on the Legacy renderer and Homebrewery v3. This section contains a list of changes that will need to be made to update the stat block.
|
||||
|
||||
### Initial Changes
|
||||
You will want to **remove all leading** `___` that started the stat block in Legacy, and replace that with `{{monster` before the stat block, and `}}` after it.
|
||||
|
||||
**If you want a frame** around the stat block, you can add `,frame` to the curly brace definition.
|
||||
|
||||
**If the stat block was wide**, make sure to add `,wide` to the curly brace definition.
|
||||
|
||||
### Blockquotes
|
||||
The key difference is the lack of blockquotes. Legacy documents use the `>` symbol at the start of the line for each line in the stat block, and the v3 renderer does not. **You will want to remove all `>` characters at the beginning of all lines, and delete any leading spaces.**
|
||||
|
||||
### Lists
|
||||
The basic characteristics and advanced characteristics sections are not list elements in Homebrewery. You will want to **remove all `-` or `*` characters from the beginning of lines.**
|
||||
|
||||
### Spacing
|
||||
In order to have the correct spacing after removing the list elements, you will want to **add two colons between the name of each basic/advanced characteristic and its value.** _(see example in the code pane)_
|
||||
|
||||
Additionally, in the special traits and actions sections, you will want to add a colon at the beginning of each line that separates a trait/action from another, as seen below. **Any empty lines between special traits and actions should contain only a colon.** _(see example in the code pane)_
|
||||
|
||||
\column
|
||||
|
||||
{{margin-top:102px}}
|
||||
|
||||
<!--
|
||||
### Legacy/Other Document Example:
|
||||
___
|
||||
> ## Centaur
|
||||
> *Large Monstrosity, neutral good*
|
||||
>___
|
||||
> - **Armor Class** 12
|
||||
> - **Hit Points** 45(6d10 + 12)
|
||||
> - **Speed** 50ft.
|
||||
>___
|
||||
>|STR|DEX|CON|INT|WIS|CHA|
|
||||
>|:---:|:---:|:---:|:---:|:---:|:---:|
|
||||
>|18 (+4)|14 (+2)|14 (+2)|9 (-1)|13 (+1)|11 (+0)|
|
||||
>___
|
||||
> - **Skills** Athletics +6, Perception +3, Survival +3
|
||||
> - **Senses** passive Perception 13
|
||||
> - **Languages** Elvish, Sylvan
|
||||
> - **Challenge** 2 (450 XP)
|
||||
> ___
|
||||
> ***Charge.*** If the centaur moves at least 30 feet straight toward a target and then hits it with a pike attack on the same turn, the target takes an extra 10 (3d6) piercing damage.
|
||||
>
|
||||
> ***Second Thing*** More details.
|
||||
>
|
||||
> ### Actions
|
||||
> ***Multiattack.*** The centaur makes two attacks: one with its pike and one with its hooves or two with its longbow.
|
||||
>
|
||||
> ***Pike.*** *Melee Weapon Attack:* +6 to hit, reach 10 ft., one target. *Hit:* 9 (1d10 + 4) piercing damage.
|
||||
>
|
||||
> ***Hooves.*** *Melee Weapon Attack:* +6 to hit, reach 5 ft., one target. *Hit:* 11 (2d6 + 4) bludgeoning damage.
|
||||
>
|
||||
> ***Longbow.*** *Ranged Weapon Attack:* +4 to hit, range 150/600 ft., one target. *Hit:* 6 (1d8 + 2) piercing damage.
|
||||
-->
|
||||
|
||||
### Homebrewery v3 Example:
|
||||
|
||||
{{monster
|
||||
## Centaur
|
||||
*Large monstrosity, neutral good*
|
||||
___
|
||||
**Armor Class** :: 12
|
||||
**Hit Points** :: 45(6d10 + 12)
|
||||
**Speed** :: 50ft.
|
||||
___
|
||||
| STR | DEX | CON | INT | WIS | CHA |
|
||||
|:-----:|:-----:|:-----:|:-----:|:-----:|:-----:|
|
||||
|18 (+4)|14 (+2)|14 (+2)|9 (-1) |13 (+1)|11 (+0)|
|
||||
___
|
||||
**Skills** :: Athletics +6, Perception +3, Survival +3
|
||||
**Senses** :: passive Perception 13
|
||||
**Languages** :: Elvish, Sylvan
|
||||
**Challenge** :: 2 (450 XP)
|
||||
___
|
||||
***Charge.*** If the centaur moves at least 30 feet straight toward a target and then hits it with a pike attack on the same turn, the target takes an extra 10 (3d6) piercing damage.
|
||||
:
|
||||
***Second Thing*** More details.
|
||||
|
||||
### Actions
|
||||
***Multiattack.*** The centaur makes two attacks: one with its pike and one with its hooves or two with its longbow.
|
||||
:
|
||||
***Pike.*** *Melee Weapon Attack:* +6 to hit, reach 10 ft., one target. *Hit:* 9 (1d10 + 4) piercing damage.
|
||||
:
|
||||
***Hooves.*** *Melee Weapon Attack:* +6 to hit, reach 5 ft., one target. *Hit:* 11 (2d6 + 4) bludgeoning damage.
|
||||
:
|
||||
***Longbow.*** *Ranged Weapon Attack:* +4 to hit, range 150/600 ft., one target. *Hit:* 6 (1d8 + 2) piercing damage.
|
||||
}}
|
||||
|
||||
{{pageNumber,auto}}
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
# The Homebrewery
|
||||
|
||||
Welcome traveler from an antique land. Please sit and tell us of what you have seen. The unheard of monsters, who slither and bite. Tell us of the wondrous items and and artifacts you have found, their mysteries yet to be unlocked. Of the vexing vocations and surprising skills you have seen.
|
||||
|
||||
### Homebrew D&D made easy
|
||||
@@ -57,17 +58,20 @@ The Homebrewery is licensed using the [MIT License](https://github.com/naturalcr
|
||||
If you wish to sell or in some way gain profit for what you make on this site, it's your responsibility to ensure you have the proper licenses/rights for any images or resources used.
|
||||
|
||||
### More Resources
|
||||
If you are looking for more 5e Homebrew resources check out [r/UnearthedArcana](https://www.reddit.com/r/UnearthedArcana/) and their list of useful resources [here](https://www.reddit.com/r/UnearthedArcana/wiki/resources).
|
||||
<a href='https://discord.gg/by3deKx' target='_blank'><img src='/assets/discordOfManyThings.svg' alt='Discord of Many Things Logo' title='Discord of Many Things Logo' style='width:50px; float: right; padding-left: 10px;'/></a>
|
||||
If you are looking for more 5e Homebrew resources check out [r/UnearthedArcana](https://www.reddit.com/r/UnearthedArcana/) and their list of useful resources [here](https://www.reddit.com/r/UnearthedArcana/wiki/resources). The <a href='https://discord.gg/by3deKx' target='_blank' title='Discord of Many Things'>Discord of Many Things</a> is another great resource to connect with fellow homebrewers for help and feedback.
|
||||
|
||||
|
||||
|
||||
<img src='https://i.imgur.com/hMna6G0.png' style='position:absolute;bottom:50px;right:30px;width:280px' />
|
||||
<img src='https://i.imgur.com/hMna6G0.png' style='position:absolute;bottom:40px;right:30px;width:280px' />
|
||||
|
||||
<div class='pageNumber'>1</div>
|
||||
<div class='footnote'>PART 1 | FANCINESS</div>
|
||||
|
||||
|
||||
|
||||
<div style='position: absolute; top: 20px; right: 20px;'>
|
||||
<a href='https://discord.gg/by3deKx' target='_blank' title='Discord of Many Things'><img src='/assets/discord.png' style='height:30px'/></a>
|
||||
<a href='https://github.com/naturalcrit/homebrewery' target='_blank' title='Github' style='color: black; padding-left: 5px;'><img src='/assets/github.png' style='height:30px'/></a>
|
||||
<a href='https://patreon.com/NaturalCrit' target='_blank' title='Patreon' style='color: black; padding-left: 5px;'><img src='/assets/patreon.png' style='height:30px'/></a>
|
||||
<a href='https://www.reddit.com/r/homebrewery/' target='_blank' title='Reddit' style='color: black; padding-left: 5px;'><img src='/assets/reddit.png' style='height:30px'/></a>
|
||||
</div>
|
||||
|
||||
\page
|
||||
|
||||
|
||||
@@ -2,7 +2,6 @@
|
||||
.page #example + table td {
|
||||
border:1px dashed #00000030;
|
||||
}
|
||||
|
||||
.page {
|
||||
padding-bottom : 1.1cm;
|
||||
}
|
||||
@@ -50,9 +49,9 @@ If you want to save ink or have a monochrome printer, add the **PRINT → {{fas,
|
||||
\column
|
||||
|
||||
## New in V3.0.0
|
||||
With the latest major update to *The Homebrewery* we've implemented an extended Markdown-like syntax for block and span elements, plus a few other changes, eliminating the need for HTML tags like `div` and `span` in most cases. No raw HTML tags should be needed in a brew, and going forward, raw HTML will no longer receive debugging support (*but can still be used if you insist*).
|
||||
We've implemented an extended Markdown-like syntax for block and span elements, plus a few other changes, eliminating the need for HTML tags like `div` and `span` in most cases. No raw HTML tags should be needed in a brew (*but can still be used if you insist*).
|
||||
|
||||
Much of the syntax and styling has changed in V3. Code in one version may be broken in the other, and updating an older brew to V3 will require more than just a copy and paste. *However*, all brews made prior to the release of v3.0.0 will still render normally, and you may switch between the "Legacy" brew renderer and the newer "V3" renderer via the {{fa,fa-info-circle}} **Properties** button on your brew at any time.
|
||||
Much of the syntax and styling has changed in V3, so converting a Legacy brew to V3 (or vice-versa) will require tweaking your document. *However*, all brews made prior to the release of v3.0.0 will still render normally, and you may switch between the "Legacy" brew renderer and the newer "V3" renderer via the {{fa,fa-info-circle}} **Properties** button on your brew at any time.
|
||||
|
||||
Scroll down to the next page for a brief summary of the changes and new features available in V3!
|
||||
|
||||
@@ -80,8 +79,15 @@ If you wish to sell or in some way gain profit for what's created on this site,
|
||||
If you'd like to credit me in your brew, I'd be flattered! Just reference that you made it with The Homebrewery.
|
||||
|
||||
### More Homebrew Resources
|
||||
Check out [r/UnearthedArcana](https://www.reddit.com/r/UnearthedArcana/) and their list of useful resources [here](https://www.reddit.com/r/UnearthedArcana/wiki/resources).
|
||||
<a href='https://discord.gg/by3deKx' target='_blank'><img src='/assets/discordOfManyThings.svg' alt='Discord of Many Things Logo' title='Discord of Many Things Logo' style='width:50px; float: right; padding-left: 10px;'/></a>
|
||||
If you are looking for more 5e Homebrew resources check out [r/UnearthedArcana](https://www.reddit.com/r/UnearthedArcana/) and their list of useful resources [here](https://www.reddit.com/r/UnearthedArcana/wiki/resources). The <a href='https://discord.gg/by3deKx' target='_blank' title='Discord of Many Things'>Discord of Many Things</a> is another great resource to connect with fellow homebrewers for help and feedback.
|
||||
|
||||
{{position:absolute;top:20px;right:20px;width:auto
|
||||
<a href='https://discord.gg/by3deKx' target='_blank' title='Discord of Many Things' style='color: black;'><img src='/assets/discord.png' style='height:30px'/></a>
|
||||
<a href='https://github.com/naturalcrit/homebrewery' target='_blank' title='Github' style='color: black; padding-left: 5px;'><img src='/assets/github.png' style='height:30px'/></a>
|
||||
<a href='https://patreon.com/NaturalCrit' target='_blank' title='Patreon' style='color: black; padding-left: 5px;'><img src='/assets/patreon.png' style='height:30px'/></a>
|
||||
<a href='https://www.reddit.com/r/homebrewery/' target='_blank' title='Reddit' style='color: black; padding-left: 5px;'><img src='/assets/reddit.png' style='height:30px'/></a>
|
||||
}}
|
||||
|
||||
\page
|
||||
|
||||
@@ -123,9 +129,7 @@ A blank line can be achieved with a run of one or more `:` alone on a line. More
|
||||
Much nicer than `<br><br><br><br><br>`
|
||||
|
||||
### Definition Lists
|
||||
V3 uses HTML *definition lists* to create "lists" with hanging indents.
|
||||
|
||||
**Senses** :: Here is some text that is long and overflows into a second line, creating a "hanging indent".
|
||||
**Example** :: V3 uses HTML *definition lists* to create "lists" with hanging indents.
|
||||
|
||||
### Column Breaks
|
||||
Column and page breaks with `\column` and `\page`.
|
||||
@@ -153,9 +157,9 @@ These can be combined to span a cell across both columns and rows. Cells must ha
|
||||
| 6A | 6B ^| 6C |
|
||||
|
||||
## Images
|
||||
Images must be hosted online somewhere, like [Imgur](https://www.imgur.com). You use the address to that image to reference it in your brew\*. Images can be included using Markdown-style images.
|
||||
Images must be hosted online somewhere, like [Imgur](https://www.imgur.com). You use the address to that image to reference it in your brew\*.
|
||||
|
||||
Using *Curly Injection* you can assign an id, classes, or specific inline CSS properties to the image.
|
||||
Using *Curly Injection* you can assign an id, classes, or inline CSS properties to the Markdown image syntax.
|
||||
|
||||
 {width:100px,border:"2px solid",border-radius:10px}
|
||||
|
||||
|
||||
@@ -11,7 +11,7 @@ const Nav = require('naturalcrit/nav/nav.jsx');
|
||||
const Navbar = require('../../navbar/navbar.jsx');
|
||||
const AccountNavItem = require('../../navbar/account.navitem.jsx');
|
||||
const RecentNavItem = require('../../navbar/recent.navitem.jsx').both;
|
||||
const IssueNavItem = require('../../navbar/issue.navitem.jsx');
|
||||
const HelpNavItem = require('../../navbar/help.navitem.jsx');
|
||||
|
||||
const SplitPane = require('naturalcrit/splitPane/splitPane.jsx');
|
||||
const Editor = require('../../editor/editor.jsx');
|
||||
@@ -23,6 +23,7 @@ const METAKEY = 'homebrewery-new-meta';
|
||||
|
||||
|
||||
const NewPage = createClass({
|
||||
displayName : 'NewPage',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
brew : {
|
||||
@@ -156,45 +157,24 @@ const NewPage = createClass({
|
||||
const index = brew.text.indexOf('```\n\n');
|
||||
brew.style = `${brew.style ? `${brew.style}\n` : ''}${brew.text.slice(7, index - 1)}`;
|
||||
brew.text = brew.text.slice(index + 5);
|
||||
};
|
||||
}
|
||||
|
||||
brew.pageCount=((brew.renderer=='legacy' ? brew.text.match(/\\page/g) : brew.text.match(/^\\page$/gm)) || []).length + 1;
|
||||
|
||||
if(this.state.saveGoogle) {
|
||||
const res = await request
|
||||
.post('/api/newGoogle/')
|
||||
const res = await request
|
||||
.post(`/api${this.state.saveGoogle ? '?saveToGoogle=true' : ''}`)
|
||||
.send(brew)
|
||||
.catch((err)=>{
|
||||
console.log(err.status === 401
|
||||
? 'Not signed in!'
|
||||
: 'Error Creating New Google Brew!');
|
||||
console.log(err);
|
||||
this.setState({ isSaving: false, errors: err });
|
||||
return;
|
||||
});
|
||||
if(!res) return;
|
||||
|
||||
brew = res.body;
|
||||
localStorage.removeItem(BREWKEY);
|
||||
localStorage.removeItem(STYLEKEY);
|
||||
localStorage.removeItem(METAKEY);
|
||||
window.location = `/edit/${brew.googleId}${brew.editId}`;
|
||||
} else {
|
||||
request.post('/api')
|
||||
.send(brew)
|
||||
.end((err, res)=>{
|
||||
if(err){
|
||||
this.setState({
|
||||
isSaving : false
|
||||
});
|
||||
return;
|
||||
}
|
||||
window.onbeforeunload = function(){};
|
||||
brew = res.body;
|
||||
localStorage.removeItem(BREWKEY);
|
||||
localStorage.removeItem(STYLEKEY);
|
||||
localStorage.removeItem(METAKEY);
|
||||
window.location = `/edit/${brew.editId}`;
|
||||
});
|
||||
}
|
||||
brew = res.body;
|
||||
localStorage.removeItem(BREWKEY);
|
||||
localStorage.removeItem(STYLEKEY);
|
||||
localStorage.removeItem(METAKEY);
|
||||
window.location = `/edit/${brew.editId}`;
|
||||
},
|
||||
|
||||
renderSaveButton : function(){
|
||||
@@ -207,33 +187,33 @@ const NewPage = createClass({
|
||||
console.log(errMsg);
|
||||
} catch (e){}
|
||||
|
||||
if(this.state.errors.status == '401'){
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Oops!
|
||||
<div className='errorContainer' onClick={this.clearErrors}>
|
||||
You must be signed in to a Google account
|
||||
to save this to<br />Google Drive!<br />
|
||||
<a target='_blank' rel='noopener noreferrer'
|
||||
href={`https://www.naturalcrit.com/login?redirect=${this.state.url}`}>
|
||||
<div className='confirm'>
|
||||
Sign In
|
||||
</div>
|
||||
</a>
|
||||
<div className='deny'>
|
||||
Not Now
|
||||
</div>
|
||||
</div>
|
||||
</Nav.item>;
|
||||
}
|
||||
// if(this.state.errors.status == '401'){
|
||||
// return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
// Oops!
|
||||
// <div className='errorContainer' onClick={this.clearErrors}>
|
||||
// You must be signed in to a Google account
|
||||
// to save this to<br />Google Drive!<br />
|
||||
// <a target='_blank' rel='noopener noreferrer'
|
||||
// href={`https://www.naturalcrit.com/login?redirect=${this.state.url}`}>
|
||||
// <div className='confirm'>
|
||||
// Sign In
|
||||
// </div>
|
||||
// </a>
|
||||
// <div className='deny'>
|
||||
// Not Now
|
||||
// </div>
|
||||
// </div>
|
||||
// </Nav.item>;
|
||||
// }
|
||||
|
||||
if(this.state.errors.status == '403' && this.state.errors.response.body.errors[0].reason == 'insufficientPermissions'){
|
||||
if(this.state.errors.response.req.url.match(/^\/api.*Google.*$/m)){
|
||||
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
|
||||
Oops!
|
||||
<div className='errorContainer' onClick={this.clearErrors}>
|
||||
Looks like your Google credentials have
|
||||
expired! Visit the log in page to sign out
|
||||
and sign back in with Google
|
||||
to save this to Google Drive!
|
||||
expired! Visit our log in page to sign out
|
||||
and sign back in with Google,
|
||||
then try saving again!
|
||||
<a target='_blank' rel='noopener noreferrer'
|
||||
href={`https://www.naturalcrit.com/login?redirect=${this.state.url}`}>
|
||||
<div className='confirm'>
|
||||
@@ -290,7 +270,7 @@ const NewPage = createClass({
|
||||
<Nav.section>
|
||||
{this.renderSaveButton()}
|
||||
{this.renderLocalPrintButton()}
|
||||
<IssueNavItem />
|
||||
<HelpNavItem />
|
||||
<RecentNavItem />
|
||||
<AccountNavItem />
|
||||
</Nav.section>
|
||||
|
||||
@@ -12,6 +12,7 @@ const STYLEKEY = 'homebrewery-new-style';
|
||||
const METAKEY = 'homebrewery-new-meta';
|
||||
|
||||
const PrintPage = createClass({
|
||||
displayName : 'PrintPage',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
query : {},
|
||||
|
||||
@@ -14,6 +14,7 @@ const BrewRenderer = require('../../brewRenderer/brewRenderer.jsx');
|
||||
|
||||
|
||||
const SharePage = createClass({
|
||||
displayName : 'SharePage',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
brew : {
|
||||
@@ -41,14 +42,14 @@ const SharePage = createClass({
|
||||
if(!(e.ctrlKey || e.metaKey)) return;
|
||||
const P_KEY = 80;
|
||||
if(e.keyCode == P_KEY){
|
||||
window.open(`/print/${this.props.brew.shareId}?dialog=true`, '_blank').focus();
|
||||
window.open(`/print/${this.processShareId()}?dialog=true`, '_blank').focus();
|
||||
e.stopPropagation();
|
||||
e.preventDefault();
|
||||
}
|
||||
},
|
||||
|
||||
processShareId : function() {
|
||||
return this.props.brew.googleId ?
|
||||
return this.props.brew.googleId && !this.props.brew.stubbed ?
|
||||
this.props.brew.googleId + this.props.brew.shareId :
|
||||
this.props.brew.shareId;
|
||||
},
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
require('./userPage.less');
|
||||
const React = require('react');
|
||||
const createClass = require('create-react-class');
|
||||
const _ = require('lodash');
|
||||
const cx = require('classnames');
|
||||
|
||||
const moment = require('moment');
|
||||
const ListPage = require('../basePages/listPage/listPage.jsx');
|
||||
|
||||
const Nav = require('naturalcrit/nav/nav.jsx');
|
||||
const Navbar = require('../../navbar/navbar.jsx');
|
||||
@@ -12,179 +11,59 @@ const Navbar = require('../../navbar/navbar.jsx');
|
||||
const RecentNavItem = require('../../navbar/recent.navitem.jsx').both;
|
||||
const Account = require('../../navbar/account.navitem.jsx');
|
||||
const NewBrew = require('../../navbar/newbrew.navitem.jsx');
|
||||
const BrewItem = require('./brewItem/brewItem.jsx');
|
||||
const ReportIssue = require('../../navbar/issue.navitem.jsx');
|
||||
|
||||
// const brew = {
|
||||
// title : 'SUPER Long title woah now',
|
||||
// authors : []
|
||||
// };
|
||||
|
||||
//const BREWS = _.times(25, ()=>{ return brew;});
|
||||
|
||||
const HelpNavItem = require('../../navbar/help.navitem.jsx');
|
||||
|
||||
const UserPage = createClass({
|
||||
displayName : 'UserPage',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
username : '',
|
||||
brews : [],
|
||||
query : ''
|
||||
};
|
||||
},
|
||||
getInitialState : function() {
|
||||
return {
|
||||
sortType : 'alpha',
|
||||
sortDir : 'asc',
|
||||
filterString : ''
|
||||
};
|
||||
},
|
||||
getUsernameWithS : function() {
|
||||
if(this.props.username.endsWith('s'))
|
||||
return `${this.props.username}'`;
|
||||
return `${this.props.username}'s`;
|
||||
},
|
||||
const usernameWithS = this.props.username + (this.props.username.endsWith('s') ? `'` : `'s`);
|
||||
|
||||
renderBrews : function(brews){
|
||||
if(!brews || !brews.length) return <div className='noBrews'>No Brews.</div>;
|
||||
|
||||
const sortedBrews = this.sortBrews(brews);
|
||||
|
||||
return _.map(sortedBrews, (brew, idx)=>{
|
||||
return <BrewItem brew={brew} key={idx}/>;
|
||||
});
|
||||
},
|
||||
|
||||
sortBrewOrder : function(brew){
|
||||
if(!brew.title){brew.title = 'No Title';}
|
||||
const mapping = {
|
||||
'alpha' : _.deburr(brew.title.toLowerCase()),
|
||||
'created' : moment(brew.createdAt).format(),
|
||||
'updated' : moment(brew.updatedAt).format(),
|
||||
'views' : brew.views,
|
||||
'latest' : moment(brew.lastViewed).format()
|
||||
};
|
||||
return mapping[this.state.sortType];
|
||||
},
|
||||
|
||||
sortBrews : function(brews){
|
||||
return _.orderBy(brews, (brew)=>{ return this.sortBrewOrder(brew); }, this.state.sortDir);
|
||||
},
|
||||
|
||||
handleSortOptionChange : function(event){
|
||||
this.setState({
|
||||
sortType : event.target.value
|
||||
});
|
||||
},
|
||||
|
||||
handleSortDirChange : function(event){
|
||||
this.setState({
|
||||
sortDir : `${(this.state.sortDir == 'asc' ? 'desc' : 'asc')}`
|
||||
});
|
||||
},
|
||||
|
||||
renderSortOption : function(sortTitle, sortValue){
|
||||
return <td>
|
||||
<button
|
||||
value={`${sortValue}`}
|
||||
onClick={this.handleSortOptionChange}
|
||||
className={`${(this.state.sortType == sortValue ? 'active' : '')}`}
|
||||
>
|
||||
{`${sortTitle}`}
|
||||
</button>
|
||||
</td>;
|
||||
},
|
||||
|
||||
handleFilterTextChange : function(e){
|
||||
this.setState({
|
||||
filterString : e.target.value
|
||||
});
|
||||
return;
|
||||
},
|
||||
|
||||
renderFilterOption : function(){
|
||||
return <td>
|
||||
<label>
|
||||
<i className='fas fa-search'></i>
|
||||
<input
|
||||
type='search'
|
||||
placeholder='search title/description'
|
||||
onChange={this.handleFilterTextChange}
|
||||
/>
|
||||
</label>
|
||||
</td>;
|
||||
},
|
||||
|
||||
renderSortOptions : function(){
|
||||
return <div className='sort-container'>
|
||||
<table>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>
|
||||
<h6>Sort by :</h6>
|
||||
</td>
|
||||
{this.renderSortOption('Title', 'alpha')}
|
||||
{this.renderSortOption('Created Date', 'created')}
|
||||
{this.renderSortOption('Updated Date', 'updated')}
|
||||
{this.renderSortOption('Views', 'views')}
|
||||
{/* {this.renderSortOption('Latest', 'latest')} */}
|
||||
<td>
|
||||
<h6>Direction :</h6>
|
||||
</td>
|
||||
<td>
|
||||
<button
|
||||
onClick={this.handleSortDirChange}
|
||||
className='sortDir'
|
||||
>
|
||||
{`${(this.state.sortDir == 'asc' ? '\u25B2 ASC' : '\u25BC DESC')}`}
|
||||
</button>
|
||||
</td>
|
||||
{this.renderFilterOption()}
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>;
|
||||
},
|
||||
|
||||
getSortedBrews : function(){
|
||||
const testString = _.deburr(this.state.filterString).toLowerCase();
|
||||
const brewCollection = this.state.filterString ? _.filter(this.props.brews, (brew)=>{
|
||||
return (_.deburr(brew.title).toLowerCase().includes(testString)) ||
|
||||
(_.deburr(brew.description).toLowerCase().includes(testString));
|
||||
}) : this.props.brews;
|
||||
return _.groupBy(brewCollection, (brew)=>{
|
||||
const brews = _.groupBy(this.props.brews, (brew)=>{
|
||||
return (brew.published ? 'published' : 'private');
|
||||
});
|
||||
|
||||
const brewCollection = [
|
||||
{
|
||||
title : `${usernameWithS} published brews`,
|
||||
class : 'published',
|
||||
brews : brews.published
|
||||
}
|
||||
];
|
||||
if(this.props.username == global.account?.username){
|
||||
brewCollection.push(
|
||||
{
|
||||
title : `${usernameWithS} unpublished brews`,
|
||||
class : 'unpublished',
|
||||
brews : brews.private
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
brewCollection : brewCollection
|
||||
};
|
||||
},
|
||||
|
||||
navItems : function() {
|
||||
return <Navbar>
|
||||
<Nav.section>
|
||||
<NewBrew />
|
||||
<HelpNavItem />
|
||||
<RecentNavItem />
|
||||
<Account />
|
||||
</Nav.section>
|
||||
</Navbar>;
|
||||
},
|
||||
|
||||
render : function(){
|
||||
const brews = this.getSortedBrews();
|
||||
|
||||
return <div className='userPage sitePage'>
|
||||
<link href='/themes/5ePhbLegacy.style.css' rel='stylesheet'/>
|
||||
<Navbar>
|
||||
<Nav.section>
|
||||
<NewBrew />
|
||||
<ReportIssue />
|
||||
<RecentNavItem />
|
||||
<Account />
|
||||
</Nav.section>
|
||||
</Navbar>
|
||||
|
||||
<div className='content V3'>
|
||||
<div className='phb'>
|
||||
{this.renderSortOptions()}
|
||||
<div className='published'>
|
||||
<h1>{this.getUsernameWithS()} published brews</h1>
|
||||
{this.renderBrews(brews.published)}
|
||||
</div>
|
||||
{this.props.username == global.account?.username &&
|
||||
<div className='unpublished'>
|
||||
<h1>{this.getUsernameWithS()} unpublished brews</h1>
|
||||
{this.renderBrews(brews.private)}
|
||||
</div>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
</div>;
|
||||
return <ListPage brewCollection={this.state.brewCollection} navItems={this.navItems()} query={this.props.query}></ListPage>;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
BIN
client/homebrew/thumbnail.png
Normal file
BIN
client/homebrew/thumbnail.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 5.9 KiB |
@@ -1,4 +1,6 @@
|
||||
module.exports = async(name, title = '', props = {})=>{
|
||||
const HOMEBREWERY_PUBLIC_URL=props.config.publicUrl;
|
||||
|
||||
return `
|
||||
<!DOCTYPE html>
|
||||
<html>
|
||||
@@ -6,7 +8,14 @@ module.exports = async(name, title = '', props = {})=>{
|
||||
<link href="//use.fontawesome.com/releases/v5.15.1/css/all.css" rel="stylesheet" />
|
||||
<link href="//fonts.googleapis.com/css?family=Open+Sans:400,300,600,700" rel="stylesheet" type="text/css" />
|
||||
<link href=${`/${name}/bundle.css`} rel='stylesheet' />
|
||||
<link rel="icon" href="/assets/homebrew/favicon.ico" type="image/x-icon" />
|
||||
<link rel="icon" href="/assets/favicon.ico" type="image/x-icon" />
|
||||
<meta property="og:title" content="${props.brew?.title || 'Homebrewery - Untitled Brew'}">
|
||||
<meta property="og:url" content="${HOMEBREWERY_PUBLIC_URL}/${props.brew?.shareId ? `share/${props.brew.shareId}` : ''}">
|
||||
<meta property="og:image" content="${props.brew?.thumbnail || `${HOMEBREWERY_PUBLIC_URL}/thumbnail.png`}">
|
||||
<meta property="og:description" content="${props.brew?.description || 'No description.'}">
|
||||
<meta property="og:site_name" content="The Homebrewery - Make your Homebrew content look legit!">
|
||||
<meta property="og:type" content="article">
|
||||
<meta name="twitter:card" content="summary_large_image">
|
||||
<title>${title.length ? `${title} - The Homebrewery`: 'The Homebrewery - NaturalCrit'}</title>
|
||||
</head>
|
||||
<body>
|
||||
|
||||
@@ -2,5 +2,8 @@
|
||||
"host" : "homebrewery.local.naturalcrit.com:8000",
|
||||
"naturalcrit_url" : "local.naturalcrit.com:8010",
|
||||
"secret" : "secret",
|
||||
"web_port" : 8000
|
||||
"web_port" : 8000,
|
||||
"enable_v3" : true,
|
||||
"local_environments" : ["docker", "local"],
|
||||
"publicUrl" : "https://homebrewery.naturalcrit.com"
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ These instructions assume that you are installing to a completely new, fresh Fre
|
||||
|
||||
2. Install wget (`pkg install -y wget`). On a fresh jail, you will be prompted to press 'Y' to set up `pkg`.
|
||||
|
||||
3. Download the installation script (`wget --no-check-certificate https://raw.githubusercontent.com/naturalcrit/homebrewery/master/freebsd/install.sh`). The parameter `--no-check-certificate` is required as we haven't set up any trusted certificates/authorities yet.
|
||||
3. Download the installation script (`wget --no-check-certificate https://raw.githubusercontent.com/naturalcrit/homebrewery/master/install/freebsd/install.sh`). The parameter `--no-check-certificate` is required as we haven't set up any trusted certificates/authorities yet.
|
||||
|
||||
4. Make the downloaded file executable (`chmod +x install.sh`).
|
||||
|
||||
35
install/README.UBUNTU.md
Normal file
35
install/README.UBUNTU.md
Normal file
@@ -0,0 +1,35 @@
|
||||
# Ubuntu Installation Instructions
|
||||
|
||||
## Before Installing
|
||||
|
||||
These instructions assume that you are installing to a completely new, fresh Ubuntu installation. As such, some steps will not be necessary if you are installing to an existing Ubuntu instance.
|
||||
|
||||
## Installation instructions
|
||||
|
||||
1. Install Ubuntu.
|
||||
|
||||
2. Install wget (`apt install -y wget`). This may already be installed, depending on your exact Ubuntu version.
|
||||
|
||||
3. Download the installation script (`wget https://raw.githubusercontent.com/naturalcrit/homebrewery/master/install/ubuntu/install.sh`).
|
||||
|
||||
4. Make the downloaded file executable (`chmod +x install.sh`).
|
||||
|
||||
5. Run the script (`sudo ./install.sh`). This will automatically download all of the required packages, install both them and HomeBrewery, configure the system and finally start HomeBrewery.
|
||||
|
||||
**NOTE:** At this time, the script **ONLY** installs HomeBrewery. It does **NOT** install the NaturalCrit login system, as that is currently a completely separate project.
|
||||
|
||||
---
|
||||
|
||||
### Testing
|
||||
|
||||
These installation instructions have been tested on the following Ubuntu releases:
|
||||
|
||||
- *ubuntu-20.04.3-desktop-amd64*
|
||||
|
||||
## Final Notes
|
||||
|
||||
While this installation process works successfully at the time of writing (December 19, 2021), it relies on all of the Node.JS packages used in the HomeBrewery project retaining their cross-platform capabilities to continue to function. This is one of the inherent advantages of Node.JS, but it is by no means guaranteed and as such, functionality or even installation may fail without warning at some point in the future.
|
||||
|
||||
Regards,
|
||||
G
|
||||
December 19, 2021
|
||||
13
install/ubuntu/etc/systemd/system/homebrewery.service
Normal file
13
install/ubuntu/etc/systemd/system/homebrewery.service
Normal file
@@ -0,0 +1,13 @@
|
||||
[Unit]
|
||||
Description=Homebrewery Web Server
|
||||
|
||||
[Service]
|
||||
User=root
|
||||
After=mongodb
|
||||
Environment=NODE_ENV=local
|
||||
WorkingDirectory=/usr/local/homebrewery
|
||||
ExecStart=node server.js
|
||||
Restart=always
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
34
install/ubuntu/install.sh
Normal file
34
install/ubuntu/install.sh
Normal file
@@ -0,0 +1,34 @@
|
||||
#!/bin/sh
|
||||
|
||||
# Install CURL and add required NodeJS source to package repo
|
||||
echo ::Install CURL
|
||||
apt install -y curl
|
||||
echo ::Add NodeJS source to package repo
|
||||
curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
|
||||
|
||||
# Install required packages
|
||||
echo ::Install Homebrewery requirements
|
||||
apt satisfy -y git nodejs npm mongodb
|
||||
|
||||
# Clone Homebrewery repo
|
||||
echo ::Get Homebrewery files
|
||||
cd /usr/local/
|
||||
git clone https://github.com/naturalcrit/homebrewery.git
|
||||
|
||||
# Install Homebrewery
|
||||
echo ::Install Homebrewery
|
||||
cd homebrewery
|
||||
npm install
|
||||
npm audit fix
|
||||
npm run postinstall
|
||||
|
||||
# Create Homebrewery service
|
||||
echo ::Create Homebrewery service
|
||||
ln -s /usr/local/homebrewery/install/ubuntu/etc/systemd/system/homebrewery.service /etc/systemd/system/homebrewery.service
|
||||
systemctl daemon-reload
|
||||
echo ::Set Homebrewery to start automatically
|
||||
systemctl enable homebrewery
|
||||
|
||||
# Start Homebrewery
|
||||
echo ::Start Homebrewery
|
||||
systemctl start homebrewery
|
||||
10840
package-lock.json
generated
10840
package-lock.json
generated
File diff suppressed because it is too large
Load Diff
66
package.json
66
package.json
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "homebrewery",
|
||||
"description": "Create authentic looking D&D homebrews using only markdown",
|
||||
"version": "3.0.4",
|
||||
"version": "3.1.1",
|
||||
"engines": {
|
||||
"node": "16.11.x"
|
||||
},
|
||||
@@ -18,8 +18,11 @@
|
||||
"lint:dry": "eslint **/*.{js,jsx}",
|
||||
"circleci": "npm test && eslint **/*.{js,jsx} --max-warnings=0",
|
||||
"verify": "npm run lint && npm test",
|
||||
"test": "pico-check",
|
||||
"test:dev": "pico-check -v -w",
|
||||
"test": "jest",
|
||||
"test:dev": "jest --verbose --watch",
|
||||
"test:basic": "jest tests/markdown/basic.test.js --verbose",
|
||||
"test:mustache-span": "jest tests/markdown/mustache-span.test.js --verbose",
|
||||
"test:route": "jest tests/routes/static-pages.test.js --verbose",
|
||||
"phb": "node scripts/phb.js",
|
||||
"prod": "set NODE_ENV=production && npm run build",
|
||||
"postinstall": "npm run buildall",
|
||||
@@ -30,53 +33,62 @@
|
||||
"eslintIgnore": [
|
||||
"build/*"
|
||||
],
|
||||
"pico-check": {
|
||||
"require": "./tests/test.init.js"
|
||||
"jest": {
|
||||
"testTimeout": 15000,
|
||||
"modulePaths": [
|
||||
"mode_modules",
|
||||
"shared",
|
||||
"server"
|
||||
]
|
||||
},
|
||||
"babel": {
|
||||
"presets": [
|
||||
"@babel/preset-env",
|
||||
"@babel/preset-react"
|
||||
],
|
||||
"plugins": [
|
||||
"@babel/plugin-transform-runtime"
|
||||
]
|
||||
},
|
||||
"dependencies": {
|
||||
"@babel/core": "^7.16.0",
|
||||
"@babel/plugin-transform-runtime": "^7.16.4",
|
||||
"@babel/preset-env": "^7.16.0",
|
||||
"@babel/preset-react": "^7.16.0",
|
||||
"body-parser": "^1.19.0",
|
||||
"@babel/core": "^7.18.5",
|
||||
"@babel/plugin-transform-runtime": "^7.18.5",
|
||||
"@babel/preset-env": "^7.18.2",
|
||||
"@babel/preset-react": "^7.17.12",
|
||||
"body-parser": "^1.20.0",
|
||||
"classnames": "^2.3.1",
|
||||
"codemirror": "^5.63.3",
|
||||
"codemirror": "^5.65.6",
|
||||
"cookie-parser": "^1.4.6",
|
||||
"create-react-class": "^15.7.0",
|
||||
"dedent-tabs": "^0.10.1",
|
||||
"express": "^4.17.1",
|
||||
"express-async-handler": "^1.1.4",
|
||||
"express-static-gzip": "2.1.1",
|
||||
"fs-extra": "10.0.0",
|
||||
"googleapis": "91.0.0",
|
||||
"express": "^4.18.1",
|
||||
"express-async-handler": "^1.2.0",
|
||||
"express-static-gzip": "2.1.7",
|
||||
"fs-extra": "10.1.0",
|
||||
"googleapis": "104.0.0",
|
||||
"js-yaml": "^4.1.0",
|
||||
"jwt-simple": "^0.5.6",
|
||||
"less": "^3.13.1",
|
||||
"lodash": "^4.17.21",
|
||||
"marked": "3.0.8",
|
||||
"marked": "4.0.17",
|
||||
"marked-extended-tables": "^1.0.3",
|
||||
"markedLegacy": "npm:marked@^0.3.19",
|
||||
"moment": "^2.29.1",
|
||||
"mongoose": "^6.0.13",
|
||||
"nanoid": "3.1.30",
|
||||
"nconf": "^0.11.3",
|
||||
"prop-types": "15.7.2",
|
||||
"query-string": "7.0.1",
|
||||
"moment": "^2.29.3",
|
||||
"mongoose": "^6.4.0",
|
||||
"nanoid": "3.3.4",
|
||||
"nconf": "^0.12.0",
|
||||
"react": "^16.14.0",
|
||||
"react-dom": "^16.14.0",
|
||||
"react-frame-component": "4.1.3",
|
||||
"react-router-dom": "5.3.0",
|
||||
"react-router-dom": "6.3.0",
|
||||
"sanitize-filename": "1.6.3",
|
||||
"superagent": "^6.1.0",
|
||||
"vitreum": "git+https://git@github.com/calculuschild/vitreum.git"
|
||||
},
|
||||
"devDependencies": {
|
||||
"eslint": "^8.2.0",
|
||||
"eslint-plugin-react": "^7.27.0",
|
||||
"pico-check": "^2.1.3"
|
||||
"eslint": "^8.18.0",
|
||||
"eslint-plugin-react": "^7.30.0",
|
||||
"jest": "^28.1.1",
|
||||
"supertest": "^6.2.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,6 +25,8 @@ const build = async ({ bundle, render, ssr })=>{
|
||||
await fs.outputFile('./build/homebrew/bundle.js', bundle);
|
||||
await fs.outputFile('./build/homebrew/ssr.js', ssr);
|
||||
await fs.copy('./themes/fonts', './build/fonts');
|
||||
await fs.copy('./themes/assets', './build/assets');
|
||||
await fs.copy('./client/homebrew/favicon.ico', './build/assets/favicon.ico');
|
||||
let src = './themes/5ePhbLegacy.style.less';
|
||||
//Parse brew theme files
|
||||
less.render(fs.readFileSync(src).toString(), {
|
||||
@@ -73,6 +75,6 @@ pack('./client/homebrew/homebrew.jsx', {
|
||||
if(isDev){
|
||||
livereload('./build');
|
||||
watchFile('./server.js', {
|
||||
watch : ['./client'] // Watch additional folders if you want
|
||||
watch : ['./client', './server'] // Watch additional folders if you want
|
||||
});
|
||||
}
|
||||
|
||||
@@ -14,6 +14,17 @@
|
||||
"codemirror/mode/javascript/javascript.js",
|
||||
"codemirror/addon/fold/foldcode.js",
|
||||
"codemirror/addon/fold/foldgutter.js",
|
||||
"codemirror/addon/fold/xml-fold.js",
|
||||
"codemirror/addon/scroll/scrollpastend.js",
|
||||
"codemirror/addon/search/search.js",
|
||||
"codemirror/addon/search/searchcursor.js",
|
||||
"codemirror/addon/search/jump-to-line.js",
|
||||
"codemirror/addon/search/match-highlighter.js",
|
||||
"codemirror/addon/search/matchesonscrollbar.js",
|
||||
"codemirror/addon/dialog/dialog.js",
|
||||
"codemirror/addon/edit/closetag.js",
|
||||
"codemirror/addon/edit/trailingspace.js",
|
||||
"codemirror/addon/selection/active-line.js",
|
||||
"moment",
|
||||
"superagent",
|
||||
"marked"
|
||||
|
||||
307
server.js
307
server.js
@@ -1,301 +1,12 @@
|
||||
/*eslint max-lines: ["warn", {"max": 300, "skipBlankLines": true, "skipComments": true}]*/
|
||||
const _ = require('lodash');
|
||||
const jwt = require('jwt-simple');
|
||||
const express = require('express');
|
||||
const app = express();
|
||||
const DB = require('./server/db.js');
|
||||
const server = require('./server/app.js');
|
||||
const config = require('./server/config.js');
|
||||
|
||||
const homebrewApi = require('./server/homebrew.api.js');
|
||||
const GoogleActions = require('./server/googleActions.js');
|
||||
const serveCompressedStaticAssets = require('./server/static-assets.mv.js');
|
||||
const sanitizeFilename = require('sanitize-filename');
|
||||
const asyncHandler = require('express-async-handler');
|
||||
|
||||
const brewAccessTypes = ['edit', 'share', 'raw'];
|
||||
|
||||
//Get the brew object from the HB database or Google Drive
|
||||
const getBrewFromId = asyncHandler(async (id, accessType)=>{
|
||||
if(!brewAccessTypes.includes(accessType))
|
||||
throw ('Invalid Access Type when getting brew');
|
||||
let brew;
|
||||
if(id.length > 12) {
|
||||
const googleId = id.slice(0, -12);
|
||||
id = id.slice(-12);
|
||||
brew = await GoogleActions.readFileMetadata(config.get('google_api_key'), googleId, id, accessType);
|
||||
} else {
|
||||
brew = await HomebrewModel.get(accessType == 'edit' ? { editId: id } : { shareId: id });
|
||||
brew = brew.toObject(); // Convert MongoDB object to standard Javascript Object
|
||||
}
|
||||
|
||||
brew = sanitizeBrew(brew, accessType === 'edit' ? false : true);
|
||||
//Split brew.text into text and style
|
||||
//unless the Access Type is RAW, in which case return immediately
|
||||
if(accessType == 'raw') {
|
||||
return brew;
|
||||
}
|
||||
splitTextAndStyle(brew);
|
||||
return brew;
|
||||
});
|
||||
|
||||
const sanitizeBrew = (brew, full=false)=>{
|
||||
delete brew._id;
|
||||
delete brew.__v;
|
||||
if(full){
|
||||
delete brew.editId;
|
||||
}
|
||||
return brew;
|
||||
};
|
||||
|
||||
const splitTextAndStyle = (brew)=>{
|
||||
brew.text = brew.text.replaceAll('\r\n', '\n');
|
||||
if(brew.text.startsWith('```css')) {
|
||||
const index = brew.text.indexOf('```\n\n');
|
||||
brew.style = brew.text.slice(7, index - 1);
|
||||
brew.text = brew.text.slice(index + 5);
|
||||
}
|
||||
};
|
||||
|
||||
app.use('/', serveCompressedStaticAssets(`${__dirname}/build`));
|
||||
|
||||
process.chdir(__dirname);
|
||||
|
||||
//app.use(express.static(`${__dirname}/build`));
|
||||
app.use(require('body-parser').json({ limit: '25mb' }));
|
||||
app.use(require('cookie-parser')());
|
||||
app.use(require('./server/forcessl.mw.js'));
|
||||
|
||||
const config = require('nconf')
|
||||
.argv()
|
||||
.env({ lowerCase: true })
|
||||
.file('environment', { file: `config/${process.env.NODE_ENV}.json` })
|
||||
.file('defaults', { file: 'config/default.json' });
|
||||
|
||||
//DB
|
||||
const mongoose = require('mongoose');
|
||||
mongoose.connect(config.get('mongodb_uri') || config.get('mongolab_uri') || 'mongodb://localhost/naturalcrit',
|
||||
{ retryWrites: false });
|
||||
mongoose.connection.on('error', (err)=>{
|
||||
console.log('Error : Could not connect to a Mongo Database.');
|
||||
console.log(' If you are running locally, make sure mongodb.exe is running.');
|
||||
console.log(err);
|
||||
throw 'Can not connect to Mongo';
|
||||
});
|
||||
|
||||
//Account Middleware
|
||||
app.use((req, res, next)=>{
|
||||
if(req.cookies && req.cookies.nc_session){
|
||||
try {
|
||||
req.account = jwt.decode(req.cookies.nc_session, config.get('secret'));
|
||||
//console.log("Just loaded up JWT from cookie:");
|
||||
//console.log(req.account);
|
||||
} catch (e){}
|
||||
}
|
||||
|
||||
req.config = {
|
||||
google_client_id : config.get('google_client_id'),
|
||||
google_client_secret : config.get('google_client_secret')
|
||||
};
|
||||
return next();
|
||||
});
|
||||
|
||||
app.use(homebrewApi);
|
||||
app.use(require('./server/admin.api.js'));
|
||||
|
||||
const HomebrewModel = require('./server/homebrew.model.js').model;
|
||||
const welcomeText = require('fs').readFileSync('./client/homebrew/pages/homePage/welcome_msg.md', 'utf8');
|
||||
const welcomeTextV3 = require('fs').readFileSync('./client/homebrew/pages/homePage/welcome_msg_v3.md', 'utf8');
|
||||
const changelogText = require('fs').readFileSync('./changelog.md', 'utf8');
|
||||
const faqText = require('fs').readFileSync('./faq.md', 'utf8');
|
||||
|
||||
String.prototype.replaceAll = function(s, r){return this.split(s).join(r);};
|
||||
|
||||
//Robots.txt
|
||||
app.get('/robots.txt', (req, res)=>{
|
||||
return res.sendFile(`${__dirname}/robots.txt`);
|
||||
});
|
||||
|
||||
//Home page
|
||||
app.get('/', async (req, res, next)=>{
|
||||
const brew = {
|
||||
text : welcomeText
|
||||
};
|
||||
req.brew = brew;
|
||||
return next();
|
||||
});
|
||||
|
||||
//Home page v3
|
||||
app.get('/v3_preview', async (req, res, next)=>{
|
||||
const brew = {
|
||||
text : welcomeTextV3,
|
||||
renderer : 'V3'
|
||||
};
|
||||
splitTextAndStyle(brew);
|
||||
req.brew = brew;
|
||||
return next();
|
||||
});
|
||||
|
||||
//Changelog page
|
||||
app.get('/changelog', async (req, res, next)=>{
|
||||
const brew = {
|
||||
title : 'Changelog',
|
||||
text : changelogText,
|
||||
renderer : 'V3'
|
||||
};
|
||||
splitTextAndStyle(brew);
|
||||
req.brew = brew;
|
||||
return next();
|
||||
});
|
||||
|
||||
//FAQ page
|
||||
app.get('/faq', async (req, res, next)=>{
|
||||
const brew = {
|
||||
title : 'FAQ',
|
||||
text : faqText,
|
||||
renderer : 'V3'
|
||||
};
|
||||
splitTextAndStyle(brew);
|
||||
req.brew = brew;
|
||||
return next();
|
||||
});
|
||||
|
||||
//Source page
|
||||
app.get('/source/:id', asyncHandler(async (req, res)=>{
|
||||
const brew = await getBrewFromId(req.params.id, 'raw');
|
||||
|
||||
const replaceStrings = { '&': '&', '<': '<', '>': '>' };
|
||||
let text = brew.text;
|
||||
for (const replaceStr in replaceStrings) {
|
||||
text = text.replaceAll(replaceStr, replaceStrings[replaceStr]);
|
||||
}
|
||||
text = `<code><pre style="white-space: pre-wrap;">${text}</pre></code>`;
|
||||
res.status(200).send(text);
|
||||
}));
|
||||
|
||||
//Download brew source page
|
||||
app.get('/download/:id', asyncHandler(async (req, res)=>{
|
||||
const brew = await getBrewFromId(req.params.id, 'raw');
|
||||
const prefix = 'HB - ';
|
||||
|
||||
let fileName = sanitizeFilename(`${prefix}${brew.title}`).replaceAll(' ', '');
|
||||
if(!fileName || !fileName.length) { fileName = `${prefix}-Untitled-Brew`; };
|
||||
res.set({
|
||||
'Cache-Control' : 'no-cache',
|
||||
'Content-Type' : 'text/plain',
|
||||
'Content-Disposition' : `attachment; filename="${fileName}.txt"`
|
||||
DB.connect(config).then(()=>{
|
||||
// Ensure that we have successfully connected to the database
|
||||
// before launching server
|
||||
const PORT = process.env.PORT || config.get('web_port') || 8000;
|
||||
server.app.listen(PORT, ()=>{
|
||||
console.log(`server on port: ${PORT}`);
|
||||
});
|
||||
res.status(200).send(brew.text);
|
||||
}));
|
||||
|
||||
//User Page
|
||||
app.get('/user/:username', async (req, res, next)=>{
|
||||
const ownAccount = req.account && (req.account.username == req.params.username);
|
||||
|
||||
let brews = await HomebrewModel.getByUser(req.params.username, ownAccount)
|
||||
.catch((err)=>{
|
||||
console.log(err);
|
||||
});
|
||||
|
||||
if(ownAccount && req?.account?.googleId){
|
||||
const googleBrews = await GoogleActions.listGoogleBrews(req, res)
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
});
|
||||
|
||||
if(googleBrews)
|
||||
brews = _.concat(brews, googleBrews);
|
||||
}
|
||||
|
||||
req.brews = _.map(brews, (brew)=>{
|
||||
return sanitizeBrew(brew, !ownAccount);
|
||||
});
|
||||
|
||||
return next();
|
||||
});
|
||||
|
||||
//Edit Page
|
||||
app.get('/edit/:id', asyncHandler(async (req, res, next)=>{
|
||||
res.header('Cache-Control', 'no-cache, no-store'); //reload the latest saved brew when pressing back button, not the cached version before save.
|
||||
const brew = await getBrewFromId(req.params.id, 'edit');
|
||||
req.brew = brew;
|
||||
return next();
|
||||
}));
|
||||
|
||||
//New Page
|
||||
app.get('/new/:id', asyncHandler(async (req, res, next)=>{
|
||||
const brew = await getBrewFromId(req.params.id, 'share');
|
||||
brew.title = `CLONE - ${brew.title}`;
|
||||
req.brew = brew;
|
||||
return next();
|
||||
}));
|
||||
|
||||
//Share Page
|
||||
app.get('/share/:id', asyncHandler(async (req, res, next)=>{
|
||||
const brew = await getBrewFromId(req.params.id, 'share');
|
||||
|
||||
if(req.params.id.length > 12) {
|
||||
const googleId = req.params.id.slice(0, -12);
|
||||
const shareId = req.params.id.slice(-12);
|
||||
await GoogleActions.increaseView(googleId, shareId, 'share', brew)
|
||||
.catch((err)=>{next(err);});
|
||||
} else {
|
||||
await HomebrewModel.increaseView({ shareId: brew.shareId });
|
||||
}
|
||||
|
||||
req.brew = brew;
|
||||
return next();
|
||||
}));
|
||||
|
||||
//Print Page
|
||||
app.get('/print/:id', asyncHandler(async (req, res, next)=>{
|
||||
const brew = await getBrewFromId(req.params.id, 'share');
|
||||
req.brew = brew;
|
||||
return next();
|
||||
}));
|
||||
|
||||
//Render the page
|
||||
const templateFn = require('./client/template.js');
|
||||
app.use((req, res)=>{
|
||||
const props = {
|
||||
version : require('./package.json').version,
|
||||
url : req.originalUrl,
|
||||
brew : req.brew,
|
||||
brews : req.brews,
|
||||
googleBrews : req.googleBrews,
|
||||
account : req.account,
|
||||
enable_v3 : config.get('enable_v3')
|
||||
};
|
||||
templateFn('homebrew', title = req.brew ? req.brew.title : '', props)
|
||||
.then((page)=>{ res.send(page); })
|
||||
.catch((err)=>{
|
||||
console.log(err);
|
||||
return res.sendStatus(500);
|
||||
});
|
||||
});
|
||||
|
||||
//v=====----- Error-Handling Middleware -----=====v//
|
||||
//Format Errors so all fields will be sent
|
||||
const replaceErrors = (key, value)=>{
|
||||
if(value instanceof Error) {
|
||||
const error = {};
|
||||
Object.getOwnPropertyNames(value).forEach(function (key) {
|
||||
error[key] = value[key];
|
||||
});
|
||||
return error;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const getPureError = (error)=>{
|
||||
return JSON.parse(JSON.stringify(error, replaceErrors));
|
||||
};
|
||||
|
||||
app.use((err, req, res, next)=>{
|
||||
const status = err.status || 500;
|
||||
console.error(err);
|
||||
res.status(status).send(getPureError(err));
|
||||
});
|
||||
//^=====--------------------------------------=====^//
|
||||
|
||||
const PORT = process.env.PORT || config.get('web_port') || 8000;
|
||||
app.listen(PORT, ()=>{
|
||||
console.log(`server on port:${PORT}`);
|
||||
});
|
||||
|
||||
338
server/app.js
Normal file
338
server/app.js
Normal file
@@ -0,0 +1,338 @@
|
||||
/*eslint max-lines: ["warn", {"max": 300, "skipBlankLines": true, "skipComments": true}]*/
|
||||
// Set working directory to project root
|
||||
process.chdir(`${__dirname}/..`);
|
||||
|
||||
const _ = require('lodash');
|
||||
const jwt = require('jwt-simple');
|
||||
const express = require('express');
|
||||
const yaml = require('js-yaml');
|
||||
const app = express();
|
||||
const config = require('./config.js');
|
||||
|
||||
const { homebrewApi, getBrew } = require('./homebrew.api.js');
|
||||
const GoogleActions = require('./googleActions.js');
|
||||
const serveCompressedStaticAssets = require('./static-assets.mv.js');
|
||||
const sanitizeFilename = require('sanitize-filename');
|
||||
const asyncHandler = require('express-async-handler');
|
||||
|
||||
const splitTextStyleAndMetadata = (brew)=>{
|
||||
brew.text = brew.text.replaceAll('\r\n', '\n');
|
||||
if(brew.text.startsWith('```metadata')) {
|
||||
const index = brew.text.indexOf('```\n\n');
|
||||
const metadataSection = brew.text.slice(12, index - 1);
|
||||
const metadata = yaml.load(metadataSection);
|
||||
Object.assign(brew, _.pick(metadata, ['title', 'description', 'tags', 'systems', 'renderer']));
|
||||
brew.text = brew.text.slice(index + 5);
|
||||
}
|
||||
if(brew.text.startsWith('```css')) {
|
||||
const index = brew.text.indexOf('```\n\n');
|
||||
brew.style = brew.text.slice(7, index - 1);
|
||||
brew.text = brew.text.slice(index + 5);
|
||||
}
|
||||
};
|
||||
|
||||
const sanitizeBrew = (brew, accessType)=>{
|
||||
brew._id = undefined;
|
||||
brew.__v = undefined;
|
||||
if(accessType !== 'edit'){
|
||||
brew.editId = undefined;
|
||||
}
|
||||
return brew;
|
||||
};
|
||||
|
||||
app.use('/', serveCompressedStaticAssets(`build`));
|
||||
|
||||
//app.use(express.static(`${__dirname}/build`));
|
||||
app.use(require('body-parser').json({ limit: '25mb' }));
|
||||
app.use(require('cookie-parser')());
|
||||
app.use(require('./forcessl.mw.js'));
|
||||
|
||||
//Account Middleware
|
||||
app.use((req, res, next)=>{
|
||||
if(req.cookies && req.cookies.nc_session){
|
||||
try {
|
||||
req.account = jwt.decode(req.cookies.nc_session, config.get('secret'));
|
||||
//console.log("Just loaded up JWT from cookie:");
|
||||
//console.log(req.account);
|
||||
} catch (e){}
|
||||
}
|
||||
|
||||
req.config = {
|
||||
google_client_id : config.get('google_client_id'),
|
||||
google_client_secret : config.get('google_client_secret')
|
||||
};
|
||||
return next();
|
||||
});
|
||||
|
||||
app.use(homebrewApi);
|
||||
app.use(require('./admin.api.js'));
|
||||
|
||||
const HomebrewModel = require('./homebrew.model.js').model;
|
||||
const welcomeText = require('fs').readFileSync('client/homebrew/pages/homePage/welcome_msg.md', 'utf8');
|
||||
const welcomeTextV3 = require('fs').readFileSync('client/homebrew/pages/homePage/welcome_msg_v3.md', 'utf8');
|
||||
const migrateText = require('fs').readFileSync('client/homebrew/pages/homePage/migrate.md', 'utf8');
|
||||
const changelogText = require('fs').readFileSync('changelog.md', 'utf8');
|
||||
const faqText = require('fs').readFileSync('faq.md', 'utf8');
|
||||
|
||||
String.prototype.replaceAll = function(s, r){return this.split(s).join(r);};
|
||||
|
||||
//Robots.txt
|
||||
app.get('/robots.txt', (req, res)=>{
|
||||
return res.sendFile(`robots.txt`, { root: process.cwd() });
|
||||
});
|
||||
|
||||
//Home page
|
||||
app.get('/', (req, res, next)=>{
|
||||
req.brew = {
|
||||
text : welcomeText
|
||||
};
|
||||
return next();
|
||||
});
|
||||
|
||||
//Home page v3
|
||||
app.get('/v3_preview', (req, res, next)=>{
|
||||
req.brew = {
|
||||
text : welcomeTextV3,
|
||||
renderer : 'V3'
|
||||
};
|
||||
splitTextStyleAndMetadata(req.brew);
|
||||
return next();
|
||||
});
|
||||
|
||||
//Legacy/Other Document -> v3 Migration Guide
|
||||
app.get('/migrate', (req, res, next)=>{
|
||||
req.brew = {
|
||||
text : migrateText,
|
||||
renderer : 'V3'
|
||||
};
|
||||
splitTextStyleAndMetadata(req.brew);
|
||||
return next();
|
||||
});
|
||||
|
||||
//Changelog page
|
||||
app.get('/changelog', async (req, res, next)=>{
|
||||
req.brew = {
|
||||
title : 'Changelog',
|
||||
text : changelogText,
|
||||
renderer : 'V3'
|
||||
};
|
||||
splitTextStyleAndMetadata(req.brew);
|
||||
return next();
|
||||
});
|
||||
|
||||
//FAQ page
|
||||
app.get('/faq', async (req, res, next)=>{
|
||||
req.brew = {
|
||||
title : 'FAQ',
|
||||
text : faqText,
|
||||
renderer : 'V3'
|
||||
};
|
||||
splitTextStyleAndMetadata(req.brew);
|
||||
return next();
|
||||
});
|
||||
|
||||
//Source page
|
||||
app.get('/source/:id', asyncHandler(getBrew('share')), (req, res)=>{
|
||||
const { brew } = req;
|
||||
|
||||
const replaceStrings = { '&': '&', '<': '<', '>': '>' };
|
||||
let text = brew.text;
|
||||
for (const replaceStr in replaceStrings) {
|
||||
text = text.replaceAll(replaceStr, replaceStrings[replaceStr]);
|
||||
}
|
||||
text = `<code><pre style="white-space: pre-wrap;">${text}</pre></code>`;
|
||||
res.status(200).send(text);
|
||||
});
|
||||
|
||||
//Download brew source page
|
||||
app.get('/download/:id', asyncHandler(getBrew('share')), (req, res)=>{
|
||||
const { brew } = req;
|
||||
sanitizeBrew(brew, 'share');
|
||||
const prefix = 'HB - ';
|
||||
|
||||
let fileName = sanitizeFilename(`${prefix}${brew.title}`).replaceAll(' ', '');
|
||||
if(!fileName || !fileName.length) { fileName = `${prefix}-Untitled-Brew`; };
|
||||
res.set({
|
||||
'Cache-Control' : 'no-cache',
|
||||
'Content-Type' : 'text/plain',
|
||||
'Content-Disposition' : `attachment; filename="${fileName}.txt"`
|
||||
});
|
||||
res.status(200).send(brew.text);
|
||||
});
|
||||
|
||||
//User Page
|
||||
app.get('/user/:username', async (req, res, next)=>{
|
||||
const ownAccount = req.account && (req.account.username == req.params.username);
|
||||
|
||||
const fields = [
|
||||
'googleId',
|
||||
'title',
|
||||
'pageCount',
|
||||
'description',
|
||||
'authors',
|
||||
'published',
|
||||
'views',
|
||||
'shareId',
|
||||
'editId',
|
||||
'createdAt',
|
||||
'updatedAt',
|
||||
'lastViewed'
|
||||
];
|
||||
|
||||
let brews = await HomebrewModel.getByUser(req.params.username, ownAccount, fields)
|
||||
.catch((err)=>{
|
||||
console.log(err);
|
||||
});
|
||||
|
||||
if(ownAccount && req?.account?.googleId){
|
||||
const auth = await GoogleActions.authCheck(req.account, res);
|
||||
let googleBrews = await GoogleActions.listGoogleBrews(auth)
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
});
|
||||
|
||||
if(googleBrews && googleBrews.length > 0) {
|
||||
for (const brew of brews.filter((brew)=>brew.googleId)) {
|
||||
const match = googleBrews.findIndex((b)=>b.editId === brew.editId);
|
||||
if(match !== -1) {
|
||||
brew.googleId = googleBrews[match].googleId;
|
||||
brew.stubbed = true;
|
||||
brew.pageCount = googleBrews[match].pageCount;
|
||||
brew.renderer = googleBrews[match].renderer;
|
||||
brew.version = googleBrews[match].version;
|
||||
googleBrews.splice(match, 1);
|
||||
}
|
||||
}
|
||||
|
||||
googleBrews = googleBrews.map((brew)=>({ ...brew, authors: [req.account.username] }));
|
||||
brews = _.concat(brews, googleBrews);
|
||||
}
|
||||
}
|
||||
|
||||
req.brews = _.map(brews, (brew)=>{
|
||||
return sanitizeBrew(brew, ownAccount ? 'edit' : 'share');
|
||||
});
|
||||
|
||||
return next();
|
||||
});
|
||||
|
||||
//Edit Page
|
||||
app.get('/edit/:id', asyncHandler(getBrew('edit')), (req, res, next)=>{
|
||||
req.brew = req.brew.toObject ? req.brew.toObject() : req.brew;
|
||||
sanitizeBrew(req.brew, 'edit');
|
||||
splitTextStyleAndMetadata(req.brew);
|
||||
res.header('Cache-Control', 'no-cache, no-store'); //reload the latest saved brew when pressing back button, not the cached version before save.
|
||||
return next();
|
||||
});
|
||||
|
||||
//New Page
|
||||
app.get('/new/:id', asyncHandler(getBrew('share')), (req, res, next)=>{
|
||||
sanitizeBrew(req.brew, 'share');
|
||||
splitTextStyleAndMetadata(req.brew);
|
||||
req.brew.title = `CLONE - ${req.brew.title}`;
|
||||
return next();
|
||||
});
|
||||
|
||||
//Share Page
|
||||
app.get('/share/:id', asyncHandler(getBrew('share')), asyncHandler(async (req, res, next)=>{
|
||||
const { brew } = req;
|
||||
|
||||
if(req.params.id.length > 12 && !brew._id) {
|
||||
const googleId = req.params.id.slice(0, -12);
|
||||
const shareId = req.params.id.slice(-12);
|
||||
await GoogleActions.increaseView(googleId, shareId, 'share', brew)
|
||||
.catch((err)=>{next(err);});
|
||||
} else {
|
||||
await HomebrewModel.increaseView({ shareId: brew.shareId });
|
||||
}
|
||||
sanitizeBrew(req.brew, 'share');
|
||||
splitTextStyleAndMetadata(req.brew);
|
||||
return next();
|
||||
}));
|
||||
|
||||
//Print Page
|
||||
app.get('/print/:id', asyncHandler(getBrew('share')), (req, res, next)=>{
|
||||
sanitizeBrew(req.brew, 'share');
|
||||
splitTextStyleAndMetadata(req.brew);
|
||||
next();
|
||||
});
|
||||
|
||||
const nodeEnv = config.get('node_env');
|
||||
const isLocalEnvironment = config.get('local_environments').includes(nodeEnv);
|
||||
// Local only
|
||||
if(isLocalEnvironment){
|
||||
// Login
|
||||
app.post('/local/login', (req, res)=>{
|
||||
const username = req.body.username;
|
||||
if(!username) return;
|
||||
|
||||
const payload = jwt.encode({ username: username, issued: new Date }, config.get('secret'));
|
||||
return res.json(payload);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
|
||||
//Render the page
|
||||
const templateFn = require('./../client/template.js');
|
||||
app.use(asyncHandler(async (req, res, next)=>{
|
||||
// Create configuration object
|
||||
const configuration = {
|
||||
local : isLocalEnvironment,
|
||||
publicUrl : config.get('publicUrl') ?? '',
|
||||
environment : nodeEnv
|
||||
};
|
||||
const props = {
|
||||
version : require('./../package.json').version,
|
||||
url : req.originalUrl,
|
||||
brew : req.brew,
|
||||
brews : req.brews,
|
||||
googleBrews : req.googleBrews,
|
||||
account : req.account,
|
||||
enable_v3 : config.get('enable_v3'),
|
||||
config : configuration
|
||||
};
|
||||
const title = req.brew ? req.brew.title : '';
|
||||
const page = await templateFn('homebrew', title, props)
|
||||
.catch((err)=>{
|
||||
console.log(err);
|
||||
return res.sendStatus(500);
|
||||
});
|
||||
if(!page) return;
|
||||
res.send(page);
|
||||
}));
|
||||
|
||||
//v=====----- Error-Handling Middleware -----=====v//
|
||||
//Format Errors so all fields will be sent
|
||||
const replaceErrors = (key, value)=>{
|
||||
if(value instanceof Error) {
|
||||
const error = {};
|
||||
Object.getOwnPropertyNames(value).forEach(function (key) {
|
||||
error[key] = value[key];
|
||||
});
|
||||
return error;
|
||||
}
|
||||
return value;
|
||||
};
|
||||
|
||||
const getPureError = (error)=>{
|
||||
return JSON.parse(JSON.stringify(error, replaceErrors));
|
||||
};
|
||||
|
||||
app.use((err, req, res, next)=>{
|
||||
const status = err.status || 500;
|
||||
console.error(err);
|
||||
res.status(status).send(getPureError(err));
|
||||
});
|
||||
|
||||
app.use((req, res)=>{
|
||||
if(!res.headersSent) {
|
||||
console.error('Headers have not been sent, responding with a server error.', req.url);
|
||||
res.status(500).send('An error occurred and the server did not send a response. The error has been logged, please note the time this occurred and report this issue.');
|
||||
}
|
||||
});
|
||||
//^=====--------------------------------------=====^//
|
||||
|
||||
module.exports = {
|
||||
app : app
|
||||
};
|
||||
5
server/config.js
Normal file
5
server/config.js
Normal file
@@ -0,0 +1,5 @@
|
||||
module.exports = require('nconf')
|
||||
.argv()
|
||||
.env({ lowerCase: true })
|
||||
.file('environment', { file: `config/${process.env.NODE_ENV}.json` })
|
||||
.file('defaults', { file: 'config/default.json' });
|
||||
37
server/db.js
Normal file
37
server/db.js
Normal file
@@ -0,0 +1,37 @@
|
||||
// The main purpose of this file is to provide an interface for database
|
||||
// connection. Even though the code is quite simple and basically a tiny
|
||||
// wrapper around mongoose package, it works as single point where
|
||||
// database setup/config is performed and the interface provided here can be
|
||||
// reused by both the main application and all tests which require database
|
||||
// connection.
|
||||
|
||||
const Mongoose = require('mongoose');
|
||||
|
||||
const getMongoDBURL = (config)=>{
|
||||
return config.get('mongodb_uri') ||
|
||||
config.get('mongolab_uri') ||
|
||||
'mongodb://localhost/homebrewery';
|
||||
};
|
||||
|
||||
const handleConnectionError = (error)=>{
|
||||
if(error) {
|
||||
console.error('Could not connect to a Mongo database: \n');
|
||||
console.error(error);
|
||||
console.error('\nIf you are running locally, make sure mongodb.exe is running and DB URL is configured properly');
|
||||
process.exit(1); // non-zero exit code to indicate an error
|
||||
}
|
||||
};
|
||||
|
||||
const disconnect = async ()=>{
|
||||
return await Mongoose.disconnect();
|
||||
};
|
||||
|
||||
const connect = async (config)=>{
|
||||
return await Mongoose.connect(getMongoDBURL(config),
|
||||
{ retryWrites: false }, handleConnectionError);
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
connect : connect,
|
||||
disconnect : disconnect
|
||||
};
|
||||
@@ -3,15 +3,24 @@ const _ = require('lodash');
|
||||
const { google } = require('googleapis');
|
||||
const { nanoid } = require('nanoid');
|
||||
const token = require('./token.js');
|
||||
const config = require('nconf')
|
||||
.argv()
|
||||
.env({ lowerCase: true }) // Load environment variables
|
||||
.file('environment', { file: `config/${process.env.NODE_ENV}.json` })
|
||||
.file('defaults', { file: 'config/default.json' });
|
||||
const config = require('./config.js');
|
||||
|
||||
//let oAuth2Client;
|
||||
const keys = typeof(config.get('service_account')) == 'string' ?
|
||||
JSON.parse(config.get('service_account')) :
|
||||
config.get('service_account');
|
||||
let serviceAuth;
|
||||
try {
|
||||
serviceAuth = google.auth.fromJSON(keys);
|
||||
serviceAuth.scopes = [
|
||||
'https://www.googleapis.com/auth/drive'
|
||||
];
|
||||
} catch (err) {
|
||||
console.warn(err);
|
||||
console.log('Please make sure that a Google Service Account is set up properly in your config files.');
|
||||
}
|
||||
google.options({ auth: serviceAuth || config.get('google_api_key') });
|
||||
|
||||
GoogleActions = {
|
||||
const GoogleActions = {
|
||||
|
||||
authCheck : (account, res)=>{
|
||||
if(!account || !account.googleId){ // If not signed into Google
|
||||
@@ -47,7 +56,7 @@ GoogleActions = {
|
||||
},
|
||||
|
||||
getGoogleFolder : async (auth)=>{
|
||||
const drive = google.drive({ version: 'v3', auth: auth });
|
||||
const drive = google.drive({ version: 'v3', auth });
|
||||
|
||||
fileMetadata = {
|
||||
'name' : 'Homebrewery',
|
||||
@@ -83,36 +92,27 @@ GoogleActions = {
|
||||
return folderId;
|
||||
},
|
||||
|
||||
listGoogleBrews : async (req, res)=>{
|
||||
|
||||
oAuth2Client = GoogleActions.authCheck(req.account, res);
|
||||
|
||||
//TODO: Change to service account to allow non-owners to view published files.
|
||||
// Requires a driveId parameter in the drive.files.list command
|
||||
// const keys = JSON.parse(config.get('service_account'));
|
||||
// const auth = google.auth.fromJSON(keys);
|
||||
// auth.scopes = ['https://www.googleapis.com/auth/drive'];
|
||||
|
||||
const drive = google.drive({ version: 'v3', auth: oAuth2Client });
|
||||
listGoogleBrews : async (auth)=>{
|
||||
const drive = google.drive({ version: 'v3', auth });
|
||||
|
||||
const obj = await drive.files.list({
|
||||
pageSize : 100,
|
||||
pageSize : 1000,
|
||||
fields : 'nextPageToken, files(id, name, description, createdTime, modifiedTime, properties)',
|
||||
q : 'mimeType != \'application/vnd.google-apps.folder\' and trashed = false'
|
||||
})
|
||||
.catch((err)=>{
|
||||
console.log(`Error Listing Google Brews`);
|
||||
console.log(`Error Listing Google Brews`);
|
||||
console.error(err);
|
||||
throw (err);
|
||||
//TODO: Should break out here, but continues on for some reason.
|
||||
});
|
||||
});
|
||||
|
||||
if(!obj.data.files.length) {
|
||||
console.log('No files found.');
|
||||
}
|
||||
console.log('No files found.');
|
||||
}
|
||||
|
||||
const brews = obj.data.files.map((file)=>{
|
||||
return {
|
||||
return {
|
||||
text : '',
|
||||
shareId : file.properties.shareId,
|
||||
editId : file.properties.editId,
|
||||
@@ -126,65 +126,47 @@ GoogleActions = {
|
||||
views : parseInt(file.properties.views),
|
||||
tags : '',
|
||||
published : file.properties.published ? file.properties.published == 'true' : false,
|
||||
authors : [req.account.username], //TODO: properly save and load authors to google drive
|
||||
systems : []
|
||||
systems : [],
|
||||
thumbnail : file.properties.thumbnail
|
||||
};
|
||||
});
|
||||
return brews;
|
||||
},
|
||||
|
||||
existsGoogleBrew : async (auth, id)=>{
|
||||
const drive = google.drive({ version: 'v3', auth: auth });
|
||||
updateGoogleBrew : async (brew)=>{
|
||||
const drive = google.drive({ version: 'v3' });
|
||||
|
||||
const result = await drive.files.get({ fileId: id })
|
||||
await drive.files.update({
|
||||
fileId : brew.googleId,
|
||||
resource : {
|
||||
name : `${brew.title}.txt`,
|
||||
description : `${brew.description}`,
|
||||
properties : {
|
||||
title : brew.title,
|
||||
shareId : brew.shareId || nanoid(12),
|
||||
editId : brew.editId || nanoid(12),
|
||||
pageCount : brew.pageCount,
|
||||
renderer : brew.renderer || 'legacy',
|
||||
isStubbed : true,
|
||||
thumbnail : brew.thumbnail
|
||||
}
|
||||
},
|
||||
media : {
|
||||
mimeType : 'text/plain',
|
||||
body : brew.text
|
||||
}
|
||||
})
|
||||
.catch((err)=>{
|
||||
console.log('error checking file exists...');
|
||||
console.log('Error saving to google');
|
||||
console.error(err);
|
||||
return false;
|
||||
throw (err);
|
||||
});
|
||||
|
||||
if(result){return true;}
|
||||
|
||||
return false;
|
||||
},
|
||||
|
||||
updateGoogleBrew : async (auth, brew)=>{
|
||||
const drive = google.drive({ version: 'v3', auth: auth });
|
||||
|
||||
if(await GoogleActions.existsGoogleBrew(auth, brew.googleId) == true) {
|
||||
await drive.files.update({
|
||||
fileId : brew.googleId,
|
||||
resource : {
|
||||
name : `${brew.title}.txt`,
|
||||
description : `${brew.description}`,
|
||||
properties : {
|
||||
title : brew.title,
|
||||
published : brew.published,
|
||||
version : brew.version,
|
||||
renderer : brew.renderer,
|
||||
tags : brew.tags,
|
||||
pageCount : brew.pageCount,
|
||||
systems : brew.systems.join()
|
||||
}
|
||||
},
|
||||
media : {
|
||||
mimeType : 'text/plain',
|
||||
body : brew.text
|
||||
}
|
||||
})
|
||||
.catch((err)=>{
|
||||
console.log('Error saving to google');
|
||||
console.error(err);
|
||||
throw (err);
|
||||
//return res.status(500).send('Error while saving');
|
||||
});
|
||||
}
|
||||
|
||||
return (brew);
|
||||
return true;
|
||||
},
|
||||
|
||||
newGoogleBrew : async (auth, brew)=>{
|
||||
const drive = google.drive({ version: 'v3', auth: auth });
|
||||
const drive = google.drive({ version: 'v3', auth });
|
||||
|
||||
const media = {
|
||||
mimeType : 'text/plain',
|
||||
@@ -194,16 +176,18 @@ GoogleActions = {
|
||||
const folderId = await GoogleActions.getGoogleFolder(auth);
|
||||
|
||||
const fileMetadata = {
|
||||
'name' : `${brew.title}.txt`,
|
||||
'description' : `${brew.description}`,
|
||||
'parents' : [folderId],
|
||||
'properties' : { //AppProperties is not accessible
|
||||
'shareId' : nanoid(12),
|
||||
'editId' : nanoid(12),
|
||||
'title' : brew.title,
|
||||
'views' : '0',
|
||||
'pageCount' : brew.pageCount,
|
||||
'renderer' : brew.renderer || 'legacy'
|
||||
name : `${brew.title}.txt`,
|
||||
description : `${brew.description}`,
|
||||
parents : [folderId],
|
||||
properties : { //AppProperties is not accessible
|
||||
shareId : brew.shareId || nanoid(12),
|
||||
editId : brew.editId || nanoid(12),
|
||||
title : brew.title,
|
||||
pageCount : brew.pageCount,
|
||||
renderer : brew.renderer || 'legacy',
|
||||
isStubbed : true,
|
||||
version : 1,
|
||||
thumbnail : brew.thumbnail || ''
|
||||
}
|
||||
};
|
||||
|
||||
@@ -230,31 +214,11 @@ GoogleActions = {
|
||||
console.error(err);
|
||||
});
|
||||
|
||||
const newHomebrew = {
|
||||
text : brew.text,
|
||||
shareId : fileMetadata.properties.shareId,
|
||||
editId : fileMetadata.properties.editId,
|
||||
createdAt : new Date(),
|
||||
updatedAt : new Date(),
|
||||
gDrive : true,
|
||||
googleId : obj.data.id,
|
||||
pageCount : fileMetadata.properties.pageCount,
|
||||
|
||||
title : brew.title,
|
||||
description : brew.description,
|
||||
tags : '',
|
||||
published : brew.published,
|
||||
renderer : brew.renderer,
|
||||
authors : [],
|
||||
systems : []
|
||||
};
|
||||
|
||||
return newHomebrew;
|
||||
return obj.data.id;
|
||||
},
|
||||
|
||||
readFileMetadata : async (auth, id, accessId, accessType)=>{
|
||||
|
||||
const drive = google.drive({ version: 'v3', auth: auth });
|
||||
getGoogleBrew : async (id, accessId, accessType)=>{
|
||||
const drive = google.drive({ version: 'v3' });
|
||||
|
||||
const obj = await drive.files.get({
|
||||
fileId : id,
|
||||
@@ -263,7 +227,6 @@ GoogleActions = {
|
||||
.catch((err)=>{
|
||||
console.log('Error loading from Google');
|
||||
throw (err);
|
||||
return;
|
||||
});
|
||||
|
||||
if(obj) {
|
||||
@@ -273,18 +236,7 @@ GoogleActions = {
|
||||
throw ('Share ID does not match');
|
||||
}
|
||||
|
||||
//Access file using service account. Using API key only causes "automated query" lockouts after a while.
|
||||
|
||||
const keys = typeof(config.get('service_account')) == 'string' ?
|
||||
JSON.parse(config.get('service_account')) :
|
||||
config.get('service_account');
|
||||
|
||||
const serviceAuth = google.auth.fromJSON(keys);
|
||||
serviceAuth.scopes = ['https://www.googleapis.com/auth/drive'];
|
||||
|
||||
const serviceDrive = google.drive({ version: 'v3', auth: serviceAuth });
|
||||
|
||||
const file = await serviceDrive.files.get({
|
||||
const file = await drive.files.get({
|
||||
fileId : id,
|
||||
fields : 'description, properties',
|
||||
alt : 'media'
|
||||
@@ -301,7 +253,7 @@ GoogleActions = {
|
||||
text : file.data,
|
||||
|
||||
description : obj.data.description,
|
||||
tags : obj.data.properties.tags ? obj.data.properties.tags : '',
|
||||
tags : obj.data.properties.tags ? obj.data.properties.tags : '',
|
||||
systems : obj.data.properties.systems ? obj.data.properties.systems.split(',') : [],
|
||||
authors : [],
|
||||
published : obj.data.properties.published ? obj.data.properties.published == 'true' : false,
|
||||
@@ -314,8 +266,8 @@ GoogleActions = {
|
||||
views : parseInt(obj.data.properties.views) || 0, //brews with no view parameter will return undefined
|
||||
version : parseInt(obj.data.properties.version) || 0,
|
||||
renderer : obj.data.properties.renderer ? obj.data.properties.renderer : 'legacy',
|
||||
thumbnail : obj.data.properties.thumbnail || '',
|
||||
|
||||
gDrive : true,
|
||||
googleId : id
|
||||
};
|
||||
|
||||
@@ -323,51 +275,34 @@ GoogleActions = {
|
||||
}
|
||||
},
|
||||
|
||||
deleteGoogleBrew : async (req, res, id)=>{
|
||||
|
||||
oAuth2Client = GoogleActions.authCheck(req.account, res);
|
||||
const drive = google.drive({ version: 'v3', auth: oAuth2Client });
|
||||
|
||||
const googleId = id.slice(0, -12);
|
||||
const accessId = id.slice(-12);
|
||||
deleteGoogleBrew : async (auth, id, accessId)=>{
|
||||
const drive = google.drive({ version: 'v3', auth });
|
||||
|
||||
const obj = await drive.files.get({
|
||||
fileId : googleId,
|
||||
fileId : id,
|
||||
fields : 'properties'
|
||||
})
|
||||
.catch((err)=>{
|
||||
console.log('Error loading from Google');
|
||||
console.error(err);
|
||||
return;
|
||||
});
|
||||
|
||||
if(obj && obj.data.properties.editId != accessId) {
|
||||
throw ('Not authorized to delete this Google brew');
|
||||
throw { status: 403, message: 'Not authorized to delete this Google brew' };
|
||||
}
|
||||
|
||||
await drive.files.update({
|
||||
fileId : googleId,
|
||||
fileId : id,
|
||||
resource : { trashed: true }
|
||||
})
|
||||
.catch((err)=>{
|
||||
console.log('Can\'t delete Google file');
|
||||
console.error(err);
|
||||
});
|
||||
|
||||
return res.status(200).send();
|
||||
},
|
||||
|
||||
increaseView : async (id, accessId, accessType, brew)=>{
|
||||
//service account because this is modifying another user's file properties
|
||||
//so we need extended scope
|
||||
const keys = typeof(config.get('service_account')) == 'string' ?
|
||||
JSON.parse(config.get('service_account')) :
|
||||
config.get('service_account');
|
||||
|
||||
const auth = google.auth.fromJSON(keys);
|
||||
auth.scopes = ['https://www.googleapis.com/auth/drive'];
|
||||
|
||||
const drive = google.drive({ version: 'v3', auth: auth });
|
||||
const drive = google.drive({ version: 'v3' });
|
||||
|
||||
await drive.files.update({
|
||||
fileId : brew.googleId,
|
||||
@@ -384,8 +319,6 @@ GoogleActions = {
|
||||
console.error(err);
|
||||
//return res.status(500).send('Error while saving');
|
||||
});
|
||||
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,9 +1,13 @@
|
||||
/* eslint-disable max-lines */
|
||||
const _ = require('lodash');
|
||||
const HomebrewModel = require('./homebrew.model.js').model;
|
||||
const router = require('express').Router();
|
||||
const zlib = require('zlib');
|
||||
const GoogleActions = require('./googleActions.js');
|
||||
const Markdown = require('../shared/naturalcrit/markdown.js');
|
||||
const yaml = require('js-yaml');
|
||||
const asyncHandler = require('express-async-handler');
|
||||
const { nanoid } = require('nanoid');
|
||||
|
||||
// const getTopBrews = (cb) => {
|
||||
// HomebrewModel.find().sort({ views: -1 }).limit(5).exec(function(err, brews) {
|
||||
@@ -11,178 +15,305 @@ const Markdown = require('../shared/naturalcrit/markdown.js');
|
||||
// });
|
||||
// };
|
||||
|
||||
const getBrew = (accessType)=>{
|
||||
// Create middleware with the accessType passed in as part of the scope
|
||||
return async (req, res, next)=>{
|
||||
// Set the id and initial potential google id, where the google id is present on the existing brew.
|
||||
let id = req.params.id, googleId = req.body?.googleId;
|
||||
|
||||
// If the id is longer than 12, then it's a google id + the edit id. This splits the longer id up.
|
||||
if(id.length > 12) {
|
||||
googleId = id.slice(0, -12);
|
||||
id = id.slice(-12);
|
||||
}
|
||||
// Try to find the document in the Homebrewery database -- if it doesn't exist, that's fine.
|
||||
let stub = await HomebrewModel.get(accessType === 'edit' ? { editId: id } : { shareId: id })
|
||||
.catch((err)=>{
|
||||
if(googleId) {
|
||||
console.warn(`Unable to find document stub for ${accessType}Id ${id}`);
|
||||
} else {
|
||||
console.warn(err);
|
||||
}
|
||||
});
|
||||
stub = stub?.toObject();
|
||||
|
||||
// If there is a google id, try to find the google brew
|
||||
if(googleId || stub?.googleId) {
|
||||
let googleError;
|
||||
const googleBrew = await GoogleActions.getGoogleBrew(googleId || stub?.googleId, id, accessType)
|
||||
.catch((err)=>{
|
||||
console.warn(err);
|
||||
googleError = err;
|
||||
});
|
||||
// If we can't find the google brew and there is a google id for the brew, throw an error.
|
||||
if(!googleBrew) throw googleError;
|
||||
// Combine the Homebrewery stub with the google brew, or if the stub doesn't exist just use the google brew
|
||||
stub = stub ? _.assign({ ...excludeStubProps(stub), stubbed: true }, excludeGoogleProps(googleBrew)) : googleBrew;
|
||||
}
|
||||
|
||||
// If after all of that we still don't have a brew, throw an exception
|
||||
if(!stub) {
|
||||
throw 'Brew not found in Homebrewery database or Google Drive';
|
||||
}
|
||||
|
||||
req.brew = stub;
|
||||
|
||||
next();
|
||||
};
|
||||
};
|
||||
|
||||
const mergeBrewText = (brew)=>{
|
||||
let text = brew.text;
|
||||
if(brew.style !== undefined) {
|
||||
text = `\`\`\`css\n` +
|
||||
`${brew.style || ''}\n` +
|
||||
`\`\`\`\n\n` +
|
||||
`${text}`;
|
||||
}
|
||||
const metadata = _.pick(brew, ['title', 'description', 'tags', 'systems', 'renderer']);
|
||||
text = `\`\`\`metadata\n` +
|
||||
`${yaml.dump(metadata)}\n` +
|
||||
`\`\`\`\n\n` +
|
||||
`${text}`;
|
||||
return text;
|
||||
};
|
||||
|
||||
const MAX_TITLE_LENGTH = 100;
|
||||
|
||||
const getGoodBrewTitle = (text)=>{
|
||||
const tokens = Markdown.marked.lexer(text);
|
||||
return (tokens.find((token)=>token.type == 'heading' || token.type == 'paragraph')?.text || 'No Title')
|
||||
return (tokens.find((token)=>token.type === 'heading' || token.type === 'paragraph')?.text || 'No Title')
|
||||
.slice(0, MAX_TITLE_LENGTH);
|
||||
};
|
||||
|
||||
const excludePropsFromUpdate = (brew)=>{
|
||||
// Remove undesired properties
|
||||
const propsToExclude = ['views', 'lastViewed'];
|
||||
const modified = _.clone(brew);
|
||||
const propsToExclude = ['_id', 'views', 'lastViewed', 'editId', 'shareId', 'googleId'];
|
||||
for (const prop of propsToExclude) {
|
||||
delete brew[prop];
|
||||
};
|
||||
delete modified[prop];
|
||||
}
|
||||
return modified;
|
||||
};
|
||||
|
||||
const excludeGoogleProps = (brew)=>{
|
||||
const modified = _.clone(brew);
|
||||
const propsToExclude = ['tags', 'systems', 'published', 'authors', 'owner', 'views'];
|
||||
for (const prop of propsToExclude) {
|
||||
delete modified[prop];
|
||||
}
|
||||
return modified;
|
||||
};
|
||||
|
||||
const excludeStubProps = (brew)=>{
|
||||
const propsToExclude = ['text', 'textBin', 'renderer', 'pageCount', 'version'];
|
||||
for (const prop of propsToExclude) {
|
||||
brew[prop] = undefined;
|
||||
}
|
||||
return brew;
|
||||
};
|
||||
|
||||
const mergeBrewText = (text, style)=>{
|
||||
if(typeof style !== 'undefined') {
|
||||
text = `\`\`\`css\n` +
|
||||
`${style}\n` +
|
||||
`\`\`\`\n\n` +
|
||||
`${text}`;
|
||||
}
|
||||
return text;
|
||||
};
|
||||
|
||||
const newBrew = (req, res)=>{
|
||||
const brew = req.body;
|
||||
|
||||
const beforeNewSave = (account, brew)=>{
|
||||
if(!brew.title) {
|
||||
brew.title = getGoodBrewTitle(brew.text);
|
||||
}
|
||||
|
||||
brew.authors = (req.account) ? [req.account.username] : [];
|
||||
brew.text = mergeBrewText(brew.text, brew.style);
|
||||
brew.authors = (account) ? [account.username] : [];
|
||||
brew.text = mergeBrewText(brew);
|
||||
};
|
||||
|
||||
const newGoogleBrew = async (account, brew, res)=>{
|
||||
const oAuth2Client = GoogleActions.authCheck(account, res);
|
||||
|
||||
const newBrew = excludeGoogleProps(brew);
|
||||
|
||||
return await GoogleActions.newGoogleBrew(oAuth2Client, newBrew);
|
||||
};
|
||||
|
||||
const newBrew = async (req, res)=>{
|
||||
const brew = req.body;
|
||||
const { saveToGoogle } = req.query;
|
||||
|
||||
delete brew.editId;
|
||||
delete brew.shareId;
|
||||
delete brew.googleId;
|
||||
|
||||
beforeNewSave(req.account, brew);
|
||||
|
||||
const newHomebrew = new HomebrewModel(brew);
|
||||
// Compress brew text to binary before saving
|
||||
newHomebrew.textBin = zlib.deflateRawSync(newHomebrew.text);
|
||||
// Delete the non-binary text field since it's not needed anymore
|
||||
newHomebrew.text = undefined;
|
||||
newHomebrew.editId = nanoid(12);
|
||||
newHomebrew.shareId = nanoid(12);
|
||||
|
||||
newHomebrew.save((err, obj)=>{
|
||||
if(err) {
|
||||
let googleId, saved;
|
||||
if(saveToGoogle) {
|
||||
googleId = await newGoogleBrew(req.account, newHomebrew, res)
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
res.status(err?.status || err?.response?.status || 500).send(err?.message || err);
|
||||
});
|
||||
if(!googleId) return;
|
||||
excludeStubProps(newHomebrew);
|
||||
newHomebrew.googleId = googleId;
|
||||
} else {
|
||||
// Compress brew text to binary before saving
|
||||
newHomebrew.textBin = zlib.deflateRawSync(newHomebrew.text);
|
||||
// Delete the non-binary text field since it's not needed anymore
|
||||
newHomebrew.text = undefined;
|
||||
}
|
||||
|
||||
saved = await newHomebrew.save()
|
||||
.catch((err)=>{
|
||||
console.error(err, err.toString(), err.stack);
|
||||
return res.status(500).send(`Error while creating new brew, ${err.toString()}`);
|
||||
}
|
||||
throw `Error while creating new brew, ${err.toString()}`;
|
||||
});
|
||||
if(!saved) return;
|
||||
saved = saved.toObject();
|
||||
|
||||
obj = obj.toObject();
|
||||
obj.gDrive = false;
|
||||
return res.status(200).send(obj);
|
||||
});
|
||||
res.status(200).send(saved);
|
||||
};
|
||||
|
||||
const updateBrew = (req, res)=>{
|
||||
HomebrewModel.get({ editId: req.params.id })
|
||||
.then((brew)=>{
|
||||
const updateBrew = excludePropsFromUpdate(req.body);
|
||||
brew = _.merge(brew, updateBrew);
|
||||
brew.text = mergeBrewText(brew.text, brew.style);
|
||||
brew.tags = updateBrew.tags;
|
||||
const updateBrew = async (req, res)=>{
|
||||
// Initialize brew from request and body, destructure query params, set a constant for the google id, and set the initial value for the after-save method
|
||||
let brew = _.assign(req.brew, excludePropsFromUpdate(req.body));
|
||||
const { saveToGoogle, removeFromGoogle } = req.query;
|
||||
const googleId = brew.googleId;
|
||||
let afterSave = async ()=>true;
|
||||
|
||||
// Compress brew text to binary before saving
|
||||
brew.textBin = zlib.deflateRawSync(brew.text);
|
||||
// Delete the non-binary text field since it's not needed anymore
|
||||
brew.text = undefined;
|
||||
brew.updatedAt = new Date();
|
||||
brew.text = mergeBrewText(brew);
|
||||
brew.tags = updateBrew.tags;
|
||||
|
||||
if(req.account) {
|
||||
brew.authors = _.uniq(_.concat(brew.authors, req.account.username));
|
||||
}
|
||||
if(brew.googleId && removeFromGoogle) {
|
||||
// If the google id exists and we're removing it from google, set afterSave to delete the google brew and mark the brew's google id as undefined
|
||||
afterSave = async ()=>{
|
||||
return await deleteGoogleBrew(req.account, googleId, brew.editId, res)
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
res.status(err?.status || err?.response?.status || 500).send(err.message || err);
|
||||
});
|
||||
};
|
||||
|
||||
brew.markModified('authors');
|
||||
brew.markModified('systems');
|
||||
|
||||
brew.save((err, obj)=>{
|
||||
if(err) throw err;
|
||||
return res.status(200).send(obj);
|
||||
brew.googleId = undefined;
|
||||
} else if(!brew.googleId && saveToGoogle) {
|
||||
// If we don't have a google id and the user wants to save to google, create the google brew and set the google id on the brew
|
||||
brew.googleId = await newGoogleBrew(req.account, excludeGoogleProps(brew), res)
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
res.status(err.status || err.response.status).send(err.message || err);
|
||||
});
|
||||
})
|
||||
if(!brew.googleId) return;
|
||||
} else if(brew.googleId) {
|
||||
// If the google id exists and no other actions are being performed, update the google brew
|
||||
const updated = await GoogleActions.updateGoogleBrew(excludeGoogleProps(brew))
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
res.status(err?.response?.status || 500).send(err);
|
||||
});
|
||||
if(!updated) return;
|
||||
}
|
||||
|
||||
if(brew.googleId) {
|
||||
// If the google id exists after all those actions, exclude the props that are stored in google and aren't needed for rendering the brew items
|
||||
excludeStubProps(brew);
|
||||
} else {
|
||||
// Compress brew text to binary before saving
|
||||
brew.textBin = zlib.deflateRawSync(brew.text);
|
||||
// Delete the non-binary text field since it's not needed anymore
|
||||
brew.text = undefined;
|
||||
}
|
||||
brew.updatedAt = new Date();
|
||||
|
||||
if(req.account) {
|
||||
brew.authors = _.uniq(_.concat(brew.authors, req.account.username));
|
||||
}
|
||||
|
||||
// Fetch the brew from the database again (if it existed there to begin with), and assign the existing brew to it
|
||||
brew = _.assign(await HomebrewModel.findOne({ _id: brew._id }), brew);
|
||||
|
||||
if(!brew.markModified) {
|
||||
// If it wasn't in the database, create a new db brew
|
||||
brew = new HomebrewModel(brew);
|
||||
}
|
||||
|
||||
brew.markModified('authors');
|
||||
brew.markModified('systems');
|
||||
|
||||
// Save the database brew
|
||||
const saved = await brew.save()
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
return res.status(500).send('Error while saving');
|
||||
res.status(err.status || 500).send(err.message || 'Unable to save brew to Homebrewery database');
|
||||
});
|
||||
if(!saved) return;
|
||||
// Call and wait for afterSave to complete
|
||||
const after = await afterSave();
|
||||
if(!after) return;
|
||||
|
||||
res.status(200).send(saved);
|
||||
};
|
||||
|
||||
const deleteBrew = (req, res)=>{
|
||||
HomebrewModel.find({ editId: req.params.id }, (err, objs)=>{
|
||||
if(!objs.length || err) {
|
||||
return res.status(404).send('Can not find homebrew with that id');
|
||||
}
|
||||
const deleteGoogleBrew = async (account, id, editId, res)=>{
|
||||
const auth = await GoogleActions.authCheck(account, res);
|
||||
await GoogleActions.deleteGoogleBrew(auth, id, editId);
|
||||
return true;
|
||||
};
|
||||
|
||||
const brew = objs[0];
|
||||
const deleteBrew = async (req, res)=>{
|
||||
let brew = req.brew;
|
||||
const { googleId, editId } = brew;
|
||||
const account = req.account;
|
||||
const isOwner = account && (brew.authors.length === 0 || brew.authors[0] === account.username);
|
||||
// If the user is the owner and the file is saved to google, mark the google brew for deletion
|
||||
const shouldDeleteGoogleBrew = googleId && isOwner;
|
||||
|
||||
if(req.account) {
|
||||
if(brew._id) {
|
||||
brew = _.assign(await HomebrewModel.findOne({ _id: brew._id }), brew);
|
||||
if(account) {
|
||||
// Remove current user as author
|
||||
brew.authors = _.pull(brew.authors, req.account.username);
|
||||
brew.authors = _.pull(brew.authors, account.username);
|
||||
brew.markModified('authors');
|
||||
}
|
||||
|
||||
if(brew.authors.length === 0) {
|
||||
// Delete brew if there are no authors left
|
||||
brew.remove((err)=>{
|
||||
if(err) return res.status(500).send('Error while removing');
|
||||
return res.status(200).send();
|
||||
});
|
||||
await brew.remove()
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
throw { status: 500, message: 'Error while removing' };
|
||||
});
|
||||
} else {
|
||||
if(shouldDeleteGoogleBrew) {
|
||||
// When there are still authors remaining, we delete the google brew but store the full brew in the Homebrewery database
|
||||
brew.googleId = undefined;
|
||||
brew.textBin = zlib.deflateRawSync(brew.text);
|
||||
brew.text = undefined;
|
||||
}
|
||||
|
||||
// Otherwise, save the brew with updated author list
|
||||
brew.save((err, savedBrew)=>{
|
||||
if(err) throw err;
|
||||
return res.status(200).send(savedBrew);
|
||||
});
|
||||
await brew.save()
|
||||
.catch((err)=>{
|
||||
throw { status: 500, message: err };
|
||||
});
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const newGoogleBrew = async (req, res, next)=>{
|
||||
let oAuth2Client;
|
||||
|
||||
try { oAuth2Client = GoogleActions.authCheck(req.account, res); } catch (err) { return res.status(err.status).send(err.message); }
|
||||
|
||||
const brew = req.body;
|
||||
|
||||
if(!brew.title) {
|
||||
brew.title = getGoodBrewTitle(brew.text);
|
||||
}
|
||||
if(shouldDeleteGoogleBrew) {
|
||||
const deleted = await deleteGoogleBrew(account, googleId, editId, res)
|
||||
.catch((err)=>{
|
||||
console.error(err);
|
||||
res.status(500).send(err);
|
||||
});
|
||||
if(!deleted) return;
|
||||
}
|
||||
|
||||
brew.authors = (req.account) ? [req.account.username] : [];
|
||||
brew.text = mergeBrewText(brew.text, brew.style);
|
||||
|
||||
delete brew.editId;
|
||||
delete brew.shareId;
|
||||
delete brew.googleId;
|
||||
|
||||
req.body = brew;
|
||||
|
||||
try {
|
||||
const newBrew = await GoogleActions.newGoogleBrew(oAuth2Client, brew);
|
||||
return res.status(200).send(newBrew);
|
||||
} catch (err) {
|
||||
return res.status(err.response.status).send(err);
|
||||
}
|
||||
res.status(204).send();
|
||||
};
|
||||
|
||||
const updateGoogleBrew = async (req, res, next)=>{
|
||||
let oAuth2Client;
|
||||
router.post('/api', asyncHandler(newBrew));
|
||||
router.put('/api/:id', asyncHandler(getBrew('edit')), asyncHandler(updateBrew));
|
||||
router.put('/api/update/:id', asyncHandler(getBrew('edit')), asyncHandler(updateBrew));
|
||||
router.delete('/api/:id', asyncHandler(getBrew('edit')), asyncHandler(deleteBrew));
|
||||
router.get('/api/remove/:id', asyncHandler(getBrew('edit')), asyncHandler(deleteBrew));
|
||||
|
||||
try { oAuth2Client = GoogleActions.authCheck(req.account, res); } catch (err) { return res.status(err.status).send(err.message); }
|
||||
|
||||
const brew = excludePropsFromUpdate(req.body);
|
||||
brew.text = mergeBrewText(brew.text, brew.style);
|
||||
|
||||
try {
|
||||
const updatedBrew = await GoogleActions.updateGoogleBrew(oAuth2Client, brew);
|
||||
return res.status(200).send(updatedBrew);
|
||||
} catch (err) {
|
||||
return res.status(err.response.status).send(err);
|
||||
}
|
||||
module.exports = {
|
||||
homebrewApi : router,
|
||||
getBrew
|
||||
};
|
||||
|
||||
router.post('/api', newBrew);
|
||||
router.post('/api/newGoogle/', newGoogleBrew);
|
||||
router.put('/api/:id', updateBrew);
|
||||
router.put('/api/update/:id', updateBrew);
|
||||
router.put('/api/updateGoogle/:id', updateGoogleBrew);
|
||||
router.delete('/api/:id', deleteBrew);
|
||||
router.get('/api/remove/:id', deleteBrew);
|
||||
router.get('/api/removeGoogle/:id', (req, res)=>{GoogleActions.deleteGoogleBrew(req, res, req.params.id);});
|
||||
|
||||
module.exports = router;
|
||||
|
||||
@@ -6,6 +6,7 @@ const zlib = require('zlib');
|
||||
const HomebrewSchema = mongoose.Schema({
|
||||
shareId : { type: String, default: ()=>{return nanoid(12);}, index: { unique: true } },
|
||||
editId : { type: String, default: ()=>{return nanoid(12);}, index: { unique: true } },
|
||||
googleId : { type: String },
|
||||
title : { type: String, default: '' },
|
||||
text : { type: String, default: '' },
|
||||
textBin : { type: Buffer },
|
||||
@@ -17,6 +18,7 @@ const HomebrewSchema = mongoose.Schema({
|
||||
renderer : { type: String, default: '' },
|
||||
authors : [String],
|
||||
published : { type: Boolean, default: false },
|
||||
thumbnail : { type: String, default: '' },
|
||||
|
||||
createdAt : { type: Date, default: Date.now },
|
||||
updatedAt : { type: Date, default: Date.now },
|
||||
@@ -36,9 +38,9 @@ HomebrewSchema.statics.increaseView = async function(query) {
|
||||
return brew;
|
||||
};
|
||||
|
||||
HomebrewSchema.statics.get = function(query){
|
||||
HomebrewSchema.statics.get = function(query, fields=null){
|
||||
return new Promise((resolve, reject)=>{
|
||||
Homebrew.find(query, (err, brews)=>{
|
||||
Homebrew.find(query, fields, null, (err, brews)=>{
|
||||
if(err || !brews.length) return reject('Can not find brew');
|
||||
if(!_.isNil(brews[0].textBin)) { // Uncompress zipped text field
|
||||
unzipped = zlib.inflateRawSync(brews[0].textBin);
|
||||
@@ -51,13 +53,13 @@ HomebrewSchema.statics.get = function(query){
|
||||
});
|
||||
};
|
||||
|
||||
HomebrewSchema.statics.getByUser = function(username, allowAccess=false){
|
||||
HomebrewSchema.statics.getByUser = function(username, allowAccess=false, fields=null){
|
||||
return new Promise((resolve, reject)=>{
|
||||
const query = { authors: username, published: true };
|
||||
if(allowAccess){
|
||||
delete query.published;
|
||||
}
|
||||
Homebrew.find(query).lean().exec((err, brews)=>{ //lean() converts results to JSObjects
|
||||
Homebrew.find(query, fields).lean().exec((err, brews)=>{ //lean() converts results to JSObjects
|
||||
if(err) return reject('Can not find brew');
|
||||
return resolve(brews);
|
||||
});
|
||||
|
||||
@@ -1,11 +1,7 @@
|
||||
const jwt = require('jwt-simple');
|
||||
|
||||
// Load configuration values
|
||||
const config = require('nconf')
|
||||
.argv()
|
||||
.env({ lowerCase: true }) // Load environment variables
|
||||
.file('environment', { file: `config/${process.env.NODE_ENV}.json` })
|
||||
.file('defaults', { file: 'config/default.json' });
|
||||
const config = require('./config.js');
|
||||
|
||||
// Generate an Access Token for the given User ID
|
||||
const generateAccessToken = (account)=>{
|
||||
|
||||
@@ -7,6 +7,7 @@ const cx = require('classnames');
|
||||
const DISMISS_KEY = 'dismiss_render_warning';
|
||||
|
||||
const RenderWarnings = createClass({
|
||||
displayName : 'RenderWarnings',
|
||||
getInitialState : function() {
|
||||
return {
|
||||
warnings : {}
|
||||
|
||||
48
shared/naturalcrit/codeEditor/close-tag.js
Normal file
48
shared/naturalcrit/codeEditor/close-tag.js
Normal file
@@ -0,0 +1,48 @@
|
||||
const autoCloseCurlyBraces = function(CodeMirror, cm, typingClosingBrace) {
|
||||
const ranges = cm.listSelections(), replacements = [];
|
||||
for (let i = 0; i < ranges.length; i++) {
|
||||
if(!ranges[i].empty()) return CodeMirror.Pass;
|
||||
const pos = ranges[i].head, line = cm.getLine(pos.line), tok = cm.getTokenAt(pos);
|
||||
if(!typingClosingBrace && (tok.type == 'string' || tok.string.charAt(0) != '{' || tok.start != pos.ch - 1))
|
||||
return CodeMirror.Pass;
|
||||
else if(typingClosingBrace) {
|
||||
let hasUnclosedBraces = false, index = -1;
|
||||
do {
|
||||
index = line.indexOf('{{', index + 1);
|
||||
if(index !== -1 && line.indexOf('}}', index + 1) === -1) {
|
||||
hasUnclosedBraces = true;
|
||||
break;
|
||||
}
|
||||
} while (index !== -1);
|
||||
if(!hasUnclosedBraces) return CodeMirror.Pass;
|
||||
}
|
||||
|
||||
replacements[i] = typingClosingBrace ? {
|
||||
text : '}}',
|
||||
newPos : CodeMirror.Pos(pos.line, pos.ch + 2)
|
||||
} : {
|
||||
text : '{}}',
|
||||
newPos : CodeMirror.Pos(pos.line, pos.ch + 1)
|
||||
};
|
||||
}
|
||||
|
||||
for (let i = ranges.length - 1; i >= 0; i--) {
|
||||
const info = replacements[i];
|
||||
cm.replaceRange(info.text, ranges[i].head, ranges[i].anchor, '+insert');
|
||||
const sel = cm.listSelections().slice(0);
|
||||
sel[i] = {
|
||||
head : info.newPos,
|
||||
anchor : info.newPos
|
||||
};
|
||||
cm.setSelections(sel);
|
||||
}
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
autoCloseCurlyBraces : function(CodeMirror, codeMirror) {
|
||||
const map = { name: 'autoCloseCurlyBraces' };
|
||||
map[`'{'`] = function(cm) { return autoCloseCurlyBraces(CodeMirror, cm); };
|
||||
map[`'}'`] = function(cm) { return autoCloseCurlyBraces(CodeMirror, cm, true); };
|
||||
codeMirror.addKeyMap(map);
|
||||
}
|
||||
};
|
||||
@@ -1,9 +1,10 @@
|
||||
/* eslint-disable max-lines */
|
||||
require('./codeEditor.less');
|
||||
const React = require('react');
|
||||
const createClass = require('create-react-class');
|
||||
const _ = require('lodash');
|
||||
const cx = require('classnames');
|
||||
|
||||
const closeTag = require('./close-tag');
|
||||
|
||||
let CodeMirror;
|
||||
if(typeof navigator !== 'undefined'){
|
||||
@@ -15,20 +16,40 @@ if(typeof navigator !== 'undefined'){
|
||||
require('codemirror/mode/javascript/javascript.js');
|
||||
|
||||
//Addons
|
||||
//Code folding
|
||||
require('codemirror/addon/fold/foldcode.js');
|
||||
require('codemirror/addon/fold/foldgutter.js');
|
||||
//Search and replace
|
||||
require('codemirror/addon/search/search.js');
|
||||
require('codemirror/addon/search/searchcursor.js');
|
||||
require('codemirror/addon/search/jump-to-line.js');
|
||||
require('codemirror/addon/search/match-highlighter.js');
|
||||
require('codemirror/addon/search/matchesonscrollbar.js');
|
||||
require('codemirror/addon/dialog/dialog.js');
|
||||
//Trailing space highlighting
|
||||
// require('codemirror/addon/edit/trailingspace.js');
|
||||
//Active line highlighting
|
||||
// require('codemirror/addon/selection/active-line.js');
|
||||
//Scroll past last line
|
||||
require('codemirror/addon/scroll/scrollpastend.js');
|
||||
//Auto-closing
|
||||
//XML code folding is a requirement of the auto-closing tag feature and is not enabled
|
||||
require('codemirror/addon/fold/xml-fold.js');
|
||||
require('codemirror/addon/edit/closetag.js');
|
||||
|
||||
const foldCode = require('./fold-code');
|
||||
foldCode.registerHomebreweryHelper(CodeMirror);
|
||||
}
|
||||
|
||||
const CodeEditor = createClass({
|
||||
displayName : 'CodeEditor',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
language : '',
|
||||
value : '',
|
||||
wrap : true,
|
||||
onChange : ()=>{}
|
||||
language : '',
|
||||
value : '',
|
||||
wrap : true,
|
||||
onChange : ()=>{},
|
||||
enableFolding : true
|
||||
};
|
||||
},
|
||||
|
||||
@@ -64,6 +85,12 @@ const CodeEditor = createClass({
|
||||
} else if(this.codeMirror?.getValue() != this.props.value) { //update editor contents if brew.text is changed from outside
|
||||
this.codeMirror.setValue(this.props.value);
|
||||
}
|
||||
|
||||
if(this.props.enableFolding) {
|
||||
this.codeMirror.setOption('foldOptions', this.foldOptions(this.codeMirror));
|
||||
} else {
|
||||
this.codeMirror.setOption('foldOptions', false);
|
||||
}
|
||||
},
|
||||
|
||||
buildEditor : function() {
|
||||
@@ -73,50 +100,85 @@ const CodeEditor = createClass({
|
||||
indentWithTabs : true,
|
||||
tabSize : 2,
|
||||
historyEventDelay : 250,
|
||||
scrollPastEnd : true,
|
||||
extraKeys : {
|
||||
'Ctrl-B' : this.makeBold,
|
||||
'Cmd-B' : this.makeBold,
|
||||
'Ctrl-I' : this.makeItalic,
|
||||
'Cmd-I' : this.makeItalic,
|
||||
'Ctrl-M' : this.makeSpan,
|
||||
'Cmd-M' : this.makeSpan,
|
||||
'Ctrl-/' : this.makeComment,
|
||||
'Cmd-/' : this.makeComment,
|
||||
'Ctrl-[' : this.foldAllCode,
|
||||
'Cmd-[' : this.foldAllCode,
|
||||
'Ctrl-]' : this.unfoldAllCode,
|
||||
'Cmd-]' : this.unfoldAllCode
|
||||
'Ctrl-B' : this.makeBold,
|
||||
'Cmd-B' : this.makeBold,
|
||||
'Ctrl-I' : this.makeItalic,
|
||||
'Cmd-I' : this.makeItalic,
|
||||
'Ctrl-U' : this.makeUnderline,
|
||||
'Cmd-U' : this.makeUnderline,
|
||||
'Ctrl-.' : this.makeNbsp,
|
||||
'Cmd-.' : this.makeNbsp,
|
||||
'Shift-Ctrl-.' : this.makeSpace,
|
||||
'Shift-Cmd-.' : this.makeSpace,
|
||||
'Shift-Ctrl-,' : this.removeSpace,
|
||||
'Shift-Cmd-,' : this.removeSpace,
|
||||
'Ctrl-M' : this.makeSpan,
|
||||
'Cmd-M' : this.makeSpan,
|
||||
'Shift-Ctrl-M' : this.makeDiv,
|
||||
'Shift-Cmd-M' : this.makeDiv,
|
||||
'Ctrl-/' : this.makeComment,
|
||||
'Cmd-/' : this.makeComment,
|
||||
'Ctrl-K' : this.makeLink,
|
||||
'Cmd-K' : this.makeLink,
|
||||
'Ctrl-L' : ()=>this.makeList('UL'),
|
||||
'Cmd-L' : ()=>this.makeList('UL'),
|
||||
'Shift-Ctrl-L' : ()=>this.makeList('OL'),
|
||||
'Shift-Cmd-L' : ()=>this.makeList('OL'),
|
||||
'Shift-Ctrl-1' : ()=>this.makeHeader(1),
|
||||
'Shift-Ctrl-2' : ()=>this.makeHeader(2),
|
||||
'Shift-Ctrl-3' : ()=>this.makeHeader(3),
|
||||
'Shift-Ctrl-4' : ()=>this.makeHeader(4),
|
||||
'Shift-Ctrl-5' : ()=>this.makeHeader(5),
|
||||
'Shift-Ctrl-6' : ()=>this.makeHeader(6),
|
||||
'Shift-Cmd-1' : ()=>this.makeHeader(1),
|
||||
'Shift-Cmd-2' : ()=>this.makeHeader(2),
|
||||
'Shift-Cmd-3' : ()=>this.makeHeader(3),
|
||||
'Shift-Cmd-4' : ()=>this.makeHeader(4),
|
||||
'Shift-Cmd-5' : ()=>this.makeHeader(5),
|
||||
'Shift-Cmd-6' : ()=>this.makeHeader(6),
|
||||
'Shift-Ctrl-Enter' : this.newColumn,
|
||||
'Shift-Cmd-Enter' : this.newColumn,
|
||||
'Ctrl-Enter' : this.newPage,
|
||||
'Cmd-Enter' : this.newPage,
|
||||
'Ctrl-F' : 'findPersistent',
|
||||
'Cmd-F' : 'findPersistent',
|
||||
'Shift-Enter' : 'findPersistentPrevious',
|
||||
'Ctrl-[' : this.foldAllCode,
|
||||
'Cmd-[' : this.foldAllCode,
|
||||
'Ctrl-]' : this.unfoldAllCode,
|
||||
'Cmd-]' : this.unfoldAllCode
|
||||
},
|
||||
foldGutter : true,
|
||||
foldOptions : {
|
||||
scanUp : true,
|
||||
rangeFinder : CodeMirror.fold.homebrewery,
|
||||
widget : (from, to)=>{
|
||||
let text = '';
|
||||
let currentLine = from.line;
|
||||
const maxLength = 50;
|
||||
while (currentLine <= to.line && text.length <= maxLength) {
|
||||
text += this.codeMirror.getLine(currentLine);
|
||||
if(currentLine < to.line)
|
||||
text += ' ';
|
||||
currentLine += 1;
|
||||
}
|
||||
|
||||
text = text.trim();
|
||||
if(text.length > maxLength)
|
||||
text = `${text.substr(0, maxLength)}...`;
|
||||
|
||||
return `\u21A4 ${text} \u21A6`;
|
||||
}
|
||||
},
|
||||
gutters : ['CodeMirror-linenumbers', 'CodeMirror-foldgutter']
|
||||
foldGutter : true,
|
||||
foldOptions : this.foldOptions(this.codeMirror),
|
||||
gutters : ['CodeMirror-linenumbers', 'CodeMirror-foldgutter'],
|
||||
autoCloseTags : true,
|
||||
styleActiveLine : true,
|
||||
showTrailingSpace : false,
|
||||
// specialChars : / /,
|
||||
// specialCharPlaceholder : function(char) {
|
||||
// const el = document.createElement('span');
|
||||
// el.className = 'cm-space';
|
||||
// el.innerHTML = ' ';
|
||||
// return el;
|
||||
// }
|
||||
});
|
||||
closeTag.autoCloseCurlyBraces(CodeMirror, this.codeMirror);
|
||||
|
||||
// Note: codeMirror passes a copy of itself in this callback. cm === this.codeMirror. Either one works.
|
||||
this.codeMirror.on('change', (cm)=>{this.props.onChange(cm.getValue());});
|
||||
this.updateSize();
|
||||
},
|
||||
|
||||
makeHeader : function (number) {
|
||||
const selection = this.codeMirror.getSelection();
|
||||
const header = Array(number).fill('#').join('');
|
||||
this.codeMirror.replaceSelection(`${header} ${selection}`, 'around');
|
||||
const cursor = this.codeMirror.getCursor();
|
||||
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch + selection.length + number + 1 });
|
||||
},
|
||||
|
||||
makeBold : function() {
|
||||
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 2) === '**' && selection.slice(-2) === '**';
|
||||
this.codeMirror.replaceSelection(t ? selection.slice(2, -2) : `**${selection}**`, 'around');
|
||||
@@ -127,14 +189,55 @@ const CodeEditor = createClass({
|
||||
},
|
||||
|
||||
makeItalic : function() {
|
||||
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 1) === '_' && selection.slice(-1) === '_';
|
||||
this.codeMirror.replaceSelection(t ? selection.slice(1, -1) : `_${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 });
|
||||
}
|
||||
},
|
||||
|
||||
makeNbsp : function() {
|
||||
this.codeMirror.replaceSelection(' ', 'end');
|
||||
},
|
||||
|
||||
makeSpace : function() {
|
||||
const selection = this.codeMirror.getSelection();
|
||||
const t = selection.slice(0, 8) === '{{width:' && selection.slice(0 -4) === '% }}';
|
||||
if(t){
|
||||
const percent = parseInt(selection.slice(8, -4)) + 10;
|
||||
this.codeMirror.replaceSelection(percent < 90 ? `{{width:${percent}% }}` : '{{width:100% }}', 'around');
|
||||
} else {
|
||||
this.codeMirror.replaceSelection(`{{width:10% }}`, 'around');
|
||||
}
|
||||
},
|
||||
|
||||
removeSpace : function() {
|
||||
const selection = this.codeMirror.getSelection();
|
||||
const t = selection.slice(0, 8) === '{{width:' && selection.slice(0 -4) === '% }}';
|
||||
if(t){
|
||||
const percent = parseInt(selection.slice(8, -4)) - 10;
|
||||
this.codeMirror.replaceSelection(percent > 10 ? `{{width:${percent}% }}` : '', 'around');
|
||||
}
|
||||
},
|
||||
|
||||
newColumn : function() {
|
||||
this.codeMirror.replaceSelection('\n\\column\n\n', 'end');
|
||||
},
|
||||
|
||||
newPage : function() {
|
||||
this.codeMirror.replaceSelection('\n\\page\n\n', 'end');
|
||||
},
|
||||
|
||||
makeUnderline : function() {
|
||||
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 3) === '<u>' && selection.slice(-4) === '</u>';
|
||||
this.codeMirror.replaceSelection(t ? selection.slice(3, -4) : `<u>${selection}</u>`, 'around');
|
||||
if(selection.length === 0){
|
||||
const cursor = this.codeMirror.getCursor();
|
||||
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - 4 });
|
||||
}
|
||||
},
|
||||
|
||||
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');
|
||||
@@ -144,12 +247,72 @@ const CodeEditor = createClass({
|
||||
}
|
||||
},
|
||||
|
||||
makeComment : function() {
|
||||
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 4) === '<!--' && selection.slice(-3) === '-->';
|
||||
this.codeMirror.replaceSelection(t ? selection.slice(4, -3) : `<!-- ${selection} -->`, 'around');
|
||||
makeDiv : function() {
|
||||
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 2) === '{{' && selection.slice(-2) === '}}';
|
||||
this.codeMirror.replaceSelection(t ? selection.slice(2, -2) : `{{\n${selection}\n}}`, 'around');
|
||||
if(selection.length === 0){
|
||||
const cursor = this.codeMirror.getCursor();
|
||||
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - 4 });
|
||||
this.codeMirror.setCursor({ line: cursor.line - 1, ch: cursor.ch }); // set to -2? if wanting to enter classes etc. if so, get rid of first \n when replacing selection
|
||||
}
|
||||
},
|
||||
|
||||
makeComment : function() {
|
||||
let regex;
|
||||
let cursorPos;
|
||||
let newComment;
|
||||
const selection = this.codeMirror.getSelection();
|
||||
if(this.props.language === 'gfm'){
|
||||
regex = /^\s*(<!--\s?)(.*?)(\s?-->)\s*$/gs;
|
||||
cursorPos = 4;
|
||||
newComment = `<!-- ${selection} -->`;
|
||||
} else {
|
||||
regex = /^\s*(\/\*\s?)(.*?)(\s?\*\/)\s*$/gs;
|
||||
cursorPos = 3;
|
||||
newComment = `/* ${selection} */`;
|
||||
}
|
||||
this.codeMirror.replaceSelection(regex.test(selection) == true ? selection.replace(regex, '$2') : newComment, 'around');
|
||||
if(selection.length === 0){
|
||||
const cursor = this.codeMirror.getCursor();
|
||||
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - cursorPos });
|
||||
};
|
||||
},
|
||||
|
||||
makeLink : function() {
|
||||
const isLink = /^\[(.*)\]\((.*)\)$/;
|
||||
const selection = this.codeMirror.getSelection().trim();
|
||||
let match;
|
||||
if(match = isLink.exec(selection)){
|
||||
const altText = match[1];
|
||||
const url = match[2];
|
||||
this.codeMirror.replaceSelection(`${altText} ${url}`);
|
||||
const cursor = this.codeMirror.getCursor();
|
||||
this.codeMirror.setSelection({ line: cursor.line, ch: cursor.ch - url.length }, { line: cursor.line, ch: cursor.ch });
|
||||
} else {
|
||||
this.codeMirror.replaceSelection(`[${selection || 'alt text'}](url)`);
|
||||
const cursor = this.codeMirror.getCursor();
|
||||
this.codeMirror.setSelection({ line: cursor.line, ch: cursor.ch - 4 }, { line: cursor.line, ch: cursor.ch - 1 });
|
||||
}
|
||||
},
|
||||
|
||||
makeList : function(listType) {
|
||||
const selectionStart = this.codeMirror.getCursor('from'), selectionEnd = this.codeMirror.getCursor('to');
|
||||
this.codeMirror.setSelection(
|
||||
{ line: selectionStart.line, ch: 0 },
|
||||
{ line: selectionEnd.line, ch: this.codeMirror.getLine(selectionEnd.line).length }
|
||||
);
|
||||
const newSelection = this.codeMirror.getSelection();
|
||||
|
||||
const regex = /^\d+\.\s|^-\s/gm;
|
||||
if(newSelection.match(regex) != null){ // if selection IS A LIST
|
||||
this.codeMirror.replaceSelection(newSelection.replace(regex, ''), 'around');
|
||||
} else { // if selection IS NOT A LIST
|
||||
listType == 'UL' ? this.codeMirror.replaceSelection(newSelection.replace(/^/gm, `- `), 'around') :
|
||||
this.codeMirror.replaceSelection(newSelection.replace(/^/gm, (()=>{
|
||||
let n = 1;
|
||||
return ()=>{
|
||||
return `${n++}. `;
|
||||
};
|
||||
})()), 'around');
|
||||
}
|
||||
},
|
||||
|
||||
@@ -183,6 +346,30 @@ const CodeEditor = createClass({
|
||||
historySize : function(){
|
||||
return this.codeMirror.doc.historySize();
|
||||
},
|
||||
|
||||
foldOptions : function(cm){
|
||||
return {
|
||||
scanUp : true,
|
||||
rangeFinder : CodeMirror.fold.homebrewery,
|
||||
widget : (from, to)=>{
|
||||
let text = '';
|
||||
let currentLine = from.line;
|
||||
const maxLength = 50;
|
||||
while (currentLine <= to.line && text.length <= maxLength) {
|
||||
text += this.codeMirror.getLine(currentLine);
|
||||
if(currentLine < to.line)
|
||||
text += ' ';
|
||||
currentLine += 1;
|
||||
}
|
||||
|
||||
text = text.trim();
|
||||
if(text.length > maxLength)
|
||||
text = `${text.substr(0, maxLength)}...`;
|
||||
|
||||
return `\u21A4 ${text} \u21A6`;
|
||||
}
|
||||
};
|
||||
},
|
||||
//----------------------//
|
||||
|
||||
render : function(){
|
||||
|
||||
@@ -1,5 +1,12 @@
|
||||
@import (less) 'codemirror/lib/codemirror.css';
|
||||
@import (less) 'codemirror/addon/fold/foldgutter.css';
|
||||
@import (less) 'codemirror/addon/search/matchesonscrollbar.css';
|
||||
@import (less) 'codemirror/addon/dialog/dialog.css';
|
||||
|
||||
@keyframes sourceMoveAnimation {
|
||||
50% {background-color: red; color: white;}
|
||||
100% {background-color: unset; color: unset;}
|
||||
}
|
||||
|
||||
.codeEditor{
|
||||
.CodeMirror-foldmarker {
|
||||
@@ -7,4 +14,19 @@
|
||||
text-shadow: none;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.sourceMoveFlash .CodeMirror-line{
|
||||
animation-name: sourceMoveAnimation;
|
||||
animation-duration: 0.4s;
|
||||
}
|
||||
|
||||
//.cm-tab {
|
||||
// background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAQAAACOs/baAAAARUlEQVR4nGJgIAG8JkXxUAcCtDWemcGR1lY4MvgzCEKY7jSBjgxBDAG09UEQzAe0AMwMHrSOAwEGRtpaMIwAAAAA//8DAG4ID9EKs6YqAAAAAElFTkSuQmCC) no-repeat right;
|
||||
//}
|
||||
|
||||
//.cm-trailingspace {
|
||||
// .cm-space {
|
||||
// background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAQAgMAAABW5NbuAAAACVBMVEVHcEwAAAAAAAAWawmTAAAAA3RSTlMAPBJ6PMxpAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAFUlEQVQI12NgwACcCQysASAEZGAAACMuAX06aCQUAAAAAElFTkSuQmCC) no-repeat right;
|
||||
// }
|
||||
//}
|
||||
}
|
||||
@@ -1,7 +1,8 @@
|
||||
/* eslint-disable max-lines */
|
||||
const _ = require('lodash');
|
||||
const Markdown = require('marked');
|
||||
const renderer = new Markdown.Renderer();
|
||||
const Marked = require('marked');
|
||||
const MarkedExtendedTables = require('marked-extended-tables');
|
||||
const renderer = new Marked.Renderer();
|
||||
|
||||
//Processes the markdown within an HTML block if it's just a class-wrapper
|
||||
renderer.html = function (html) {
|
||||
@@ -9,7 +10,7 @@ renderer.html = function (html) {
|
||||
const openTag = html.substring(0, html.indexOf('>')+1);
|
||||
html = html.substring(html.indexOf('>')+1);
|
||||
html = html.substring(0, html.lastIndexOf('</div>'));
|
||||
return `${openTag} ${Markdown(html)} </div>`;
|
||||
return `${openTag} ${Marked.parse(html)} </div>`;
|
||||
}
|
||||
return html;
|
||||
};
|
||||
@@ -235,200 +236,10 @@ const definitionLists = {
|
||||
}
|
||||
};
|
||||
|
||||
const spanTable = {
|
||||
name : 'spanTable',
|
||||
level : 'block', // Is this a block-level or inline-level tokenizer?
|
||||
start(src) { return src.match(/^\n *([^\n ].*\|.*)\n/)?.index; }, // Hint to Marked.js to stop and check for a match
|
||||
tokenizer(src, tokens) {
|
||||
//const regex = this.tokenizer.rules.block.table;
|
||||
const regex = new RegExp('^ *([^\\n ].*\\|.*\\n(?: *[^\\s].*\\n)*?)' // Header
|
||||
+ ' {0,3}(?:\\| *)?(:?-+:? *(?:\\| *:?-+:? *)*)\\|?' // Align
|
||||
+ '(?:\\n *((?:(?!\\n| {0,3}((?:- *){3,}|(?:_ *){3,}|(?:\\* *){3,})' // Cells
|
||||
+ '(?:\\n+|$)| {0,3}#{1,6} | {0,3}>| {4}[^\\n]| {0,3}(?:`{3,}'
|
||||
+ '(?=[^`\\n]*\\n)|~{3,})[^\\n]*\\n| {0,3}(?:[*+-]|1[.)]) |'
|
||||
+ '<\\/?(?:address|article|aside|base|basefont|blockquote|body|'
|
||||
+ 'caption|center|col|colgroup|dd|details|dialog|dir|div|dl|dt|fieldset|figcaption|figure|footer|form|frame|frameset|h[1-6]|head|header|hr|html|iframe|legend|li|link|main|menu|menuitem|meta|nav|noframes|ol|optgroup|option|p|param|section|source|summary|table|tbody|td|tfoot|th|thead|title|tr|track|ul)(?: +|\\n|\\/?>)|<(?:script|pre|style|textarea|!--)).*(?:\\n|$))*)\\n*|$)'); // Cells
|
||||
const cap = regex.exec(src);
|
||||
|
||||
if(cap) {
|
||||
const item = {
|
||||
type : 'spanTable',
|
||||
header : cap[1].replace(/\n$/, '').split('\n'),
|
||||
align : cap[2].replace(/^ *|\| *$/g, '').split(/ *\| */),
|
||||
rows : cap[3] ? cap[3].replace(/\n$/, '').split('\n') : []
|
||||
};
|
||||
|
||||
// Get first header row to determine how many columns
|
||||
item.header[0] = splitCells(item.header[0]);
|
||||
|
||||
const colCount = item.header[0].reduce((length, header)=>{
|
||||
return length + header.colspan;
|
||||
}, 0);
|
||||
|
||||
if(colCount === item.align.length) {
|
||||
item.raw = cap[0];
|
||||
|
||||
let i, j, k, row;
|
||||
|
||||
// Get alignment row (:---:)
|
||||
let l = item.align.length;
|
||||
|
||||
for (i = 0; i < l; i++) {
|
||||
if(/^ *-+: *$/.test(item.align[i])) {
|
||||
item.align[i] = 'right';
|
||||
} else if(/^ *:-+: *$/.test(item.align[i])) {
|
||||
item.align[i] = 'center';
|
||||
} else if(/^ *:-+ *$/.test(item.align[i])) {
|
||||
item.align[i] = 'left';
|
||||
} else {
|
||||
item.align[i] = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Get any remaining header rows
|
||||
l = item.header.length;
|
||||
for (i = 1; i < l; i++) {
|
||||
item.header[i] = splitCells(item.header[i], colCount, item.header[i-1]);
|
||||
}
|
||||
|
||||
// Get main table cells
|
||||
l = item.rows.length;
|
||||
for (i = 0; i < l; i++) {
|
||||
item.rows[i] = splitCells(item.rows[i], colCount, item.rows[i-1]);
|
||||
}
|
||||
|
||||
// header child tokens
|
||||
l = item.header.length;
|
||||
for (j = 0; j < l; j++) {
|
||||
row = item.header[j];
|
||||
for (k = 0; k < row.length; k++) {
|
||||
row[k].tokens = [];
|
||||
this.lexer.inlineTokens(row[k].text, row[k].tokens);
|
||||
}
|
||||
}
|
||||
|
||||
// cell child tokens
|
||||
l = item.rows.length;
|
||||
for (j = 0; j < l; j++) {
|
||||
row = item.rows[j];
|
||||
for (k = 0; k < row.length; k++) {
|
||||
row[k].tokens = [];
|
||||
this.lexer.inlineTokens(row[k].text, row[k].tokens);
|
||||
}
|
||||
}
|
||||
return item;
|
||||
}
|
||||
}
|
||||
},
|
||||
renderer(token) {
|
||||
let i, j, row, cell, col, text;
|
||||
let output = `<table>`;
|
||||
output += `<thead>`;
|
||||
for (i = 0; i < token.header.length; i++) {
|
||||
row = token.header[i];
|
||||
let col = 0;
|
||||
output += `<tr>`;
|
||||
for (j = 0; j < row.length; j++) {
|
||||
cell = row[j];
|
||||
text = this.parser.parseInline(cell.tokens);
|
||||
output += getTableCell(text, cell, 'th', token.align[col]);
|
||||
col += cell.colspan;
|
||||
}
|
||||
output += `</tr>`;
|
||||
}
|
||||
output += `</thead>`;
|
||||
if(token.rows.length) {
|
||||
output += `<tbody>`;
|
||||
for (i = 0; i < token.rows.length; i++) {
|
||||
row = token.rows[i];
|
||||
col = 0;
|
||||
output += `<tr>`;
|
||||
for (j = 0; j < row.length; j++) {
|
||||
cell = row[j];
|
||||
text = this.parser.parseInline(cell.tokens);
|
||||
output += getTableCell(text, cell, 'td', token.align[col]);
|
||||
col += cell.colspan;
|
||||
}
|
||||
output += `</tr>`;
|
||||
}
|
||||
output += `</tbody>`;
|
||||
}
|
||||
output += `</table>`;
|
||||
return output;
|
||||
}
|
||||
};
|
||||
|
||||
const getTableCell = (text, cell, type, align)=>{
|
||||
if(!cell.rowspan) {
|
||||
return '';
|
||||
}
|
||||
const tag = `<${type}`
|
||||
+ `${cell.colspan > 1 ? ` colspan=${cell.colspan}` : ''}`
|
||||
+ `${cell.rowspan > 1 ? ` rowspan=${cell.rowspan}` : ''}`
|
||||
+ `${align ? ` align=${align}` : ''}>`;
|
||||
return `${tag + text}</${type}>\n`;
|
||||
};
|
||||
|
||||
const splitCells = (tableRow, count, prevRow = [])=>{
|
||||
const cells = [...tableRow.matchAll(/(?:[^|\\]|\\.?)+(?:\|+|$)/g)].map((x)=>x[0]);
|
||||
|
||||
// Remove first/last cell in a row if whitespace only and no leading/trailing pipe
|
||||
if(!cells[0]?.trim()) { cells.shift(); }
|
||||
if(!cells[cells.length - 1]?.trim()) { cells.pop(); }
|
||||
|
||||
let numCols = 0;
|
||||
let i, j, trimmedCell, prevCell, prevCols;
|
||||
|
||||
for (i = 0; i < cells.length; i++) {
|
||||
trimmedCell = cells[i].split(/\|+$/)[0];
|
||||
cells[i] = {
|
||||
rowspan : 1,
|
||||
colspan : Math.max(cells[i].length - trimmedCell.length, 1),
|
||||
text : trimmedCell.trim().replace(/\\\|/g, '|')
|
||||
// display escaped pipes as normal character
|
||||
};
|
||||
|
||||
// Handle Rowspan
|
||||
if(trimmedCell.slice(-1) == '^' && prevRow.length) {
|
||||
// Find matching cell in previous row
|
||||
prevCols = 0;
|
||||
for (j = 0; j < prevRow.length; j++) {
|
||||
prevCell = prevRow[j];
|
||||
if((prevCols == numCols) && (prevCell.colspan == cells[i].colspan)) {
|
||||
// merge into matching cell in previous row (the "target")
|
||||
cells[i].rowSpanTarget = prevCell.rowSpanTarget ?? prevCell;
|
||||
cells[i].rowSpanTarget.text += ` ${cells[i].text.slice(0, -1)}`;
|
||||
cells[i].rowSpanTarget.rowspan += 1;
|
||||
cells[i].rowspan = 0;
|
||||
break;
|
||||
}
|
||||
prevCols += prevCell.colspan;
|
||||
if(prevCols > numCols)
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
numCols += cells[i].colspan;
|
||||
}
|
||||
|
||||
// Force main cell rows to match header column count
|
||||
if(numCols > count) {
|
||||
cells.splice(count);
|
||||
} else {
|
||||
while (numCols < count) {
|
||||
cells.push({
|
||||
colspan : 1,
|
||||
text : ''
|
||||
});
|
||||
numCols += 1;
|
||||
}
|
||||
}
|
||||
return cells;
|
||||
};
|
||||
|
||||
Markdown.use({ extensions: [mustacheSpans, mustacheDivs, mustacheInjectInline, definitionLists, spanTable] });
|
||||
Markdown.use(mustacheInjectBlock);
|
||||
Markdown.use({ smartypants: true });
|
||||
Marked.use({ extensions: [mustacheSpans, mustacheDivs, mustacheInjectInline, definitionLists] });
|
||||
Marked.use(MarkedExtendedTables());
|
||||
Marked.use(mustacheInjectBlock);
|
||||
Marked.use({ smartypants: true });
|
||||
|
||||
//Fix local links in the Preview iFrame to link inside the frame
|
||||
renderer.link = function (href, title, text) {
|
||||
@@ -532,11 +343,11 @@ const processStyleTags = (string)=>{
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
marked : Markdown,
|
||||
marked : Marked,
|
||||
render : (rawBrewText)=>{
|
||||
rawBrewText = rawBrewText.replace(/^\\column$/gm, `\n<div class='columnSplit'></div>\n`)
|
||||
.replace(/^(:+)$/gm, (match)=>`${`<div class='blank'></div>`.repeat(match.length)}\n`);
|
||||
return Markdown(
|
||||
return Marked.parse(
|
||||
sanatizeScriptTags(rawBrewText),
|
||||
{ renderer: renderer }
|
||||
);
|
||||
|
||||
@@ -8,7 +8,8 @@ const NaturalCritIcon = require('naturalcrit/svg/naturalcrit.svg.jsx');
|
||||
|
||||
const Nav = {
|
||||
base : createClass({
|
||||
render : function(){
|
||||
displayName : 'Nav.base',
|
||||
render : function(){
|
||||
return <nav>
|
||||
<div className='navContent'>
|
||||
{this.props.children}
|
||||
@@ -26,7 +27,8 @@ const Nav = {
|
||||
},
|
||||
|
||||
section : createClass({
|
||||
render : function(){
|
||||
displayName : 'Nav.section',
|
||||
render : function(){
|
||||
return <div className='navSection'>
|
||||
{this.props.children}
|
||||
</div>;
|
||||
@@ -34,6 +36,7 @@ const Nav = {
|
||||
}),
|
||||
|
||||
item : createClass({
|
||||
displayName : 'Nav.item',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
icon : null,
|
||||
@@ -69,6 +72,7 @@ const Nav = {
|
||||
}),
|
||||
|
||||
dropdown : createClass({
|
||||
displayName : 'Nav.dropdown',
|
||||
getInitialState : function() {
|
||||
return {
|
||||
showDropdown : false
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
@import '../styles/colors';
|
||||
@keyframes glideDropDown {
|
||||
0% {transform : translate(0px, -100%);
|
||||
opacity : 0;
|
||||
@@ -49,6 +50,7 @@ nav{
|
||||
}
|
||||
}
|
||||
.navItem{
|
||||
#backgroundColors;
|
||||
.animate(background-color);
|
||||
padding : 8px 12px;
|
||||
cursor : pointer;
|
||||
@@ -58,30 +60,12 @@ nav{
|
||||
color : white;
|
||||
text-decoration : none;
|
||||
text-transform : uppercase;
|
||||
line-height : 13px;
|
||||
i{
|
||||
margin-left : 5px;
|
||||
font-size : 13px;
|
||||
float : right;
|
||||
}
|
||||
&.tealLight:hover{ background-color : @tealLight };
|
||||
&.teal:hover{ background-color : @teal };
|
||||
&.greenLight:hover{ background-color : @greenLight };
|
||||
&.green:hover{ background-color : @green };
|
||||
&.blueLight:hover{ background-color : @blueLight };
|
||||
&.blue:hover{ background-color : @blue };
|
||||
&.purpleLight:hover{ background-color : @purpleLight };
|
||||
&.purple:hover{ background-color : @purple };
|
||||
&.steelLight:hover{ background-color : @steelLight };
|
||||
&.steel:hover{ background-color : @steel };
|
||||
&.yellowLight:hover{ background-color : @yellowLight };
|
||||
&.yellow:hover{ background-color : @yellow };
|
||||
&.orangeLight:hover{ background-color : @orangeLight };
|
||||
&.orange:hover{ background-color : @orange };
|
||||
&.redLight:hover{ background-color : @redLight };
|
||||
&.red:hover{ background-color : @red };
|
||||
&.silverLight:hover{ background-color : @silverLight };
|
||||
&.silver:hover{ background-color : @silver };
|
||||
&.greyLight:hover{ background-color : @greyLight };
|
||||
&.grey:hover{ background-color : @grey };
|
||||
}
|
||||
.navSection:last-child .navItem{
|
||||
border-left : 1px solid #666;
|
||||
|
||||
@@ -5,47 +5,82 @@ const _ = require('lodash');
|
||||
const cx = require('classnames');
|
||||
|
||||
const SplitPane = createClass({
|
||||
displayName : 'SplitPane',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
storageKey : 'naturalcrit-pane-split',
|
||||
onDragFinish : function(){} //fires when dragging
|
||||
|
||||
};
|
||||
},
|
||||
|
||||
getInitialState : function() {
|
||||
return {
|
||||
size : null,
|
||||
isDragging : false
|
||||
currentDividerPos : null,
|
||||
windowWidth : 0,
|
||||
isDragging : false,
|
||||
moveSource : false,
|
||||
moveBrew : false,
|
||||
showMoveArrows : true
|
||||
};
|
||||
},
|
||||
|
||||
componentDidMount : function() {
|
||||
const paneSize = window.localStorage.getItem(this.props.storageKey);
|
||||
if(paneSize){
|
||||
const dividerPos = window.localStorage.getItem(this.props.storageKey);
|
||||
if(dividerPos){
|
||||
this.setState({
|
||||
size : paneSize
|
||||
currentDividerPos : this.limitPosition(dividerPos, 0.1*(window.innerWidth-13), 0.9*(window.innerWidth-13)),
|
||||
userSetDividerPos : dividerPos,
|
||||
windowWidth : window.innerWidth
|
||||
});
|
||||
} else {
|
||||
this.setState({
|
||||
currentDividerPos : window.innerWidth / 2,
|
||||
userSetDividerPos : window.innerWidth / 2
|
||||
});
|
||||
}
|
||||
window.addEventListener('resize', this.handleWindowResize);
|
||||
},
|
||||
|
||||
componentWillUnmount : function() {
|
||||
window.removeEventListener('resize', this.handleWindowResize);
|
||||
},
|
||||
|
||||
handleWindowResize : function() {
|
||||
// Allow divider to increase in size to last user-set position
|
||||
// Limit current position to between 10% and 90% of visible space
|
||||
const newLoc = this.limitPosition(this.state.userSetDividerPos, 0.1*(window.innerWidth-13), 0.9*(window.innerWidth-13));
|
||||
|
||||
this.setState({
|
||||
currentDividerPos : newLoc,
|
||||
windowWidth : window.innerWidth
|
||||
});
|
||||
},
|
||||
|
||||
limitPosition : function(x, min = 1, max = window.innerWidth - 13) {
|
||||
const result = Math.round(Math.min(max, Math.max(min, x)));
|
||||
return result;
|
||||
},
|
||||
|
||||
handleUp : function(){
|
||||
if(this.state.isDragging){
|
||||
this.props.onDragFinish(this.state.size);
|
||||
window.localStorage.setItem(this.props.storageKey, this.state.size);
|
||||
this.props.onDragFinish(this.state.currentDividerPos);
|
||||
window.localStorage.setItem(this.props.storageKey, this.state.currentDividerPos);
|
||||
}
|
||||
this.setState({ isDragging: false });
|
||||
},
|
||||
|
||||
handleDown : function(){
|
||||
this.setState({ isDragging: true });
|
||||
//this.unFocus()
|
||||
},
|
||||
|
||||
handleMove : function(e){
|
||||
if(!this.state.isDragging) return;
|
||||
|
||||
const minWidth = 1;
|
||||
const maxWidth = window.innerWidth - 13;
|
||||
const newSize = Math.min(maxWidth, Math.max(minWidth, e.pageX));
|
||||
const newSize = this.limitPosition(e.pageX);
|
||||
this.setState({
|
||||
size : newSize
|
||||
currentDividerPos : newSize,
|
||||
userSetDividerPos : newSize
|
||||
});
|
||||
},
|
||||
/*
|
||||
@@ -56,20 +91,58 @@ const SplitPane = createClass({
|
||||
window.getSelection().removeAllRanges();
|
||||
}
|
||||
},
|
||||
*/
|
||||
*/
|
||||
|
||||
setMoveArrows : function(newState) {
|
||||
if(this.state.showMoveArrows != newState){
|
||||
this.setState({
|
||||
showMoveArrows : newState
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
renderMoveArrows : function(){
|
||||
if(this.state.showMoveArrows) {
|
||||
return <>
|
||||
<div className='arrow left'
|
||||
style={{ left: this.state.currentDividerPos-4 }}
|
||||
onClick={()=>this.setState({ moveSource: !this.state.moveSource })} >
|
||||
<i className='fas fa-arrow-left' />
|
||||
</div>
|
||||
<div className='arrow right'
|
||||
style={{ left: this.state.currentDividerPos-4 }}
|
||||
onClick={()=>this.setState({ moveBrew: !this.state.moveBrew })} >
|
||||
<i className='fas fa-arrow-right' />
|
||||
</div>
|
||||
</>;
|
||||
}
|
||||
},
|
||||
|
||||
renderDivider : function(){
|
||||
return <div className='divider' onMouseDown={this.handleDown} >
|
||||
<div className='dots'>
|
||||
<i className='fas fa-circle' />
|
||||
<i className='fas fa-circle' />
|
||||
<i className='fas fa-circle' />
|
||||
return <>
|
||||
{this.renderMoveArrows()}
|
||||
<div className='divider' onMouseDown={this.handleDown} >
|
||||
<div className='dots'>
|
||||
<i className='fas fa-circle' />
|
||||
<i className='fas fa-circle' />
|
||||
<i className='fas fa-circle' />
|
||||
</div>
|
||||
</div>
|
||||
</div>;
|
||||
</>;
|
||||
},
|
||||
|
||||
render : function(){
|
||||
return <div className='splitPane' onMouseMove={this.handleMove} onMouseUp={this.handleUp}>
|
||||
<Pane ref='pane1' width={this.state.size}>{this.props.children[0]}</Pane>
|
||||
<Pane
|
||||
ref='pane1'
|
||||
width={this.state.currentDividerPos}
|
||||
>
|
||||
{React.cloneElement(this.props.children[0], {
|
||||
moveBrew : this.state.moveBrew,
|
||||
moveSource : this.state.moveSource,
|
||||
setMoveArrows : this.setMoveArrows
|
||||
})}
|
||||
</Pane>
|
||||
{this.renderDivider()}
|
||||
<Pane ref='pane2' isDragging={this.state.isDragging}>{this.props.children[1]}</Pane>
|
||||
</div>;
|
||||
@@ -77,6 +150,7 @@ const SplitPane = createClass({
|
||||
});
|
||||
|
||||
const Pane = createClass({
|
||||
displayName : 'Pane',
|
||||
getDefaultProps : function() {
|
||||
return {
|
||||
width : null
|
||||
|
||||
@@ -13,7 +13,7 @@
|
||||
.divider{
|
||||
display : table;
|
||||
height : 100%;
|
||||
width : 12px;
|
||||
width : 15px;
|
||||
cursor : ew-resize;
|
||||
background-color : #bbb;
|
||||
text-align : center;
|
||||
@@ -32,4 +32,28 @@
|
||||
background-color: #999;
|
||||
}
|
||||
}
|
||||
.arrow{
|
||||
position : absolute;
|
||||
width : 25px;
|
||||
height : 25px;
|
||||
border : 2px solid #bbb;
|
||||
border-radius : 15px;
|
||||
text-align : center;
|
||||
font-size : 1.2em;
|
||||
cursor : pointer;
|
||||
background-color : #ddd;
|
||||
z-index : 999;
|
||||
box-shadow : 0 4px 5px #0000007f;
|
||||
&.left{
|
||||
.tooltipLeft('Jump to location in Editor');
|
||||
top : 30px;
|
||||
}
|
||||
&.right{
|
||||
.tooltipRight('Jump to location in Preview');
|
||||
top : 60px;
|
||||
}
|
||||
&:hover{
|
||||
background-color: #666;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -21,3 +21,26 @@
|
||||
@silver : #BDC3C7;
|
||||
@greyLight : #95A5A6;
|
||||
@grey : #7F8C8D;
|
||||
|
||||
#backgroundColors {
|
||||
&.tealLight:hover{ background-color : @tealLight };
|
||||
&.teal:hover{ background-color : @teal };
|
||||
&.greenLight:hover{ background-color : @greenLight };
|
||||
&.green:hover{ background-color : @green };
|
||||
&.blueLight:hover{ background-color : @blueLight };
|
||||
&.blue:hover{ background-color : @blue };
|
||||
&.purpleLight:hover{ background-color : @purpleLight };
|
||||
&.purple:hover{ background-color : @purple };
|
||||
&.steelLight:hover{ background-color : @steelLight };
|
||||
&.steel:hover{ background-color : @steel };
|
||||
&.yellowLight:hover{ background-color : @yellowLight };
|
||||
&.yellow:hover{ background-color : @yellow };
|
||||
&.orangeLight:hover{ background-color : @orangeLight };
|
||||
&.orange:hover{ background-color : @orange };
|
||||
&.redLight:hover{ background-color : @redLight };
|
||||
&.red:hover{ background-color : @red };
|
||||
&.silverLight:hover{ background-color : @silverLight };
|
||||
&.silver:hover{ background-color : @silver };
|
||||
&.greyLight:hover{ background-color : @greyLight };
|
||||
&.grey:hover{ background-color : @grey };
|
||||
}
|
||||
@@ -1,7 +0,0 @@
|
||||
const test = require('pico-check');
|
||||
|
||||
test('Just setting up a spot for future tests', (t)=>{
|
||||
t.pass();
|
||||
});
|
||||
|
||||
module.exports = test;
|
||||
15
tests/markdown/basic.test.js
Normal file
15
tests/markdown/basic.test.js
Normal file
@@ -0,0 +1,15 @@
|
||||
/* eslint-disable max-lines */
|
||||
|
||||
const Markdown = require('naturalcrit/markdown.js');
|
||||
|
||||
test('Escapes <script> tag', function() {
|
||||
const source = '<script></script>';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toMatch('<script></script>');
|
||||
});
|
||||
|
||||
test('Processes the markdown within an HTML block if its just a class wrapper', function() {
|
||||
const source = '<div>*Bold text*</div>';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toBe('<div> <p><em>Bold text</em></p>\n </div>');
|
||||
});
|
||||
128
tests/markdown/mustache-span.test.js
Normal file
128
tests/markdown/mustache-span.test.js
Normal file
@@ -0,0 +1,128 @@
|
||||
/* eslint-disable max-lines */
|
||||
|
||||
const Markdown = require('naturalcrit/markdown.js');
|
||||
|
||||
test('Renders a mustache span with text only', function() {
|
||||
const source = '{{ text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toBe('<span class="inline-block ">text</span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with text only, but with spaces', function() {
|
||||
const source = '{{ this is a text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toBe('<span class="inline-block ">this is a text</span>');
|
||||
});
|
||||
|
||||
test('Renders an empty mustache span', function() {
|
||||
const source = '{{}}';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toBe('<span class="inline-block "></span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with just a space', function() {
|
||||
const source = '{{ }}';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toBe('<span class="inline-block "></span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with a few spaces only', function() {
|
||||
const source = '{{ }}';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toBe('<span class="inline-block "></span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with text and class', function() {
|
||||
const source = '{{my-class text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
// FIXME: why do we have those two extra spaces after closing "?
|
||||
expect(rendered).toBe('<span class="inline-block my-class" >text</span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with text and two classes', function() {
|
||||
const source = '{{my-class,my-class2 text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
// FIXME: why do we have those two extra spaces after closing "?
|
||||
expect(rendered).toBe('<span class="inline-block my-class my-class2" >text</span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with text with spaces and class', function() {
|
||||
const source = '{{my-class this is a text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
// FIXME: why do we have those two extra spaces after closing "?
|
||||
expect(rendered).toBe('<span class="inline-block my-class" >this is a text</span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with text and id', function() {
|
||||
const source = '{{#my-span text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
// FIXME: why do we have that one extra space after closing "?
|
||||
expect(rendered).toBe('<span class="inline-block " id="my-span" >text</span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with text and two ids', function() {
|
||||
const source = '{{#my-span,#my-favorite-span text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
// FIXME: do we need to report an error here somehow?
|
||||
expect(rendered).toBe('<span class="inline-block " id="my-span" >text</span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with text and css property', function() {
|
||||
const source = '{{color:red text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toBe('<span class="inline-block " style="color:red;">text</span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with text and two css properties', function() {
|
||||
const source = '{{color:red,padding:5px text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toBe('<span class="inline-block " style="color:red; padding:5px;">text</span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with text and css property which contains quotes', function() {
|
||||
const source = '{{font:"trebuchet ms" text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
// FIXME: is it correct to remove quotes surrounding css property value?
|
||||
expect(rendered).toBe('<span class="inline-block " style="font:trebuchet ms;">text</span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with text and two css properties which contains quotes', function() {
|
||||
const source = '{{font:"trebuchet ms",padding:"5px 10px" text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toBe('<span class="inline-block " style="font:trebuchet ms; padding:5px 10px;">text</span>');
|
||||
});
|
||||
|
||||
|
||||
test('Renders a mustache span with text with quotes and css property which contains quotes', function() {
|
||||
const source = '{{font:"trebuchet ms" text "with quotes"}}';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toBe('<span class="inline-block " style="font:trebuchet ms;">text “with quotes”</span>');
|
||||
});
|
||||
|
||||
test('Renders a mustache span with text, id, class and a couple of css properties', function() {
|
||||
const source = '{{pen,#author,color:orange,font-family:"trebuchet ms" text}}';
|
||||
const rendered = Markdown.render(source);
|
||||
expect(rendered).toBe('<span class="inline-block pen" id="author" style="color:orange; font-family:trebuchet ms;">text</span>');
|
||||
});
|
||||
|
||||
// TODO: add tests for ID with accordance to CSS spec:
|
||||
//
|
||||
// From https://drafts.csswg.org/selectors/#id-selectors:
|
||||
//
|
||||
// > An ID selector consists of a “number sign” (U+0023, #) immediately followed by the ID value, which must be a CSS identifier.
|
||||
//
|
||||
// From: https://www.w3.org/TR/CSS21/syndata.html#value-def-identifier:
|
||||
//
|
||||
// > In CSS, identifiers (including element names, classes, and IDs in selectors) can contain only the characters [a-zA-Z0-9]
|
||||
// > and ISO 10646 characters U+00A0 and higher, plus the hyphen (-) and the underscore (_);
|
||||
// > they cannot start with a digit, two hyphens, or a hyphen followed by a digit.
|
||||
// > Identifiers can also contain escaped characters and any ISO 10646 character as a numeric code (see next item).
|
||||
// > For instance, the identifier "B&W?" may be written as "B\&W\?" or "B\26 W\3F".
|
||||
// > Note that Unicode is code-by-code equivalent to ISO 10646 (see [UNICODE] and [ISO10646]).
|
||||
|
||||
// TODO: add tests for class with accordance to CSS spec:
|
||||
//
|
||||
// From: https://drafts.csswg.org/selectors/#class-html:
|
||||
//
|
||||
// > The class selector is given as a full stop (. U+002E) immediately followed by an identifier.
|
||||
|
||||
27
tests/routes/static-pages.test.js
Normal file
27
tests/routes/static-pages.test.js
Normal file
@@ -0,0 +1,27 @@
|
||||
const supertest = require('supertest');
|
||||
|
||||
// Mimic https responses to avoid being redirected all the time
|
||||
const app = supertest.agent(require('app.js').app)
|
||||
.set('X-Forwarded-Proto', 'https');
|
||||
|
||||
describe('Tests for static pages', ()=>{
|
||||
it('Home page works', ()=>{
|
||||
return app.get('/').expect(200);
|
||||
});
|
||||
|
||||
it('Home page v3 works', ()=>{
|
||||
return app.get('/v3_preview').expect(200);
|
||||
});
|
||||
|
||||
it('Changelog page works', ()=>{
|
||||
return app.get('/changelog').expect(200);
|
||||
});
|
||||
|
||||
it('FAQ page works', ()=>{
|
||||
return app.get('/faq').expect(200);
|
||||
});
|
||||
|
||||
it('robots.txt works', ()=>{
|
||||
return app.get('/robots.txt').expect(200);
|
||||
});
|
||||
});
|
||||
@@ -1 +0,0 @@
|
||||
//Set up configs and DB connectiosna nd what not in here
|
||||
@@ -242,9 +242,6 @@ body {
|
||||
display : block;
|
||||
padding-bottom : 0px;
|
||||
}
|
||||
p + p {
|
||||
padding-top : .8em;
|
||||
}
|
||||
:last-child {
|
||||
margin-bottom : 0;
|
||||
}
|
||||
@@ -275,9 +272,6 @@ body {
|
||||
padding-bottom : 0px;
|
||||
line-height : 1.5em;
|
||||
}
|
||||
p + p {
|
||||
padding-top : .8em;
|
||||
}
|
||||
:last-child {
|
||||
margin-bottom : 0;
|
||||
}
|
||||
@@ -517,7 +511,8 @@ body {
|
||||
color : #58180d;
|
||||
background-color : #faf7ea;
|
||||
border-radius : 4px;
|
||||
white-space : pre-wrap
|
||||
white-space : pre-wrap;
|
||||
overflow-wrap : break-word;
|
||||
}
|
||||
|
||||
pre code{
|
||||
@@ -550,7 +545,6 @@ body {
|
||||
-webkit-column-break-after : always;
|
||||
break-after : always;
|
||||
-moz-column-break-after : always;
|
||||
break-before : column;
|
||||
}
|
||||
//Avoid breaking up
|
||||
blockquote,table{
|
||||
@@ -609,8 +603,8 @@ body {
|
||||
white-space : nowrap;
|
||||
}
|
||||
&.frame {
|
||||
margin-top : 0.66cm;
|
||||
margin-bottom : 1.05cm;
|
||||
margin-top : 0.7cm;
|
||||
margin-bottom : 0.9cm;
|
||||
margin-left : -0.1cm;
|
||||
margin-right : -0.1cm;
|
||||
width : calc(100% + 0.2cm);
|
||||
@@ -618,32 +612,38 @@ body {
|
||||
background-color : white;
|
||||
border : initial;
|
||||
border-style : solid;
|
||||
border-image-outset : 0.55cm 0.3cm;
|
||||
border-image-outset : 0.4cm 0.3cm;
|
||||
border-image-repeat : stretch;
|
||||
border-image-slice : 200;
|
||||
border-image-source : @frameBorderImage;
|
||||
border-image-width : 47px;
|
||||
&.wide:first-child {
|
||||
margin-top: 0.12cm;
|
||||
}
|
||||
}
|
||||
&.decoration {
|
||||
transform-style : preserve-3d;
|
||||
position:relative;
|
||||
}
|
||||
&.decoration::before {
|
||||
content :'';
|
||||
position : absolute;
|
||||
background-image : @classTableDecoration;
|
||||
background-size : contain;
|
||||
background-repeat : space;
|
||||
width : 7.75cm;
|
||||
height : calc(100% + 3.3cm);
|
||||
top : 50%;
|
||||
left : 50%;
|
||||
transform : translateY(-50%) translateX(-50%) translateZ(-1px);
|
||||
filter : drop-shadow(0px 0px 1px #C8C5C080)
|
||||
content :'';
|
||||
position : absolute;
|
||||
background-image : @classTableDecoration,
|
||||
@classTableDecoration;
|
||||
background-size : contain, contain;
|
||||
background-repeat : no-repeat, no-repeat;
|
||||
background-position : top, bottom;
|
||||
width : 7.75cm;
|
||||
height : calc(100% + 3.3cm);
|
||||
top : 50%;
|
||||
left : 50%;
|
||||
transform : translateY(-50%) translateX(-50%);
|
||||
filter : drop-shadow(0px 0px 1px #C8C5C080);
|
||||
z-index : -1;
|
||||
}
|
||||
&.decoration.wide::before {
|
||||
width : calc(100% + 3.3cm);
|
||||
height : 7.75cm;
|
||||
top : calc(50% + 0.4cm);
|
||||
width : calc(100% + 3.3cm);
|
||||
height : 7.75cm;
|
||||
background-position : left, right;
|
||||
}
|
||||
h5 + table{
|
||||
margin-top : 0.2cm;
|
||||
@@ -658,10 +658,10 @@ body {
|
||||
break-inside : avoid;
|
||||
h1 {
|
||||
text-align : center;
|
||||
margin-bottom : 0cm;
|
||||
margin-bottom : 0.3cm;
|
||||
}
|
||||
a{
|
||||
display : table;
|
||||
display : inline;
|
||||
color : inherit;
|
||||
text-decoration : none;
|
||||
&:hover{
|
||||
@@ -669,14 +669,12 @@ body {
|
||||
}
|
||||
}
|
||||
h4 {
|
||||
margin-top : 0.14cm;
|
||||
margin-top : 0.2cm;
|
||||
line-height : 0.4cm;
|
||||
& + ul li {
|
||||
line-height: 1.2em;
|
||||
}
|
||||
}
|
||||
& > ul {
|
||||
margin-top: 0.52cm;
|
||||
}
|
||||
ul{
|
||||
padding-left : 0;
|
||||
list-style-type : none;
|
||||
|
||||
BIN
themes/assets/discord.png
Normal file
BIN
themes/assets/discord.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 3.1 KiB |
1
themes/assets/discordOfManyThings.svg
Normal file
1
themes/assets/discordOfManyThings.svg
Normal file
@@ -0,0 +1 @@
|
||||
<svg id="Layer_3" data-name="Layer 3" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 350.028 390.552"><defs><style>.cls-1{opacity:0.9;}.cls-2{fill:#001013;}.cls-3{fill:#fff;}.cls-4{fill:#aa2a29;}</style></defs><title>Discord of Many Things blank</title><g class="cls-1"><path d="M100.991,82.743c-1.649,3.324-3.395,5.768-4.1,8.482-1.49,5.753-3.44,11.644-3.455,17.482q-.332,125.259-.141,250.519c.007,20.122,12.708,36.368,31.407,40.239a38.328,38.328,0,0,0,7.722.761q103.611,0,207.222-.088h6.314c-3.256-11.462-9.664-34.015-9.664-34.015l2.431,2.023s41.561,37.755,62.33,56.6c2.489,2.26,3.694,4.462,3.593,7.885-.241,8.186-.078,16.383-.078,25.492-6.333-5.527-11.928-10.35-17.457-15.247-9.586-8.493-19.2-16.957-28.644-25.6a10.032,10.032,0,0,0-7.39-2.774q-117.228-.1-234.457-.334c-20.632-.031-33.959-9.189-41.021-28.578-.852-2.339-.783-5.091-.784-7.653q-.057-116.5-.031-233.007V119.145C74.791,102.517,84.2,89.068,100.991,82.743Z" transform="translate(-74.79 -67.573)"/></g><path class="cls-2" d="M338.234,371.589s5.556,19.924,8.513,30.53h-5.075c-69.335,0-138.67-.1-208,.074-16.925.043-35.116-9.515-40.505-33.247a26.538,26.538,0,0,1-.379-5.827q-.027-128.172.025-256.344c.021-19.276,15.226-36.749,34.427-38.688a82.669,82.669,0,0,1,8.279-.447q123.288-.034,246.578-.067c13.265-.016,24.7,3.79,33.278,14.235a39.273,39.273,0,0,1,9.447,25.5q-.015,167.477-.012,334.955c0,1.245-.1,2.49-.2,4.645-4.075-3.565-7.6-6.552-11.018-9.655q-35.236-31.992-70.44-64.017c-1.2-1.091-3.713-3.147-3.713-3.147l-2-1.775Z" transform="translate(-74.79 -67.573)"/><path class="cls-3" d="M419.838,435.934c-7.848-6.892-15.026-12.977-21.961-19.329q-28.235-25.86-56.253-51.954c-2.314-2.157-4.59-3.247-7.356-1.784-3.036,1.607-2.77,4.676-2.022,7.359,2.286,8.2,4.817,16.338,7.24,24.5a17.108,17.108,0,0,1,.294,1.851c-1.486.084-2.872.233-4.258.233-67.363.012-134.726-.155-202.088.123-18.267.075-32.955-13.095-34.769-29.353a92.257,92.257,0,0,1-.886-10.108Q97.7,233.488,97.793,109.5c.013-10.518,3.19-20.063,11.156-27.471a31.92,31.92,0,0,1,20.439-8.917c1.948-.109,3.9-.181,5.852-.181q123.5-.014,247-.063c9.957-.012,18.894,2.145,26.329,9.1,7.956,7.441,11.177,16.934,11.214,27.457.142,40.84.057,81.681.057,122.522V435.934Z" transform="translate(-74.79 -67.573)"/><path class="cls-4" d="M311.029,170.975c-11.8,45.005-23.315,88.959-35.123,134.016l-97.168-98.883Z" transform="translate(-74.79 -67.573)"/><path class="cls-4" d="M380.8,265.712l-95.97,40.316c11.438-43.808,22.639-86.709,33.839-129.609l1.08-.272Z" transform="translate(-74.79 -67.573)"/><path class="cls-4" d="M165.3,322.955c2.91-36.463,5.761-72.179,8.709-109.116l94.711,96.472Z" transform="translate(-74.79 -67.573)"/><path class="cls-4" d="M223.458,107.926l83.127,55.063L178.71,196.919Z" transform="translate(-74.79 -67.573)"/><path class="cls-4" d="M366.285,281.366l-72.5,73.414c-3.524-13.182-6.849-25.617-10.306-38.549Z" transform="translate(-74.79 -67.573)"/><path class="cls-4" d="M274.874,318.478c3.445,12.8,6.765,25.143,10.376,38.559l-98.635-26.556.032-1.153Z" transform="translate(-74.79 -67.573)"/><path class="cls-4" d="M374.888,241.261l-51.71-75.57,26.8-21.529,25.831,96.619Z" transform="translate(-74.79 -67.573)"/><path class="cls-4" d="M165.492,207.523c-2.39,30.748-4.736,60.942-7.083,91.135l-1.063.159c-8.5-31.936-17-63.872-25.705-96.581Z" transform="translate(-74.79 -67.573)"/><path class="cls-4" d="M317.039,159.316l-68.251-45.24.307-.794,93.794,25.212Z" transform="translate(-74.79 -67.573)"/><path class="cls-4" d="M136.517,193.952,203.5,125.03l1.086.832L167.794,198.9Z" transform="translate(-74.79 -67.573)"/></svg>
|
||||
|
After Width: | Height: | Size: 3.5 KiB |
BIN
themes/assets/github.png
Normal file
BIN
themes/assets/github.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.9 KiB |
BIN
themes/assets/patreon.png
Normal file
BIN
themes/assets/patreon.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 2.4 KiB |
BIN
themes/assets/reddit.png
Normal file
BIN
themes/assets/reddit.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 4.0 KiB |
BIN
themes/fonts/5e/Nodesto Caps Condensed Bold Italic.woff2
Normal file
BIN
themes/fonts/5e/Nodesto Caps Condensed Bold Italic.woff2
Normal file
Binary file not shown.
BIN
themes/fonts/5e/Nodesto Caps Condensed Bold.woff2
Normal file
BIN
themes/fonts/5e/Nodesto Caps Condensed Bold.woff2
Normal file
Binary file not shown.
BIN
themes/fonts/5e/Nodesto Caps Condensed Italic.woff2
Normal file
BIN
themes/fonts/5e/Nodesto Caps Condensed Italic.woff2
Normal file
Binary file not shown.
BIN
themes/fonts/5e/Nodesto Caps Condensed.woff2
Normal file
BIN
themes/fonts/5e/Nodesto Caps Condensed.woff2
Normal file
Binary file not shown.
@@ -77,3 +77,32 @@
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
/* Cover Page */
|
||||
@font-face {
|
||||
font-family: NodestoCapsCondensed;
|
||||
src: url('../fonts/5e/Nodesto Caps Condensed.woff2');
|
||||
font-weight: normal;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: NodestoCapsCondensed;
|
||||
src: url('../fonts/5e/Nodesto Caps Condensed Bold.woff2');
|
||||
font-weight: bold;
|
||||
font-style: normal;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: NodestoCapsCondensed;
|
||||
src: url('../fonts/5e/Nodesto Caps Condensed Italic.woff2');
|
||||
font-weight: normal;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
@font-face {
|
||||
font-family: NodestoCapsCondensed;
|
||||
src: url('../fonts/5e/Nodesto Caps Condensed Bold Italic.woff2');
|
||||
font-weight: bold;
|
||||
font-style: italic;
|
||||
}
|
||||
Reference in New Issue
Block a user