0
0
mirror of https://github.com/naturalcrit/homebrewery.git synced 2026-01-26 22:43:07 +00:00

Compare commits

..

1 Commits

Author SHA1 Message Date
Trevor Buckner
7c49088656 Move Themes/styles into iFrame Head 2024-10-16 00:04:49 -04:00
115 changed files with 4407 additions and 5371 deletions

View File

@@ -70,30 +70,15 @@ jobs:
- run: - run:
name: Test - Hard Breaks name: Test - Hard Breaks
command: npm run test:hard-breaks command: npm run test:hard-breaks
- run:
name: Test - Non-Breaking Spaces
command: npm run test:non-breaking-spaces
- run:
name: Test - Paragraph Justification
command: npm run test:paragraph-justification
- run: - run:
name: Test - Variables name: Test - Variables
command: npm run test:variables command: npm run test:variables
- run:
name: Test - Emojis
command: npm run test:emojis
- run: - run:
name: Test - Routes name: Test - Routes
command: npm run test:route command: npm run test:route
- run:
name: Test - HTML sanitization
command: npm run test:safehtml
- run: - run:
name: Test - Coverage name: Test - Coverage
command: npm run test:coverage command: npm run test:coverage
- run:
name: Test - Content Negotiation
command: npm run test:content-negotiation
workflows: workflows:
build_and_test: build_and_test:

View File

@@ -1,29 +1,26 @@
> [!TIP] <!--
> Before submitting a Pull Request, please consider the following to speed up reviews: Before submitting a Pull Request, please consider the following to speed up reviews:
> - 👷‍♀️ Create small PRs. Large PRs can usually be broken down into incremental PRs. - 👷‍♀️ Create small PRs. Large PRs can usually be broken down into incremental PRs.
> - 🚩 Do you already have several open PRs? Consider finishing or asking for help with existing PRs first. - 🚩 Do you already have several open PRs? Consider finishing or asking for help with existing PRs first.
> - 🔧 Does your PR reference a discussed and approved issue, especially for personal or edge-case requests? - 🔧 Does your PR reference a discussed and approved issue, especially for personal or edge-case requests?
> - 💡 Is the solution agreed upon? Save rework time by discussing strategy before coding. - 💡 Is the solution agreed upon? Save rework time by discussing strategy before coding.
-->
## Description ## Description
_Describe what your PR accomplishes. Consider walking through the main changes to aid reviewers in following your code, especially if it covers multiple files._
## Related Issues or Discussions ## Related Issues or Discussions
> [!CAUTION]
> If no issue exists yet, create it, and get agreement on the approach (or paste in a previous agreement from chat, etc.) before moving forward. (Experimental PRs are OK without prior discussion, but do not expect to get merged.)
- Closes # - Closes #
## QA Instructions, Screenshots, Recordings ## QA Instructions, Screenshots, Recordings
_Replace this line with instructions on how to test or view your changes, as well as any before/after _Please replace this line with instructions on how to test or view your changes, as well as any before/after
screenshots or recordings for UI changes._ images for UI changes._
### Reviewer Checklist ### Reviewer Checklist
_Replace the list below with specific features you want reviewers to look at._ _Please replace the list below with specific features you want reviewers to look at._
*Reviewers, refer to this list when testing features, or suggest new items * *Reviewers, refer to this list when testing features, or suggest new items *
- [ ] Verify new features are functional - [ ] Verify new features are functional
@@ -35,3 +32,5 @@ _Replace the list below with specific features you want reviewers to look at._
- [ ] Feature A handles negative numbers - [ ] Feature A handles negative numbers
- [ ] Identify opportunities for simplification and refactoring - [ ] Identify opportunities for simplification and refactoring
- [ ] Check for code legibility and appropriate comments - [ ] Check for code legibility and appropriate comments
<details><summary>Copy this list</summary>

View File

@@ -1,4 +1,4 @@
FROM node:22-alpine FROM node:20-alpine
RUN apk --no-cache add git RUN apk --no-cache add git
ENV NODE_ENV=docker ENV NODE_ENV=docker
@@ -9,10 +9,7 @@ WORKDIR /usr/src/app
# Copy package.json into the image, then run yarn install # Copy package.json into the image, then run yarn install
# This improves caching so we don't have to download the dependencies every time the code changes # This improves caching so we don't have to download the dependencies every time the code changes
COPY package.json ./ COPY package.json ./
COPY config/docker.json usr/src/app/config
# --ignore-scripts tells yarn not to run postbuild. We run it explicitly later # --ignore-scripts tells yarn not to run postbuild. We run it explicitly later
RUN node --version
RUN npm --version
RUN npm install --ignore-scripts RUN npm install --ignore-scripts
# Bundle app source and build application # Bundle app source and build application

View File

