diff --git a/.circleci/config.yml b/.circleci/config.yml
index 5effc0bb2..cc6bd8d82 100644
--- a/.circleci/config.yml
+++ b/.circleci/config.yml
@@ -82,6 +82,9 @@ jobs:
- run:
name: Test - HTML sanitization
command: npm run test:safehtml
+ - run:
+ name: Test - Helpers
+ command: npm run test:helpers
- run:
name: Test - Coverage
command: npm run test:coverage
diff --git a/changelog.md b/changelog.md
index d783130f0..1c5a9b714 100644
--- a/changelog.md
+++ b/changelog.md
@@ -128,7 +128,7 @@ Fixes issue [#4858](https://github.com/naturalcrit/homebrewery/issues/4858)
Fixes part of issue [#4101](https://github.com/naturalcrit/homebrewery/issues/4101)
##### G-Ambatte
-* [x] Fix editor panel shrinking when openingdev tools
+* [x] Fix editor panel shrinking when opening dev tools
Fixes issue [#4866](https://github.com/naturalcrit/homebrewery/issues/4866)
@@ -154,7 +154,7 @@ Fixes issue [#4904](https://github.com/naturalcrit/homebrewery/issues/4904)
##### 5e-Cleric, Gazook89
* [x] Fix various issues with Codemirror 6
-Fixes issues [#4771](https://github.com/naturalcrit/homebrewery/issues/4771), [#4583](https://github.com/naturalcrit/homebrewery/issues/4783)
+Fixes issues [#4771](https://github.com/naturalcrit/homebrewery/issues/4771), [#4783](https://github.com/naturalcrit/homebrewery/issues/4783)
}}
\page
@@ -170,7 +170,6 @@ Fixes issues [#4771](https://github.com/naturalcrit/homebrewery/issues/4771), [#
##### 5e-Cleric
* [x] Add auto-suggest to tag entry input box
-* [x] Replace all example artwork with
* [x] Added tooltips to the {{openSans :fas_circle_info: **Properties**}} menu
* [x] Removed {{openSans **SYSTEMS**}} checkboxes from {{openSans :fas_circle_info: **Properties**}} menu; instead {{openSans **TAGS**}} should be used for this purpose
* [x] Replace all AI-generated art with public domain art
@@ -222,7 +221,7 @@ Fixes issue [#4559](https://github.com/naturalcrit/homebrewery/issues/4559)
##### G-Ambatte
* [x] Fix default save location failing on new documents
-Fixes issue [#4437](https://github.com/naturalcrit/homebrewery/issues/3175)
+Fixes issue [#4437](https://github.com/naturalcrit/homebrewery/issues/4437)
* [x] Fix usernames with special symbols unable to open userpage
Fixes issue [#807](https://github.com/naturalcrit/homebrewery/issues/807)
diff --git a/client/homebrew/brewRenderer/brewRenderer.jsx b/client/homebrew/brewRenderer/brewRenderer.jsx
index 65de45177..618a64ecd 100644
--- a/client/homebrew/brewRenderer/brewRenderer.jsx
+++ b/client/homebrew/brewRenderer/brewRenderer.jsx
@@ -6,7 +6,7 @@ import React, { useState, useRef, useMemo, useEffect } from 'react';
import _ from 'lodash';
import MarkdownLegacy from '@shared/markdownLegacy.js';
-import { hbfm } from 'hbmarkedwrapper';
+import { hbfm } from 'marked-hbfm';
import ErrorBar from './errorBar/errorBar.jsx';
import ToolBar from './toolBar/toolBar.jsx';
@@ -23,7 +23,6 @@ import safeHTML from './safeHTML.js';
const PAGEBREAK_REGEX_V3 = /^(?=\\page(?:break)?(?: *{[^\n{}]*})?$)/m;
const PAGEBREAK_REGEX_LEGACY = /\\page(?:break)?/m;
const COLUMNBREAK_REGEX_LEGACY = /\\column(:?break)?/m;
-const PAGE_HEIGHT = 1056;
const TOOLBAR_STATE_KEY = 'HB_renderer_toolbarState';
@@ -47,31 +46,25 @@ const BrewPage = (props)=>{
};
const pageRef = useRef(null);
const cleanText = safeHTML(props.contents);
+ const pageNum = props.index + 1;
useEffect(()=>{
if(!pageRef.current) return;
- // Observer for tracking pages within the `.pages` div
+ // Observer for tracking which pages are at least 30% visible in the iframe
const visibleObserver = new IntersectionObserver(
- (entries)=>{
- entries.forEach((entry)=>{
- if(entry.isIntersecting)
- props.onVisibilityChange(props.index + 1, true, false); // add page to array of visible pages.
- else
- props.onVisibilityChange(props.index + 1, false, false);
- });
- },
+ (entries)=>entries.forEach((entry)=>{
+ props.onVisibilityChange(pageNum, entry.isIntersecting, false); // add/remove page from array of visible pages.
+ }),
{ threshold: .3, rootMargin: '0px 0px 0px 0px' } // detect when >30% of page is within bounds.
);
// Observer for tracking the page at the center of the iframe.
const centerObserver = new IntersectionObserver(
- (entries)=>{
- entries.forEach((entry)=>{
- if(entry.isIntersecting)
- props.onVisibilityChange(props.index + 1, true, true); // Set this page as the center page
- });
- },
+ (entries)=>entries.forEach((entry)=>{
+ if(entry.isIntersecting)
+ props.onVisibilityChange(pageNum, true, true); // Set this page as the center page
+ }),
{ threshold: 0, rootMargin: '-50% 0px -50% 0px' } // Detect when the page is at the center
);
@@ -92,7 +85,7 @@ const BrewPage = (props)=>{
//v=====--------------------< Brew Renderer Component >-------------------=====v//
let renderedPages = [];
-let pageTemplates = [];
+const pageTemplates = [];
let rawPages = [];
const BrewRenderer = (props)=>{
@@ -100,22 +93,24 @@ const BrewRenderer = (props)=>{
text : '',
style : '',
renderer : 'legacy',
- theme : '5ePHB',
lang : '',
errors : [],
currentEditorCursorPageNum : 1,
- currentEditorViewPageNum : 1,
currentBrewRendererPageNum : 1,
themeBundle : {},
onPageChange : ()=>{},
...props
};
+ const pagesRef = useRef(null);
+
+ const [visiblePages, setVisiblePages] = useState([]);
+ const [centerPage , setCenterPage ] = useState(1);
+ const [headerState , setHeaderState ] = useState(false);
+
const [state, setState] = useState({
- isMounted : false,
- visibility : 'hidden',
- visiblePages : [],
- centerPage : 1
+ isMounted : false,
+ visibility : 'hidden'
});
const [displayOptions, setDisplayOptions] = useState({
@@ -133,12 +128,6 @@ const BrewRenderer = (props)=>{
toolbarState && setDisplayOptions(toolbarState);
}, []);
- const [headerState, setHeaderState] = useState(false);
-
- const mainRef = useRef(null);
- const pagesRef = useRef(null);
- const urlRef = useRef('');
-
if(props.renderer == 'legacy') {
rawPages = props.text.split(PAGEBREAK_REGEX_LEGACY);
} else {
@@ -146,20 +135,16 @@ const BrewRenderer = (props)=>{
}
const handlePageVisibilityChange = (pageNum, isVisible, isCenter)=>{
- setState((prevState)=>{
- const updatedVisiblePages = new Set(prevState.visiblePages);
- if(!isCenter)
- isVisible ? updatedVisiblePages.add(pageNum) : updatedVisiblePages.delete(pageNum);
-
- return {
- ...prevState,
- visiblePages : [...updatedVisiblePages].sort((a, b)=>a - b),
- centerPage : isCenter ? pageNum : prevState.centerPage
- };
+ setVisiblePages((prev)=>{
+ const updatedVisiblePages = new Set(prev);
+ isVisible ? updatedVisiblePages.add(pageNum) : updatedVisiblePages.delete(pageNum);
+ return [...updatedVisiblePages].sort((a, b)=>a - b);
});
- if(isCenter)
+ if(isCenter) {
+ setCenterPage(pageNum);
props.onPageChange(pageNum);
+ }
};
const isInView = (index)=>{
@@ -327,7 +312,7 @@ const BrewRenderer = (props)=>{
};
const renderedStyle = useMemo(()=>renderStyle(), [props.style, props.themeBundle]);
- renderedPages = useMemo(()=>renderPages(), [props.text, displayOptions]);
+ renderedPages = useMemo(()=>renderPages(), [props.text, centerPage, displayOptions]);
return (
<>
@@ -341,19 +326,19 @@ const BrewRenderer = (props)=>{
: null}
${text}`;
- 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 - ';
-
- const encodeRFC3986ValueChars = (str)=>{
- return (
- encodeURIComponent(str)
- .replace(/[!'()*]/g, (char)=>{`%${char.charCodeAt(0).toString(16).toUpperCase()}`;})
- );
- };
-
- 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*=UTF-8''${encodeRFC3986ValueChars(fileName)}.txt`
- });
- res.status(200).send(brew.text);
- });
+ brew.authors.includes(req.account?.username)
+ ? sanitizeBrew(brew, 'shareAuthor')
+ : sanitizeBrew(brew, 'share');
+ splitTextStyleAndMetadata(brew);
+ res.json({ brew });
+ }));
//Serve brew metadata
app.get('/metadata/:id', asyncHandler(getBrew('share')), (req, res)=>{
@@ -280,78 +166,6 @@ export default async function createApp(vite) {
//Serve brew styling
app.get('/css/:id', asyncHandler(getBrew('share')), (req, res)=>{getCSS(req, res);});
- //User Page
- app.get('/user/:username', dbCheck, async (req, res, next)=>{
- const ownAccount = req.account && (req.account.username == req.params.username);
-
- req.ogMeta = { ...defaultMetaTags,
- title : `${req.params.username}'s Collection`,
- description : 'View my collection of homebrew on the Homebrewery.'
- // type : could be 'profile'?
- };
-
- const fields = [
- 'googleId',
- 'title',
- 'pageCount',
- 'description',
- 'authors',
- 'lang',
- 'published',
- 'views',
- 'shareId',
- 'editId',
- 'createdAt',
- 'updatedAt',
- 'lastViewed',
- 'thumbnail',
- 'tags'
- ];
-
- let brews = await HomebrewModel.getByUser(req.params.username, ownAccount, fields)
- .catch((err)=>{
- console.log(err);
- });
-
- brews.forEach((brew)=>brew.stubbed = true); //All brews from MongoDB are "stubbed"
-
- 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 stub matches file from Google, use Google metadata over stub metadata
- 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.pageCount = googleBrews[match].pageCount;
- brew.renderer = googleBrews[match].renderer;
- brew.version = googleBrews[match].version;
- brew.webViewLink = googleBrews[match].webViewLink;
- googleBrews.splice(match, 1);
- }
- }
-
- //Remaining unstubbed google brews display current user as author
- googleBrews = googleBrews.map((brew)=>({ ...brew, authors: [req.account.username] }));
- brews = _.concat(brews, googleBrews);
- }
- }
-
- req.brews = _.map(brews, (brew)=>{
- // Clean up brew data
- brew.title = brew.title?.trim();
- brew.description = brew.description?.trim();
- return sanitizeBrew(brew, ownAccount ? 'edit' : 'share');
- });
-
- return next();
- });
-
//Change author name on brews
app.put('/api/user/rename', dbCheck, async (req, res)=>{
const { username, newUsername } = req.body;
@@ -412,143 +226,26 @@ export default async function createApp(vite) {
}
});
- //Edit Page
- app.get('/edit/:id', asyncHandler(getBrew('edit')), asyncHandler(async(req, res, next)=>{
- req.brew = req.brew.toObject ? req.brew.toObject() : req.brew;
+ // Create Event Stream source for pages to listen to
+ app.get('/stream', (req, res)=>{
+ res.writeHead(200, {
+ 'Content-Type' : 'text/event-stream',
+ 'Cache-Control' : 'no-cache',
+ 'Connection' : 'keep-alive',
+ 'Content-Encoding' : 'none'
+ });
- req.userThemes = await(getUsersBrewThemes(req.account?.username));
+ Stream.on('sendUpdate', (event, data)=>{
+ console.log('Event:', event, '\nData:', data);
+ res.write(`data: ${JSON.stringify({ ...data, eventType: event })}\n\n`);
+ });
+ });
- req.ogMeta = { ...defaultMetaTags,
- title : req.brew.title || 'Untitled Brew',
- description : req.brew.description || 'No description.',
- image : req.brew.thumbnail || defaultMetaTags.image,
- locale : req.brew.lang,
- type : 'article'
- };
-
- 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 from ID
- app.get('/new/:id', asyncHandler(getBrew('share')), asyncHandler(async(req, res, next)=>{
- sanitizeBrew(req.brew, 'share');
- splitTextStyleAndMetadata(req.brew);
- const brew = {
- shareId : req.brew.shareId,
- title : `CLONE - ${req.brew.title}`,
- text : req.brew.text,
- style : req.brew.style,
- renderer : req.brew.renderer,
- theme : req.brew.theme,
- tags : req.brew.tags,
- snippets : req.brew.snippets
- };
- req.brew = _.defaults(brew, DEFAULT_BREW);
-
- req.userThemes = await(getUsersBrewThemes(req.account?.username));
-
- req.ogMeta = { ...defaultMetaTags,
- title : 'New',
- description : 'Start crafting your homebrew on the Homebrewery!'
- };
-
- return next();
- }));
-
- //New Page
- app.get('/new', asyncHandler(async(req, res, next)=>{
- req.userThemes = await(getUsersBrewThemes(req.account?.username));
-
- req.ogMeta = { ...defaultMetaTags,
- title : 'New',
- description : 'Start crafting your homebrew on the Homebrewery!'
- };
-
- return next();
- }));
-
- //Share Page
- app.get('/share/:id', dbCheck, asyncHandler(getBrew('share')), asyncHandler(async (req, res, next)=>{
- const { brew } = req;
- req.ogMeta = { ...defaultMetaTags,
- title : `${req.brew.title || 'Untitled Brew'} - ${req.brew.authors[0] || 'No author.'}`,
- description : req.brew.description || 'No description.',
- image : req.brew.thumbnail || defaultMetaTags.image,
- type : 'article'
- };
-
- // increase visitor view count, do not include visits by author(s)
- if(!brew.authors.includes(req.account?.username)){
- if(req.params.id.length > 12 && !brew._id) {
- const googleId = brew.googleId;
- const shareId = brew.shareId;
- await GoogleActions.increaseView(googleId, shareId, 'share', brew)
- .catch((err)=>{next(err);});
- } else {
- await HomebrewModel.increaseView({ shareId: brew.shareId });
- }
- };
-
- brew.authors.includes(req.account?.username) ? sanitizeBrew(req.brew, 'shareAuthor') : sanitizeBrew(req.brew, 'share');
- splitTextStyleAndMetadata(req.brew);
- return next();
- }));
-
- //Account Page
- app.get('/account', dbCheck, asyncHandler(async (req, res, next)=>{
- const data = {};
- data.title = 'Account Information Page';
-
- if(!req.account) {
- res.set('WWW-Authenticate', 'Bearer realm="Authorization Required"');
- const error = new Error('No valid account');
- error.status = 401;
- error.HBErrorCode = '50';
- error.page = data.title;
- return next(error);
- };
-
- let auth;
- let googleCount = [];
- if(req.account) {
- if(req.account.googleId) {
- auth = await GoogleActions.authCheck(req.account, res, false);
-
- googleCount = await GoogleActions.listGoogleBrews(auth)
- .catch((err)=>{
- console.error(err);
- });
- }
-
- const query = { authors: req.account.username, googleId: { $exists: false } };
- const mongoCount = await HomebrewModel.countDocuments(query)
- .catch((err)=>{
- console.log(err);
- return 0;
- });
-
- data.accountDetails = {
- username : req.account.username,
- issued : req.account.issued,
- googleId : Boolean(req.account.googleId),
- authCheck : Boolean(req.account.googleId && auth?.credentials.access_token),
- mongoCount : mongoCount,
- googleCount : googleCount?.length
- };
- }
-
- req.brew = data;
-
- req.ogMeta = { ...defaultMetaTags,
- title : `Account Page`,
- description : null
- };
-
- return next();
- }));
+ // After Stream starts, send initStream event
+ setTimeout(()=>{
+ Stream.emit('sendUpdate', 'initStream', { time: new Date });
+ }, 1000);
+
// Local only
if(isLocalEnvironment){
@@ -566,15 +263,6 @@ export default async function createApp(vite) {
app.use('/staticImages', express.static(config.get('hb_images') && fs.existsSync(config.get('hb_images')) ? config.get('hb_images') :'staticImages'));
app.use('/staticFonts', express.static(config.get('hb_fonts') && fs.existsSync(config.get('hb_fonts')) ? config.get('hb_fonts'):'staticFonts'));
- //Vault Page
- app.get('/vault', asyncHandler(async(req, res, next)=>{
- req.ogMeta = { ...defaultMetaTags,
- title : 'The Vault',
- description : 'Search for Brews'
- };
- return next();
- }));
-
//Send rendered page
app.use(asyncHandler(async (req, res, next)=>{
if(!req.route) return res.redirect('/'); // Catch-all for invalid routes
diff --git a/server/eventStreamSource.js b/server/eventStreamSource.js
new file mode 100644
index 000000000..66fdb3354
--- /dev/null
+++ b/server/eventStreamSource.js
@@ -0,0 +1,9 @@
+import { EventEmitter } from 'events';
+
+const Stream = new EventEmitter;
+
+export default {
+ emit : function(event) {return Stream.emit(event, ...([...arguments].slice(1)));}, // Arguments doesn't work for arrow functions
+ on : (event, listener)=>{return Stream.on(event, listener);},
+ off : (event, listener)=>{return Stream.off(event, listener);}
+};
\ No newline at end of file
diff --git a/server/homebrew.api.js b/server/homebrew.api.js
index 0321bf919..4cf9f1fc1 100644
--- a/server/homebrew.api.js
+++ b/server/homebrew.api.js
@@ -4,7 +4,7 @@ import { model as HomebrewModel } from './homebrew.model.js';
import express from 'express';
import zlib from 'zlib';
import GoogleActions from './googleActions.js';
-import { hbfm } from 'hbmarkedwrapper';
+import { hbfm } from 'marked-hbfm';
import * as yaml from 'js-yaml';
import asyncHandler from 'express-async-handler';
import { nanoid } from 'nanoid';
@@ -21,6 +21,8 @@ const router = express.Router();
import { DEFAULT_BREW, DEFAULT_BREW_LOAD } from './brewDefaults.js';
import Themes from '../themes/themes.json' with { type: 'json' };
+import Stream from './eventStreamSource.js';
+
const isStaticTheme = (renderer, themeName)=>{
return Themes[renderer]?.[themeName] !== undefined;
};
@@ -168,8 +170,7 @@ const api = {
const googleBrew = await GoogleActions.getGoogleBrew(oAuth2Client, googleId, id, accessType)
.catch((googleError)=>{
- const reason = googleError.errors?.[0].reason;
- if(reason == 'notFound')
+ if(googleError.code === 404 || googleError.status === 404)
throw { ...googleError, HBErrorCode: '02', authors: stub?.authors, account: req.account?.username };
else
throw { ...googleError, HBErrorCode: '01' };
@@ -501,6 +502,8 @@ const api = {
saved.textBin = undefined; // Remove textBin from the saved object to save bandwidth
+ Stream.emit('sendUpdate', 'brewUpdated', { time: new Date, shareId: brew.shareId, version: brew.version });
+
res.status(200).send(saved);
},
deleteGoogleBrew : async (account, id, editId, res)=>{
@@ -616,9 +619,9 @@ const api = {
router.use(dbCheck);
router.post('/api', checkClientVersion, asyncHandler(api.newBrew));
-router.put('/api/:id', checkClientVersion, asyncHandler(api.getBrew('edit', false)), asyncHandler(api.updateBrew));
+router.put('/api/:id', checkClientVersion, asyncHandler(api.getBrew('edit', false)), asyncHandler(api.updateBrew)); //alt endpoint, unused
router.put('/api/update/:id', checkClientVersion, asyncHandler(api.getBrew('edit', false)), asyncHandler(api.updateBrew));
-router.delete('/api/:id', checkClientVersion, asyncHandler(api.deleteBrew));
+router.delete('/api/:id', checkClientVersion, asyncHandler(api.deleteBrew)); //alt endpoint, unused
router.get('/api/remove/:id', checkClientVersion, asyncHandler(api.deleteBrew));
router.get('/api/theme/:renderer/:id', asyncHandler(api.getThemeBundle));
diff --git a/server/page-routes.js b/server/page-routes.js
new file mode 100644
index 000000000..e2e7be193
--- /dev/null
+++ b/server/page-routes.js
@@ -0,0 +1,380 @@
+/*eslint max-lines: ["warn", {"max": 300, "skipBlankLines": true, "skipComments": true}]*/
+// page-routes.js
+
+import { dirname } from 'path';
+import { fileURLToPath } from 'url';
+const __dirname = dirname(fileURLToPath(import.meta.url));
+process.chdir(`${__dirname}/..`);
+
+import _ from 'lodash';
+import express from 'express';
+import asyncHandler from 'express-async-handler';
+import fs from 'fs';
+
+//==== Middleware Imports ====//
+import dbCheck from './middleware/dbCheck.js';
+import sanitizeFilename from 'sanitize-filename';
+import { DEFAULT_BREW } from './brewDefaults.js';
+import { splitTextStyleAndMetadata } from '../shared/helpers.js';
+import GoogleActions from './googleActions.js';
+
+import api from './homebrew.api.js';
+const { getBrew, getUsersBrewThemes } = api;
+
+const welcomeText = fs.readFileSync('./client/homebrew/pages/homePage/welcome_msg.md', 'utf8');
+const welcomeTextLegacy = fs.readFileSync('./client/homebrew/pages/homePage/welcome_msg_legacy.md', 'utf8');
+const migrateText = fs.readFileSync('./client/homebrew/pages/homePage/migrate.md', 'utf8');
+const changelogText = fs.readFileSync('changelog.md', 'utf8');
+const faqText = fs.readFileSync('faq.md', 'utf8');
+
+export default function pageRoutes({
+ defaultMetaTags,
+ HomebrewModel,
+ sanitizeBrew,
+}) {
+ const app = express.Router();
+
+ //Home page
+ app.get('/', (req, res, next)=>{
+ req.brew = {
+ text : welcomeText,
+ renderer : 'V3',
+ theme : '5ePHB'
+ },
+
+ req.ogMeta = { ...defaultMetaTags,
+ title : 'Homepage',
+ description : 'Homepage'
+ };
+
+ splitTextStyleAndMetadata(req.brew);
+ return next();
+ });
+
+ //Home page Legacy
+ app.get('/legacy', (req, res, next)=>{
+ req.brew = {
+ text : welcomeTextLegacy,
+ renderer : 'legacy',
+ theme : '5ePHB'
+ },
+
+ req.ogMeta = { ...defaultMetaTags,
+ title : 'Homepage (Legacy)',
+ description : 'Homepage'
+ };
+
+ splitTextStyleAndMetadata(req.brew);
+ return next();
+ });
+
+ //Legacy/Other Document -> v3 Migration Guide
+ app.get('/migrate', (req, res, next)=>{
+ req.brew = {
+ text : migrateText,
+ renderer : 'V3',
+ theme : '5ePHB'
+ },
+
+ req.ogMeta = { ...defaultMetaTags,
+ title : 'v3 Migration Guide',
+ description : 'A brief guide to converting Legacy documents to the v3 renderer.'
+ };
+
+ splitTextStyleAndMetadata(req.brew);
+ return next();
+ });
+
+ //Changelog page
+ app.get('/changelog', async (req, res, next)=>{
+ req.brew = {
+ title : 'Changelog',
+ text : changelogText,
+ renderer : 'V3',
+ theme : '5ePHB'
+ },
+
+ req.ogMeta = { ...defaultMetaTags,
+ title : 'Changelog',
+ description : 'Development changelog.'
+ };
+
+ splitTextStyleAndMetadata(req.brew);
+ return next();
+ });
+
+ //FAQ page
+ app.get('/faq', async (req, res, next)=>{
+ req.brew = {
+ title : 'FAQ',
+ text : faqText,
+ renderer : 'V3',
+ theme : '5ePHB'
+ },
+
+ req.ogMeta = { ...defaultMetaTags,
+ title : 'FAQ',
+ description : 'Frequently Asked Questions'
+ };
+
+ 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 = `${text}`;
+ 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 - ';
+
+ const encodeRFC3986ValueChars = (str)=>{
+ return (
+ encodeURIComponent(str)
+ .replace(/[!'()*]/g, (char)=>{`%${char.charCodeAt(0).toString(16).toUpperCase()}`;})
+ );
+ };
+
+ 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*=UTF-8''${encodeRFC3986ValueChars(fileName)}.txt`
+ });
+ res.status(200).send(brew.text);
+ });
+
+ //User Page
+ app.get('/user/:username', dbCheck, async (req, res, next)=>{
+ const ownAccount = req.account && (req.account.username == req.params.username);
+
+ req.ogMeta = { ...defaultMetaTags,
+ title : `${req.params.username}'s Collection`,
+ description : 'View my collection of homebrew on the Homebrewery.'
+ // type : could be 'profile'?
+ };
+
+ const fields = [
+ 'googleId',
+ 'title',
+ 'pageCount',
+ 'description',
+ 'authors',
+ 'lang',
+ 'published',
+ 'views',
+ 'shareId',
+ 'editId',
+ 'createdAt',
+ 'updatedAt',
+ 'lastViewed',
+ 'thumbnail',
+ 'tags'
+ ];
+
+ let brews = await HomebrewModel.getByUser(req.params.username, ownAccount, fields)
+ .catch((err)=>{
+ console.log(err);
+ });
+
+ brews.forEach((brew)=>brew.stubbed = true); //All brews from MongoDB are "stubbed"
+
+ 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 stub matches file from Google, use Google metadata over stub metadata
+ 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.pageCount = googleBrews[match].pageCount;
+ brew.renderer = googleBrews[match].renderer;
+ brew.version = googleBrews[match].version;
+ brew.webViewLink = googleBrews[match].webViewLink;
+ googleBrews.splice(match, 1);
+ }
+ }
+
+ //Remaining unstubbed google brews display current user as author
+ googleBrews = googleBrews.map((brew)=>({ ...brew, authors: [req.account.username] }));
+ brews = _.concat(brews, googleBrews);
+ }
+ }
+
+ req.brews = _.map(brews, (brew)=>{
+ // Clean up brew data
+ brew.title = brew.title?.trim();
+ brew.description = brew.description?.trim();
+ return sanitizeBrew(brew, ownAccount ? 'edit' : 'share');
+ });
+
+ return next();
+ });
+
+ //Edit Page
+ app.get('/edit/:id', asyncHandler(getBrew('edit')), asyncHandler(async(req, res, next)=>{
+ req.brew = req.brew.toObject ? req.brew.toObject() : req.brew;
+
+ req.userThemes = await(getUsersBrewThemes(req.account?.username));
+
+ req.ogMeta = { ...defaultMetaTags,
+ title : req.brew.title || 'Untitled Brew',
+ description : req.brew.description || 'No description.',
+ image : req.brew.thumbnail || defaultMetaTags.image,
+ locale : req.brew.lang,
+ type : 'article'
+ };
+
+ 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 from ID
+ app.get('/new/:id', asyncHandler(getBrew('share')), asyncHandler(async(req, res, next)=>{
+ sanitizeBrew(req.brew, 'share');
+ splitTextStyleAndMetadata(req.brew);
+ const brew = {
+ shareId : req.brew.shareId,
+ title : `CLONE - ${req.brew.title}`,
+ text : req.brew.text,
+ style : req.brew.style,
+ renderer : req.brew.renderer,
+ theme : req.brew.theme,
+ tags : req.brew.tags,
+ snippets : req.brew.snippets
+ };
+ req.brew = _.defaults(brew, DEFAULT_BREW);
+
+ req.userThemes = await(getUsersBrewThemes(req.account?.username));
+
+ req.ogMeta = { ...defaultMetaTags,
+ title : 'New',
+ description : 'Start crafting your homebrew on the Homebrewery!'
+ };
+
+ return next();
+ }));
+
+ //New Page
+ app.get('/new', asyncHandler(async(req, res, next)=>{
+ req.userThemes = await(getUsersBrewThemes(req.account?.username));
+
+ req.ogMeta = { ...defaultMetaTags,
+ title : 'New',
+ description : 'Start crafting your homebrew on the Homebrewery!'
+ };
+
+ return next();
+ }));
+
+ //Share Page
+ app.get('/share/:id', dbCheck, asyncHandler(getBrew('share')), asyncHandler(async (req, res, next)=>{
+ const { brew } = req;
+ req.ogMeta = { ...defaultMetaTags,
+ title : `${req.brew.title || 'Untitled Brew'} - ${req.brew.authors[0] || 'No author.'}`,
+ description : req.brew.description || 'No description.',
+ image : req.brew.thumbnail || defaultMetaTags.image,
+ type : 'article'
+ };
+
+ // increase visitor view count, do not include visits by author(s)
+ if(!brew.authors.includes(req.account?.username)){
+ if(req.params.id.length > 12 && !brew._id) {
+ const googleId = brew.googleId;
+ const shareId = brew.shareId;
+ await GoogleActions.increaseView(googleId, shareId, 'share', brew)
+ .catch((err)=>{next(err);});
+ } else {
+ await HomebrewModel.increaseView({ shareId: brew.shareId });
+ }
+ };
+
+ brew.authors.includes(req.account?.username) ? sanitizeBrew(req.brew, 'shareAuthor') : sanitizeBrew(req.brew, 'share');
+ splitTextStyleAndMetadata(req.brew);
+ return next();
+ }));
+
+ //Account Page
+ app.get('/account', dbCheck, asyncHandler(async (req, res, next)=>{
+ const data = {};
+ data.title = 'Account Information Page';
+
+ if(!req.account) {
+ res.set('WWW-Authenticate', 'Bearer realm="Authorization Required"');
+ const error = new Error('No valid account');
+ error.status = 401;
+ error.HBErrorCode = '50';
+ error.page = data.title;
+ return next(error);
+ };
+
+ let auth;
+ let googleCount = [];
+ if(req.account) {
+ if(req.account.googleId) {
+ auth = await GoogleActions.authCheck(req.account, res, false);
+
+ googleCount = await GoogleActions.listGoogleBrews(auth)
+ .catch((err)=>{
+ console.error(err);
+ });
+ }
+
+ const query = { authors: req.account.username, googleId: { $exists: false } };
+ const mongoCount = await HomebrewModel.countDocuments(query)
+ .catch((err)=>{
+ console.log(err);
+ return 0;
+ });
+
+ data.accountDetails = {
+ username : req.account.username,
+ issued : req.account.issued,
+ googleId : Boolean(req.account.googleId),
+ authCheck : Boolean(req.account.googleId && auth?.credentials.access_token),
+ mongoCount : mongoCount,
+ googleCount : googleCount?.length
+ };
+ }
+
+ req.brew = data;
+
+ req.ogMeta = { ...defaultMetaTags,
+ title : `Account Page`,
+ description : null
+ };
+
+ return next();
+ }));
+
+ //Vault Page
+ app.get('/vault', asyncHandler(async(req, res, next)=>{
+ req.ogMeta = { ...defaultMetaTags,
+ title : 'The Vault',
+ description : 'Search for Brews'
+ };
+ return next();
+ }));
+
+ return app;
+}
\ No newline at end of file
diff --git a/shared/helpers.js b/shared/helpers.js
index db046b810..d20687843 100644
--- a/shared/helpers.js
+++ b/shared/helpers.js
@@ -229,5 +229,6 @@ export {
printCurrentBrew,
fetchThemeBundle,
brewSnippetsToJSON,
- debugTextMismatch
+ debugTextMismatch,
+ yamlSnippetsToText
};
diff --git a/tests/html/helpers.test.js b/tests/html/helpers.test.js
new file mode 100644
index 000000000..a81a62173
--- /dev/null
+++ b/tests/html/helpers.test.js
@@ -0,0 +1,114 @@
+import {
+ fetchThemeBundle,
+ brewSnippetsToJSON,
+ debugTextMismatch,
+ yamlSnippetsToText,
+} from '../../shared/helpers.js';
+
+import dedent from 'dedent';
+
+// Marked.js adds line returns after closing tags on some default tokens.
+// This removes those line returns for comparison sake.
+String.prototype.trimReturns = function(){
+ return this.replace(/\r?\n|\r/g, '');
+};
+
+const emoji = 'df_d12_2';
+
+const brewSnippetsThemeTest = [
+ {
+ name : 'Test Theme',
+ snippets : dedent `
+ \snippet First Theme Snippet
+ I am the first theme snippet!
+
+ \snippet Second Theme Snippet
+ I am the second theme Snippet!`,
+ }
+];
+
+const brewSnippetsBrewTest = dedent`
+ \snippet First Brew Snippet
+ I am the first brew snippet!
+
+ \snippet Second Brew Snippet
+ I am the second brew Snippet!`;
+
+describe(`brewSnippetsToJSON`, ()=>{
+ it('converts raw brew snippets without theme snippets to JSON', function() {
+ const testMenuObject = {
+ groupName : 'Brew Snippets',
+ icon : 'fas fa-th-list',
+ view : 'text',
+ snippets : [{
+ name : 'Test Snippets JSON without theme snippets',
+ subsnippets : [
+ {
+ gen : 'I am the first brew snippet!\n',
+ name : 'First Brew Snippet'
+ }, {
+ gen : 'I am the second brew Snippet!',
+ name: 'Second Brew Snippet'
+ }
+ ]}]
+ };
+ const rendered = brewSnippetsToJSON(`Test Snippets JSON without theme snippets`, brewSnippetsBrewTest, null, true);
+ expect(rendered).toStrictEqual(testMenuObject);
+ });
+
+ it('converts raw brew snippets with theme snippets to JSON', function() {
+ const testMenuObject = {
+ groupName : 'Brew Snippets',
+ icon : 'fas fa-th-list',
+ view : 'text',
+ snippets : [{
+ gen : '',
+ icon : '',
+ name : 'Test Theme',
+ subsnippets : [
+ {
+ gen : 'I am the first theme snippet!\n',
+ icon : '',
+ name : 'First Theme Snippet',
+ },
+ {
+ gen : 'I am the second theme Snippet!',
+ icon : '',
+ name : 'Second Theme Snippet',
+ },
+ ]},
+ {
+ name : 'Test Snippets JSON with theme snippets',
+ subsnippets : [
+ {
+ gen : 'I am the first brew snippet!\n',
+ name : 'First Brew Snippet'
+ },
+ {
+ gen : 'I am the second brew Snippet!',
+ name: 'Second Brew Snippet'
+ }
+ ]
+ }]};
+ const rendered = brewSnippetsToJSON(`Test Snippets JSON with theme snippets`, brewSnippetsBrewTest, brewSnippetsThemeTest, true);
+ expect(rendered).toStrictEqual(testMenuObject);
+ });
+});
+
+describe(`YAMLSnippetsToText`, ()=>{
+ it('converts brew snippet YAML to a string ', function() {
+ const brewSnippetsYAML = [{
+ subsnippets : [
+ {
+ gen : 'I am the first brew snippet!\n',
+ name : 'First Brew Snippet'
+ }, {
+ gen : 'I am the second brew Snippet!',
+ name: 'Second Brew Snippet'
+ }
+ ]
+ }];
+ const rendered = yamlSnippetsToText(brewSnippetsYAML);
+ expect(rendered).toBe(`${brewSnippetsBrewTest}\n`);
+ });
+});
\ No newline at end of file
diff --git a/tests/markdown/basic.test.js b/tests/markdown/basic.test.js
index a01c032fd..8e395f3b0 100644
--- a/tests/markdown/basic.test.js
+++ b/tests/markdown/basic.test.js
@@ -1,6 +1,6 @@
-import { hbfm } from 'hbmarkedwrapper';
+import { hbfm } from 'marked-hbfm';
test('Processes the markdown within an HTML block if its just a class wrapper', function() {
const source = '