@@ -1,119 +1,12 @@
# Offline Install Instructions: Docker # Running Homebrewery via Docker
These instructions are for setting up a persistent instance of the Homebrewery application locally using Docker. The repo includes a Dockerfile and a docker-compose.yml file.
If you intend to develop with Homebrewery, following the Homebrewery application section of this guide is not recommended. Using docker to deploy MongoDB locally for development is not a bad idea at all, however. To run the application via docker-compose.yml:
`docker-compose up -d`
# Install Docker To stop the application:
`docker-compose down`
## Docker Desktop (MacOS/Windows)
Windows and Mac installs use Docker Desktop. Current install instructions are below.
* [Mac](https://docs.docker.com/desktop/mac/install/)
* [Windows](https://docs.docker.com/desktop/windows/install/)
You can set up the docker engine to start on boot via the Docker desktop UI.
## Docker Engine
Linux installs use Docker Engine. Docker provides installers and instructions for several of the most common distrubutions. If you do not see yours listed, it is very likely supported indirectly by your distribution.
* [Arch](https://docs.docker.com/desktop/setup/install/linux/archlinux/)
* [CentOS](https://docs.docker.com/engine/install/centos/)
* [Debian](https://docs.docker.com/engine/install/debian/)
* [Fedora](https://docs.docker.com/engine/install/fedora/)
* [RHEL](https://docs.docker.com/engine/install/rhel/)
* [Ubuntu](https://docs.docker.com/engine/install/ubuntu/)
### Post installation steps
[Manage Docker as a non-root user (highly recommended)](https://docs.docker.com/engine/install/linux-postinstall/#manage-docker-as-a-non-root-user)
[Enable Docker to start on boot (highly recommended)](https://docs.docker.com/engine/install/linux-postinstall/#configure-docker-to-start-on-boot)
# Build Homebrewery Image
Next we build the homebrewery docker image. Start by cloning the repository.
```shell
git clone https://github.com/naturalcrit/homebrewery.git
cd homebrewery
```
Make an changes you need to `config/docker.json` then build the image. If it does not exist,the below as a template.
```
{
"host" : "localhost:8000",
"naturalcrit_url" : "local.naturalcrit.com:8010",
"secret" : "secret",
"web_port" : 8000,
"enable_v3" : true,
"mongodb_uri": "mongodb://172.17.0.2/homebrewery",
"enable_themes" : true,
}
```
```shell
docker-compose build homebrewery
```
# Add Mongo container
Once docker is installed and running, it is time to set up the containers. First up, Mongo.
```shell
docker run --name homebrewery-mongodb -d --restart unless-stopped -v mongodata:/data/db -p 27017:27017 mongo:latest
```
Older CPUs may run into an issue with AVX support.
```
WARNING: MongoDB 5.0+ requires a CPU with AVX support, and your current system does not appear to have that!
see https://jira.mongodb.org/browse/SERVER-54407
see also https://www.mongodb.com/community/forums/t/mongodb-5-0-cpu-intel-g4650-compatibility/116610/2
see also https://github.com/docker-library/mongo/issues/485#issuecomment-891991814
```
If you see a message similar to this, try using the bitnami mongo instead.
```shell
docker run --name homebrewery-mongodb -d --restart unless-stopped -v mongodata:/data/db -p 27017:27017 bitnami/mongo:latest
```
If your distribution is running on an arm device such as a Raspberry Pi, you will need to run the arm-built MongoDB v4.4.
```shell
docker run --name homebrewery-mongodb -d --restart unless-stopped -v mongodata:/data/db -p 27017:27017 arm64v8/mongo:4.4
```
## Run the Homebrewery Image
```shell
# Make sure you run this in the homebrewery directory
docker run --name homebrewery-app -d --restart unless-stopped -e NODE_ENV=docker -v $(pwd)/config/docker.json:/usr/src/app/config/docker.json -p 8000:8000 docker.io/library/homebrewery:latest
```
## Updating the Image
When Homebrewery code updates, your docker container will not automatically follow the changes. To do so you will need to rebuild your homebrewery image.
First, return to your homebrewery clone (from Build Homebrewery Image above) or recreate the clone if you deleted your copy of the code.
First, delete the existing image.
```shell
docker rm -f homebrewery-app
```
Next, update the clone's code to the latest version.
```shell
cd homebrewery
git checkout master
git pull upstream master
```
Finally, rebuild and restart the homebrewery image.
```shell
docker-compose build homebrewery
docker run --name homebrewery-app -d --restart unless-stopped -e NODE_ENV=docker -v $(pwd)/config/docker.json:/usr/src/app/config/docker.json -p 8000:8000 docker.io/library/homebrewery:latest
```
To stop the application and remove all data:
`docker-compose down -v`

View File

@@ -1,10 +0,0 @@
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-transform-runtime",
"babel-plugin-transform-import-meta"
]
}

View File

@@ -79,146 +79,12 @@ pre {
.varSyntaxTable th:first-of-type { .varSyntaxTable th:first-of-type {
width:6cm; width:6cm;
} }
.page .exampleTable td,th {
border:1px dashed #00000030;
}
``` ```
## changelog ## changelog
For a full record of development, visit our [Github Page](https://github.com/naturalcrit/homebrewery). For a full record of development, visit our [Github Page](https://github.com/naturalcrit/homebrewery).
### Thursday 01/30/2024 - v3.17.0
{{taskList
##### 5e-Cleric
* [x] Update FAQ
* [x] Fix styling for Vault buttons and checkboxes
* [x] Improve navigation bar styling
* [x] Add feature to change username at https://www.naturalcrit.com/account
* [x] Fix Reddit link crash when title has non-latin chars
##### dbolack
* [x] Fix page shadows toolbar option
Fixes issue [#3919](https://github.com/naturalcrit/homebrewery/issues/3919)
* [x] Add `:>>>` syntax for horizontal :>>>>> spaces
* [x] Update Docker install instructions
Fixes issue [#1930](https://github.com/naturalcrit/homebrewery/issues/1930)
* [x] Allow styling pages via `\page{myStyles}` (with calculuschild)
Fixes issue [#3901](https://github.com/naturalcrit/homebrewery/issues/3901)
* [x] Update Ubuntu install instructions
Fixes issue [#1952](https://github.com/naturalcrit/homebrewery/issues/1952)
* [x] Add `:-:` `:-` `-:` syntax for paragraph alignment, similar to table column alignment; for example:
-: -: Right-aligned
:-: :-: Centered
* [x] Add `:-- 50% --:` syntax to allow setting table column widths by percentage; for example:
```
| Narrow | Wide |
|:- 10% -:|:-90%--:|
| Cell | Cell |
```
| Narrow | Wide |
|:- 10% -:|:-90%--:|
|Cell | Cell |
{exampleTable}
##### G-Ambatte
* [x] Fix crash when opening brew Properties tab
Fixes issue [#3927](https://github.com/naturalcrit/homebrewery/issues/3927)
* [x] Update error pages with steps to refresh credentials
Fixes issue [#3955](https://github.com/naturalcrit/homebrewery/issues/3955)
* [x] Add {{openSans :fas_rectangle_list: **NAVIGATION**}} menu to the viewer toolbar
##### calculuschild
* [x] Reduce display lag on large brews
##### Gazook89
* [x] Smarter detection of current page number
Fixes issue [#3824](https://github.com/naturalcrit/homebrewery/issues/3824)
##### All
* [x] Update dependencies and scripts
* [x] Refactor components and fix various errors
}}
\column
### Wednesday 11/27/2024 - v3.16.1
{{taskList
##### 5e-Cleric
* [x] Allow linking to specific HTML IDs via `#ID` at the end of the URL, e.g.: `homebrewery.naturalcrit.com/share/share/a6RCXwaDS58i#p4` to link to Page 4 directly
Fixes issues [#2820](https://github.com/naturalcrit/homebrewery/issues/2820), [#3505](https://github.com/naturalcrit/homebrewery/issues/3505)
* [x] Fix generation of link to certain Google Drive brews
Fixes issue [#3776](https://github.com/naturalcrit/homebrewery/issues/3776)
##### abquintic
* [x] Fix blank pages appearing when pasting text
Fixes issue [#3718](https://github.com/naturalcrit/homebrewery/issues/3718)
##### Gazook89
* [x] Add new brew viewing options to the view toolbar
- {{fac,single-spread}} {{openSans **SINGLE PAGE**}}
- {{fac,facing-spread}} {{openSans **TWO PAGE**}}
- {{fac,flow-spread}} {{openSans **GRID**}}
Fixes issue [#1379](https://github.com/naturalcrit/homebrewery/issues/1379)
* [x] Updates to tag input boxes
##### G-Ambatte
* [x] Admin tools to fix certain corrupted documents
Fixes issue [#3801](https://github.com/naturalcrit/homebrewery/issues/3801)
* [x] Fix print window being affected by document zoom
Fixes issue [#3744](https://github.com/naturalcrit/homebrewery/issues/3744)
##### calculuschild, 5e-Cleric, G-Ambatte, Gazook89, abquintic
* [x] Multiple code refactors, cleanups, and security fixes
}}
\page
### Saturday 10/12/2024 - v3.16.0 ### Saturday 10/12/2024 - v3.16.0
{{taskList {{taskList

View File

@@ -1,5 +1,3 @@
require('./brewLookup.less');
const React = require('react'); const React = require('react');
const createClass = require('create-react-class'); const createClass = require('create-react-class');
const cx = require('classnames'); const cx = require('classnames');
@@ -17,40 +15,19 @@ const BrewLookup = createClass({
query : '', query : '',
foundBrew : null, foundBrew : null,
searching : false, searching : false,
error : null, error : null
scriptCount : 0
}; };
}, },
handleChange(e){ handleChange(e){
this.setState({ query: e.target.value }); this.setState({ query: e.target.value });
}, },
lookup(){ lookup(){
this.setState({ searching: true, error: null, scriptCount: 0 }); this.setState({ searching: true, error: null });
request.get(`/admin/lookup/${this.state.query}`) request.get(`/admin/lookup/${this.state.query}`)
.then((res)=>{ .then((res)=>this.setState({ foundBrew: res.body }))
const foundBrew = res.body;
const scriptCheck = foundBrew?.text.match(/(<\/?s)cript/g);
this.setState({
foundBrew : foundBrew,
scriptCount : scriptCheck?.length || 0,
});
})
.catch((err)=>this.setState({ error: err })) .catch((err)=>this.setState({ error: err }))
.finally(()=>{ .finally(()=>this.setState({ searching: false }));
this.setState({
searching : false
});
});
},
async cleanScript(){
if(!this.state.foundBrew?.shareId) return;
await request.put(`/admin/clean/script/${this.state.foundBrew.shareId}`)
.catch((err)=>{ this.setState({ error: err }); return; });
this.lookup();
}, },
renderFoundBrew(){ renderFoundBrew(){
@@ -69,23 +46,12 @@ const BrewLookup = createClass({
<dt>Share Link</dt> <dt>Share Link</dt>
<dd><a href={`/share/${brew.shareId}`} target='_blank' rel='noopener noreferrer'>/share/{brew.shareId}</a></dd> <dd><a href={`/share/${brew.shareId}`} target='_blank' rel='noopener noreferrer'>/share/{brew.shareId}</a></dd>
<dt>Created Time</dt>
<dd>{brew.createdAt ? Moment(brew.createdAt).toLocaleString() : 'No creation date'}</dd>
<dt>Last Updated</dt> <dt>Last Updated</dt>
<dd>{Moment(brew.updatedAt).fromNow()}</dd> <dd>{Moment(brew.updatedAt).fromNow()}</dd>
<dt>Num of Views</dt> <dt>Num of Views</dt>
<dd>{brew.views}</dd> <dd>{brew.views}</dd>
<dt>SCRIPT tags detected</dt>
<dd>{this.state.scriptCount}</dd>
</dl> </dl>
{this.state.scriptCount > 0 &&
<div className='cleanButton'>
<button onClick={this.cleanScript}>CLEAN BREW</button>
</div>
}
</div>; </div>;
}, },

View File

@@ -1,6 +0,0 @@
.brewLookup {
.cleanButton {
display : inline-block;
width : 100%;
}
}

View File

@@ -66,7 +66,7 @@ const NotificationAdd = ()=>{
<label className='field'> <label className='field'>
Dismiss Key: Dismiss Key:
<input className='fieldInput' type='text' ref={dismissKeyRef} required <input className='fieldInput' type='text' ref={dismissKeyRef} required
placeholder='dismiss_notif_drive' placeholder='GOOGLEDRIVENOTIF'
/> />
</label> </label>

View File

@@ -14,6 +14,9 @@ const NotificationDetail = ({ notification, onDelete })=>(
<dt>Title</dt> <dt>Title</dt>
<dd>{notification.title || 'No Title'}</dd> <dd>{notification.title || 'No Title'}</dd>
<dt>Text</dt>
<dd>{notification.text || 'No Text'}</dd>
<dt>Created</dt> <dt>Created</dt>
<dd>{Moment(notification.createdAt).format('LLLL')}</dd> <dd>{Moment(notification.createdAt).format('LLLL')}</dd>
@@ -22,9 +25,6 @@ const NotificationDetail = ({ notification, onDelete })=>(
<dt>Stop</dt> <dt>Stop</dt>
<dd>{Moment(notification.stopAt).format('LLLL') || 'No End Time'}</dd> <dd>{Moment(notification.stopAt).format('LLLL') || 'No End Time'}</dd>
<dt>Text</dt>
<dd>{notification.text || 'No Text'}</dd>
</dl> </dl>
<button onClick={()=>onDelete(notification.dismissKey)}>DELETE</button> <button onClick={()=>onDelete(notification.dismissKey)}>DELETE</button>
</> </>

View File

@@ -1,96 +0,0 @@
import React, { useState, useRef, forwardRef, useEffect, cloneElement, Children } from 'react';
import './Anchored.less';
// Anchored is a wrapper component that must have as children an <AnchoredTrigger> and a <AnchoredBox> component.
// AnchoredTrigger must have a unique `id` prop, which is passed up to Anchored, saved in state on mount, and
// then passed down through props into AnchoredBox. The `id` is used for the CSS Anchor Positioning properties.
// **The Anchor Positioning API is not available in Firefox yet**
// So in Firefox the positioning isn't perfect but is likely sufficient, and FF team seems to be working on the API quickly.
// When Anchor Positioning is added to Firefox, this can also be rewritten using the Popover API-- add the `popover` attribute
// to the container div, which will render the container in the *top level* and give it better interactions like
// click outside to dismiss. **Do not** add without Anchor, though, because positioning is very limited with the `popover`
// attribute.
const Anchored = ({ children })=>{
const [visible, setVisible] = useState(false);
const [anchorId, setAnchorId] = useState(null);
const boxRef = useRef(null);
const triggerRef = useRef(null);
// promote trigger id to Anchored id (to pass it back down to the box as "anchorId")
useEffect(()=>{
if(triggerRef.current){
setAnchorId(triggerRef.current.id);
}
}, []);
// close box on outside click or Escape key
useEffect(()=>{
const handleClickOutside = (evt)=>{
if(
boxRef.current &&
!boxRef.current.contains(evt.target) &&
triggerRef.current &&
!triggerRef.current.contains(evt.target)
) {
setVisible(false);
}
};
const handleEscapeKey = (evt)=>{
if(evt.key === 'Escape') setVisible(false);
};
window.addEventListener('click', handleClickOutside);
window.addEventListener('keydown', handleEscapeKey);
return ()=>{
window.removeEventListener('click', handleClickOutside);
window.removeEventListener('keydown', handleEscapeKey);
};
}, []);
const toggleVisibility = ()=>setVisible((prev)=>!prev);
// Map children to inject necessary props
const mappedChildren = Children.map(children, (child)=>{
if(child.type === AnchoredTrigger) {
return cloneElement(child, { ref: triggerRef, toggleVisibility, visible });
}
if(child.type === AnchoredBox) {
return cloneElement(child, { ref: boxRef, visible, anchorId });
}
return child;
});
return <>{mappedChildren}</>;
};
// forward ref for AnchoredTrigger
const AnchoredTrigger = forwardRef(({ toggleVisibility, visible, children, className, ...props }, ref)=>(
<button
ref={ref}
className={`anchored-trigger${visible ? ' active' : ''} ${className}`}
onClick={toggleVisibility}
style={{ anchorName: `--${props.id}` }} // setting anchor properties here allows greater recyclability.
{...props}
>
{children}
</button>
));
// forward ref for AnchoredBox
const AnchoredBox = forwardRef(({ visible, children, className, anchorId, ...props }, ref)=>(
<div
ref={ref}
className={`anchored-box${visible ? ' active' : ''} ${className}`}
style={{ positionAnchor: `--${anchorId}` }} // setting anchor properties here allows greater recyclability.
{...props}
>
{children}
</div>
));
export { Anchored, AnchoredTrigger, AnchoredBox };

View File

@@ -1,13 +0,0 @@
.anchored-box {
position:absolute;
@supports (inset-block-start: anchor(bottom)){
inset-block-start: anchor(bottom);
}
justify-self: anchor-center;
visibility: hidden;
&.active {
visibility: visible;
}
}

View File

@@ -1,20 +1,18 @@
// Dialog box, for popups and modal blocking messages // Dialog box, for popups and modal blocking messages
import React from 'react'; const React = require('react');
const { useRef, useEffect } = React; const { useRef, useEffect } = React;
function Dialog({ dismisskeys = [], closeText = 'Close', blocking = false, ...rest }) { function Dialog({ dismissKey, closeText = 'Close', blocking = false, ...rest }) {
const dialogRef = useRef(null); const dialogRef = useRef(null);
useEffect(()=>{ useEffect(()=>{
if(!dismissKey || !localStorage.getItem(dismissKey)) {
blocking ? dialogRef.current?.showModal() : dialogRef.current?.show(); blocking ? dialogRef.current?.showModal() : dialogRef.current?.show();
}
}, []); }, []);
const dismiss = ()=>{ const dismiss = ()=>{
dismisskeys.forEach((key)=>{ dismissKey && localStorage.setItem(dismissKey, true);
if(key) {
localStorage.setItem(key, 'true');
}
});
dialogRef.current?.close(); dialogRef.current?.close();
}; };

View File

@@ -1,11 +1,11 @@
/*eslint max-lines: ["warn", {"max": 300, "skipBlankLines": true, "skipComments": true}]*/ /*eslint max-lines: ["warn", {"max": 300, "skipBlankLines": true, "skipComments": true}]*/
require('./brewRenderer.less'); require('./brewRenderer.less');
const React = require('react'); const React = require('react');
const { useState, useRef, useMemo, useEffect } = React; const { useState, useRef, useCallback, useMemo } = React;
const _ = require('lodash'); const _ = require('lodash');
const MarkdownLegacy = require('naturalcrit/markdownLegacy.js'); const MarkdownLegacy = require('naturalcrit/markdownLegacy.js');
import Markdown from 'naturalcrit/markdown.js'; const Markdown = require('naturalcrit/markdown.js');
const ErrorBar = require('./errorBar/errorBar.jsx'); const ErrorBar = require('./errorBar/errorBar.jsx');
const ToolBar = require('./toolBar/toolBar.jsx'); const ToolBar = require('./toolBar/toolBar.jsx');
@@ -16,10 +16,9 @@ const Frame = require('react-frame-component').default;
const dedent = require('dedent-tabs').default; const dedent = require('dedent-tabs').default;
const { printCurrentBrew } = require('../../../shared/helpers.js'); const { printCurrentBrew } = require('../../../shared/helpers.js');
import HeaderNav from './headerNav/headerNav.jsx'; const DOMPurify = require('dompurify');
import { safeHTML } from './safeHTML.js'; const purifyConfig = { FORCE_BODY: true, SANITIZE_DOM: false };
const PAGEBREAK_REGEX_V3 = /^(?=\\page(?: *{[^\n{}]*})?$)/m;
const PAGE_HEIGHT = 1056; const PAGE_HEIGHT = 1056;
const INITIAL_CONTENT = dedent` const INITIAL_CONTENT = dedent`
@@ -30,7 +29,6 @@ const INITIAL_CONTENT = dedent`
<base target=_blank> <base target=_blank>
</head><body style='overflow: hidden'><div></div></body></html>`; </head><body style='overflow: hidden'><div></div></body></html>`;
//v=====----------------------< Brew Page Component >---------------------=====v// //v=====----------------------< Brew Page Component >---------------------=====v//
const BrewPage = (props)=>{ const BrewPage = (props)=>{
props = { props = {
@@ -38,46 +36,8 @@ const BrewPage = (props)=>{
index : 0, index : 0,
...props ...props
}; };
const pageRef = useRef(null); const cleanText = props.contents; //DOMPurify.sanitize(props.contents, purifyConfig);
const cleanText = safeHTML(props.contents); return <div className={props.className} id={`p${props.index + 1}`} >
useEffect(()=>{
if(!pageRef.current) return;
// Observer for tracking pages within the `.pages` div
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);
});
},
{ 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
});
},
{ threshold: 0, rootMargin: '-50% 0px -50% 0px' } // Detect when the page is at the center
);
// attach observers to each `.page`
visibleObserver.observe(pageRef.current);
centerObserver.observe(pageRef.current);
return ()=>{
visibleObserver.disconnect();
centerObserver.disconnect();
};
}, []);
return <div className={props.className} id={`p${props.index + 1}`} data-index={props.index} ref={pageRef} style={props.style} {...props.attributes}>
<div className='columnWrapper' dangerouslySetInnerHTML={{ __html: cleanText }} /> <div className='columnWrapper' dangerouslySetInnerHTML={{ __html: cleanText }} />
</div>; </div>;
}; };
@@ -106,44 +66,24 @@ const BrewRenderer = (props)=>{
const [state, setState] = useState({ const [state, setState] = useState({
isMounted : false, isMounted : false,
visibility : 'hidden', visibility : 'hidden',
visiblePages : [], zoom : 100
centerPage : 1
}); });
const [displayOptions, setDisplayOptions] = useState({
zoomLevel : 100,
spread : 'single',
startOnRight : true,
pageShadows : true
});
const [headerState, setHeaderState] = useState(false);
const mainRef = useRef(null); const mainRef = useRef(null);
const pagesRef = useRef(null);
if(props.renderer == 'legacy') { if(props.renderer == 'legacy') {
rawPages = props.text.split('\\page'); rawPages = props.text.split('\\page');
} else { } else {
rawPages = props.text.split(PAGEBREAK_REGEX_V3); rawPages = props.text.split(/^\\page$/gm);
} }
const handlePageVisibilityChange = (pageNum, isVisible, isCenter)=>{ const updateCurrentPage = useCallback(_.throttle((e)=>{
setState((prevState)=>{ const { scrollTop, clientHeight, scrollHeight } = e.target;
const updatedVisiblePages = new Set(prevState.visiblePages); const totalScrollableHeight = scrollHeight - clientHeight;
if(!isCenter) const currentPageNumber = Math.max(Math.ceil((scrollTop / totalScrollableHeight) * rawPages.length), 1);
isVisible ? updatedVisiblePages.add(pageNum) : updatedVisiblePages.delete(pageNum);
return { props.onPageChange(currentPageNumber);
...prevState, }, 200), []);
visiblePages : [...updatedVisiblePages].sort((a, b)=>a - b),
centerPage : isCenter ? pageNum : prevState.centerPage
};
});
if(isCenter)
props.onPageChange(pageNum);
};
const isInView = (index)=>{ const isInView = (index)=>{
if(!state.isMounted) if(!state.isMounted)
@@ -165,41 +105,19 @@ const BrewRenderer = (props)=>{
}; };
const renderStyle = ()=>{ const renderStyle = ()=>{
const themeStyles = props.themeBundle?.joinedStyles ?? '<style>@import url("/themes/V3/Blank/style.css");</style>'; const cleanStyle = props.style; //DOMPurify.sanitize(props.style, purifyConfig);
const cleanStyle = safeHTML(`${themeStyles} \n\n <style> ${props.style} </style>`); const themeStyles = props.themeBundle?.joinedStyles ?? '@import url("/themes/V3/Blank/style.css");';
return <div style={{ display: 'none' }} dangerouslySetInnerHTML={{ __html: cleanStyle }} />; return `${themeStyles}\n\n${cleanStyle}`;
}; };
const renderPage = (pageText, index)=>{ const renderPage = (pageText, index)=>{
let styles = {
...(!displayOptions.pageShadows ? { boxShadow: 'none' } : {})
// Add more conditions as needed
};
let classes = 'page';
let attributes = {};
if(props.renderer == 'legacy') { if(props.renderer == 'legacy') {
const html = MarkdownLegacy.render(pageText); const html = MarkdownLegacy.render(pageText);
return <BrewPage className='page phb' index={index} key={index} contents={html} />;
return <BrewPage className='page phb' index={index} key={index} contents={html} style={styles} onVisibilityChange={handlePageVisibilityChange} />;
} else { } else {
if(pageText.startsWith('\\page')) {
const firstLineTokens = Markdown.marked.lexer(pageText.split('\n', 1)[0])[0].tokens;
const injectedTags = firstLineTokens.find((obj)=>obj.injectedTags !== undefined)?.injectedTags;
if(injectedTags) {
styles = { ...styles, ...injectedTags.styles };
styles = _.mapKeys(styles, (v, k) => k.startsWith('--') ? k : _.camelCase(k)); // Convert CSS to camelCase for React
classes = [classes, injectedTags.classes].join(' ').trim();
attributes = injectedTags.attributes;
}
pageText = pageText.includes('\n') ? pageText.substring(pageText.indexOf('\n') + 1) : ''; // Remove the \page line
}
pageText += `\n\n&nbsp;\n\\column\n&nbsp;`; //Artificial column break at page end to emulate column-fill:auto (until `wide` is used, when column-fill:balance will reappear) pageText += `\n\n&nbsp;\n\\column\n&nbsp;`; //Artificial column break at page end to emulate column-fill:auto (until `wide` is used, when column-fill:balance will reappear)
const html = Markdown.render(pageText, index); const html = Markdown.render(pageText, index);
return <BrewPage className='page' index={index} key={index} contents={html} />;
return <BrewPage className={classes} index={index} key={index} contents={html} style={styles} attributes={attributes} onVisibilityChange={handlePageVisibilityChange} />;
} }
}; };
@@ -211,7 +129,6 @@ const BrewRenderer = (props)=>{
renderedPages.length = 0; renderedPages.length = 0;
// Render currently-edited page first so cross-page effects (variables, links) can propagate out first // Render currently-edited page first so cross-page effects (variables, links) can propagate out first
if(rawPages.length > props.currentEditorCursorPageNum -1)
renderedPages[props.currentEditorCursorPageNum - 1] = renderPage(rawPages[props.currentEditorCursorPageNum - 1], props.currentEditorCursorPageNum - 1); renderedPages[props.currentEditorCursorPageNum - 1] = renderPage(rawPages[props.currentEditorCursorPageNum - 1], props.currentEditorCursorPageNum - 1);
_.forEach(rawPages, (page, index)=>{ _.forEach(rawPages, (page, index)=>{
@@ -232,29 +149,7 @@ const BrewRenderer = (props)=>{
} }
}; };
const scrollToHash = (hash)=>{
if(!hash) return;
const iframeDoc = document.getElementById('BrewRenderer').contentDocument;
let anchor = iframeDoc.querySelector(hash);
if(anchor) {
anchor.scrollIntoView({ behavior: 'smooth' });
} else {
// Use MutationObserver to wait for the element if it's not immediately available
new MutationObserver((mutations, obs)=>{
anchor = iframeDoc.querySelector(hash);
if(anchor) {
anchor.scrollIntoView({ behavior: 'smooth' });
obs.disconnect();
}
}).observe(iframeDoc, { childList: true, subtree: true });
}
};
const frameDidMount = ()=>{ //This triggers when iFrame finishes internal "componentDidMount" const frameDidMount = ()=>{ //This triggers when iFrame finishes internal "componentDidMount"
scrollToHash(window.location.hash);
setTimeout(()=>{ //We still see a flicker where the style isn't applied yet, so wait 100ms before showing iFrame setTimeout(()=>{ //We still see a flicker where the style isn't applied yet, so wait 100ms before showing iFrame
renderPages(); //Make sure page is renderable before showing renderPages(); //Make sure page is renderable before showing
setState((prevState)=>({ setState((prevState)=>({
@@ -270,30 +165,28 @@ const BrewRenderer = (props)=>{
document.dispatchEvent(new MouseEvent('click')); document.dispatchEvent(new MouseEvent('click'));
}; };
const handleDisplayOptionsChange = (newDisplayOptions)=>{ //Toolbar settings:
setDisplayOptions(newDisplayOptions); const handleZoom = (newZoom)=>{
}; setState((prevState)=>({
...prevState,
const pagesStyle = { zoom : newZoom
zoom : `${displayOptions.zoomLevel}%`, }));
columnGap : `${displayOptions.columnGap}px`,
rowGap : `${displayOptions.rowGap}px`
}; };
const styleObject = {}; const styleObject = {};
if(global.config.deployment) { if(global.config.deployment) {
styleObject.backgroundImage = `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='40px' width='200px'><text x='0' y='15' fill='%23fff7' font-size='20'>${global.config.deployment}</text></svg>")`; styleObject.backgroundImage = `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='40px' width='200px'><text x='0' y='15' fill='white' font-size='20'>${global.config.deployment}</text></svg>")`;
} }
const renderedStyle = useMemo(()=>renderStyle(), [props.style, props.themeBundle]); const renderedStyle = useMemo(()=> renderStyle(), [props.style?.length, props.themeBundle]);
renderedPages = useMemo(()=>renderPages(), [props.text, displayOptions]); renderedPages = useMemo(() => renderPages(), [props.text?.length]);
return ( return (
<> <>
{/*render dummy page while iFrame is mounting.*/} {/*render dummy page while iFrame is mounting.*/}
{!state.isMounted {!state.isMounted
? <div className='brewRenderer'> ? <div className='brewRenderer' onScroll={updateCurrentPage}>
<div className='pages'> <div className='pages'>
{renderDummyPage(1)} {renderDummyPage(1)}
</div> </div>
@@ -306,32 +199,30 @@ const BrewRenderer = (props)=>{
<NotificationPopup /> <NotificationPopup />
</div> </div>
<ToolBar displayOptions={displayOptions} onDisplayOptionsChange={handleDisplayOptionsChange} visiblePages={state.visiblePages.length > 0 ? state.visiblePages : [state.centerPage]} totalPages={rawPages.length} headerState={headerState} setHeaderState={setHeaderState}/> <ToolBar onZoomChange={handleZoom} currentPage={props.currentBrewRendererPageNum} totalPages={rawPages.length}/>
{/*render in iFrame so broken code doesn't crash the site.*/} {/*render in iFrame so broken code doesn't crash the site.*/}
<Frame id='BrewRenderer' initialContent={INITIAL_CONTENT} <Frame id='BrewRenderer' initialContent={INITIAL_CONTENT} head={<style>{renderedStyle}</style>}
style={{ width: '100%', height: '100%', visibility: state.visibility }} style={{ width: '100%', height: '100%', visibility: state.visibility }}
contentDidMount={frameDidMount} contentDidMount={frameDidMount}
onClick={()=>{emitClick();}} onClick={()=>{emitClick();}}
> >
<div className={`brewRenderer ${global.config.deployment && 'deployment'}`} <div className={`brewRenderer ${global.config.deployment && 'deployment'}`}
onScroll={updateCurrentPage}
onKeyDown={handleControlKeys} onKeyDown={handleControlKeys}
tabIndex={-1} tabIndex={-1}
style={ styleObject } style={ styleObject }>
>
{/* Apply CSS from Style tab and render pages from Markdown tab */} {/* Apply CSS from Style tab and render pages from Markdown tab */}
{state.isMounted {state.isMounted
&& &&
<> <>
{renderedStyle} <div className='pages' lang={`${props.lang || 'en'}`} style={{ zoom: `${state.zoom}%` }}>
<div className={`pages ${displayOptions.startOnRight ? 'recto' : 'verso'} ${displayOptions.spread}`} lang={`${props.lang || 'en'}`} style={pagesStyle} ref={pagesRef}>
{renderedPages} {renderedPages}
</div> </div>
</> </>
} }
</div> </div>
{headerState ? <HeaderNav ref={pagesRef} /> : <></>}
</Frame> </Frame>
</> </>
); );

View File

@@ -3,45 +3,13 @@
.brewRenderer { .brewRenderer {
overflow-y : scroll; overflow-y : scroll;
will-change : transform; will-change : transform;
padding-top : 60px; padding-top : 30px;
height : 100vh; height : 100vh;
&:has(.facing, .flow) {
padding : 60px 30px;
}
&.deployment { &.deployment {
background-color: darkred; background-color: darkred;
} }
:where(.pages) { :where(.pages) {
&.facing { margin : 30px 0px;
display: grid;
grid-template-columns: repeat(2, auto);
grid-template-rows: repeat(3, auto);
gap: 10px 10px;
justify-content: safe center;
&.recto .page:first-child {
// sets first page on 'right' ('recto') of the preview, as if for a Cover page.
// todo: add a checkbox to toggle this setting
grid-column-start: 2;
}
& :where(.page) {
margin-left: unset !important;
margin-right: unset !important;
}
}
&.flow {
display: flex;
flex-wrap: wrap;
gap: 10px;
justify-content: safe center;
& :where(.page) {
flex: 0 0 auto;
margin-left: unset !important;
margin-right: unset !important;
}
}
& > :where(.page) { & > :where(.page) {
width : 215.9mm; width : 215.9mm;
height : 279.4mm; height : 279.4mm;
@@ -50,9 +18,6 @@
margin-left : auto; margin-left : auto;
box-shadow : 1px 4px 14px #000000; box-shadow : 1px 4px 14px #000000;
} }
*[id] {
scroll-margin-top:100px;
}
} }
&::-webkit-scrollbar { &::-webkit-scrollbar {
width : 20px; width : 20px;
@@ -70,7 +35,6 @@
.pane { position : relative; } .pane { position : relative; }
@media print { @media print {
.toolBar { display : none; } .toolBar { display : none; }
.brewRenderer { .brewRenderer {
@@ -83,7 +47,4 @@
& > .page { box-shadow : unset; } & > .page { box-shadow : unset; }
} }
} }
.headerNav {
visibility: hidden;
}
} }

View File

@@ -1,53 +1,75 @@
require('./errorBar.less'); require('./errorBar.less');
const React = require('react'); const React = require('react');
const createClass = require('create-react-class');
const _ = require('lodash');
import Dialog from '../../../components/dialog.jsx'; const ErrorBar = createClass({
displayName : 'ErrorBar',
getDefaultProps : function() {
return {
errors : []
};
},
const DISMISS_BUTTON = <i className='fas fa-times dismiss' />; hasOpenError : false,
hasCloseError : false,
hasMatchError : false,
const ErrorBar = (props)=>{ renderErrors : function(){
if(!props.errors.length) return null; this.hasOpenError = false;
let hasOpenError = false, hasCloseError = false, hasMatchError = false; this.hasCloseError = false;
this.hasMatchError = false;
props.errors.map((err)=>{
if(err.id === 'OPEN') hasOpenError = true;
if(err.id === 'CLOSE') hasCloseError = true;
if(err.id === 'MISMATCH') hasMatchError = true;
});
const renderErrors = ()=>( const errors = _.map(this.props.errors, (err, idx)=>{
<ul> if(err.id == 'OPEN') this.hasOpenError = true;
{props.errors.map((err, idx)=>{ if(err.id == 'CLOSE') this.hasCloseError = true;
if(err.id == 'MISMATCH') this.hasMatchError = true;
return <li key={idx}> return <li key={idx}>
Line {err.line} : {err.text}, '{err.type}' tag Line {err.line} : {err.text}, '{err.type}' tag
</li>; </li>;
})} });
</ul>
);
const renderProtip = ()=>( return <ul>{errors}</ul>;
<div className='protips'> },
renderProtip : function(){
const msg = [];
if(this.hasOpenError){
msg.push(<div>
An unmatched opening tag means there's an opened tag that isn't closed. You need to close your tags, like this {'</div>'}. Make sure to match types!
</div>);
}
if(this.hasCloseError){
msg.push(<div>
An unmatched closing tag means you closed a tag without opening it. Either remove it, or check to where you think you opened it.
</div>);
}
if(this.hasMatchError){
msg.push(<div>
A type mismatch means you closed a tag, but the last open tag was a different type.
</div>);
}
return <div className='protips'>
<h4>Protips!</h4> <h4>Protips!</h4>
{hasOpenError && <div>Unmatched opening tag. Close your tags, like this {'</div>'}. Match types!</div>} {msg}
{hasCloseError && <div>Unmatched closing tag. Either remove it or check where it was opened.</div>} </div>;
{hasMatchError && <div>Type mismatch. Closed a tag with a different type.</div>} },
</div>
);
return ( render : function(){
<Dialog className='errorBar' closeText={DISMISS_BUTTON} > if(!this.props.errors.length) return null;
<div>
return <div className='errorBar'>
<i className='fas fa-exclamation-triangle' /> <i className='fas fa-exclamation-triangle' />
<h2> There are HTML errors in your markup</h2> <h3> There are HTML errors in your markup</h3>
<small> <small>If these aren't fixed your brew will not render properly when you print it to PDF or share it</small>
If these aren't fixed your brew will not render properly when you print it to PDF or share it {this.renderErrors()}
</small>
{renderErrors()}
</div>
<hr /> <hr />
{renderProtip()} {this.renderProtip()}
</Dialog> </div>;
); }
}; });
module.exports = ErrorBar; module.exports = ErrorBar;

View File

@@ -1,34 +1,41 @@
.errorBar{ .errorBar{
position : absolute; position : absolute;
top : 32px; z-index : 10000;
z-index : 1; box-sizing : border-box;
width : 100%; width : 100%;
color : white; margin-right : 13px;
padding : 20px;
padding-bottom : 10px;
padding-left : 100px;
background-color : @red; background-color : @red;
border : unset; color : white;
i{
div { position : absolute;
> i { left : 30px;
float : left;
margin-right : 10px;
margin-bottom : 20px;
font-size : 3em;
opacity : 0.8; opacity : 0.8;
font-size : 3em;
}
h3{
font-size : 1.1em;
font-weight : 800;
} }
h2 { font-weight : 800; }
ul{ ul{
margin-top : 15px; margin-top : 15px;
font-size : 0.8em; font-size : 0.8em;
list-style-position : inside; list-style-position : inside;
list-style-type : disc; list-style-type : disc;
li { line-height : 1.6em; } li{
line-height : 1.6em;
} }
} }
hr{ hr{
box-sizing : border-box;
height : 2px; height : 2px;
width : 150%;
margin-top : 25px; margin-top : 25px;
margin-bottom : 15px; margin-bottom : 15px;
margin-left : -100px;
background-color : darken(@red, 8%); background-color : darken(@red, 8%);
border : none; border : none;
} }
@@ -37,22 +44,17 @@
opacity: 0.7; opacity: 0.7;
} }
.protips{ .protips{
margin-left : -80px;
font-size : 0.6em; font-size : 0.6em;
&>div{
margin-bottom : 10px;
line-height : 1.2em; line-height : 1.2em;
}
h4{ h4{
opacity : 0.8;
font-weight : 800; font-weight : 800;
line-height : 1.5em; line-height : 1.5em;
text-transform : uppercase; text-transform : uppercase;
} }
} }
button.dismiss {
position : absolute;
top : 20px;
right : 30px;
padding : unset;
font-size : 40px;
background-color : transparent;
opacity : 0.6;
&:hover { opacity : 1; }
}
} }

View File

@@ -1,106 +0,0 @@
require('./headerNav.less');
import * as React from 'react';
import * as _ from 'lodash';
const MAX_TEXT_LENGTH = 40;
const HeaderNav = React.forwardRef(({}, pagesRef)=>{
const renderHeaderLinks = ()=>{
if(!pagesRef.current) return;
const selector = [
'.pages > .page', // All page elements, which by definition have IDs
'.page:not(:has(.toc)) > [id]', // All direct children of non-ToC .page with an ID (Legacy)
'.page:not(:has(.toc)) > .columnWrapper > [id]', // All direct children of non-ToC .page > .columnWrapper with an ID (V3)
'.page:not(:has(.toc)) h2', // All non-ToC H2 titles, like Monster frame titles
];
const elements = pagesRef.current.querySelectorAll(selector.join(','));
if(!elements) return;
const navList = [];
// navList is a list of objects which have the following structure:
// {
// depth : how deeply indented the item should be
// text : the text to display in the nav link
// link : the hyperlink to navigate to when clicked
// className : [optional] the class to apply to the nav link for styling
// }
elements.forEach((el)=>{
if(el.className.match(/\bpage\b/)) {
let text = `Page ${el.id.slice(1)}`; // The ID of a page *should* always be equal to `p` followed by the page number
if(el.querySelector('.toc')){ // If the page contains a table of contents, add "- Contents" to the display text
text += ' - Contents';
};
navList.push({
depth : 0, // Pages are always at the least indented level
text : text,
link : el.id,
className : 'pageLink'
});
return;
}
if(el.localName.match(/^h[1-6]/)){ // Header elements H1 through H6
navList.push({
depth : el.localName[1], // Depth is set by the header level
text : el.textContent, // Use `textContent` because `innerText` is affected by rendering, e.g. 'content-visibility: auto'
link : el.id
});
return;
}
navList.push({
depth : 7, // All unmatched elements with IDs are set to the maximum depth (7)
text : el.textContent, // Use `textContent` because `innerText` is affected by rendering, e.g. 'content-visibility: auto'
link : el.id
});
});
return _.map(navList, (navItem, index)=>{
return <HeaderNavItem {...navItem} key={index} />;
});
};
return <nav className='headerNav'>
<ul>
{renderHeaderLinks()}
</ul>
</nav>;
}
);
const HeaderNavItem = ({ link, text, depth, className })=>{
const trimString = (text, prefixLength = 0)=>{
// Sanity check nav link strings
let output = text;
// If the string has a line break, only use the first line
if(text.indexOf('\n')){
output = text.split('\n')[0];
}
// Trim unecessary spaces from string
output = output.trim();
// Reduce excessively long strings
const maxLength = MAX_TEXT_LENGTH - prefixLength;
if(output.length > maxLength){
return `${output.slice(0, maxLength).trim()}...`;
}
return output;
};
if(!link || !text) return;
return <li>
<a href={`#${link}`} target='_self' className={`depth-${depth} ${className ?? ''}`}>
{trimString(text, depth)}
</a>
</li>;
};
export default HeaderNav;

View File

@@ -1,47 +0,0 @@
.headerNav {
position: fixed;
top: 32px;
left: 0px;
padding: 5px 10px;
background-color: #ccc;
border-radius: 5px;
max-height: calc(100vh - 32px);
max-width: 40vw;
overflow-y: auto;
&.active {
padding-bottom: 10px;
.navIcon {
padding-bottom: 10px;
}
}
.navIcon {
cursor: pointer;
}
li {
list-style-type: none;
a {
display: inline-block;
width: 100%;
font-family: 'Open Sans';
font-size: 12px;
padding: 2px;
color: inherit;
text-decoration: none;
cursor: pointer;
&:hover {
text-decoration: underline;
}
&.pageLink {
font-weight: 900;
}
@depths: 1,2,3,4,5,6,7;
each(@depths, {
&.depth-@{value} {
padding-left: ((@value - 1) * 0.5em);
}
});
}
}
}

View File

@@ -1,63 +1,44 @@
require('./notificationPopup.less'); require('./notificationPopup.less');
import React, { useEffect, useState } from 'react'; const React = require('react');
import request from '../../utils/request-middleware.js'; const _ = require('lodash');
import Dialog from '../../../components/dialog.jsx'; import Dialog from '../../../components/dialog.jsx';
const DISMISS_KEY = 'dismiss_notification01-10-24';
const DISMISS_BUTTON = <i className='fas fa-times dismiss' />; const DISMISS_BUTTON = <i className='fas fa-times dismiss' />;
const NotificationPopup = ()=>{ const NotificationPopup = ()=>{
const [notifications, setNotifications] = useState([]); return <Dialog className='notificationPopup' dismissKey={DISMISS_KEY} closeText={DISMISS_BUTTON} >
const [dissmissKeyList, setDismissKeyList] = useState([]);
const [error, setError] = useState(null);
useEffect(()=>{
getNotifications();
}, []);
const getNotifications = async ()=>{
setError(null);
try {
const res = await request.get('/admin/notification/all');
pickActiveNotifications(res.body || []);
} catch (err) {
console.log(err);
setError(`Error looking up notifications: ${err?.response?.body?.message || err.message}`);
}
};
const pickActiveNotifications = (notifs)=>{
const now = new Date();
const filteredNotifications = notifs.filter((notification)=>{
const startDate = new Date(notification.startAt);
const stopDate = new Date(notification.stopAt);
const dismissed = localStorage.getItem(notification.dismissKey) ? true : false;
return now >= startDate && now <= stopDate && !dismissed;
});
setNotifications(filteredNotifications);
setDismissKeyList(filteredNotifications.map((notif)=>notif.dismissKey));
};
const renderNotificationsList = ()=>{
if(error) return <div className='error'>{error}</div>;
return notifications.map((notification)=>(
<li key={notification.dismissKey} >
<em>{notification.title}</em><br />
<p dangerouslySetInnerHTML={{ __html: notification.text }}></p>
</li>
));
};
if(!notifications.length) return;
return <Dialog className='notificationPopup' dismisskeys={dissmissKeyList} closeText={DISMISS_BUTTON} >
<div className='header'> <div className='header'>
<i className='fas fa-info-circle info'></i> <i className='fas fa-info-circle info'></i>
<h3>Notice</h3> <h3>Notice</h3>
<small>This website is always improving and we are still adding new features and squashing bugs. Keep the following in mind:</small> <small>This website is always improving and we are still adding new features and squashing bugs. Keep the following in mind:</small>
</div> </div>
<ul> <ul>
{renderNotificationsList()} <li key='Vault'>
<em>Search brews with our new page!</em><br />
We have been working very hard in making this possible, now you can share your work and look at it in the new <a href='/vault'>Vault</a> page!
All PUBLISHED brews will be available to anyone searching there, by title or author, and filtering by renderer.
More features will be coming.
</li>
<li key='googleDriveFolder'>
<em>Don't delete your Homebrewery folder on Google Drive!</em> <br />
We have had several reports of users losing their brews, not realizing
that they had deleted the files on their Google Drive. If you have a Homebrewery folder
on your Google Drive with *.txt files inside, <em>do not delete it</em>!
We cannot help you recover files that you have deleted from your own
Google Drive.
</li>
<li key='faq'>
<em>Protect your work! </em> <br />
If you opt not to use your Google Drive, keep in mind that we do not save a history of your projects. Please make frequent backups of your brews!&nbsp;
<a target='_blank' href='https://www.reddit.com/r/homebrewery/comments/adh6lh/faqs_psas_announcements/'>
See the FAQ
</a> to learn how to avoid losing your work!
</li>
</ul> </ul>
</Dialog>; </Dialog>;
}; };

View File

@@ -55,10 +55,7 @@
margin-top : 1.4em; margin-top : 1.4em;
font-size : 0.8em; font-size : 0.8em;
line-height : 1.4em; line-height : 1.4em;
em { em { font-weight : 800; }
text-transform:capitalize;
font-weight : 800;
}
} }
} }
} }

View File

@@ -1,46 +0,0 @@
// Derived from the vue-html-secure package, customized for Homebrewery
let doc = null;
let div = null;
function safeHTML(htmlString) {
// If the Document interface doesn't exist, exit
if(typeof document == 'undefined') return null;
// If the test document and div don't exist, create them
if(!doc) doc = document.implementation.createHTMLDocument('');
if(!div) div = doc.createElement('div');
// Set the test div contents to the evaluation string
div.innerHTML = htmlString;
// Grab all nodes from the test div
const elements = div.querySelectorAll('*');
// Blacklisted tags
const blacklistTags = ['script', 'noscript', 'noembed'];
// Tests to remove attributes
const blacklistAttrs = [
(test)=>{return test.localName.indexOf('on') == 0;},
(test)=>{return test.localName.indexOf('type') == 0 && test.value.match(/submit/i);},
(test)=>{return test.value.replace(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205f\u3000]/g, '').toLowerCase().trim().indexOf('javascript:') == 0;}
];
elements.forEach((element)=>{
// Check each element for blacklisted type
if(blacklistTags.includes(element?.localName?.toLowerCase())) {
element.remove();
return;
}
// Check remaining elements for blacklisted attributes
for (const attribute of element.attributes){
if(blacklistAttrs.some((test)=>{return test(attribute);})) {
element.removeAttribute(attribute.localName);
break;
};
};
});
return div.innerHTML;
};
module.exports.safeHTML = safeHTML;

View File

@@ -1,31 +1,28 @@
/* eslint-disable max-lines */
require('./toolBar.less'); require('./toolBar.less');
const React = require('react'); const React = require('react');
const { useState, useEffect } = React; const { useState, useEffect } = React;
const _ = require('lodash'); const _ = require('lodash');
import { Anchored, AnchoredBox, AnchoredTrigger } from '../../../components/Anchored.jsx';
const MAX_ZOOM = 300; const MAX_ZOOM = 300;
const MIN_ZOOM = 10; const MIN_ZOOM = 10;
const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPages, headerState, setHeaderState })=>{ const ToolBar = ({ onZoomChange, currentPage, onPageChange, totalPages })=>{
const [pageNum, setPageNum] = useState(1); const [zoomLevel, setZoomLevel] = useState(100);
const [pageNum, setPageNum] = useState(currentPage);
const [toolsVisible, setToolsVisible] = useState(true); const [toolsVisible, setToolsVisible] = useState(true);
useEffect(()=>{ useEffect(()=>{
// format multiple visible pages as a range (e.g. "150-153") onZoomChange(zoomLevel);
const pageRange = visiblePages.length === 1 ? `${visiblePages[0]}` : `${visiblePages[0]} - ${visiblePages.at(-1)}`; }, [zoomLevel]);
setPageNum(pageRange);
}, [visiblePages]); useEffect(()=>{
setPageNum(currentPage);
}, [currentPage]);
const handleZoomButton = (zoom)=>{ const handleZoomButton = (zoom)=>{
handleOptionChange('zoomLevel', _.round(_.clamp(zoom, MIN_ZOOM, MAX_ZOOM))); setZoomLevel(_.round(_.clamp(zoom, MIN_ZOOM, MAX_ZOOM)));
};
const handleOptionChange = (optionKey, newValue)=>{
onDisplayOptionsChange({ ...displayOptions, [optionKey]: newValue });
}; };
const handlePageInput = (pageInput)=>{ const handlePageInput = (pageInput)=>{
@@ -33,16 +30,16 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
setPageNum(parseInt(pageInput)); // input type is 'text', so `page` comes in as a string, not number. setPageNum(parseInt(pageInput)); // input type is 'text', so `page` comes in as a string, not number.
}; };
// scroll to a page, used in the Prev/Next Page buttons.
const scrollToPage = (pageNumber)=>{ const scrollToPage = (pageNumber)=>{
if(typeof pageNumber !== 'number') return;
pageNumber = _.clamp(pageNumber, 1, totalPages); pageNumber = _.clamp(pageNumber, 1, totalPages);
const iframe = document.getElementById('BrewRenderer'); const iframe = document.getElementById('BrewRenderer');
const brewRenderer = iframe?.contentWindow?.document.querySelector('.brewRenderer'); const brewRenderer = iframe?.contentWindow?.document.querySelector('.brewRenderer');
const page = brewRenderer?.querySelector(`#p${pageNumber}`); const page = brewRenderer?.querySelector(`#p${pageNumber}`);
page?.scrollIntoView({ block: 'start' }); page?.scrollIntoView({ block: 'start' });
setPageNum(pageNumber);
}; };
const calculateChange = (mode)=>{ const calculateChange = (mode)=>{
const iframe = document.getElementById('BrewRenderer'); const iframe = document.getElementById('BrewRenderer');
const iframeWidth = iframe.getBoundingClientRect().width; const iframeWidth = iframe.getBoundingClientRect().width;
@@ -58,66 +55,55 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
desiredZoom = (iframeWidth / widestPage) * 100; desiredZoom = (iframeWidth / widestPage) * 100;
} else if(mode == 'fit'){ } else if(mode == 'fit'){
let minDimRatio;
// find the page with the largest single dim (height or width) so that zoom can be adapted to fit it. // find the page with the largest single dim (height or width) so that zoom can be adapted to fit it.
if(displayOptions.spread === 'facing') const minDimRatio = [...pages].reduce((minRatio, page)=>Math.min(minRatio, iframeWidth / page.offsetWidth, iframeHeight / page.offsetHeight), Infinity);
minDimRatio = [...pages].reduce((minRatio, page)=>Math.min(minRatio, iframeWidth / page.offsetWidth / 2), Infinity); // if 'facing' spread, fit two pages in view
else
minDimRatio = [...pages].reduce((minRatio, page)=>Math.min(minRatio, iframeWidth / page.offsetWidth, iframeHeight / page.offsetHeight), Infinity);
desiredZoom = minDimRatio * 100; desiredZoom = minDimRatio * 100;
} }
const margin = 5; // extra space so page isn't edge to edge (not truly "to fill") const margin = 5; // extra space so page isn't edge to edge (not truly "to fill")
const deltaZoom = (desiredZoom - displayOptions.zoomLevel) - margin; const deltaZoom = (desiredZoom - zoomLevel) - margin;
return deltaZoom; return deltaZoom;
}; };
return ( return (
<div id='preview-toolbar' className={`toolBar ${toolsVisible ? 'visible' : 'hidden'}`} role='toolbar'> <div className={`toolBar ${toolsVisible ? 'visible' : 'hidden'}`}>
<div className='toggleButton'> <button className='toggleButton' title={`${toolsVisible ? 'Hide' : 'Show'} Preview Toolbar`} onClick={()=>{setToolsVisible(!toolsVisible);}}><i className='fas fa-glasses' /></button>
<button title={`${toolsVisible ? 'Hide' : 'Show'} Preview Toolbar`} onClick={()=>{setToolsVisible(!toolsVisible);}}><i className='fas fa-glasses' /></button>
<button title={`${headerState ? 'Hide' : 'Show'} Header Navigation`} onClick={()=>{setHeaderState(!headerState);}}><i className='fas fa-rectangle-list' /></button>
</div>
{/*v=====----------------------< Zoom Controls >---------------------=====v*/} {/*v=====----------------------< Zoom Controls >---------------------=====v*/}
<div className='group' role='group' aria-label='Zoom' aria-hidden={!toolsVisible}> <div className='group'>
<button <button
id='fill-width' id='fill-width'
className='tool' className='tool'
title='Set zoom to fill preview with one page' onClick={()=>handleZoomButton(zoomLevel + calculateChange('fill'))}
onClick={()=>handleZoomButton(displayOptions.zoomLevel + calculateChange('fill'))}
> >
<i className='fac fit-width' /> <i className='fac fit-width' />
</button> </button>
<button <button
id='zoom-to-fit' id='zoom-to-fit'
className='tool' className='tool'
title='Set zoom to fit entire page in preview' onClick={()=>handleZoomButton(zoomLevel + calculateChange('fit'))}
onClick={()=>handleZoomButton(displayOptions.zoomLevel + calculateChange('fit'))}
> >
<i className='fac zoom-to-fit' /> <i className='fac zoom-to-fit' />
</button> </button>
<button <button
id='zoom-out' id='zoom-out'
className='tool' className='tool'
onClick={()=>handleZoomButton(displayOptions.zoomLevel - 20)} onClick={()=>handleZoomButton(zoomLevel - 20)}
disabled={displayOptions.zoomLevel <= MIN_ZOOM} disabled={zoomLevel <= MIN_ZOOM}
title='Zoom Out'
> >
<i className='fas fa-magnifying-glass-minus' /> <i className='fas fa-magnifying-glass-minus' />
</button> </button>
<input <input
id='zoom-slider' id='zoom-slider'
className='range-input tool hover-tooltip' className='range-input tool'
type='range' type='range'
name='zoom' name='zoom'
title='Set Zoom'
list='zoomLevels' list='zoomLevels'
min={MIN_ZOOM} min={MIN_ZOOM}
max={MAX_ZOOM} max={MAX_ZOOM}
step='1' step='1'
value={displayOptions.zoomLevel} value={zoomLevel}
onChange={(e)=>handleZoomButton(parseInt(e.target.value))} onChange={(e)=>handleZoomButton(parseInt(e.target.value))}
/> />
<datalist id='zoomLevels'> <datalist id='zoomLevels'>
@@ -127,74 +113,20 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
<button <button
id='zoom-in' id='zoom-in'
className='tool' className='tool'
onClick={()=>handleZoomButton(displayOptions.zoomLevel + 20)} onClick={()=>handleZoomButton(zoomLevel + 20)}
disabled={displayOptions.zoomLevel >= MAX_ZOOM} disabled={zoomLevel >= MAX_ZOOM}
title='Zoom In'
> >
<i className='fas fa-magnifying-glass-plus' /> <i className='fas fa-magnifying-glass-plus' />
</button> </button>
</div> </div>
{/*v=====----------------------< Spread Controls >---------------------=====v*/}
<div className='group' role='group' aria-label='Spread' aria-hidden={!toolsVisible}>
<div className='radio-group' role='radiogroup'>
<button role='radio'
id='single-spread'
className='tool'
title='Single Page'
onClick={()=>{handleOptionChange('spread', 'active');}}
aria-checked={displayOptions.spread === 'single'}
><i className='fac single-spread' /></button>
<button role='radio'
id='facing-spread'
className='tool'
title='Facing Pages'
onClick={()=>{handleOptionChange('spread', 'facing');}}
aria-checked={displayOptions.spread === 'facing'}
><i className='fac facing-spread' /></button>
<button role='radio'
id='flow-spread'
className='tool'
title='Flow Pages'
onClick={()=>{handleOptionChange('spread', 'flow');}}
aria-checked={displayOptions.spread === 'flow'}
><i className='fac flow-spread' /></button>
</div>
<Anchored>
<AnchoredTrigger id='spread-settings' className='tool' title='Spread options'><i className='fas fa-gear' /></AnchoredTrigger>
<AnchoredBox title='Options'>
<h1>Options</h1>
<label title='Modify the horizontal space between pages.'>
Column gap
<input type='range' min={0} max={200} defaultValue={10} className='range-input' onChange={(evt)=>handleOptionChange('columnGap', evt.target.value)} />
</label>
<label title='Modify the vertical space between rows of pages.'>
Row gap
<input type='range' min={0} max={200} defaultValue={10} className='range-input' onChange={(evt)=>handleOptionChange('rowGap', evt.target.value)} />
</label>
<label title='Start 1st page on the right side, such as if you have cover page.'>
Start on right
<input type='checkbox' checked={displayOptions.startOnRight} onChange={()=>{handleOptionChange('startOnRight', !displayOptions.startOnRight);}}
title={displayOptions.spread !== 'facing' ? 'Switch to Facing to enable toggle.' : null} />
</label>
<label title='Toggle the page shadow on every page.'>
Page shadows
<input type='checkbox' checked={displayOptions.pageShadows} onChange={()=>{handleOptionChange('pageShadows', !displayOptions.pageShadows);}} />
</label>
</AnchoredBox>
</Anchored>
</div>
{/*v=====----------------------< Page Controls >---------------------=====v*/} {/*v=====----------------------< Page Controls >---------------------=====v*/}
<div className='group' role='group' aria-label='Pages' aria-hidden={!toolsVisible}> <div className='group'>
<button <button
id='previous-page' id='previous-page'
className='previousPage tool' className='previousPage tool'
type='button' onClick={()=>scrollToPage(pageNum - 1)}
title='Previous Page(s)' disabled={pageNum <= 1}
onClick={()=>scrollToPage(_.min(visiblePages) - visiblePages.length)}
disabled={visiblePages.includes(1)}
> >
<i className='fas fa-arrow-left'></i> <i className='fas fa-arrow-left'></i>
</button> </button>
@@ -205,7 +137,6 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
className='text-input' className='text-input'
type='text' type='text'
name='page' name='page'
title='Current page(s) in view'
inputMode='numeric' inputMode='numeric'
pattern='[0-9]' pattern='[0-9]'
value={pageNum} value={pageNum}
@@ -213,18 +144,15 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
onChange={(e)=>handlePageInput(e.target.value)} onChange={(e)=>handlePageInput(e.target.value)}
onBlur={()=>scrollToPage(pageNum)} onBlur={()=>scrollToPage(pageNum)}
onKeyDown={(e)=>e.key == 'Enter' && scrollToPage(pageNum)} onKeyDown={(e)=>e.key == 'Enter' && scrollToPage(pageNum)}
style={{ width: `${pageNum.length}ch` }}
/> />
<span id='page-count' title='Total Page Count'>/ {totalPages}</span> <span id='page-count'>/ {totalPages}</span>
</div> </div>
<button <button
id='next-page' id='next-page'
className='tool' className='tool'
type='button' onClick={()=>scrollToPage(pageNum + 1)}
title='Next Page(s)' disabled={pageNum >= totalPages}
onClick={()=>scrollToPage(_.max(visiblePages) + 1)}
disabled={visiblePages.includes(totalPages)}
> >
<i className='fas fa-arrow-right'></i> <i className='fas fa-arrow-right'></i>
</button> </button>

View File

@@ -13,12 +13,11 @@
height : auto; height : auto;
padding : 2px 0; padding : 2px 0;
font-family : 'Open Sans', sans-serif; font-family : 'Open Sans', sans-serif;
font-size : 13px;
color : #CCCCCC; color : #CCCCCC;
background-color : #555555; background-color : #555555;
& > *:not(.toggleButton) { & > *:not(.toggleButton) {
opacity: 1; opacity: 1;
transition : all 0.2s ease; transition: all .2s ease;
} }
.group { .group {
@@ -35,78 +34,14 @@
align-items : center; align-items : center;
} }
.active, [aria-checked='true'] { background-color : #444444; }
.anchored-trigger {
&.active { background-color : #444444; }
}
.anchored-box {
--box-color : #555555;
top : 30px;
display : flex;
flex-direction : column;
gap : 5px;
padding : 15px;
margin-top : 10px;
font-size : 0.8em;
color : #CCCCCC;
background-color : var(--box-color);
border-radius : 5px;
h1 {
padding-bottom : 0.3em;
margin-bottom : 0.5em;
border-bottom : 1px solid currentColor;
}
h2 {
padding-bottom : 0.3em;
margin : 1em 0 0.5em 0;
color : lightgray;
border-bottom : 1px solid currentColor;
}
label {
display : flex;
gap : 6px;
align-items : center;
justify-content : space-between;
}
input {
height : unset;
&[type='range'] { padding : 0; }
}
&::before {
position : absolute;
top : -20px;
left : 50%;
width : 0px;
height : 0px;
pointer-events : none;
content : '';
border : 10px solid transparent;
border-bottom : 10px solid var(--box-color);
transform : translateX(-50%);
}
}
.radio-group:has(button[role='radio']) {
display : flex;
height : 100%;
border : 1px solid #333333;
}
input { input {
position : relative; position : relative;
height : 1.5em; height : 1.5em;
padding : 2px 5px; padding : 2px 5px;
font-family : 'Open Sans', sans-serif; font-family : 'Open Sans', sans-serif;
color : inherit; color : #000000;
background : #3B3B3B; background : #EEEEEE;
border : none; border : 1px solid gray;
&:focus { outline : 1px solid #D3D3D3; } &:focus { outline : 1px solid #D3D3D3; }
// `.range-input` if generic to all range inputs, or `#zoom-slider` if only for zoom slider // `.range-input` if generic to all range inputs, or `#zoom-slider` if only for zoom slider
@@ -115,14 +50,14 @@
color : #D3D3D3; color : #D3D3D3;
accent-color : #D3D3D3; accent-color : #D3D3D3;
&::-webkit-slider-thumb, &::-moz-range-thumb { &::-webkit-slider-thumb, &::-moz-slider-thumb {
width : 5px; width : 5px;
height : 5px; height : 5px;
cursor : ew-resize; cursor : pointer;
outline : none; outline : none;
} }
&.hover-tooltip[value]:hover::after { &:hover::after {
position : absolute; position : absolute;
bottom : -30px; bottom : -30px;
left : 50%; left : 50%;
@@ -141,49 +76,53 @@
// `.text-input` if generic to all range inputs, or `#page-input` if only for current page input // `.text-input` if generic to all range inputs, or `#page-input` if only for current page input
&#page-input { &#page-input {
min-width : 5ch; width : 4ch;
margin-right : 1ch; margin-right : 1ch;
text-align : center; text-align : center;
} }
} }
button { button {
box-sizing : border-box; box-sizing : content-box;
display : flex; display : flex;
align-items : center; align-items : center;
justify-content : center; justify-content : center;
width : auto; width : auto;
min-width : 46px; min-width : 46px;
height : 100%; height : 100%;
padding : 0 0px;
font-weight : unset;
color : inherit;
background-color : unset;
&:hover { background-color : #444444; } &:hover { background-color : #444444; }
&:focus { border : 1px solid #D3D3D3;outline : none;} &:focus { outline : 1px solid #D3D3D3; }
&:disabled { &:disabled {
color : #777777; color : #777777;
background-color : unset !important; background-color : unset !important;
} }
i { font-size : 1.2em; } i {
font-size:1.2em;
}
} }
&.hidden { &.hidden {
width: 32px;
transition: all .3s ease;
flex-wrap:nowrap; flex-wrap:nowrap;
width : 92px;
overflow: hidden; overflow: hidden;
background-color: unset; background-color: unset;
opacity : 0.5; opacity: .5;
transition : all 0.3s ease;
& > *:not(.toggleButton) { & > *:not(.toggleButton) {
opacity: 0; opacity: 0;
transition : all 0.2s ease; transition: all .2s ease;
} }
} }
} }
.toggleButton { button.toggleButton {
z-index : 5;
position:absolute; position:absolute;
left: 0; left: 0;
z-index : 5;
width: 32px; width: 32px;
min-width: unset; min-width: unset;
height : 100%;
display : flex;
} }

View File

@@ -4,7 +4,7 @@ const React = require('react');
const createClass = require('create-react-class'); const createClass = require('create-react-class');
const _ = require('lodash'); const _ = require('lodash');
const dedent = require('dedent-tabs').default; const dedent = require('dedent-tabs').default;
import Markdown from '../../../shared/naturalcrit/markdown.js'; const Markdown = require('../../../shared/naturalcrit/markdown.js');
const CodeEditor = require('naturalcrit/codeEditor/codeEditor.jsx'); const CodeEditor = require('naturalcrit/codeEditor/codeEditor.jsx');
const SnippetBar = require('./snippetbar/snippetbar.jsx'); const SnippetBar = require('./snippetbar/snippetbar.jsx');
@@ -12,7 +12,6 @@ const MetadataEditor = require('./metadataEditor/metadataEditor.jsx');
const EDITOR_THEME_KEY = 'HOMEBREWERY-EDITOR-THEME'; const EDITOR_THEME_KEY = 'HOMEBREWERY-EDITOR-THEME';
const PAGEBREAK_REGEX_V3 = /^(?=\\page(?: *{[^\n{}]*})?$)/m;
const SNIPPETBAR_HEIGHT = 25; const SNIPPETBAR_HEIGHT = 25;
const DEFAULT_STYLE_TEXT = dedent` const DEFAULT_STYLE_TEXT = dedent`
/*=======--- Example CSS styling ---=======*/ /*=======--- Example CSS styling ---=======*/
@@ -127,15 +126,15 @@ const Editor = createClass({
}, },
updateCurrentCursorPage : function(cursor) { updateCurrentCursorPage : function(cursor) {
const lines = this.props.brew.text.split('\n').slice(1, cursor.line + 1); const lines = this.props.brew.text.split('\n').slice(0, cursor.line + 1);
const pageRegex = this.props.brew.renderer == 'V3' ? PAGEBREAK_REGEX_V3 : /\\page/; const pageRegex = this.props.brew.renderer == 'V3' ? /^\\page$/ : /\\page/;
const currentPage = lines.reduce((count, line)=>count + (pageRegex.test(line) ? 1 : 0), 1); const currentPage = lines.reduce((count, line)=>count + (pageRegex.test(line) ? 1 : 0), 1);
this.props.onCursorPageChange(currentPage); this.props.onCursorPageChange(currentPage);
}, },
updateCurrentViewPage : function(topScrollLine) { updateCurrentViewPage : function(topScrollLine) {
const lines = this.props.brew.text.split('\n').slice(1, topScrollLine + 1); const lines = this.props.brew.text.split('\n').slice(0, topScrollLine + 1);
const pageRegex = this.props.brew.renderer == 'V3' ? PAGEBREAK_REGEX_V3 : /\\page/; const pageRegex = this.props.brew.renderer == 'V3' ? /^\\page$/ : /\\page/;
const currentPage = lines.reduce((count, line)=>count + (pageRegex.test(line) ? 1 : 0), 1); const currentPage = lines.reduce((count, line)=>count + (pageRegex.test(line) ? 1 : 0), 1);
this.props.onViewPageChange(currentPage); this.props.onViewPageChange(currentPage);
}, },
@@ -175,7 +174,7 @@ const Editor = createClass({
for (let i=customHighlights.length - 1;i>=0;i--) customHighlights[i].clear(); for (let i=customHighlights.length - 1;i>=0;i--) customHighlights[i].clear();
let editorPageCount = 1; // start page count from page 1 let editorPageCount = 2; // start page count from page 2
_.forEach(this.props.brew.text.split('\n'), (line, lineNumber)=>{ _.forEach(this.props.brew.text.split('\n'), (line, lineNumber)=>{
@@ -191,10 +190,7 @@ const Editor = createClass({
// Styling for \page breaks // Styling for \page breaks
if((this.props.renderer == 'legacy' && line.includes('\\page')) || if((this.props.renderer == 'legacy' && line.includes('\\page')) ||
(this.props.renderer == 'V3' && line.match(PAGEBREAK_REGEX_V3))) { (this.props.renderer == 'V3' && line.match(/^\\page$/))) {
if(lineNumber > 0) // Since \page is optional on first line of document,
editorPageCount += 1; // don't use it to increment page count; stay at 1
// add back the original class 'background' but also add the new class '.pageline' // add back the original class 'background' but also add the new class '.pageline'
codeMirror.addLineClass(lineNumber, 'background', 'pageLine'); codeMirror.addLineClass(lineNumber, 'background', 'pageLine');
@@ -203,6 +199,8 @@ const Editor = createClass({
textContent : editorPageCount textContent : editorPageCount
}); });
codeMirror.setBookmark({ line: lineNumber, ch: line.length }, pageCountElement); codeMirror.setBookmark({ line: lineNumber, ch: line.length }, pageCountElement);
editorPageCount += 1;
}; };
// New Codemirror styling for V3 renderer // New Codemirror styling for V3 renderer
@@ -360,7 +358,7 @@ const Editor = createClass({
if(!this.isText() || isJumping) if(!this.isText() || isJumping)
return; return;
const textSplit = this.props.renderer == 'V3' ? PAGEBREAK_REGEX_V3 : /\\page/; const textSplit = this.props.renderer == 'V3' ? /^\\page$/gm : /\\page/;
const textString = this.props.brew.text.split(textSplit).slice(0, targetPage-1).join(textSplit); const textString = this.props.brew.text.split(textSplit).slice(0, targetPage-1).join(textSplit);
const targetLine = textString.match('\n') ? textString.split('\n').length - 1 : -1; const targetLine = textString.match('\n') ? textString.split('\n').length - 1 : -1;

View File

@@ -2,7 +2,6 @@
.editor { .editor {
position : relative; position : relative;
width : 100%; width : 100%;
container: editor / inline-size;
.codeEditor { .codeEditor {
height : 100%; height : 100%;

View File

@@ -3,10 +3,10 @@ require('./metadataEditor.less');
const React = require('react'); const React = require('react');
const createClass = require('create-react-class'); const createClass = require('create-react-class');
const _ = require('lodash'); const _ = require('lodash');
import request from '../../utils/request-middleware.js'; const request = require('../../utils/request-middleware.js');
const Nav = require('naturalcrit/nav/nav.jsx'); const Nav = require('naturalcrit/nav/nav.jsx');
const Combobox = require('client/components/combobox.jsx'); const Combobox = require('client/components/combobox.jsx');
const TagInput = require('../tagInput/tagInput.jsx'); const StringArrayEditor = require('../stringArrayEditor/stringArrayEditor.jsx');
const Themes = require('themes/themes.json'); const Themes = require('themes/themes.json');
@@ -341,11 +341,10 @@ const MetadataEditor = createClass({
{this.renderThumbnail()} {this.renderThumbnail()}
</div> </div>
<TagInput label='tags' valuePatterns={[/^(?:(?:group|meta|system|type):)?[A-Za-z0-9][A-Za-z0-9 \/.\-]{0,40}$/]} <StringArrayEditor label='tags' valuePatterns={[/^(?:(?:group|meta|system|type):)?[A-Za-z0-9][A-Za-z0-9 \/.\-]{0,40}$/]}
placeholder='add tag' unique={true} placeholder='add tag' unique={true}
values={this.props.metadata.tags} values={this.props.metadata.tags}
onChange={(e)=>this.handleFieldChange('tags', e)} onChange={(e)=>this.handleFieldChange('tags', e)}/>
/>
<div className='field systems'> <div className='field systems'>
<label>systems</label> <label>systems</label>
@@ -364,13 +363,12 @@ const MetadataEditor = createClass({
{this.renderAuthors()} {this.renderAuthors()}
<TagInput label='invited authors' valuePatterns={[/.+/]} <StringArrayEditor label='invited authors' valuePatterns={[/.+/]}
validators={[(v)=>!this.props.metadata.authors?.includes(v)]} validators={[(v)=>!this.props.metadata.authors?.includes(v)]}
placeholder='invite author' unique={true} placeholder='invite author' unique={true}
values={this.props.metadata.invitedAuthors} values={this.props.metadata.invitedAuthors}
notes={['Invited author usernames are case sensitive.', 'After adding an invited author, send them the edit link. There, they can choose to accept or decline the invitation.']} notes={['Invited author usernames are case sensitive.', 'After adding an invited author, send them the edit link. There, they can choose to accept or decline the invitation.']}
onChange={(e)=>this.handleFieldChange('invitedAuthors', e)} onChange={(e)=>this.handleFieldChange('invitedAuthors', e)}/>
/>
<h2>Privacy</h2> <h2>Privacy</h2>

View File

@@ -79,7 +79,6 @@
text-overflow : ellipsis; text-overflow : ellipsis;
} }
button { button {
.colorButton();
padding : 0px 5px; padding : 0px 5px;
color : white; color : white;
background-color : black; background-color : black;
@@ -139,16 +138,16 @@
margin-bottom : 15px; margin-bottom : 15px;
button { width : 100%; } button { width : 100%; }
button.publish { button.publish {
.colorButton(@blueLight); .button(@blueLight);
} }
button.unpublish { button.unpublish {
.colorButton(@silver); .button(@silver);
} }
} }
.delete.field .value { .delete.field .value {
button { button {
.colorButton(@red); .button(@red);
} }
} }
.authors.field .value { .authors.field .value {
@@ -272,7 +271,7 @@
&:last-child { border-radius : 0 0.5em 0.5em 0; } &:last-child { border-radius : 0 0.5em 0.5em 0; }
} }
.tag { .badge {
padding : 0.3em; padding : 0.3em;
margin : 2px; margin : 2px;
font-size : 0.9em; font-size : 0.9em;

View File

@@ -150,10 +150,8 @@ const Snippetbar = createClass({
renderSnippetGroups : function(){ renderSnippetGroups : function(){
const snippets = this.state.snippets.filter((snippetGroup)=>snippetGroup.view === this.props.view); const snippets = this.state.snippets.filter((snippetGroup)=>snippetGroup.view === this.props.view);
if(snippets.length === 0) return null;
return <div className='snippets'> return _.map(snippets, (snippetGroup)=>{
{_.map(snippets, (snippetGroup)=>{
return <SnippetGroup return <SnippetGroup
brew={this.props.brew} brew={this.props.brew}
groupName={snippetGroup.groupName} groupName={snippetGroup.groupName}
@@ -163,9 +161,7 @@ const Snippetbar = createClass({
onSnippetClick={this.handleSnippetClick} onSnippetClick={this.handleSnippetClick}
cursorPos={this.props.cursorPos} cursorPos={this.props.cursorPos}
/>; />;
}) });
}
</div>;
}, },
replaceContent : function(item){ replaceContent : function(item){
@@ -207,11 +203,23 @@ const Snippetbar = createClass({
renderEditorButtons : function(){ renderEditorButtons : function(){
if(!this.props.showEditButtons) return; if(!this.props.showEditButtons) return;
let foldButtons;
if(this.props.view == 'text'){
foldButtons =
<>
<div className={`editorTool foldAll ${this.props.foldCode ? 'active' : ''}`}
onClick={this.props.foldCode} >
<i className='fas fa-compress-alt' />
</div>
<div className={`editorTool unfoldAll ${this.props.unfoldCode ? 'active' : ''}`}
onClick={this.props.unfoldCode} >
<i className='fas fa-expand-alt' />
</div>
</>;
}
return ( return <div className='editors'>
<div className='editors'>
{this.props.view !== 'meta' && <><div className='historyTools'>
<div className={`editorTool snippetGroup history ${this.state.historyExists ? 'active' : ''}`} <div className={`editorTool snippetGroup history ${this.state.historyExists ? 'active' : ''}`}
onClick={this.toggleHistoryMenu} > onClick={this.toggleHistoryMenu} >
<i className='fas fa-clock-rotate-left' /> <i className='fas fa-clock-rotate-left' />
@@ -225,25 +233,15 @@ const Snippetbar = createClass({
onClick={this.props.redo} > onClick={this.props.redo} >
<i className='fas fa-redo' /> <i className='fas fa-redo' />
</div> </div>
</div> <div className='divider'></div>
<div className='codeTools'> {foldButtons}
<div className={`editorTool foldAll ${this.props.foldCode ? 'active' : ''}`} <div className={`editorTool editorTheme ${this.state.themeSelector ? 'active' : ''}`}
onClick={this.props.foldCode} >
<i className='fas fa-compress-alt' />
</div>
<div className={`editorTool unfoldAll ${this.props.unfoldCode ? 'active' : ''}`}
onClick={this.props.unfoldCode} >
<i className='fas fa-expand-alt' />
</div>
<div className={`editorTheme ${this.state.themeSelector ? 'active' : ''}`}
onClick={this.toggleThemeSelector} > onClick={this.toggleThemeSelector} >
<i className='fas fa-palette' /> <i className='fas fa-palette' />
{this.state.themeSelector && this.renderThemeSelector()} {this.state.themeSelector && this.renderThemeSelector()}
</div> </div>
</div></>}
<div className='divider'></div>
<div className='tabs'>
<div className={cx('text', { selected: this.props.view === 'text' })} <div className={cx('text', { selected: this.props.view === 'text' })}
onClick={()=>this.props.onViewChange('text')}> onClick={()=>this.props.onViewChange('text')}>
<i className='fa fa-beer' /> <i className='fa fa-beer' />
@@ -256,10 +254,7 @@ const Snippetbar = createClass({
onClick={()=>this.props.onViewChange('meta')}> onClick={()=>this.props.onViewChange('meta')}>
<i className='fas fa-info-circle' /> <i className='fas fa-info-circle' />
</div> </div>
</div> </div>;
</div>
)
}, },
render : function(){ render : function(){
@@ -296,9 +291,8 @@ const SnippetGroup = createClass({
return _.map(snippets, (snippet)=>{ return _.map(snippets, (snippet)=>{
return <div className='snippet' key={snippet.name} onClick={(e)=>this.handleSnippetClick(e, snippet)}> return <div className='snippet' key={snippet.name} onClick={(e)=>this.handleSnippetClick(e, snippet)}>
<i className={snippet.icon} /> <i className={snippet.icon} />
<span className={`name${snippet.disabled ? ' disabled' : ''}`} title={snippet.name}>{snippet.name}</span> <span className='name'title={snippet.name}>{snippet.name}</span>
{snippet.experimental && <span className='beta'>beta</span>} {snippet.experimental && <span className='beta'>beta</span>}
{snippet.disabled && <span className='beta' title='temporarily disabled due to large slowdown; under re-design'>disabled</span>}
{snippet.subsnippets && <> {snippet.subsnippets && <>
<i className='fas fa-caret-right'></i> <i className='fas fa-caret-right'></i>
<div className='dropdown side'> <div className='dropdown side'>

View File

@@ -4,45 +4,23 @@
.snippetBar { .snippetBar {
@menuHeight : 25px; @menuHeight : 25px;
position : relative; position : relative;
display : flex; height : @menuHeight;
flex-wrap : wrap-reverse;
justify-content : space-between;
height : auto;
color : black; color : black;
background-color : #DDDDDD; background-color : #DDDDDD;
.snippets {
display : flex;
justify-content : flex-start;
min-width : 327.58px;
}
.editors { .editors {
position : absolute;
top : 0px;
right : 0px;
display : flex; display : flex;
justify-content : flex-end; justify-content : space-between;
min-width : 225px; height : @menuHeight;
&:only-child { margin-left : auto;min-width:unset;}
>div {
display : flex;
flex : 1;
justify-content : space-around;
&:first-child { border-left : none; }
& > div { & > div {
position : relative;
width : @menuHeight; width : @menuHeight;
height : @menuHeight; height : @menuHeight;
line-height : @menuHeight; line-height : @menuHeight;
text-align : center; text-align : center;
cursor : pointer; cursor : pointer;
&.editorTool:not(.active) {
cursor:not-allowed;
}
&:hover,&.selected { background-color : #999999; } &:hover,&.selected { background-color : #999999; }
&.text { &.text {
.tooltipLeft('Brew Editor'); .tooltipLeft('Brew Editor');
@@ -68,25 +46,26 @@
&.foldAll { &.foldAll {
.tooltipLeft('Fold All'); .tooltipLeft('Fold All');
font-size : 0.75em; font-size : 0.75em;
color : grey; color : inherit;
&.active { color : inherit; }
} }
&.unfoldAll { &.unfoldAll {
.tooltipLeft('Unfold All'); .tooltipLeft('Unfold All');
font-size : 0.75em; font-size : 0.75em;
color : grey; color : inherit;
&.active { color : inherit; }
} }
&.history { &.history {
.tooltipLeft('History'); .tooltipLeft('History');
position : relative;
font-size : 0.75em; font-size : 0.75em;
color : grey; color : grey;
border : none; position : relative;
&.active { color : inherit; } &.active {
color : inherit;
}
&>.dropdown{ &>.dropdown{
right : -1px; right : -1px;
& > .snippet { padding-right : 10px; } &>.snippet{
padding-right : 10px;
}
} }
} }
&.editorTheme { &.editorTheme {
@@ -117,7 +96,6 @@
background-color : inherit; background-color : inherit;
} }
} }
}
.snippetBarButton { .snippetBarButton {
display : inline-block; display : inline-block;
height : @menuHeight; height : @menuHeight;
@@ -126,7 +104,6 @@
font-weight : 800; font-weight : 800;
line-height : @menuHeight; line-height : @menuHeight;
text-transform : uppercase; text-transform : uppercase;
text-wrap : nowrap;
cursor : pointer; cursor : pointer;
&:hover, &.selected { background-color : #999999; } &:hover, &.selected { background-color : #999999; }
i { i {
@@ -143,7 +120,7 @@
.tooltipLeft('Edit Brew Properties'); .tooltipLeft('Edit Brew Properties');
} }
.snippetGroup { .snippetGroup {
border-right : 1px solid currentColor;
&:hover { &:hover {
& > .dropdown { visibility : visible; } & > .dropdown { visibility : visible; }
} }
@@ -165,10 +142,10 @@
cursor : pointer; cursor : pointer;
.animate(background-color); .animate(background-color);
i { i {
min-width : 25px;
height : 1.2em; height : 1.2em;
margin-right : 8px; margin-right : 8px;
font-size : 1.2em; font-size : 1.2em;
min-width: 25px;
text-align: center; text-align: center;
& ~ i { & ~ i {
margin-right : 0; margin-right : 0;
@@ -202,7 +179,6 @@
} }
} }
.name { margin-right : auto; } .name { margin-right : auto; }
.disabled { text-decoration : line-through; }
.beta { .beta {
align-self : center; align-self : center;
padding : 4px 6px; padding : 4px 6px;
@@ -229,18 +205,3 @@
} }
} }
} }
@container editor (width < 553px) {
.snippetBar {
.editors {
flex : 1;
justify-content : space-between;
border-bottom : 1px solid;
}
.snippets {
flex : 1;
justify-content : space-evenly;
}
.editors > div.history > .dropdown { right : unset; }
}
}

View File

@@ -0,0 +1,149 @@
const React = require('react');
const createClass = require('create-react-class');
const _ = require('lodash');
const StringArrayEditor = createClass({
displayName : 'StringArrayEditor',
getDefaultProps : function() {
return {
label : '',
values : [],
valuePatterns : null,
validators : [],
placeholder : '',
notes : [],
unique : false,
cannotEdit : [],
onChange : ()=>{}
};
},
getInitialState : function() {
return {
valueContext : !!this.props.values ? this.props.values.map((value)=>({
value,
editing : false
})) : [],
temporaryValue : '',
updateValue : ''
};
},
componentDidUpdate : function(prevProps) {
if(!_.eq(this.props.values, prevProps.values)) {
this.setState({
valueContext : this.props.values ? this.props.values.map((newValue)=>({
value : newValue,
editing : this.state.valueContext.find(({ value })=>value === newValue)?.editing || false
})) : []
});
}
},
handleChange : function(value) {
this.props.onChange({
target : {
value
}
});
},
addValue : function(value){
this.handleChange(_.uniq([...this.props.values, value]));
this.setState({
temporaryValue : ''
});
},
removeValue : function(index){
this.handleChange(this.props.values.filter((_, i)=>i !== index));
},
updateValue : function(value, index){
const valueContext = this.state.valueContext;
valueContext[index].value = value;
valueContext[index].editing = false;
this.handleChange(valueContext.map((context)=>context.value));
this.setState({ valueContext, updateValue: '' });
},
editValue : function(index){
if(!!this.props.cannotEdit && this.props.cannotEdit.includes(this.props.values[index])) {
return;
}
const valueContext = this.state.valueContext.map((context, i)=>{
context.editing = index === i;
return context;
});
this.setState({ valueContext, updateValue: this.props.values[index] });
},
valueIsValid : function(value, index) {
const values = _.clone(this.props.values);
if(index !== undefined) {
values.splice(index, 1);
}
const matchesPatterns = !this.props.valuePatterns || this.props.valuePatterns.some((pattern)=>!!(value || '').match(pattern));
const uniqueIfSet = !this.props.unique || !values.includes(value);
const passesValidators = !this.props.validators || this.props.validators.every((validator)=>validator(value));
return matchesPatterns && uniqueIfSet && passesValidators;
},
handleValueInputKeyDown : function(event, index) {
if(event.key === 'Enter') {
if(this.valueIsValid(event.target.value, index)) {
if(index !== undefined) {
this.updateValue(event.target.value, index);
} else {
this.addValue(event.target.value);
}
}
} else if(event.key === 'Escape') {
this.closeEditInput(index);
}
},
closeEditInput : function(index) {
const valueContext = this.state.valueContext;
valueContext[index].editing = false;
this.setState({ valueContext, updateValue: '' });
},
render : function() {
const valueElements = Object.values(this.state.valueContext).map((context, i)=>context.editing
? <React.Fragment key={i}>
<div className='input-group'>
<input type='text' className={`value ${this.valueIsValid(this.state.updateValue, i) ? '' : 'invalid'}`} autoFocus placeholder={this.props.placeholder}
value={this.state.updateValue}
onKeyDown={(e)=>this.handleValueInputKeyDown(e, i)}
onChange={(e)=>this.setState({ updateValue: e.target.value })}/>
{<div className='icon steel' onClick={(e)=>{ e.stopPropagation(); this.closeEditInput(i); }}><i className='fa fa-undo fa-fw'/></div>}
{this.valueIsValid(this.state.updateValue, i) ? <div className='icon steel' onClick={(e)=>{ e.stopPropagation(); this.updateValue(this.state.updateValue, i); }}><i className='fa fa-check fa-fw'/></div> : null}
</div>
</React.Fragment>
: <div className='badge' key={i} onClick={()=>this.editValue(i)}>{context.value}
{!!this.props.cannotEdit && this.props.cannotEdit.includes(context.value) ? null : <div className='icon steel' onClick={(e)=>{ e.stopPropagation(); this.removeValue(i); }}><i className='fa fa-times fa-fw'/></div>}
</div>
);
return <div className='field'>
<label>{this.props.label}</label>
<div style={{ flex: '1 0' }} className='value'>
<div className='list'>
{valueElements}
<div className='input-group'>
<input type='text' className={`value ${this.valueIsValid(this.state.temporaryValue) ? '' : 'invalid'}`} placeholder={this.props.placeholder}
value={this.state.temporaryValue}
onKeyDown={(e)=>this.handleValueInputKeyDown(e)}
onChange={(e)=>this.setState({ temporaryValue: e.target.value })}/>
{this.valueIsValid(this.state.temporaryValue) ? <div className='icon steel' onClick={(e)=>{ e.stopPropagation(); this.addValue(this.state.temporaryValue); }}><i className='fa fa-check fa-fw'/></div> : null}
</div>
</div>
{this.props.notes ? this.props.notes.map((n, index)=><p key={index}><small>{n}</small></p>) : null}
</div>
</div>;
}
});
module.exports = StringArrayEditor;

View File

@@ -1,105 +0,0 @@
require('./tagInput.less');
const React = require('react');
const { useState, useEffect } = React;
const _ = require('lodash');
const TagInput = ({ unique = true, values = [], ...props }) => {
const [tempInputText, setTempInputText] = useState('');
const [tagList, setTagList] = useState(values.map((value) => ({ value, editing: false })));
useEffect(()=>{
handleChange(tagList.map((context)=>context.value))
}, [tagList])
const handleChange = (value)=>{
props.onChange({
target : { value }
})
};
const handleInputKeyDown = ({ evt, value, index, options = {} }) => {
if (_.includes(['Enter', ','], evt.key)) {
evt.preventDefault();
submitTag(evt.target.value, value, index);
if (options.clear) {
setTempInputText('');
}
}
};
const submitTag = (newValue, originalValue, index) => {
setTagList((prevContext) => {
// remove existing tag
if(newValue === null){
return [...prevContext].filter((context, i)=>i !== index);
}
// add new tag
if(originalValue === null){
return [...prevContext, { value: newValue, editing: false }]
}
// update existing tag
return prevContext.map((context, i) => {
if (i === index) {
return { ...context, value: newValue, editing: false };
}
return context;
});
});
};
const editTag = (index) => {
setTagList((prevContext) => {
return prevContext.map((context, i) => {
if (i === index) {
return { ...context, editing: true };
}
return { ...context, editing: false };
});
});
};
const renderReadTag = (context, index) => {
return (
<li key={index}
data-value={context.value}
className='tag'
onClick={() => editTag(index)}>
{context.value}
<button onClick={(evt)=>{evt.stopPropagation(); submitTag(null, context.value, index)}}><i className='fa fa-times fa-fw'/></button>
</li>
);
};
const renderWriteTag = (context, index) => {
return (
<input type='text'
key={index}
defaultValue={context.value}
onKeyDown={(evt) => handleInputKeyDown({evt, value: context.value, index: index})}
autoFocus
/>
);
};
return (
<div className='field'>
<label>{props.label}</label>
<div className='value'>
<ul className='list'>
{tagList.map((context, index) => { return context.editing ? renderWriteTag(context, index) : renderReadTag(context, index); })}
</ul>
<input
type='text'
className='value'
placeholder={props.placeholder}
value={tempInputText}
onChange={(e) => setTempInputText(e.target.value)}
onKeyDown={(evt) => handleInputKeyDown({ evt, value: null, options: { clear: true } })}
/>
</div>
</div>
);
};
module.exports = TagInput;

View File

@@ -1,12 +1,8 @@
//╔===--------------- Polyfills --------------===╗//
import 'core-js/es/string/to-well-formed.js';
//╚===--------------- ---------------===╝//
require('./homebrew.less'); require('./homebrew.less');
const React = require('react'); const React = require('react');
const createClass = require('create-react-class'); const createClass = require('create-react-class');
const { StaticRouter:Router } = require('react-router'); const { StaticRouter:Router } = require('react-router-dom/server');
const { Route, Routes, useParams, useSearchParams } = require('react-router'); const { Route, Routes, useParams, useSearchParams } = require('react-router-dom');
const HomePage = require('./pages/homePage/homePage.jsx'); const HomePage = require('./pages/homePage/homePage.jsx');
const EditPage = require('./pages/editPage/editPage.jsx'); const EditPage = require('./pages/editPage/editPage.jsx');

View File

@@ -25,11 +25,12 @@
.homebrew nav { .homebrew nav {
background-color : #333333; background-color : #333333;
.navContent {
position : relative; position : relative;
z-index : 2; z-index : 2;
display : flex; display : flex;
justify-content : space-between; justify-content : space-between;
}
.navSection { .navSection {
display : flex; display : flex;
align-items : center; align-items : center;

View File

@@ -1,149 +1,154 @@
require('./brewItem.less'); require('./brewItem.less');
const React = require('react'); const React = require('react');
const { useCallback } = React; const createClass = require('create-react-class');
const moment = require('moment'); const moment = require('moment');
import request from '../../../../utils/request-middleware.js'; const request = require('../../../../utils/request-middleware.js');
const googleDriveIcon = require('../../../../googleDrive.svg'); const googleDriveIcon = require('../../../../googleDrive.svg');
const homebreweryIcon = require('../../../../thumbnail.png'); const homebreweryIcon = require('../../../../thumbnail.png');
const dedent = require('dedent-tabs').default; const dedent = require('dedent-tabs').default;
const BrewItem = ({ const BrewItem = createClass({
brew = { displayName : 'BrewItem',
getDefaultProps : function() {
return {
brew : {
title : '', title : '',
description : '', description : '',
authors : [], authors : [],
stubbed : true, stubbed : true
},
updateListFilter : ()=>{},
reportError : ()=>{},
renderStorage : true
};
}, },
updateListFilter = ()=>{},
reportError = ()=>{},
renderStorage = true,
})=>{
const deleteBrew = useCallback(()=>{ deleteBrew : function(){
if(brew.authors.length <= 1) { if(this.props.brew.authors.length <= 1){
if(!window.confirm('Are you sure you want to delete this brew? Because you are the only owner of this brew, the document will be deleted permanently.')) return; if(!confirm('Are you sure you want to delete this brew? Because you are the only owner of this brew, the document will be deleted permanently.')) return;
if(!window.confirm('Are you REALLY sure? You will not be able to recover the document.')) return; if(!confirm('Are you REALLY sure? You will not be able to recover the document.')) return;
} else { } else {
if(!window.confirm('Are you sure you want to remove this brew from your collection? This will remove you as an editor, but other owners will still be able to access the document.')) return; if(!confirm('Are you sure you want to remove this brew from your collection? This will remove you as an editor, but other owners will still be able to access the document.')) return;
if(!window.confirm('Are you REALLY sure? You will lose editor access to this document.')) return; if(!confirm('Are you REALLY sure? You will lose editor access to this document.')) return;
} }
request.delete(`/api/${brew.googleId ?? ''}${brew.editId}`).send().end((err, res)=>{ request.delete(`/api/${this.props.brew.googleId ?? ''}${this.props.brew.editId}`)
if (err) reportError(err); else window.location.reload(); .send()
.end((err, res)=>{
if(err) {
this.props.reportError(err);
} else {
location.reload();
}
}); });
}, [brew, reportError]); },
const updateFilter = useCallback((type, term)=> updateListFilter(type, term), [updateListFilter]); updateFilter : function(type, term){
this.props.updateListFilter(type, term);
},
const renderDeleteBrewLink = ()=>{ renderDeleteBrewLink : function(){
if(!brew.editId) return null; if(!this.props.brew.editId) return;
return ( return <a className='deleteLink' onClick={this.deleteBrew}>
<a className='deleteLink' onClick={deleteBrew}>
<i className='fas fa-trash-alt' title='Delete' /> <i className='fas fa-trash-alt' title='Delete' />
</a> </a>;
); },
};
const renderEditLink = ()=>{ renderEditLink : function(){
if(!brew.editId) return null; if(!this.props.brew.editId) return;
let editLink = brew.editId; let editLink = this.props.brew.editId;
if(brew.googleId && !brew.stubbed) editLink = brew.googleId + editLink; if(this.props.brew.googleId && !this.props.brew.stubbed) {
editLink = this.props.brew.googleId + editLink;
}
return ( return <a className='editLink' href={`/edit/${editLink}`} target='_blank' rel='noopener noreferrer'>
<a className='editLink' href={`/edit/${editLink}`} target='_blank' rel='noopener noreferrer'>
<i className='fas fa-pencil-alt' title='Edit' /> <i className='fas fa-pencil-alt' title='Edit' />
</a> </a>;
); },
};
const renderShareLink = ()=>{ renderShareLink : function(){
if(!brew.shareId) return null; if(!this.props.brew.shareId) return;
let shareLink = brew.shareId; let shareLink = this.props.brew.shareId;
if(brew.googleId && !brew.stubbed) { if(this.props.brew.googleId && !this.props.brew.stubbed) {
shareLink = brew.googleId + shareLink; shareLink = this.props.brew.googleId + shareLink;
} }
return ( return <a className='shareLink' href={`/share/${shareLink}`} target='_blank' rel='noopener noreferrer'>
<a className='shareLink' href={`/share/${shareLink}`} target='_blank' rel='noopener noreferrer'>
<i className='fas fa-share-alt' title='Share' /> <i className='fas fa-share-alt' title='Share' />
</a> </a>;
); },
};
const renderDownloadLink = ()=>{ renderDownloadLink : function(){
if(!brew.shareId) return null; if(!this.props.brew.shareId) return;
let shareLink = brew.shareId; let shareLink = this.props.brew.shareId;
if(brew.googleId && !brew.stubbed) { if(this.props.brew.googleId && !this.props.brew.stubbed) {
shareLink = brew.googleId + shareLink; shareLink = this.props.brew.googleId + shareLink;
} }
return ( return <a className='downloadLink' href={`/download/${shareLink}`}>
<a className='downloadLink' href={`/download/${shareLink}`}>
<i className='fas fa-download' title='Download' /> <i className='fas fa-download' title='Download' />
</a> </a>;
); },
};
const renderStorageIcon = ()=>{ renderStorageIcon : function(){
if(!renderStorage) return null; if(!this.props.renderStorage) return;
if(brew.googleId) { if(this.props.brew.googleId) {
return ( return <span title={this.props.brew.webViewLink ? 'Your Google Drive Storage': 'Another User\'s Google Drive Storage'}>
<span title={brew.webViewLink ? 'Your Google Drive Storage' : 'Another User\'s Google Drive Storage'}> <a href={this.props.brew.webViewLink} target='_blank'>
<a href={brew.webViewLink} target='_blank'>
<img className='googleDriveIcon' src={googleDriveIcon} alt='googleDriveIcon' /> <img className='googleDriveIcon' src={googleDriveIcon} alt='googleDriveIcon' />
</a> </a>
</span> </span>;
);
} }
return ( return <span title='Homebrewery Storage'>
<span title='Homebrewery Storage'>
<img className='homebreweryIcon' src={homebreweryIcon} alt='homebreweryIcon' /> <img className='homebreweryIcon' src={homebreweryIcon} alt='homebreweryIcon' />
</span> </span>;
); },
};
if(Array.isArray(brew.tags)) { render : function(){
const brew = this.props.brew;
if(Array.isArray(brew.tags)) { // temporary fix until dud tags are cleaned
brew.tags = brew.tags?.filter((tag)=>tag); //remove tags that are empty strings brew.tags = brew.tags?.filter((tag)=>tag); //remove tags that are empty strings
brew.tags.sort((a, b)=>{ brew.tags.sort((a, b)=>{
return a.indexOf(':') - b.indexOf(':') !== 0 ? a.indexOf(':') - b.indexOf(':') : a.toLowerCase().localeCompare(b.toLowerCase()); return a.indexOf(':') - b.indexOf(':') != 0 ? a.indexOf(':') - b.indexOf(':') : a.toLowerCase().localeCompare(b.toLowerCase());
}); });
} }
const dateFormatString = 'YYYY-MM-DD HH:mm:ss'; const dateFormatString = 'YYYY-MM-DD HH:mm:ss';
return ( return <div className='brewItem'>
<div className='brewItem'> {brew.thumbnail &&
{brew.thumbnail && <div className='thumbnail' style={{ backgroundImage: `url(${brew.thumbnail})` }}></div>} <div className='thumbnail' style={{ backgroundImage: `url(${brew.thumbnail})` }} >
</div>
}
<div className='text'> <div className='text'>
<h2>{brew.title}</h2> <h2>{brew.title}</h2>
<p className='description'>{brew.description}</p> <p className='description'>{brew.description}</p>
</div> </div>
<hr /> <hr />
<div className='info'> <div className='info'>
{brew.tags?.length ? (
{brew.tags?.length ? <>
<div className='brewTags' title={`${brew.tags.length} tags:\n${brew.tags.join('\n')}`}> <div className='brewTags' title={`${brew.tags.length} tags:\n${brew.tags.join('\n')}`}>
<i className='fas fa-tags'/> <i className='fas fa-tags'/>
{brew.tags.map((tag, idx)=>{ {brew.tags.map((tag, idx)=>{
const matches = tag.match(/^(?:([^:]+):)?([^:]+)$/); const matches = tag.match(/^(?:([^:]+):)?([^:]+)$/);
return <span key={idx} className={matches[1]} onClick={()=>updateFilter(tag)}>{matches[2]}</span>; return <span key={idx} className={matches[1]} onClick={()=>{this.updateFilter(tag);}}>{matches[2]}</span>;
})} })}
</div> </div>
) : null} </> : <></>
}
<span title={`Authors:\n${brew.authors?.join('\n')}`}> <span title={`Authors:\n${brew.authors?.join('\n')}`}>
<i className='fas fa-user' />{' '} <i className='fas fa-user'/> {brew.authors?.map((author, index)=>(
{brew.authors?.map((author, index)=>(
<React.Fragment key={index}> <React.Fragment key={index}>
{author === 'hidden' ? ( {author === 'hidden'
<span title="Username contained an email address; hidden to protect user's privacy"> ? <span title="Username contained an email address; hidden to protect user's privacy">{author}</span>
{author} : <a href={`/user/${author}`}>{author}</a>
</span> }
) : (<a href={`/user/${author}`}>{author}</a>)}
{index < brew.authors.length - 1 && ', '} {index < brew.authors.length - 1 && ', '}
</React.Fragment> </React.Fragment>
))} ))}
@@ -152,28 +157,27 @@ const BrewItem = ({
<span title={`Last viewed: ${moment(brew.lastViewed).local().format(dateFormatString)}`}> <span title={`Last viewed: ${moment(brew.lastViewed).local().format(dateFormatString)}`}>
<i className='fas fa-eye'/> {brew.views} <i className='fas fa-eye'/> {brew.views}
</span> </span>
{brew.pageCount && ( {brew.pageCount &&
<span title={`Page count: ${brew.pageCount}`}> <span title={`Page count: ${brew.pageCount}`}>
<i className='far fa-file' /> {brew.pageCount} <i className='far fa-file' /> {brew.pageCount}
</span> </span>
)} }
<span <span title={dedent`
title={dedent` Created: ${moment(brew.createdAt).local().format(dateFormatString)} Created: ${moment(brew.createdAt).local().format(dateFormatString)}
Last updated: ${moment(brew.updatedAt).local().format(dateFormatString)}`} Last updated: ${moment(brew.updatedAt).local().format(dateFormatString)}`}>
>
<i className='fas fa-sync-alt' /> {moment(brew.updatedAt).fromNow()} <i className='fas fa-sync-alt' /> {moment(brew.updatedAt).fromNow()}
</span> </span>
{renderStorageIcon()} {this.renderStorageIcon()}
</div> </div>
<div className='links'> <div className='links'>
{renderShareLink()} {this.renderShareLink()}
{renderEditLink()} {this.renderEditLink()}
{renderDownloadLink()} {this.renderDownloadLink()}
{renderDeleteBrewLink()} {this.renderDeleteBrewLink()}
</div> </div>
</div> </div>;
); }
}; });
module.exports = BrewItem; module.exports = BrewItem;

View File

@@ -4,7 +4,7 @@ const React = require('react');
const _ = require('lodash'); const _ = require('lodash');
const createClass = require('create-react-class'); const createClass = require('create-react-class');
import request from '../../utils/request-middleware.js'; const request = require('../../utils/request-middleware.js');
const { Meta } = require('vitreum/headtags'); const { Meta } = require('vitreum/headtags');
const Nav = require('naturalcrit/nav/nav.jsx'); const Nav = require('naturalcrit/nav/nav.jsx');
@@ -16,7 +16,6 @@ const PrintNavItem = require('../../navbar/print.navitem.jsx');
const ErrorNavItem = require('../../navbar/error-navitem.jsx'); const ErrorNavItem = require('../../navbar/error-navitem.jsx');
const Account = require('../../navbar/account.navitem.jsx'); const Account = require('../../navbar/account.navitem.jsx');
const RecentNavItem = require('../../navbar/recent.navitem.jsx').both; const RecentNavItem = require('../../navbar/recent.navitem.jsx').both;
const VaultNavItem = require('../../navbar/vault.navitem.jsx');
const SplitPane = require('naturalcrit/splitPane/splitPane.jsx'); const SplitPane = require('naturalcrit/splitPane/splitPane.jsx');
const Editor = require('../../editor/editor.jsx'); const Editor = require('../../editor/editor.jsx');
@@ -24,7 +23,7 @@ const BrewRenderer = require('../../brewRenderer/brewRenderer.jsx');
const LockNotification = require('./lockNotification/lockNotification.jsx'); const LockNotification = require('./lockNotification/lockNotification.jsx');
import Markdown from 'naturalcrit/markdown.js'; const Markdown = require('naturalcrit/markdown.js');
const { DEFAULT_BREW_LOAD } = require('../../../../server/brewDefaults.js'); const { DEFAULT_BREW_LOAD } = require('../../../../server/brewDefaults.js');
const { printCurrentBrew, fetchThemeBundle } = require('../../../../shared/helpers.js'); const { printCurrentBrew, fetchThemeBundle } = require('../../../../shared/helpers.js');
@@ -229,8 +228,8 @@ const EditPage = createClass({
htmlErrors : Markdown.validate(prevState.brew.text) htmlErrors : Markdown.validate(prevState.brew.text)
})); }));
await updateHistory(this.state.brew).catch(console.error); await updateHistory(this.state.brew);
await versionHistoryGarbageCollection().catch(console.error); await versionHistoryGarbageCollection();
const transfer = this.state.saveGoogle == _.isNil(this.state.brew.googleId); const transfer = this.state.saveGoogle == _.isNil(this.state.brew.googleId);
@@ -381,7 +380,7 @@ const EditPage = createClass({
**[Homebrewery Link](${global.config.publicUrl}/share/${shareLink})**`; **[Homebrewery Link](${global.config.publicUrl}/share/${shareLink})**`;
return `https://www.reddit.com/r/UnearthedArcana/submit?title=${encodeURIComponent(title.toWellFormed())}&text=${encodeURIComponent(text)}`; return `https://www.reddit.com/r/UnearthedArcana/submit?title=${encodeURIComponent(title)}&text=${encodeURIComponent(text)}`;
}, },
renderNavbar : function(){ renderNavbar : function(){
@@ -418,7 +417,6 @@ const EditPage = createClass({
</Nav.item> </Nav.item>
</Nav.dropdown> </Nav.dropdown>
<PrintNavItem /> <PrintNavItem />
<VaultNavItem />
<RecentNavItem brew={this.state.brew} storageKey='edit' /> <RecentNavItem brew={this.state.brew} storageKey='edit' />
<Account /> <Account />
</Nav.section> </Nav.section>
@@ -431,8 +429,8 @@ const EditPage = createClass({
<Meta name='robots' content='noindex, nofollow' /> <Meta name='robots' content='noindex, nofollow' />
{this.renderNavbar()} {this.renderNavbar()}
{this.props.brew.lock && <LockNotification shareId={this.props.brew.shareId} message={this.props.brew.lock.editMessage} />}
<div className='content'> <div className='content'>
{this.props.brew.lock && <LockNotification shareId={this.props.brew.shareId} message={this.props.brew.lock.editMessage} />}
<SplitPane onDragFinish={this.handleSplitMove}> <SplitPane onDragFinish={this.handleSplitMove}>
<Editor <Editor
ref={this.editor} ref={this.editor}

View File

@@ -1,7 +1,7 @@
require('./errorPage.less'); require('./errorPage.less');
const React = require('react'); const React = require('react');
const UIPage = require('../basePages/uiPage/uiPage.jsx'); const UIPage = require('../basePages/uiPage/uiPage.jsx');
import Markdown from '../../../../shared/naturalcrit/markdown.js'; const Markdown = require('../../../../shared/naturalcrit/markdown.js');
const ErrorIndex = require('./errors/errorIndex.js'); const ErrorIndex = require('./errors/errorIndex.js');
const ErrorPage = ({ brew })=>{ const ErrorPage = ({ brew })=>{

View File

@@ -2,11 +2,6 @@ const dedent = require('dedent-tabs').default;
const loginUrl = 'https://www.naturalcrit.com/login'; const loginUrl = 'https://www.naturalcrit.com/login';
// Prevent parsing text (e.g. document titles) as markdown
const escape = (text) => {
return text.split('').map(char => `&#${char.charCodeAt(0)};`).join('');
};
//001-050 : Brew errors //001-050 : Brew errors
//050-100 : Other pages errors //050-100 : Other pages errors
@@ -23,18 +18,7 @@ const errorIndex = (props)=>{
'01' : dedent` '01' : dedent`
## An error occurred while retrieving this brew from Google Drive! ## An error occurred while retrieving this brew from Google Drive!
Google is able to see the brew at this link, but reported an error while attempting to retrieve it. Google reported an error while attempting to retrieve a brew from this link.`,
### Refreshing your Google Credentials
This issue is likely caused by an issue with your Google credentials; if you are the owner of this file, the following steps may resolve the issue:
- Go to https://www.naturalcrit.com/login and click logout if present (in small text at the bottom of the page).
- Click "Sign In with Google", which will refresh your Google credentials.
- After completing the sign in process, return to Homebrewery and refresh/reload the page so that it can pick up the updated credentials.
- If this was the source of the issue, it should now be resolved.
If following these steps does not resolve the issue, please let us know!`,
// Google Drive - 404 : brew deleted or access denied // Google Drive - 404 : brew deleted or access denied
'02' : dedent` '02' : dedent`
@@ -66,7 +50,7 @@ const errorIndex = (props)=>{
- **The Google Account may be closed.** Google may have removed the account - **The Google Account may be closed.** Google may have removed the account
due to inactivity or violating a Google policy. Make sure the owner can due to inactivity or violating a Google policy. Make sure the owner can
still access Google Drive normally and upload/download files to it. still access Google Drive normally and upload/download files to it.
:
If the file isn't found, Google Drive usually puts your file in your Trash folder for If the file isn't found, Google Drive usually puts your file in your Trash folder for
30 days. Assuming the trash hasn't been emptied yet, it might be worth checking. 30 days. Assuming the trash hasn't been emptied yet, it might be worth checking.
You can also find the Activity tab on the right side of the Google Drive page, which You can also find the Activity tab on the right side of the Google Drive page, which
@@ -94,7 +78,7 @@ const errorIndex = (props)=>{
: :
**Brew Title:** ${escape(props.brew.brewTitle) || 'Unable to show title'} **Brew Title:** ${props.brew.brewTitle || 'Unable to show title'}
**Current Authors:** ${props.brew.authors?.map((author)=>{return `[${author}](/user/${author})`;}).join(', ') || 'Unable to list authors'} **Current Authors:** ${props.brew.authors?.map((author)=>{return `[${author}](/user/${author})`;}).join(', ') || 'Unable to list authors'}
@@ -109,7 +93,7 @@ const errorIndex = (props)=>{
: :
**Brew Title:** ${escape(props.brew.brewTitle) || 'Unable to show title'} **Brew Title:** ${props.brew.brewTitle || 'Unable to show title'}
**Current Authors:** ${props.brew.authors?.map((author)=>{return `[${author}](/user/${author})`;}).join(', ') || 'Unable to list authors'} **Current Authors:** ${props.brew.authors?.map((author)=>{return `[${author}](/user/${author})`;}).join(', ') || 'Unable to list authors'}
@@ -186,7 +170,7 @@ const errorIndex = (props)=>{
**Brew ID:** ${props.brew.brewId} **Brew ID:** ${props.brew.brewId}
**Brew Title:** ${escape(props.brew.brewTitle)}`, **Brew Title:** ${props.brew.brewTitle}`,
// ####### Admin page error ####### // ####### Admin page error #######
'52': dedent` '52': dedent`

View File

@@ -2,7 +2,7 @@ require('./homePage.less');
const React = require('react'); const React = require('react');
const createClass = require('create-react-class'); const createClass = require('create-react-class');
const cx = require('classnames'); const cx = require('classnames');
import request from '../../utils/request-middleware.js'; const request = require('../../utils/request-middleware.js');
const { Meta } = require('vitreum/headtags'); const { Meta } = require('vitreum/headtags');
const Nav = require('naturalcrit/nav/nav.jsx'); const Nav = require('naturalcrit/nav/nav.jsx');
@@ -100,7 +100,8 @@ const HomePage = createClass({
return <div className='homePage sitePage'> return <div className='homePage sitePage'>
<Meta name='google-site-verification' content='NwnAQSSJZzAT7N-p5MY6ydQ7Njm67dtbu73ZSyE5Fy4' /> <Meta name='google-site-verification' content='NwnAQSSJZzAT7N-p5MY6ydQ7Njm67dtbu73ZSyE5Fy4' />
{this.renderNavbar()} {this.renderNavbar()}
<div className="content">
<div className='content'>
<SplitPane onDragFinish={this.handleSplitMove}> <SplitPane onDragFinish={this.handleSplitMove}>
<Editor <Editor
ref={this.editor} ref={this.editor}
@@ -127,6 +128,7 @@ const HomePage = createClass({
/> />
</SplitPane> </SplitPane>
</div> </div>
<div className={cx('floatingSaveButton', { show: this.state.welcomeText != this.state.brew.text })} onClick={this.handleSave}> <div className={cx('floatingSaveButton', { show: this.state.welcomeText != this.state.brew.text })} onClick={this.handleSave}>
Save current <i className='fas fa-save' /> Save current <i className='fas fa-save' />
</div> </div>

View File

@@ -91,6 +91,13 @@ If you are looking for more 5e Homebrew resources check out [r/UnearthedArcana](
\page \page
## Markdown+ ## Markdown+
The Homebrewery aims to make homebrewing as simple as possible, providing a live editor with Markdown syntax that is more human-readable and faster to write with than raw HTML. The Homebrewery aims to make homebrewing as simple as possible, providing a live editor with Markdown syntax that is more human-readable and faster to write with than raw HTML.

View File

@@ -2,9 +2,9 @@
require('./newPage.less'); require('./newPage.less');
const React = require('react'); const React = require('react');
const createClass = require('create-react-class'); const createClass = require('create-react-class');
import request from '../../utils/request-middleware.js'; const request = require('../../utils/request-middleware.js');
import Markdown from 'naturalcrit/markdown.js'; const Markdown = require('naturalcrit/markdown.js');
const Nav = require('naturalcrit/nav/nav.jsx'); const Nav = require('naturalcrit/nav/nav.jsx');
const PrintNavItem = require('../../navbar/print.navitem.jsx'); const PrintNavItem = require('../../navbar/print.navitem.jsx');
@@ -223,7 +223,7 @@ const NewPage = createClass({
render : function(){ render : function(){
return <div className='newPage sitePage'> return <div className='newPage sitePage'>
{this.renderNavbar()} {this.renderNavbar()}
<div className="content"> <div className='content'>
<SplitPane onDragFinish={this.handleSplitMove}> <SplitPane onDragFinish={this.handleSplitMove}>
<Editor <Editor
ref={this.editor} ref={this.editor}

View File

@@ -1,6 +1,6 @@
require('./sharePage.less'); require('./sharePage.less');
const React = require('react'); const React = require('react');
const { useState, useEffect, useCallback } = React; const createClass = require('create-react-class');
const { Meta } = require('vitreum/headtags'); const { Meta } = require('vitreum/headtags');
const Nav = require('naturalcrit/nav/nav.jsx'); const Nav = require('naturalcrit/nav/nav.jsx');
@@ -14,114 +14,122 @@ const BrewRenderer = require('../../brewRenderer/brewRenderer.jsx');
const { DEFAULT_BREW_LOAD } = require('../../../../server/brewDefaults.js'); const { DEFAULT_BREW_LOAD } = require('../../../../server/brewDefaults.js');
const { printCurrentBrew, fetchThemeBundle } = require('../../../../shared/helpers.js'); const { printCurrentBrew, fetchThemeBundle } = require('../../../../shared/helpers.js');
const SharePage = (props)=>{ const SharePage = createClass({
const { brew = DEFAULT_BREW_LOAD, disableMeta = false } = props; displayName : 'SharePage',
getDefaultProps : function() {
return {
brew : DEFAULT_BREW_LOAD,
disableMeta : false
};
},
const [state, setState] = useState({ getInitialState : function() {
return {
themeBundle : {}, themeBundle : {},
currentBrewRendererPageNum : 1, currentBrewRendererPageNum : 1
}); };
},
const handleBrewRendererPageChange = useCallback((pageNumber)=>{ componentDidMount : function() {
setState((prevState)=>({ document.addEventListener('keydown', this.handleControlKeys);
currentBrewRendererPageNum : pageNumber,
...prevState }));
}, []);
const handleControlKeys = (e)=>{ fetchThemeBundle(this, this.props.brew.renderer, this.props.brew.theme);
},
componentWillUnmount : function() {
document.removeEventListener('keydown', this.handleControlKeys);
},
handleBrewRendererPageChange : function(pageNumber){
this.setState({ currentBrewRendererPageNum: pageNumber });
},
handleControlKeys : function(e){
if(!(e.ctrlKey || e.metaKey)) return; if(!(e.ctrlKey || e.metaKey)) return;
const P_KEY = 80; const P_KEY = 80;
if(e.keyCode === P_KEY) { if(e.keyCode == P_KEY){
printCurrentBrew(); if(e.keyCode == P_KEY) printCurrentBrew();
e.stopPropagation(); e.stopPropagation();
e.preventDefault(); e.preventDefault();
} }
}; },
useEffect(()=>{ processShareId : function() {
document.addEventListener('keydown', handleControlKeys); return this.props.brew.googleId && !this.props.brew.stubbed ?
fetchThemeBundle( this.props.brew.googleId + this.props.brew.shareId :
{ setState }, this.props.brew.shareId;
brew.renderer, },
brew.theme
);
return ()=>{ renderEditLink : function(){
document.removeEventListener('keydown', handleControlKeys); if(!this.props.brew.editId) return;
};
}, []);
const processShareId = ()=>{ let editLink = this.props.brew.editId;
return brew.googleId && !brew.stubbed ? brew.googleId + brew.shareId : brew.shareId; if(this.props.brew.googleId && !this.props.brew.stubbed) {
}; editLink = this.props.brew.googleId + editLink;
}
const renderEditLink = ()=>{ return <Nav.item color='orange' icon='fas fa-pencil-alt' href={`/edit/${editLink}`}>
if(!brew.editId) return null;
const editLink = brew.googleId && ! brew.stubbed ? brew.googleId + brew.editId : brew.editId;
return (
<Nav.item color='orange' icon='fas fa-pencil-alt' href={`/edit/${editLink}`}>
edit edit
</Nav.item> </Nav.item>;
); },
};
const titleEl = ( render : function(){
<Nav.item className='brewTitle' style={disableMeta ? { cursor: 'default' } : {}}> const titleStyle = this.props.disableMeta ? { cursor: 'default' } : {};
{brew.title} const titleEl = <Nav.item className='brewTitle' style={titleStyle}>{this.props.brew.title}</Nav.item>;
</Nav.item>
);
return ( return <div className='sharePage sitePage'>
<div className='sharePage sitePage'>
<Meta name='robots' content='noindex, nofollow' /> <Meta name='robots' content='noindex, nofollow' />
<Navbar> <Navbar>
<Nav.section className='titleSection'> <Nav.section className='titleSection'>
{disableMeta ? titleEl : <MetadataNav brew={brew}>{titleEl}</MetadataNav>} {
this.props.disableMeta ?
titleEl
:
<MetadataNav brew={this.props.brew}>
{titleEl}
</MetadataNav>
}
</Nav.section> </Nav.section>
<Nav.section> <Nav.section>
{brew.shareId && ( {this.props.brew.shareId && <>
<>
<PrintNavItem/> <PrintNavItem/>
<Nav.dropdown> <Nav.dropdown>
<Nav.item color='red' icon='fas fa-code'> <Nav.item color='red' icon='fas fa-code'>
source source
</Nav.item> </Nav.item>
<Nav.item color='blue' icon='fas fa-eye' href={`/source/${processShareId()}`}> <Nav.item color='blue' icon='fas fa-eye' href={`/source/${this.processShareId()}`}>
view view
</Nav.item> </Nav.item>
{renderEditLink()} {this.renderEditLink()}
<Nav.item color='blue' icon='fas fa-download' href={`/download/${processShareId()}`}> <Nav.item color='blue' icon='fas fa-download' href={`/download/${this.processShareId()}`}>
download download
</Nav.item> </Nav.item>
<Nav.item color='blue' icon='fas fa-clone' href={`/new/${processShareId()}`}> <Nav.item color='blue' icon='fas fa-clone' href={`/new/${this.processShareId()}`}>
clone to new clone to new
</Nav.item> </Nav.item>
</Nav.dropdown> </Nav.dropdown>
</> </>}
)} <RecentNavItem brew={this.props.brew} storageKey='view' />
<RecentNavItem brew={brew} storageKey='view' />
<Account /> <Account />
</Nav.section> </Nav.section>
</Navbar> </Navbar>
<div className='content'> <div className='content'>
<BrewRenderer <BrewRenderer
text={brew.text} text={this.props.brew.text}
style={brew.style} style={this.props.brew.style}
lang={brew.lang} lang={this.props.brew.lang}
renderer={brew.renderer} renderer={this.props.brew.renderer}
theme={brew.theme} theme={this.props.brew.theme}
themeBundle={state.themeBundle} themeBundle={this.state.themeBundle}
onPageChange={handleBrewRendererPageChange} onPageChange={this.handleBrewRendererPageChange}
currentBrewRendererPageNum={state.currentBrewRendererPageNum} currentBrewRendererPageNum={this.state.currentBrewRendererPageNum}
allowPrint={true} allowPrint={true}
/> />
</div> </div>
</div> </div>;
); }
}; });
module.exports = SharePage; module.exports = SharePage;

View File

@@ -1,5 +1,5 @@
.sharePage{ .sharePage{
nav .navSection.titleSection { .navContent .navSection.titleSection {
flex-grow: 1; flex-grow: 1;
justify-content: center; justify-content: center;
} }

View File

@@ -1,11 +1,12 @@
const React = require('react'); const React = require('react');
const { useState } = React; const createClass = require('create-react-class');
const _ = require('lodash'); const _ = require('lodash');
const ListPage = require('../basePages/listPage/listPage.jsx'); const ListPage = require('../basePages/listPage/listPage.jsx');
const Nav = require('naturalcrit/nav/nav.jsx'); const Nav = require('naturalcrit/nav/nav.jsx');
const Navbar = require('../../navbar/navbar.jsx'); const Navbar = require('../../navbar/navbar.jsx');
const RecentNavItem = require('../../navbar/recent.navitem.jsx').both; const RecentNavItem = require('../../navbar/recent.navitem.jsx').both;
const Account = require('../../navbar/account.navitem.jsx'); const Account = require('../../navbar/account.navitem.jsx');
const NewBrew = require('../../navbar/newbrew.navitem.jsx'); const NewBrew = require('../../navbar/newbrew.navitem.jsx');
@@ -13,48 +14,69 @@ const HelpNavItem = require('../../navbar/help.navitem.jsx');
const ErrorNavItem = require('../../navbar/error-navitem.jsx'); const ErrorNavItem = require('../../navbar/error-navitem.jsx');
const VaultNavitem = require('../../navbar/vault.navitem.jsx'); const VaultNavitem = require('../../navbar/vault.navitem.jsx');
const UserPage = (props)=>{ const UserPage = createClass({
props = { displayName : 'UserPage',
getDefaultProps : function() {
return {
username : '', username : '',
brews : [], brews : [],
query : '', query : '',
...props error : null
}; };
},
getInitialState : function() {
const usernameWithS = this.props.username + (this.props.username.endsWith('s') ? `` : `s`);
const [error, setError] = useState(null); const brews = _.groupBy(this.props.brews, (brew)=>{
return (brew.published ? 'published' : 'private');
const usernameWithS = props.username + (props.username.endsWith('s') ? `` : `s`); });
const groupedBrews = _.groupBy(props.brews, (brew)=>brew.published ? 'published' : 'private');
const brewCollection = [ const brewCollection = [
{ {
title : `${usernameWithS} published brews`, title : `${usernameWithS} published brews`,
class : 'published', class : 'published',
brews : groupedBrews.published || [] brews : brews.published
}, }
...(props.username === global.account?.username ? [{ ];
if(this.props.username == global.account?.username){
brewCollection.push(
{
title : `${usernameWithS} unpublished brews`, title : `${usernameWithS} unpublished brews`,
class : 'unpublished', class : 'unpublished',
brews : groupedBrews.private || [] brews : brews.private
}] : []) }
]; );
}
const navItems = ( return {
<Navbar> brewCollection : brewCollection
};
},
errorReported : function(error) {
this.setState({
error
});
},
navItems : function() {
return <Navbar>
<Nav.section> <Nav.section>
{error && (<ErrorNavItem error={error} parent={null}></ErrorNavItem>)} {this.state.error ?
<ErrorNavItem error={this.state.error} parent={this}></ErrorNavItem> :
null
}
<NewBrew /> <NewBrew />
<HelpNavItem /> <HelpNavItem />
<VaultNavitem/> <VaultNavitem/>
<RecentNavItem /> <RecentNavItem />
<Account /> <Account />
</Nav.section> </Nav.section>
</Navbar> </Navbar>;
); },
return ( render : function(){
<ListPage brewCollection={brewCollection} navItems={navItems} query={props.query} reportError={(err)=>setError(err)} /> return <ListPage brewCollection={this.state.brewCollection} navItems={this.navItems()} query={this.props.query} reportError={this.errorReported}></ListPage>;
); }
}; });
module.exports = UserPage; module.exports = UserPage;

View File

@@ -15,7 +15,7 @@ const BrewItem = require('../basePages/listPage/brewItem/brewItem.jsx');
const SplitPane = require('../../../../shared/naturalcrit/splitPane/splitPane.jsx'); const SplitPane = require('../../../../shared/naturalcrit/splitPane/splitPane.jsx');
const ErrorIndex = require('../errorPage/errors/errorIndex.js'); const ErrorIndex = require('../errorPage/errors/errorIndex.js');
import request from '../../utils/request-middleware.js'; const request = require('../../utils/request-middleware.js');
const VaultPage = (props)=>{ const VaultPage = (props)=>{
const [pageState, setPageState] = useState(parseInt(props.query.page) || 1); const [pageState, setPageState] = useState(parseInt(props.query.page) || 1);
@@ -411,13 +411,14 @@ const VaultPage = (props)=>{
}; };
return ( return (
<div className='sitePage vaultPage'> <div className='vaultPage'>
<link href='/themes/V3/Blank/style.css' rel='stylesheet' /> <link href='/themes/V3/Blank/style.css' rel='stylesheet' />
<link href='/themes/V3/5ePHB/style.css' rel='stylesheet' /> <link href='/themes/V3/5ePHB/style.css' rel='stylesheet' />
{renderNavItems()} {renderNavItems()}
<div className="content"> <div className='content'>
<SplitPane showDividerButtons={false}> <SplitPane showDividerButtons={false}>
<div className='form dataGroup'>{renderForm()}</div> <div className='form dataGroup'>{renderForm()}</div>
<div className='resultsContainer dataGroup'> <div className='resultsContainer dataGroup'>
{renderSortBar()} {renderSortBar()}
{renderFoundBrews()} {renderFoundBrews()}

View File

@@ -5,7 +5,11 @@
*:not(input) { user-select : none; } *:not(input) { user-select : none; }
.content .dataGroup { .content {
height : 100%;
background : #2C3E50;
.dataGroup {
width : 100%; width : 100%;
height : 100%; height : 100%;
background : white; background : white;
@@ -92,11 +96,49 @@
&:invalid { background : rgb(255, 188, 181); } &:invalid { background : rgb(255, 188, 181); }
&[type='checkbox'] {
position : relative;
display : inline-block;
width : 50px;
height : 30px;
font-family : 'WalterTurncoat';
font-size : 20px;
font-weight : 800;
color : white;
letter-spacing : 2px;
appearance : none;
background : red;
isolation : isolate;
border-radius : 5px;
&::before,&::after {
position : absolute;
inset : 0;
z-index : 5;
padding-top : 2px;
text-align : center;
}
&::before {
display : block;
content : 'No';
}
&::after {
display : none;
content : 'Yes';
}
&:checked {
background : green;
&::before { display : none; }
&::after { display : block; }
}
}
} }
#searchButton { #searchButton {
.colorButton(@green);
position : absolute; position : absolute;
right : 20px; right : 20px;
bottom : 0; bottom : 0;
@@ -114,6 +156,7 @@
flex-direction : column; flex-direction : column;
height : 100%; height : 100%;
overflow-y : auto; overflow-y : auto;
font-family : 'BookInsanityRemake';
font-size : 0.34cm; font-size : 0.34cm;
h3 { h3 {
@@ -317,7 +360,6 @@
} }
button { button {
.colorButton(@green);
width : max-content; width : max-content;
&.previousPage { grid-area : previousPage; } &.previousPage { grid-area : previousPage; }
@@ -329,7 +371,7 @@
} }
} }
} }
}
} }
@keyframes trailingDots { @keyframes trailingDots {
@@ -346,7 +388,7 @@
// media query for when the page is smaller than 1079 px in width // media query for when the page is smaller than 1079 px in width
@media screen and (max-width : 1079px) { @media screen and (max-width : 1079px) {
.vaultPage { .vaultPage .content {
.dataGroup.form .brewLookup { padding : 1px 20px 20px 10px; } .dataGroup.form .brewLookup { padding : 1px 20px 20px 10px; }

View File

@@ -1,19 +0,0 @@
import * as IDB from 'idb-keyval/dist/index.js';
export function initCustomStore(db, store){
const createCustomStore = async ()=>IDB.createStore(db, store);
return {
entries : async ()=>IDB.entries(await createCustomStore()),
keys : async ()=>IDB.keys(await createCustomStore()),
values : async ()=>IDB.values(await createCustomStore()),
clear : async ()=>IDB.clear(await createCustomStore),
get : async (key)=>IDB.get(key, await createCustomStore()),
getMany : async (keys)=>IDB.getMany(keys, await createCustomStore()),
set : async (key, value)=>IDB.set(key, value, await createCustomStore()),
setMany : async (entries)=>IDB.setMany(entries, await createCustomStore()),
update : async (key, updateFn)=>IDB.update(key, updateFn, await createCustomStore()),
del : async (key)=>IDB.del(key, await createCustomStore()),
delMany : async (keys)=>IDB.delMany(keys, await createCustomStore())
};
};

View File

@@ -1,4 +1,4 @@
import request from 'superagent'; const request = require('superagent');
const addHeader = (request)=>request.set('Homebrewery-Version', global.version); const addHeader = (request)=>request.set('Homebrewery-Version', global.version);
@@ -9,4 +9,4 @@ const requestMiddleware = {
delete : (path)=>addHeader(request.delete(path)), delete : (path)=>addHeader(request.delete(path)),
}; };
export default requestMiddleware; module.exports = requestMiddleware;

View File

@@ -1,4 +1,4 @@
import { initCustomStore } from './customIDBStore.js'; import * as IDB from 'idb-keyval/dist/index.js';
export const HISTORY_PREFIX = 'HOMEBREWERY-HISTORY'; export const HISTORY_PREFIX = 'HOMEBREWERY-HISTORY';
export const HISTORY_SLOTS = 5; export const HISTORY_SLOTS = 5;
@@ -21,14 +21,12 @@ const HISTORY_SAVE_DELAYS = {
// '5' : 5 // '5' : 5
// }; // };
const GARBAGE_COLLECT_DELAY = 28 * 24 * 60;
// const GARBAGE_COLLECT_DELAY = 10;
const HB_DB = 'HOMEBREWERY-DB'; const HB_DB = 'HOMEBREWERY-DB';
const HB_STORE = 'HISTORY'; const HB_STORE = 'HISTORY';
const IDB = initCustomStore(HB_DB, HB_STORE); const GARBAGE_COLLECT_DELAY = 28 * 24 * 60;
// const GARBAGE_COLLECT_DELAY = 10;
function getKeyBySlot(brew, slot){ function getKeyBySlot(brew, slot){
// Return a string representing the key for this brew and history slot // Return a string representing the key for this brew and history slot
@@ -55,6 +53,11 @@ function parseBrewForStorage(brew, slot = 0) {
return [key, archiveBrew]; return [key, archiveBrew];
} }
// Create a custom IDB store
async function createHBStore(){
return await IDB.createStore(HB_DB, HB_STORE);
}
export async function loadHistory(brew){ export async function loadHistory(brew){
const DEFAULT_HISTORY_ITEM = { expireAt: '2000-01-01T00:00:00.000Z', shareId: brew.shareId, noData: true }; const DEFAULT_HISTORY_ITEM = { expireAt: '2000-01-01T00:00:00.000Z', shareId: brew.shareId, noData: true };
@@ -66,7 +69,7 @@ export async function loadHistory(brew){
}; };
// Load all keys from IDB at once // Load all keys from IDB at once
const dataArray = await IDB.getMany(historyKeys); const dataArray = await IDB.getMany(historyKeys, await createHBStore());
return dataArray.map((data)=>{ return data ?? DEFAULT_HISTORY_ITEM; }); return dataArray.map((data)=>{ return data ?? DEFAULT_HISTORY_ITEM; });
} }
@@ -94,7 +97,7 @@ export async function updateHistory(brew) {
// Update the most recent brew // Update the most recent brew
historyUpdate.push(parseBrewForStorage(brew, 1)); historyUpdate.push(parseBrewForStorage(brew, 1));
await IDB.setMany(historyUpdate); await IDB.setMany(historyUpdate, await createHBStore());
// Break out of data checks because we found an expired value // Break out of data checks because we found an expired value
break; break;
@@ -103,17 +106,14 @@ export async function updateHistory(brew) {
}; };
export async function versionHistoryGarbageCollection(){ export async function versionHistoryGarbageCollection(){
const entries = await IDB.entries();
const expiredKeys = []; const entries = await IDB.entries(await createHBStore());
for (const [key, value] of entries){ for (const [key, value] of entries){
const expireAt = new Date(value.savedAt); const expireAt = new Date(value.savedAt);
expireAt.setMinutes(expireAt.getMinutes() + GARBAGE_COLLECT_DELAY); expireAt.setMinutes(expireAt.getMinutes() + GARBAGE_COLLECT_DELAY);
if(new Date() > expireAt){ if(new Date() > expireAt){
expiredKeys.push(key); await IDB.del(key, await createHBStore());
}; };
}; };
if(expiredKeys.length > 0){
await IDB.delMany(expiredKeys);
}
}; };

View File

@@ -73,12 +73,3 @@
.fit-width { .fit-width {
mask-image: url('../icons/fit-width.svg'); mask-image: url('../icons/fit-width.svg');
} }
.single-spread {
mask-image: url('../icons/single-spread.svg');
}
.facing-spread {
mask-image: url('../icons/facing-spread.svg');
}
.flow-spread {
mask-image: url('../icons/flow-spread.svg');
}

View File

@@ -1,10 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(0.979101,0,0,0.919064,-29.0748,1.98095)">
<path d="M78.584,16.13C78.584,15.335 78.164,14.69 77.647,14.69L30.632,14.69C30.115,14.69 29.695,15.335 29.695,16.13L29.695,88.365C29.695,89.16 30.115,89.805 30.632,89.805L77.647,89.805C78.164,89.805 78.584,89.16 78.584,88.365L78.584,16.13Z"/>
</g>
<g transform="matrix(0.979101,0,0,0.919064,23.058,1.98095)">
<path d="M78.584,16.13C78.584,15.335 78.164,14.69 77.647,14.69L30.632,14.69C30.115,14.69 29.695,15.335 29.695,16.13L29.695,88.365C29.695,89.16 30.115,89.805 30.632,89.805L77.647,89.805C78.164,89.805 78.584,89.16 78.584,88.365L78.584,16.13Z"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 1.1 KiB

View File

@@ -1,24 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(1.0781,0,0,1.0781,-3.90545,-3.90502)">
<g transform="matrix(0.590052,0,0,0.553871,-13.8993,-2.19227)">
<path d="M78.584,16.13C78.584,15.335 78.164,14.69 77.647,14.69L30.632,14.69C30.115,14.69 29.695,15.335 29.695,16.13L29.695,88.365C29.695,89.16 30.115,89.805 30.632,89.805L77.647,89.805C78.164,89.805 78.584,89.16 78.584,88.365L78.584,16.13Z"/>
</g>
<g transform="matrix(0.590052,0,0,0.553871,-13.8993,44.3152)">
<path d="M78.584,16.13C78.584,15.335 78.164,14.69 77.647,14.69L30.632,14.69C30.115,14.69 29.695,15.335 29.695,16.13L29.695,88.365C29.695,89.16 30.115,89.805 30.632,89.805L77.647,89.805C78.164,89.805 78.584,89.16 78.584,88.365L78.584,16.13Z"/>
</g>
<g transform="matrix(0.590052,0,0,0.553871,17.5184,-2.19227)">
<path d="M78.584,16.13C78.584,15.335 78.164,14.69 77.647,14.69L30.632,14.69C30.115,14.69 29.695,15.335 29.695,16.13L29.695,88.365C29.695,89.16 30.115,89.805 30.632,89.805L77.647,89.805C78.164,89.805 78.584,89.16 78.584,88.365L78.584,16.13Z"/>
</g>
<g transform="matrix(0.590052,0,0,0.553871,50.0095,-2.19227)">
<path d="M78.584,16.13C78.584,15.335 78.164,14.69 77.647,14.69L30.632,14.69C30.115,14.69 29.695,15.335 29.695,16.13L29.695,88.365C29.695,89.16 30.115,89.805 30.632,89.805L77.647,89.805C78.164,89.805 78.584,89.16 78.584,88.365L78.584,16.13Z"/>
</g>
<g transform="matrix(0.590052,0,0,0.553871,17.5184,44.3152)">
<path d="M78.584,16.13C78.584,15.335 78.164,14.69 77.647,14.69L30.632,14.69C30.115,14.69 29.695,15.335 29.695,16.13L29.695,88.365C29.695,89.16 30.115,89.805 30.632,89.805L77.647,89.805C78.164,89.805 78.584,89.16 78.584,88.365L78.584,16.13Z"/>
</g>
<g transform="matrix(0.590052,0,0,0.553871,50.0095,44.3152)">
<path d="M78.584,16.13C78.584,15.335 78.164,14.69 77.647,14.69L30.632,14.69C30.115,14.69 29.695,15.335 29.695,16.13L29.695,88.365C29.695,89.16 30.115,89.805 30.632,89.805L77.647,89.805C78.164,89.805 78.584,89.16 78.584,88.365L78.584,16.13Z"/>
</g>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 2.5 KiB

View File

@@ -1,7 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve" xmlns:serif="http://www.serif.com/" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2;">
<g transform="matrix(1.41826,0,0,1.3313,-26.7845,-19.5573)">
<path d="M78.584,16.13C78.584,15.335 78.164,14.69 77.647,14.69L30.632,14.69C30.115,14.69 29.695,15.335 29.695,16.13L29.695,88.365C29.695,89.16 30.115,89.805 30.632,89.805L77.647,89.805C78.164,89.805 78.584,89.16 78.584,88.365L78.584,16.13Z"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 777 B

View File

@@ -8,8 +8,6 @@ const template = async function(name, title='', props = {}){
}); });
const ogMetaTags = ogTags.join('\n'); const ogMetaTags = ogTags.join('\n');
const ssrModule = await import(`../build/${name}/ssr.cjs`);
return `<!DOCTYPE html> return `<!DOCTYPE html>
<html> <html>
<head> <head>
@@ -23,7 +21,7 @@ const template = async function(name, title='', props = {}){
<title>${title.length ? `${title} - The Homebrewery`: 'The Homebrewery - NaturalCrit'}</title> <title>${title.length ? `${title} - The Homebrewery`: 'The Homebrewery - NaturalCrit'}</title>
</head> </head>
<body> <body>
<main id="reactRoot">${ssrModule.default(props)}</main> <main id="reactRoot">${require(`../build/${name}/ssr.js`)(props)}</main>
<script src=${`/${name}/bundle.js`}></script> <script src=${`/${name}/bundle.js`}></script>
<script>start_app(${JSON.stringify(props)})</script> <script>start_app(${JSON.stringify(props)})</script>
</body> </body>
@@ -31,4 +29,4 @@ const template = async function(name, title='', props = {}){
`; `;
}; };
export default template; module.exports = template;

View File

@@ -1,3 +1,4 @@
version: '2'
services: services:
mongodb: mongodb:
image: mongo:latest image: mongo:latest

17
faq.md
View File

@@ -69,6 +69,7 @@ pre {
You can check the site status here: [Everyone or Just Me](https://downforeveryoneorjustme.com/homebrewery.naturalcrit.com) You can check the site status here: [Everyone or Just Me](https://downforeveryoneorjustme.com/homebrewery.naturalcrit.com)
### Why am I getting an error when trying to save, and my account is linked to Google? ### Why am I getting an error when trying to save, and my account is linked to Google?
A sign-in with Google only lasts a year until the authentication expires. You must go [here](https://www.naturalcrit.com/login), click the *Log-out* button, and then sign back in using your Google account. A sign-in with Google only lasts a year until the authentication expires. You must go [here](https://www.naturalcrit.com/login), click the *Log-out* button, and then sign back in using your Google account.
@@ -81,17 +82,12 @@ If you have linked your account with a Google account, you would change your pas
### Is there a way to restore a previous version of my brew? ### Is there a way to restore a previous version of my brew?
In your brew, there is an icon, :fas_clock_rotate_left:, that button opens up a menu with versions of your brew, stored in order from newer to older, up to a week old. Because of the amount of duplicates this function creates, this information is stored in **your browser**, so if you were to uninstall it or clear your cookies and site data, or change computers, the info will not be there. Currently, there is no way to do this through the site yourself. This would take too much of a toll on the amount of storage the homebrewery requires. However, we do have daily backups of our database that we keep for 8 days, and you can contact the moderators on [the subreddit](https://www.reddit.com/r/homebrewery) with your Homebrewery username, the name of the lost brew, and the last known time it was working properly. We can manually look through our backups and restore it if it exists.
Also, we do have daily backups of our database that we keep for 8 days, and you can contact the moderators on [the subreddit](https://www.reddit.com/r/homebrewery) with your Homebrewery username, the name of the lost brew, and the last known time it was working properly. We can manually look through our backups and restore it if it exists.
### I worked on a brew for X hours, and suddenly all the text disappeared! ### I worked on a brew for X hours, and suddenly all the text disappeared!
This usually happens if you accidentally drag-select all of your text and then start typing which overwrites the selection. Do not panic, and do not refresh the page or reload your brew quite yet as it is probably auto-saved in this state already. Simply press CTRL+Z as many times as needed to undo your last few changes and you will be back to where you were, then make sure to save your brew in the "good" state. This usually happens if you accidentally drag-select all of your text and then start typing which overwrites the selection. Do not panic, and do not refresh the page or reload your brew quite yet as it is probably auto-saved in this state already. Simply press CTRL+Z as many times as needed to undo your last few changes and you will be back to where you were, then make sure to save your brew in the "good" state.
You can also load a history version old enough to have all the text, using the :fas_clock_rotate_left: history versions button.
\column \column
### Why is only Chrome supported? ### Why is only Chrome supported?
@@ -118,6 +114,9 @@ Once you have an image you would like to use, it is recommended to host it somew
### A particular font does not work for my language, what do I do? ### A particular font does not work for my language, what do I do?
The fonts used were originally created for use with the English language, though revisions since then have added more support for other languages. They are still not complete sets and may be missing a glyph/character you need. Unfortunately, the volunteer group as it stands at the time of this writing does not have a font guru, so it would be difficult to add more glyphs (especially complicated glyphs). Let us know which glyph is missing on the subreddit, but you may need to search [Google Fonts](https://fonts.google.com) for an alternative font if you need something fast. The fonts used were originally created for use with the English language, though revisions since then have added more support for other languages. They are still not complete sets and may be missing a glyph/character you need. Unfortunately, the volunteer group as it stands at the time of this writing does not have a font guru, so it would be difficult to add more glyphs (especially complicated glyphs). Let us know which glyph is missing on the subreddit, but you may need to search [Google Fonts](https://fonts.google.com) for an alternative font if you need something fast.
### Whenever I click on the "Get PDF" button, instead of getting a download, it opens Print Preview in another tab.
Yes, this is by design. In the print preview, select "Save as PDF" as the Destination, and then click "Save". There will be a normal download dialog where you can save your brew as a PDF.
### I have white borders on the bottom/sides of the print preview. ### I have white borders on the bottom/sides of the print preview.
The Homebrewery paper size and your print paper size do not match. The Homebrewery paper size and your print paper size do not match.
@@ -127,8 +126,4 @@ The Homebrewery defaults to creating US Letter page sizes. If you are printing
### Typing `#### Adhesion` in the text editor doesn't show the header at all in the completed page? ### Typing `#### Adhesion` in the text editor doesn't show the header at all in the completed page?
Your ad-blocking software is mistakenly assuming your text to be an ad. We recommend whitelisting homebrewery.naturalcrit.com in your ad-blocking software, as we have no ads. Your ad-blocking software is mistakenly assuming your text to be an ad. Whitelist homebrewery.naturalcrit.com in your ad-blocking software.
### My username appears as _hidden_ when checking my brews in the Vault, why is that?
Your username is most likely your e-mail adress, and our code is picking that up and protecting your identity. This will remain as is, but you can ask for a name change by contacting the moderators on [the subreddit](https://www.reddit.com/r/homebrewery) with your Homebrewery username, and your desired new name. You will also be asked to provide details about some of your unpublished brews, to verify your identity. No information will be leaked or shared.

View File

@@ -24,16 +24,12 @@ These instructions assume that you are installing to a completely new, fresh Ubu
These installation instructions have been tested on the following Ubuntu releases: These installation instructions have been tested on the following Ubuntu releases:
- *ubuntu-24.04.1-desktop-amd64* - *ubuntu-20.04.3-desktop-amd64*
- *ubuntu-22.04.5-desktop-amd64*
- *ubuntu-20.04.6-desktop-amd64*
## Final Notes ## 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. 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.
Earlier versions of Ubuntu may requier an alternate Mongo setup, see https://www.mongodb.com/docs/manual/tutorial/install-mongodb-on-ubuntu/ for assistance.
Regards, Regards,
G G
December 19, 2021 December 19, 2021

View File

@@ -3,8 +3,7 @@ Description=Homebrewery Web Server
[Service] [Service]
User=root User=root
BindsTo=mongod.service After=mongodb
After=mongod.service
Environment=NODE_ENV=local Environment=NODE_ENV=local
WorkingDirectory=/usr/local/homebrewery WorkingDirectory=/usr/local/homebrewery
ExecStart=node server.js ExecStart=node server.js

View File

@@ -1,60 +1,14 @@
#!/bin/sh #!/bin/sh
# Detect Ubuntu Version
export DISTRO=$(grep "^NAME=" /etc/os-release | awk -F '=' '{print $2}' | sed 's/"//g')
export DISTRO_VER=$(grep "VERSION_ID=" /etc/os-release | awk -F '=' '{print $2}' | sed 's/"//g')
export MATCHED="Yes"
if [ "${DISTRO}" != "Ubuntu" ];
then
echo :: Ubuntu not detected. Are you using an alternate spin or derivative?
echo :: Detected - ${DISTRO}
read -p [y/N] YESNO
if [ "${YESNO}" != "Y" ] && [ ]"${YESNO}" != "y" ]; then
exit
fi
MATCHED="No"
fi
# Install CURL and add required NodeJS source to package repo # Install CURL and add required NodeJS source to package repo
echo ::Install CURL echo ::Install CURL
apt install -y curl apt install -y curl
echo ::Add NodeJS source to package repo echo ::Add NodeJS source to package repo
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - curl -fsSL https://deb.nodesource.com/setup_16.x | sudo -E bash -
# Add Mongo CE Source
if [ ${DISTRO} = "Ubuntu" ];
then
echo ::Add Mongo CE source to package repo
curl -fsSL https://www.mongodb.org/static/pgp/server-8.0.asc | \
sudo gpg -o /usr/share/keyrings/mongodb-server-8.0.gpg \
--dearmor
if [ "${DISTRO_VER}" == "24.04" ]; then
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu noble/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
elif [ "${DISTRO_VER}" == "22.04" ]; then
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
elif [ "${DISTRO_VER}" == "20.04" ]; then
echo "deb [ arch=amd64,arm64 signed-by=/usr/share/keyrings/mongodb-server-8.0.gpg ] https://repo.mongodb.org/apt/ubuntu focal/mongodb-org/8.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-8.0.list
else
MATCHED="No"
fi
sudo apt-get update
fi
if [ ${MATCHED} == "No" ]; then
echo :: WARNING
echo :: Unable to determine Ubuntu version for Mongo installation purposes.
echo :: Please check your spin/distro documentation to install Mongo CE and enable it on startup.
fi
# Install required packages # Install required packages
echo ::Install Homebrewery requirements echo ::Install Homebrewery requirements
apt satisfy -y git nodejs npm mongodb-org apt satisfy -y git nodejs npm mongodb
# Enable and start Mongo
systemctl enable mongod
systemctl start mongod
# Clone Homebrewery repo # Clone Homebrewery repo
echo ::Get Homebrewery files echo ::Get Homebrewery files

4289
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,11 +1,10 @@
{ {
"name": "homebrewery", "name": "homebrewery",
"description": "Create authentic looking D&D homebrews using only markdown", "description": "Create authentic looking D&D homebrews using only markdown",
"version": "3.17.0", "version": "3.16.0",
"type": "module",
"engines": { "engines": {
"npm": "^10.2.x", "npm": "^10.2.x",
"node": "^20.18.x" "node": "^20.17.x"
}, },
"repository": { "repository": {
"type": "git", "type": "git",
@@ -27,7 +26,6 @@
"test:api-unit:themes": "jest \"server/.*.spec.js\" -t \"theme bundle\" --verbose", "test:api-unit:themes": "jest \"server/.*.spec.js\" -t \"theme bundle\" --verbose",
"test:api-unit:css": "jest \"server/.*.spec.js\" -t \"Get CSS\" --verbose", "test:api-unit:css": "jest \"server/.*.spec.js\" -t \"Get CSS\" --verbose",
"test:api-unit:notifications": "jest \"server/.*.spec.js\" -t \"Notifications\" --verbose", "test:api-unit:notifications": "jest \"server/.*.spec.js\" -t \"Notifications\" --verbose",
"test:content-negotiation": "jest \"server/middleware/.*.spec.js\" --verbose",
"test:coverage": "jest --coverage --silent --runInBand", "test:coverage": "jest --coverage --silent --runInBand",
"test:dev": "jest --verbose --watch", "test:dev": "jest --verbose --watch",
"test:basic": "jest tests/markdown/basic.test.js --verbose", "test:basic": "jest tests/markdown/basic.test.js --verbose",
@@ -38,11 +36,8 @@
"test:mustache-syntax:injection": "jest \".*(mustache-syntax).*\" -t '^Injection:.*' --verbose --noStackTrace", "test:mustache-syntax:injection": "jest \".*(mustache-syntax).*\" -t '^Injection:.*' --verbose --noStackTrace",
"test:definition-lists": "jest tests/markdown/definition-lists.test.js --verbose --noStackTrace", "test:definition-lists": "jest tests/markdown/definition-lists.test.js --verbose --noStackTrace",
"test:hard-breaks": "jest tests/markdown/hard-breaks.test.js --verbose --noStackTrace", "test:hard-breaks": "jest tests/markdown/hard-breaks.test.js --verbose --noStackTrace",
"test:non-breaking-spaces": "jest tests/markdown/non-breaking-spaces.test.js --verbose --noStackTrace",
"test:paragraph-justification": "jest tests/markdown/paragraph-justification.test.js --verbose --noStackTrace",
"test:emojis": "jest tests/markdown/emojis.test.js --verbose --noStackTrace", "test:emojis": "jest tests/markdown/emojis.test.js --verbose --noStackTrace",
"test:route": "jest tests/routes/static-pages.test.js --verbose", "test:route": "jest tests/routes/static-pages.test.js --verbose",
"test:safehtml": "jest tests/html/safeHTML.test.js --verbose",
"phb": "node --experimental-require-module scripts/phb.js", "phb": "node --experimental-require-module scripts/phb.js",
"prod": "set NODE_ENV=production && npm run build", "prod": "set NODE_ENV=production && npm run build",
"postinstall": "npm run build", "postinstall": "npm run build",
@@ -60,9 +55,6 @@
"shared", "shared",
"server" "server"
], ],
"transformIgnorePatterns": [
"node_modules/(?!nanoid/).*"
],
"coveragePathIgnorePatterns": [ "coveragePathIgnorePatterns": [
"build/*" "build/*"
], ],
@@ -84,63 +76,68 @@
"jest-expect-message" "jest-expect-message"
] ]
}, },
"babel": {
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-transform-runtime"
]
},
"dependencies": { "dependencies": {
"@babel/core": "^7.26.7", "@babel/core": "^7.25.8",
"@babel/plugin-transform-runtime": "^7.25.9", "@babel/plugin-transform-runtime": "^7.25.7",
"@babel/preset-env": "^7.26.7", "@babel/preset-env": "^7.25.8",
"@babel/preset-react": "^7.26.3", "@babel/preset-react": "^7.25.7",
"@googleapis/drive": "^8.14.0", "@googleapis/drive": "^8.14.0",
"body-parser": "^1.20.2", "body-parser": "^1.20.2",
"classnames": "^2.5.1", "classnames": "^2.5.1",
"codemirror": "^5.65.6", "codemirror": "^5.65.6",
"cookie-parser": "^1.4.7", "cookie-parser": "^1.4.7",
"core-js": "^3.40.0",
"cors": "^2.8.5",
"create-react-class": "^15.7.0", "create-react-class": "^15.7.0",
"dedent-tabs": "^0.10.3", "dedent-tabs": "^0.10.3",
"dompurify": "^3.2.4", "dompurify": "^3.1.7",
"expr-eval": "^2.0.2", "expr-eval": "^2.0.2",
"express": "^4.21.2", "express": "^4.21.1",
"express-async-handler": "^1.2.0", "express-async-handler": "^1.2.0",
"express-static-gzip": "2.2.0", "express-static-gzip": "2.1.8",
"fs-extra": "11.3.0", "fs-extra": "11.2.0",
"idb-keyval": "^6.2.1", "idb-keyval": "^6.2.1",
"js-yaml": "^4.1.0", "js-yaml": "^4.1.0",
"jwt-simple": "^0.5.6", "jwt-simple": "^0.5.6",
"less": "^3.13.1", "less": "^3.13.1",
"lodash": "^4.17.21", "lodash": "^4.17.21",
"marked": "13.0.3", "marked": "11.2.0",
"marked-emoji": "^1.4.3", "marked-emoji": "^1.4.2",
"marked-extended-tables": "^1.1.0", "marked-extended-tables": "^1.0.10",
"marked-gfm-heading-id": "^4.0.1", "marked-gfm-heading-id": "^3.2.0",
"marked-smartypants-lite": "^1.0.3", "marked-smartypants-lite": "^1.0.2",
"markedLegacy": "npm:marked@^0.3.19", "markedLegacy": "npm:marked@^0.3.19",
"moment": "^2.30.1", "moment": "^2.30.1",
"mongoose": "^8.9.5", "mongoose": "^8.7.1",
"nanoid": "5.0.9", "nanoid": "3.3.4",
"nconf": "^0.12.1", "nconf": "^0.12.1",
"react": "^18.3.1", "react": "^18.3.1",
"react-dom": "^18.3.1", "react-dom": "^18.3.1",
"react-frame-component": "^4.1.3", "react-frame-component": "^4.1.3",
"react-router": "^7.1.4", "react-router-dom": "6.27.0",
"sanitize-filename": "1.6.3", "sanitize-filename": "1.6.3",
"superagent": "^10.1.1", "superagent": "^10.1.0",
"vitreum": "git+https://git@github.com/calculuschild/vitreum.git" "vitreum": "git+https://git@github.com/calculuschild/vitreum.git"
}, },
"devDependencies": { "devDependencies": {
"@stylistic/stylelint-plugin": "^3.1.1", "@stylistic/stylelint-plugin": "^3.1.1",
"babel-plugin-transform-import-meta": "^2.3.2", "eslint": "^9.12.0",
"eslint": "^9.19.0", "eslint-plugin-jest": "^28.8.3",
"eslint-plugin-jest": "^28.11.0", "eslint-plugin-react": "^7.37.1",
"eslint-plugin-react": "^7.37.4", "globals": "^15.11.0",
"globals": "^15.14.0",
"jest": "^29.7.0", "jest": "^29.7.0",
"jest-expect-message": "^1.1.3", "jest-expect-message": "^1.1.3",
"jsdom-global": "^3.0.2",
"postcss-less": "^6.0.0", "postcss-less": "^6.0.0",
"stylelint": "^16.14.1", "stylelint": "^16.10.0",
"stylelint-config-recess-order": "^6.0.0", "stylelint-config-recess-order": "^5.1.1",
"stylelint-config-recommended": "^15.0.0", "stylelint-config-recommended": "^14.0.1",
"supertest": "^7.0.0" "supertest": "^7.0.0"
} }
} }

View File

@@ -1,14 +1,13 @@
const fs = require('fs-extra');
const Proj = require('./project.json');
import fs from 'fs-extra'; const { pack } = require('vitreum');
import Proj from './project.json' with { type: 'json' };
import vitreum from 'vitreum';
const { pack } = vitreum;
import lessTransform from 'vitreum/transforms/less.js';
import assetTransform from 'vitreum/transforms/asset.js';
const isDev = !!process.argv.find((arg)=>arg=='--dev'); const isDev = !!process.argv.find((arg)=>arg=='--dev');
const lessTransform = require('vitreum/transforms/less.js');
const assetTransform = require('vitreum/transforms/asset.js');
//const Meta = require('vitreum/headtags');
const transforms = { const transforms = {
'.less' : lessTransform, '.less' : lessTransform,
'*' : assetTransform('./build') '*' : assetTransform('./build')
@@ -18,7 +17,7 @@ const build = async ({ bundle, render, ssr })=>{
const css = await lessTransform.generate({ paths: './shared' }); const css = await lessTransform.generate({ paths: './shared' });
await fs.outputFile('./build/admin/bundle.css', css); await fs.outputFile('./build/admin/bundle.css', css);
await fs.outputFile('./build/admin/bundle.js', bundle); await fs.outputFile('./build/admin/bundle.js', bundle);
await fs.outputFile('./build/admin/ssr.cjs', ssr); await fs.outputFile('./build/admin/ssr.js', ssr);
}; };
fs.emptyDirSync('./build/admin'); fs.emptyDirSync('./build/admin');

View File

@@ -1,18 +1,16 @@
import fs from 'fs-extra'; const fs = require('fs-extra');
import zlib from 'zlib'; const zlib = require('zlib');
import Proj from './project.json' with { type: 'json' }; const Proj = require('./project.json');
import vitreum from 'vitreum';
const { pack, watchFile, livereload } = vitreum;
import lessTransform from 'vitreum/transforms/less.js'; const { pack, watchFile, livereload } = require('vitreum');
import assetTransform from 'vitreum/transforms/asset.js'; const isDev = !!process.argv.find((arg)=>arg=='--dev');
import babel from '@babel/core';
import babelConfig from '../babel.config.json' with { type : 'json' };
import less from 'less';
const isDev = !!process.argv.find((arg) => arg === '--dev'); const lessTransform = require('vitreum/transforms/less.js');
const assetTransform = require('vitreum/transforms/asset.js');
const babel = require('@babel/core');
const less = require('less');
const babelify = async (code)=>(await babel.transformAsync(code, babelConfig)).code; const babelify = async (code)=>(await babel.transformAsync(code, { presets: [['@babel/preset-env', { 'exclude': ['proposal-dynamic-import'] }], '@babel/preset-react'], plugins: ['@babel/plugin-transform-runtime'] })).code;
const transforms = { const transforms = {
'.js' : (code, filename, opts)=>babelify(code), '.js' : (code, filename, opts)=>babelify(code),
@@ -26,7 +24,7 @@ const build = async ({ bundle, render, ssr })=>{
//css = `@layer bundle {\n${css}\n}`; //css = `@layer bundle {\n${css}\n}`;
await fs.outputFile('./build/homebrew/bundle.css', css); await fs.outputFile('./build/homebrew/bundle.css', css);
await fs.outputFile('./build/homebrew/bundle.js', bundle); await fs.outputFile('./build/homebrew/bundle.js', bundle);
await fs.outputFile('./build/homebrew/ssr.cjs', ssr); await fs.outputFile('./build/homebrew/ssr.js', ssr);
await fs.copy('./client/homebrew/favicon.ico', './build/assets/favicon.ico'); await fs.copy('./client/homebrew/favicon.ico', './build/assets/favicon.ico');
@@ -53,7 +51,7 @@ fs.emptyDirSync('./build');
const themes = { Legacy: {}, V3: {} }; const themes = { Legacy: {}, V3: {} };
let themeFiles = fs.readdirSync('./themes/Legacy'); let themeFiles = fs.readdirSync('./themes/Legacy');
for (let dir of themeFiles) { for (dir of themeFiles) {
const themeData = JSON.parse(fs.readFileSync(`./themes/Legacy/${dir}/settings.json`).toString()); const themeData = JSON.parse(fs.readFileSync(`./themes/Legacy/${dir}/settings.json`).toString());
themeData.path = dir; themeData.path = dir;
themes.Legacy[dir] = (themeData); themes.Legacy[dir] = (themeData);
@@ -70,7 +68,7 @@ fs.emptyDirSync('./build');
} }
themeFiles = fs.readdirSync('./themes/V3'); themeFiles = fs.readdirSync('./themes/V3');
for (let dir of themeFiles) { for (dir of themeFiles) {
const themeData = JSON.parse(fs.readFileSync(`./themes/V3/${dir}/settings.json`).toString()); const themeData = JSON.parse(fs.readFileSync(`./themes/V3/${dir}/settings.json`).toString());
themeData.path = dir; themeData.path = dir;
themes.V3[dir] = (themeData); themes.V3[dir] = (themeData);
@@ -106,14 +104,14 @@ fs.emptyDirSync('./build');
const editorThemesBuildDir = './build/homebrew/cm-themes'; const editorThemesBuildDir = './build/homebrew/cm-themes';
await fs.copy('./node_modules/codemirror/theme', editorThemesBuildDir); await fs.copy('./node_modules/codemirror/theme', editorThemesBuildDir);
await fs.copy('./themes/codeMirror/customThemes', editorThemesBuildDir); await fs.copy('./themes/codeMirror/customThemes', editorThemesBuildDir);
const editorThemeFiles = fs.readdirSync(editorThemesBuildDir); editorThemeFiles = fs.readdirSync(editorThemesBuildDir);
const editorThemeFile = './themes/codeMirror/editorThemes.json'; const editorThemeFile = './themes/codeMirror/editorThemes.json';
if(fs.existsSync(editorThemeFile)) fs.rmSync(editorThemeFile); if(fs.existsSync(editorThemeFile)) fs.rmSync(editorThemeFile);
const stream = fs.createWriteStream(editorThemeFile, { flags: 'a' }); const stream = fs.createWriteStream(editorThemeFile, { flags: 'a' });
stream.write('[\n"default"'); stream.write('[\n"default"');
for (let themeFile of editorThemeFiles) { for (themeFile of editorThemeFiles) {
stream.write(`,\n"${themeFile.slice(0, -4)}"`); stream.write(`,\n"${themeFile.slice(0, -4)}"`);
} }
stream.write('\n]\n'); stream.write('\n]\n');

View File

@@ -1,12 +1,12 @@
import DB from './server/db.js'; const DB = require('./server/db.js');
import server from './server/app.js'; const server = require('./server/app.js');
import config from './server/config.js'; const config = require('./server/config.js');
DB.connect(config).then(()=>{ DB.connect(config).then(()=>{
// Ensure that we have successfully connected to the database // Ensure that we have successfully connected to the database
// before launching server // before launching server
const PORT = process.env.PORT || config.get('web_port') || 8000; const PORT = process.env.PORT || config.get('web_port') || 8000;
server.listen(PORT, ()=>{ server.app.listen(PORT, ()=>{
const reset = '\x1b[0m'; // Reset to default style const reset = '\x1b[0m'; // Reset to default style
const bright = '\x1b[1m'; // Bright (bold) style const bright = '\x1b[1m'; // Bright (bold) style
const cyan = '\x1b[36m'; // Cyan color const cyan = '\x1b[36m'; // Cyan color

View File

@@ -1,15 +1,9 @@
import { model as HomebrewModel } from './homebrew.model.js'; const HomebrewModel = require('./homebrew.model.js').model;
import { model as NotificationModel } from './notifications.model.js'; const NotificationModel = require('./notifications.model.js').model;
import express from 'express'; const router = require('express').Router();
import Moment from 'moment'; const Moment = require('moment');
import zlib from 'zlib'; const templateFn = require('../client/template.js');
import templateFn from '../client/template.js'; const zlib = require('zlib');
import HomebrewAPI from './homebrew.api.js';
import asyncHandler from 'express-async-handler';
import { splitTextStyleAndMetadata } from '../shared/helpers.js';
const router = express.Router();
process.env.ADMIN_USER = process.env.ADMIN_USER || 'admin'; process.env.ADMIN_USER = process.env.ADMIN_USER || 'admin';
process.env.ADMIN_PASS = process.env.ADMIN_PASS || 'password3'; process.env.ADMIN_PASS = process.env.ADMIN_PASS || 'password3';
@@ -72,8 +66,23 @@ router.post('/admin/cleanup', mw.adminOnly, (req, res)=>{
}); });
/* Searches for matching edit or share id, also attempts to partial match */ /* Searches for matching edit or share id, also attempts to partial match */
router.get('/admin/lookup/:id', mw.adminOnly, asyncHandler(HomebrewAPI.getBrew('admin', false)), async (req, res, next)=>{ router.get('/admin/lookup/:id', mw.adminOnly, async (req, res, next)=>{
return res.json(req.brew); HomebrewModel.findOne({
$or : [
{ editId: { $regex: req.params.id, $options: 'i' } },
{ shareId: { $regex: req.params.id, $options: 'i' } },
]
}).exec()
.then((brew)=>{
if(!brew) // No document found
return res.status(404).json({ error: 'Document not found' });
else
return res.json(brew);
})
.catch((err)=>{
console.error(err);
return res.status(500).json({ error: 'Internal Server Error' });
});
}); });
/* Find 50 brews that aren't compressed yet */ /* Find 50 brews that aren't compressed yet */
@@ -91,28 +100,6 @@ router.get('/admin/finduncompressed', mw.adminOnly, (req, res)=>{
}); });
}); });
/* Cleans `<script` and `</script>` from the "text" field of a brew */
router.put('/admin/clean/script/:id', asyncHandler(HomebrewAPI.getBrew('admin', false)), async (req, res)=>{
console.log(`[ADMIN] Cleaning script tags from ShareID ${req.params.id}`);
function cleanText(text){return text.replaceAll(/(<\/?s)cript/gi, '');};
const brew = req.brew;
const properties = ['text', 'description', 'title'];
properties.forEach((property)=>{
brew[property] = cleanText(brew[property]);
});
splitTextStyleAndMetadata(brew);
req.body = brew;
// Remove Account from request to prevent Admin user from being added to brew as an Author
req.account = undefined;
return await HomebrewAPI.updateBrew(req, res);
});
/* Compresses the "text" field of a brew to binary */ /* Compresses the "text" field of a brew to binary */
router.put('/admin/compress/:id', (req, res)=>{ router.put('/admin/compress/:id', (req, res)=>{
@@ -157,7 +144,6 @@ router.get('/admin/notification/all', async (req, res, next)=>{
try { try {
const notifications = await NotificationModel.getAll(); const notifications = await NotificationModel.getAll();
return res.json(notifications); return res.json(notifications);
} catch (error) { } catch (error) {
console.log('Error getting all notifications: ', error.message); console.log('Error getting all notifications: ', error.message);
return res.status(500).json({ message: error.message }); return res.status(500).json({ message: error.message });
@@ -165,6 +151,7 @@ router.get('/admin/notification/all', async (req, res, next)=>{
}); });
router.post('/admin/notification/add', mw.adminOnly, async (req, res, next)=>{ router.post('/admin/notification/add', mw.adminOnly, async (req, res, next)=>{
console.table(req.body);
try { try {
const notification = await NotificationModel.addNotification(req.body); const notification = await NotificationModel.addNotification(req.body);
return res.status(201).json(notification); return res.status(201).json(notification);
@@ -195,4 +182,4 @@ router.get('/admin', mw.adminOnly, (req, res)=>{
}); });
}); });
export default router; module.exports = router;

View File

@@ -1,10 +1,9 @@
import supertest from 'supertest'; const supertest = require('supertest');
import HBApp from './app.js';
import {model as NotificationModel } from './notifications.model.js';
const app = supertest.agent(require('app.js').app)
.set('X-Forwarded-Proto', 'https');
// Mimic https responses to avoid being redirected all the time const NotificationModel = require('./notifications.model.js').model;
const app = supertest.agent(HBApp).set('X-Forwarded-Proto', 'https');
describe('Tests for admin api', ()=>{ describe('Tests for admin api', ()=>{
afterEach(()=>{ afterEach(()=>{

View File

@@ -1,41 +1,25 @@
/*eslint max-lines: ["warn", {"max": 500, "skipBlankLines": true, "skipComments": true}]*/ /*eslint max-lines: ["warn", {"max": 500, "skipBlankLines": true, "skipComments": true}]*/
// Set working directory to project root // Set working directory to project root
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import packageJSON from './../package.json' with { type: 'json' };
const __dirname = dirname(fileURLToPath(import.meta.url));
process.chdir(`${__dirname}/..`); process.chdir(`${__dirname}/..`);
const version = packageJSON.version;
import _ from 'lodash';
import jwt from 'jwt-simple';
import express from 'express';
import yaml from 'js-yaml';
import config from './config.js';
import fs from 'fs-extra';
const _ = require('lodash');
const jwt = require('jwt-simple');
const express = require('express');
const yaml = require('js-yaml');
const app = express(); const app = express();
const config = require('./config.js');
const fs = require('fs-extra');
import api from './homebrew.api.js'; const { homebrewApi, getBrew, getUsersBrewThemes, getCSS } = require('./homebrew.api.js');
const { homebrewApi, getBrew, getUsersBrewThemes, getCSS } = api; const GoogleActions = require('./googleActions.js');
import adminApi from './admin.api.js'; const serveCompressedStaticAssets = require('./static-assets.mv.js');
import vaultApi from './vault.api.js'; const sanitizeFilename = require('sanitize-filename');
import GoogleActions from './googleActions.js'; const asyncHandler = require('express-async-handler');
import serveCompressedStaticAssets from './static-assets.mv.js'; const templateFn = require('./../client/template.js');
import sanitizeFilename from 'sanitize-filename';
import asyncHandler from 'express-async-handler';
import templateFn from '../client/template.js';
import { model as HomebrewModel } from './homebrew.model.js';
import { DEFAULT_BREW } from './brewDefaults.js'; const { DEFAULT_BREW } = require('./brewDefaults.js');
import { splitTextStyleAndMetadata } from '../shared/helpers.js';
//==== Middleware Imports ====// const { splitTextStyleAndMetadata } = require('../shared/helpers.js');
import contentNegotiation from './middleware/content-negotiation.js';
import bodyParser from 'body-parser';
import cookieParser from 'cookie-parser';
import forceSSL from './forcessl.mw.js';
const sanitizeBrew = (brew, accessType)=>{ const sanitizeBrew = (brew, accessType)=>{
@@ -47,47 +31,13 @@ const sanitizeBrew = (brew, accessType)=>{
return brew; return brew;
}; };
app.set('trust proxy', 1 /* number of proxies between user and server */); app.set('trust proxy', 1 /* number of proxies between user and server */)
app.use('/', serveCompressedStaticAssets(`build`)); app.use('/', serveCompressedStaticAssets(`build`));
app.use(contentNegotiation); app.use(require('./middleware/content-negotiation.js'));
app.use(bodyParser.json({ limit: '25mb' })); app.use(require('body-parser').json({ limit: '25mb' }));
app.use(cookieParser()); app.use(require('cookie-parser')());
app.use(forceSSL); app.use(require('./forcessl.mw.js'));
import cors from 'cors';
const nodeEnv = config.get('node_env');
const isLocalEnvironment = config.get('local_environments').includes(nodeEnv);
const corsOptions = {
origin : (origin, callback)=>{
const allowedOrigins = [
'https://homebrewery.naturalcrit.com',
'https://www.naturalcrit.com',
'https://naturalcrit-stage.herokuapp.com',
'https://homebrewery-stage.herokuapp.com',
];
if(isLocalEnvironment) {
allowedOrigins.push('http://localhost:8000', 'http://localhost:8010');
}
const herokuRegex = /^https:\/\/(?:homebrewery-pr-\d+\.herokuapp\.com|naturalcrit-pr-\d+\.herokuapp\.com)$/; // Matches any Heroku app
if(!origin || allowedOrigins.includes(origin) || herokuRegex.test(origin)) {
callback(null, true);
} else {
console.log(origin, 'not allowed');
callback(new Error('Not allowed by CORS, if you think this is an error, please contact us'));
}
},
methods : ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
credentials : true,
};
app.use(cors(corsOptions));
//Account Middleware //Account Middleware
app.use((req, res, next)=>{ app.use((req, res, next)=>{
@@ -96,9 +46,7 @@ app.use((req, res, next)=>{
req.account = jwt.decode(req.cookies.nc_session, config.get('secret')); req.account = jwt.decode(req.cookies.nc_session, config.get('secret'));
//console.log("Just loaded up JWT from cookie:"); //console.log("Just loaded up JWT from cookie:");
//console.log(req.account); //console.log(req.account);
} catch (e){ } catch (e){}
console.log(e);
}
} }
req.config = { req.config = {
@@ -109,14 +57,15 @@ app.use((req, res, next)=>{
}); });
app.use(homebrewApi); app.use(homebrewApi);
app.use(adminApi); app.use(require('./admin.api.js'));
app.use(vaultApi); app.use(require('./vault.api.js'));
const welcomeText = fs.readFileSync('client/homebrew/pages/homePage/welcome_msg.md', 'utf8'); const HomebrewModel = require('./homebrew.model.js').model;
const welcomeTextLegacy = fs.readFileSync('client/homebrew/pages/homePage/welcome_msg_legacy.md', 'utf8'); const welcomeText = require('fs').readFileSync('client/homebrew/pages/homePage/welcome_msg.md', 'utf8');
const migrateText = fs.readFileSync('client/homebrew/pages/homePage/migrate.md', 'utf8'); const welcomeTextLegacy = require('fs').readFileSync('client/homebrew/pages/homePage/welcome_msg_legacy.md', 'utf8');
const changelogText = fs.readFileSync('changelog.md', 'utf8'); const migrateText = require('fs').readFileSync('client/homebrew/pages/homePage/migrate.md', 'utf8');
const faqText = fs.readFileSync('faq.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);}; String.prototype.replaceAll = function(s, r){return this.split(s).join(r);};
@@ -309,7 +258,7 @@ app.get('/user/:username', async (req, res, next)=>{
console.log(err); console.log(err);
}); });
brews.forEach((brew)=>brew.stubbed = true); //All brews from MongoDB are "stubbed" brews.forEach(brew => brew.stubbed = true); //All brews from MongoDB are "stubbed"
if(ownAccount && req?.account?.googleId){ if(ownAccount && req?.account?.googleId){
const auth = await GoogleActions.authCheck(req.account, res); const auth = await GoogleActions.authCheck(req.account, res);
@@ -348,34 +297,6 @@ app.get('/user/:username', async (req, res, next)=>{
return next(); return next();
}); });
//Change author name on brews
app.put('/api/user/rename', async (req, res)=>{
const { username, newUsername } = req.body;
const ownAccount = req.account && (req.account.username == newUsername);
if(!username || !newUsername)
return res.status(400).json({ error: 'Username and newUsername are required.' });
if(!ownAccount)
return res.status(403).json({ error: 'Must be logged in to change your username' });
try {
const brews = await HomebrewModel.getByUser(username, true, ['authors']);
const renamePromises = brews.map(async (brew)=>{
const updatedAuthors = brew.authors.map((author)=>author === username ? newUsername : author
);
return HomebrewModel.updateOne(
{ _id: brew._id },
{ $set: { authors: updatedAuthors } }
);
});
await Promise.all(renamePromises);
return res.json({ success: true, message: `Brews for ${username} renamed to ${newUsername}.` });
} catch (error) {
console.error('Error renaming brews:', error);
return res.status(500).json({ error: 'Failed to rename brews.' });
}
});
//Edit Page //Edit Page
app.get('/edit/:id', asyncHandler(getBrew('edit')), asyncHandler(async(req, res, next)=>{ app.get('/edit/:id', asyncHandler(getBrew('edit')), asyncHandler(async(req, res, next)=>{
req.brew = req.brew.toObject ? req.brew.toObject() : req.brew; req.brew = req.brew.toObject ? req.brew.toObject() : req.brew;
@@ -477,7 +398,7 @@ app.get('/account', asyncHandler(async (req, res, next)=>{
let googleCount = []; let googleCount = [];
if(req.account) { if(req.account) {
if(req.account.googleId) { if(req.account.googleId) {
auth = await GoogleActions.authCheck(req.account, res, false); auth = await GoogleActions.authCheck(req.account, res, false)
googleCount = await GoogleActions.listGoogleBrews(auth) googleCount = await GoogleActions.listGoogleBrews(auth)
.catch((err)=>{ .catch((err)=>{
@@ -512,6 +433,8 @@ app.get('/account', asyncHandler(async (req, res, next)=>{
return next(); return next();
})); }));
const nodeEnv = config.get('node_env');
const isLocalEnvironment = config.get('local_environments').includes(nodeEnv);
// Local only // Local only
if(isLocalEnvironment){ if(isLocalEnvironment){
// Login // Login
@@ -556,7 +479,7 @@ const renderPage = async (req, res)=>{
deployment : config.get('heroku_app_name') ?? '' deployment : config.get('heroku_app_name') ?? ''
}; };
const props = { const props = {
version : version, version : require('./../package.json').version,
url : req.customUrl || req.originalUrl, url : req.customUrl || req.originalUrl,
brew : req.brew, brew : req.brew,
brews : req.brews, brews : req.brews,
@@ -633,4 +556,6 @@ app.use((req, res)=>{
}); });
//^=====--------------------------------------=====^// //^=====--------------------------------------=====^//
export default app; module.exports = {
app : app
};

View File

@@ -1,4 +1,4 @@
import _ from 'lodash'; const _ = require('lodash');
// Default properties for newly-created brews // Default properties for newly-created brews
const DEFAULT_BREW = { const DEFAULT_BREW = {
@@ -32,7 +32,7 @@ const DEFAULT_BREW_LOAD = _.defaults(
}, },
DEFAULT_BREW); DEFAULT_BREW);
export { module.exports = {
DEFAULT_BREW, DEFAULT_BREW,
DEFAULT_BREW_LOAD DEFAULT_BREW_LOAD
}; };

View File

@@ -1,6 +1,4 @@
import nconf from 'nconf'; module.exports = require('nconf')
export default nconf
.argv() .argv()
.env({ lowerCase: true }) .env({ lowerCase: true })
.file('environment', { file: `config/${process.env.NODE_ENV}.json` }) .file('environment', { file: `config/${process.env.NODE_ENV}.json` })

View File

@@ -5,7 +5,7 @@
// reused by both the main application and all tests which require database // reused by both the main application and all tests which require database
// connection. // connection.
import Mongoose from 'mongoose'; const Mongoose = require('mongoose');
const getMongoDBURL = (config)=>{ const getMongoDBURL = (config)=>{
return config.get('mongodb_uri') || return config.get('mongodb_uri') ||
@@ -31,7 +31,7 @@ const connect = async (config)=>{
.catch((error)=>handleConnectionError(error)); .catch((error)=>handleConnectionError(error));
}; };
export default { module.exports = {
connect, connect : connect,
disconnect disconnect : disconnect
}; };

View File

@@ -1,4 +1,4 @@
export default (req, res, next)=>{ module.exports = (req, res, next)=>{
if(process.env.NODE_ENV === 'local' || process.env.NODE_ENV === 'docker') return next(); if(process.env.NODE_ENV === 'local' || process.env.NODE_ENV === 'docker') return next();
if(req.header('x-forwarded-proto') !== 'https') { if(req.header('x-forwarded-proto') !== 'https') {
return res.redirect(302, `https://${req.get('Host')}${req.url}`); return res.redirect(302, `https://${req.get('Host')}${req.url}`);

View File

@@ -1,9 +1,8 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
import googleDrive from '@googleapis/drive'; const googleDrive = require('@googleapis/drive');
import { nanoid } from 'nanoid'; const { nanoid } = require('nanoid');
import token from './token.js'; const token = require('./token.js');
import config from './config.js'; const config = require('./config.js');
let serviceAuth; let serviceAuth;
if(!config.get('service_account')){ if(!config.get('service_account')){
@@ -60,7 +59,7 @@ const GoogleActions = {
account.googleRefreshToken = tokens.refresh_token; account.googleRefreshToken = tokens.refresh_token;
} }
account.googleAccessToken = tokens.access_token; account.googleAccessToken = tokens.access_token;
const JWTToken = token(account); const JWTToken = token.generateAccessToken(account);
//Save updated token to cookie //Save updated token to cookie
//res.cookie('nc_session', JWTToken, { maxAge: 1000*60*60*24*365, path: '/', sameSite: 'lax' }); //res.cookie('nc_session', JWTToken, { maxAge: 1000*60*60*24*365, path: '/', sameSite: 'lax' });
@@ -73,7 +72,7 @@ const GoogleActions = {
getGoogleFolder : async (auth)=>{ getGoogleFolder : async (auth)=>{
const drive = googleDrive.drive({ version: 'v3', auth }); const drive = googleDrive.drive({ version: 'v3', auth });
const fileMetadata = { fileMetadata = {
'name' : 'Homebrewery', 'name' : 'Homebrewery',
'mimeType' : 'application/vnd.google-apps.folder' 'mimeType' : 'application/vnd.google-apps.folder'
}; };
@@ -241,8 +240,8 @@ const GoogleActions = {
return obj.data.id; return obj.data.id;
}, },
getGoogleBrew : async (auth = defaultAuth, id, accessId, accessType)=>{ getGoogleBrew : async (id, accessId, accessType)=>{
const drive = googleDrive.drive({ version: 'v3', auth: auth }); const drive = googleDrive.drive({ version: 'v3', auth: defaultAuth });
const obj = await drive.files.get({ const obj = await drive.files.get({
fileId : id, fileId : id,
@@ -345,4 +344,4 @@ const GoogleActions = {
} }
}; };
export default GoogleActions; module.exports = GoogleActions;

View File

@@ -1,20 +1,18 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
import _ from 'lodash'; const _ = require('lodash');
import {model as HomebrewModel} from './homebrew.model.js'; const HomebrewModel = require('./homebrew.model.js').model;
import express from 'express'; const router = require('express').Router();
import zlib from 'zlib'; const zlib = require('zlib');
import GoogleActions from './googleActions.js'; const GoogleActions = require('./googleActions.js');
import Markdown from '../shared/naturalcrit/markdown.js'; const Markdown = require('../shared/naturalcrit/markdown.js');
import yaml from 'js-yaml'; const yaml = require('js-yaml');
import asyncHandler from 'express-async-handler'; const asyncHandler = require('express-async-handler');
import { nanoid } from 'nanoid'; const { nanoid } = require('nanoid');
import { splitTextStyleAndMetadata } from '../shared/helpers.js'; const { splitTextStyleAndMetadata } = require('../shared/helpers.js');
import checkClientVersion from './middleware/check-client-version.js';
const router = express.Router(); const { DEFAULT_BREW, DEFAULT_BREW_LOAD } = require('./brewDefaults.js');
import { DEFAULT_BREW, DEFAULT_BREW_LOAD } from './brewDefaults.js'; const Themes = require('../themes/themes.json');
import Themes from '../themes/themes.json' with { type: 'json' };
const isStaticTheme = (renderer, themeName)=>{ const isStaticTheme = (renderer, themeName)=>{
return Themes[renderer]?.[themeName] !== undefined; return Themes[renderer]?.[themeName] !== undefined;
@@ -87,68 +85,66 @@ const api = {
// Create middleware with the accessType passed in as part of the scope // Create middleware with the accessType passed in as part of the scope
return async (req, res, next)=>{ return async (req, res, next)=>{
// Get relevant IDs for the brew // Get relevant IDs for the brew
let { id, googleId } = api.getId(req); const { id, googleId } = api.getId(req);
const accessMap = {
edit : { editId: id },
share : { shareId: id },
admin : { $or : [{ editId: id }, { shareId: id }] }
};
// Try to find the document in the Homebrewery database -- if it doesn't exist, that's fine. // Try to find the document in the Homebrewery database -- if it doesn't exist, that's fine.
let stub = await HomebrewModel.get(accessMap[accessType]) let stub = await HomebrewModel.get(accessType === 'edit' ? { editId: id } : { shareId: id })
.catch((err)=>{ .catch((err)=>{
if(googleId) if(googleId) {
console.warn(`Unable to find document stub for ${accessType}Id ${id}`); console.warn(`Unable to find document stub for ${accessType}Id ${id}`);
else } else {
console.warn(err); console.warn(err);
}
}); });
stub = stub?.toObject(); stub = stub?.toObject();
googleId ??= stub?.googleId;
const isOwner = (accessType == 'edit' && (!stub || stub?.authors?.length === 0)) || stub?.authors?.[0] === req.account?.username;
const isAuthor = stub?.authors?.includes(req.account?.username);
const isInvited = stub?.invitedAuthors?.includes(req.account?.username);
if(accessType === 'edit' && !(isOwner || isAuthor || isInvited)) {
const accessError = { name: 'Access Error', status: 401, authors: stub?.authors, brewTitle: stub?.title, shareId: stub?.shareId };
if(req.account)
throw { ...accessError, message: 'User is not an Author', HBErrorCode: '03' };
else
throw { ...accessError, message: 'User is not logged in', HBErrorCode: '04' };
}
if(stub?.lock?.locked && accessType != 'edit') { if(stub?.lock?.locked && accessType != 'edit') {
throw { HBErrorCode: '51', code: stub?.lock.code, message: stub?.lock.shareMessage, brewId: stub?.shareId, brewTitle: stub?.title }; throw { HBErrorCode: '51', code: stub.lock.code, message: stub.lock.shareMessage, brewId: stub.shareId, brewTitle: stub.title };
} }
// If there's a google id, get it if requesting the full brew or if no stub found yet // If there is a google id, try to find the google brew
if(googleId && (!stubOnly || !stub)) { if(!stubOnly && (googleId || stub?.googleId)) {
const oAuth2Client = isOwner ? GoogleActions.authCheck(req.account, res) : undefined; let googleError;
const googleBrew = await GoogleActions.getGoogleBrew(googleId || stub?.googleId, id, accessType)
const googleBrew = await GoogleActions.getGoogleBrew(oAuth2Client, googleId, id, accessType) .catch((err)=>{
.catch((googleError)=>{ googleError = err;
const reason = googleError.errors?.[0].reason;
if(reason == 'notFound')
throw { ...googleError, HBErrorCode: '02', authors: stub?.authors, account: req.account?.username };
else
throw { ...googleError, HBErrorCode: '01' };
}); });
// Throw any error caught while attempting to retrieve Google brew.
if(googleError) {
const reason = googleError.errors?.[0].reason;
if(reason == 'notFound') {
throw { ...googleError, HBErrorCode: '02', authors: stub?.authors, account: req.account?.username };
} else {
throw { ...googleError, HBErrorCode: '01' };
}
}
// Combine the Homebrewery stub with the google brew, or if the stub doesn't exist just use the google brew // Combine the Homebrewery stub with the google brew, or if the stub doesn't exist just use the google brew
stub = stub ? _.assign({ ...api.excludeStubProps(stub), stubbed: true }, api.excludeGoogleProps(googleBrew)) : googleBrew; stub = stub ? _.assign({ ...api.excludeStubProps(stub), stubbed: true }, api.excludeGoogleProps(googleBrew)) : googleBrew;
} }
const authorsExist = stub?.authors?.length > 0;
const isAuthor = stub?.authors?.includes(req.account?.username);
const isInvited = stub?.invitedAuthors?.includes(req.account?.username);
if(accessType === 'edit' && (authorsExist && !(isAuthor || isInvited))) {
const accessError = { name: 'Access Error', status: 401 };
if(req.account){
throw { ...accessError, message: 'User is not an Author', HBErrorCode: '03', authors: stub.authors, brewTitle: stub.title, shareId: stub.shareId };
}
throw { ...accessError, message: 'User is not logged in', HBErrorCode: '04', authors: stub.authors, brewTitle: stub.title, shareId: stub.shareId };
}
// If after all of that we still don't have a brew, throw an exception // If after all of that we still don't have a brew, throw an exception
if(!stub) if(!stub && !stubOnly) {
throw { name: 'BrewLoad Error', message: 'Brew not found', status: 404, HBErrorCode: '05', accessType: accessType, brewId: id }; throw { name: 'BrewLoad Error', message: 'Brew not found', status: 404, HBErrorCode: '05', accessType: accessType, brewId: id };
}
// Clean up brew: fill in missing fields with defaults / fix old invalid values // Clean up brew: fill in missing fields with defaults / fix old invalid values
if(stub) {
stub.tags = stub.tags || undefined; // Clear empty strings stub.tags = stub.tags || undefined; // Clear empty strings
stub.renderer = stub.renderer || undefined; // Clear empty strings stub.renderer = stub.renderer || undefined; // Clear empty strings
stub = _.defaults(stub, DEFAULT_BREW_LOAD); // Fill in blank fields stub = _.defaults(stub, DEFAULT_BREW_LOAD); // Fill in blank fields
}
req.brew = stub; req.brew = stub ?? {};
next(); next();
}; };
}, },
@@ -299,8 +295,9 @@ const api = {
req.params.id = currentTheme.theme; req.params.id = currentTheme.theme;
req.params.renderer = currentTheme.renderer; req.params.renderer = currentTheme.renderer;
} else { }
//=== Static Themes ===// //=== Static Themes ===//
else {
const localSnippets = `${req.params.renderer}_${req.params.id}`; // Just log the name for loading on client const localSnippets = `${req.params.renderer}_${req.params.id}`; // Just log the name for loading on client
const localStyle = `@import url(\"/themes/${req.params.renderer}/${req.params.id}/style.css\");`; const localStyle = `@import url(\"/themes/${req.params.renderer}/${req.params.id}/style.css\");`;
completeSnippets.push(localSnippets); completeSnippets.push(localSnippets);
@@ -467,11 +464,12 @@ const api = {
} }
}; };
router.post('/api', checkClientVersion, asyncHandler(api.newBrew)); router.use('/api', require('./middleware/check-client-version.js'));
router.put('/api/:id', checkClientVersion, asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew)); router.post('/api', asyncHandler(api.newBrew));
router.put('/api/update/:id', checkClientVersion, asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew)); router.put('/api/:id', asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew));
router.delete('/api/:id', checkClientVersion, asyncHandler(api.deleteBrew)); router.put('/api/update/:id', asyncHandler(api.getBrew('edit', true)), asyncHandler(api.updateBrew));
router.get('/api/remove/:id', checkClientVersion, asyncHandler(api.deleteBrew)); router.delete('/api/:id', asyncHandler(api.deleteBrew));
router.get('/api/remove/:id', asyncHandler(api.deleteBrew));
router.get('/api/theme/:renderer/:id', asyncHandler(api.getThemeBundle)); router.get('/api/theme/:renderer/:id', asyncHandler(api.getThemeBundle));
export default api; module.exports = api;

View File

@@ -1,7 +1,5 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
import { splitTextStyleAndMetadata } from '../shared/helpers.js';
describe('Tests for api', ()=>{ describe('Tests for api', ()=>{
let api; let api;
let google; let google;
@@ -38,9 +36,8 @@ describe('Tests for api', ()=>{
} }
}); });
google = require('./googleActions.js').default; google = require('./googleActions.js');
model = require('./homebrew.model.js').model; model = require('./homebrew.model.js').model;
api = require('./homebrew.api').default;
jest.mock('./googleActions.js'); jest.mock('./googleActions.js');
google.authCheck = jest.fn(()=>'client'); google.authCheck = jest.fn(()=>'client');
@@ -57,6 +54,8 @@ describe('Tests for api', ()=>{
setHeader : jest.fn(()=>{}) setHeader : jest.fn(()=>{})
}; };
api = require('./homebrew.api');
hbBrew = { hbBrew = {
text : `brew text`, text : `brew text`,
style : 'hello yes i am css', style : 'hello yes i am css',
@@ -298,7 +297,7 @@ describe('Tests for api', ()=>{
expect(next).toHaveBeenCalled(); expect(next).toHaveBeenCalled();
expect(api.getId).toHaveBeenCalledWith(req); expect(api.getId).toHaveBeenCalledWith(req);
expect(model.get).toHaveBeenCalledWith({ shareId: '1' }); expect(model.get).toHaveBeenCalledWith({ shareId: '1' });
expect(google.getGoogleBrew).toHaveBeenCalledWith(undefined, '2', '1', 'share'); expect(google.getGoogleBrew).toHaveBeenCalledWith('2', '1', 'share');
}); });
it('access is denied to a locked brew', async()=>{ it('access is denied to a locked brew', async()=>{
@@ -970,57 +969,4 @@ brew`);
expect(res.send).toHaveBeenCalledWith(''); expect(res.send).toHaveBeenCalledWith('');
}); });
}); });
describe('Split Text, Style, and Metadata', ()=>{
it('basic splitting', async ()=>{
const testBrew = {
text : '```metadata\n' +
'title: title\n' +
'description: description\n' +
'tags: [ \'tag a\' , \'tag b\' ]\n' +
'systems: [ test system ]\n' +
'renderer: legacy\n' +
'theme: 5ePHB\n' +
'lang: en\n' +
'\n' +
'```\n' +
'\n' +
'```css\n' +
'style\n' +
'style\n' +
'style\n' +
'```\n' +
'\n' +
'text\n'
};
splitTextStyleAndMetadata(testBrew);
// Metadata
expect(testBrew.title).toEqual('title');
expect(testBrew.description).toEqual('description');
expect(testBrew.tags).toEqual(['tag a', 'tag b']);
expect(testBrew.systems).toEqual(['test system']);
expect(testBrew.renderer).toEqual('legacy');
expect(testBrew.theme).toEqual('5ePHB');
expect(testBrew.lang).toEqual('en');
// Style
expect(testBrew.style).toEqual('style\nstyle\nstyle');
// Text
expect(testBrew.text).toEqual('text\n');
});
it('convert tags string to array', async ()=>{
const testBrew = {
text : '```metadata\n' +
'tags: tag a\n' +
'```\n\n'
};
splitTextStyleAndMetadata(testBrew);
// Metadata
expect(testBrew.tags).toEqual(['tag a']);
});
});
}); });

View File

@@ -1,8 +1,7 @@
import mongoose from 'mongoose'; const mongoose = require('mongoose');
import { nanoid } from 'nanoid'; const { nanoid } = require('nanoid');
import _ from 'lodash'; const _ = require('lodash');
import zlib from 'zlib'; const zlib = require('zlib');
const HomebrewSchema = mongoose.Schema({ const HomebrewSchema = mongoose.Schema({
shareId : { type: String, default: ()=>{return nanoid(12);}, index: { unique: true } }, shareId : { type: String, default: ()=>{return nanoid(12);}, index: { unique: true } },
@@ -45,7 +44,7 @@ HomebrewSchema.statics.get = async function(query, fields=null){
const brew = await Homebrew.findOne(query, fields).orFail() const brew = await Homebrew.findOne(query, fields).orFail()
.catch((error)=>{throw 'Can not find brew';}); .catch((error)=>{throw 'Can not find brew';});
if(!_.isNil(brew.textBin)) { // Uncompress zipped text field if(!_.isNil(brew.textBin)) { // Uncompress zipped text field
const unzipped = zlib.inflateRawSync(brew.textBin); unzipped = zlib.inflateRawSync(brew.textBin);
brew.text = unzipped.toString(); brew.text = unzipped.toString();
} }
return brew; return brew;
@@ -63,7 +62,7 @@ HomebrewSchema.statics.getByUser = async function(username, allowAccess=false, f
const Homebrew = mongoose.model('Homebrew', HomebrewSchema); const Homebrew = mongoose.model('Homebrew', HomebrewSchema);
export { module.exports = {
HomebrewSchema as schema, schema : HomebrewSchema,
Homebrew as model model : Homebrew,
}; };

View File

@@ -1,10 +1,8 @@
import packageJSON from '../../package.json' with { type: 'json' }; module.exports = (req, res, next)=>{
export default (req, res, next)=>{
const userVersion = req.get('Homebrewery-Version'); const userVersion = req.get('Homebrewery-Version');
const version = packageJSON.version; const version = require('../../package.json').version;
if(userVersion !== version) { if(userVersion != version) {
return res.status(412).send({ return res.status(412).send({
message : `Client version ${userVersion} is out of date. Please save your changes elsewhere and refresh to pick up client version ${version}.` message : `Client version ${userVersion} is out of date. Please save your changes elsewhere and refresh to pick up client version ${version}.`
}); });
@@ -12,4 +10,3 @@ export default (req, res, next)=>{
next(); next();
}; };

View File

@@ -1,12 +1,12 @@
import config from '../config.js'; const config = require('../config.js');
const nodeEnv = config.get('node_env'); const nodeEnv = config.get('node_env');
const isLocalEnvironment = config.get('local_environments').includes(nodeEnv); const isLocalEnvironment = config.get('local_environments').includes(nodeEnv);
export default (req, res, next)=>{ module.exports = (req, res, next)=>{
const isImageRequest = req.get('Accept')?.split(',') const isImageRequest = req.get('Accept')?.split(',')
?.filter((h)=>!h.includes('q=')) ?.filter((h)=>!h.includes('q='))
?.every((h)=>/image\/.*/.test(h)); ?.every((h)=>/image\/.*/.test(h));
if(isImageRequest && !(isLocalEnvironment && req.url?.startsWith('/staticImages'))) { if(isImageRequest && !isLocalEnvironment && !req.url?.startsWith('/staticImages')) {
return res.status(406).send({ return res.status(406).send({
message : 'Request for image at this URL is not supported' message : 'Request for image at this URL is not supported'
}); });

View File

@@ -1,4 +1,4 @@
import contentNegotiationMiddleware from './content-negotiation.js'; const contentNegotiationMiddleware = require('./content-negotiation.js');
describe('content-negotiation-middleware', ()=>{ describe('content-negotiation-middleware', ()=>{
let request; let request;

View File

@@ -1,5 +1,5 @@
import mongoose from 'mongoose'; const mongoose = require('mongoose');
import _ from 'lodash'; const _ = require('lodash');
const NotificationSchema = new mongoose.Schema({ const NotificationSchema = new mongoose.Schema({
dismissKey : { type: String, unique: true, required: true }, dismissKey : { type: String, unique: true, required: true },
@@ -56,7 +56,7 @@ NotificationSchema.statics.getAll = async function() {
const Notification = mongoose.model('Notification', NotificationSchema); const Notification = mongoose.model('Notification', NotificationSchema);
export { module.exports = {
NotificationSchema as schema, schema : NotificationSchema,
Notification as model model : Notification,
}; };

View File

@@ -1,4 +1,4 @@
import expressStaticGzip from 'express-static-gzip'; const expressStaticGzip = require('express-static-gzip');
// Serve brotli-compressed static files if available // Serve brotli-compressed static files if available
const customCacheControlHandler=(response, path)=>{ const customCacheControlHandler=(response, path)=>{
@@ -28,4 +28,4 @@ const init=(pathToAssets)=>{
} }); } });
}; };
export default init; module.exports = init;

View File

@@ -1,5 +1,7 @@
import jwt from 'jwt-simple'; const jwt = require('jwt-simple');
import config from './config.js';
// Load configuration values
const config = require('./config.js');
// Generate an Access Token for the given User ID // Generate an Access Token for the given User ID
const generateAccessToken = (account)=>{ const generateAccessToken = (account)=>{
@@ -22,4 +24,6 @@ const generateAccessToken = (account)=>{
return token; return token;
}; };
export default generateAccessToken; module.exports = {
generateAccessToken : generateAccessToken
};

View File

@@ -1,6 +1,6 @@
import express from 'express'; const express = require('express');
import asyncHandler from 'express-async-handler'; const asyncHandler = require('express-async-handler');
import {model as HomebrewModel } from './homebrew.model.js'; const HomebrewModel = require('./homebrew.model.js').model;
const router = express.Router(); const router = express.Router();
@@ -106,4 +106,4 @@ const findTotal = async (req, res)=>{
router.get('/api/vault/total', asyncHandler(findTotal)); router.get('/api/vault/total', asyncHandler(findTotal));
router.get('/api/vault', asyncHandler(findBrews)); router.get('/api/vault', asyncHandler(findBrews));
export default router; module.exports = router;

View File

@@ -1,6 +1,6 @@
import _ from 'lodash'; const _ = require('lodash');
import yaml from 'js-yaml'; const yaml = require('js-yaml');
import request from '../client/homebrew/utils/request-middleware.js'; const request = require('../client/homebrew/utils/request-middleware.js');
const splitTextStyleAndMetadata = (brew)=>{ const splitTextStyleAndMetadata = (brew)=>{
brew.text = brew.text.replaceAll('\r\n', '\n'); brew.text = brew.text.replaceAll('\r\n', '\n');
@@ -21,9 +21,6 @@ const splitTextStyleAndMetadata = (brew)=>{
brew.snippets = brew.text.slice(11, index - 1); brew.snippets = brew.text.slice(11, index - 1);
brew.text = brew.text.slice(index + 5); brew.text = brew.text.slice(index + 5);
} }
// Handle old brews that still have empty strings in the tags metadata
if(typeof brew.tags === 'string') brew.tags = brew.tags ? [brew.tags] : [];
}; };
const printCurrentBrew = ()=>{ const printCurrentBrew = ()=>{
@@ -47,14 +44,14 @@ const fetchThemeBundle = async (obj, renderer, theme)=>{
if(!res) return; if(!res) return;
const themeBundle = res.body; const themeBundle = res.body;
themeBundle.joinedStyles = themeBundle.styles.map((style)=>`<style>${style}</style>`).join('\n\n'); themeBundle.joinedStyles = themeBundle.styles.map((style)=>`${style}`).join('\n\n');
obj.setState((prevState)=>({ obj.setState((prevState)=>({
...prevState, ...prevState,
themeBundle : themeBundle themeBundle : themeBundle
})); }));
}; };
export { module.exports = {
splitTextStyleAndMetadata, splitTextStyleAndMetadata,
printCurrentBrew, printCurrentBrew,
fetchThemeBundle, fetchThemeBundle,

View File

@@ -1,7 +1,7 @@
import diceFont from '../../../themes/fonts/iconFonts/diceFont.js'; const diceFont = require('../../../themes/fonts/iconFonts/diceFont.js');
import elderberryInn from '../../../themes/fonts/iconFonts/elderberryInn.js'; const elderberryInn = require('../../../themes/fonts/iconFonts/elderberryInn.js');
import fontAwesome from '../../../themes/fonts/iconFonts/fontAwesome.js'; const fontAwesome = require('../../../themes/fonts/iconFonts/fontAwesome.js');
import gameIcons from '../../../themes/fonts/iconFonts/gameIcons.js'; const gameIcons = require('../../../themes/fonts/iconFonts/gameIcons.js');
const emojis = { const emojis = {
...diceFont, ...diceFont,

View File

@@ -11,8 +11,8 @@
@import (less) './themes/fonts/iconFonts/fontAwesome.less'; @import (less) './themes/fonts/iconFonts/fontAwesome.less';
@keyframes sourceMoveAnimation { @keyframes sourceMoveAnimation {
50% { color : white;background-color : red;} 50% {background-color: red; color: white;}
100% { color : unset;background-color : unset;} 100% {background-color: unset; color: unset;}
} }
.codeEditor{ .codeEditor{
@@ -21,16 +21,9 @@
} }
.CodeMirror-foldmarker { .CodeMirror-foldmarker {
font-family: inherit; font-family: inherit;
text-shadow: none;
font-weight: 600; font-weight: 600;
color: grey; color: grey;
text-shadow : none;
}
.CodeMirror-foldgutter {
cursor : pointer;
border-left : 1px solid #EEEEEE;
transition : background 0.1s;
&:hover { background : #DDDDDD; }
} }
.sourceMoveFlash .CodeMirror-line{ .sourceMoveFlash .CodeMirror-line{
@@ -39,7 +32,9 @@
} }
.CodeMirror-vscrollbar { .CodeMirror-vscrollbar {
&::-webkit-scrollbar { width : 20px; } &::-webkit-scrollbar {
width: 20px;
}
&::-webkit-scrollbar-thumb { &::-webkit-scrollbar-thumb {
width: 20px; width: 20px;
background: linear-gradient(90deg, #858585 15px, #808080 15px); background: linear-gradient(90deg, #858585 15px, #808080 15px);

View File

@@ -1,19 +1,18 @@
/* eslint-disable max-depth */
/* eslint-disable max-lines */ /* eslint-disable max-lines */
import _ from 'lodash'; const _ = require('lodash');
import { Parser as MathParser } from 'expr-eval'; const Marked = require('marked');
import { marked as Marked } from 'marked'; const MarkedExtendedTables = require('marked-extended-tables');
import MarkedExtendedTables from 'marked-extended-tables'; const { markedSmartypantsLite: MarkedSmartypantsLite } = require('marked-smartypants-lite');
import { markedSmartypantsLite as MarkedSmartypantsLite } from 'marked-smartypants-lite'; const { gfmHeadingId: MarkedGFMHeadingId, resetHeadings: MarkedGFMResetHeadingIDs } = require('marked-gfm-heading-id');
import { gfmHeadingId as MarkedGFMHeadingId, resetHeadings as MarkedGFMResetHeadingIDs } from 'marked-gfm-heading-id'; const { markedEmoji: MarkedEmojis } = require('marked-emoji');
import { markedEmoji as MarkedEmojis } from 'marked-emoji';
//Icon fonts included so they can appear in emoji autosuggest dropdown //Icon fonts included so they can appear in emoji autosuggest dropdown
import diceFont from '../../themes/fonts/iconFonts/diceFont.js'; const diceFont = require('../../themes/fonts/iconFonts/diceFont.js');
import elderberryInn from '../../themes/fonts/iconFonts/elderberryInn.js'; const elderberryInn = require('../../themes/fonts/iconFonts/elderberryInn.js');
import gameIcons from '../../themes/fonts/iconFonts/gameIcons.js'; const fontAwesome = require('../../themes/fonts/iconFonts/fontAwesome.js');
import fontAwesome from '../../themes/fonts/iconFonts/fontAwesome.js'; const gameIcons = require('../../themes/fonts/iconFonts/gameIcons.js');
const MathParser = require('expr-eval').Parser;
const renderer = new Marked.Renderer(); const renderer = new Marked.Renderer();
const tokenizer = new Marked.Tokenizer(); const tokenizer = new Marked.Tokenizer();
@@ -173,7 +172,7 @@ const mustacheSpans = {
return `<span` + return `<span` +
`${tags.classes ? ` class="${tags.classes}"` : ''}` + `${tags.classes ? ` class="${tags.classes}"` : ''}` +
`${tags.id ? ` id="${tags.id}"` : ''}` + `${tags.id ? ` id="${tags.id}"` : ''}` +
`${tags.styles ? ` style="${Object.entries(tags.styles).map(([key, value])=>`${key}:${value};`).join(' ')}"` : ''}` + `${tags.styles ? ` style="${tags.styles}"` : ''}` +
`${tags.attributes ? ` ${Object.entries(tags.attributes).map(([key, value])=>`${key}="${value}"`).join(' ')}` : ''}` + `${tags.attributes ? ` ${Object.entries(tags.attributes).map(([key, value])=>`${key}="${value}"`).join(' ')}` : ''}` +
`>${this.parser.parseInline(token.tokens)}</span>`; // parseInline to turn child tokens into HTML `>${this.parser.parseInline(token.tokens)}</span>`; // parseInline to turn child tokens into HTML
} }
@@ -229,7 +228,7 @@ const mustacheDivs = {
return `<div` + return `<div` +
`${tags.classes ? ` class="${tags.classes}"` : ''}` + `${tags.classes ? ` class="${tags.classes}"` : ''}` +
`${tags.id ? ` id="${tags.id}"` : ''}` + `${tags.id ? ` id="${tags.id}"` : ''}` +
`${tags.styles ? ` style="${Object.entries(tags.styles).map(([key, value])=>`${key}:${value};`).join(' ')}"` : ''}` + `${tags.styles ? ` style="${tags.styles}"` : ''}` +
`${tags.attributes ? ` ${Object.entries(tags.attributes).map(([key, value])=>`${key}="${value}"`).join(' ')}` : ''}` + `${tags.attributes ? ` ${Object.entries(tags.attributes).map(([key, value])=>`${key}="${value}"`).join(' ')}` : ''}` +
`>${this.parser.parse(token.tokens)}</div>`; // parse to turn child tokens into HTML `>${this.parser.parse(token.tokens)}</div>`; // parse to turn child tokens into HTML
} }
@@ -266,13 +265,18 @@ const mustacheInjectInline = {
const text = this.parser.parseInline([token]); const text = this.parser.parseInline([token]);
const originalTags = extractHTMLStyleTags(text); const originalTags = extractHTMLStyleTags(text);
const injectedTags = token.injectedTags; const injectedTags = token.injectedTags;
const tags = mergeHTMLTags(originalTags, injectedTags); const tags = {
id : injectedTags.id || originalTags.id || null,
classes : [originalTags.classes, injectedTags.classes].join(' ').trim() || null,
styles : [originalTags.styles, injectedTags.styles].join(' ').trim() || null,
attributes : Object.assign(originalTags.attributes ?? {}, injectedTags.attributes ?? {})
};
const openingTag = /(<[^\s<>]+)[^\n<>]*(>.*)/s.exec(text); const openingTag = /(<[^\s<>]+)[^\n<>]*(>.*)/s.exec(text);
if(openingTag) { if(openingTag) {
return `${openingTag[1]}` + return `${openingTag[1]}` +
`${tags.classes ? ` class="${tags.classes}"` : ''}` + `${tags.classes ? ` class="${tags.classes}"` : ''}` +
`${tags.id ? ` id="${tags.id}"` : ''}` + `${tags.id ? ` id="${tags.id}"` : ''}` +
`${!_.isEmpty(tags.styles) ? ` style="${Object.entries(tags.styles).map(([key, value])=>`${key}:${value};`).join(' ')}"` : ''}` + `${tags.styles ? ` style="${tags.styles}"` : ''}` +
`${!_.isEmpty(tags.attributes) ? ` ${Object.entries(tags.attributes).map(([key, value])=>`${key}="${value}"`).join(' ')}` : ''}` + `${!_.isEmpty(tags.attributes) ? ` ${Object.entries(tags.attributes).map(([key, value])=>`${key}="${value}"`).join(' ')}` : ''}` +
`${openingTag[2]}`; // parse to turn child tokens into HTML `${openingTag[2]}`; // parse to turn child tokens into HTML
} }
@@ -310,13 +314,18 @@ const mustacheInjectBlock = {
const text = this.parser.parse([token]); const text = this.parser.parse([token]);
const originalTags = extractHTMLStyleTags(text); const originalTags = extractHTMLStyleTags(text);
const injectedTags = token.injectedTags; const injectedTags = token.injectedTags;
const tags = mergeHTMLTags(originalTags, injectedTags); const tags = {
id : injectedTags.id || originalTags.id || null,
classes : [originalTags.classes, injectedTags.classes].join(' ').trim() || null,
styles : [originalTags.styles, injectedTags.styles].join(' ').trim() || null,
attributes : Object.assign(originalTags.attributes ?? {}, injectedTags.attributes ?? {})
};
const openingTag = /(<[^\s<>]+)[^\n<>]*(>.*)/s.exec(text); const openingTag = /(<[^\s<>]+)[^\n<>]*(>.*)/s.exec(text);
if(openingTag) { if(openingTag) {
return `${openingTag[1]}` + return `${openingTag[1]}` +
`${tags.classes ? ` class="${tags.classes}"` : ''}` + `${tags.classes ? ` class="${tags.classes}"` : ''}` +
`${tags.id ? ` id="${tags.id}"` : ''}` + `${tags.id ? ` id="${tags.id}"` : ''}` +
`${!_.isEmpty(tags.styles) ? ` style="${Object.entries(tags.styles).map(([key, value])=>`${key}:${value};`).join(' ')}"` : ''}` + `${tags.styles ? ` style="${tags.styles}"` : ''}` +
`${!_.isEmpty(tags.attributes) ? ` ${Object.entries(tags.attributes).map(([key, value])=>`${key}="${value}"`).join(' ')}` : ''}` + `${!_.isEmpty(tags.attributes) ? ` ${Object.entries(tags.attributes).map(([key, value])=>`${key}="${value}"`).join(' ')}` : ''}` +
`${openingTag[2]}`; // parse to turn child tokens into HTML `${openingTag[2]}`; // parse to turn child tokens into HTML
} }
@@ -361,43 +370,6 @@ const superSubScripts = {
} }
}; };
const justifiedParagraphClasses = [];
justifiedParagraphClasses[2] = 'Left';
justifiedParagraphClasses[4] = 'Right';
justifiedParagraphClasses[6] = 'Center';
const justifiedParagraphs = {
name : 'justifiedParagraphs',
level : 'block',
start(src) {
return src.match(/\n(?:-:|:-|-:) {1}/m)?.index;
}, // Hint to Marked.js to stop and check for a match
tokenizer(src, tokens) {
const regex = /^(((:-))|((-:))|((:-:))) .+(\n(([^\n].*\n)*(\n|$))|$)/ygm;
const match = regex.exec(src);
if(match?.length) {
let whichJustify;
if(match[2]?.length) whichJustify = 2;
if(match[4]?.length) whichJustify = 4;
if(match[6]?.length) whichJustify = 6;
return {
type : 'justifiedParagraphs', // Should match "name" above
raw : match[0], // Text to consume from the source
length : match[whichJustify].length,
text : match[0].slice(match[whichJustify].length),
class : justifiedParagraphClasses[whichJustify],
tokens : this.lexer.inlineTokens(match[0].slice(match[whichJustify].length + 1))
};
}
},
renderer(token) {
return `<p align="${token.class}">${this.parser.parseInline(token.tokens)}</p>`;
}
};
const forcedParagraphBreaks = { const forcedParagraphBreaks = {
name : 'hardBreaks', name : 'hardBreaks',
level : 'block', level : 'block',
@@ -419,27 +391,6 @@ const forcedParagraphBreaks = {
} }
}; };
const nonbreakingSpaces = {
name : 'nonbreakingSpaces',
level : 'inline',
start(src) { return src.match(/:>+/m)?.index; }, // Hint to Marked.js to stop and check for a match
tokenizer(src, tokens) {
const regex = /:(>+)/ym;
const match = regex.exec(src);
if(match?.length) {
return {
type : 'nonbreakingSpaces', // Should match "name" above
raw : match[0], // Text to consume from the source
length : match[1].length,
text : ''
};
}
},
renderer(token) {
return `&nbsp;`.repeat(token.length).concat('');
}
};
const definitionListsSingleLine = { const definitionListsSingleLine = {
name : 'definitionListsSingleLine', name : 'definitionListsSingleLine',
level : 'block', level : 'block',
@@ -708,7 +659,7 @@ function MarkedVariables() {
} }
if(match[8]) { // Inline Definition if(match[8]) { // Inline Definition
const label = match[10] ? match[10].trim().replace(/\s+/g, ' ') : null; // Trim edge spaces and shorten blocks of whitespace to 1 space const label = match[10] ? match[10].trim().replace(/\s+/g, ' ') : null; // Trim edge spaces and shorten blocks of whitespace to 1 space
let content = match[11] || null; let content = match[11] ? match[11].trim().replace(/\s+/g, ' ') : null; // Trim edge spaces and shorten blocks of whitespace to 1 space
// In case of nested (), find the correct matching end ) // In case of nested (), find the correct matching end )
let level = 0; let level = 0;
@@ -724,8 +675,10 @@ function MarkedVariables() {
break; break;
} }
} }
if(i > -1) {
combinedRegex.lastIndex = combinedRegex.lastIndex - (content.length - i); combinedRegex.lastIndex = combinedRegex.lastIndex - (content.length - i);
content = content.slice(0, i).trim().replace(/\s+/g, ' '); content = content.slice(0, i).trim().replace(/\s+/g, ' ');
}
varsQueue.push( varsQueue.push(
{ type : 'varDefBlock', { type : 'varDefBlock',
@@ -795,12 +748,11 @@ const tableTerminators = [
]; ];
Marked.use(MarkedVariables()); Marked.use(MarkedVariables());
Marked.use({ extensions : [justifiedParagraphs, definitionListsMultiLine, definitionListsSingleLine, forcedParagraphBreaks, Marked.use({ extensions : [definitionListsMultiLine, definitionListsSingleLine, forcedParagraphBreaks, superSubScripts,
nonbreakingSpaces, superSubScripts, mustacheSpans, mustacheDivs, mustacheInjectInline] }); mustacheSpans, mustacheDivs, mustacheInjectInline] });
Marked.use(mustacheInjectBlock); Marked.use(mustacheInjectBlock);
Marked.use({ renderer: renderer, tokenizer: tokenizer, mangle: false }); Marked.use({ renderer: renderer, tokenizer: tokenizer, mangle: false });
Marked.use(MarkedExtendedTables(tableTerminators), MarkedGFMHeadingId({ globalSlugs: true }), Marked.use(MarkedExtendedTables(tableTerminators), MarkedGFMHeadingId({ globalSlugs: true }), MarkedSmartypantsLite(), MarkedEmojis(MarkedEmojiOptions));
MarkedSmartypantsLite(), MarkedEmojis(MarkedEmojiOptions));
function cleanUrl(href) { function cleanUrl(href) {
try { try {
@@ -861,20 +813,15 @@ const processStyleTags = (string)=>{
const index = attr.indexOf('='); const index = attr.indexOf('=');
let [key, value] = [attr.substring(0, index), attr.substring(index + 1)]; let [key, value] = [attr.substring(0, index), attr.substring(index + 1)];
value = value.replace(/"/g, ''); value = value.replace(/"/g, '');
obj[key.trim()] = value.trim(); obj[key] = value;
return obj; return obj;
}, {}) || null; }, {}) || null;
const styles = tags?.length ? tags.reduce((styleObj, style) => { const styles = tags?.length ? tags.map((tag)=>tag.replace(/:"?([^"]*)"?/g, ':$1;').trim()).join(' ') : null;
const index = style.indexOf(':');
const [key, value] = [style.substring(0, index), style.substring(index + 1)];
styleObj[key.trim()] = value.replace(/"?([^"]*)"?/g, '$1').trim();
return styleObj;
}, {}) : null;
return { return {
id : id, id : id,
classes : classes, classes : classes,
styles : _.isEmpty(styles) ? null : styles, styles : styles,
attributes : _.isEmpty(attributes) ? null : attributes attributes : _.isEmpty(attributes) ? null : attributes
}; };
}; };
@@ -884,45 +831,30 @@ const extractHTMLStyleTags = (htmlString)=>{
const firstElementOnly = htmlString.split('>')[0]; const firstElementOnly = htmlString.split('>')[0];
const id = firstElementOnly.match(/id="([^"]*)"/)?.[1] || null; const id = firstElementOnly.match(/id="([^"]*)"/)?.[1] || null;
const classes = firstElementOnly.match(/class="([^"]*)"/)?.[1] || null; const classes = firstElementOnly.match(/class="([^"]*)"/)?.[1] || null;
const styles = firstElementOnly.match(/style="([^"]*)"/)?.[1] const styles = firstElementOnly.match(/style="([^"]*)"/)?.[1] || null;
?.split(';').reduce((styleObj, style) => {
if (style.trim() === '') return styleObj;
const index = style.indexOf(':');
const [key, value] = [style.substring(0, index), style.substring(index + 1)];
styleObj[key.trim()] = value.trim();
return styleObj;
}, {}) || null;
const attributes = firstElementOnly.match(/[a-zA-Z]+="[^"]*"/g) const attributes = firstElementOnly.match(/[a-zA-Z]+="[^"]*"/g)
?.filter((attr)=>!attr.startsWith('class="') && !attr.startsWith('style="') && !attr.startsWith('id="')) ?.filter((attr)=>!attr.startsWith('class="') && !attr.startsWith('style="') && !attr.startsWith('id="'))
.reduce((obj, attr)=>{ .reduce((obj, attr)=>{
const index = attr.indexOf('='); const index = attr.indexOf('=');
let [key, value] = [attr.substring(0, index), attr.substring(index + 1)]; let [key, value] = [attr.substring(0, index), attr.substring(index + 1)];
obj[key.trim()] = value.replace(/"/g, ''); value = value.replace(/"/g, '');
obj[key] = value;
return obj; return obj;
}, {}) || null; }, {}) || null;
return { return {
id : id, id : id,
classes : classes, classes : classes,
styles : _.isEmpty(styles) ? null : styles, styles : styles,
attributes : _.isEmpty(attributes) ? null : attributes attributes : _.isEmpty(attributes) ? null : attributes
}; };
}; };
const mergeHTMLTags = (originalTags, newTags) => {
return {
id : newTags.id || originalTags.id || null,
classes : [originalTags.classes, newTags.classes].join(' ').trim() || null,
styles : Object.assign(originalTags.styles ?? {}, newTags.styles ?? {}),
attributes : Object.assign(originalTags.attributes ?? {}, newTags.attributes ?? {})
};
};
const globalVarsList = {}; const globalVarsList = {};
let varsQueue = []; let varsQueue = [];
let globalPageNumber = 0; let globalPageNumber = 0;
const Markdown = { module.exports = {
marked : Marked, marked : Marked,
render : (rawBrewText, pageNumber=0)=>{ render : (rawBrewText, pageNumber=0)=>{
globalVarsList[pageNumber] = {}; //Reset global links for current page, to ensure values are parsed in order globalVarsList[pageNumber] = {}; //Reset global links for current page, to ensure values are parsed in order
@@ -933,7 +865,6 @@ const Markdown = {
} }
rawBrewText = rawBrewText.replace(/^\\column$/gm, `\n<div class='columnSplit'></div>\n`); rawBrewText = rawBrewText.replace(/^\\column$/gm, `\n<div class='columnSplit'></div>\n`);
const opts = Marked.defaults; const opts = Marked.defaults;
rawBrewText = opts.hooks.preprocess(rawBrewText); rawBrewText = opts.hooks.preprocess(rawBrewText);
@@ -1004,6 +935,3 @@ const Markdown = {
return errors; return errors;
}, },
}; };
export default Markdown;

View File

@@ -12,7 +12,9 @@ const Nav = {
displayName : 'Nav.base', displayName : 'Nav.base',
render : function(){ render : function(){
return <nav> return <nav>
<div className='navContent'>
{this.props.children} {this.props.children}
</div>
</nav>; </nav>;
} }
}), }),

View File

@@ -1,110 +1,200 @@
require('./splitPane.less'); require('./splitPane.less');
const React = require('react'); const React = require('react');
const { useState, useEffect } = React; const createClass = require('create-react-class');
const cx = require('classnames');
const storageKey = 'naturalcrit-pane-split'; const SplitPane = createClass({
displayName : 'SplitPane',
getDefaultProps : function() {
return {
storageKey : 'naturalcrit-pane-split',
onDragFinish : function(){}, //fires when dragging
showDividerButtons : true
};
},
const SplitPane = (props)=>{ getInitialState : function() {
const { return {
onDragFinish = ()=>{}, currentDividerPos : null,
showDividerButtons = true windowWidth : 0,
} = props; isDragging : false,
moveSource : false,
moveBrew : false,
showMoveArrows : true
};
},
const [isDragging, setIsDragging] = useState(false); pane1 : React.createRef(null),
const [dividerPos, setDividerPos] = useState(null); pane2 : React.createRef(null),
const [moveSource, setMoveSource] = useState(false);
const [moveBrew, setMoveBrew] = useState(false);
const [showMoveArrows, setShowMoveArrows] = useState(true);
const [liveScroll, setLiveScroll] = useState(false);
useEffect(()=>{ componentDidMount : function() {
const savedPos = window.localStorage.getItem(storageKey); const dividerPos = window.localStorage.getItem(this.props.storageKey);
setDividerPos(savedPos ? limitPosition(savedPos, 0.1 * (window.innerWidth - 13), 0.9 * (window.innerWidth - 13)) : window.innerWidth / 2); if(dividerPos){
setLiveScroll(window.localStorage.getItem('liveScroll') === 'true'); this.setState({
currentDividerPos : this.limitPosition(dividerPos, 0.1*(window.innerWidth-13), 0.9*(window.innerWidth-13)),
window.addEventListener('resize', handleResize); userSetDividerPos : dividerPos,
return ()=>window.removeEventListener('resize', handleResize); windowWidth : window.innerWidth
}, []); });
} else {
const limitPosition = (x, min = 1, max = window.innerWidth - 13)=>Math.round(Math.min(max, Math.max(min, x))); this.setState({
currentDividerPos : window.innerWidth / 2,
//when resizing, the divider should grow smaller if less space is given, then grow back if the space is restored, to the original position userSetDividerPos : window.innerWidth / 2
const handleResize = () =>setDividerPos(limitPosition(window.localStorage.getItem(storageKey), 0.1 * (window.innerWidth - 13), 0.9 * (window.innerWidth - 13))); });
const handleUp =(e)=>{
e.preventDefault();
if(isDragging) {
onDragFinish(dividerPos);
window.localStorage.setItem(storageKey, dividerPos);
} }
setIsDragging(false); window.addEventListener('resize', this.handleWindowResize);
};
const handleDown = (e)=>{ // This lives here instead of in the initial render because you cannot touch localStorage until the componant mounts.
const loadLiveScroll = window.localStorage.getItem('liveScroll') === 'true';
this.setState({ liveScroll: loadLiveScroll });
},
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(e){
e.preventDefault(); e.preventDefault();
setIsDragging(true); if(this.state.isDragging){
}; this.props.onDragFinish(this.state.currentDividerPos);
window.localStorage.setItem(this.props.storageKey, this.state.currentDividerPos);
}
this.setState({ isDragging: false });
},
const handleMove = (e)=>{ handleDown : function(e){
if(!isDragging) return;
e.preventDefault(); e.preventDefault();
setDividerPos(limitPosition(e.pageX)); this.setState({ isDragging: true });
}; //this.unFocus()
},
const liveScrollToggle = ()=>{ handleMove : function(e){
window.localStorage.setItem('liveScroll', String(!liveScroll)); if(!this.state.isDragging) return;
setLiveScroll(!liveScroll);
};
const renderMoveArrows = (showMoveArrows && e.preventDefault();
<> const newSize = this.limitPosition(e.pageX);
this.setState({
currentDividerPos : newSize,
userSetDividerPos : newSize
});
},
liveScrollToggle : function() {
window.localStorage.setItem('liveScroll', String(!this.state.liveScroll));
this.setState({ liveScroll: !this.state.liveScroll });
},
/*
unFocus : function() {
if(document.selection){
document.selection.empty();
}else{
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' <div className='arrow left'
onClick={()=>setMoveSource(!moveSource)} > style={{ left: this.state.currentDividerPos-4 }}
onClick={()=>this.setState({ moveSource: !this.state.moveSource })} >
<i className='fas fa-arrow-left' /> <i className='fas fa-arrow-left' />
</div> </div>
<div className='arrow right' <div className='arrow right'
onClick={()=>setMoveBrew(!moveBrew)} > style={{ left: this.state.currentDividerPos-4 }}
onClick={()=>this.setState({ moveBrew: !this.state.moveBrew })} >
<i className='fas fa-arrow-right' /> <i className='fas fa-arrow-right' />
</div> </div>
<div id='scrollToggleDiv' className={liveScroll ? 'arrow lock' : 'arrow unlock'} <div id='scrollToggleDiv' className={this.state.liveScroll ? 'arrow lock' : 'arrow unlock'}
onClick={liveScrollToggle} > style={{ left: this.state.currentDividerPos-4 }}
<i id='scrollToggle' className={liveScroll ? 'fas fa-lock' : 'fas fa-unlock'} /> onClick={this.liveScrollToggle} >
<i id='scrollToggle' className={this.state.liveScroll ? 'fas fa-lock' : 'fas fa-unlock'} />
</div> </div>
</> </>;
); }
},
const renderDivider = ( renderDivider : function(){
<div className={`divider ${isDragging && 'dragging'}`} onPointerDown={handleDown}> return <>
{showDividerButtons && renderMoveArrows} {this.props.showDividerButtons && this.renderMoveArrows()}
<div className='divider' onPointerDown={this.handleDown} >
<div className='dots'> <div className='dots'>
<i className='fas fa-circle' /> <i className='fas fa-circle' />
<i className='fas fa-circle' /> <i className='fas fa-circle' />
<i className='fas fa-circle' /> <i className='fas fa-circle' />
</div> </div>
</div> </div>
); </>;
},
return ( render : function(){
<div className='splitPane' onPointerMove={handleMove} onPointerUp={handleUp}> return <div className='splitPane' onPointerMove={this.handleMove} onPointerUp={this.handleUp}>
<Pane width={dividerPos} moveBrew={moveBrew} moveSource={moveSource} liveScroll={liveScroll} setMoveArrows={setShowMoveArrows}> <Pane
{props.children[0]} width={this.state.currentDividerPos}
>
{React.cloneElement(this.props.children[0], {
...(this.props.showDividerButtons && {
moveBrew : this.state.moveBrew,
moveSource : this.state.moveSource,
liveScroll : this.state.liveScroll,
setMoveArrows : this.setMoveArrows,
}),
})}
</Pane> </Pane>
{renderDivider} {this.renderDivider()}
<Pane isDragging={isDragging}>{props.children[1]}</Pane> <Pane isDragging={this.state.isDragging}>{this.props.children[1]}</Pane>
</div> </div>;
); }
}; });
const Pane = ({ width, children, isDragging, moveBrew, moveSource, liveScroll, setMoveArrows })=>{ const Pane = createClass({
const styles = width displayName : 'Pane',
? { flex: 'none', width: `${width}px` } getDefaultProps : function() {
: { pointerEvents: isDragging ? 'none' : 'auto' }; //Disable mouse capture in the right pane; else dragging into the iframe drops the divider return {
width : null
return (
<div className='pane' style={styles}>
{React.cloneElement(children, { moveBrew, moveSource, liveScroll, setMoveArrows })}
</div>
);
}; };
},
render : function(){
let styles = {};
if(this.props.width){
styles = {
flex : 'none',
width : `${this.props.width}px`
};
} else {
styles = {
pointerEvents : this.props.isDragging ? 'none' : 'auto' //Disable mouse capture in the rightmost pane; dragging into the iframe drops the divider otherwise
};
}
return <div className={cx('pane', this.props.className)} style={styles}>
{this.props.children}
</div>;
}
});
module.exports = SplitPane; module.exports = SplitPane;

View File

@@ -2,50 +2,49 @@
.splitPane{ .splitPane{
position : relative; position : relative;
display : flex; display : flex;
flex-direction : row;
height : 100%; height : 100%;
outline : none; outline : none;
flex-direction : row;
.pane{ .pane{
flex : 1;
overflow-x : hidden; overflow-x : hidden;
overflow-y : hidden; overflow-y : hidden;
flex : 1;
} }
.divider{ .divider{
position : relative;
display : table;
width : 15px;
height : 100%;
text-align : center;
touch-action : none; touch-action : none;
display : table;
height : 100%;
width : 15px;
cursor : ew-resize; cursor : ew-resize;
background-color : #BBBBBB; background-color : #bbb;
text-align : center;
.dots{ .dots{
display : table-cell; display : table-cell;
text-align : center;
vertical-align : middle; vertical-align : middle;
text-align : center;
i{ i{
display : block !important; display : block !important;
margin : 10px 0px; margin : 10px 0px;
font-size : 6px; font-size : 6px;
color : #666666; color : #666;
} }
} }
&:hover,&.dragging { background-color : #999999; } &:hover{
background-color: #999;
}
} }
.arrow{ .arrow{
position : absolute; position : absolute;
left : 50%;
z-index : 999;
width : 25px; width : 25px;
height : 25px; height : 25px;
font-size : 1.2em; border : 2px solid #bbb;
text-align : center;
cursor : pointer;
background-color : #DDDDDD;
border : 2px solid #BBBBBB;
border-radius : 15px; border-radius : 15px;
box-shadow : 0 4px 5px #0000007F; text-align : center;
translate : -50%; font-size : 1.2em;
cursor : pointer;
background-color : #ddd;
z-index : 999;
box-shadow : 0 4px 5px #0000007f;
&.left{ &.left{
.tooltipLeft('Jump to location in Editor'); .tooltipLeft('Jump to location in Editor');
top : 30px; top : 30px;
@@ -57,12 +56,14 @@
&.lock{ &.lock{
.tooltipRight('De-sync Editor and Preview locations.'); .tooltipRight('De-sync Editor and Preview locations.');
top : 90px; top : 90px;
background : #666666; background: #666;
} }
&.unlock{ &.unlock{
.tooltipRight('Sync Editor and Preview locations'); .tooltipRight('Sync Editor and Preview locations');
top : 90px; top : 90px;
} }
&:hover { background-color : #666666; } &:hover{
background-color: #666;
}
} }
} }

View File

@@ -21,7 +21,10 @@ html,body, #reactRoot{
*{ *{
box-sizing : border-box; box-sizing : border-box;
} }
.colorButton(@backgroundColor : @green){ button{
.button();
}
.button(@backgroundColor : @green){
.animate(background-color); .animate(background-color);
display : inline-block; display : inline-block;
padding : 0.6em 1.2em; padding : 0.6em 1.2em;
@@ -43,6 +46,5 @@ html,body, #reactRoot{
} }
&:disabled{ &:disabled{
background-color : @silver !important; background-color : @silver !important;
cursor:not-allowed;
} }
} }

View File

@@ -1,4 +1,4 @@
:where(html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,button,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video){ :where(html,body,div,span,applet,object,iframe,h1,h2,h3,h4,h5,h6,p,blockquote,pre,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,table,caption,tbody,tfoot,thead,tr,th,td,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video){
border:0;font-size:100%;font:inherit;vertical-align:baseline;margin:0;padding:0 border:0;font-size:100%;font:inherit;vertical-align:baseline;margin:0;padding:0
} }
@@ -25,9 +25,3 @@
:where(table){ :where(table){
border-collapse:collapse;border-spacing:0 border-collapse:collapse;border-spacing:0
} }
:where(button) {
background-color: unset;
text-transform: unset;
color: unset;
}

View File

@@ -1,5 +1,5 @@
import stylelint from 'stylelint'; const stylelint = require('stylelint');
import { isNumber } from 'stylelint/lib/utils/validateTypes.mjs'; const { isNumber } = require('stylelint/lib/utils/validateTypes.cjs');
const { report, ruleMessages, validateOptions } = stylelint.utils; const { report, ruleMessages, validateOptions } = stylelint.utils;
const ruleName = 'naturalcrit/declaration-block-multi-line-min-declarations'; const ruleName = 'naturalcrit/declaration-block-multi-line-min-declarations';
@@ -7,8 +7,9 @@ const messages = ruleMessages(ruleName, {
expected : (decls)=>`Rule with ${decls} declaration${decls == 1 ? '' : 's'} should be single line`, expected : (decls)=>`Rule with ${decls} declaration${decls == 1 ? '' : 's'} should be single line`,
}); });
const ruleFunction = (primaryOption, secondaryOptionObject, context)=>{
return (postcssRoot, postcssResult)=>{ module.exports = stylelint.createPlugin(ruleName, function getPlugin(primaryOption, secondaryOptionObject, context) {
return function lint(postcssRoot, postcssResult) {
const validOptions = validateOptions( const validOptions = validateOptions(
postcssResult, postcssResult,
@@ -19,23 +20,26 @@ const ruleFunction = (primaryOption, secondaryOptionObject, context)=>{
} }
); );
if(!validOptions) //If the options are invalid, don't lint if(!validOptions) { //If the options are invalid, don't lint
return; return;
}
const isAutoFixing = Boolean(context.fix); const isAutoFixing = Boolean(context.fix);
postcssRoot.walkRules((rule)=>{ //Iterate CSS rules postcssRoot.walkRules((rule)=>{ //Iterate CSS rules
//Apply rule only if all children are decls (no further nested rules) //Apply rule only if all children are decls (no further nested rules)
if(rule.nodes.length > primaryOption || !rule.nodes.every((node)=>node.type === 'decl')) if(rule.nodes.length > primaryOption || !rule.nodes.every((node)=>node.type === 'decl')) {
return; return;
}
//Ignore if already one line //Ignore if already one line
if(!rule.nodes.some((node)=>node.raws.before.includes('\n')) && !rule.raws.after.includes('\n')) if(!rule.nodes.some((node)=>node.raws.before.includes('\n')) && !rule.raws.after.includes('\n'))
return; return;
if(isAutoFixing) { //We are in “fix” mode if(isAutoFixing) { //We are in “fix” mode
rule.each((decl)=>decl.raws.before = ' '); rule.each((decl)=>{
decl.raws.before = ' ';
});
rule.raws.after = ' '; rule.raws.after = ' ';
} else { } else {
report({ report({
@@ -48,9 +52,7 @@ const ruleFunction = (primaryOption, secondaryOptionObject, context)=>{
} }
}); });
}; };
}; });
ruleFunction.ruleName = ruleName; module.exports.ruleName = ruleName;
ruleFunction.messages = messages; module.exports.messages = messages;
export default stylelint.createPlugin(ruleName, ruleFunction);

View File

@@ -1,28 +1,31 @@
import stylelint from 'stylelint'; const stylelint = require('stylelint');
const { report, ruleMessages, validateOptions } = stylelint.utils;
const { report, ruleMessages, validateOptions } = stylelint.utils;
const ruleName = 'naturalcrit/declaration-colon-align'; const ruleName = 'naturalcrit/declaration-colon-align';
const messages = ruleMessages(ruleName, { const messages = ruleMessages(ruleName, {
expected : (rule)=>`Expected colons aligned within rule "${rule}"`, expected : (rule)=>`Expected colons aligned within rule "${rule}"`,
}); });
const ruleFunction = (primaryOption, secondaryOptionObject, context)=>{
return (postcssRoot, postcssResult)=>{ module.exports = stylelint.createPlugin(ruleName, function getPlugin(primaryOption, secondaryOptionObject, context) {
return function lint(postcssRoot, postcssResult) {
const validOptions = validateOptions( const validOptions = validateOptions(
postcssResult, postcssResult,
ruleName, ruleName,
{ {
actual : primaryOption, actual : primaryOption,
possible : [true, false] possible : [
true,
false
]
} }
); );
if(!validOptions) // If the options are invalid, don't lint if(!validOptions) { //If the options are invalid, don't lint
return; return;
}
const isAutoFixing = Boolean(context.fix); const isAutoFixing = Boolean(context.fix);
postcssRoot.walkRules((rule)=>{ //Iterate CSS rules postcssRoot.walkRules((rule)=>{ //Iterate CSS rules
let maxColonPos = 0; let maxColonPos = 0;
@@ -33,16 +36,13 @@ const ruleFunction = (primaryOption, secondaryOptionObject, context)=>{
return; return;
const colonPos = declaration.prop.length + declaration.raws.between.indexOf(':'); const colonPos = declaration.prop.length + declaration.raws.between.indexOf(':');
if(maxColonPos > 0 && colonPos != maxColonPos) {
if(maxColonPos > 0 && colonPos != maxColonPos)
misaligned = true; misaligned = true;
}
maxColonPos = Math.max(maxColonPos, colonPos); maxColonPos = Math.max(maxColonPos, colonPos);
}); });
if(!misaligned) if(misaligned) {
return;
if(isAutoFixing) { //We are in “fix” mode if(isAutoFixing) { //We are in “fix” mode
rule.each((declaration)=>{ rule.each((declaration)=>{
if(declaration.type != 'decl') if(declaration.type != 'decl')
@@ -59,11 +59,10 @@ const ruleFunction = (primaryOption, secondaryOptionObject, context)=>{
word : rule.selector, // Which exact word caused the error? This positions the error properly word : rule.selector, // Which exact word caused the error? This positions the error properly
}); });
} }
}
}); });
}; };
}; });
ruleFunction.ruleName = ruleName; module.exports.ruleName = ruleName;
ruleFunction.messages = messages; module.exports.messages = messages;
export default stylelint.createPlugin(ruleName, ruleFunction);

View File

@@ -1,5 +1,5 @@
import stylelint from 'stylelint'; const stylelint = require('stylelint');
import { isNumber } from 'stylelint/lib/utils/validateTypes.mjs'; const { isNumber } = require('stylelint/lib/utils/validateTypes.cjs');
const { report, ruleMessages, validateOptions } = stylelint.utils; const { report, ruleMessages, validateOptions } = stylelint.utils;
const ruleName = 'naturalcrit/declaration-colon-min-space-before'; const ruleName = 'naturalcrit/declaration-colon-min-space-before';
@@ -7,8 +7,9 @@ const messages = ruleMessages(ruleName, {
expected : (num)=>`Expected at least ${num} space${num == 1 ? '' : 's'} before ":"` expected : (num)=>`Expected at least ${num} space${num == 1 ? '' : 's'} before ":"`
}); });
const ruleFunction = (primaryOption, secondaryOptionObject, context)=>{
return (postcssRoot, postcssResult)=>{ module.exports = stylelint.createPlugin(ruleName, function getPlugin(primaryOption, secondaryOptionObject, context) {
return function lint(postcssRoot, postcssResult) {
const validOptions = validateOptions( const validOptions = validateOptions(
postcssResult, postcssResult,
@@ -29,9 +30,9 @@ const ruleFunction = (primaryOption, secondaryOptionObject, context)=>{
const between = decl.raws.between; const between = decl.raws.between;
const colonIndex = between.indexOf(':'); const colonIndex = between.indexOf(':');
if(between.slice(0, colonIndex).length >= primaryOption) if(between.slice(0, colonIndex).length >= primaryOption) {
return; return;
}
if(isAutoFixing) { //We are in “fix” mode if(isAutoFixing) { //We are in “fix” mode
decl.raws.between = between.slice(0, colonIndex).replace(/\s*$/, ' '.repeat(primaryOption)) + between.slice(colonIndex); decl.raws.between = between.slice(0, colonIndex).replace(/\s*$/, ' '.repeat(primaryOption)) + between.slice(colonIndex);
} else { } else {
@@ -45,9 +46,7 @@ const ruleFunction = (primaryOption, secondaryOptionObject, context)=>{
} }
}); });
}; };
}; });
ruleFunction.ruleName = ruleName; module.exports.ruleName = ruleName;
ruleFunction.messages = messages; module.exports.messages = messages;
export default stylelint.createPlugin(ruleName, ruleFunction);

View File

@@ -1,50 +0,0 @@
require('jsdom-global')();
import { safeHTML } from '../../client/homebrew/brewRenderer/safeHTML';
test('Javascript via href', function() {
const source = `<a href="javascript:alert('This is a JavaScript injection via href attribute')">Click me</a>`;
const rendered = safeHTML(source);
expect(rendered).toBe('<a>Click me</a>');
});
test('Javascript via src', function() {
const source = `<img src="javascript:alert('This is a JavaScript injection via src attribute')">`;
const rendered = safeHTML(source);
expect(rendered).toBe('<img>');
});
test('Javascript via form submit action', function() {
const source = `<form action="javascript:alert('This is a JavaScript injection via action attribute')">\n<input type="submit" value="Submit">\n</form>`;
const rendered = safeHTML(source);
expect(rendered).toBe('<form>\n<input value=\"Submit\">\n</form>');
});
test('Javascript via inline event handler - onClick', function() {
const source = `<div style="background-color: red; color: white; width: 100px; height: 100px;" onclick="alert('This is a JavaScript injection via inline event handler')">\nClick me\n</div>`;
const rendered = safeHTML(source);
expect(rendered).toBe('<div style=\"background-color: red; color: white; width: 100px; height: 100px;\">\nClick me\n</div>');
});
test('Javascript via inline event handler - onMouseOver', function() {
const source = `<div onmouseover="alert('This is a JavaScript injection via inline event handler')">Hover over me</div>`;
const rendered = safeHTML(source);
expect(rendered).toBe('<div>Hover over me</div>');
});
test('Javascript via data attribute', function() {
const source = `<div data-code="javascript:alert('This is a JavaScript injection via data attribute')">Test</div>`;
const rendered = safeHTML(source);
expect(rendered).toBe('<div>Test</div>');
});
test('Javascript via event delegation', function() {
const source = `<div id="parent"><button id="child">Click me</button></div><script>document.getElementById('parent').addEventListener('click', function(event) {if (event.target.id === 'child') {console.log('This is JavaScript executed via event delegation');}});</script>`;
const rendered = safeHTML(source);
expect(rendered).toBe('<div id="parent"><button id="child">Click me</button></div>');
});

View File

@@ -1,6 +1,6 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
import Markdown from 'naturalcrit/markdown.js'; const Markdown = require('naturalcrit/markdown.js');
test('Processes the markdown within an HTML block if its just a class wrapper', function() { test('Processes the markdown within an HTML block if its just a class wrapper', function() {
const source = '<div>*Bold text*</div>'; const source = '<div>*Bold text*</div>';

View File

@@ -1,6 +1,6 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
import Markdown from 'naturalcrit/markdown.js'; const Markdown = require('naturalcrit/markdown.js');
describe('Inline Definition Lists', ()=>{ describe('Inline Definition Lists', ()=>{
test('No Term 1 Definition', function() { test('No Term 1 Definition', function() {

View File

@@ -1,4 +1,4 @@
import Markdown from 'naturalcrit/markdown.js'; const Markdown = require('naturalcrit/markdown.js');
const dedent = require('dedent-tabs').default; const dedent = require('dedent-tabs').default;
// Marked.js adds line returns after closing tags on some default tokens. // Marked.js adds line returns after closing tags on some default tokens.

View File

@@ -1,6 +1,6 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
import Markdown from 'naturalcrit/markdown.js'; const Markdown = require('naturalcrit/markdown.js');
describe('Hard Breaks', ()=>{ describe('Hard Breaks', ()=>{
test('Single Break', function() { test('Single Break', function() {

Some files were not shown because too many files have changed in this diff Show More