Merge branch 'master' of https://github.com/naturalcrit/homebrewery into search-by-tags

This commit is contained in:
Víctor Losada Hernández
2026-02-09 15:11:43 +01:00
262 changed files with 28191 additions and 14203 deletions
+15 -6
View File
@@ -10,7 +10,7 @@ orbs:
jobs: jobs:
build: build:
docker: docker:
- image: cimg/node:20.8.0 - image: cimg/node:20.18.0
- image: mongo:4.4 - image: mongo:4.4
working_directory: ~/homebrewery working_directory: ~/homebrewery
@@ -27,7 +27,7 @@ jobs:
# fallback to using the latest cache if no exact match is found # fallback to using the latest cache if no exact match is found
- v1-dependencies- - v1-dependencies-
- run: sudo npm install -g npm@10.2.0 - run: sudo npm install -g npm@10.8.2
- node/install-packages: - node/install-packages:
app-dir: ~/homebrewery app-dir: ~/homebrewery
cache-path: node_modules cache-path: node_modules
@@ -45,7 +45,7 @@ jobs:
test: test:
docker: docker:
- image: cimg/node:20.8.0 - image: cimg/node:20.17.0
working_directory: ~/homebrewery working_directory: ~/homebrewery
parallelism: 1 parallelism: 1
@@ -64,21 +64,30 @@ jobs:
- run: - run:
name: Test - Mustache Spans name: Test - Mustache Spans
command: npm run test:mustache-syntax command: npm run test:mustache-syntax
- run:
name: Test - Definition Lists
command: npm run test:definition-lists
- 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: - 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:
+9
View File
@@ -5,6 +5,15 @@ updates:
schedule: schedule:
interval: daily interval: daily
open-pull-requests-limit: 99 open-pull-requests-limit: 99
groups:
dev-dependencies:
dependency-type: "development"
patterns: ["*"]
update-types: ["patch", "minor"]
prod-dependencies:
dependency-type: "production"
patterns: ["*"]
update-types: ["patch", "minor"]
ignore: ignore:
- dependency-name: eslint - dependency-name: eslint
versions: versions:
+13 -12
View File
@@ -1,26 +1,29 @@
<!-- > [!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
_Please replace this line with instructions on how to test or view your changes, as well as any before/after _Replace this line with instructions on how to test or view your changes, as well as any before/after
images for UI changes._ screenshots or recordings for UI changes._
### Reviewer Checklist ### Reviewer Checklist
_Please replace the list below with specific features you want reviewers to look at._ _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
@@ -32,5 +35,3 @@ _Please replace the list below with specific features you want reviewers to look
- [ ] 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>
+46 -46
View File
@@ -1,48 +1,48 @@
{ {
"extends": [ "extends": [
"stylelint-config-recess-order", "stylelint-config-recess-order",
"stylelint-config-recommended"], "stylelint-config-recommended"],
"plugins": [ "plugins": [
"@stylistic/stylelint-plugin", "@stylistic/stylelint-plugin",
"./stylelint_plugins/declaration-colon-align.js", "./stylelint_plugins/declaration-colon-align.js",
"./stylelint_plugins/declaration-colon-min-space-before", "./stylelint_plugins/declaration-colon-min-space-before",
"./stylelint_plugins/declaration-block-multi-line-min-declarations" "./stylelint_plugins/declaration-block-multi-line-min-declarations"
], ],
"customSyntax": "postcss-less", "customSyntax": "postcss-less",
"rules": { "rules": {
"no-descending-specificity" : null, "no-descending-specificity" : null,
"at-rule-no-unknown" : null, "at-rule-no-unknown" : null,
"function-no-unknown" : null, "function-no-unknown" : null,
"font-family-no-missing-generic-family-keyword" : null, "font-family-no-missing-generic-family-keyword" : null,
"font-weight-notation" : "named-where-possible", "font-weight-notation" : "named-where-possible",
"font-family-name-quotes" : "always-unless-keyword", "font-family-name-quotes" : "always-unless-keyword",
"@stylistic/indentation" : "tab", "@stylistic/indentation" : "tab",
"no-duplicate-selectors" : true, "no-duplicate-selectors" : true,
"@stylistic/color-hex-case" : "upper", "@stylistic/color-hex-case" : "upper",
"color-hex-length" : "long", "color-hex-length" : "long",
"@stylistic/selector-combinator-space-after" : "always", "@stylistic/selector-combinator-space-after" : "always",
"@stylistic/selector-combinator-space-before" : "always", "@stylistic/selector-combinator-space-before" : "always",
"@stylistic/selector-attribute-operator-space-before" : "never", "@stylistic/selector-attribute-operator-space-before" : "never",
"@stylistic/selector-attribute-operator-space-after" : "never", "@stylistic/selector-attribute-operator-space-after" : "never",
"@stylistic/selector-attribute-brackets-space-inside" : "never", "@stylistic/selector-attribute-brackets-space-inside" : "never",
"selector-attribute-quotes" : "always", "selector-attribute-quotes" : "always",
"selector-pseudo-element-colon-notation" : "double", "selector-pseudo-element-colon-notation" : "double",
"@stylistic/selector-pseudo-class-parentheses-space-inside" : "never", "@stylistic/selector-pseudo-class-parentheses-space-inside" : "never",
"@stylistic/block-opening-brace-space-before" : "always", "@stylistic/block-opening-brace-space-before" : "always",
"naturalcrit/declaration-colon-min-space-before" : 1, "naturalcrit/declaration-colon-min-space-before" : 1,
"@stylistic/declaration-block-trailing-semicolon" : "always", "@stylistic/declaration-block-trailing-semicolon" : "always",
"@stylistic/declaration-colon-space-after" : "always", "@stylistic/declaration-colon-space-after" : "always",
"@stylistic/number-leading-zero" : "always", "@stylistic/number-leading-zero" : "always",
"function-url-quotes" : ["always", { "except": ["empty"] }], "function-url-quotes" : ["always", { "except": ["empty"] }],
"function-url-scheme-disallowed-list" : ["data","http"], "function-url-scheme-disallowed-list" : ["data","http"],
"comment-whitespace-inside" : "always", "comment-whitespace-inside" : "always",
"@stylistic/string-quotes" : "single", "@stylistic/string-quotes" : "single",
"@stylistic/media-feature-range-operator-space-before" : "always", "@stylistic/media-feature-range-operator-space-before" : "always",
"@stylistic/media-feature-range-operator-space-after" : "always", "@stylistic/media-feature-range-operator-space-after" : "always",
"@stylistic/media-feature-parentheses-space-inside" : "never", "@stylistic/media-feature-parentheses-space-inside" : "never",
"@stylistic/media-feature-colon-space-before" : "always", "@stylistic/media-feature-colon-space-before" : "always",
"@stylistic/media-feature-colon-space-after" : "always", "@stylistic/media-feature-colon-space-after" : "always",
"naturalcrit/declaration-colon-align" : true, "naturalcrit/declaration-colon-align" : true,
"naturalcrit/declaration-block-multi-line-min-declarations": 1 "naturalcrit/declaration-block-multi-line-min-declarations" : 1
} }
} }
+4 -1
View File
@@ -1,4 +1,4 @@
FROM node:20-alpine FROM node:22-alpine
RUN apk --no-cache add git RUN apk --no-cache add git
ENV NODE_ENV=docker ENV NODE_ENV=docker
@@ -9,7 +9,10 @@ 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
+126 -8
View File
@@ -1,12 +1,130 @@
# Running Homebrewery via Docker # Offline Install Instructions: Docker
The repo includes a Dockerfile and a docker-compose.yml file. These instructions are for setting up a persistent instance of the Homebrewery application locally using Docker.
To run the application via docker-compose.yml: 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.
`docker-compose up -d`
To stop the application: # Install Docker
`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,
"mongodb_uri": "mongodb://172.17.0.2/homebrewery",
}
```
```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
```
**NOTE:** If you are running from the Windows command line, this will not work as `$(pwd)` is not valid syntax. Use this command instead:
```shell
# Make sure you run this in the homebrewery directory
docker run --name homebrewery-app -d --restart unless-stopped -e NODE_ENV=docker -v %cd%/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
```
**NOTE:** If you are running from the Windows command line, this will not work as `$(pwd)` is not valid syntax. Use this command instead:
```shell
# Make sure you run this in the homebrewery directory
docker run --name homebrewery-app -d --restart unless-stopped -e NODE_ENV=docker -v %cd%/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`
+5 -2
View File
@@ -75,8 +75,9 @@ it using the two commands:
1. `npm install` 1. `npm install`
1. `npm start` 1. `npm start`
You should now be able to go to [http://localhost:8000](http://localhost:8000) When the Homebrewery server is started for the first time, it will modify the database to create the indexes required for better Homebrewery performance. This may take a few moments to complete for each index, dependent on how much content is in your local database - a brand new, empty database should be done in seconds.
in your browser and use The Homebrewery offline.
On completion, you should be able to go to [http://localhost:8000](http://localhost:8000) in your browser and use The Homebrewery offline.
If you had any issue at all, here are some links that may be useful: If you had any issue at all, here are some links that may be useful:
- [Course](https://learn.mongodb.com/courses/m103-basic-cluster-administration) on cluster administration, useful for beginners - [Course](https://learn.mongodb.com/courses/m103-basic-cluster-administration) on cluster administration, useful for beginners
@@ -144,3 +145,5 @@ your contribution to the project, please join our [gitter chat][gitter-url].
[github-mark-duplicate-url]: https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/about-duplicate-issues-and-pull-requests [github-mark-duplicate-url]: https://docs.github.com/en/free-pro-team@latest/github/managing-your-work-on-github/about-duplicate-issues-and-pull-requests
[github-pr-docs-url]: https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request [github-pr-docs-url]: https://docs.github.com/en/free-pro-team@latest/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request
[gitter-url]: https://gitter.im/naturalcrit/Lobby [gitter-url]: https://gitter.im/naturalcrit/Lobby
+10
View File
@@ -0,0 +1,10 @@
{
"presets": [
"@babel/preset-env",
"@babel/preset-react"
],
"plugins": [
"@babel/plugin-transform-runtime",
"babel-plugin-transform-import-meta"
]
}
+2361 -1934
View File
File diff suppressed because it is too large Load Diff
+40 -26
View File
@@ -1,38 +1,52 @@
require('./admin.less'); import './admin.less';
const React = require('react'); import React, { useEffect, useState } from 'react';
const createClass = require('create-react-class'); import BrewUtils from './brewUtils/brewUtils.jsx';
import NotificationUtils from './notificationUtils/notificationUtils.jsx';
import AuthorUtils from './authorUtils/authorUtils.jsx';
import LockTools from './lockTools/lockTools.jsx';
const tabGroups = ['brew', 'notifications', 'authors', 'locks'];
const BrewCleanup = require('./brewCleanup/brewCleanup.jsx'); const ADMIN_TAB = 'HB_adminPage_currentTab';
const BrewLookup = require('./brewLookup/brewLookup.jsx');
const BrewCompress = require ('./brewCompress/brewCompress.jsx');
const Stats = require('./stats/stats.jsx');
const Admin = createClass({ const Admin = ()=>{
getDefaultProps : function() { const [currentTab, setCurrentTab] = useState('');
return {};
},
render : function(){ useEffect(()=>{
return <div className='admin'> setCurrentTab(localStorage.getItem(ADMIN_TAB) || 'brew');
}, []);
useEffect(()=>{
localStorage.setItem(ADMIN_TAB, currentTab);
}, [currentTab]);
return (
<div className='admin'>
<header> <header>
<div className='container'> <div className='container'>
<i className='fas fa-rocket' /> <i className='fas fa-rocket' />
homebrewery admin The Homebrewery Admin Page
<a href='/'>back to homepage</a>
</div> </div>
</header> </header>
<div className='container'> <main className='container'>
<Stats /> <nav className='tabs'>
<hr /> {tabGroups.map((tab, idx)=>(
<BrewLookup /> <button
<hr /> className={tab === currentTab ? 'active' : ''}
<BrewCleanup /> key={idx}
<hr /> onClick={()=>setCurrentTab(tab)}>
<BrewCompress /> {tab.toUpperCase()}
</div> </button>
</div>; ))}
} </nav>
}); {currentTab === 'brew' && <BrewUtils />}
{currentTab === 'notifications' && <NotificationUtils />}
{currentTab === 'authors' && <AuthorUtils />}
{currentTab === 'locks' && <LockTools />}
</main>
</div>
);
};
module.exports = Admin; module.exports = Admin;
+117 -23
View File
@@ -3,42 +3,136 @@
@import 'naturalcrit/styles/animations.less'; @import 'naturalcrit/styles/animations.less';
@import 'naturalcrit/styles/colors.less'; @import 'naturalcrit/styles/colors.less';
@import 'naturalcrit/styles/tooltip.less'; @import 'naturalcrit/styles/tooltip.less';
@import './themes/fonts/iconFonts/fontAwesome.less';
@import 'font-awesome/css/font-awesome.css'; @import 'font-awesome/css/font-awesome.css';
html,body, #reactContainer, .naturalCrit{ html,body, #reactContainer, .naturalCrit { min-height : 100%; }
min-height : 100%;
}
@sidebarWidth : 250px; @sidebarWidth : 250px;
body{ body {
background-color : #eee; height : 100%;
font-family : 'Open Sans', sans-serif;
color : #4b5055;
font-weight : 100;
text-rendering : optimizeLegibility;
margin : 0;
padding : 0; padding : 0;
height : 100%; margin : 0;
font-family : 'Open Sans', sans-serif;
font-weight : 100;
color : #4B5055;
background-color : #EEEEEE;
text-rendering : optimizeLegibility;
} }
.admin{ :where(.admin) {
padding-bottom : 50px;
header{ header {
padding : 20px 0px;
margin-bottom : 30px;
font-size : 2em;
color : white;
background-color : @red; background-color : @red;
font-size: 2em; i { margin-right : 30px; }
padding : 20px 0px; a { float : right; }
color : white; }
margin-bottom: 30px;
i{ hr { margin : 30px 0px; }
margin-right: 30px;
:where(.container) {
input {
height : 33px;
padding : 0px 10px;
margin-bottom : 20px;
font-family : monospace;
}
button {
height : 37px;
vertical-align : middle;
}
dl {
display : grid;
grid-template-columns : 120px 1fr;
row-gap : 10px;
align-items : center;
justify-items : start;
padding-top : 0.5em;
dt {
float : left;
clear : left;
height : fit-content;
font-weight : 900;
text-align : right;
&::after { content : ' : '; }
}
dd { height : fit-content; }
}
.tabs button {
margin-right : 3px;
margin-left : 3px;
color : black;
background-color : #EEEEEE;
border : 1px solid #444444;
border-radius : 5px;
&:hover {
color : #EEEEEE;
background-color : #444444;
}
&.active {
margin-right : 2px;
margin-left : 2px;
text-decoration : underline;
background-color : #CCCCCC;
border : 2px solid #444444;
}
}
.notificationUtils {
display : flex;
gap : 50px;
justify-content : space-between;
} }
} }
hr{ table {
margin : 30px 0px; padding : 10px;
tr {
border-bottom : 1px solid;
&:last-of-type { border : none; }
&:nth-child(even) { background : #DDDDDD; }
}
thead {
background : rgb(193,236,230);
border-bottom : 2px solid;
}
th, td {
padding : 5px 10px;
vertical-align : middle;
text-align : center;
border-right : 1px solid;
&:last-child { border-right : none; }
}
th { font-weight : 900; }
td {
&:first-child {
font-weight : 900;
text-align : left;
}
}
} }
.error {
float : right;
padding : 10px;
margin-block : 10px;
font-weight : 900;
color : white;
background : rgb(178, 54, 54);
}
} }
@@ -0,0 +1,87 @@
import './authorLookup.less';
import React from 'react';
import request from 'superagent';
const authorLookup = ()=>{
const [author, setAuthor] = React.useState('');
const [searching, setSearching] = React.useState(false);
const [results, setResults] = React.useState([]);
const lookup = async ()=>{
if(!author) return;
setSearching(true);
setResults([]);
const brews = await request.get(`/admin/user/list/${author}`);
setResults(brews.body);
setSearching(false);
};
const renderResults = ()=>{
if(results.length == 0) return <>
<h2>Results</h2>
<p>None found.</p>
</>;
return <>
<h2>{`Results - ${results.length} brews` }</h2>
<table className='resultsTable'>
<thead>
<tr>
<th>Title</th>
<th>Share</th>
<th>Edit</th>
<th>Last Update</th>
<th>Storage</th>
</tr>
</thead>
<tbody>
{results
.sort((a, b)=>{ // Sort brews from most recently updated
if(a.updatedAt > b.updatedAt) return -1;
return 1;
})
.map((brew, idx)=>{
return <tr key={idx}>
<td><strong>{brew.title}</strong></td>
<td><a href={`/share/${brew.shareId}`}>{brew.shareId}</a></td>
<td>{brew.editId}</td>
<td style={{ width: '200px' }}>{brew.updatedAt}</td>
<td>{brew.googleId ? 'Google' : 'Homebrewery'}</td>
</tr>;
})}
</tbody>
</table>
</>;
};
const handleKeyPress = (evt)=>{
if(evt.key === 'Enter') return lookup();
};
const handleChange = (evt)=>{
setAuthor(evt.target.value);
};
return (
<div className='authorLookup'>
<div className='authorLookupInputs'>
<h2>Author Lookup</h2>
<label className='field'>
Author Name:
<input className='fieldInput' value={author} onKeyDown={handleKeyPress} onChange={handleChange} />
<button onClick={lookup}>
<i className={`fas ${searching ? 'fa-spin fa-spinner' : 'fa-search'}`} />
</button>
</label>
</div>
<div className='authorLookupResults'>
{renderResults()}
</div>
</div>
);
};
export default authorLookup;
@@ -0,0 +1,29 @@
.authorLookup {
position : relative;
display : flex;
flex-direction : column;
.field {
display : flex;
gap : 5px;
align-items : center;
justify-items : stretch;
width : 100%;
margin-bottom : 20px;
input {
height : 33px;
padding : 0px 10px;
margin-bottom : unset;
font-family : monospace;
}
button {
width : 50px;
i { margin-right : 10px; }
}
}
}
+13
View File
@@ -0,0 +1,13 @@
import React from 'react';
import AuthorLookup from './authorLookup/authorLookup.jsx';
const authorUtils = ()=>{
return (
<section className='authorUtils'>
<AuthorLookup />
</section>
);
};
export default authorUtils;
-10
View File
@@ -1,10 +0,0 @@
.BrewCleanup{
.removeBox{
margin-top: 20px;
button{
background-color: @red;
margin-right: 10px;
}
}
}
@@ -1,10 +0,0 @@
.BrewCompress{
.removeBox{
margin-top: 20px;
button{
background-color: @red;
margin-right: 10px;
}
}
}
-82
View File
@@ -1,82 +0,0 @@
require('./brewLookup.less');
const React = require('react');
const createClass = require('create-react-class');
const cx = require('classnames');
const request = require('superagent');
const Moment = require('moment');
const BrewLookup = createClass({
getDefaultProps() {
return {};
},
getInitialState() {
return {
query : '',
foundBrew : null,
searching : false,
error : null
};
},
handleChange(e){
this.setState({ query: e.target.value });
},
lookup(){
this.setState({ searching: true, error: null });
request.get(`/admin/lookup/${this.state.query}`)
.then((res)=>this.setState({ foundBrew: res.body }))
.catch((err)=>this.setState({ error: err }))
.finally(()=>this.setState({ searching: false }));
},
renderFoundBrew(){
const brew = this.state.foundBrew;
return <div className='foundBrew'>
<dl>
<dt>Title</dt>
<dd>{brew.title}</dd>
<dt>Authors</dt>
<dd>{brew.authors.join(', ')}</dd>
<dt>Edit Link</dt>
<dd><a href={`/edit/${brew.editId}`} target='_blank' rel='noopener noreferrer'>/edit/{brew.editId}</a></dd>
<dt>Share Link</dt>
<dd><a href={`/share/${brew.shareId}`} target='_blank' rel='noopener noreferrer'>/share/{brew.shareId}</a></dd>
<dt>Last Updated</dt>
<dd>{Moment(brew.updatedAt).fromNow()}</dd>
<dt>Num of Views</dt>
<dd>{brew.views}</dd>
</dl>
</div>;
},
render(){
return <div className='brewLookup'>
<h2>Brew Lookup</h2>
<input type='text' value={this.state.query} onChange={this.handleChange} placeholder='edit or share id' />
<button onClick={this.lookup}>
<i className={cx('fas', {
'fa-search' : !this.state.searching,
'fa-spin fa-spinner' : this.state.searching,
})} />
</button>
{this.state.error
&& <div className='error'>{this.state.error.toString()}</div>
}
{this.state.foundBrew
? this.renderFoundBrew()
: <div className='noBrew'>No brew found.</div>
}
</div>;
}
});
module.exports = BrewLookup;
-30
View File
@@ -1,30 +0,0 @@
.brewLookup{
input{
height : 33px;
margin-bottom : 20px;
padding : 0px 10px;
font-family : monospace;
}
button{
vertical-align : middle;
height : 37px;
}
dl{
@maxItemWidth : 132px;
dt{
float : left;
clear : left;
width : @maxItemWidth;
text-align : right;
&::after {
content: " : ";
}
}
dd{
height : 1em;
margin-left : @maxItemWidth + 6px;
padding : 0 0 0.5em 0;
}
}
}
@@ -1,11 +1,8 @@
require('./brewCleanup.less'); import React from 'react';
const React = require('react'); import createReactClass from 'create-react-class';
const createClass = require('create-react-class'); import request from 'superagent';
const request = require('superagent'); const BrewCleanup = createReactClass({
const BrewCleanup = createClass({
displayName : 'BrewCleanup', displayName : 'BrewCleanup',
getDefaultProps(){ getDefaultProps(){
return {}; return {};
@@ -39,9 +36,9 @@ const BrewCleanup = createClass({
if(!this.state.primed) return; if(!this.state.primed) return;
if(!this.state.count){ if(!this.state.count){
return <div className='removeBox'>No Matching Brews found.</div>; return <div className='result noBrews'>No Matching Brews found.</div>;
} }
return <div className='removeBox'> return <div className='result'>
<button onClick={this.cleanup} className='remove'> <button onClick={this.cleanup} className='remove'>
{this.state.pending {this.state.pending
? <i className='fas fa-spin fa-spinner' /> ? <i className='fas fa-spin fa-spinner' />
@@ -52,7 +49,7 @@ const BrewCleanup = createClass({
</div>; </div>;
}, },
render(){ render(){
return <div className='BrewCleanup'> return <div className='brewUtil brewCleanup'>
<h2> Brew Cleanup </h2> <h2> Brew Cleanup </h2>
<p>Removes very short brews to tidy up the database</p> <p>Removes very short brews to tidy up the database</p>
@@ -65,10 +62,10 @@ const BrewCleanup = createClass({
{this.renderPrimed()} {this.renderPrimed()}
{this.state.error {this.state.error
&& <div className='error'>{this.state.error.toString()}</div> && <div className='error noBrews'>{this.state.error.toString()}</div>
} }
</div>; </div>;
} }
}); });
module.exports = BrewCleanup; export default BrewCleanup;
@@ -1,11 +1,8 @@
require('./brewCompress.less'); import React from 'react';
const React = require('react'); import createReactClass from 'create-react-class';
const createClass = require('create-react-class'); import request from 'superagent';
const request = require('superagent'); const BrewCompress = createReactClass({
const BrewCompress = createClass({
displayName : 'BrewCompress', displayName : 'BrewCompress',
getDefaultProps(){ getDefaultProps(){
return {}; return {};
@@ -53,9 +50,9 @@ const BrewCompress = createClass({
if(!this.state.primed) return; if(!this.state.primed) return;
if(!this.state.count){ if(!this.state.count){
return <div className='removeBox'>No Matching Brews found.</div>; return <div className='result noBrews'>No Matching Brews found.</div>;
} }
return <div className='removeBox'> return <div className='result'>
<button onClick={this.cleanup} className='remove'> <button onClick={this.cleanup} className='remove'>
{this.state.pending {this.state.pending
? <i className='fas fa-spin fa-spinner' /> ? <i className='fas fa-spin fa-spinner' />
@@ -69,7 +66,7 @@ const BrewCompress = createClass({
</div>; </div>;
}, },
render(){ render(){
return <div className='BrewCompress'> return <div className='brewUtil brewCompress'>
<h2> Brew Compression </h2> <h2> Brew Compression </h2>
<p>Compresses the text in brews to binary</p> <p>Compresses the text in brews to binary</p>
@@ -88,4 +85,4 @@ const BrewCompress = createClass({
} }
}); });
module.exports = BrewCompress; export default BrewCompress;
@@ -0,0 +1,112 @@
import React from 'react';
import createReactClass from 'create-react-class';
import request from 'superagent';
import cx from 'classnames';
import Moment from 'moment';
const BrewLookup = createReactClass({
getDefaultProps() {
return {};
},
getInitialState() {
return {
query : '',
foundBrew : null,
searching : false,
error : null,
scriptCount : 0
};
},
handleChange(e){
this.setState({ query: e.target.value });
},
lookup(){
this.setState({ searching: true, error: null, scriptCount: 0 });
request.get(`/admin/lookup/${this.state.query}`)
.then((res)=>{
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 }))
.finally(()=>{
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(){
const brew = this.state.foundBrew;
return <div className='result'>
<dl>
<dt>Title</dt>
<dd>{brew.title}</dd>
<dt>Authors</dt>
<dd>{brew.authors.join(', ')}</dd>
<dt>Edit Link</dt>
<dd><a href={`/edit/${brew.editId}`} target='_blank' rel='noopener noreferrer'>/edit/{brew.editId}</a></dd>
<dt>Share Link</dt>
<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>
<dd>{Moment(brew.updatedAt).fromNow()}</dd>
<dt>Num of Views</dt>
<dd>{brew.views}</dd>
<dt>SCRIPT tags detected</dt>
<dd>{this.state.scriptCount}</dd>
</dl>
{this.state.scriptCount > 0 &&
<div className='cleanButton'>
<button onClick={this.cleanScript}>CLEAN BREW</button>
</div>
}
</div>;
},
render(){
return <div className='brewUtil brewLookup'>
<h2>Brew Lookup</h2>
<input type='text' value={this.state.query} onChange={this.handleChange} placeholder='edit or share id' />
<button onClick={this.lookup}>
<i className={cx('fas', {
'fa-search' : !this.state.searching,
'fa-spin fa-spinner' : this.state.searching,
})} />
</button>
{this.state.error
&& <div className='error'>{this.state.error.toString()}</div>
}
{this.state.foundBrew
? this.renderFoundBrew()
: <div className='result noBrew'>No brew found.</div>
}
</div>;
}
});
export default BrewLookup;
+22
View File
@@ -0,0 +1,22 @@
import React from 'react';
import './brewUtils.less';
import BrewCleanup from './brewCleanup/brewCleanup.jsx';
import BrewLookup from './brewLookup/brewLookup.jsx';
import BrewCompress from './brewCompress/brewCompress.jsx';
import Stats from './stats/stats.jsx';
const BrewUtils = ()=>{
return (
<>
<Stats />
<hr />
<BrewLookup />
<hr />
<BrewCleanup />
<hr />
<BrewCompress />
</>
);
};
export default BrewUtils;
+29
View File
@@ -0,0 +1,29 @@
.brewUtil {
.result {
margin-top : 20px;
button {
margin-right : 10px;
background-color : @red;
}
}
.cleanButton {
display : inline-block;
width : 100%;
}
}
.stats {
position : relative;
.pending {
position : absolute;
top : 0.5em;
left : 100px;
width : 100%;
height : 100%;
}
&:has(.pending) { opacity : 0.5; }
dl { grid-template-columns : 200px 250px; }
}
@@ -1,12 +1,8 @@
require('./stats.less'); import React from 'react';
const React = require('react'); import createReactClass from 'create-react-class';
const createClass = require('create-react-class'); import request from 'superagent';
const cx = require('classnames');
const request = require('superagent'); const Stats = createReactClass({
const Stats = createClass({
displayName : 'Stats', displayName : 'Stats',
getDefaultProps(){ getDefaultProps(){
return {}; return {};
@@ -14,7 +10,8 @@ const Stats = createClass({
getInitialState(){ getInitialState(){
return { return {
stats : { stats : {
totalBrews : 0 totalBrews : 0,
totalPublishedBrews : 0
}, },
fetching : false fetching : false
}; };
@@ -29,11 +26,13 @@ const Stats = createClass({
.finally(()=>this.setState({ fetching: false })); .finally(()=>this.setState({ fetching: false }));
}, },
render(){ render(){
return <div className='Stats'> return <div className='brewUtil stats'>
<h2> Stats </h2> <h2> Stats </h2>
<dl> <dl>
<dt>Total Brew Count</dt> <dt>Total Brew Count</dt>
<dd>{this.state.stats.totalBrews}</dd> <dd>{this.state.stats.totalBrews}</dd>
<dt>Total Brews Published</dt>
<dd>{this.state.stats.totalPublishedBrews}</dd>
</dl> </dl>
{this.state.fetching {this.state.fetching
@@ -43,4 +42,4 @@ const Stats = createClass({
} }
}); });
module.exports = Stats; export default Stats;
+342
View File
@@ -0,0 +1,342 @@
/*eslint max-lines: ["warn", {"max": 500, "skipBlankLines": true, "skipComments": true}]*/
import './lockTools.less';
import React from 'react';
import createReactClass from 'create-react-class';
import request from '../../homebrew/utils/request-middleware.js';
const LockTools = createReactClass({
displayName : 'LockTools',
getInitialState : function() {
return {
fetching : false,
reviewCount : 0
};
},
componentDidMount : function() {
this.updateReviewCount();
},
updateReviewCount : async function() {
const newCount = await request.get('/api/lock/count')
.then((res)=>{return res.body?.count || 'Unknown';});
if(newCount != this.state.reviewCount){
this.setState({
reviewCount : newCount
});
}
},
updateLockData : function(lock){
this.setState({
lock : lock
});
},
render : function() {
return <div className='lockTools'>
<h2>Lock Count</h2>
<p>Number of brews currently locked: {this.state.reviewCount}</p>
<button onClick={this.updateReviewCount}>REFRESH</button>
<hr />
<LockTable title='Locked Brews' text='Total Locked Brews' resultName='lockedDocuments' fetchURL='/api/locks' propertyNames={['shareId', 'title']} loadBrew={this.updateLockData} ></LockTable>
<hr />
<LockTable title='Brews Awaiting Review' text='Total Reviews Waiting' resultName='reviewDocuments' fetchURL='/api/lock/reviews' propertyNames={['shareId', 'title']} loadBrew={this.updateLockData} ></LockTable>
<hr />
<LockBrew key={this.state.lock?.key || 0} lock={this.state.lock}></LockBrew>
<hr />
<div style={{ columns: 2 }}>
<LockLookup title='Unlock Brew' fetchURL='/api/unlock' updateFn={this.updateReviewCount}></LockLookup>
<LockLookup title='Clear Review Request' fetchURL='/api/lock/review/remove'></LockLookup>
</div>
<hr />
</div>;
}
});
const LockBrew = createReactClass({
displayName : 'LockBrew',
getInitialState : function() {
// Default values
return {
brewId : this.props.lock?.shareId || '',
code : this.props.lock?.code || 455,
editMessage : this.props.lock?.editMessage || '',
shareMessage : this.props.lock?.shareMessage || 'This Brew has been locked.',
result : {},
overwrite : false,
};
},
handleChange : function(e, varName) {
const output = {};
output[varName] = e.target.value;
this.setState(output);
},
submit : function(e){
e.preventDefault();
if(!this.state.editMessage) return;
const newLock = {
overwrite : this.state.overwrite,
code : parseInt(this.state.code) || 100,
editMessage : this.state.editMessage,
shareMessage : this.state.shareMessage,
applied : new Date
};
request.post(`/api/lock/${this.state.brewId}`)
.send(newLock)
.set('Content-Type', 'application/json')
.then((response)=>{
this.setState({ result: response.body });
})
.catch((err)=>{
this.setState({ result: err.response.body });
});
},
renderInput : function (name) {
return <input type='text' name={name} value={this.state[name]} onChange={(e)=>this.handleChange(e, name)} autoComplete='off' required/>;
},
renderResult : function(){
return <>
<h3>Result:</h3>
<table>
<tbody>
{Object.keys(this.state.result).map((key, idx)=>{
return <tr key={`${idx}-row`}>
<td key={`${idx}-key`}>{key}</td>
<td key={`${idx}-value`}>{this.state.result[key].toString()}
</td>
</tr>;
})}
</tbody>
</table>
</>;
},
render : function() {
return <div className='lockBrew'>
<div className='lockForm'>
<h2>Lock Brew</h2>
<form onSubmit={this.submit}>
<label>
ID:
{this.renderInput('brewId')}
</label>
<br />
<label>
Error Code:
{this.renderInput('code')}
</label>
<br />
<label>
Private Message:
{this.renderInput('editMessage')}
</label>
<br />
<label>
Public Message:
{this.renderInput('shareMessage')}
</label>
<br />
<label className='checkbox'>
Overwrite
<input name='overwrite' className='checkbox' type='checkbox' value={this.state.overwrite} onClick={()=>{return this.setState((prevState)=>{return { overwrite: !prevState.overwrite };});}} />
</label>
<label>
<input type='submit' />
</label>
</form>
{this.state.result && this.renderResult()}
</div>
<div className='lockSuggestions'>
<h2>Suggestions</h2>
<div className='lockCodes'>
<h3>Codes</h3>
<ul>
<li>455 - Generic Lock</li>
<li>456 - Copyright issues</li>
<li>457 - Confidential Information Leakage</li>
<li>458 - Sensitive Personal Information</li>
<li>459 - Defamation or Libel</li>
<li>460 - Hate Speech or Discrimination</li>
<li>461 - Illegal Activities</li>
<li>462 - Malware or Phishing</li>
<li>463 - Plagiarism</li>
<li>465 - Misrepresentation</li>
<li>466 - Inappropriate Content</li>
</ul>
</div>
<div className='lockMessages'>
<h3>Messages</h3>
<ul>
<li><b>Private Message:</b> This is the private message that is ONLY displayed to the authors of the locked brew. This message MUST specify exactly what actions must be taken in order to have the brew unlocked.</li>
<li><b>Public Message:</b> This is the public message that is displayed to the EVERYONE that attempts to view the locked brew.</li>
</ul>
</div>
</div>
</div>;
}
});
const LockTable = createReactClass({
displayName : 'LockTable',
getDefaultProps : function() {
return {
title : '',
text : '',
fetchURL : '/api/locks',
resultName : '',
propertyNames : ['shareId'],
loadBrew : ()=>{}
};
},
getInitialState : function() {
return {
result : '',
error : '',
searching : false
};
},
lockKey : React.createRef(0),
clickFn : function (){
this.setState({ searching: true, error: null });
request.get(this.props.fetchURL)
.then((res)=>this.setState({ result: res.body }))
.catch((err)=>this.setState({ result: err.response.body }))
.finally(()=>{
this.setState({ searching: false });
});
},
updateBrewLockData : function (lockData){
this.lockKey.current++;
const brewData = {
key : this.lockKey.current,
shareId : lockData.shareId,
code : lockData.lock.code,
editMessage : lockData.lock.editMessage,
shareMessage : lockData.lock.shareMessage
};
this.props.loadBrew(brewData);
},
render : function () {
return <>
<div className='brewsAwaitingReview'>
<div className='brewBlock'>
<h2>{this.props.title}</h2>
<button onClick={this.clickFn}>
REFRESH
<i className={`fas ${!this.state.searching ? 'fa-search' : 'fa-spin fa-spinner'}`} />
</button>
</div>
{this.state.result[this.props.resultName] &&
<>
<p>{this.props.text}: {this.state.result[this.props.resultName].length}</p>
<table className='lockTable'>
<thead>
<tr>
{this.props.propertyNames.map((name, idx)=>{
return <th key={idx}>{name}</th>;
})}
<th>clip</th>
<th>load</th>
</tr>
</thead>
<tbody>
{this.state.result[this.props.resultName].map((result, resultIdx)=>{
return <tr className='row' key={`${resultIdx}-row`}>
{this.props.propertyNames.map((name, nameIdx)=>{
return <td key={`${resultIdx}-${nameIdx}`}>
{result[name].toString()}
</td>;
})}
<td className='icon' title='Copy ID to Clipboard' onClick={()=>{navigator.clipboard.writeText(result.shareId.toString());}}><i className='fa-regular fa-clipboard'></i></td>
<td className='icon' title='View Lock details' onClick={()=>{this.updateBrewLockData(result);}}><i className='fa-regular fa-circle-down'></i></td>
</tr>;
})}
</tbody>
</table>
</>
}
</div>
</>;
}
});
const LockLookup = createReactClass({
displayName : 'LockLookup',
getDefaultProps : function() {
return {
fetchURL : '/api/lookup'
};
},
getInitialState : function() {
return {
query : '',
result : '',
error : '',
searching : false
};
},
handleChange(e){
this.setState({ query: e.target.value });
},
clickFn(){
this.setState({ searching: true, error: null });
request.put(`${this.props.fetchURL}/${this.state.query}`)
.then((res)=>this.setState({ result: res.body }))
.catch((err)=>this.setState({ result: err.response.body }))
.finally(()=>{
this.setState({ searching: false });
});
},
renderResult : function(){
return <div className='lockLookup'>
<h3>Result:</h3>
<table>
<tbody>
{Object.keys(this.state.result).map((key, idx)=>{
return <tr key={`${idx}-row`}>
<td key={`${idx}-key`}>{key}</td>
<td key={`${idx}-value`}>{this.state.result[key].toString()}
</td>
</tr>;
})}
</tbody>
</table>
</div>;
},
render : function() {
return <div className='brewLookup'>
<h2>{this.props.title}</h2>
<input type='text' value={this.state.query} onChange={this.handleChange} placeholder='share id' />
<button onClick={this.clickFn}>
<i className={`fas ${!this.state.searching ? 'fa-search' : 'fa-spin fa-spinner'}`} />
</button>
{this.state.error
&& <div className='error'>{this.state.error.toString()}</div>
}
{this.state.result && this.renderResult()}
</div>;
}
});
export default LockTools;
+66
View File
@@ -0,0 +1,66 @@
.lockTools {
.lockBrew {
columns : 2;
.lockForm {
break-inside : avoid;
label {
display : inline-block;
width : 100%;
line-height : 2.25em;
text-align : right;
input {
float : right;
width : 65%;
margin-left : 10px;
}
&.checkbox {
line-height: 1.5em;
input {
width : 1.5em;
height : 1.5em;
}
}
}
}
.lockSuggestions {
line-height : 1.2em;
break-inside : avoid;
columns : 2;
h2 { column-span : all; }
h3 { margin-top : 0px; }
b { font-weight : 600; }
.lockCodes { break-inside : avoid; }
}
}
.lockTable {
cursor : default;
break-inside : avoid;
.row:hover {
color : #000000;
background-color : #CCCCCC;
}
.icon {
cursor : pointer;
&:hover { text-shadow : 0px 0px 6px black; }
}
}
th, td {
padding : 4px 10px;
text-align : center;
}
table, td { border : 1px solid #333333; }
.brewLookup {
min-height : 175px;
break-inside : avoid;
h2 { margin-top : 0px; }
}
button i { padding-left : 5px; }
}
@@ -0,0 +1,108 @@
import './notificationAdd.less';
import React, { useState, useRef } from 'react';
import request from 'superagent';
const NotificationAdd = ()=>{
const [notificationResult, setNotificationResult] = useState(null);
const [searching, setSearching] = useState(false);
const [error, setError] = useState(null);
const dismissKeyRef = useRef(null);
const titleRef = useRef(null);
const textRef = useRef(null);
const startAtRef = useRef(null);
const stopAtRef = useRef(null);
const saveNotification = async ()=>{
const dismissKey = dismissKeyRef.current.value;
const title = titleRef.current.value;
const text = textRef.current.value;
const startAt = new Date(startAtRef.current.value);
const stopAt = new Date(stopAtRef.current.value);
// Basic validation
if(!dismissKey || !title || !text || isNaN(startAt.getTime()) || isNaN(stopAt.getTime())) {
setError('All fields are required');
return;
}
if(startAt >= stopAt) {
setError('End date must be after the start date!');
return;
}
const data = {
dismissKey,
title,
text,
startAt : startAt?.toISOString() ?? '',
stopAt : stopAt?.toISOString() ?? '',
};
try {
setSearching(true);
setError(null);
const response = await request.post('/admin/notification/add').send(data);
console.log(response.body);
// Reset form fields
dismissKeyRef.current.value = '';
titleRef.current.value = '';
textRef.current.value = '';
setNotificationResult('Notification successfully created.');
setSearching(false);
} catch (err) {
console.log(err.response.body.message);
setError(`Error saving notification: ${err.response.body.message}`);
setSearching(false);
}
};
return (
<div className='notificationAdd'>
<h2>Add Notification</h2>
<label className='field'>
Dismiss Key:
<input className='fieldInput' type='text' ref={dismissKeyRef} required
placeholder='dismiss_notif_drive'
/>
</label>
<label className='field'>
Title:
<input className='fieldInput' type='text' ref={titleRef} required
placeholder='Stop using Google Drive as image host'
/>
</label>
<label className='field'>
Text:
<textarea className='fieldInput' type='text' ref={textRef} required
placeholder='Google Drive is not an image hosting site, you should not use it as such.'
>
</textarea>
</label>
<label className='field'>
Start Date:
<input type='date' className='fieldInput' ref={startAtRef} required/>
</label>
<label className='field'>
End Date:
<input type='date' className='fieldInput' ref={stopAtRef} required/>
</label>
<div className='notificationResult'>{notificationResult}</div>
<button className='notificationSave' onClick={saveNotification} disabled={searching}>
<i className={`fas ${searching ? 'fa-spin fa-spinner' : 'fa-save'}`}/>
Save Notification
</button>
{error && <div className='error'>{error}</div>}
</div>
);
};
export default NotificationAdd;
@@ -0,0 +1,38 @@
.notificationAdd {
position : relative;
display : flex;
flex-direction : column;
width : 500px;
.field {
display : grid;
grid-template-columns : 120px 200px;
align-items : center;
justify-items : stretch;
width : 100%;
margin-bottom : 20px;
input {
height : 33px;
padding : 0px 10px;
margin-bottom : unset;
font-family : monospace;
&[type='date'] { width : 14ch; }
}
textarea {
width : 50ch;
min-height : 7em;
max-height : 20em;
padding : 10px;
resize : vertical;
}
}
button {
width : 200px;
i { margin-right : 10px; }
}
}
@@ -0,0 +1,103 @@
import './notificationLookup.less';
import React, { useState } from 'react';
import request from 'superagent';
import Moment from 'moment';
const NotificationDetail = ({ notification, onDelete })=>(
<>
<dl>
<dt>Key</dt>
<dd>{notification.dismissKey}</dd>
<dt>Title</dt>
<dd>{notification.title || 'No Title'}</dd>
<dt>Created</dt>
<dd>{Moment(notification.createdAt).format('LLLL')}</dd>
<dt>Start</dt>
<dd>{Moment(notification.startAt).format('LLLL') || 'No Start Time'}</dd>
<dt>Stop</dt>
<dd>{Moment(notification.stopAt).format('LLLL') || 'No End Time'}</dd>
<dt>Text</dt>
<dd>{notification.text || 'No Text'}</dd>
</dl>
<button onClick={()=>onDelete(notification.dismissKey)}>DELETE</button>
</>
);
const NotificationLookup = ()=>{
const [searching, setSearching] = useState(false);
const [error, setError] = useState(null);
const [notifications, setNotifications] = useState([]);
const lookupAll = async ()=>{
setSearching(true);
setError(null);
try {
const res = await request.get('/admin/notification/all');
setNotifications(res.body || []);
} catch (err) {
console.log(err);
setError(`Error looking up notifications: ${err.response.body.message}`);
} finally {
setSearching(false);
}
};
const deleteNotification = async (dismissKey)=>{
if(!dismissKey) return;
const confirmed = window.confirm(
`Really delete notification ${dismissKey}?`
);
if(!confirmed) {
console.log('Delete notification cancelled');
return;
}
console.log('Delete notification confirm');
try {
await request.delete(`/admin/notification/delete/${dismissKey}`);
lookupAll();
} catch (err) {
console.log(err);
setError(`Error deleting notification: ${err.response.body.message}`);
};
};
const renderNotificationsList = ()=>{
if(error)
return <div className='error'>{error}</div>;
if(notifications.length === 0)
return <div className='noNotification'>No notifications available.</div>;
return (
<ul className='notificationList'>
{notifications.map((notification)=>(
<li key={notification.dismissKey} >
<details>
<summary>{notification.title || 'No Title'}</summary>
<NotificationDetail notification={notification} onDelete={deleteNotification} />
</details>
</li>
))}
</ul>
);
};
return (
<div className='notificationLookup'>
<h2>Check all Notifications</h2>
<button onClick={lookupAll}>
<i className={`fas ${searching ? 'fa-spin fa-spinner' : 'fa-search'}`} />
</button>
{renderNotificationsList()}
</div>
);
};
export default NotificationLookup;
@@ -0,0 +1,35 @@
.notificationLookup {
width : 450px;
height : fit-content;
.noNotification { margin-block : 20px; }
.notificationList {
display : flex;
flex-direction : column;
max-height : 500px;
margin-block : 20px;
overflow : auto;
border : 1px solid;
border-radius : 5px;
li {
padding : 10px;
background : #CCCCCC;
&:nth-child(even) { background : #DDDDDD; }
&:first-child {
border-top-left-radius : 5px;
border-top-right-radius : 5px;
}
&:last-child {
border-bottom-right-radius : 5px;
border-bottom-left-radius : 5px;
}
summary {
font-size : 20px;
font-weight : 900;
}
}
}
}
@@ -0,0 +1,14 @@
import React from 'react';
import NotificationLookup from './notificationLookup/notificationLookup.jsx';
import NotificationAdd from './notificationAdd/notificationAdd.jsx';
const NotificationUtils = ()=>{
return (
<section className='notificationUtils'>
<NotificationAdd />
<NotificationLookup />
</section>
);
};
export default NotificationUtils;
-28
View File
@@ -1,28 +0,0 @@
.Stats{
position : relative;
.pending{
position : absolute;
top : 0px;
left : 0px;
height : 100%;
width : 100%;
background-color : rgba(238,238,238, 0.5);
}
dl{
@maxItemWidth : 132px;
dt{
float : left;
clear : left;
width : @maxItemWidth;
text-align : right;
&::after {
content: " : ";
}
}
dd{
margin : 0 0 0 @maxItemWidth + 10px;
padding : 0 0 0.5em 0;
}
}
}
+96
View File
@@ -0,0 +1,96 @@
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 };
+11
View File
@@ -0,0 +1,11 @@
.anchored-box {
position : absolute;
visibility : hidden;
justify-self : anchor-center;
@supports (inset-block-start: anchor(bottom)) {
inset-block-start : anchor(bottom);
}
&.active { visibility : visible; }
}
@@ -1,7 +1,7 @@
const diceFont = require('../../../themes/fonts/iconFonts/diceFont.js'); import diceFont from 'themes/fonts/iconFonts/diceFont.js';
const elderberryInn = require('../../../themes/fonts/iconFonts/elderberryInn.js'); import elderberryInn from 'themes/fonts/iconFonts/elderberryInn.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'); import gameIcons from 'themes/fonts/iconFonts/gameIcons.js';
const emojis = { const emojis = {
...diceFont, ...diceFont,
@@ -79,6 +79,6 @@ const showAutocompleteEmoji = function(CodeMirror, editor) {
}); });
}; };
module.exports = { export default {
showAutocompleteEmoji showAutocompleteEmoji
}; };
@@ -38,11 +38,11 @@ const autoCloseCurlyBraces = function(CodeMirror, cm, typingClosingBrace) {
} }
}; };
module.exports = { export default {
autoCloseCurlyBraces : function(CodeMirror, codeMirror) { autoCloseCurlyBraces : function(CodeMirror, codeMirror) {
const map = { name: 'autoCloseCurlyBraces' }; const map = { name: 'autoCloseCurlyBraces' };
map[`'{'`] = function(cm) { return autoCloseCurlyBraces(CodeMirror, cm); }; map[`'{'`] = function(cm) { return autoCloseCurlyBraces(CodeMirror, cm); };
map[`'}'`] = function(cm) { return autoCloseCurlyBraces(CodeMirror, cm, true); }; map[`'}'`] = function(cm) { return autoCloseCurlyBraces(CodeMirror, cm, true); };
codeMirror.addKeyMap(map); codeMirror?.addKeyMap(map);
} }
}; };
@@ -1,51 +1,13 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
require('./codeEditor.less'); import './codeEditor.less';
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const _ = require('lodash'); import _ from 'lodash';
const closeTag = require('./close-tag'); import closeTag from './close-tag';
const autoCompleteEmoji = require('./autocompleteEmoji'); import autoCompleteEmoji from './autocompleteEmoji';
let CodeMirror; let CodeMirror;
if(typeof window !== 'undefined'){
CodeMirror = require('codemirror');
//Language Modes const CodeEditor = createReactClass({
require('codemirror/mode/gfm/gfm.js'); //Github flavoured markdown
require('codemirror/mode/css/css.js');
require('codemirror/mode/javascript/javascript.js');
//Addons
//Code folding
require('codemirror/addon/fold/foldcode.js');
require('codemirror/addon/fold/foldgutter.js');
//Search and replace
require('codemirror/addon/search/search.js');
require('codemirror/addon/search/searchcursor.js');
require('codemirror/addon/search/jump-to-line.js');
require('codemirror/addon/search/match-highlighter.js');
require('codemirror/addon/search/matchesonscrollbar.js');
require('codemirror/addon/dialog/dialog.js');
//Trailing space highlighting
// require('codemirror/addon/edit/trailingspace.js');
//Active line highlighting
// require('codemirror/addon/selection/active-line.js');
//Scroll past last line
require('codemirror/addon/scroll/scrollpastend.js');
//Auto-closing
//XML code folding is a requirement of the auto-closing tag feature and is not enabled
require('codemirror/addon/fold/xml-fold.js');
require('codemirror/addon/edit/closetag.js');
//Autocompletion
require('codemirror/addon/hint/show-hint.js');
const foldPagesCode = require('./fold-pages');
foldPagesCode.registerHomebreweryHelper(CodeMirror);
const foldCSSCode = require('./fold-css');
foldCSSCode.registerHomebreweryHelper(CodeMirror);
}
const CodeEditor = createClass({
displayName : 'CodeEditor', displayName : 'CodeEditor',
getDefaultProps : function() { getDefaultProps : function() {
return { return {
@@ -66,23 +28,54 @@ const CodeEditor = createClass({
editor : React.createRef(null), editor : React.createRef(null),
componentDidMount : function() { async componentDidMount() {
CodeMirror = (await import('codemirror')).default;
this.CodeMirror = CodeMirror;
await import('codemirror/mode/gfm/gfm.js');
await import('codemirror/mode/css/css.js');
await import('codemirror/mode/javascript/javascript.js');
// addons
await import('codemirror/addon/fold/foldcode.js');
await import('codemirror/addon/fold/foldgutter.js');
await import('codemirror/addon/fold/xml-fold.js');
await import('codemirror/addon/search/search.js');
await import('codemirror/addon/search/searchcursor.js');
await import('codemirror/addon/search/jump-to-line.js');
await import('codemirror/addon/search/match-highlighter.js');
await import('codemirror/addon/search/matchesonscrollbar.js');
await import('codemirror/addon/dialog/dialog.js');
await import('codemirror/addon/scroll/scrollpastend.js');
await import('codemirror/addon/edit/closetag.js');
await import('codemirror/addon/hint/show-hint.js');
// import 'codemirror/addon/selection/active-line.js';
// import 'codemirror/addon/edit/trailingspace.js';
// register helpers dynamically as well
const foldPagesCode = (await import('./fold-pages')).default;
const foldCSSCode = (await import('./fold-css')).default;
foldPagesCode.registerHomebreweryHelper(CodeMirror);
foldCSSCode.registerHomebreweryHelper(CodeMirror);
this.buildEditor(); this.buildEditor();
const newDoc = CodeMirror.Doc(this.props.value, this.props.language); const newDoc = CodeMirror?.Doc(this.props.value, this.props.language);
this.codeMirror.swapDoc(newDoc); this.codeMirror?.swapDoc(newDoc);
}, },
componentDidUpdate : function(prevProps) { componentDidUpdate : function(prevProps) {
if(prevProps.view !== this.props.view){ //view changed; swap documents if(prevProps.view !== this.props.view){ //view changed; swap documents
let newDoc; let newDoc;
if(!this.state.docs[this.props.view]) { if(!this.state.docs[this.props.view]) {
newDoc = CodeMirror.Doc(this.props.value, this.props.language); newDoc = CodeMirror?.Doc(this.props.value, this.props.language);
} else { } else {
newDoc = this.state.docs[this.props.view]; newDoc = this.state.docs[this.props.view];
} }
const oldDoc = { [prevProps.view]: this.codeMirror.swapDoc(newDoc) }; const oldDoc = { [prevProps.view]: this.codeMirror?.swapDoc(newDoc) };
this.setState((prevState)=>({ this.setState((prevState)=>({
docs : _.merge({}, prevState.docs, oldDoc) docs : _.merge({}, prevState.docs, oldDoc)
@@ -90,17 +83,17 @@ const CodeEditor = createClass({
this.props.rerenderParent(); this.props.rerenderParent();
} else if(this.codeMirror?.getValue() != this.props.value) { //update editor contents if brew.text is changed from outside } else if(this.codeMirror?.getValue() != this.props.value) { //update editor contents if brew.text is changed from outside
this.codeMirror.setValue(this.props.value); this.codeMirror?.setValue(this.props.value);
} }
if(this.props.enableFolding) { if(this.props.enableFolding) {
this.codeMirror.setOption('foldOptions', this.foldOptions(this.codeMirror)); this.codeMirror?.setOption('foldOptions', this.foldOptions(this.codeMirror));
} else { } else {
this.codeMirror.setOption('foldOptions', false); this.codeMirror?.setOption('foldOptions', false);
} }
if(prevProps.editorTheme !== this.props.editorTheme){ if(prevProps.editorTheme !== this.props.editorTheme){
this.codeMirror.setOption('theme', this.props.editorTheme); this.codeMirror?.setOption('theme', this.props.editorTheme);
} }
}, },
@@ -188,8 +181,8 @@ const CodeEditor = createClass({
closeTag.autoCloseCurlyBraces(CodeMirror, this.codeMirror); closeTag.autoCloseCurlyBraces(CodeMirror, this.codeMirror);
autoCompleteEmoji.showAutocompleteEmoji(CodeMirror, this.codeMirror); autoCompleteEmoji.showAutocompleteEmoji(CodeMirror, this.codeMirror);
// Note: codeMirror passes a copy of itself in this callback. cm === this.codeMirror. Either one works. // Note: codeMirror passes a copy of itself in this callback. cm === this.codeMirror?. Either one works.
this.codeMirror.on('change', (cm)=>{this.props.onChange(cm.getValue());}); this.codeMirror?.on('change', (cm)=>{this.props.onChange(cm.getValue());});
this.updateSize(); this.updateSize();
}, },
@@ -203,84 +196,84 @@ const CodeEditor = createClass({
}, },
dedent : function () { dedent : function () {
this.codeMirror.execCommand('indentLess'); this.codeMirror?.execCommand('indentLess');
}, },
makeHeader : function (number) { makeHeader : function (number) {
const selection = this.codeMirror.getSelection(); const selection = this.codeMirror?.getSelection();
const header = Array(number).fill('#').join(''); const header = Array(number).fill('#').join('');
this.codeMirror.replaceSelection(`${header} ${selection}`, 'around'); this.codeMirror?.replaceSelection(`${header} ${selection}`, 'around');
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror?.getCursor();
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch + selection.length + number + 1 }); this.codeMirror?.setCursor({ line: cursor.line, ch: cursor.ch + selection.length + number + 1 });
}, },
makeBold : function() { makeBold : function() {
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 2) === '**' && selection.slice(-2) === '**'; const selection = this.codeMirror?.getSelection(), t = selection.slice(0, 2) === '**' && selection.slice(-2) === '**';
this.codeMirror.replaceSelection(t ? selection.slice(2, -2) : `**${selection}**`, 'around'); this.codeMirror?.replaceSelection(t ? selection.slice(2, -2) : `**${selection}**`, 'around');
if(selection.length === 0){ if(selection.length === 0){
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror?.getCursor();
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - 2 }); this.codeMirror?.setCursor({ line: cursor.line, ch: cursor.ch - 2 });
} }
}, },
makeItalic : function() { makeItalic : function() {
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 1) === '*' && selection.slice(-1) === '*'; const selection = this.codeMirror?.getSelection(), t = selection.slice(0, 1) === '*' && selection.slice(-1) === '*';
this.codeMirror.replaceSelection(t ? selection.slice(1, -1) : `*${selection}*`, 'around'); this.codeMirror?.replaceSelection(t ? selection.slice(1, -1) : `*${selection}*`, 'around');
if(selection.length === 0){ if(selection.length === 0){
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror?.getCursor();
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - 1 }); this.codeMirror?.setCursor({ line: cursor.line, ch: cursor.ch - 1 });
} }
}, },
makeSuper : function() { makeSuper : function() {
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 1) === '^' && selection.slice(-1) === '^'; const selection = this.codeMirror?.getSelection(), t = selection.slice(0, 1) === '^' && selection.slice(-1) === '^';
this.codeMirror.replaceSelection(t ? selection.slice(1, -1) : `^${selection}^`, 'around'); this.codeMirror?.replaceSelection(t ? selection.slice(1, -1) : `^${selection}^`, 'around');
if(selection.length === 0){ if(selection.length === 0){
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror?.getCursor();
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - 1 }); this.codeMirror?.setCursor({ line: cursor.line, ch: cursor.ch - 1 });
} }
}, },
makeSub : function() { makeSub : function() {
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 2) === '^^' && selection.slice(-2) === '^^'; const selection = this.codeMirror?.getSelection(), t = selection.slice(0, 2) === '^^' && selection.slice(-2) === '^^';
this.codeMirror.replaceSelection(t ? selection.slice(2, -2) : `^^${selection}^^`, 'around'); this.codeMirror?.replaceSelection(t ? selection.slice(2, -2) : `^^${selection}^^`, 'around');
if(selection.length === 0){ if(selection.length === 0){
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror?.getCursor();
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - 2 }); this.codeMirror?.setCursor({ line: cursor.line, ch: cursor.ch - 2 });
} }
}, },
makeNbsp : function() { makeNbsp : function() {
this.codeMirror.replaceSelection('&nbsp;', 'end'); this.codeMirror?.replaceSelection('&nbsp;', 'end');
}, },
makeSpace : function() { makeSpace : function() {
const selection = this.codeMirror.getSelection(); const selection = this.codeMirror?.getSelection();
const t = selection.slice(0, 8) === '{{width:' && selection.slice(0 -4) === '% }}'; const t = selection.slice(0, 8) === '{{width:' && selection.slice(0 -4) === '% }}';
if(t){ if(t){
const percent = parseInt(selection.slice(8, -4)) + 10; const percent = parseInt(selection.slice(8, -4)) + 10;
this.codeMirror.replaceSelection(percent < 90 ? `{{width:${percent}% }}` : '{{width:100% }}', 'around'); this.codeMirror?.replaceSelection(percent < 90 ? `{{width:${percent}% }}` : '{{width:100% }}', 'around');
} else { } else {
this.codeMirror.replaceSelection(`{{width:10% }}`, 'around'); this.codeMirror?.replaceSelection(`{{width:10% }}`, 'around');
} }
}, },
removeSpace : function() { removeSpace : function() {
const selection = this.codeMirror.getSelection(); const selection = this.codeMirror?.getSelection();
const t = selection.slice(0, 8) === '{{width:' && selection.slice(0 -4) === '% }}'; const t = selection.slice(0, 8) === '{{width:' && selection.slice(0 -4) === '% }}';
if(t){ if(t){
const percent = parseInt(selection.slice(8, -4)) - 10; const percent = parseInt(selection.slice(8, -4)) - 10;
this.codeMirror.replaceSelection(percent > 10 ? `{{width:${percent}% }}` : '', 'around'); this.codeMirror?.replaceSelection(percent > 10 ? `{{width:${percent}% }}` : '', 'around');
} }
}, },
newColumn : function() { newColumn : function() {
this.codeMirror.replaceSelection('\n\\column\n\n', 'end'); this.codeMirror?.replaceSelection('\n\\column\n\n', 'end');
}, },
newPage : function() { newPage : function() {
this.codeMirror.replaceSelection('\n\\page\n\n', 'end'); this.codeMirror?.replaceSelection('\n\\page\n\n', 'end');
}, },
injectText : function(injectText, overwrite=true) { injectText : function(injectText, overwrite=true) {
@@ -293,29 +286,29 @@ const CodeEditor = createClass({
}, },
makeUnderline : function() { makeUnderline : function() {
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 3) === '<u>' && selection.slice(-4) === '</u>'; const selection = this.codeMirror?.getSelection(), t = selection.slice(0, 3) === '<u>' && selection.slice(-4) === '</u>';
this.codeMirror.replaceSelection(t ? selection.slice(3, -4) : `<u>${selection}</u>`, 'around'); this.codeMirror?.replaceSelection(t ? selection.slice(3, -4) : `<u>${selection}</u>`, 'around');
if(selection.length === 0){ if(selection.length === 0){
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror?.getCursor();
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - 4 }); this.codeMirror?.setCursor({ line: cursor.line, ch: cursor.ch - 4 });
} }
}, },
makeSpan : function() { makeSpan : function() {
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 2) === '{{' && selection.slice(-2) === '}}'; const selection = this.codeMirror?.getSelection(), t = selection.slice(0, 2) === '{{' && selection.slice(-2) === '}}';
this.codeMirror.replaceSelection(t ? selection.slice(2, -2) : `{{ ${selection}}}`, 'around'); this.codeMirror?.replaceSelection(t ? selection.slice(2, -2) : `{{ ${selection}}}`, 'around');
if(selection.length === 0){ if(selection.length === 0){
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror?.getCursor();
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - 2 }); this.codeMirror?.setCursor({ line: cursor.line, ch: cursor.ch - 2 });
} }
}, },
makeDiv : function() { makeDiv : function() {
const selection = this.codeMirror.getSelection(), t = selection.slice(0, 2) === '{{' && selection.slice(-2) === '}}'; const selection = this.codeMirror?.getSelection(), t = selection.slice(0, 2) === '{{' && selection.slice(-2) === '}}';
this.codeMirror.replaceSelection(t ? selection.slice(2, -2) : `{{\n${selection}\n}}`, 'around'); this.codeMirror?.replaceSelection(t ? selection.slice(2, -2) : `{{\n${selection}\n}}`, 'around');
if(selection.length === 0){ if(selection.length === 0){
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror?.getCursor();
this.codeMirror.setCursor({ line: cursor.line - 1, ch: cursor.ch }); // set to -2? if wanting to enter classes etc. if so, get rid of first \n when replacing selection this.codeMirror?.setCursor({ line: cursor.line - 1, ch: cursor.ch }); // set to -2? if wanting to enter classes etc. if so, get rid of first \n when replacing selection
} }
}, },
@@ -323,7 +316,7 @@ const CodeEditor = createClass({
let regex; let regex;
let cursorPos; let cursorPos;
let newComment; let newComment;
const selection = this.codeMirror.getSelection(); const selection = this.codeMirror?.getSelection();
if(this.props.language === 'gfm'){ if(this.props.language === 'gfm'){
regex = /^\s*(<!--\s?)(.*?)(\s?-->)\s*$/gs; regex = /^\s*(<!--\s?)(.*?)(\s?-->)\s*$/gs;
cursorPos = 4; cursorPos = 4;
@@ -333,44 +326,44 @@ const CodeEditor = createClass({
cursorPos = 3; cursorPos = 3;
newComment = `/* ${selection} */`; newComment = `/* ${selection} */`;
} }
this.codeMirror.replaceSelection(regex.test(selection) == true ? selection.replace(regex, '$2') : newComment, 'around'); this.codeMirror?.replaceSelection(regex.test(selection) == true ? selection.replace(regex, '$2') : newComment, 'around');
if(selection.length === 0){ if(selection.length === 0){
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror?.getCursor();
this.codeMirror.setCursor({ line: cursor.line, ch: cursor.ch - cursorPos }); this.codeMirror?.setCursor({ line: cursor.line, ch: cursor.ch - cursorPos });
}; };
}, },
makeLink : function() { makeLink : function() {
const isLink = /^\[(.*)\]\((.*)\)$/; const isLink = /^\[(.*)\]\((.*)\)$/;
const selection = this.codeMirror.getSelection().trim(); const selection = this.codeMirror?.getSelection().trim();
let match; let match;
if(match = isLink.exec(selection)){ if(match = isLink.exec(selection)){
const altText = match[1]; const altText = match[1];
const url = match[2]; const url = match[2];
this.codeMirror.replaceSelection(`${altText} ${url}`); this.codeMirror?.replaceSelection(`${altText} ${url}`);
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror?.getCursor();
this.codeMirror.setSelection({ line: cursor.line, ch: cursor.ch - url.length }, { line: cursor.line, ch: cursor.ch }); this.codeMirror?.setSelection({ line: cursor.line, ch: cursor.ch - url.length }, { line: cursor.line, ch: cursor.ch });
} else { } else {
this.codeMirror.replaceSelection(`[${selection || 'alt text'}](url)`); this.codeMirror?.replaceSelection(`[${selection || 'alt text'}](url)`);
const cursor = this.codeMirror.getCursor(); const cursor = this.codeMirror?.getCursor();
this.codeMirror.setSelection({ line: cursor.line, ch: cursor.ch - 4 }, { line: cursor.line, ch: cursor.ch - 1 }); this.codeMirror?.setSelection({ line: cursor.line, ch: cursor.ch - 4 }, { line: cursor.line, ch: cursor.ch - 1 });
} }
}, },
makeList : function(listType) { makeList : function(listType) {
const selectionStart = this.codeMirror.getCursor('from'), selectionEnd = this.codeMirror.getCursor('to'); const selectionStart = this.codeMirror?.getCursor('from'), selectionEnd = this.codeMirror?.getCursor('to');
this.codeMirror.setSelection( this.codeMirror?.setSelection(
{ line: selectionStart.line, ch: 0 }, { line: selectionStart.line, ch: 0 },
{ line: selectionEnd.line, ch: this.codeMirror.getLine(selectionEnd.line).length } { line: selectionEnd.line, ch: this.codeMirror?.getLine(selectionEnd.line).length }
); );
const newSelection = this.codeMirror.getSelection(); const newSelection = this.codeMirror?.getSelection();
const regex = /^\d+\.\s|^-\s/gm; const regex = /^\d+\.\s|^-\s/gm;
if(newSelection.match(regex) != null){ // if selection IS A LIST if(newSelection.match(regex) != null){ // if selection IS A LIST
this.codeMirror.replaceSelection(newSelection.replace(regex, ''), 'around'); this.codeMirror?.replaceSelection(newSelection.replace(regex, ''), 'around');
} else { // if selection IS NOT A LIST } else { // if selection IS NOT A LIST
listType == 'UL' ? this.codeMirror.replaceSelection(newSelection.replace(/^/gm, `- `), 'around') : listType == 'UL' ? this.codeMirror?.replaceSelection(newSelection.replace(/^/gm, `- `), 'around') :
this.codeMirror.replaceSelection(newSelection.replace(/^/gm, (()=>{ this.codeMirror?.replaceSelection(newSelection.replace(/^/gm, (()=>{
let n = 1; let n = 1;
return ()=>{ return ()=>{
return `${n++}. `; return `${n++}. `;
@@ -380,39 +373,39 @@ const CodeEditor = createClass({
}, },
foldAllCode : function() { foldAllCode : function() {
this.codeMirror.execCommand('foldAll'); this.codeMirror?.execCommand('foldAll');
}, },
unfoldAllCode : function() { unfoldAllCode : function() {
this.codeMirror.execCommand('unfoldAll'); this.codeMirror?.execCommand('unfoldAll');
}, },
//=-- Externally used -==// //=-- Externally used -==//
setCursorPosition : function(line, char){ setCursorPosition : function(line, char){
setTimeout(()=>{ setTimeout(()=>{
this.codeMirror.focus(); this.codeMirror?.focus();
this.codeMirror.doc.setCursor(line, char); this.codeMirror?.doc.setCursor(line, char);
}, 10); }, 10);
}, },
getCursorPosition : function(){ getCursorPosition : function(){
return this.codeMirror.getCursor(); return this.codeMirror?.getCursor();
}, },
getTopVisibleLine : function(){ getTopVisibleLine : function(){
const rect = this.codeMirror.getWrapperElement().getBoundingClientRect(); const rect = this.codeMirror?.getWrapperElement().getBoundingClientRect();
const topVisibleLine = this.codeMirror.lineAtHeight(rect.top, 'window'); const topVisibleLine = this.codeMirror?.lineAtHeight(rect.top, 'window');
return topVisibleLine; return topVisibleLine;
}, },
updateSize : function(){ updateSize : function(){
this.codeMirror.refresh(); this.codeMirror?.refresh();
}, },
redo : function(){ redo : function(){
return this.codeMirror.redo(); return this.codeMirror?.redo();
}, },
undo : function(){ undo : function(){
return this.codeMirror.undo(); return this.codeMirror?.undo();
}, },
historySize : function(){ historySize : function(){
return this.codeMirror.doc.historySize(); return this.codeMirror?.doc.historySize();
}, },
foldOptions : function(cm){ foldOptions : function(cm){
@@ -426,7 +419,7 @@ const CodeEditor = createClass({
let foldPreviewText = ''; let foldPreviewText = '';
while (currentLine <= to.line && text.length <= maxLength) { while (currentLine <= to.line && text.length <= maxLength) {
const currentText = this.codeMirror.getLine(currentLine); const currentText = this.codeMirror?.getLine(currentLine);
currentLine++; currentLine++;
if(currentText[0] == '#'){ if(currentText[0] == '#'){
foldPreviewText = currentText; foldPreviewText = currentText;
@@ -461,5 +454,5 @@ const CodeEditor = createClass({
} }
}); });
module.exports = CodeEditor; export default CodeEditor;
@@ -0,0 +1,60 @@
@import (less) 'codemirror/lib/codemirror.css';
@import (less) 'codemirror/addon/fold/foldgutter.css';
@import (less) 'codemirror/addon/search/matchesonscrollbar.css';
@import (less) 'codemirror/addon/dialog/dialog.css';
@import (less) 'codemirror/addon/hint/show-hint.css';
//Icon fonts included so they can appear in emoji autosuggest dropdown
@import (less) './themes/fonts/iconFonts/diceFont.less';
@import (less) './themes/fonts/iconFonts/elderberryInn.less';
@import (less) './themes/fonts/iconFonts/gameIcons.less';
@import (less) './themes/fonts/iconFonts/fontAwesome.less';
@keyframes sourceMoveAnimation {
50% { color : white;background-color : red;}
100% { color : unset;background-color : unset;}
}
.codeEditor {
@media screen and (pointer : coarse) {
font-size : 16px;
}
.CodeMirror-foldmarker {
font-family : inherit;
font-weight : 600;
color : grey;
text-shadow : none;
}
.CodeMirror-foldgutter {
cursor : pointer;
border-left : 1px solid #EEEEEE;
transition : background 0.1s;
&:hover { background : #DDDDDD; }
}
.sourceMoveFlash .CodeMirror-line {
animation-name : sourceMoveAnimation;
animation-duration : 0.4s;
}
.CodeMirror-search-field {
width:25em !important;
outline:1px inset #00000055 !important;
}
//.cm-tab {
// background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAMCAQAAACOs/baAAAARUlEQVR4nGJgIAG8JkXxUAcCtDWemcGR1lY4MvgzCEKY7jSBjgxBDAG09UEQzAe0AMwMHrSOAwEGRtpaMIwAAAAA//8DAG4ID9EKs6YqAAAAAElFTkSuQmCC) no-repeat right;
//}
//.cm-trailingspace {
// .cm-space {
// background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAgAAAAQAgMAAABW5NbuAAAACVBMVEVHcEwAAAAAAAAWawmTAAAAA3RSTlMAPBJ6PMxpAAAACXBIWXMAAC4jAAAuIwF4pT92AAAAFUlEQVQI12NgwACcCQysASAEZGAAACMuAX06aCQUAAAAAElFTkSuQmCC) no-repeat right;
// }
//}
}
.emojiPreview {
font-size : 1.5em;
line-height : 1.2em;
}
@@ -1,4 +1,4 @@
module.exports = { export default {
registerHomebreweryHelper : function(CodeMirror) { registerHomebreweryHelper : function(CodeMirror) {
CodeMirror.registerHelper('fold', 'homebrewerycss', function(cm, start) { CodeMirror.registerHelper('fold', 'homebrewerycss', function(cm, start) {
@@ -1,4 +1,4 @@
module.exports = { export default {
registerHomebreweryHelper : function(CodeMirror) { registerHomebreweryHelper : function(CodeMirror) {
CodeMirror.registerHelper('fold', 'homebrewery', function(cm, start) { CodeMirror.registerHelper('fold', 'homebrewery', function(cm, start) {
const matcher = /^\\page.*/; const matcher = /^\\page.*/;
+15 -14
View File
@@ -1,9 +1,9 @@
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const _ = require('lodash'); import _ from 'lodash';
require('./combobox.less'); import './combobox.less';
const Combobox = createClass({ const Combobox = createReactClass({
displayName : 'Combobox', displayName : 'Combobox',
getDefaultProps : function() { getDefaultProps : function() {
return { return {
@@ -45,6 +45,7 @@ const Combobox = createClass({
}, },
handleDropdown : function(show){ handleDropdown : function(show){
this.setState({ this.setState({
value : show ? '' : this.props.default,
showDropdown : show, showDropdown : show,
inputFocused : this.props.autoSuggest.clearAutoSuggestOnClick ? show : false inputFocused : this.props.autoSuggest.clearAutoSuggestOnClick ? show : false
}); });
@@ -58,10 +59,10 @@ const Combobox = createClass({
this.props.onEntry(e); this.props.onEntry(e);
}); });
}, },
handleSelect : function(e){ handleSelect : function(value, data=value){
this.setState({ this.setState({
value : e.currentTarget.getAttribute('data-value') value : value
}, ()=>{this.props.onSelect(this.state.value);}); }, ()=>{this.props.onSelect(data);});
; ;
}, },
renderTextInput : function(){ renderTextInput : function(){
@@ -78,10 +79,11 @@ const Combobox = createClass({
if(!e.target.checkValidity()){ if(!e.target.checkValidity()){
this.setState({ this.setState({
value : this.props.default value : this.props.default
}, ()=>this.props.onEntry(e)); });
} }
}} }}
/> />
<i className='fas fa-caret-down'/>
</div> </div>
); );
}, },
@@ -92,11 +94,10 @@ const Combobox = createClass({
const filterOn = _.isString(this.props.autoSuggest.filterOn) ? [this.props.autoSuggest.filterOn] : this.props.autoSuggest.filterOn; const filterOn = _.isString(this.props.autoSuggest.filterOn) ? [this.props.autoSuggest.filterOn] : this.props.autoSuggest.filterOn;
const filteredArrays = filterOn.map((attr)=>{ const filteredArrays = filterOn.map((attr)=>{
const children = dropdownChildren.filter((item)=>{ const children = dropdownChildren.filter((item)=>{
if(suggestMethod === 'includes'){ if(suggestMethod === 'includes')
return item.props[attr]?.toLowerCase().includes(this.state.value.toLowerCase()); return item.props[attr]?.toLowerCase().includes(this.state.value.toLowerCase());
} else if(suggestMethod === 'startsWith'){ if(suggestMethod === 'startsWith')
return item.props[attr]?.toLowerCase().startsWith(this.state.value.toLowerCase()); return item.props[attr]?.toLowerCase().startsWith(this.state.value.toLowerCase());
}
}); });
return children; return children;
}); });
@@ -111,7 +112,7 @@ const Combobox = createClass({
}, },
render : function () { render : function () {
const dropdownChildren = this.state.options.map((child, i)=>{ const dropdownChildren = this.state.options.map((child, i)=>{
const clone = React.cloneElement(child, { onClick: (e)=>this.handleSelect(e) }); const clone = React.cloneElement(child, { onClick: ()=>this.handleSelect(child.props.value, child.props.data) });
return clone; return clone;
}); });
return ( return (
@@ -125,4 +126,4 @@ const Combobox = createClass({
} }
}); });
module.exports = Combobox; export default Combobox;
+42 -46
View File
@@ -1,50 +1,46 @@
.dropdown-container { .dropdown-container {
position:relative; position : relative;
input { input { width : 100%; }
width: 100%; .item i {
} position : absolute;
.dropdown-options { right : 10px;
position:absolute; color : black;
background-color: white; }
z-index: 100; .dropdown-options {
width: 100%; position : absolute;
border: 1px solid gray; z-index : 100;
overflow-y: auto; width : 100%;
max-height: 200px; max-height : 200px;
overflow-y : auto;
background-color : white;
border : 1px solid gray;
&::-webkit-scrollbar { &::-webkit-scrollbar { width : 14px; }
width: 14px; &::-webkit-scrollbar-track { background : #FFFFFF; }
} &::-webkit-scrollbar-thumb {
&::-webkit-scrollbar-track { background-color : #949494;
background: #ffffff; border : 3px solid #FFFFFF;
} border-radius : 10px;
&::-webkit-scrollbar-thumb { }
background-color: #949494;
border-radius: 10px;
border: 3px solid #ffffff;
}
.item {
position:relative;
font-size: 11px;
font-family: Open Sans;
padding: 5px;
cursor: default;
margin: 0 3px;
//border-bottom: 1px solid darkgray;
&:hover {
filter: brightness(120%);
background-color: rgb(163, 163, 163);
}
.detail {
width:100%;
text-align: left;
color: rgb(124, 124, 124);
font-style:italic;
font-size: 9px;
}
}
}
.item {
position : relative;
padding : 5px;
margin : 0 3px;
font-family : 'Open Sans';
font-size : 11px;
cursor : default;
&:hover {
background-color : rgb(163, 163, 163);
filter : brightness(120%);
}
.detail {
width : 100%;
font-size : 9px;
font-style : italic;
color : rgb(124, 124, 124);
text-align : left;
}
}
}
} }
+9 -7
View File
@@ -1,22 +1,24 @@
// Dialog box, for popups and modal blocking messages // Dialog box, for popups and modal blocking messages
const React = require('react'); import React from 'react';
const { useRef, useEffect } = React; const { useRef, useEffect } = React;
function Dialog({ dismissKey, closeText = 'Close', blocking = false, ...rest }) { function Dialog({ dismisskeys = [], 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 = ()=>{
dismissKey && localStorage.setItem(dismissKey, true); dismisskeys.forEach((key)=>{
if(key) {
localStorage.setItem(key, 'true');
}
});
dialogRef.current?.close(); dialogRef.current?.close();
}; };
return ( return (
<dialog ref={dialogRef} onCancel={dismiss} {...rest}> <dialog ref={dialogRef} onCancel={dismiss} {...rest}>
{rest.children} {rest.children}
<button className='dismiss' onClick={dismiss}> <button className='dismiss' onClick={dismiss}>
@@ -1,11 +1,11 @@
require('./renderWarnings.less'); import './renderWarnings.less';
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const _ = require('lodash'); import _ from 'lodash';
import Dialog from '../../../client/components/dialog.jsx'; import Dialog from '../dialog.jsx';
const RenderWarnings = createClass({ const RenderWarnings = createReactClass({
displayName : 'RenderWarnings', displayName : 'RenderWarnings',
getInitialState : function() { getInitialState : function() {
return { return {
@@ -25,7 +25,7 @@ const RenderWarnings = createClass({
if(!isChrome){ if(!isChrome){
return <li key='chrome'> return <li key='chrome'>
<em>Built for Chrome </em> <br /> <em>Built for Chrome </em> <br />
Other browsers have not been tested for compatiblilty. If you Other browsers have not been tested for compatibility. If you
experience issues with your document not rendering or printing experience issues with your document not rendering or printing
properly, please try using the latest version of Chrome before properly, please try using the latest version of Chrome before
submitting a bug report. submitting a bug report.
@@ -57,4 +57,4 @@ const RenderWarnings = createClass({
} }
}); });
module.exports = RenderWarnings; export default RenderWarnings;
+110
View File
@@ -0,0 +1,110 @@
import './splitPane.less';
import React, { useEffect, useState } from 'react';
const PANE_WIDTH_KEY = 'HB_editor_splitWidth';
const LIVE_SCROLL_KEY = 'HB_editor_liveScroll';
const SplitPane = (props)=>{
const {
onDragFinish = ()=>{},
showDividerButtons = true
} = props;
const [isDragging, setIsDragging] = useState(false);
const [dividerPos, setDividerPos] = useState(null);
const [moveSource, setMoveSource] = useState(false);
const [moveBrew, setMoveBrew] = useState(false);
const [showMoveArrows, setShowMoveArrows] = useState(true);
const [liveScroll, setLiveScroll] = useState(false);
useEffect(()=>{
const savedPos = window.localStorage.getItem(PANE_WIDTH_KEY);
setDividerPos(savedPos ? limitPosition(savedPos, 0.1 * (window.innerWidth - 13), 0.9 * (window.innerWidth - 13)) : window.innerWidth / 2);
setLiveScroll(window.localStorage.getItem(LIVE_SCROLL_KEY) === 'true');
window.addEventListener('resize', handleResize);
return ()=>window.removeEventListener('resize', handleResize);
}, []);
const limitPosition = (x, min = 1, max = window.innerWidth - 13)=>Math.round(Math.min(max, Math.max(min, x)));
//when resizing, the divider should grow smaller if less space is given, then grow back if the space is restored, to the original position
const handleResize = ()=>setDividerPos(limitPosition(window.localStorage.getItem(PANE_WIDTH_KEY), 0.1 * (window.innerWidth - 13), 0.9 * (window.innerWidth - 13)));
const handleUp =(e)=>{
e.preventDefault();
if(isDragging) {
onDragFinish(dividerPos);
window.localStorage.setItem(PANE_WIDTH_KEY, dividerPos);
}
setIsDragging(false);
};
const handleDown = (e)=>{
e.preventDefault();
setIsDragging(true);
};
const handleMove = (e)=>{
if(!isDragging) return;
e.preventDefault();
setDividerPos(limitPosition(e.pageX));
};
const liveScrollToggle = ()=>{
window.localStorage.setItem(LIVE_SCROLL_KEY, String(!liveScroll));
setLiveScroll(!liveScroll);
};
const renderMoveArrows = (showMoveArrows &&
<>
<div className='arrow left'
onClick={()=>setMoveSource(!moveSource)} >
<i className='fas fa-arrow-left' />
</div>
<div className='arrow right'
onClick={()=>setMoveBrew(!moveBrew)} >
<i className='fas fa-arrow-right' />
</div>
<div id='scrollToggleDiv' className={liveScroll ? 'arrow lock' : 'arrow unlock'}
onClick={liveScrollToggle} >
<i id='scrollToggle' className={liveScroll ? 'fas fa-lock' : 'fas fa-unlock'} />
</div>
</>
);
const renderDivider = (
<div className={`divider ${isDragging && 'dragging'}`} onPointerDown={handleDown}>
{showDividerButtons && renderMoveArrows}
<div className='dots'>
<i className='fas fa-circle' />
<i className='fas fa-circle' />
<i className='fas fa-circle' />
</div>
</div>
);
return (
<div className='splitPane' onPointerMove={handleMove} onPointerUp={handleUp}>
<Pane width={dividerPos} moveBrew={moveBrew} moveSource={moveSource} liveScroll={liveScroll} setMoveArrows={setShowMoveArrows}>
{props.children[0]}
</Pane>
{renderDivider}
<Pane isDragging={isDragging}>{props.children[1]}</Pane>
</div>
);
};
const Pane = ({ width, children, isDragging, moveBrew, moveSource, liveScroll, setMoveArrows })=>{
const styles = width
? { flex: 'none', width: `${width}px` }
: { pointerEvents: isDragging ? 'none' : 'auto' }; //Disable mouse capture in the right pane; else dragging into the iframe drops the divider
return (
<div className='pane' style={styles}>
{React.cloneElement(children, { moveBrew, moveSource, liveScroll, setMoveArrows })}
</div>
);
};
export default SplitPane;
@@ -1,69 +1,68 @@
.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 {
touch-action : none; position : relative;
display : table; display : table;
height : 100%;
width : 15px; width : 15px;
cursor : ew-resize; height : 100%;
background-color : #bbb;
text-align : center; text-align : center;
.dots{ touch-action : none;
cursor : ew-resize;
background-color : #BBBBBB;
.dots {
display : table-cell; display : table-cell;
vertical-align : middle; vertical-align : middle;
text-align : center; text-align : center;
i{ i {
display : block !important; display : block !important;
margin : 10px 0px; margin : 10px 0px;
font-size : 6px; font-size : 6px;
color : #666; color : #666666;
} }
} }
&:hover{ &:hover,&.dragging { background-color : #999999; }
background-color: #999;
}
} }
.arrow{ .arrow {
position : absolute; position : absolute;
left : 50%;
z-index : 999;
width : 25px; width : 25px;
height : 25px; height : 25px;
border : 2px solid #bbb;
border-radius : 15px;
text-align : center;
font-size : 1.2em; font-size : 1.2em;
text-align : center;
cursor : pointer; cursor : pointer;
background-color : #ddd; background-color : #DDDDDD;
z-index : 999; border : 2px solid #BBBBBB;
box-shadow : 0 4px 5px #0000007f; border-radius : 15px;
&.left{ box-shadow : 0 4px 5px #0000007F;
translate : -50%;
&.left {
.tooltipLeft('Jump to location in Editor'); .tooltipLeft('Jump to location in Editor');
top : 30px; top : 30px;
} }
&.right{ &.right {
.tooltipRight('Jump to location in Preview'); .tooltipRight('Jump to location in Preview');
top : 60px; top : 60px;
} }
&.lock{ &.lock {
.tooltipRight('De-sync Editor and Preview locations.'); .tooltipRight('De-sync Editor and Preview locations.');
top : 90px; top : 90px;
background: #666; background : #666666;
} }
&.unlock{ &.unlock {
.tooltipRight('Sync Editor and Preview locations'); .tooltipRight('Sync Editor and Preview locations');
top : 90px; top : 90px;
} }
&:hover{ &:hover { background-color : #666666; }
background-color: #666;
}
} }
} }
@@ -1,7 +1,6 @@
const React = require('react'); import React from 'react';
const createClass = require('create-react-class');
module.exports = function(props){ export default function(props){
return <svg version='1.1' x='0px' y='0px' viewBox='0 0 90 112.5' enableBackground='new 0 0 90 90' > return <svg version='1.1' x='0px' y='0px' viewBox='0 0 90 112.5' enableBackground='new 0 0 90 90' >
<path d='M25.363,25.54c0,1.906,8.793,3.454,19.636,3.454c10.848,0,19.638-1.547,19.638-3.454c0-1.12-3.056-2.117-7.774-2.75 c-1.418,1.891-3.659,3.133-6.208,3.133c-2.85,0-5.315-1.547-6.67-3.833C33.617,22.185,25.363,23.692,25.363,25.54z'/><path d='M84.075,54.142c0-8.68-2.868-17.005-8.144-23.829c1.106-1.399,1.41-2.771,1.41-3.854c0-6.574-10.245-9.358-19.264-10.533 c0.209,0.706,0.359,1.439,0.359,2.215c0,0.09-0.022,0.17-0.028,0.26l0,0c-0.028,0.853-0.195,1.667-0.479,2.429 c9.106,1.282,14.508,3.754,14.508,5.63c0,2.644-10.688,6.486-27.439,6.486c-16.748,0-27.438-3.842-27.438-6.486 c0-2.542,9.904-6.183,25.559-6.459c-0.098-0.396-0.159-0.807-0.2-1.223c0.006,0,0.013,0,0.017,0 c-0.017-0.213-0.063-0.417-0.063-0.636c0-1.084,0.226-2.119,0.628-3.058c-6.788,0.129-30.846,1.299-30.846,11.376 c0,1.083,0.305,2.455,1.411,3.854c-5.276,6.823-8.145,15.149-8.145,23.829c0,11.548,5.187,20.107,14.693,25.115 c-0.902,3.146-1.391,7.056,1.111,8.181c2.626,1.178,5.364-2.139,7.111-5.005c4.73,1.261,10.13,1.923,16.161,1.923 c6.034,0,11.428-0.661,16.158-1.922c1.75,2.865,4.493,6.18,7.112,5.004c2.504-1.123,2.014-5.035,1.113-8.179 C78.889,74.249,84.075,65.689,84.075,54.142z M70.39,31.392c5.43,6.046,8.78,14,8.78,22.75c0,20.919-18.582,25.309-34.171,25.309 c-15.587,0-34.17-4.39-34.17-25.309c0-8.75,3.35-16.7,8.781-22.753c5.561,2.643,15.502,4.009,25.389,4.009 C54.886,35.397,64.829,34.031,70.39,31.392z'/><path d='M50.654,23.374c2.892,0,5.234-2.341,5.234-5.233c0-2.887-2.343-5.23-5.234-5.23c-2.887,0-5.231,2.343-5.231,5.23 C45.423,21.032,47.768,23.374,50.654,23.374z'/> <path d='M25.363,25.54c0,1.906,8.793,3.454,19.636,3.454c10.848,0,19.638-1.547,19.638-3.454c0-1.12-3.056-2.117-7.774-2.75 c-1.418,1.891-3.659,3.133-6.208,3.133c-2.85,0-5.315-1.547-6.67-3.833C33.617,22.185,25.363,23.692,25.363,25.54z'/><path d='M84.075,54.142c0-8.68-2.868-17.005-8.144-23.829c1.106-1.399,1.41-2.771,1.41-3.854c0-6.574-10.245-9.358-19.264-10.533 c0.209,0.706,0.359,1.439,0.359,2.215c0,0.09-0.022,0.17-0.028,0.26l0,0c-0.028,0.853-0.195,1.667-0.479,2.429 c9.106,1.282,14.508,3.754,14.508,5.63c0,2.644-10.688,6.486-27.439,6.486c-16.748,0-27.438-3.842-27.438-6.486 c0-2.542,9.904-6.183,25.559-6.459c-0.098-0.396-0.159-0.807-0.2-1.223c0.006,0,0.013,0,0.017,0 c-0.017-0.213-0.063-0.417-0.063-0.636c0-1.084,0.226-2.119,0.628-3.058c-6.788,0.129-30.846,1.299-30.846,11.376 c0,1.083,0.305,2.455,1.411,3.854c-5.276,6.823-8.145,15.149-8.145,23.829c0,11.548,5.187,20.107,14.693,25.115 c-0.902,3.146-1.391,7.056,1.111,8.181c2.626,1.178,5.364-2.139,7.111-5.005c4.73,1.261,10.13,1.923,16.161,1.923 c6.034,0,11.428-0.661,16.158-1.922c1.75,2.865,4.493,6.18,7.112,5.004c2.504-1.123,2.014-5.035,1.113-8.179 C78.889,74.249,84.075,65.689,84.075,54.142z M70.39,31.392c5.43,6.046,8.78,14,8.78,22.75c0,20.919-18.582,25.309-34.171,25.309 c-15.587,0-34.17-4.39-34.17-25.309c0-8.75,3.35-16.7,8.781-22.753c5.561,2.643,15.502,4.009,25.389,4.009 C54.886,35.397,64.829,34.031,70.39,31.392z'/><path d='M50.654,23.374c2.892,0,5.234-2.341,5.234-5.233c0-2.887-2.343-5.23-5.234-5.23c-2.887,0-5.231,2.343-5.231,5.23 C45.423,21.032,47.768,23.374,50.654,23.374z'/>
<circle cx='62.905' cy='10.089' r='3.595'/> <circle cx='62.905' cy='10.089' r='3.595'/>
@@ -1,6 +1,5 @@
const React = require('react'); import React from 'react';
const createClass = require('create-react-class');
module.exports = function(props){ export default function(props){
return <svg version='1.1' x='0px' y='0px' viewBox='0 0 100 100' enableBackground='new 0 0 100 100'><path d='M80.644,87.982l16.592-41.483c0.054-0.128,0.088-0.26,0.108-0.394c0.006-0.039,0.007-0.077,0.011-0.116 c0.007-0.087,0.008-0.174,0.002-0.26c-0.003-0.046-0.007-0.091-0.014-0.137c-0.014-0.089-0.036-0.176-0.063-0.262 c-0.012-0.034-0.019-0.069-0.031-0.103c-0.047-0.118-0.106-0.229-0.178-0.335c-0.004-0.006-0.006-0.012-0.01-0.018L67.999,3.358 c-0.01-0.013-0.003-0.026-0.013-0.04L68,3.315V4c0,0-0.033,0-0.037,0c-0.403-1-1.094-1.124-1.752-0.976 c0,0.004-0.004-0.012-0.007-0.012C66.201,3.016,66.194,3,66.194,3H66.19h-0.003h-0.003h-0.004h-0.003c0,0-0.004,0-0.007,0 s-0.003-0.151-0.007-0.151L20.495,15.227c-0.025,0.007-0.046-0.019-0.071-0.011c-0.087,0.028-0.172,0.041-0.253,0.083 c-0.054,0.027-0.102,0.053-0.152,0.085c-0.051,0.033-0.101,0.061-0.147,0.099c-0.044,0.036-0.084,0.073-0.124,0.113 c-0.048,0.048-0.093,0.098-0.136,0.152c-0.03,0.039-0.059,0.076-0.085,0.117c-0.046,0.07-0.084,0.145-0.12,0.223 c-0.011,0.023-0.027,0.042-0.036,0.066L2.911,57.664C2.891,57.715,3,57.768,3,57.82v0.002c0,0.186,0,0.375,0,0.562 c0,0.004,0,0.004,0,0.008c0,0,0,0,0,0.002c0,0,0,0,0,0.004v0.004v0.002c0,0.074-0.002,0.15,0.012,0.223 C3.015,58.631,3,58.631,3,58.633c0,0.004,0,0.004,0,0.008c0,0,0,0,0,0.002c0,0,0,0,0,0.004v0.004c0,0,0,0,0,0.002v0.004 c0,0.191-0.046,0.377,0.06,0.545c0-0.002-0.03,0.004-0.03,0.004c0,0.004-0.03,0.004-0.03,0.004c0,0.002,0,0.002,0,0.002 l-0.045,0.004c0.03,0.047,0.036,0.09,0.068,0.133l29.049,37.359c0.002,0.004,0,0.006,0.002,0.01c0.002,0.002,0,0.004,0.002,0.008 c0.006,0.008,0.014,0.014,0.021,0.021c0.024,0.029,0.052,0.051,0.078,0.078c0.027,0.029,0.053,0.057,0.082,0.082 c0.03,0.027,0.055,0.062,0.086,0.088c0.026,0.02,0.057,0.033,0.084,0.053c0.04,0.027,0.081,0.053,0.123,0.076 c0.005,0.004,0.01,0.008,0.016,0.01c0.087,0.051,0.176,0.09,0.269,0.123c0.042,0.014,0.082,0.031,0.125,0.043 c0.021,0.006,0.041,0.018,0.062,0.021c0.123,0.027,0.249,0.043,0.375,0.043c0.099,0,0.202-0.012,0.304-0.027l45.669-8.303 c0.057-0.01,0.108-0.021,0.163-0.037C79.547,88.992,79.562,89,79.575,89c0.004,0,0.004,0,0.004,0c0.021,0,0.039-0.027,0.06-0.035 c0.041-0.014,0.08-0.034,0.12-0.052c0.021-0.01,0.044-0.019,0.064-0.03c0.017-0.01,0.026-0.015,0.033-0.017 c0.014-0.008,0.023-0.021,0.037-0.028c0.14-0.078,0.269-0.174,0.38-0.285c0.014-0.016,0.024-0.034,0.038-0.048 c0.109-0.119,0.201-0.252,0.271-0.398c0.006-0.01,0.016-0.018,0.021-0.029c0.004-0.008,0.008-0.017,0.011-0.026 c0.002-0.004,0.003-0.006,0.005-0.01C80.627,88.021,80.635,88.002,80.644,87.982z M77.611,84.461L48.805,66.453l32.407-25.202 L77.611,84.461z M46.817,63.709L35.863,23.542l43.818,14.608L46.817,63.709z M84.668,40.542l8.926,5.952l-11.902,29.75 L84.668,40.542z M89.128,39.446L84.53,36.38l-6.129-12.257L89.128,39.446z M79.876,34.645L37.807,20.622L65.854,6.599L79.876,34.645 z M33.268,19.107l-6.485-2.162l23.781-6.487L33.268,19.107z M21.92,18.895l8.67,2.891L10.357,47.798L21.92,18.895z M32.652,24.649 l10.845,39.757L7.351,57.178L32.652,24.649z M43.472,67.857L32.969,92.363L8.462,60.855L43.472,67.857z M46.631,69.09l27.826,17.393 l-38.263,6.959L46.631,69.09z'></path></svg>; return <svg version='1.1' x='0px' y='0px' viewBox='0 0 100 100' enableBackground='new 0 0 100 100'><path d='M80.644,87.982l16.592-41.483c0.054-0.128,0.088-0.26,0.108-0.394c0.006-0.039,0.007-0.077,0.011-0.116 c0.007-0.087,0.008-0.174,0.002-0.26c-0.003-0.046-0.007-0.091-0.014-0.137c-0.014-0.089-0.036-0.176-0.063-0.262 c-0.012-0.034-0.019-0.069-0.031-0.103c-0.047-0.118-0.106-0.229-0.178-0.335c-0.004-0.006-0.006-0.012-0.01-0.018L67.999,3.358 c-0.01-0.013-0.003-0.026-0.013-0.04L68,3.315V4c0,0-0.033,0-0.037,0c-0.403-1-1.094-1.124-1.752-0.976 c0,0.004-0.004-0.012-0.007-0.012C66.201,3.016,66.194,3,66.194,3H66.19h-0.003h-0.003h-0.004h-0.003c0,0-0.004,0-0.007,0 s-0.003-0.151-0.007-0.151L20.495,15.227c-0.025,0.007-0.046-0.019-0.071-0.011c-0.087,0.028-0.172,0.041-0.253,0.083 c-0.054,0.027-0.102,0.053-0.152,0.085c-0.051,0.033-0.101,0.061-0.147,0.099c-0.044,0.036-0.084,0.073-0.124,0.113 c-0.048,0.048-0.093,0.098-0.136,0.152c-0.03,0.039-0.059,0.076-0.085,0.117c-0.046,0.07-0.084,0.145-0.12,0.223 c-0.011,0.023-0.027,0.042-0.036,0.066L2.911,57.664C2.891,57.715,3,57.768,3,57.82v0.002c0,0.186,0,0.375,0,0.562 c0,0.004,0,0.004,0,0.008c0,0,0,0,0,0.002c0,0,0,0,0,0.004v0.004v0.002c0,0.074-0.002,0.15,0.012,0.223 C3.015,58.631,3,58.631,3,58.633c0,0.004,0,0.004,0,0.008c0,0,0,0,0,0.002c0,0,0,0,0,0.004v0.004c0,0,0,0,0,0.002v0.004 c0,0.191-0.046,0.377,0.06,0.545c0-0.002-0.03,0.004-0.03,0.004c0,0.004-0.03,0.004-0.03,0.004c0,0.002,0,0.002,0,0.002 l-0.045,0.004c0.03,0.047,0.036,0.09,0.068,0.133l29.049,37.359c0.002,0.004,0,0.006,0.002,0.01c0.002,0.002,0,0.004,0.002,0.008 c0.006,0.008,0.014,0.014,0.021,0.021c0.024,0.029,0.052,0.051,0.078,0.078c0.027,0.029,0.053,0.057,0.082,0.082 c0.03,0.027,0.055,0.062,0.086,0.088c0.026,0.02,0.057,0.033,0.084,0.053c0.04,0.027,0.081,0.053,0.123,0.076 c0.005,0.004,0.01,0.008,0.016,0.01c0.087,0.051,0.176,0.09,0.269,0.123c0.042,0.014,0.082,0.031,0.125,0.043 c0.021,0.006,0.041,0.018,0.062,0.021c0.123,0.027,0.249,0.043,0.375,0.043c0.099,0,0.202-0.012,0.304-0.027l45.669-8.303 c0.057-0.01,0.108-0.021,0.163-0.037C79.547,88.992,79.562,89,79.575,89c0.004,0,0.004,0,0.004,0c0.021,0,0.039-0.027,0.06-0.035 c0.041-0.014,0.08-0.034,0.12-0.052c0.021-0.01,0.044-0.019,0.064-0.03c0.017-0.01,0.026-0.015,0.033-0.017 c0.014-0.008,0.023-0.021,0.037-0.028c0.14-0.078,0.269-0.174,0.38-0.285c0.014-0.016,0.024-0.034,0.038-0.048 c0.109-0.119,0.201-0.252,0.271-0.398c0.006-0.01,0.016-0.018,0.021-0.029c0.004-0.008,0.008-0.017,0.011-0.026 c0.002-0.004,0.003-0.006,0.005-0.01C80.627,88.021,80.635,88.002,80.644,87.982z M77.611,84.461L48.805,66.453l32.407-25.202 L77.611,84.461z M46.817,63.709L35.863,23.542l43.818,14.608L46.817,63.709z M84.668,40.542l8.926,5.952l-11.902,29.75 L84.668,40.542z M89.128,39.446L84.53,36.38l-6.129-12.257L89.128,39.446z M79.876,34.645L37.807,20.622L65.854,6.599L79.876,34.645 z M33.268,19.107l-6.485-2.162l23.781-6.487L33.268,19.107z M21.92,18.895l8.67,2.891L10.357,47.798L21.92,18.895z M32.652,24.649 l10.845,39.757L7.351,57.178L32.652,24.649z M43.472,67.857L32.969,92.363L8.462,60.855L43.472,67.857z M46.631,69.09l27.826,17.393 l-38.263,6.959L46.631,69.09z'></path></svg>;
}; };
+180 -70
View File
@@ -1,34 +1,38 @@
/*eslint max-lines: ["warn", {"max": 300, "skipBlankLines": true, "skipComments": true}]*/ /*eslint max-lines: ["warn", {"max": 300, "skipBlankLines": true, "skipComments": true}]*/
require('./brewRenderer.less'); import './brewRenderer.less';
const React = require('react'); import React, { useState, useRef, useMemo, useEffect } from 'react';
const { useState, useRef, useEffect, useCallback } = React; import _ from 'lodash';
const _ = require('lodash');
const MarkdownLegacy = require('naturalcrit/markdownLegacy.js'); import MarkdownLegacy from '../../../shared/markdownLegacy.js';
const Markdown = require('naturalcrit/markdown.js'); import Markdown from '../../../shared/markdown.js';
const ErrorBar = require('./errorBar/errorBar.jsx'); import ErrorBar from './errorBar/errorBar.jsx';
const ToolBar = require('./toolBar/toolBar.jsx'); import ToolBar from './toolBar/toolBar.jsx';
//TODO: move to the brew renderer //TODO: move to the brew renderer
const RenderWarnings = require('homebrewery/renderWarnings/renderWarnings.jsx'); import RenderWarnings from '../../components/renderWarnings/renderWarnings.jsx';
const NotificationPopup = require('./notificationPopup/notificationPopup.jsx'); import NotificationPopup from './notificationPopup/notificationPopup.jsx';
const Frame = require('react-frame-component').default; import Frame from 'react-frame-component';
const dedent = require('dedent-tabs').default; import dedent from 'dedent';
const { printCurrentBrew } = require('../../../shared/helpers.js'); import { printCurrentBrew } from '../../../shared/helpers.js';
const DOMPurify = require('dompurify'); import HeaderNav from './headerNav/headerNav.jsx';
const purifyConfig = { FORCE_BODY: true, SANITIZE_DOM: false }; import { safeHTML } from './safeHTML.js';
const PAGEBREAK_REGEX_V3 = /^(?=\\page(?:break)?(?: *{[^\n{}]*})?$)/m;
const PAGEBREAK_REGEX_LEGACY = /\\page(?:break)?/m;
const COLUMNBREAK_REGEX_LEGACY = /\\column(:?break)?/m;
const PAGE_HEIGHT = 1056; const PAGE_HEIGHT = 1056;
const TOOLBAR_STATE_KEY = 'HB_renderer_toolbarState';
const INITIAL_CONTENT = dedent` const INITIAL_CONTENT = dedent`
<!DOCTYPE html><html><head> <!DOCTYPE html><html><head>
<link href="//use.fontawesome.com/releases/v6.5.1/css/all.css" rel="stylesheet" type="text/css" />
<link href="//fonts.googleapis.com/css?family=Open+Sans:400,300,600,700" rel="stylesheet" type="text/css" /> <link href="//fonts.googleapis.com/css?family=Open+Sans:400,300,600,700" rel="stylesheet" type="text/css" />
<link href='/homebrew/bundle.css' type="text/css" rel='stylesheet' /> <link href='/homebrew/bundle.css' type="text/css" rel='stylesheet' />
<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 = {
@@ -36,15 +40,53 @@ const BrewPage = (props)=>{
index : 0, index : 0,
...props ...props
}; };
const cleanText = props.contents; //DOMPurify.sanitize(props.contents, purifyConfig); const pageRef = useRef(null);
return <div className={props.className} id={`p${props.index + 1}`} > const cleanText = safeHTML(props.contents);
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>;
}; };
//v=====--------------------< Brew Renderer Component >-------------------=====v// //v=====--------------------< Brew Renderer Component >-------------------=====v//
const renderedPages = []; let renderedPages = [];
let rawPages = []; let rawPages = [];
const BrewRenderer = (props)=>{ const BrewRenderer = (props)=>{
@@ -55,48 +97,64 @@ const BrewRenderer = (props)=>{
theme : '5ePHB', theme : '5ePHB',
lang : '', lang : '',
errors : [], errors : [],
currentEditorCursorPageNum : 0, currentEditorCursorPageNum : 1,
currentEditorViewPageNum : 0, currentEditorViewPageNum : 1,
currentBrewRendererPageNum : 0, currentBrewRendererPageNum : 1,
themeBundle : {}, themeBundle : {},
onPageChange : ()=>{}, onPageChange : ()=>{},
...props ...props
}; };
const [state, setState] = useState({ const [state, setState] = useState({
height : PAGE_HEIGHT, isMounted : false,
isMounted : false, visibility : 'hidden',
visibility : 'hidden', visiblePages : [],
zoom : 100 centerPage : 1
}); });
const mainRef = useRef(null); const [displayOptions, setDisplayOptions] = useState({
zoomLevel : 100,
spread : 'single',
startOnRight : true,
pageShadows : true,
rowGap : 5,
columnGap : 10,
});
if(props.renderer == 'legacy') { //useEffect to store or gather toolbar state from storage
rawPages = props.text.split('\\page'); useEffect(()=>{
} else { const toolbarState = JSON.parse(window.localStorage.getItem(TOOLBAR_STATE_KEY));
rawPages = props.text.split(/^\\page$/gm); toolbarState && setDisplayOptions(toolbarState);
}
useEffect(()=>{ // Unmounting steps
return ()=>{window.removeEventListener('resize', updateSize);};
}, []); }, []);
const updateSize = ()=>{ const [headerState, setHeaderState] = useState(false);
setState((prevState)=>({
...prevState, const mainRef = useRef(null);
height : mainRef.current.parentNode.clientHeight, const pagesRef = useRef(null);
}));
if(props.renderer == 'legacy') {
rawPages = props.text.split(PAGEBREAK_REGEX_LEGACY);
} else {
rawPages = props.text.split(PAGEBREAK_REGEX_V3);
}
const handlePageVisibilityChange = (pageNum, isVisible, isCenter)=>{
setState((prevState)=>{
const updatedVisiblePages = new Set(prevState.visiblePages);
if(!isCenter)
isVisible ? updatedVisiblePages.add(pageNum) : updatedVisiblePages.delete(pageNum);
return {
...prevState,
visiblePages : [...updatedVisiblePages].sort((a, b)=>a - b),
centerPage : isCenter ? pageNum : prevState.centerPage
};
});
if(isCenter)
props.onPageChange(pageNum);
}; };
const updateCurrentPage = useCallback(_.throttle((e)=>{
const { scrollTop, clientHeight, scrollHeight } = e.target;
const totalScrollableHeight = scrollHeight - clientHeight;
const currentPageNumber = Math.max(Math.ceil((scrollTop / totalScrollableHeight) * rawPages.length), 1);
props.onPageChange(currentPageNumber);
}, 200), []);
const isInView = (index)=>{ const isInView = (index)=>{
if(!state.isMounted) if(!state.isMounted)
return false; return false;
@@ -117,19 +175,44 @@ const BrewRenderer = (props)=>{
}; };
const renderStyle = ()=>{ const renderStyle = ()=>{
const cleanStyle = props.style; //DOMPurify.sanitize(props.style, purifyConfig);
const themeStyles = props.themeBundle?.joinedStyles ?? '<style>@import url("/themes/V3/Blank/style.css");</style>'; const themeStyles = props.themeBundle?.joinedStyles ?? '<style>@import url("/themes/V3/Blank/style.css");</style>';
return <div style={{ display: 'none' }} dangerouslySetInnerHTML={{ __html: `${themeStyles} \n\n <style> ${cleanStyle} </style>` }} />; const cleanStyle = safeHTML(`${themeStyles} \n\n <style> ${props.style} </style>`);
return <div style={{ display: 'none' }} dangerouslySetInnerHTML={{ __html: 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') {
pageText.replace(COLUMNBREAK_REGEX_LEGACY, '```\n````\n'); // Allow Legacy brews to use `\column(break)`
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
}
// DO NOT REMOVE!!! REQUIRED FOR BACKWARDS COMPATIBILITY WITH NON-UPGRADABLE VERSIONS OF CHROME.
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} />;
} }
}; };
@@ -141,7 +224,8 @@ 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
renderedPages[props.currentEditorCursorPageNum - 1] = renderPage(rawPages[props.currentEditorCursorPageNum - 1], props.currentEditorCursorPageNum - 1); if(rawPages.length > props.currentEditorCursorPageNum -1)
renderedPages[props.currentEditorCursorPageNum - 1] = renderPage(rawPages[props.currentEditorCursorPageNum - 1], props.currentEditorCursorPageNum - 1);
_.forEach(rawPages, (page, index)=>{ _.forEach(rawPages, (page, index)=>{
if((isInView(index) || !renderedPages[index]) && typeof window !== 'undefined'){ if((isInView(index) || !renderedPages[index]) && typeof window !== 'undefined'){
@@ -161,10 +245,30 @@ 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
updateSize();
window.addEventListener('resize', updateSize);
renderPages(); //Make sure page is renderable before showing renderPages(); //Make sure page is renderable before showing
setState((prevState)=>({ setState((prevState)=>({
...prevState, ...prevState,
@@ -179,19 +283,25 @@ const BrewRenderer = (props)=>{
document.dispatchEvent(new MouseEvent('click')); document.dispatchEvent(new MouseEvent('click'));
}; };
//Toolbar settings: const handleDisplayOptionsChange = (newDisplayOptions)=>{
const handleZoom = (newZoom)=>{ setDisplayOptions(newDisplayOptions);
setState((prevState)=>({ localStorage.setItem(TOOLBAR_STATE_KEY, JSON.stringify(newDisplayOptions));
...prevState,
zoom : newZoom
}));
}; };
const pagesStyle = {
zoom : `${displayOptions.zoomLevel}%`,
columnGap : `${displayOptions.columnGap}px`,
rowGap : `${displayOptions.rowGap}px`
};
const renderedStyle = useMemo(()=>renderStyle(), [props.style, props.themeBundle]);
renderedPages = useMemo(()=>renderPages(), [props.text, displayOptions]);
return ( return (
<> <>
{/*render dummy page while iFrame is mounting.*/} {/*render dummy page while iFrame is mounting.*/}
{!state.isMounted {!state.isMounted
? <div className='brewRenderer' onScroll={updateCurrentPage}> ? <div className='brewRenderer'>
<div className='pages'> <div className='pages'>
{renderDummyPage(1)} {renderDummyPage(1)}
</div> </div>
@@ -204,7 +314,7 @@ const BrewRenderer = (props)=>{
<NotificationPopup /> <NotificationPopup />
</div> </div>
<ToolBar onZoomChange={handleZoom} currentPage={props.currentBrewRendererPageNum} totalPages={rawPages.length}/> <ToolBar displayOptions={displayOptions} onDisplayOptionsChange={handleDisplayOptionsChange} visiblePages={state.visiblePages.length > 0 ? state.visiblePages : [state.centerPage]} totalPages={rawPages.length} headerState={headerState} setHeaderState={setHeaderState}/>
{/*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}
@@ -212,26 +322,26 @@ const BrewRenderer = (props)=>{
contentDidMount={frameDidMount} contentDidMount={frameDidMount}
onClick={()=>{emitClick();}} onClick={()=>{emitClick();}}
> >
<div className={'brewRenderer'} <div className='brewRenderer'
onScroll={updateCurrentPage}
onKeyDown={handleControlKeys} onKeyDown={handleControlKeys}
tabIndex={-1} tabIndex={-1}
style={{ height: state.height }}> >
{/* 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
&& &&
<> <>
{renderStyle()} {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}>
{renderPages()} {renderedPages}
</div> </div>
</> </>
} }
</div> </div>
{headerState ? <HeaderNav ref={pagesRef} /> : <></>}
</Frame> </Frame>
</> </>
); );
}; };
module.exports = BrewRenderer; export default BrewRenderer;
+53 -7
View File
@@ -1,11 +1,42 @@
@import (multiple, less) 'shared/naturalcrit/styles/reset.less'; @import (multiple, less) 'shared/naturalcrit/styles/reset.less';
.brewRenderer { .brewRenderer {
height : 100vh;
padding-top : 60px;
overflow-y : scroll; overflow-y : scroll;
will-change : transform; will-change : transform;
padding-top : 30px; &:has(.facing, .flow) { padding : 60px 30px; }
:where(.pages) { :where(.pages) {
margin : 30px 0px; &.facing {
display : grid;
grid-template-rows : repeat(3, auto);
grid-template-columns : repeat(2, 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-right : unset !important;
margin-left : unset !important;
}
}
&.flow {
display : flex;
flex-wrap : wrap;
gap : 10px;
justify-content : safe center;
& :where(.page) {
flex : 0 0 auto;
margin-right : unset !important;
margin-left : unset !important;
}
}
& > :where(.page) { & > :where(.page) {
width : 215.9mm; width : 215.9mm;
height : 279.4mm; height : 279.4mm;
@@ -14,6 +45,7 @@
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;
@@ -27,19 +59,33 @@
} }
&-corner { visibility : hidden; } &-corner { visibility : hidden; }
} }
@supports (break-after:always) {
.columnSplit {
margin-bottom: 100vh;
}
}
} }
.pane { position : relative; } .pane { position : relative; }
@media print { @media print {
.toolBar { display : none; } .toolBar { display : none; }
.brewRenderer { .brewRenderer {
height : 100%; height : 100%;
padding-top : unset; padding : unset;
overflow-y : unset; overflow-y : unset;
&:has(.facing, .flow) {
padding : unset;
}
.pages { .pages {
margin : 0px; margin : 0px;
zoom : 100% !important;
display : block;
& > .page { box-shadow : unset; } & > .page { box-shadow : unset; }
} }
} }
} .headerNav { visibility : hidden; }
}
@@ -1,75 +1,53 @@
require('./errorBar.less'); import './errorBar.less';
const React = require('react'); import React from 'react';
const createClass = require('create-react-class');
const _ = require('lodash');
const ErrorBar = createClass({ import Dialog from '../../../components/dialog.jsx';
displayName : 'ErrorBar',
getDefaultProps : function() {
return {
errors : []
};
},
hasOpenError : false, const DISMISS_BUTTON = <i className='fas fa-times dismiss' />;
hasCloseError : false,
hasMatchError : false,
renderErrors : function(){ const ErrorBar = (props)=>{
this.hasOpenError = false; if(!props.errors.length) return null;
this.hasCloseError = false; let hasOpenError = false, hasCloseError = false, hasMatchError = 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 errors = _.map(this.props.errors, (err, idx)=>{ const renderErrors = ()=>(
if(err.id == 'OPEN') this.hasOpenError = true; <ul>
if(err.id == 'CLOSE') this.hasCloseError = true; {props.errors.map((err, idx)=>{
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>
);
return <ul>{errors}</ul>; const renderProtip = ()=>(
}, <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>
{msg} {hasOpenError && <div>Unmatched opening tag. Close your tags, like this {'</div>'}. Match types!</div>}
</div>; {hasCloseError && <div>Unmatched closing tag. Either remove it or check where it was opened.</div>}
}, {hasMatchError && <div>Type mismatch. Closed a tag with a different type.</div>}
</div>
);
render : function(){ return (
if(!this.props.errors.length) return null; <Dialog className='errorBar' closeText={DISMISS_BUTTON} >
<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 />
{this.renderProtip()} {renderProtip()}
</div>; </Dialog>
} );
}); };
module.exports = ErrorBar; export default ErrorBar;
@@ -1,60 +1,58 @@
.errorBar{ .errorBar {
position : absolute; position : absolute;
z-index : 10000; top : 32px;
box-sizing : border-box; z-index : 1;
width : 100%; width : 100%;
margin-right : 13px;
padding : 20px;
padding-bottom : 10px;
padding-left : 100px;
background-color : @red;
color : white; color : white;
i{ background-color : @red;
position : absolute; border : unset;
left : 30px;
opacity : 0.8; div {
font-size : 3em; > i {
} float : left;
h3{ margin-right : 10px;
font-size : 1.1em; margin-bottom : 20px;
font-weight : 800; font-size : 3em;
} opacity : 0.8;
ul{ }
margin-top : 15px; h2 { font-weight : 800; }
font-size : 0.8em; ul {
list-style-position : inside; margin-top : 15px;
list-style-type : disc; font-size : 0.8em;
li{ list-style-position : inside;
line-height : 1.6em; list-style-type : disc;
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;
} }
small{ small {
font-size: 0.6em; font-size : 0.6em;
opacity: 0.7; opacity : 0.7;
} }
.protips{ .protips {
margin-left : -80px; font-size : 0.6em;
font-size : 0.6em; line-height : 1.2em;
&>div{ h4 {
margin-bottom : 10px;
line-height : 1.2em;
}
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; }
}
} }
@@ -0,0 +1,113 @@
import './headerNav.less';
import React from 'react';
import _ from 'lodash';
const MAX_TEXT_LENGTH = 40;
const HeaderNav = React.forwardRef(({}, pagesRef)=>{
const renderHeaderLinks = ()=>{
if(!pagesRef.current) return;
// Top Level Pages
// Pages that contain an element with a specified class (e.g. cover pages, table of contents)
// will NOT have its content scanned for navigation headers, instead displaying a custom label
// ---
// The property name is class that will be used for detecting the page is a top level page
// The property value is a function that returns the text to be used
const topLevelPages = {
'.frontCover' : (el, pageType)=>{ const text = getHeaderContent(el); return text ? `Cover: ${text}` : 'Cover Page'; },
'.insideCover' : (el, pageType)=>{ const text = getHeaderContent(el); return text ? `Interior: ${text}` : 'Interior Cover Page'; },
'.partCover' : (el, pageType)=>{ const text = getHeaderContent(el); return text ? `Section: ${text}` : 'Section Cover Page'; },
'.backCover' : (el, pageType)=>{ const text = getHeaderContent(el); return text ? `Back: ${text}` : 'Rear Cover Page'; },
'.toc' : ()=>{ return 'Table of Contents'; },
};
const getHeaderContent = (el)=>el.querySelector('h1')?.textContent;
const topLevelPageSelector = Object.keys(topLevelPages).join(',');
const selector = [
'.pages > .page', // All page elements, which by definition have IDs
`.page:not(:has(${topLevelPageSelector})) > [id]`, // All direct children of non-excluded .pages with an ID (Legacy)
`.page:not(:has(${topLevelPageSelector})) > .columnWrapper > [id]`, // All direct children of non-excluded .page > .columnWrapper with an ID (V3)
`.page:not(:has(${topLevelPageSelector})) h2`, // All non-excluded 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)=>{
const navEntry = { // Default structure of a navList entry
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
};
if(el.classList.contains('page')) {
let text = `Page ${el.id.slice(1)}`; // Get the page # by trimming off the 'p' from the ID
const pageType = Object.keys(topLevelPages).find((pageType)=>el.querySelector(pageType));
if(pageType)
text += ` - ${topLevelPages[pageType](el, pageType)}`; // If a Top Level Page, add extra label
navEntry.depth = 0; // Pages are always at the least indented level
navEntry.text = text;
navEntry.className = 'pageLink';
} else if(el.localName.match(/^h[1-6]/)){ // Header elements H1 through H6
navEntry.depth = el.localName[1]; // Depth is set by the header level
}
navList.push(navEntry);
});
return _.map(navList, (navItem, index)=><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;
@@ -0,0 +1,39 @@
.headerNav {
position : fixed;
top : 32px;
left : 0px;
max-width : 40vw;
max-height : calc(100vh - 32px);
padding : 5px 10px;
overflow-y : auto;
background-color : #CCCCCC;
border-radius : 5px;
&.active {
padding-bottom : 10px;
.navIcon { padding-bottom : 10px; }
}
.navIcon { cursor : pointer; }
li {
list-style-type : none;
a {
display : inline-block;
width : 100%;
padding : 2px;
font-family : 'Open Sans';
font-size : 12px;
color : inherit;
text-decoration : none;
cursor : pointer;
&:hover { text-decoration : underline; }
&.pageLink { font-weight : 900; }
@depths: 0,1,2,3,4,5,6,7;
each(@depths, {
&.depth-@{value} {
padding-left: ((@value) * 0.5em);
}
});
}
}
}
@@ -1,46 +1,65 @@
require('./notificationPopup.less'); import './notificationPopup.less';
const React = require('react'); import React, { useEffect, useState } from 'react';
const _ = require('lodash'); import request from '../../utils/request-middleware.js';
import Markdown from 'markdown.js';
import Dialog from '../../../components/dialog.jsx'; import Dialog from '../../../components/dialog.jsx';
const DISMISS_KEY = 'dismiss_notification04-09-24';
const DISMISS_BUTTON = <i className='fas fa-times dismiss' />; const DISMISS_BUTTON = <i className='fas fa-times dismiss' />;
const NotificationPopup = ()=>{ const NotificationPopup = ()=>{
return <Dialog className='notificationPopup' dismissKey={DISMISS_KEY} closeText={DISMISS_BUTTON} > const [notifications, setNotifications] = useState([]);
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: Markdown.render(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>
<li key='Vault'> {renderNotificationsList()}
<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>;
}; };
module.exports = NotificationPopup; export default NotificationPopup;
@@ -48,14 +48,46 @@
} }
ul { ul {
margin-top : 15px; margin-top : 15px;
font-size : 0.8em; font-size : 0.9em;
list-style-position : outside; list-style-position : outside;
list-style-type : disc; list-style-type : disc;
li { li {
margin-top : 1.4em; padding-left : 1em;
font-size : 0.8em; margin-top : 1.5em;
line-height : 1.4em; font-size : 0.9em;
em { font-weight : 800; } line-height : 1.5em;
em {
font-weight : 800;
text-transform : capitalize;
}
li {
margin-top : 0;
line-height : 1.2em;
list-style-type : square;
}
}
ul ul,ol ol,ul ol,ol ul {
margin-bottom : 0px;
margin-left : 1.5em;
} }
} }
}
/* Markdown styling */
code {
padding : 0.1em 0.5em;
font-family : 'Courier New', 'Courier', monospace;
overflow-wrap : break-word;
white-space : pre-wrap;
background : #08115A;
border-radius : 2px;
}
pre code {
display : inline-block;
width : 100%;
}
.blank {
height : 1em;
margin-top : 0;
& + * { margin-top : 0; }
}
}
+46
View File
@@ -0,0 +1,46 @@
// 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;
+132 -35
View File
@@ -1,28 +1,38 @@
require('./toolBar.less'); /* eslint-disable max-lines */
const React = require('react'); import './toolBar.less';
const { useState, useEffect } = React; import React, { useState, useEffect } from 'react';
const _ = require('lodash'); import _ from '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 = ({ onZoomChange, currentPage, onPageChange, totalPages })=>{ const TOOLBAR_VISIBILITY = 'HB_renderer_toolbarVisibility';
const [zoomLevel, setZoomLevel] = useState(100); const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPages, headerState, setHeaderState })=>{
const [pageNum, setPageNum] = useState(currentPage);
const [pageNum, setPageNum] = useState(1);
const [toolsVisible, setToolsVisible] = useState(true); const [toolsVisible, setToolsVisible] = useState(true);
useEffect(()=>{ useEffect(()=>{
onZoomChange(zoomLevel); // format multiple visible pages as a range (e.g. "150-153")
}, [zoomLevel]); const pageRange = visiblePages.length === 1 ? `${visiblePages[0]}` : `${visiblePages[0]} - ${visiblePages.at(-1)}`;
setPageNum(pageRange);
}, [visiblePages]);
useEffect(()=>{ useEffect(()=>{
setPageNum(currentPage); const Visibility = localStorage.getItem(TOOLBAR_VISIBILITY);
}, [currentPage]); if(Visibility) setToolsVisible(Visibility === 'true');
}, []);
const handleZoomButton = (zoom)=>{ const handleZoomButton = (zoom)=>{
setZoomLevel(_.round(_.clamp(zoom, MIN_ZOOM, MAX_ZOOM))); handleOptionChange('zoomLevel', _.round(_.clamp(zoom, MIN_ZOOM, MAX_ZOOM)));
};
const handleOptionChange = (optionKey, newValue)=>{
onDisplayOptionsChange({ ...displayOptions, [optionKey]: newValue });
}; };
const handlePageInput = (pageInput)=>{ const handlePageInput = (pageInput)=>{
@@ -30,16 +40,16 @@ const ToolBar = ({ onZoomChange, currentPage, onPageChange, totalPages })=>{
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;
@@ -52,58 +62,87 @@ const ToolBar = ({ onZoomChange, currentPage, onPageChange, totalPages })=>{
// find widest page, in case pages are different widths, so that the zoom is adapted to not cut the widest page off screen. // find widest page, in case pages are different widths, so that the zoom is adapted to not cut the widest page off screen.
const widestPage = _.maxBy([...pages], 'offsetWidth').offsetWidth; const widestPage = _.maxBy([...pages], 'offsetWidth').offsetWidth;
desiredZoom = (iframeWidth / widestPage) * 100; if(displayOptions.spread === 'facing')
desiredZoom = (iframeWidth / ((widestPage * 2) + parseInt(displayOptions.columnGap))) * 100;
else
desiredZoom = (iframeWidth / (widestPage + 20)) * 100;
} else if(mode == 'fit'){ } else if(mode == 'fit'){
// 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.
const minDimRatio = [...pages].reduce((minRatio, page)=>Math.min(minRatio, iframeWidth / page.offsetWidth, iframeHeight / page.offsetHeight), Infinity); let minDimRatio;
if(displayOptions.spread === 'single')
minDimRatio = [...pages].reduce(
(minRatio, page)=>Math.min(minRatio,
iframeWidth / page.offsetWidth,
iframeHeight / page.offsetHeight
),
Infinity
);
else
minDimRatio = [...pages].reduce(
(minRatio, page)=>Math.min(minRatio,
iframeWidth / ((page.offsetWidth * 2) + parseInt(displayOptions.columnGap)),
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 - zoomLevel) - margin; const deltaZoom = (desiredZoom - displayOptions.zoomLevel) - margin;
return deltaZoom; return deltaZoom;
}; };
return ( return (
<div className={`toolBar ${toolsVisible ? 'visible' : 'hidden'}`}> <div id='preview-toolbar' className={`toolBar ${toolsVisible ? 'visible' : 'hidden'}`} role='toolbar'>
<button className='toggleButton' title={`${toolsVisible ? 'Hide' : 'Show'} Preview Toolbar`} onClick={()=>{setToolsVisible(!toolsVisible);}}><i className='fas fa-glasses' /></button> <div className='toggleButton'>
<button title={`${toolsVisible ? 'Hide' : 'Show'} Preview Toolbar`} onClick={()=>{
setToolsVisible(!toolsVisible);
localStorage.setItem(TOOLBAR_VISIBILITY, !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'> <div className='group' role='group' aria-label='Zoom' aria-hidden={!toolsVisible}>
<button <button
id='fill-width' id='fill-width'
className='tool' className='tool'
onClick={()=>handleZoomButton(zoomLevel + calculateChange('fill'))} title='Set zoom to fill preview with one page'
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'
onClick={()=>handleZoomButton(zoomLevel + calculateChange('fit'))} title='Set zoom to fit entire page in preview'
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(zoomLevel - 20)} onClick={()=>handleZoomButton(displayOptions.zoomLevel - 20)}
disabled={zoomLevel <= MIN_ZOOM} disabled={displayOptions.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' className='range-input tool hover-tooltip'
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={zoomLevel} value={displayOptions.zoomLevel}
onChange={(e)=>handleZoomButton(parseInt(e.target.value))} onChange={(e)=>handleZoomButton(parseInt(e.target.value))}
/> />
<datalist id='zoomLevels'> <datalist id='zoomLevels'>
@@ -113,20 +152,74 @@ const ToolBar = ({ onZoomChange, currentPage, onPageChange, totalPages })=>{
<button <button
id='zoom-in' id='zoom-in'
className='tool' className='tool'
onClick={()=>handleZoomButton(zoomLevel + 20)} onClick={()=>handleZoomButton(displayOptions.zoomLevel + 20)}
disabled={zoomLevel >= MAX_ZOOM} disabled={displayOptions.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', 'single');}}
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={displayOptions.columnGap || 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={displayOptions.rowGap || 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'> <div className='group' role='group' aria-label='Pages' aria-hidden={!toolsVisible}>
<button <button
id='previous-page' id='previous-page'
className='previousPage tool' className='previousPage tool'
onClick={()=>scrollToPage(pageNum - 1)} type='button'
disabled={pageNum <= 1} title='Previous Page(s)'
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>
@@ -137,6 +230,7 @@ const ToolBar = ({ onZoomChange, currentPage, onPageChange, totalPages })=>{
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}
@@ -144,15 +238,18 @@ const ToolBar = ({ onZoomChange, currentPage, onPageChange, totalPages })=>{
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'>/ {totalPages}</span> <span id='page-count' title='Total Page Count'>/ {totalPages}</span>
</div> </div>
<button <button
id='next-page' id='next-page'
className='tool' className='tool'
onClick={()=>scrollToPage(pageNum + 1)} type='button'
disabled={pageNum >= totalPages} title='Next Page(s)'
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>
@@ -161,4 +258,4 @@ const ToolBar = ({ onZoomChange, currentPage, onPageChange, totalPages })=>{
); );
}; };
module.exports = ToolBar; export default ToolBar;
@@ -6,18 +6,19 @@
box-sizing : border-box; box-sizing : border-box;
display : flex; display : flex;
flex-wrap : wrap; flex-wrap : wrap;
gap : 8px 30px; gap : 8px 20px;
align-items : center; align-items : center;
justify-content : center; justify-content : center;
width : 100%; width : 100%;
height : auto; height : auto;
padding : 2px 0; padding : 2px 10px 2px 90px;
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 .2s ease; transition : all 0.2s ease;
} }
.group { .group {
@@ -34,14 +35,78 @@
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 : #000000; color : inherit;
background : #EEEEEE; background : #3B3B3B;
border : 1px solid gray; border : none;
&: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
@@ -50,14 +115,14 @@
color : #D3D3D3; color : #D3D3D3;
accent-color : #D3D3D3; accent-color : #D3D3D3;
&::-webkit-slider-thumb, &::-moz-slider-thumb { &::-webkit-slider-thumb, &::-moz-range-thumb {
width : 5px; width : 5px;
height : 5px; height : 5px;
cursor : pointer; cursor : ew-resize;
outline : none; outline : none;
} }
&:hover::after { &.hover-tooltip[value]:hover::after {
position : absolute; position : absolute;
bottom : -30px; bottom : -30px;
left : 50%; left : 50%;
@@ -76,53 +141,51 @@
// `.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 {
width : 4ch; min-width : 5ch;
margin-right : 1ch; margin-right : 1ch;
text-align : center; text-align : center;
} }
} }
button { button {
box-sizing : content-box; box-sizing : border-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 : 40px;
height : 100%; height : 100%;
padding : 0 0px;
font-weight : unset;
color : inherit;
background-color : unset;
&:hover { background-color : #444444; } &:hover { background-color : #444444; }
&:focus { outline : 1px solid #D3D3D3; } &:focus {outline : none; border : 1px solid #D3D3D3;}
&:disabled { &:disabled {
color : #777777; color : #777777;
background-color : unset !important; background-color : unset !important;
} }
i { i { font-size : 1.2em; }
font-size:1.2em;
}
} }
&.hidden { &.hidden {
width: 32px; flex-wrap : nowrap;
transition: all .3s ease; width : 92px;
flex-wrap:nowrap; overflow : hidden;
overflow: hidden; background-color : unset;
background-color: unset; opacity : 0.7;
opacity: .5; transition : all 0.3s ease;
& > *:not(.toggleButton) { & > *:not(.toggleButton) {
opacity: 0; opacity : 0;
transition: all .2s ease; transition : all 0.2s ease;
}
.toggleButton button i {
filter: drop-shadow(0 0 2px black) drop-shadow(0 0 1px black);
} }
} }
} }
button.toggleButton { .toggleButton {
z-index : 5; position : absolute;
position:absolute; left : 0;
left: 0; z-index : 5;
width: 32px; display : flex;
min-width: unset; height : 100%;
} }
+132 -98
View File
@@ -1,18 +1,19 @@
/*eslint max-lines: ["warn", {"max": 500, "skipBlankLines": true, "skipComments": true}]*/ /*eslint max-lines: ["warn", {"max": 500, "skipBlankLines": true, "skipComments": true}]*/
require('./editor.less'); import './editor.less';
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const _ = require('lodash'); import _ from 'lodash';
const dedent = require('dedent-tabs').default; import dedent from 'dedent';
const Markdown = require('../../../shared/naturalcrit/markdown.js'); import Markdown from '../../../shared/markdown.js';
const CodeEditor = require('naturalcrit/codeEditor/codeEditor.jsx'); import CodeEditor from '../../components/codeEditor/codeEditor.jsx';
const SnippetBar = require('./snippetbar/snippetbar.jsx'); import SnippetBar from './snippetbar/snippetbar.jsx';
const MetadataEditor = require('./metadataEditor/metadataEditor.jsx'); import MetadataEditor from './metadataEditor/metadataEditor.jsx';
const EDITOR_THEME_KEY = 'HOMEBREWERY-EDITOR-THEME'; const EDITOR_THEME_KEY = 'HB_editor_theme';
const SNIPPETBAR_HEIGHT = 25; const PAGEBREAK_REGEX_V3 = /^(?=\\page(?:break)?(?: *{[^\n{}]*})?$)/m;
const SNIPPETBREAK_REGEX_V3 = /^\\snippet\ .*$/;
const DEFAULT_STYLE_TEXT = dedent` const DEFAULT_STYLE_TEXT = dedent`
/*=======--- Example CSS styling ---=======*/ /*=======--- Example CSS styling ---=======*/
/* Any CSS here will apply to your document! */ /* Any CSS here will apply to your document! */
@@ -21,9 +22,16 @@ const DEFAULT_STYLE_TEXT = dedent`
color: black; color: black;
}`; }`;
const DEFAULT_SNIPPET_TEXT = dedent`
\snippet example snippet
The text between \`\snippet title\` lines will become a snippet of name \`title\` as this example provides.
This snippet is accessible in the brew tab, and will be inherited if the brew is used as a theme.
`;
let isJumping = false; let isJumping = false;
const Editor = createClass({ const Editor = createReactClass({
displayName : 'Editor', displayName : 'Editor',
getDefaultProps : function() { getDefaultProps : function() {
return { return {
@@ -32,10 +40,8 @@ const Editor = createClass({
style : '' style : ''
}, },
onTextChange : ()=>{}, onBrewChange : ()=>{},
onStyleChange : ()=>{}, reportError : ()=>{},
onMetaChange : ()=>{},
reportError : ()=>{},
onCursorPageChange : ()=>{}, onCursorPageChange : ()=>{},
onViewPageChange : ()=>{}, onViewPageChange : ()=>{},
@@ -50,8 +56,9 @@ const Editor = createClass({
}, },
getInitialState : function() { getInitialState : function() {
return { return {
editorTheme : this.props.editorTheme, editorTheme : this.props.editorTheme,
view : 'text' //'text', 'style', 'meta' view : 'text', //'text', 'style', 'meta', 'snippet'
snippetBarHeight : 26,
}; };
}, },
@@ -61,17 +68,16 @@ const Editor = createClass({
isText : function() {return this.state.view == 'text';}, isText : function() {return this.state.view == 'text';},
isStyle : function() {return this.state.view == 'style';}, isStyle : function() {return this.state.view == 'style';},
isMeta : function() {return this.state.view == 'meta';}, isMeta : function() {return this.state.view == 'meta';},
isSnip : function() {return this.state.view == 'snippet';},
componentDidMount : function() { componentDidMount : function() {
this.updateEditorSize();
this.highlightCustomMarkdown(); this.highlightCustomMarkdown();
window.addEventListener('resize', this.updateEditorSize);
document.getElementById('BrewRenderer').addEventListener('keydown', this.handleControlKeys); document.getElementById('BrewRenderer').addEventListener('keydown', this.handleControlKeys);
document.addEventListener('keydown', this.handleControlKeys); document.addEventListener('keydown', this.handleControlKeys);
this.codeEditor.current.codeMirror.on('cursorActivity', (cm)=>{this.updateCurrentCursorPage(cm.getCursor());}); this.codeEditor.current.codeMirror?.on('cursorActivity', (cm)=>{this.updateCurrentCursorPage(cm.getCursor());});
this.codeEditor.current.codeMirror.on('scroll', _.throttle(()=>{this.updateCurrentViewPage(this.codeEditor.current.getTopVisibleLine());}, 200)); this.codeEditor.current.codeMirror?.on('scroll', _.throttle(()=>{this.updateCurrentViewPage(this.codeEditor.current.getTopVisibleLine());}, 200));
const editorTheme = window.localStorage.getItem(EDITOR_THEME_KEY); const editorTheme = window.localStorage.getItem(EDITOR_THEME_KEY);
if(editorTheme) { if(editorTheme) {
@@ -79,10 +85,15 @@ const Editor = createClass({
editorTheme : editorTheme editorTheme : editorTheme
}); });
} }
}, const snippetBar = document.querySelector('.editor > .snippetBar');
if (!snippetBar) return;
componentWillUnmount : function() { this.resizeObserver = new ResizeObserver(entries => {
window.removeEventListener('resize', this.updateEditorSize); const height = document.querySelector('.editor > .snippetBar').offsetHeight;
this.setState({ snippetBarHeight: height });
});
this.resizeObserver.observe(snippetBar);
}, },
componentDidUpdate : function(prevProps, prevState, snapshot) { componentDidUpdate : function(prevProps, prevState, snapshot) {
@@ -105,6 +116,10 @@ const Editor = createClass({
} }
}, },
componentWillUnmount() {
if (this.resizeObserver) this.resizeObserver.disconnect();
},
handleControlKeys : function(e){ handleControlKeys : function(e){
if(!(e.ctrlKey && e.metaKey && e.shiftKey)) return; if(!(e.ctrlKey && e.metaKey && e.shiftKey)) return;
const LEFTARROW_KEY = 37; const LEFTARROW_KEY = 37;
@@ -117,24 +132,16 @@ const Editor = createClass({
} }
}, },
updateEditorSize : function() {
if(this.codeEditor.current) {
let paneHeight = this.editor.current.parentNode.clientHeight;
paneHeight -= SNIPPETBAR_HEIGHT;
this.codeEditor.current.codeMirror.setSize(null, paneHeight);
}
},
updateCurrentCursorPage : function(cursor) { updateCurrentCursorPage : function(cursor) {
const lines = this.props.brew.text.split('\n').slice(0, cursor.line + 1); const lines = this.props.brew.text.split('\n').slice(1, cursor.line + 1);
const pageRegex = this.props.brew.renderer == 'V3' ? /^\\page$/ : /\\page/; const pageRegex = this.props.brew.renderer == 'V3' ? PAGEBREAK_REGEX_V3 : /\\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(0, topScrollLine + 1); const lines = this.props.brew.text.split('\n').slice(1, topScrollLine + 1);
const pageRegex = this.props.brew.renderer == 'V3' ? /^\\page$/ : /\\page/; const pageRegex = this.props.brew.renderer == 'V3' ? PAGEBREAK_REGEX_V3 : /\\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);
}, },
@@ -145,25 +152,25 @@ const Editor = createClass({
handleViewChange : function(newView){ handleViewChange : function(newView){
this.props.setMoveArrows(newView === 'text'); this.props.setMoveArrows(newView === 'text');
this.setState({ this.setState({
view : newView view : newView
}, ()=>{ }, ()=>{
this.codeEditor.current?.codeMirror.focus(); this.codeEditor.current?.codeMirror?.focus();
this.updateEditorSize(); });
}); //TODO: not sure if updateeditorsize needed
}, },
highlightCustomMarkdown : function(){ highlightCustomMarkdown : function(){
if(!this.codeEditor.current) return; if(!this.codeEditor.current?.codeMirror) return;
if(this.state.view === 'text') { if((this.state.view === 'text') ||(this.state.view === 'snippet')) {
const codeMirror = this.codeEditor.current.codeMirror; const codeMirror = this.codeEditor.current.codeMirror;
codeMirror.operation(()=>{ // Batch CodeMirror styling codeMirror?.operation(()=>{ // Batch CodeMirror styling
const foldLines = []; const foldLines = [];
//reset custom text styles //reset custom text styles
const customHighlights = codeMirror.getAllMarks().filter((mark)=>{ const customHighlights = codeMirror?.getAllMarks().filter((mark)=>{
// Record details of folded sections // Record details of folded sections
if(mark.__isFold) { if(mark.__isFold) {
const fold = mark.find(); const fold = mark.find();
@@ -174,14 +181,20 @@ 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 = 2; // start page count from page 2 let userSnippetCount = 1; // start snippet count from snippet 1
let editorPageCount = 1; // start page count from page 1
_.forEach(this.props.brew.text.split('\n'), (line, lineNumber)=>{ const whichSource = this.state.view === 'text' ? this.props.brew.text : this.props.brew.snippets;
_.forEach(whichSource?.split('\n'), (line, lineNumber)=>{
const tabHighlight = this.state.view === 'text' ? 'pageLine' : 'snippetLine';
const textOrSnip = this.state.view === 'text';
//reset custom line styles //reset custom line styles
codeMirror.removeLineClass(lineNumber, 'background', 'pageLine'); codeMirror?.removeLineClass(lineNumber, 'background', 'pageLine');
codeMirror.removeLineClass(lineNumber, 'text'); codeMirror?.removeLineClass(lineNumber, 'background', 'snippetLine');
codeMirror.removeLineClass(lineNumber, 'wrap', 'sourceMoveFlash'); codeMirror?.removeLineClass(lineNumber, 'text');
codeMirror?.removeLineClass(lineNumber, 'wrap', 'sourceMoveFlash');
// Don't process lines inside folded text // Don't process lines inside folded text
// If the current lineNumber is inside any folded marks, skip line styling // If the current lineNumber is inside any folded marks, skip line styling
@@ -190,23 +203,26 @@ 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(/^\\page$/))) { (this.props.renderer == 'V3' && line.match(textOrSnip ? PAGEBREAK_REGEX_V3 : SNIPPETBREAK_REGEX_V3))) {
if((lineNumber > 0) && (textOrSnip)) // Since \page is optional on first line of document,
editorPageCount += 1; // don't use it to increment page count; stay at 1
else if(this.state.view !== 'text') userSnippetCount += 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', tabHighlight);
const pageCountElement = Object.assign(document.createElement('span'), { const pageCountElement = Object.assign(document.createElement('span'), {
className : 'editor-page-count', className : 'editor-page-count',
textContent : editorPageCount textContent : textOrSnip ? editorPageCount : userSnippetCount
}); });
codeMirror.setBookmark({ line: lineNumber, ch: line.length }, pageCountElement); codeMirror?.setBookmark({ line: lineNumber, ch: line.length }, pageCountElement);
editorPageCount += 1;
}; };
// New Codemirror styling for V3 renderer
if(this.props.renderer == 'V3') { // New CodeMirror styling for V3 renderer
if(line.match(/^\\column$/)){ if(this.props.renderer === 'V3') {
codeMirror.addLineClass(lineNumber, 'text', 'columnSplit'); if(line.match(/^\\column(?:break)?$/)){
codeMirror?.addLineClass(lineNumber, 'text', 'columnSplit');
} }
// definition lists // definition lists
@@ -215,14 +231,14 @@ const Editor = createClass({
const regex = /^([^\n]*?:?\s?)(::[^\n]*)(?:\n|$)/ymd; // the `d` flag, for match indices, throws an ESLint error. const regex = /^([^\n]*?:?\s?)(::[^\n]*)(?:\n|$)/ymd; // the `d` flag, for match indices, throws an ESLint error.
let match; let match;
while ((match = regex.exec(line)) != null){ while ((match = regex.exec(line)) != null){
codeMirror.markText({ line: lineNumber, ch: match.indices[0][0] }, { line: lineNumber, ch: match.indices[0][1] }, { className: 'dl-highlight' }); codeMirror?.markText({ line: lineNumber, ch: match.indices[0][0] }, { line: lineNumber, ch: match.indices[0][1] }, { className: 'dl-highlight' });
codeMirror.markText({ line: lineNumber, ch: match.indices[1][0] }, { line: lineNumber, ch: match.indices[1][1] }, { className: 'dt-highlight' }); codeMirror?.markText({ line: lineNumber, ch: match.indices[1][0] }, { line: lineNumber, ch: match.indices[1][1] }, { className: 'dt-highlight' });
codeMirror.markText({ line: lineNumber, ch: match.indices[2][0] }, { line: lineNumber, ch: match.indices[2][1] }, { className: 'dd-highlight' }); codeMirror?.markText({ line: lineNumber, ch: match.indices[2][0] }, { line: lineNumber, ch: match.indices[2][1] }, { className: 'dd-highlight' });
const ddIndex = match.indices[2][0]; const ddIndex = match.indices[2][0];
const colons = /::/g; const colons = /::/g;
const colonMatches = colons.exec(match[2]); const colonMatches = colons.exec(match[2]);
if(colonMatches !== null){ if(colonMatches !== null){
codeMirror.markText({ line: lineNumber, ch: colonMatches.index + ddIndex }, { line: lineNumber, ch: colonMatches.index + colonMatches[0].length + ddIndex }, { className: 'dl-colon-highlight' }); codeMirror?.markText({ line: lineNumber, ch: colonMatches.index + ddIndex }, { line: lineNumber, ch: colonMatches.index + colonMatches[0].length + ddIndex }, { className: 'dl-colon-highlight' });
} }
} }
} }
@@ -239,7 +255,7 @@ const Editor = createClass({
const match = subRegex.exec(line) || superRegex.exec(line); const match = subRegex.exec(line) || superRegex.exec(line);
if(match) { if(match) {
isSuper = !subRegex.lastIndex; isSuper = !subRegex.lastIndex;
codeMirror.markText({ line: lineNumber, ch: match.index }, { line: lineNumber, ch: match.index + match[0].length }, { className: isSuper ? 'superscript' : 'subscript' }); codeMirror?.markText({ line: lineNumber, ch: match.index }, { line: lineNumber, ch: match.index + match[0].length }, { className: isSuper ? 'superscript' : 'subscript' });
} }
startIndex = line.indexOf('^', Math.max(startIndex + 1, subRegex.lastIndex, superRegex.lastIndex)); startIndex = line.indexOf('^', Math.max(startIndex + 1, subRegex.lastIndex, superRegex.lastIndex));
} }
@@ -250,7 +266,7 @@ const Editor = createClass({
const regex = /(?:^|[^{\n])({(?=((?:[:=](?:"[\w,\-()#%. ]*"|[\w\-()#%.]*)|[^"':={}\s]*)*))\2})/gm; const regex = /(?:^|[^{\n])({(?=((?:[:=](?:"[\w,\-()#%. ]*"|[\w\-()#%.]*)|[^"':={}\s]*)*))\2})/gm;
let match; let match;
while ((match = regex.exec(line)) != null) { while ((match = regex.exec(line)) != null) {
codeMirror.markText({ line: lineNumber, ch: line.indexOf(match[1]) }, { line: lineNumber, ch: line.indexOf(match[1]) + match[1].length }, { className: 'injection' }); codeMirror?.markText({ line: lineNumber, ch: line.indexOf(match[1]) }, { line: lineNumber, ch: line.indexOf(match[1]) + match[1].length }, { className: 'injection' });
} }
} }
// Highlight inline spans {{content}} // Highlight inline spans {{content}}
@@ -268,7 +284,7 @@ const Editor = createClass({
blockCount = 0; blockCount = 0;
continue; continue;
} }
codeMirror.markText({ line: lineNumber, ch: match.index }, { line: lineNumber, ch: match.index + match[0].length }, { className: 'inline-block' }); codeMirror?.markText({ line: lineNumber, ch: match.index }, { line: lineNumber, ch: match.index + match[0].length }, { className: 'inline-block' });
} }
} else if(line.trimLeft().startsWith('{{') || line.trimLeft().startsWith('}}')){ } else if(line.trimLeft().startsWith('{{') || line.trimLeft().startsWith('}}')){
// Highlight block divs {{\n Content \n}} // Highlight block divs {{\n Content \n}}
@@ -277,7 +293,7 @@ const Editor = createClass({
const match = line.match(/^ *{{(?=((?:[:=](?:"[\w,\-()#%. ]*"|[\w\-()#%.]*)|[^"':={}\s]*)*))\1 *$|^ *}}$/); const match = line.match(/^ *{{(?=((?:[:=](?:"[\w,\-()#%. ]*"|[\w\-()#%.]*)|[^"':={}\s]*)*))\1 *$|^ *}}$/);
if(match) if(match)
endCh = match.index+match[0].length; endCh = match.index+match[0].length;
codeMirror.markText({ line: lineNumber, ch: 0 }, { line: lineNumber, ch: endCh }, { className: 'block' }); codeMirror?.markText({ line: lineNumber, ch: 0 }, { line: lineNumber, ch: endCh }, { className: 'block' });
} }
// Emojis // Emojis
@@ -298,11 +314,11 @@ const Editor = createClass({
const endPos = { line: lineNumber, ch: match.index + match[0].length }; const endPos = { line: lineNumber, ch: match.index + match[0].length };
// Iterate over conflicting marks and clear them // Iterate over conflicting marks and clear them
const marks = codeMirror.findMarks(startPos, endPos); const marks = codeMirror?.findMarks(startPos, endPos);
marks.forEach(function(marker) { marks.forEach(function(marker) {
if(!marker.__isFold) marker.clear(); if(!marker.__isFold) marker.clear();
}); });
codeMirror.markText(startPos, endPos, { className: 'emoji' }); codeMirror?.markText(startPos, endPos, { className: 'emoji' });
} }
startIndex = line.indexOf(':', Math.max(startIndex + 1, emojiRegex.lastIndex)); startIndex = line.indexOf(':', Math.max(startIndex + 1, emojiRegex.lastIndex));
} }
@@ -314,17 +330,17 @@ const Editor = createClass({
}, },
brewJump : function(targetPage=this.props.currentEditorCursorPageNum, smooth=true){ brewJump : function(targetPage=this.props.currentEditorCursorPageNum, smooth=true){
if(!window || isJumping) if(!window || !this.isText() || isJumping)
return; return;
// Get current brewRenderer scroll position and calculate target position // Get current brewRenderer scroll position and calculate target position
const brewRenderer = window.frames['BrewRenderer'].contentDocument.getElementsByClassName('brewRenderer')[0]; const brewRenderer = window.frames['BrewRenderer'].contentDocument.getElementsByClassName('brewRenderer')[0];
const currentPos = brewRenderer.scrollTop; const currentPos = brewRenderer.scrollTop;
const targetPos = window.frames['BrewRenderer'].contentDocument.getElementById(`p${targetPage}`).getBoundingClientRect().top; const targetPos = window.frames['BrewRenderer'].contentDocument.getElementById(`p${targetPage}`).getBoundingClientRect().top;
const checkIfScrollComplete = ()=>{ let scrollingTimeout;
let scrollingTimeout; const checkIfScrollComplete = ()=>{ // Prevent interrupting a scroll in progress if user clicks multiple times
clearTimeout(scrollingTimeout); // Reset the timer every time a scroll event occurs clearTimeout(scrollingTimeout); // Reset the timer every time a scroll event occurs
scrollingTimeout = setTimeout(()=>{ scrollingTimeout = setTimeout(()=>{
isJumping = false; isJumping = false;
brewRenderer.removeEventListener('scroll', checkIfScrollComplete); brewRenderer.removeEventListener('scroll', checkIfScrollComplete);
@@ -355,58 +371,58 @@ const Editor = createClass({
}, },
sourceJump : function(targetPage=this.props.currentBrewRendererPageNum, smooth=true){ sourceJump : function(targetPage=this.props.currentBrewRendererPageNum, smooth=true){
if(!this.isText || isJumping) if(!this.isText() || isJumping)
return; return;
const textSplit = this.props.renderer == 'V3' ? /^\\page$/gm : /\\page/; const textSplit = this.props.renderer == 'V3' ? PAGEBREAK_REGEX_V3 : /\\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;
let currentY = this.codeEditor.current.codeMirror.getScrollInfo().top; let currentY = this.codeEditor.current.codeMirror?.getScrollInfo().top;
let targetY = this.codeEditor.current.codeMirror.heightAtLine(targetLine, 'local', true); let targetY = this.codeEditor.current.codeMirror?.heightAtLine(targetLine, 'local', true);
const checkIfScrollComplete = ()=>{ let scrollingTimeout;
let scrollingTimeout; const checkIfScrollComplete = ()=>{ // Prevent interrupting a scroll in progress if user clicks multiple times
clearTimeout(scrollingTimeout); // Reset the timer every time a scroll event occurs clearTimeout(scrollingTimeout); // Reset the timer every time a scroll event occurs
scrollingTimeout = setTimeout(()=>{ scrollingTimeout = setTimeout(()=>{
isJumping = false; isJumping = false;
this.codeEditor.current.codeMirror.off('scroll', checkIfScrollComplete); this.codeEditor.current.codeMirror?.off('scroll', checkIfScrollComplete);
}, 150); // If 150 ms pass without a scroll event, assume scrolling is done }, 150); // If 150 ms pass without a scroll event, assume scrolling is done
}; };
isJumping = true; isJumping = true;
checkIfScrollComplete(); checkIfScrollComplete();
this.codeEditor.current.codeMirror.on('scroll', checkIfScrollComplete); if (this.codeEditor.current?.codeMirror) {
this.codeEditor.current.codeMirror?.on('scroll', checkIfScrollComplete);
}
if(smooth) { if(smooth) {
//Scroll 1/10 of the way every 10ms until 1px off. //Scroll 1/10 of the way every 10ms until 1px off.
const incrementalScroll = setInterval(()=>{ const incrementalScroll = setInterval(()=>{
currentY += (targetY - currentY) / 10; currentY += (targetY - currentY) / 10;
this.codeEditor.current.codeMirror.scrollTo(null, currentY); this.codeEditor.current.codeMirror?.scrollTo(null, currentY);
// Update target: target height is not accurate until within +-10 lines of the visible window // Update target: target height is not accurate until within +-10 lines of the visible window
if(Math.abs(targetY - currentY > 100)) if(Math.abs(targetY - currentY > 100))
targetY = this.codeEditor.current.codeMirror.heightAtLine(targetLine, 'local', true); targetY = this.codeEditor.current.codeMirror?.heightAtLine(targetLine, 'local', true);
// End when close enough // End when close enough
if(Math.abs(targetY - currentY) < 1) { if(Math.abs(targetY - currentY) < 1) {
this.codeEditor.current.codeMirror.scrollTo(null, targetY); // Scroll any remaining difference this.codeEditor.current.codeMirror?.scrollTo(null, targetY); // Scroll any remaining difference
this.codeEditor.current.setCursorPosition({ line: targetLine + 1, ch: 0 }); this.codeEditor.current.setCursorPosition({ line: targetLine + 1, ch: 0 });
this.codeEditor.current.codeMirror.addLineClass(targetLine + 1, 'wrap', 'sourceMoveFlash'); this.codeEditor.current.codeMirror?.addLineClass(targetLine + 1, 'wrap', 'sourceMoveFlash');
clearInterval(incrementalScroll); clearInterval(incrementalScroll);
} }
}, 10); }, 10);
} else { } else {
this.codeEditor.current.codeMirror.scrollTo(null, targetY); // Scroll any remaining difference this.codeEditor.current.codeMirror?.scrollTo(null, targetY); // Scroll any remaining difference
this.codeEditor.current.setCursorPosition({ line: targetLine + 1, ch: 0 }); this.codeEditor.current.setCursorPosition({ line: targetLine + 1, ch: 0 });
this.codeEditor.current.codeMirror.addLineClass(targetLine + 1, 'wrap', 'sourceMoveFlash'); this.codeEditor.current.codeMirror?.addLineClass(targetLine + 1, 'wrap', 'sourceMoveFlash');
} }
}, },
//Called when there are changes to the editor's dimensions //Called when there are changes to the editor's dimensions
update : function(){ update : function(){},
this.codeEditor.current?.updateSize();
},
updateEditorTheme : function(newTheme){ updateEditorTheme : function(newTheme){
window.localStorage.setItem(EDITOR_THEME_KEY, newTheme); window.localStorage.setItem(EDITOR_THEME_KEY, newTheme);
@@ -428,9 +444,10 @@ const Editor = createClass({
language='gfm' language='gfm'
view={this.state.view} view={this.state.view}
value={this.props.brew.text} value={this.props.brew.text}
onChange={this.props.onTextChange} onChange={this.props.onBrewChange('text')}
editorTheme={this.state.editorTheme} editorTheme={this.state.editorTheme}
rerenderParent={this.rerenderParent} /> rerenderParent={this.rerenderParent}
style={{ height: `calc(100% - ${this.state.snippetBarHeight}px)` }} />
</>; </>;
} }
if(this.isStyle()){ if(this.isStyle()){
@@ -440,10 +457,11 @@ const Editor = createClass({
language='css' language='css'
view={this.state.view} view={this.state.view}
value={this.props.brew.style ?? DEFAULT_STYLE_TEXT} value={this.props.brew.style ?? DEFAULT_STYLE_TEXT}
onChange={this.props.onStyleChange} onChange={this.props.onBrewChange('style')}
enableFolding={true} enableFolding={true}
editorTheme={this.state.editorTheme} editorTheme={this.state.editorTheme}
rerenderParent={this.rerenderParent} /> rerenderParent={this.rerenderParent}
style={{ height: `calc(100% - ${this.state.snippetBarHeight}px)` }} />
</>; </>;
} }
if(this.isMeta()){ if(this.isMeta()){
@@ -454,11 +472,27 @@ const Editor = createClass({
rerenderParent={this.rerenderParent} /> rerenderParent={this.rerenderParent} />
<MetadataEditor <MetadataEditor
metadata={this.props.brew} metadata={this.props.brew}
onChange={this.props.onMetaChange} themeBundle={this.props.themeBundle}
onChange={this.props.onBrewChange('metadata')}
reportError={this.props.reportError} reportError={this.props.reportError}
userThemes={this.props.userThemes}/> userThemes={this.props.userThemes}/>
</>; </>;
} }
if(this.isSnip()){
if(!this.props.brew.snippets) { this.props.brew.snippets = DEFAULT_SNIPPET_TEXT; }
return <>
<CodeEditor key='codeEditor'
ref={this.codeEditor}
language='gfm'
view={this.state.view}
value={this.props.brew.snippets}
onChange={this.props.onBrewChange('snippets')}
enableFolding={true}
editorTheme={this.state.editorTheme}
rerenderParent={this.rerenderParent}
style={{ height: `calc(100% -${this.state.snippetBarHeight}px)` }} />
</>;
}
}, },
redo : function(){ redo : function(){
@@ -499,7 +533,7 @@ const Editor = createClass({
historySize={this.historySize()} historySize={this.historySize()}
currentEditorTheme={this.state.editorTheme} currentEditorTheme={this.state.editorTheme}
updateEditorTheme={this.updateEditorTheme} updateEditorTheme={this.updateEditorTheme}
snippetBundle={this.props.snippetBundle} themeBundle={this.props.themeBundle}
cursorPos={this.codeEditor.current?.getCursorPosition() || {}} cursorPos={this.codeEditor.current?.getCursorPosition() || {}}
updateBrew={this.props.updateBrew} updateBrew={this.props.updateBrew}
/> />
@@ -510,4 +544,4 @@ const Editor = createClass({
} }
}); });
module.exports = Editor; export default Editor;
+24 -18
View File
@@ -1,11 +1,13 @@
@import 'themes/codeMirror/customEditorStyles.less'; @import 'themes/codeMirror/customEditorStyles.less';
.editor { .editor {
position : relative; position : relative;
width : 100%; width : 100%;
height : 100%;
container : editor / inline-size;
.codeEditor { .codeEditor {
height : 100%; height : calc(100% - 25px);
.pageLine { .CodeMirror { height : 100%; }
.pageLine, .snippetLine {
background : #33333328; background : #33333328;
border-top : #333399 solid 1px; border-top : #333399 solid 1px;
} }
@@ -13,6 +15,10 @@
float : right; float : right;
color : grey; color : grey;
} }
.editor-snippet-count {
float : right;
color : grey;
}
.columnSplit { .columnSplit {
font-style : italic; font-style : italic;
color : grey; color : grey;
@@ -44,26 +50,26 @@
color : green; color : green;
} }
.emoji:not(.cm-comment) { .emoji:not(.cm-comment) {
margin-left : 2px;
color : #360034;
background : #ffc8ff;
border-radius : 6px;
font-weight : bold;
padding-bottom : 1px; padding-bottom : 1px;
margin-left : 2px;
font-weight : bold;
color : #360034;
outline : solid 2px #FF96FC;
outline-offset : -2px; outline-offset : -2px;
outline : solid 2px #ff96fc; background : #FFC8FF;
border-radius : 6px;
} }
.superscript:not(.cm-comment) { .superscript:not(.cm-comment) {
font-weight : bold;
color : goldenrod;
vertical-align : super;
font-size : 0.9em; font-size : 0.9em;
font-weight : bold;
vertical-align : super;
color : goldenrod;
} }
.subscript:not(.cm-comment) { .subscript:not(.cm-comment) {
font-weight : bold;
color : rgb(123, 123, 15);
vertical-align : sub;
font-size : 0.9em; font-size : 0.9em;
font-weight : bold;
vertical-align : sub;
color : rgb(123, 123, 15);
} }
.dl-highlight { .dl-highlight {
&.dl-colon-highlight { &.dl-colon-highlight {
@@ -102,4 +108,4 @@
span { padding : 2px 5px; } span { padding : 2px 5px; }
} }
} }
@@ -1,20 +1,18 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
require('./metadataEditor.less'); import './metadataEditor.less';
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const _ = require('lodash'); import _ from 'lodash';
const request = require('../../utils/request-middleware.js'); import request from '../../utils/request-middleware.js';
const Nav = require('naturalcrit/nav/nav.jsx'); import Combobox from '../../../components/combobox.jsx';
const Combobox = require('client/components/combobox.jsx'); import TagInput from '../tagInput/tagInput.jsx';
const StringArrayEditor = require('../stringArrayEditor/stringArrayEditor.jsx');
import Themes from 'themes/themes.json';
const Themes = require('themes/themes.json'); import validations from './validations.js';
const validations = require('./validations.js');
const SYSTEMS = ['5e', '4e', '3.5e', 'Pathfinder']; const SYSTEMS = ['5e', '4e', '3.5e', 'Pathfinder'];
const homebreweryThumbnail = require('../../thumbnail.png'); import homebreweryThumbnail from '../../thumbnail.png';
const callIfExists = (val, fn, ...args)=>{ const callIfExists = (val, fn, ...args)=>{
if(val[fn]) { if(val[fn]) {
@@ -22,7 +20,7 @@ const callIfExists = (val, fn, ...args)=>{
} }
}; };
const MetadataEditor = createClass({ const MetadataEditor = createReactClass({
displayName : 'MetadataEditor', displayName : 'MetadataEditor',
getDefaultProps : function() { getDefaultProps : function() {
return { return {
@@ -40,6 +38,7 @@ const MetadataEditor = createClass({
theme : '5ePHB', theme : '5ePHB',
lang : 'en' lang : 'en'
}, },
onChange : ()=>{}, onChange : ()=>{},
reportError : ()=>{} reportError : ()=>{}
}; };
@@ -67,6 +66,11 @@ const MetadataEditor = createClass({
const inputRules = validations[name] ?? []; const inputRules = validations[name] ?? [];
const validationErr = inputRules.map((rule)=>rule(e.target.value)).filter(Boolean); const validationErr = inputRules.map((rule)=>rule(e.target.value)).filter(Boolean);
const debouncedReportValidity = _.debounce((target, errMessage)=>{
callIfExists(target, 'setCustomValidity', errMessage);
callIfExists(target, 'reportValidity');
}, 300); // 300ms debounce delay, adjust as needed
// if no validation rules, save to props // if no validation rules, save to props
if(validationErr.length === 0){ if(validationErr.length === 0){
callIfExists(e.target, 'setCustomValidity', ''); callIfExists(e.target, 'setCustomValidity', '');
@@ -74,14 +78,16 @@ const MetadataEditor = createClass({
...this.props.metadata, ...this.props.metadata,
[name] : e.target.value [name] : e.target.value
}); });
return true;
} else { } else {
// if validation issues, display built-in browser error popup with each error. // if validation issues, display built-in browser error popup with each error.
const errMessage = validationErr.map((err)=>{ const errMessage = validationErr.map((err)=>{
return `- ${err}`; return `- ${err}`;
}).join('\n'); }).join('\n');
callIfExists(e.target, 'setCustomValidity', errMessage);
callIfExists(e.target, 'reportValidity'); debouncedReportValidity(e.target, errMessage);
return false;
} }
}, },
@@ -102,6 +108,7 @@ const MetadataEditor = createClass({
} }
this.props.onChange(this.props.metadata, 'renderer'); this.props.onChange(this.props.metadata, 'renderer');
}, },
handlePublish : function(val){ handlePublish : function(val){
this.props.onChange({ this.props.onChange({
...this.props.metadata, ...this.props.metadata,
@@ -112,6 +119,14 @@ const MetadataEditor = createClass({
handleTheme : function(theme){ handleTheme : function(theme){
this.props.metadata.renderer = theme.renderer; this.props.metadata.renderer = theme.renderer;
this.props.metadata.theme = theme.path; this.props.metadata.theme = theme.path;
this.props.onChange(this.props.metadata, 'theme');
},
handleThemeWritein : function(e) {
const shareId = e.target.value.split('/').pop(); //Extract just the ID if a URL was pasted in
this.props.metadata.theme = shareId;
this.props.onChange(this.props.metadata, 'theme'); this.props.onChange(this.props.metadata, 'theme');
}, },
@@ -191,8 +206,6 @@ const MetadataEditor = createClass({
}, },
renderThemeDropdown : function(){ renderThemeDropdown : function(){
if(!global.enable_themes) return;
const mergedThemes = _.merge(Themes, this.props.userThemes); const mergedThemes = _.merge(Themes, this.props.userThemes);
const listThemes = (renderer)=>{ const listThemes = (renderer)=>{
@@ -200,7 +213,7 @@ const MetadataEditor = createClass({
if(theme.path == this.props.metadata.shareId) return; if(theme.path == this.props.metadata.shareId) return;
const preview = theme.thumbnail || `/themes/${theme.renderer}/${theme.path}/dropdownPreview.png`; const preview = theme.thumbnail || `/themes/${theme.renderer}/${theme.path}/dropdownPreview.png`;
const texture = theme.thumbnail || `/themes/${theme.renderer}/${theme.path}/dropdownTexture.png`; const texture = theme.thumbnail || `/themes/${theme.renderer}/${theme.path}/dropdownTexture.png`;
return <div className='item' key={`${renderer}_${theme.name}`} onClick={()=>this.handleTheme(theme)} title={''}> return <div className='item' key={`${renderer}_${theme.name}`} value={`${theme.author ?? renderer} : ${theme.name}`} data={theme} title={''}>
{theme.author ?? renderer} : {theme.name} {theme.author ?? renderer} : {theme.name}
<div className='texture-container'> <div className='texture-container'>
<img src={texture}/> <img src={texture}/>
@@ -210,26 +223,40 @@ const MetadataEditor = createClass({
<img src={preview}/> <img src={preview}/>
</div> </div>
</div>; </div>;
}); }).filter(Boolean);
}; };
const currentRenderer = this.props.metadata.renderer; const currentRenderer = this.props.metadata.renderer;
const currentTheme = mergedThemes[`${_.upperFirst(this.props.metadata.renderer)}`][this.props.metadata.theme] const currentThemeDisplay = this.props.themeBundle?.name ? `${this.props.themeBundle.author ?? currentRenderer} : ${this.props.themeBundle.name}` : 'No Theme Selected';
?? { name: `!!! THEME MISSING !!! ID=${this.props.metadata.theme}` };
let dropdown; let dropdown;
if(currentRenderer == 'legacy') { if(currentRenderer == 'legacy') {
dropdown = dropdown =
<Nav.dropdown className='disabled value' trigger='disabled'> <div className='disabled value' trigger='disabled'>
<div> {`Themes are not supported in the Legacy Renderer`} <i className='fas fa-caret-down'></i> </div> <div> Themes are not supported in the Legacy Renderer </div>
</Nav.dropdown>; </div>;
} else { } else {
dropdown = dropdown =
<Nav.dropdown className='value' trigger='click'> <div className='value'>
<div> {currentTheme.author ?? _.upperFirst(currentRenderer)} : {currentTheme.name} <i className='fas fa-caret-down'></i> </div> <Combobox trigger='click'
className='themes-dropdown'
{listThemes(currentRenderer)} default={currentThemeDisplay}
</Nav.dropdown>; placeholder='Select from below, or enter the Share URL or ID of a brew with the meta:theme tag'
onSelect={(value)=>this.handleTheme(value)}
onEntry={(e)=>{
e.target.setCustomValidity(''); //Clear the validation popup while typing
if(this.handleFieldChange('theme', e))
this.handleThemeWritein(e);
}}
options={listThemes(currentRenderer)}
autoSuggest={{
suggestMethod : 'includes',
clearAutoSuggestOnClick : true,
filterOn : ['value', 'title']
}}
/>
<small>Select from the list below (built-in themes and brews you have tagged "meta:theme"), or paste in the Share URL or Share ID of any brew.</small>
</div>;
} }
return <div className='field themes'> return <div className='field themes'>
@@ -244,15 +271,13 @@ const MetadataEditor = createClass({
return _.map(langCodes.sort(), (code, index)=>{ return _.map(langCodes.sort(), (code, index)=>{
const localName = new Intl.DisplayNames([code], { type: 'language' }); const localName = new Intl.DisplayNames([code], { type: 'language' });
const englishName = new Intl.DisplayNames('en', { type: 'language' }); const englishName = new Intl.DisplayNames('en', { type: 'language' });
return <div className='item' title={`${englishName.of(code)}`} key={`${index}`} data-value={`${code}`} data-detail={`${localName.of(code)}`}> return <div className='item' title={englishName.of(code)} key={`${index}`} value={code} detail={localName.of(code)}>
{`${code}`} {code}
<div className='detail'>{`${localName.of(code)}`}</div> <div className='detail'>{localName.of(code)}</div>
</div>; </div>;
}); });
}; };
const debouncedHandleFieldChange = _.debounce(this.handleFieldChange, 500);
return <div className='field language'> return <div className='field language'>
<label>language</label> <label>language</label>
<div className='value'> <div className='value'>
@@ -263,16 +288,15 @@ const MetadataEditor = createClass({
onSelect={(value)=>this.handleLanguage(value)} onSelect={(value)=>this.handleLanguage(value)}
onEntry={(e)=>{ onEntry={(e)=>{
e.target.setCustomValidity(''); //Clear the validation popup while typing e.target.setCustomValidity(''); //Clear the validation popup while typing
debouncedHandleFieldChange('lang', e); this.handleFieldChange('lang', e);
}} }}
options={listLanguages()} options={listLanguages()}
autoSuggest={{ autoSuggest={{
suggestMethod : 'startsWith', suggestMethod : 'startsWith',
clearAutoSuggestOnClick : true, clearAutoSuggestOnClick : true,
filterOn : ['data-value', 'data-detail', 'title'] filterOn : ['value', 'detail', 'title']
}} }}
> />
</Combobox>
<small>Sets the HTML Lang property for your brew. May affect hyphenation or spellcheck.</small> <small>Sets the HTML Lang property for your brew. May affect hyphenation or spellcheck.</small>
</div> </div>
@@ -280,8 +304,6 @@ const MetadataEditor = createClass({
}, },
renderRenderOptions : function(){ renderRenderOptions : function(){
if(!global.enable_v3) return;
return <div className='field systems'> return <div className='field systems'>
<label>Renderer</label> <label>Renderer</label>
<div className='value'> <div className='value'>
@@ -304,17 +326,14 @@ const MetadataEditor = createClass({
onChange={(e)=>this.handleRenderer('V3', e)} /> onChange={(e)=>this.handleRenderer('V3', e)} />
V3 V3
</label> </label>
<small><a href='/legacy' target='_blank' rel='noopener noreferrer'>Click here to see the demo page for the old Legacy renderer!</a></small>
<a href='/legacy' target='_blank' rel='noopener noreferrer'>
Click here to see the demo page for the old Legacy renderer!
</a>
</div> </div>
</div>; </div>;
}, },
render : function(){ render : function(){
return <div className='metadataEditor'> return <div className='metadataEditor'>
<h1 className='sectionHead'>Brew</h1> <h1>Properties Editor</h1>
<div className='field title'> <div className='field title'>
<label>title</label> <label>title</label>
@@ -344,10 +363,11 @@ const MetadataEditor = createClass({
{this.renderThumbnail()} {this.renderThumbnail()}
</div> </div>
<StringArrayEditor label='tags' valuePatterns={[/^(?:(?:group|meta|system|type):)?[A-Za-z0-9][A-Za-z0-9 \/.\-]{0,40}$/]} <TagInput 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>
@@ -362,28 +382,25 @@ const MetadataEditor = createClass({
{this.renderRenderOptions()} {this.renderRenderOptions()}
<hr/> <h2>Authors</h2>
<h1 className='sectionHead'>Authors</h1>
{this.renderAuthors()} {this.renderAuthors()}
<StringArrayEditor label='invited authors' valuePatterns={[/.+/]} <TagInput 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)}
/>
<hr/> <h2>Privacy</h2>
<h1 className='sectionHead'>Privacy</h1>
<div className='field publish'> <div className='field publish'>
<label>publish</label> <label>publish</label>
<div className='value'> <div className='value'>
{this.renderPublish()} {this.renderPublish()}
<small>Published homebrews will be publicly viewable and searchable (eventually...)</small> <small>Published brews are searchable in <a href='/vault'>the Vault</a> and visible on your user page. Unpublished brews are not indexed in the Vault or visible on your user page, but can still be shared and indexed by search engines. You can unpublish a brew any time.</small>
</div> </div>
</div> </div>
@@ -393,4 +410,4 @@ const MetadataEditor = createClass({
} }
}); });
module.exports = MetadataEditor; export default MetadataEditor;
@@ -1,20 +1,31 @@
@import 'naturalcrit/styles/colors.less'; @import 'naturalcrit/styles/colors.less';
.userThemeName {
padding-right : 10px;
padding-left : 10px;
}
.metadataEditor { .metadataEditor {
position : absolute; position : absolute;
z-index : 5;
box-sizing : border-box; box-sizing : border-box;
width : 100%; width : 100%;
height : calc(100vh - 54px); // 54px is the height of the navbar + snippet bar. probably a better way to dynamic get this. height : calc(100vh - 54px); // 54px is the height of the navbar + snippet bar. probably a better way to dynamic get this.
padding : 25px; padding : 25px;
overflow-y : auto; overflow-y : auto;
font-size : 13px;
background-color : #999999; background-color : #999999;
.sectionHead { h1 {
margin : 20px 0; margin : 0 0 40px;
font-weight : 1000; font-weight : bold;
text-transform : uppercase;
&:first-of-type { margin-top : 0; } }
h2 {
margin : 20px 0;
font-weight : bold;
color : #555555;
border-bottom : 2px solid gray;
} }
& > div { margin-bottom : 10px; } & > div { margin-bottom : 10px; }
@@ -43,7 +54,7 @@
min-width : 200px; min-width : 200px;
& > label { & > label {
width : 80px; width : 80px;
font-size : 11px; font-size : 0.9em;
font-weight : 800; font-weight : 800;
line-height : 1.8em; line-height : 1.8em;
text-transform : uppercase; text-transform : uppercase;
@@ -52,19 +63,25 @@
flex : 1 1 auto; flex : 1 1 auto;
width : 50px; width : 50px;
&:invalid { background : #FFB9B9; } &:invalid { background : #FFB9B9; }
small {
display : block;
font-size : 0.9em;
font-style : italic;
line-height : 1.4em;
}
} }
input[type='text'], textarea { input[type='text'], textarea {
border : 1px solid gray; border : 1px solid gray;
&:focus { outline : 1px solid #444444; } &:focus { outline : 1px solid #444444; }
} }
&.thumbnail { &.thumbnail, &.themes {
height : 1.4em;
label { line-height : 2.0em; } label { line-height : 2.0em; }
.value { .value {
overflow : hidden; overflow : hidden;
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;
@@ -73,12 +90,22 @@
} }
} }
&.themes {
.value {
overflow : visible;
text-overflow : auto;
}
button {
padding-right : 5px;
padding-left : 5px;
}
}
&.description { &.description {
flex : 1; flex : 1;
textarea.value { textarea.value {
height : auto; height : auto;
font-family : 'Open Sans', sans-serif; font-family : 'Open Sans', sans-serif;
font-size : 0.8em;
resize : none; resize : none;
} }
} }
@@ -87,12 +114,6 @@
z-index : 200; z-index : 200;
max-width : 150px; max-width : 150px;
} }
small {
display : inline-block;
font-size : 0.6em;
font-style : italic;
line-height : 1.4em;
}
} }
@@ -113,18 +134,13 @@
display : inline-flex; display : inline-flex;
align-items : center; align-items : center;
margin-right : 15px; margin-right : 15px;
font-size : 0.7em; font-size : 0.9em;
font-weight : 800; font-weight : 800;
white-space : nowrap;
vertical-align : middle; vertical-align : middle;
white-space : nowrap;
cursor : pointer; cursor : pointer;
user-select : none; user-select : none;
} }
a {
display : inline-flex;
font-size : 0.7em;
font-weight : 800;
}
input { input {
margin : 3px; margin : 3px;
vertical-align : middle; vertical-align : middle;
@@ -136,110 +152,89 @@
margin-bottom : 15px; margin-bottom : 15px;
button { width : 100%; } button { width : 100%; }
button.publish { button.publish {
.button(@blueLight); .colorButton(@blueLight);
} }
button.unpublish { button.unpublish {
.button(@silver); .colorButton(@silver);
} }
} }
.delete.field .value { .delete.field .value {
button { button {
.button(@red); .colorButton(@red);
} }
} }
.authors.field .value { .authors.field .value { line-height : 1.5em; }
font-size : 0.8em;
line-height : 1.5em;
}
.themes.field { .themes.field {
font-size : 13.33px; & .dropdown-container {
.navDropdownContainer {
position : relative; position : relative;
z-index : 100; z-index : 100;
background-color : white; background-color : white;
&.disabled { }
font-style : italic; & .dropdown-options { overflow-y : visible; }
color : dimgray; .disabled {
background-color : darkgray; font-style : italic;
} color : dimgray;
& > div:first-child { background-color : darkgray;
padding : 6px 3px; }
background-color : inherit; .item {
border : 2px solid rgb(118,118,118); position : relative;
i { float : right; } padding : 3px 3px;
&:hover { overflow : visible;
color : white; background-color : white;
background-color : @blue; border-top : 1px solid rgb(118, 118, 118);
.preview {
position : absolute;
top : 0;
right : 0;
z-index : 1;
display : flex;
flex-direction : column;
width : 200px;
overflow : hidden;
color : black;
background : #CCCCCC;
border-radius : 5px;
box-shadow : 0 0 5px black;
opacity : 0;
transition : opacity 250ms ease;
h6 {
padding-block : 0.5em;
padding-inline : 1em;
font-weight : 900;
border-bottom : 2px solid hsl(0,0%,40%);
} }
} }
.navDropdown .item > p {
width : 45%; .texture-container {
height : 1.1em; position : absolute;
overflow : hidden; top : 0;
text-overflow : ellipsis; left : 0;
white-space : nowrap; width : 100%;
} height : 100%;
.navDropdown { min-height : 100%;
position : absolute; overflow : hidden;
width : 100%; > img {
box-shadow : 0px 5px 10px rgba(0, 0, 0, 0.3); position : absolute;
.item { top : 0;
position : relative; right : 0;
padding : 3px 3px; width : 50%;
overflow : visible; min-height : 100%;
background-color : white; -webkit-mask-image : linear-gradient(90deg, transparent, black 20%);
border-top : 1px solid rgb(118, 118, 118); mask-image : linear-gradient(90deg, transparent, black 20%);
.preview {
position : absolute;
top : 0;
right : 0;
z-index : 1;
display : flex;
flex-direction : column;
width : 200px;
overflow : hidden;
color : black;
background : #CCCCCC;
border-radius : 5px;
box-shadow : 0 0 5px black;
opacity : 0;
transition : opacity 250ms ease;
h6 {
padding-block : 0.5em;
padding-inline : 1em;
font-weight : 900;
border-bottom : 2px solid hsl(0,0%,40%);
}
}
&:hover {
color : white;
background-color : @blue;
}
&:hover > .preview { opacity : 1; }
.texture-container {
position : absolute;
top : 0;
left : 0;
width : 100%;
height : 100%;
min-height : 100%;
overflow : hidden;
> img {
position : absolute;
top : 0px;
right : 0;
width : 50%;
min-height : 100%;
-webkit-mask-image : linear-gradient(90deg, transparent, black 20%);
mask-image : linear-gradient(90deg, transparent, black 20%);
}
}
} }
} }
&:hover {
color : white;
background-color : @blue;
filter : unset;
}
&:hover > .preview { opacity : 1; }
} }
} }
.field .list { .field .list {
display : flex; display : flex;
flex : 1 0; flex : 1 0;
@@ -258,27 +253,26 @@
color : white; color : white;
text-align : center; text-align : center;
cursor : pointer; cursor : pointer;
i { i {
position : relative; position : relative;
top : 50%; top : 50%;
transform : translateY(-50%); transform : translateY(-50%);
} }
&:not(:last-child) { border-right : 1px solid black; } &:not(:last-child) { border-right : 1px solid black; }
&:last-child { border-radius : 0 0.5em 0.5em 0; } &:last-child { border-radius : 0 0.5em 0.5em 0; }
} }
.badge { .tag {
padding : 0.3em; padding : 0.3em;
margin : 2px; margin : 2px;
font-size : 0.9em; font-size : 0.9em;
background-color : #DDDDDD; background-color : #DDDDDD;
border-radius : 0.5em; border-radius : 0.5em;
.icon { .icon { #groupedIcon; }
#groupedIcon; }
} }
.input-group { .input-group {
@@ -294,17 +288,30 @@
height : 100%; height : 100%;
} }
.invalid:focus { background-color : pink; } .input-group {
height : ~'calc(.9em + 4px + .6em)';
.icon { input { border-radius : 0.5em 0 0 0.5em; }
#groupedIcon;
top : -0.54em;
right : 1px;
height : 97%;
font-size : 0.8em;
i { font-size : 1.125em; } input:last-child { border-radius : 0.5em; }
.value {
width : 7.5vw;
min-width : 75px;
height : 100%;
}
.invalid:focus { background-color : pink; }
.icon {
#groupedIcon;
top : -0.54em;
right : 1px;
height : 97%;
i { font-size : 1.125em; }
}
} }
} }
} }
} }
@@ -1,4 +1,4 @@
module.exports = { export default {
title : [ title : [
(value)=>{ (value)=>{
return value?.length > 100 ? 'Max title length of 100 characters' : null; return value?.length > 100 ? 'Max title length of 100 characters' : null;
@@ -18,7 +18,7 @@ module.exports = {
try { try {
Boolean(new URL(value)); Boolean(new URL(value));
return null; return null;
} catch (e) { } catch {
return 'Must be a valid URL'; return 'Must be a valid URL';
} }
} }
@@ -27,6 +27,19 @@ module.exports = {
(value)=>{ (value)=>{
return new RegExp(/^([a-zA-Z]{2,3})(-[a-zA-Z]{4})?(-(?:[0-9]{3}|[a-zA-Z]{2}))?$/).test(value) === false && (value.length > 0) ? 'Invalid language code.' : null; return new RegExp(/^([a-zA-Z]{2,3})(-[a-zA-Z]{4})?(-(?:[0-9]{3}|[a-zA-Z]{2}))?$/).test(value) === false && (value.length > 0) ? 'Invalid language code.' : null;
} }
],
theme : [
(value)=>{
const URL = global.config.baseUrl.replace(/[-/\\^$*+?.()|[\]{}]/g, '\\$&'); //Escape any regex characters
const shareIDPattern = '[a-zA-Z0-9-_]{12}';
const shareURLRegex = new RegExp(`^${URL}\\/share\\/${shareIDPattern}$`);
const shareIDRegex = new RegExp(`^${shareIDPattern}$`);
if(value?.length === 0) return null;
if(shareURLRegex.test(value)) return null;
if(shareIDRegex.test(value)) return null;
return 'Must be a valid Share URL or a 12-character ID.';
}
] ]
}; };
+139 -95
View File
@@ -1,28 +1,36 @@
/*eslint max-lines: ["warn", {"max": 250, "skipBlankLines": true, "skipComments": true}]*/ /*eslint max-lines: ["warn", {"max": 350, "skipBlankLines": true, "skipComments": true}]*/
require('./snippetbar.less'); import './snippetbar.less';
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const _ = require('lodash');
const cx = require('classnames');
import { getHistoryItems, historyExists } from '../../utils/versionHistory.js'; import _ from 'lodash';
import cx from 'classnames';
//Import all themes import { loadHistory } from '../../utils/versionHistory.js';
const ThemeSnippets = {}; import { brewSnippetsToJSON } from '../../../../shared/helpers.js';
ThemeSnippets['Legacy_5ePHB'] = require('themes/Legacy/5ePHB/snippets.js');
ThemeSnippets['V3_5ePHB'] = require('themes/V3/5ePHB/snippets.js');
ThemeSnippets['V3_5eDMG'] = require('themes/V3/5eDMG/snippets.js');
ThemeSnippets['V3_Journal'] = require('themes/V3/Journal/snippets.js');
ThemeSnippets['V3_Blank'] = require('themes/V3/Blank/snippets.js');
const EditorThemes = require('build/homebrew/codeMirror/editorThemes.json'); import Legacy5ePHB from 'themes/Legacy/5ePHB/snippets.js';
import V3_5ePHB from 'themes/V3/5ePHB/snippets.js';
import V3_5eDMG from 'themes/V3/5eDMG/snippets.js';
import V3_Journal from 'themes/V3/Journal/snippets.js';
import V3_Blank from 'themes/V3/Blank/snippets.js';
const ThemeSnippets = {
Legacy_5ePHB : Legacy5ePHB,
V3_5ePHB : V3_5ePHB,
V3_5eDMG : V3_5eDMG,
V3_Journal : V3_Journal,
V3_Blank : V3_Blank,
};
import EditorThemes from 'build/homebrew/codeMirror/editorThemes.json';
const execute = function(val, props){ const execute = function(val, props){
if(_.isFunction(val)) return val(props); if(_.isFunction(val)) return val(props);
return val; return val;
}; };
const Snippetbar = createClass({ const Snippetbar = createReactClass({
displayName : 'SnippetBar', displayName : 'SnippetBar',
getDefaultProps : function() { getDefaultProps : function() {
return { return {
@@ -40,7 +48,7 @@ const Snippetbar = createClass({
unfoldCode : ()=>{}, unfoldCode : ()=>{},
updateEditorTheme : ()=>{}, updateEditorTheme : ()=>{},
cursorPos : {}, cursorPos : {},
snippetBundle : [], themeBundle : [],
updateBrew : ()=>{} updateBrew : ()=>{}
}; };
}, },
@@ -50,37 +58,57 @@ const Snippetbar = createClass({
renderer : this.props.renderer, renderer : this.props.renderer,
themeSelector : false, themeSelector : false,
snippets : [], snippets : [],
historyExists : false showHistory : false,
historyExists : false,
historyItems : []
}; };
}, },
componentDidMount : async function() { componentDidMount : async function(prevState) {
const snippets = this.compileSnippets(); const snippets = this.compileSnippets();
this.setState({ this.setState({
snippets : snippets snippets : snippets
}); });
}, },
componentDidUpdate : async function(prevProps) { componentDidUpdate : async function(prevProps, prevState) {
if(prevProps.renderer != this.props.renderer || prevProps.theme != this.props.theme || prevProps.snippetBundle != this.props.snippetBundle) { if(prevProps.renderer != this.props.renderer ||
prevProps.theme != this.props.theme ||
prevProps.themeBundle != this.props.themeBundle ||
prevProps.brew.snippets != this.props.brew.snippets) {
this.setState({ this.setState({
snippets : this.compileSnippets() snippets : this.compileSnippets()
}); });
}; };
if(historyExists(this.props.brew) != this.state.historyExists){ // Update history list if it has changed
const checkHistoryItems = await loadHistory(this.props.brew);
// If all items have the noData property, there is no saved data
const checkHistoryExists = !checkHistoryItems.every((historyItem)=>{
return historyItem?.noData;
});
if(prevState.historyExists != checkHistoryExists){
this.setState({ this.setState({
historyExists : !this.state.historyExists historyExists : checkHistoryExists
}); });
}; }
// If any history items have changed, update the list
if(checkHistoryExists && checkHistoryItems.some((historyItem, index)=>{
return index >= prevState.historyItems.length || !_.isEqual(historyItem, prevState.historyItems[index]);
})){
this.setState({
historyItems : checkHistoryItems
});
}
}, },
mergeCustomizer : function(oldValue, newValue, key) { mergeCustomizer : function(oldValue, newValue, key) {
if(key == 'snippets') { if(key == 'snippets') {
const result = _.reverse(_.unionBy(_.reverse(newValue), _.reverse(oldValue), 'name')); // Join snippets together, with preference for the child theme over the parent theme const result = _.reverse(_.unionBy(_.reverse(newValue), _.reverse(oldValue), 'name')); // Join snippets together, with preference for the child theme over the parent theme
return result.filter((snip)=>snip.gen || snip.subsnippets); return result.filter((snip)=>snip.gen || snip.subsnippets);
} };
}, },
compileSnippets : function() { compileSnippets : function() {
@@ -88,15 +116,21 @@ const Snippetbar = createClass({
let oldSnippets = _.keyBy(compiledSnippets, 'groupName'); let oldSnippets = _.keyBy(compiledSnippets, 'groupName');
for (let snippets of this.props.snippetBundle) { if(this.props.themeBundle.snippets) {
if(typeof(snippets) == 'string') // load staticThemes as needed; they were sent as just a file name for (let snippets of this.props.themeBundle.snippets) {
snippets = ThemeSnippets[snippets]; if(typeof(snippets) == 'string') // load staticThemes as needed; they were sent as just a file name
snippets = ThemeSnippets[snippets];
const newSnippets = _.keyBy(_.cloneDeep(snippets), 'groupName'); const newSnippets = _.keyBy(_.cloneDeep(snippets), 'groupName');
compiledSnippets = _.values(_.mergeWith(oldSnippets, newSnippets, this.mergeCustomizer)); compiledSnippets = _.values(_.mergeWith(oldSnippets, newSnippets, this.mergeCustomizer));
oldSnippets = _.keyBy(compiledSnippets, 'groupName'); oldSnippets = _.keyBy(compiledSnippets, 'groupName');
}
} }
const userSnippetsasJSON = brewSnippetsToJSON(this.props.brew.title || 'New Document', this.props.brew.snippets, this.props.themeBundle.snippets);
compiledSnippets.push(userSnippetsasJSON);
return compiledSnippets; return compiledSnippets;
}, },
@@ -133,30 +167,40 @@ 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 _.map(snippets, (snippetGroup)=>{ return <div className='snippets'>
return <SnippetGroup {_.map(snippets, (snippetGroup)=>{
brew={this.props.brew} return <SnippetGroup
groupName={snippetGroup.groupName} brew={this.props.brew}
icon={snippetGroup.icon} groupName={snippetGroup.groupName}
snippets={snippetGroup.snippets} icon={snippetGroup.icon}
key={snippetGroup.groupName} snippets={snippetGroup.snippets}
onSnippetClick={this.handleSnippetClick} key={snippetGroup.groupName}
cursorPos={this.props.cursorPos} onSnippetClick={this.handleSnippetClick}
/>; cursorPos={this.props.cursorPos}
}); />;
})
}
</div>;
}, },
replaceContent : function(item){ replaceContent : function(item){
return this.props.updateBrew(item); return this.props.updateBrew(item);
}, },
toggleHistoryMenu : function(){
this.setState({
showHistory : !this.state.showHistory
});
},
renderHistoryItems : function() { renderHistoryItems : function() {
const historyItems = getHistoryItems(this.props.brew); if(!this.state.historyExists) return;
return <div className='dropdown'> return <div className='dropdown'>
{_.map(historyItems, (item, index)=>{ {_.map(this.state.historyItems, (item, index)=>{
if(!item.savedAt) return; if(item.noData || !item.savedAt) return;
const saveTime = new Date(item.savedAt); const saveTime = new Date(item.savedAt);
const diffMs = new Date() - saveTime; const diffMs = new Date() - saveTime;
@@ -180,10 +224,24 @@ const Snippetbar = createClass({
renderEditorButtons : function(){ renderEditorButtons : function(){
if(!this.props.showEditButtons) return; if(!this.props.showEditButtons) return;
let foldButtons; return (
if(this.props.view == 'text'){ <div className='editors'>
foldButtons = {this.props.view !== 'meta' && <><div className='historyTools'>
<> <div className={`editorTool snippetGroup history ${this.state.historyExists ? 'active' : ''}`}
onClick={this.toggleHistoryMenu} >
<i className='fas fa-clock-rotate-left' />
{ this.state.showHistory && this.renderHistoryItems() }
</div>
<div className={`editorTool undo ${this.props.historySize.undo ? 'active' : ''}`}
onClick={this.props.undo} >
<i className='fas fa-undo' />
</div>
<div className={`editorTool redo ${this.props.historySize.redo ? 'active' : ''}`}
onClick={this.props.redo} >
<i className='fas fa-redo' />
</div>
</div>
<div className='codeTools'>
<div className={`editorTool foldAll ${this.props.foldCode ? 'active' : ''}`} <div className={`editorTool foldAll ${this.props.foldCode ? 'active' : ''}`}
onClick={this.props.foldCode} > onClick={this.props.foldCode} >
<i className='fas fa-compress-alt' /> <i className='fas fa-compress-alt' />
@@ -192,45 +250,34 @@ const Snippetbar = createClass({
onClick={this.props.unfoldCode} > onClick={this.props.unfoldCode} >
<i className='fas fa-expand-alt' /> <i className='fas fa-expand-alt' />
</div> </div>
</>; <div className={`editorTheme ${this.state.themeSelector ? 'active' : ''}`}
onClick={this.toggleThemeSelector} >
<i className='fas fa-palette' />
{this.state.themeSelector && this.renderThemeSelector()}
</div>
</div></>}
} <div className='tabs'>
<div className={cx('text', { selected: this.props.view === 'text' })}
onClick={()=>this.props.onViewChange('text')}>
<i className='fa fa-beer' />
</div>
<div className={cx('style', { selected: this.props.view === 'style' })}
onClick={()=>this.props.onViewChange('style')}>
<i className='fa fa-paint-brush' />
</div>
<div className={cx('snippet', { selected: this.props.view === 'snippet' })}
onClick={()=>this.props.onViewChange('snippet')}>
<i className='fas fa-th-list' />
</div>
<div className={cx('meta', { selected: this.props.view === 'meta' })}
onClick={()=>this.props.onViewChange('meta')}>
<i className='fas fa-info-circle' />
</div>
</div>
return <div className='editors'>
<div className={`editorTool snippetGroup history ${this.state.historyExists ? 'active' : ''}`} >
<i className='fas fa-clock-rotate-left' />
{this.state.historyExists && this.renderHistoryItems() }
</div> </div>
<div className={`editorTool undo ${this.props.historySize.undo ? 'active' : ''}`} );
onClick={this.props.undo} >
<i className='fas fa-undo' />
</div>
<div className={`editorTool redo ${this.props.historySize.redo ? 'active' : ''}`}
onClick={this.props.redo} >
<i className='fas fa-redo' />
</div>
<div className='divider'></div>
{foldButtons}
<div className={`editorTool editorTheme ${this.state.themeSelector ? 'active' : ''}`}
onClick={this.toggleThemeSelector} >
<i className='fas fa-palette' />
{this.state.themeSelector && this.renderThemeSelector()}
</div>
<div className='divider'></div>
<div className={cx('text', { selected: this.props.view === 'text' })}
onClick={()=>this.props.onViewChange('text')}>
<i className='fa fa-beer' />
</div>
<div className={cx('style', { selected: this.props.view === 'style' })}
onClick={()=>this.props.onViewChange('style')}>
<i className='fa fa-paint-brush' />
</div>
<div className={cx('meta', { selected: this.props.view === 'meta' })}
onClick={()=>this.props.onViewChange('meta')}>
<i className='fas fa-info-circle' />
</div>
</div>;
}, },
render : function(){ render : function(){
@@ -241,14 +288,9 @@ const Snippetbar = createClass({
} }
}); });
module.exports = Snippetbar; export default Snippetbar;
const SnippetGroup = createReactClass({
const SnippetGroup = createClass({
displayName : 'SnippetGroup', displayName : 'SnippetGroup',
getDefaultProps : function() { getDefaultProps : function() {
return { return {
@@ -267,8 +309,9 @@ 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'title={snippet.name}>{snippet.name}</span> <span className={`name${snippet.disabled ? ' disabled' : ''}`} 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'>
@@ -280,7 +323,8 @@ const SnippetGroup = createClass({
}, },
render : function(){ render : function(){
return <div className='snippetGroup snippetBarButton'> const snippetGroup = `snippetGroup snippetBarButton ${this.props.snippets.length === 0 ? 'disabledSnippets' : ''}`;
return <div className={snippetGroup}>
<div className='text'> <div className='text'>
<i className={this.props.icon} /> <i className={this.props.icon} />
<span className='groupName'>{this.props.groupName}</span> <span className='groupName'>{this.props.groupName}</span>
+133 -86
View File
@@ -4,97 +4,120 @@
.snippetBar { .snippetBar {
@menuHeight : 25px; @menuHeight : 25px;
position : relative; position : relative;
height : @menuHeight; display : flex;
flex-wrap : wrap-reverse;
justify-content : space-between;
height : auto;
color : black; color : black;
background-color : #DDDDDD; background-color : #DDDDDD;
.editors { .snippets {
position : absolute;
top : 0px;
right : 0px;
display : flex; display : flex;
justify-content : space-between; justify-content : flex-start;
height : @menuHeight; min-width : 499.35px; //must be controlled every time an item is added, must be hardcoded for the wrapping as it is applied
& > div { }
width : @menuHeight;
height : @menuHeight; .editors {
line-height : @menuHeight; display : flex;
text-align : center; justify-content : flex-end;
cursor : pointer; min-width : 250px; //must be controlled every time an item is added, must be hardcoded for the wrapping as it is applied
&:hover,&.selected { background-color : #999999; }
&.text { &:only-child {min-width : unset; margin-left : auto;}
.tooltipLeft('Brew Editor');
} >div {
&.style { display : flex;
.tooltipLeft('Style Editor'); flex : 1;
} justify-content : space-around;
&.meta {
.tooltipLeft('Properties'); &:first-child { border-left : none; }
}
&.undo { & > div {
.tooltipLeft('Undo'); position : relative;
font-size : 0.75em; width : @menuHeight;
color : grey; height : @menuHeight;
&.active { color : inherit; } line-height : @menuHeight;
} text-align : center;
&.redo { cursor : pointer;
.tooltipLeft('Redo');
font-size : 0.75em; &.editorTool:not(.active) { cursor : not-allowed; }
color : grey;
&.active { color : inherit; } &:hover,&.selected { background-color : #999999; }
} &.text {
&.foldAll { .tooltipLeft('Brew Editor');
.tooltipLeft('Fold All');
font-size : 0.75em;
color : inherit;
}
&.unfoldAll {
.tooltipLeft('Unfold All');
font-size : 0.75em;
color : inherit;
}
&.history {
.tooltipLeft('History');
font-size : 0.75em;
color : grey;
position : relative;
&.active {
color : inherit;
} }
&>.dropdown{ &.style {
right : -1px; .tooltipLeft('Style Editor');
&>.snippet{ }
padding-right : 10px; &.meta {
.tooltipLeft('Properties');
}
&.snippet {
.tooltipLeft('Snippets');
}
&.undo {
.tooltipLeft('Undo');
font-size : 0.75em;
color : grey;
&.active { color : inherit; }
}
&.redo {
.tooltipLeft('Redo');
font-size : 0.75em;
color : grey;
&.active { color : inherit; }
}
&.foldAll {
.tooltipLeft('Fold All');
font-size : 0.75em;
color : grey;
&.active { color : inherit; }
}
&.unfoldAll {
.tooltipLeft('Unfold All');
font-size : 0.75em;
color : grey;
&.active { color : inherit; }
}
&.history {
.tooltipLeft('History');
position : relative;
font-size : 0.75em;
color : grey;
border : none;
&.active { color : inherit; }
& > .dropdown {
right : -1px;
& > .snippet { padding-right : 10px; }
} }
} }
} &.editorTheme {
&.editorTheme { .tooltipLeft('Editor Themes');
.tooltipLeft('Editor Themes'); font-size : 0.75em;
font-size : 0.75em; color : inherit;
color : black; &.active {
&.active { position : relative;
position : relative; background-color : #999999;
background-color : #999999; }
}
&.divider {
width : 5px;
background : linear-gradient(currentColor, currentColor) no-repeat center/1px 100%;
&:hover { background-color : inherit; }
} }
} }
&.divider { .themeSelector {
width : 5px; position : absolute;
background : linear-gradient(currentColor, currentColor) no-repeat center/1px 100%; top : 25px;
&:hover { background-color : inherit; } right : 0;
z-index : 10;
display : flex;
align-items : center;
justify-content : center;
width : 170px;
height : inherit;
background-color : inherit;
} }
} }
.themeSelector {
position : absolute;
top : 25px;
right : 0;
z-index : 10;
display : flex;
align-items : center;
justify-content : center;
width : 170px;
height : inherit;
background-color : inherit;
}
} }
.snippetBarButton { .snippetBarButton {
display : inline-block; display : inline-block;
@@ -104,6 +127,7 @@
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 {
@@ -120,7 +144,7 @@
.tooltipLeft('Edit Brew Properties'); .tooltipLeft('Edit Brew Properties');
} }
.snippetGroup { .snippetGroup {
border-right : 1px solid currentColor;
&:hover { &:hover {
& > .dropdown { visibility : visible; } & > .dropdown { visibility : visible; }
} }
@@ -128,9 +152,9 @@
position : absolute; position : absolute;
top : 100%; top : 100%;
z-index : 1000; z-index : 1000;
visibility : hidden;
padding : 0px; padding : 0px;
margin-left : -5px; margin-left : -5px;
visibility : hidden;
background-color : #DDDDDD; background-color : #DDDDDD;
.snippet { .snippet {
position : relative; position : relative;
@@ -142,11 +166,11 @@
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;
margin-left : 5px; margin-left : 5px;
@@ -179,6 +203,7 @@
} }
} }
.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;
@@ -204,4 +229,26 @@
} }
} }
} }
} .disabledSnippets {
color: grey;
cursor: not-allowed;
&:hover { background-color: #DDDDDD;}
}
}
@container editor (width < 750px) {
.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; }
}
}
@@ -1,149 +0,0 @@
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' }}>
<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;
@@ -0,0 +1,104 @@
import './tagInput.less';
import React, { useState, useEffect } from 'react';
import _ from '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>
);
};
export default TagInput;
+72 -80
View File
@@ -1,91 +1,83 @@
require('./homebrew.less');
const React = require('react');
const createClass = require('create-react-class');
const { StaticRouter:Router } = require('react-router-dom/server');
const { Route, Routes, useParams, useSearchParams } = require('react-router-dom');
const HomePage = require('./pages/homePage/homePage.jsx'); import 'core-js/es/string/to-well-formed.js'; //Polyfill for older browsers
const EditPage = require('./pages/editPage/editPage.jsx'); import './homebrew.less';
const UserPage = require('./pages/userPage/userPage.jsx'); import React from 'react';
const SharePage = require('./pages/sharePage/sharePage.jsx'); import { StaticRouter as Router, Route, Routes, useParams, useSearchParams } from 'react-router';
const NewPage = require('./pages/newPage/newPage.jsx');
const ErrorPage = require('./pages/errorPage/errorPage.jsx');
const VaultPage = require('./pages/vaultPage/vaultPage.jsx');
const AccountPage = require('./pages/accountPage/accountPage.jsx');
const WithRoute = (props)=>{ import { updateLocalStorage } from './utils/updateLocalStorage/updateLocalStorageKeys.js';
import HomePage from './pages/homePage/homePage.jsx';
import EditPage from './pages/editPage/editPage.jsx';
import UserPage from './pages/userPage/userPage.jsx';
import SharePage from './pages/sharePage/sharePage.jsx';
import NewPage from './pages/newPage/newPage.jsx';
import ErrorPage from './pages/errorPage/errorPage.jsx';
import VaultPage from './pages/vaultPage/vaultPage.jsx';
import AccountPage from './pages/accountPage/accountPage.jsx';
const WithRoute = ({ el: Element, ...rest })=>{
const params = useParams(); const params = useParams();
const [searchParams] = useSearchParams(); const [searchParams] = useSearchParams();
const queryParams = {}; const queryParams = Object.fromEntries(searchParams?.entries() || []);
for (const [key, value] of searchParams?.entries() || []) { return <Element {...rest} {...params} query={queryParams} />;
queryParams[key] = value;
}
const Element = props.el;
const allProps = {
...props,
...params,
query : queryParams,
el : undefined
};
return <Element {...allProps} />;
}; };
const Homebrew = createClass({ const Homebrew = (props)=>{
displayName : 'Homebrewery', const {
getDefaultProps : function() { url = '',
return { version = '0.0.0',
url : '', account = null,
welcomeText : '', config,
changelog : '', brew = {
version : '0.0.0', title : '',
account : null, text : '',
enable_v3 : false, shareId : null,
brew : { editId : null,
title : '', createdAt : null,
text : '', updatedAt : null,
shareId : null, lang : ''
editId : null, },
createdAt : null, userThemes,
updatedAt : null, brews
lang : '' } = props;
}
};
},
getInitialState : function() { global.account = account;
global.account = this.props.account; global.version = version;
global.version = this.props.version; global.config = config;
global.enable_v3 = this.props.enable_v3;
global.enable_themes = this.props.enable_themes;
global.config = this.props.config;
return {}; const backgroundObject = ()=>{
}, if(global.config.deployment || (config.local && config.development)){
const bgText = global.config.deployment || 'Local';
return {
backgroundImage : `url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' version='1.1' height='100px' width='200px'><text x='0' y='15' fill='%23fff7' font-size='20'>${bgText}</text></svg>")`
};
}
return null;
};
updateLocalStorage();
render : function (){ return (
return ( <Router location={url}>
<Router location={this.props.url}> <div className={`homebrew${(config.deployment || config.local) ? ' deployment' : ''}`} style={backgroundObject()}>
<div className='homebrew'> <Routes>
<Routes> <Route path='/edit/:id' element={<WithRoute el={EditPage} brew={brew} userThemes={userThemes}/>} />
<Route path='/edit/:id' element={<WithRoute el={EditPage} brew={this.props.brew} userThemes={this.props.userThemes}/>} /> <Route path='/share/:id' element={<WithRoute el={SharePage} brew={brew} />} />
<Route path='/share/:id' element={<WithRoute el={SharePage} brew={this.props.brew} />} /> <Route path='/new/:id' element={<WithRoute el={NewPage} brew={brew} userThemes={userThemes}/>} />
<Route path='/new/:id' element={<WithRoute el={NewPage} brew={this.props.brew} userThemes={this.props.userThemes}/>} /> <Route path='/new' element={<WithRoute el={NewPage} userThemes={userThemes}/> } />
<Route path='/new' element={<WithRoute el={NewPage} userThemes={this.props.userThemes}/> } /> <Route path='/user/:username' element={<WithRoute el={UserPage} brews={brews} />} />
<Route path='/user/:username' element={<WithRoute el={UserPage} brews={this.props.brews} />} /> <Route path='/vault' element={<WithRoute el={VaultPage}/>}/>
<Route path='/vault' element={<WithRoute el={VaultPage}/>}/> <Route path='/changelog' element={<WithRoute el={SharePage} brew={brew} disableMeta={true} />} />
<Route path='/changelog' element={<WithRoute el={SharePage} brew={this.props.brew} disableMeta={true} />} /> <Route path='/faq' element={<WithRoute el={SharePage} brew={brew} disableMeta={true} />} />
<Route path='/faq' element={<WithRoute el={SharePage} brew={this.props.brew} disableMeta={true} />} /> <Route path='/migrate' element={<WithRoute el={SharePage} brew={brew} disableMeta={true} />} />
<Route path='/migrate' element={<WithRoute el={SharePage} brew={this.props.brew} disableMeta={true} />} /> <Route path='/account' element={<WithRoute el={AccountPage} brew={brew} accountDetails={brew.accountDetails} />} />
<Route path='/account' element={<WithRoute el={AccountPage} brew={this.props.brew} accountDetails={this.props.brew.accountDetails} />} /> <Route path='/legacy' element={<WithRoute el={HomePage} brew={brew} />} />
<Route path='/legacy' element={<WithRoute el={HomePage} brew={this.props.brew} />} /> <Route path='/error' element={<WithRoute el={ErrorPage} brew={brew} />} />
<Route path='/error' element={<WithRoute el={ErrorPage} brew={this.props.brew} />} /> <Route path='/' element={<WithRoute el={HomePage} brew={brew} />} />
<Route path='/' element={<WithRoute el={HomePage} brew={this.props.brew} />} /> <Route path='/*' element={<WithRoute el={HomePage} brew={brew} />} />
<Route path='/*' element={<WithRoute el={HomePage} brew={this.props.brew} />} /> </Routes>
</Routes> </div>
</div> </Router>
</Router> );
); };
}
});
module.exports = Homebrew; module.exports = Homebrew;
+15 -17
View File
@@ -1,36 +1,34 @@
@import 'naturalcrit/styles/core.less'; @import 'naturalcrit/styles/core.less';
.homebrew{ .homebrew {
height : 100%; height : 100%;
.sitePage{ background-color:@steel;
&.deployment { background-color : darkred; }
.sitePage {
display : flex; display : flex;
height : 100%;
background-color : @steel;
flex-direction : column; flex-direction : column;
height : 100%;
overflow-y : hidden; overflow-y : hidden;
.content{ .content {
position : relative; position : relative;
height : calc(~"100% - 29px"); //Navbar height
flex : auto; flex : auto;
height : calc(~'100% - 29px'); //Navbar height
overflow-y : hidden; overflow-y : hidden;
} }
&.listPage .content { &.listPage .content {
overflow-y : scroll; overflow-y : scroll;
&::-webkit-scrollbar { &::-webkit-scrollbar {
width: 20px; width : 20px;
&:horizontal{ &:horizontal {
height: 20px; width : auto;
width:auto; height : 20px;
} }
&-thumb { &-thumb {
background: linear-gradient(90deg, #d3c1af 15px, #00000000 15px); background : linear-gradient(90deg, #D3C1AF 15px, #00000000 15px);
&:horizontal{ &:horizontal { background : linear-gradient(0deg, #D3C1AF 15px, #00000000 15px); }
background: linear-gradient(0deg, #d3c1af 15px, #00000000 15px);
}
}
&-corner {
visibility: hidden;
} }
&-corner { visibility : hidden; }
} }
} }
} }
+7 -7
View File
@@ -1,9 +1,9 @@
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const Nav = require('naturalcrit/nav/nav.jsx'); import request from 'superagent';
const request = require('superagent'); import Nav from './nav.jsx';
const Account = createClass({ const Account = createReactClass({
displayName : 'AccountNavItem', displayName : 'AccountNavItem',
getInitialState : function() { getInitialState : function() {
return { return {
@@ -70,7 +70,7 @@ const Account = createClass({
{global.account.username} {global.account.username}
</Nav.item> </Nav.item>
<Nav.item <Nav.item
href={`/user/${encodeURI(global.account.username)}`} href={`/user/${encodeURIComponent(global.account.username)}`}
color='yellow' color='yellow'
icon='fas fa-beer' icon='fas fa-beer'
> >
@@ -111,4 +111,4 @@ const Account = createClass({
} }
}); });
module.exports = Account; export default Account;
@@ -1,34 +0,0 @@
const React = require('react');
const createClass = require('create-react-class');
const cx = require('classnames');
const Nav = require('naturalcrit/nav/nav.jsx');
const MAX_TITLE_LENGTH = 50;
const EditTitle = createClass({
displayName : 'EditTitleNavItem',
getDefaultProps : function() {
return {
title : '',
onChange : function(){}
};
},
handleChange : function(e){
if(e.target.value.length > MAX_TITLE_LENGTH) return;
this.props.onChange(e.target.value);
},
render : function(){
return <Nav.item className='editTitle'>
<input placeholder='Brew Title' type='text' value={this.props.title} onChange={this.handleChange} />
<div className={cx('charCount', { 'max': this.props.title.length >= MAX_TITLE_LENGTH })}>
{this.props.title.length}/{MAX_TITLE_LENGTH}
</div>
</Nav.item>;
},
});
module.exports = EditTitle;
+138 -122
View File
@@ -1,131 +1,147 @@
require('./error-navitem.less'); import './error-navitem.less';
const React = require('react'); import React from 'react';
const Nav = require('naturalcrit/nav/nav.jsx'); import Nav from './nav.jsx';
const createClass = require('create-react-class');
const ErrorNavItem = createClass({ const ErrorNavItem = ({ error = '', clearError })=>{
getDefaultProps : function() { const response = error.response;
return { const errorCode = error.code;
error : '', const status = response?.status;
parent : null const HBErrorCode = response?.body?.HBErrorCode;
}; const message = response?.body?.message;
},
render : function() {
const clearError = ()=>{
const state = {
error : null
};
if(this.props.parent.state.isSaving) {
state.isSaving = false;
}
this.props.parent.setState(state);
};
const error = this.props.error; let errMsg = '';
const response = error.response; try {
const status = response.status; errMsg += `${error.toString()}\n\n`;
const HBErrorCode = response.body?.HBErrorCode; errMsg += `\`\`\`\n${error.stack}\n`;
const message = response.body?.message; errMsg += `${JSON.stringify(response?.error, null, ' ')}\n\`\`\``;
let errMsg = ''; console.log(errMsg);
try { } catch {}
errMsg += `${error.toString()}\n\n`;
errMsg += `\`\`\`\n${error.stack}\n`;
errMsg += `${JSON.stringify(response.error, null, ' ')}\n\`\`\``;
console.log(errMsg);
} catch (e){}
if(status === 409) {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
{message ?? 'Conflict: please refresh to get latest changes'}
</div>
</Nav.item>;
}
if(status === 412) {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
{message ?? 'Your client is out of date. Please save your changes elsewhere and refresh.'}
</div>
</Nav.item>;
}
if(HBErrorCode === '04') {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
You are no longer signed in as an author of
this brew! Were you signed out from a different
window? Visit our log in page, then try again!
<br></br>
<a target='_blank' rel='noopener noreferrer'
href={`https://www.naturalcrit.com/login?redirect=${window.location.href}`}>
<div className='confirm'>
Sign In
</div>
</a>
<div className='deny'>
Not Now
</div>
</div>
</Nav.item>;
}
if(response.body?.errors?.[0].reason == 'storageQuotaExceeded') {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
Can't save because your Google Drive seems to be full!
</div>
</Nav.item>;
}
if(response.req.url.match(/^\/api.*Google.*$/m)){
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
Looks like your Google credentials have
expired! Visit our log in page to sign out
and sign back in with Google,
then try saving again!
<br></br>
<a target='_blank' rel='noopener noreferrer'
href={`https://www.naturalcrit.com/login?redirect=${window.location.href}`}>
<div className='confirm'>
Sign In
</div>
</a>
<div className='deny'>
Not Now
</div>
</div>
</Nav.item>;
}
if(HBErrorCode === '09') {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
Looks like there was a problem retreiving
the theme, or a theme that it inherits,
for this brew. Verify that brew <a className='lowercase' target='_blank' rel='noopener noreferrer' href={`/share/${response.body.brewId}`}>
{response.body.brewId}</a> still exists!
</div>
</Nav.item>;
}
if(status === 409) {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'> return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops! Oops!
<div className='errorContainer'> <div className='errorContainer' onClick={clearError}>
Looks like there was a problem saving. <br /> {message ?? 'Conflict: please refresh to get latest changes'}
Report the issue <a target='_blank' rel='noopener noreferrer' href={`https://github.com/naturalcrit/homebrewery/issues/new?template=save_issue.yml&error-code=${encodeURIComponent(errMsg)}`}>
here
</a>.
</div> </div>
</Nav.item>; </Nav.item>;
} }
});
module.exports = ErrorNavItem; if(status === 412) {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
{message ?? 'Your client is out of date. Please save your changes elsewhere and refresh.'}
</div>
</Nav.item>;
}
if(HBErrorCode === '04') {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
You are no longer signed in as an author of
this brew! Were you signed out from a different
window? Visit our log in page, then try again!
<br></br>
<a target='_blank' rel='noopener noreferrer'
href={`https://www.naturalcrit.com/login?redirect=${window.location.href}`}>
<div className='confirm'>
Sign In
</div>
</a>
<div className='deny'>
Not Now
</div>
</div>
</Nav.item>;
}
if(response?.body?.errors?.[0].reason == 'storageQuotaExceeded') {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
Can't save because your Google Drive seems to be full!
</div>
</Nav.item>;
}
if(response?.req.url.match(/^\/api.*Google.*$/m)){
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
Looks like your Google credentials have
expired! Visit our log in page to sign out
and sign back in with Google,
then try saving again!
<br></br>
<a target='_blank' rel='noopener noreferrer'
href={`https://www.naturalcrit.com/login?redirect=${window.location.href}`}>
<div className='confirm'>
Sign In
</div>
</a>
<div className='deny'>
Not Now
</div>
</div>
</Nav.item>;
}
if(HBErrorCode === '09') {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
Looks like there was a problem retreiving
the theme, or a theme that it inherits,
for this brew. Verify that brew <a className='lowercase' target='_blank' rel='noopener noreferrer' href={`/share/${response.body.brewId}`}>
{response.body.brewId}</a> still exists!
</div>
</Nav.item>;
}
if(HBErrorCode === '10') {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
Looks like the brew you have selected
as a theme is not tagged for use as a
theme. Verify that
brew <a className='lowercase' target='_blank' rel='noopener noreferrer' href={`/share/${response.body.brewId}`}>
{response.body.brewId}</a> has the <span className='lowercase'>meta:theme</span> tag!
</div>
</Nav.item>;
}
if(HBErrorCode === '13') {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
Server has lost connection to the database.
</div>
</Nav.item>;
}
if(errorCode === 'ECONNABORTED') {
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer' onClick={clearError}>
The request to the server was interrupted or timed out.
This can happen due to a network issue, or if
trying to save a particularly large brew.
Please check your internet connection and try again.
</div>
</Nav.item>;
}
return <Nav.item className='save error' icon='fas fa-exclamation-triangle'>
Oops!
<div className='errorContainer'>
Looks like there was a problem saving. <br />
Report the issue <a target='_blank' rel='noopener noreferrer' href={`https://github.com/naturalcrit/homebrewery/issues/new?template=save_issue.yml&error-code=${encodeURIComponent(errMsg)}`}>
here
</a>.
</div>
</Nav.item>;
};
export default ErrorNavItem;
+65 -73
View File
@@ -1,78 +1,70 @@
.navItem.error { .navItem.error {
position : relative; position : relative;
background-color : @red; background-color : @red;
} }
.errorContainer{ .errorContainer {
animation-name: glideDown; position : absolute;
animation-duration: 0.4s; top : 100%;
position : absolute; left : 50%;
top : 100%; z-index : 1000;
left : 50%; width : 140px;
z-index : 1000; padding : 3px;
width : 140px; font-size : 10px;
padding : 3px; font-weight : 800;
color : white; color : white;
background-color : #333; text-align : center;
border : 3px solid #444; text-transform : uppercase;
border-radius : 5px; background-color : #333333;
transform : translate(-50% + 3px, 10px); border : 3px solid #444444;
text-align : center; border-radius : 5px;
font-size : 10px; transform : translate(-50% + 3px, 10px);
font-weight : 800; animation-name : glideDown;
text-transform : uppercase; animation-duration : 0.4s;
.lowercase { .lowercase { text-transform : none; }
text-transform : none; a { color : @teal; }
&::before {
position : absolute;
top : -23px;
left : 53px;
width : 0px;
height : 0px;
content : '';
border-top : 10px solid transparent;
border-right : 10px solid transparent;
border-bottom : 10px solid #444444;
border-left : 10px solid transparent;
}
&::after {
position : absolute;
top : -19px;
left : 53px;
width : 0px;
height : 0px;
content : '';
border-top : 10px solid transparent;
border-right : 10px solid transparent;
border-bottom : 10px solid #333333;
border-left : 10px solid transparent;
}
.deny {
display : inline-block;
width : 48%;
padding : 5px;
margin : 1px;
background-color : #333333;
border-left : 1px solid #666666;
.animate(background-color);
&:hover { background-color : red; }
}
.confirm {
display : inline-block;
width : 48%;
padding : 5px;
margin : 1px;
color : white;
background-color : #333333;
.animate(background-color);
&:hover { background-color : teal; }
} }
a{
color : @teal;
}
&:before {
content: "";
width: 0px;
height: 0px;
position: absolute;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 10px solid transparent;
border-bottom: 10px solid #444;
left: 53px;
top: -23px;
}
&:after {
content: "";
width: 0px;
height: 0px;
position: absolute;
border-left: 10px solid transparent;
border-right: 10px solid transparent;
border-top: 10px solid transparent;
border-bottom: 10px solid #333;
left: 53px;
top: -19px;
}
.deny {
width : 48%;
margin : 1px;
padding : 5px;
background-color : #333;
display : inline-block;
border-left : 1px solid #666;
.animate(background-color);
&:hover{
background-color : red;
}
}
.confirm {
width : 48%;
margin : 1px;
padding : 5px;
background-color : #333;
display : inline-block;
color : white;
.animate(background-color);
&:hover{
background-color : teal;
}
}
} }
+4 -4
View File
@@ -1,9 +1,9 @@
const React = require('react'); import React from 'react';
const dedent = require('dedent-tabs').default; import dedent from 'dedent';
const Nav = require('naturalcrit/nav/nav.jsx'); import Nav from './nav.jsx';
module.exports = function(props){ export default function(props){
return <Nav.dropdown> return <Nav.dropdown>
<Nav.item color='grey' icon='fas fa-question-circle'> <Nav.item color='grey' icon='fas fa-question-circle'>
need help? need help?
+7 -7
View File
@@ -1,11 +1,11 @@
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const Moment = require('moment'); import Moment from 'moment';
const Nav = require('naturalcrit/nav/nav.jsx'); import Nav from './nav.jsx';
const MetadataNav = createClass({ const MetadataNav = createReactClass({
displayName : 'MetadataNav', displayName : 'MetadataNav',
getDefaultProps : function() { getDefaultProps : function() {
return { return {
@@ -32,7 +32,7 @@ const MetadataNav = createClass({
return <> return <>
{this.props.brew.authors.map((author, idx, arr)=>{ {this.props.brew.authors.map((author, idx, arr)=>{
const spacer = arr.length - 1 == idx ? <></> : <span>, </span>; const spacer = arr.length - 1 == idx ? <></> : <span>, </span>;
return <span key={idx}><a className='userPageLink' href={`/user/${author}`}>{author}</a>{spacer}</span>; return <span key={idx}><a className='userPageLink' href={`/user/${encodeURIComponent(author)}`}>{author}</a>{spacer}</span>;
})} })}
</>; </>;
}, },
@@ -86,4 +86,4 @@ const MetadataNav = createClass({
}); });
module.exports = MetadataNav; export default MetadataNav;
@@ -1,20 +1,17 @@
require('client/homebrew/navbar/navbar.less'); import './navbar.less';
const React = require('react'); import React, { useState, useRef, useEffect } from 'react';
const { useState, useRef, useEffect } = React; import createReactClass from 'create-react-class';
const createClass = require('create-react-class'); import _ from 'lodash';
const _ = require('lodash'); import cx from 'classnames';
const cx = require('classnames');
const NaturalCritIcon = require('naturalcrit/svg/naturalcrit.svg.jsx'); import NaturalCritIcon from '../../components/svg/naturalcrit-d20.svg.jsx';
const Nav = { const Nav = {
base : createClass({ base : createReactClass({
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>;
} }
}), }),
@@ -27,7 +24,7 @@ const Nav = {
</a>; </a>;
}, },
section : createClass({ section : createReactClass({
displayName : 'Nav.section', displayName : 'Nav.section',
render : function(){ render : function(){
return <div className={`navSection ${this.props.className ?? ''}`}> return <div className={`navSection ${this.props.className ?? ''}`}>
@@ -36,7 +33,7 @@ const Nav = {
} }
}), }),
item : createClass({ item : createReactClass({
displayName : 'Nav.item', displayName : 'Nav.item',
getDefaultProps : function() { getDefaultProps : function() {
return { return {
@@ -119,4 +116,4 @@ const Nav = {
}; };
module.exports = Nav; export default Nav;
+7 -7
View File
@@ -1,11 +1,11 @@
require('./navbar.less'); import './navbar.less';
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const Nav = require('naturalcrit/nav/nav.jsx'); import Nav from './nav.jsx';
const PatreonNavItem = require('./patreon.navitem.jsx'); import PatreonNavItem from './patreon.navitem.jsx';
const Navbar = createClass({ const Navbar = createReactClass({
displayName : 'Navbar', displayName : 'Navbar',
getInitialState : function() { getInitialState : function() {
return { return {
@@ -49,4 +49,4 @@ const Navbar = createClass({
} }
}); });
module.exports = Navbar; export default Navbar;
+14 -12
View File
@@ -24,13 +24,12 @@
} }
.homebrew nav { .homebrew nav {
position : relative;
z-index : 2;
display : flex;
justify-content : space-between;
background-color : #333333; background-color : #333333;
.navContent {
position : relative;
z-index : 2;
display : flex;
justify-content : space-between;
}
.navSection { .navSection {
display : flex; display : flex;
align-items : center; align-items : center;
@@ -38,7 +37,10 @@
&:has(.brewTitle) { &:has(.brewTitle) {
flex-grow : 1; flex-grow : 1;
min-width : 300px; min-width : 300px;
}
>.brewTitle {
cursor:auto;
} }
} }
// "NaturalCrit" logo // "NaturalCrit" logo
@@ -83,8 +85,8 @@
font-weight : 800; font-weight : 800;
line-height : 13px; line-height : 13px;
color : white; color : white;
text-decoration : none;
text-transform : uppercase; text-transform : uppercase;
text-decoration : none;
cursor : pointer; cursor : pointer;
background-color : #333333; background-color : #333333;
i { i {
@@ -107,11 +109,11 @@
display : block; display : block;
width : 100%; width : 100%;
overflow : hidden; overflow : hidden;
text-overflow : ellipsis;
font-size : 12px; font-size : 12px;
font-weight : 800; font-weight : 800;
color : white; color : white;
text-align : center; text-align : center;
text-overflow : ellipsis;
text-transform : initial; text-transform : initial;
white-space : nowrap; white-space : nowrap;
background-color : transparent; background-color : transparent;
@@ -171,16 +173,16 @@
h4 { h4 {
box-sizing : border-box; box-sizing : border-box;
display : block; display : block;
flex-basis : 20%;
flex-grow : 1; flex-grow : 1;
flex-basis : 20%;
min-width : 76px; min-width : 76px;
padding : 5px 0; padding : 5px 0;
color : #BBBBBB; color : #BBBBBB;
text-align : center; text-align : center;
} }
p { p {
flex-basis : 80%;
flex-grow : 1; flex-grow : 1;
flex-basis : 80%;
padding : 5px 0; padding : 5px 0;
font-family : 'Open Sans', sans-serif; font-family : 'Open Sans', sans-serif;
font-size : 10px; font-size : 10px;
@@ -216,10 +218,10 @@
z-index : 10000; z-index : 10000;
box-sizing : border-box; box-sizing : border-box;
display : block; display : block;
visibility : hidden;
width : 100%; width : 100%;
padding : 13px 5px; padding : 13px 5px;
text-align : center; text-align : center;
visibility : hidden;
background-color : #333333; background-color : #333333;
} }
} }
+73 -34
View File
@@ -1,64 +1,103 @@
const React = require('react'); import React from 'react';
const _ = require('lodash'); import _ from 'lodash';
const Nav = require('naturalcrit/nav/nav.jsx'); import Nav from './nav.jsx';
const { splitTextStyleAndMetadata } = require('../../../shared/helpers.js'); // Importing the function from helpers.js import { splitTextStyleAndMetadata } from '../../../shared/helpers.js';
const BREWKEY = 'homebrewery-new'; const BREWKEY = 'HB_newPage_content';
const STYLEKEY = 'homebrewery-new-style'; const STYLEKEY = 'HB_newPage_style';
const METAKEY = 'homebrewery-new-meta'; const METAKEY = 'HB_newPage_meta';
const NewBrew = ()=>{ const NewBrew = ()=>{
const handleFileChange = (e)=>{ const handleFileChange = (e)=>{
const file = e.target.files[0]; const file = e.target.files[0];
if(file) { if(!file) return;
const reader = new FileReader();
reader.onload = (e)=>{ if(!confirmLocalStorageChange()) return;
const fileContent = e.target.result;
const newBrew = { const reader = new FileReader();
text : fileContent, reader.onload = (e)=>{
style : '' const fileContent = e.target.result;
}; const newBrew = { text: fileContent, style: '' };
if(fileContent.startsWith('```metadata')) {
splitTextStyleAndMetadata(newBrew); // Modify newBrew directly if(fileContent.startsWith('```metadata')) {
localStorage.setItem(BREWKEY, newBrew.text); splitTextStyleAndMetadata(newBrew);
localStorage.setItem(STYLEKEY, newBrew.style); localStorage.setItem(BREWKEY, newBrew.text);
localStorage.setItem(METAKEY, JSON.stringify(_.pick(newBrew, ['title', 'description', 'tags', 'systems', 'renderer', 'theme', 'lang']))); localStorage.setItem(STYLEKEY, newBrew.style);
window.location.href = '/new'; localStorage.setItem(METAKEY, JSON.stringify(
} else { _.pick(newBrew, ['title', 'description', 'tags', 'systems', 'renderer', 'theme', 'lang'])
alert('This file is invalid, please, enter a valid file'); ));
} window.location.href = '/new';
}; return;
reader.readAsText(file); }
}
const type = file.name.split('.').pop().toLowerCase();
alert(`This file is invalid: ${!type ? 'Missing file extension' :`.${type} files are not supported`}. Only .txt files exported from the Homebrewery are allowed.`);
console.log(file);
};
reader.readAsText(file);
}; };
const confirmLocalStorageChange = ()=>{
const currentText = localStorage.getItem(BREWKEY);
const currentStyle = localStorage.getItem(STYLEKEY);
const currentMeta = localStorage.getItem(METAKEY);
// TRUE if no data in any local storage key
// TRUE if data in any local storage key AND approval given
// FALSE if data in any local storage key AND approval declined
return (!(currentText || currentStyle || currentMeta) || confirm(
`You have made changes in the new brew space. If you continue, that information will be PERMANENTLY LOST.\nAre you sure you wish to continue?`
));
};
const clearLocalStorage = ()=>{
if(!confirmLocalStorageChange()) return;
localStorage.removeItem(BREWKEY);
localStorage.removeItem(STYLEKEY);
localStorage.removeItem(METAKEY);
window.location.href = '/new';
return;
};
return ( return (
<Nav.dropdown> <Nav.dropdown>
<Nav.item <Nav.item
className='new' className='new'
color='purple' color='purple'
icon='fa-solid fa-plus-square'> icon='fa-solid fa-plus-square'>
new new
</Nav.item> </Nav.item>
<Nav.item <Nav.item
className='fromBlank' className='new'
href='/new' href='/new'
newTab={true} newTab={true}
color='purple' color='purple'
icon='fa-solid fa-file'> icon='fa-solid fa-file'>
from blank resume draft
</Nav.item>
<Nav.item
className='fromBlank'
newTab={true}
color='yellow'
icon='fa-solid fa-file-circle-plus'
onClick={()=>{ clearLocalStorage(); }}>
from blank
</Nav.item> </Nav.item>
<Nav.item <Nav.item
className='fromFile' className='fromFile'
color='purple' color='green'
icon='fa-solid fa-upload' icon='fa-solid fa-upload'
onClick={()=>{ document.getElementById('uploadTxt').click(); }}> onClick={()=>{ document.getElementById('uploadTxt').click(); }}>
<input id='uploadTxt' className='newFromLocal' type='file' onChange={handleFileChange} style={{ display: 'none' }} /> <input id='uploadTxt' className='newFromLocal' type='file' onChange={handleFileChange} style={{ display: 'none' }} />
from file from file
</Nav.item> </Nav.item>
</Nav.dropdown> </Nav.dropdown>
); );
}; };
module.exports = NewBrew; export default NewBrew;
+3 -3
View File
@@ -1,7 +1,7 @@
const React = require('react'); import React from 'react';
const Nav = require('naturalcrit/nav/nav.jsx'); import Nav from './nav.jsx';
module.exports = function(props){ export default function(props){
return <Nav.item return <Nav.item
className='patreon' className='patreon'
newTab={true} newTab={true}
+4 -4
View File
@@ -1,8 +1,8 @@
const React = require('react'); import React from 'react';
const Nav = require('naturalcrit/nav/nav.jsx'); import Nav from './nav.jsx';
const { printCurrentBrew } = require('../../../shared/helpers.js'); import { printCurrentBrew } from '../../../shared/helpers.js';
module.exports = function(){ export default function(){
return <Nav.item onClick={printCurrentBrew} color='purple' icon='far fa-file-pdf'> return <Nav.item onClick={printCurrentBrew} color='purple' icon='far fa-file-pdf'>
get PDF get PDF
</Nav.item>; </Nav.item>;
+13 -13
View File
@@ -1,15 +1,15 @@
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const _ = require('lodash'); import _ from 'lodash';
const Moment = require('moment'); import Moment from 'moment';
const Nav = require('naturalcrit/nav/nav.jsx'); import Nav from './nav.jsx';
const EDIT_KEY = 'homebrewery-recently-edited'; const EDIT_KEY = 'HB_nav_recentlyEdited';
const VIEW_KEY = 'homebrewery-recently-viewed'; const VIEW_KEY = 'HB_nav_recentlyViewed';
const RecentItems = createClass({ const RecentItems = createReactClass({
DisplayName : 'RecentItems', DisplayName : 'RecentItems',
getDefaultProps : function() { getDefaultProps : function() {
return { return {
@@ -36,7 +36,7 @@ const RecentItems = createClass({
//== Add current brew to appropriate recent items list (depending on storageKey) ==// //== Add current brew to appropriate recent items list (depending on storageKey) ==//
if(this.props.storageKey == 'edit'){ if(this.props.storageKey == 'edit'){
let editId = this.props.brew.editId; let editId = this.props.brew.editId;
if(this.props.brew.googleId){ if(this.props.brew.googleId && !this.props.brew.stubbed){
editId = `${this.props.brew.googleId}${this.props.brew.editId}`; editId = `${this.props.brew.googleId}${this.props.brew.editId}`;
} }
edited = _.filter(edited, (brew)=>{ edited = _.filter(edited, (brew)=>{
@@ -51,7 +51,7 @@ const RecentItems = createClass({
} }
if(this.props.storageKey == 'view'){ if(this.props.storageKey == 'view'){
let shareId = this.props.brew.shareId; let shareId = this.props.brew.shareId;
if(this.props.brew.googleId){ if(this.props.brew.googleId && !this.props.brew.stubbed){
shareId = `${this.props.brew.googleId}${this.props.brew.shareId}`; shareId = `${this.props.brew.googleId}${this.props.brew.shareId}`;
} }
viewed = _.filter(viewed, (brew)=>{ viewed = _.filter(viewed, (brew)=>{
@@ -83,7 +83,7 @@ const RecentItems = createClass({
let edited = JSON.parse(localStorage.getItem(EDIT_KEY) || '[]'); let edited = JSON.parse(localStorage.getItem(EDIT_KEY) || '[]');
if(this.props.storageKey == 'edit') { if(this.props.storageKey == 'edit') {
let prevEditId = prevProps.brew.editId; let prevEditId = prevProps.brew.editId;
if(prevProps.brew.googleId){ if(prevProps.brew.googleId && !this.props.brew.stubbed){
prevEditId = `${prevProps.brew.googleId}${prevProps.brew.editId}`; prevEditId = `${prevProps.brew.googleId}${prevProps.brew.editId}`;
} }
@@ -91,7 +91,7 @@ const RecentItems = createClass({
return brew.id !== prevEditId; return brew.id !== prevEditId;
}); });
let editId = this.props.brew.editId; let editId = this.props.brew.editId;
if(this.props.brew.googleId){ if(this.props.brew.googleId && !this.props.brew.stubbed){
editId = `${this.props.brew.googleId}${this.props.brew.editId}`; editId = `${this.props.brew.googleId}${this.props.brew.editId}`;
} }
edited.unshift({ edited.unshift({
@@ -175,7 +175,7 @@ const RecentItems = createClass({
}); });
module.exports = { export default {
edited : (props)=>{ edited : (props)=>{
return <RecentItems return <RecentItems
-44
View File
@@ -1,44 +0,0 @@
const React = require('react');
const createClass = require('create-react-class');
const Nav = require('naturalcrit/nav/nav.jsx');
const MAIN_URL = 'https://www.reddit.com/r/UnearthedArcana/submit?selftext=true';
const RedditShare = createClass({
displayName : 'RedditShareNavItem',
getDefaultProps : function() {
return {
brew : {
title : '',
sharedId : '',
text : ''
}
};
},
getText : function(){
},
handleClick : function(){
const url = [
MAIN_URL,
`title=${encodeURIComponent(this.props.brew.title ? this.props.brew.title : 'Check out my brew!')}`,
`text=${encodeURIComponent(this.props.brew.text)}`
].join('&');
window.open(url, '_blank');
},
render : function(){
return <Nav.item icon='fa-reddit-alien' color='red' onClick={this.handleClick}>
share on reddit
</Nav.item>;
},
});
module.exports = RedditShare;
+35
View File
@@ -0,0 +1,35 @@
import React from 'react';
import dedent from 'dedent';
import Nav from './nav.jsx';
const getShareId = (brew)=>(
brew.googleId && !brew.stubbed
? brew.googleId + brew.shareId
: brew.shareId
);
const getRedditLink = (brew)=>{
const text = dedent`
Hey guys! I've been working on this homebrew. I'd love your feedback. Check it out.
**[Homebrewery Link](${global.config.baseUrl}/share/${getShareId(brew)})**`;
return `https://www.reddit.com/r/UnearthedArcana/submit?title=${encodeURIComponent(brew.title.toWellFormed())}&text=${encodeURIComponent(text)}`;
};
export default ({ brew })=>(
<Nav.dropdown>
<Nav.item color='teal' icon='fas fa-share-alt'>
share
</Nav.item>
<Nav.item color='blue' href={`/share/${getShareId(brew)}`}>
view
</Nav.item>
<Nav.item color='blue' onClick={()=>{navigator.clipboard.writeText(`${global.config.baseUrl}/share/${getShareId(brew)}`);}}>
copy url
</Nav.item>
<Nav.item color='blue' href={getRedditLink(brew)} newTab rel='noopener noreferrer'>
post to reddit
</Nav.item>
</Nav.dropdown>
);
+3 -3
View File
@@ -1,8 +1,8 @@
const React = require('react'); import React from 'react';
const Nav = require('naturalcrit/nav/nav.jsx'); import Nav from './nav.jsx';
module.exports = function (props) { export default function (props) {
return ( return (
<Nav.item <Nav.item
color='purple' color='purple'
@@ -1,7 +1,7 @@
const React = require('react'); import React from 'react';
const moment = require('moment'); import moment from 'moment';
const UIPage = require('../basePages/uiPage/uiPage.jsx'); import UIPage from '../basePages/uiPage/uiPage.jsx';
const NaturalCritIcon = require('naturalcrit/svg/naturalcrit.svg.jsx'); import NaturalCritIcon from '../../../components/svg/naturalcrit-d20.svg.jsx';
let SAVEKEY = ''; let SAVEKEY = '';
@@ -13,7 +13,7 @@ const AccountPage = (props)=>{
// initialize save location from local storage based on user id // initialize save location from local storage based on user id
React.useEffect(()=>{ React.useEffect(()=>{
if(!saveLocation && accountDetails.username) { if(!saveLocation && accountDetails.username) {
SAVEKEY = `HOMEBREWERY-DEFAULT-SAVE-LOCATION-${accountDetails.username}`; SAVEKEY = `HB_editor_defaultSave_${accountDetails.username}`;
// if no SAVEKEY in local storage, default save location to Google Drive if user has Google account. // if no SAVEKEY in local storage, default save location to Google Drive if user has Google account.
let saveLocation = window.localStorage.getItem(SAVEKEY); let saveLocation = window.localStorage.getItem(SAVEKEY);
saveLocation = saveLocation ?? (accountDetails.googleId ? 'GOOGLE-DRIVE' : 'HOMEBREWERY'); saveLocation = saveLocation ?? (accountDetails.googleId ? 'GOOGLE-DRIVE' : 'HOMEBREWERY');
@@ -79,4 +79,4 @@ const AccountPage = (props)=>{
</UIPage>); </UIPage>);
}; };
module.exports = AccountPage; export default AccountPage;
@@ -1,183 +1,178 @@
require('./brewItem.less'); import './brewItem.less';
const React = require('react'); import React, { useCallback } from 'react';
const createClass = require('create-react-class'); import moment from 'moment';
const moment = require('moment'); import request from '../../../../utils/request-middleware.js';
const request = require('../../../../utils/request-middleware.js');
const googleDriveIcon = require('../../../../googleDrive.svg'); import googleDriveIcon from '../../../../googleDrive.svg';
const homebreweryIcon = require('../../../../thumbnail.png'); import homebreweryIcon from '../../../../thumbnail.svg';
const dedent = require('dedent-tabs').default; import dedent from 'dedent';
const BrewItem = createClass({ const BrewItem = ({
displayName : 'BrewItem', brew = {
getDefaultProps : function() { title : '',
return { description : '',
brew : { authors : [],
title : '', stubbed : true,
description : '',
authors : [],
stubbed : true
},
updateListFilter : ()=>{},
reportError : ()=>{},
renderStorage : true
};
}, },
updateListFilter = ()=>{},
reportError = ()=>{},
renderStorage = true,
})=>{
deleteBrew : function(){ const deleteBrew = useCallback(()=>{
if(this.props.brew.authors.length <= 1){ if(brew.authors.length <= 1) {
if(!confirm('Are you sure you want to delete this brew? Because you are the only owner of this brew, the document will be deleted permanently.')) return; if(!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 REALLY sure? You will not be able to recover the document.')) return; if(!window.confirm('Are you REALLY sure? You will not be able to recover the document.')) return;
} else { } else {
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 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 REALLY sure? You will lose editor access to this document.')) return; if(!window.confirm('Are you REALLY sure? You will lose editor access to this document.')) return;
} }
request.delete(`/api/${this.props.brew.googleId ?? ''}${this.props.brew.editId}`) request.delete(`/api/${brew.googleId ?? ''}${brew.editId}`).send().end((err, res)=>{
.send() if(err) reportError(err); else window.location.reload();
.end((err, res)=>{ });
if(err) { }, [brew, reportError]);
this.props.reportError(err);
} else {
location.reload();
}
});
},
updateFilter : function(type, term){ const updateFilter = useCallback((type, term)=>updateListFilter(type, term), [updateListFilter]);
this.props.updateListFilter(type, term);
},
renderDeleteBrewLink : function(){ const renderDeleteBrewLink = ()=>{
if(!this.props.brew.editId) return; if(!brew.editId) return null;
return <a className='deleteLink' onClick={this.deleteBrew}> return (
<i className='fas fa-trash-alt' title='Delete' /> <a className='deleteLink' onClick={deleteBrew}>
</a>; <i className='fas fa-trash-alt' title='Delete' />
}, </a>
);
};
renderEditLink : function(){ const renderEditLink = ()=>{
if(!this.props.brew.editId) return; if(!brew.editId) return null;
let editLink = this.props.brew.editId; let editLink = brew.editId;
if(this.props.brew.googleId && !this.props.brew.stubbed) { if(brew.googleId && !brew.stubbed) editLink = brew.googleId + editLink;
editLink = this.props.brew.googleId + editLink;
return (
<a className='editLink' href={`/edit/${editLink}`} target='_blank' rel='noopener noreferrer'>
<i className='fas fa-pencil-alt' title='Edit' />
</a>
);
};
const renderShareLink = ()=>{
if(!brew.shareId) return null;
let shareLink = brew.shareId;
if(brew.googleId && !brew.stubbed) {
shareLink = brew.googleId + shareLink;
} }
return <a className='editLink' href={`/edit/${editLink}`} target='_blank' rel='noopener noreferrer'> return (
<i className='fas fa-pencil-alt' title='Edit' /> <a className='shareLink' href={`/share/${shareLink}`} target='_blank' rel='noopener noreferrer'>
</a>; <i className='fas fa-share-alt' title='Share' />
}, </a>
);
};
renderShareLink : function(){ const renderDownloadLink = ()=>{
if(!this.props.brew.shareId) return; if(!brew.shareId) return null;
let shareLink = this.props.brew.shareId; let shareLink = brew.shareId;
if(this.props.brew.googleId && !this.props.brew.stubbed) { if(brew.googleId && !brew.stubbed) {
shareLink = this.props.brew.googleId + shareLink; shareLink = brew.googleId + shareLink;
} }
return <a className='shareLink' href={`/share/${shareLink}`} target='_blank' rel='noopener noreferrer'> return (
<i className='fas fa-share-alt' title='Share' /> <a className='downloadLink' href={`/download/${shareLink}`}>
</a>; <i className='fas fa-download' title='Download' />
}, </a>
);
};
renderDownloadLink : function(){ const renderStorageIcon = ()=>{
if(!this.props.brew.shareId) return; if(!renderStorage) return null;
if(brew.googleId) {
let shareLink = this.props.brew.shareId; return (
if(this.props.brew.googleId && !this.props.brew.stubbed) { <span title={brew.webViewLink ? 'Your Google Drive Storage' : 'Another User\'s Google Drive Storage'}>
shareLink = this.props.brew.googleId + shareLink; <a href={brew.webViewLink} target='_blank'>
<img className='googleDriveIcon' src={googleDriveIcon} alt='googleDriveIcon' />
</a>
</span>
);
} }
return <a className='downloadLink' href={`/download/${shareLink}`}> return (
<i className='fas fa-download' title='Download' /> <span title='Homebrewery Storage'>
</a>; <img className='homebreweryIcon' src={homebreweryIcon} alt='homebreweryIcon' />
}, </span>
);
};
renderStorageIcon : function(){ if(Array.isArray(brew.tags)) {
if(!this.props.renderStorage) return; brew.tags = brew.tags?.filter((tag)=>tag); // remove tags that are empty strings
if(this.props.brew.googleId) { brew.tags.sort((a, b)=>{
return <span title={this.props.brew.webViewLink ? 'Your Google Drive Storage': 'Another User\'s Google Drive Storage'}> return a.indexOf(':') - b.indexOf(':') !== 0 ? a.indexOf(':') - b.indexOf(':') : a.toLowerCase().localeCompare(b.toLowerCase());
<a href={this.props.brew.webViewLink} target='_blank'> });
<img className='googleDriveIcon' src={googleDriveIcon} alt='googleDriveIcon' /> }
</a>
</span>;
}
return <span title='Homebrewery Storage'> const dateFormatString = 'YYYY-MM-DD HH:mm:ss';
<img className='homebreweryIcon' src={homebreweryIcon} alt='homebreweryIcon' />
</span>;
},
render : function(){ return (
const brew = this.props.brew; <div className='brewItem'>
if(Array.isArray(brew.tags)) { // temporary fix until dud tags are cleaned {brew.thumbnail && <div className='thumbnail' style={{ backgroundImage: `url(${brew.thumbnail})` }}></div>}
brew.tags = brew.tags?.filter((tag)=>tag); //remove tags that are empty strings
brew.tags.sort((a, b)=>{
return a.indexOf(':') - b.indexOf(':') != 0 ? a.indexOf(':') - b.indexOf(':') : a.toLowerCase().localeCompare(b.toLowerCase());
});
}
const dateFormatString = 'YYYY-MM-DD HH:mm:ss';
return <div className='brewItem'>
{brew.thumbnail &&
<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={()=>{this.updateFilter(tag);}}>{matches[2]}</span>; return <span key={idx} className={matches[1]} onClick={()=>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'/> {brew.authors?.map((author, index)=>( <i className='fas fa-user' />{' '}
{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">{author}</span> <span title="Username contained an email address; hidden to protect user's privacy">
: <a href={`/user/${author}`}>{author}</a> {author}
} </span>
) : (<a href={`/user/${encodeURIComponent(author)}`}>{author}</a>)}
{index < brew.authors.length - 1 && ', '} {index < brew.authors.length - 1 && ', '}
</React.Fragment> </React.Fragment>
))} ))}
</span> </span>
<br /> <br />
<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 title={dedent` <span
Created: ${moment(brew.createdAt).local().format(dateFormatString)} title={dedent` 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>
{this.renderStorageIcon()} {renderStorageIcon()}
</div> </div>
<div className='links'> <div className='links'>
{this.renderShareLink()} {renderShareLink()}
{this.renderEditLink()} {renderEditLink()}
{this.renderDownloadLink()} {renderDownloadLink()}
{this.renderDeleteBrewLink()} {renderDeleteBrewLink()}
</div> </div>
</div>; </div>
} );
}); };
module.exports = BrewItem; export default BrewItem;
@@ -1,148 +1,129 @@
.brewItem{ .brewItem {
position : relative; position : relative;
box-sizing : border-box;
display : inline-block; display : inline-block;
vertical-align : top;
box-sizing : border-box;
box-sizing : border-box;
overflow : hidden;
width : 48%; width : 48%;
min-height : 105px; min-height : 105px;
margin-right : 15px;
margin-bottom : 15px;
padding : 5px 15px 2px 6px; padding : 5px 15px 2px 6px;
padding-right : 15px; padding-right : 15px;
border : 1px solid #c9ad6a; margin-right : 15px;
margin-bottom : 15px;
overflow : hidden;
vertical-align : top;
background-color : #CAB2802E;
border : 1px solid #C9AD6A;
border-radius : 5px; border-radius : 5px;
box-shadow : 0px 4px 5px 0px #333333;
break-inside : avoid;
-webkit-column-break-inside : avoid; -webkit-column-break-inside : avoid;
page-break-inside : avoid; page-break-inside : avoid;
break-inside : avoid; .thumbnail {
box-shadow : 0px 4px 5px 0px #333; position : absolute;
background-color : #cab2802e; top : 0;
.thumbnail { right : 0;
position: absolute; z-index : -1;
width: 150px; width : 150px;
height: 100%; height : 100%;
top: 0; background-repeat : no-repeat;
right: 0; background-position : right top;
z-index: -1; background-size : contain;
background-size: contain; opacity : 50%;
background-repeat: no-repeat; -webkit-mask-image : linear-gradient(80deg, #00000000 20%, #005500 40%);
background-position: right top; mask-image : linear-gradient(80deg, #00000000 20%, #005500 40%);
mask-image: linear-gradient(80deg, #0000 20%, #050 40%);
-webkit-mask-image: linear-gradient(80deg, #0000 20%, #050 40%);
opacity: 50%;
} }
.text { .text {
min-height : 54px; min-height : 54px;
h4{ h4 {
margin-bottom : 5px; margin-bottom : 5px;
font-size : 2.2em; font-size : 2.2em;
} }
} }
.info{ .info {
position: initial; position : initial;
bottom: 2px; bottom : 2px;
font-family : ScalySansRemake; font-family : "ScalySansRemake";
font-size : 1.2em; font-size : 1.2em;
&>span{ & > span {
margin-right : 12px; margin-right : 12px;
line-height : 1.5em; line-height : 1.5em;
a { a { color : inherit; }
color:inherit;
}
} }
} }
.brewTags span { .brewTags span {
background-color: #c8ac6e3b; display : inline-block;
margin: 2px; padding : 2px;
padding: 2px; margin : 2px;
border: 1px solid #c8ac6e; font-weight : bold;
border-radius: 4px; white-space : nowrap;
white-space: nowrap; cursor : pointer;
display: inline-block; background-color : #C8AC6E3B;
font-weight: bold; border : 1px solid #C8AC6E;
border-color: currentColor; border-color : currentColor;
cursor : pointer; border-radius : 4px;
&:before { &::before {
font-family: 'Font Awesome 5 Free'; margin-right : 3px;
font-size: 12px; font-family : 'Font Awesome 6 Free';
margin-right: 3px; font-size : 12px;
} }
&.type { &.type {
background-color: #0080003b; color : #008000;
color: #008000; background-color : #0080003B;
&:before{ &::before { content : '\f0ad'; }
content: '\f0ad';
}
} }
&.group { &.group {
background-color: #5050503b; color : #000000;
color: #000000; background-color : #5050503B;
&:before{ &::before { content : '\f500'; }
content: '\f500';
}
} }
&.meta { &.meta {
background-color: #0000803b; color : #000080;
color: #000080; background-color : #0000803B;
&:before{ &::before { content : '\f05a'; }
content: '\f05a';
}
} }
&.system { &.system {
background-color: #8000003b; color : #800000;
color: #800000; background-color : #8000003B;
&:before{ &::before { content : '\f518'; }
content: '\f518';
}
} }
} }
&:hover{ &:hover {
.links{ .links { opacity : 1; }
opacity : 1;
}
} }
&:nth-child(2n + 1){ &:nth-child(2n + 1) { margin-right : 0px; }
margin-right : 0px; .links {
}
.links{
.animate(opacity); .animate(opacity);
position : absolute; position : absolute;
top : 0px; top : 0px;
right : 0px; right : 0px;
height : 100%;
width : 2em; width : 2em;
opacity : 0; height : 100%;
background-color : fade(black, 60%);
text-align : center; text-align : center;
a{ background-color : fade(black, 60%);
opacity : 0;
a {
.animate(opacity); .animate(opacity);
display : block; display : block;
margin : 8px 0px; margin : 8px 0px;
opacity : 0.6;
font-size : 1.3em; font-size : 1.3em;
color : white; color : white;
text-decoration : unset; text-decoration : unset;
&:hover{ opacity : 0.6;
opacity : 1; &:hover { opacity : 1; }
} i { cursor : pointer; }
i{
cursor : pointer;
}
} }
} }
.googleDriveIcon { .googleDriveIcon {
height : 18px;
padding : 0px; padding : 0px;
margin : -5px; margin : -5px;
height : 18px;
} }
.homebreweryIcon { .homebreweryIcon {
mix-blend-mode : darken; position : relative;
height : 24px; padding : 0px;
position : relative; top : 5px;
top : 5px; left : -7.5px;
left : -5px; height : 18px;
} }
} }
@@ -1,18 +1,20 @@
/*eslint max-lines: ["warn", {"max": 300, "skipBlankLines": true, "skipComments": true}]*/ /*eslint max-lines: ["warn", {"max": 300, "skipBlankLines": true, "skipComments": true}]*/
require('./listPage.less'); import './listPage.less';
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const _ = require('lodash'); import _ from 'lodash';
const moment = require('moment'); import moment from 'moment';
const BrewItem = require('./brewItem/brewItem.jsx'); import BrewItem from './brewItem/brewItem.jsx';
const USERPAGE_KEY_PREFIX = 'HOMEBREWERY-LISTPAGE'; const USERPAGE_SORT_DIR = 'HB_listPage_sortDir';
const USERPAGE_SORT_TYPE = 'HB_listPage_sortType';
const USERPAGE_GROUP_VISIBILITY_PREFIX = 'HB_listPage_visibility_group';
const DEFAULT_SORT_TYPE = 'alpha'; const DEFAULT_SORT_TYPE = 'alpha';
const DEFAULT_SORT_DIR = 'asc'; const DEFAULT_SORT_DIR = 'asc';
const ListPage = createClass({ const ListPage = createReactClass({
displayName : 'ListPage', displayName : 'ListPage',
getDefaultProps : function() { getDefaultProps : function() {
return { return {
@@ -50,12 +52,12 @@ const ListPage = createClass({
// LOAD FROM LOCAL STORAGE // LOAD FROM LOCAL STORAGE
if(typeof window !== 'undefined') { if(typeof window !== 'undefined') {
const newSortType = (this.state.sortType ?? (localStorage.getItem(`${USERPAGE_KEY_PREFIX}-SORTTYPE`) || DEFAULT_SORT_TYPE)); const newSortType = (this.state.sortType ?? (localStorage.getItem(USERPAGE_SORT_TYPE) || DEFAULT_SORT_TYPE));
const newSortDir = (this.state.sortDir ?? (localStorage.getItem(`${USERPAGE_KEY_PREFIX}-SORTDIR`) || DEFAULT_SORT_DIR)); const newSortDir = (this.state.sortDir ?? (localStorage.getItem(USERPAGE_SORT_DIR) || DEFAULT_SORT_DIR));
this.updateUrl(this.state.filterString, newSortType, newSortDir); this.updateUrl(this.state.filterString, newSortType, newSortDir);
const brewCollection = this.props.brewCollection.map((brewGroup)=>{ const brewCollection = this.props.brewCollection.map((brewGroup)=>{
brewGroup.visible = (localStorage.getItem(`${USERPAGE_KEY_PREFIX}-VISIBILITY-${brewGroup.class}`) ?? 'true')=='true'; brewGroup.visible = (localStorage.getItem(`${USERPAGE_GROUP_VISIBILITY_PREFIX}_${brewGroup.class}`) ?? 'true')=='true';
return brewGroup; return brewGroup;
}); });
@@ -73,10 +75,10 @@ const ListPage = createClass({
saveToLocalStorage : function() { saveToLocalStorage : function() {
this.state.brewCollection.map((brewGroup)=>{ this.state.brewCollection.map((brewGroup)=>{
localStorage.setItem(`${USERPAGE_KEY_PREFIX}-VISIBILITY-${brewGroup.class}`, `${brewGroup.visible}`); localStorage.setItem(`${USERPAGE_GROUP_VISIBILITY_PREFIX}_${brewGroup.class}`, `${brewGroup.visible}`);
}); });
localStorage.setItem(`${USERPAGE_KEY_PREFIX}-SORTTYPE`, this.state.sortType); localStorage.setItem(USERPAGE_SORT_TYPE, this.state.sortType);
localStorage.setItem(`${USERPAGE_KEY_PREFIX}-SORTDIR`, this.state.sortDir); localStorage.setItem(USERPAGE_SORT_DIR, this.state.sortDir);
}, },
renderBrews : function(brews){ renderBrews : function(brews){
@@ -277,4 +279,4 @@ const ListPage = createClass({
} }
}); });
module.exports = ListPage; export default ListPage;
@@ -1,5 +1,5 @@
.noColumns(){ .noColumns() {
column-count : auto; column-count : auto;
column-fill : auto; column-fill : auto;
column-gap : normal; column-gap : normal;
@@ -13,177 +13,151 @@
height : auto; height : auto;
min-height : 279.4mm; min-height : 279.4mm;
margin : 20px auto; margin : 20px auto;
contain : unset; contain : unset;
} }
.listPage{ .listPage {
.content{ .content {
z-index : 1; z-index : 1;
.page{ .page {
.noColumns() !important; //Needed to override PHB Theme since this is on a lower @layer .noColumns() !important; //Needed to override PHB Theme since this is on a lower @layer
&::after{ &::after { display : none; }
display : none; .noBrews {
}
.noBrews{
margin : 10px 0px; margin : 10px 0px;
font-size : 1.3em; font-size : 1.3em;
font-style : italic; font-style : italic;
} }
.brewCollection { .brewCollection {
h1:hover{ h1:hover { cursor : pointer; }
cursor: pointer;
}
.active::before, .inactive::before { .active::before, .inactive::before {
font-family: 'Font Awesome 5 Free'; padding-right : 0.5em;
font-weight: 900; font-family : 'Font Awesome 6 Free';
font-size: 0.6cm; font-size : 0.6cm;
padding-right: 0.5em; font-weight : 900;
}
.active {
color: var(--HB_Color_HeaderText);
}
.active::before {
content: '\f107';
}
.inactive {
color: #707070;
}
.inactive::before {
content: '\f105';
} }
.active { color : var(--HB_Color_HeaderText); }
.active::before { content : '\f107'; }
.inactive { color : #707070; }
.inactive::before { content : '\f105'; }
} }
} }
} }
.sort-container { .sort-container {
font-family : 'Open Sans', sans-serif; position : sticky;
position : sticky; top : 0;
top : 0; left : 0;
left : 0; z-index : 1;
width : 100%; display : flex;
height : 30px; flex-wrap : wrap;
background-color : #555; row-gap : 5px;
border-top : 1px solid #666; column-gap : 15px;
border-bottom : 1px solid #666; align-items : baseline;
color : white; justify-content : center;
text-align : center; width : 100%;
z-index : 1; height : 30px;
display : flex; font-family : 'Open Sans', sans-serif;
justify-content : center; color : white;
align-items : baseline; text-align : center;
column-gap : 15px; background-color : #555555;
row-gap : 5px; border-top : 1px solid #666666;
flex-wrap : wrap; border-bottom : 1px solid #666666;
h6{ h6 {
text-transform : uppercase;
font-family : 'Open Sans', sans-serif; font-family : 'Open Sans', sans-serif;
font-size : 11px; font-size : 11px;
font-weight : bold; font-weight : bold;
text-transform : uppercase;
} }
.sort-option { .sort-option {
display: flex; display : flex;
align-items: center; align-items : center;
padding: 0 8px; height : 100%;
color: #ccc; padding : 0 8px;
height: 100%; color : #CCCCCC;
&:hover{ &:hover { background-color : #444444; }
background-color : #444;
}
&.active { &.active {
font-weight: bold; font-weight : bold;
color: #ddd; color : #DDDDDD;
background-color: #333; background-color : #333333;
button { button {
color: white; height : 100%;
font-weight: 800; font-weight : 800;
height: 100%; color : white;
& + .sortDir { & + .sortDir { padding-left : 5px; }
padding-left: 5px;
} }
} }
}
} }
.filter-option { .filter-option {
margin-left: 20px; margin-left : 20px;
background-color : transparent !important;
font-size : 11px; font-size : 11px;
i{ background-color : transparent !important;
padding-right : 5px; i { padding-right : 5px; }
} }
button {
padding : 0;
font-family : 'Open Sans', sans-serif;
font-size : 11px;
font-weight : normal;
color : #CCCCCC;
text-transform : uppercase;
background-color : transparent;
} }
button{
background-color : transparent;
font-family : 'Open Sans', sans-serif;
text-transform : uppercase;
font-weight : normal;
font-size : 11px;
color : #ccc;
padding : 0;
}
} }
.tags-container { .tags-container {
height : 30px;
background-color : #555;
border-top : 1px solid #666;
border-bottom : 1px solid #666;
color : white;
display : flex; display : flex;
justify-content : center;
align-items : center;
column-gap : 15px;
row-gap : 5px;
flex-wrap : wrap; flex-wrap : wrap;
row-gap : 5px;
column-gap : 15px;
align-items : center;
justify-content : center;
height : 30px;
color : white;
background-color : #555555;
border-top : 1px solid #666666;
border-bottom : 1px solid #666666;
span { span {
padding : 3px;
font-family : 'Open Sans', sans-serif; font-family : 'Open Sans', sans-serif;
font-size : 11px; font-size : 11px;
font-weight : bold; font-weight : bold;
color : #DFDFDF;
cursor : pointer;
border : 1px solid; border : 1px solid;
border-radius : 3px; border-radius : 3px;
padding : 3px; &::before {
cursor : pointer; margin-right : 3px;
color: #dfdfdf; font-family : 'Font Awesome 6 Free';
&:before { font-size : 12px;
font-family: 'Font Awesome 5 Free';
font-size: 12px;
margin-right: 3px;
} }
&:after { &::after {
content: '\f00d'; margin-left : 3px;
font-family: 'Font Awesome 5 Free'; font-family : 'Font Awesome 6 Free';
font-size: 12px; font-size : 12px;
margin-left: 3px; content : '\f00d';
} }
&.type { &.type {
background-color: #008000; background-color : #008000;
border-color: #00a000; border-color : #00A000;
&:before{ &::before { content : '\f0ad'; }
content: '\f0ad';
}
} }
&.group { &.group {
background-color: #505050; background-color : #505050;
border-color: #000000; border-color : #000000;
&:before{ &::before { content : '\f500'; }
content: '\f500';
}
} }
&.meta { &.meta {
background-color: #000080; background-color : #000080;
border-color: #0000a0; border-color : #0000A0;
&:before{ &::before { content : '\f05a'; }
content: '\f05a';
}
} }
&.system { &.system {
background-color: #800000; background-color : #800000;
border-color: #a00000; border-color : #A00000;
&:before{ &::before { content : '\f518'; }
content: '\f518';
}
} }
} }
} }
@@ -1,16 +1,17 @@
require('./uiPage.less'); import './uiPage.less';
const React = require('react'); import React from 'react';
const createClass = require('create-react-class'); import createReactClass from 'create-react-class';
const Nav = require('naturalcrit/nav/nav.jsx'); import Nav from '../../../navbar/nav.jsx';
const Navbar = require('../../../navbar/navbar.jsx'); import Navbar from '../../../navbar/navbar.jsx';
const NewBrewItem = require('../../../navbar/newbrew.navitem.jsx'); import NewBrewItem from '../../../navbar/newbrew.navitem.jsx';
const HelpNavItem = require('../../../navbar/help.navitem.jsx'); import HelpNavItem from '../../../navbar/help.navitem.jsx';
const RecentNavItem = require('../../../navbar/recent.navitem.jsx').both; import RecentNavItems from '../../../navbar/recent.navitem.jsx';
const Account = require('../../../navbar/account.navitem.jsx'); const { both: RecentNavItem } = RecentNavItems;
import Account from '../../../navbar/account.navitem.jsx';
const UIPage = createClass({ const UIPage = createReactClass({
displayName : 'UIPage', displayName : 'UIPage',
render : function(){ render : function(){
@@ -35,4 +36,4 @@ const UIPage = createClass({
} }
}); });
module.exports = UIPage; export default UIPage;
@@ -1,7 +1,7 @@
.homebrew { .homebrew {
.uiPage.sitePage { .uiPage.sitePage {
.content { .content {
width : ~"min(90vw, 1000px)"; width : ~'min(90vw, 1000px)';
padding : 2% 4%; padding : 2% 4%;
margin-top : 25px; margin-top : 25px;
margin-right : auto; margin-right : auto;
@@ -17,19 +17,20 @@
border : 2px solid black; border : 2px solid black;
border-radius : 5px; border-radius : 5px;
button { button {
width : 125px;
margin-right : 5px;
color : black;
background-color : transparent; background-color : transparent;
border : 1px solid black; border : 1px solid black;
border-radius : 5px; border-radius : 5px;
width : 125px;
color : black;
margin-right : 5px;
&.active { &.active {
background-color: #0007; color : white;
color: white; background-color : #00000077;
&:before { &::before {
content: '\f00c'; margin-right : 5px;
font-family: 'FONT AWESOME 5 FREE'; font-family : 'Font Awesome 6 Free';
margin-right: 5px; font-weight : 900;
content : '\f00c';
} }
} }
} }
+334 -387
View File
@@ -1,472 +1,419 @@
/* eslint-disable max-lines */ /* eslint-disable max-lines */
require('./editPage.less'); import './editPage.less';
const React = require('react');
const _ = require('lodash');
const createClass = require('create-react-class');
const request = require('../../utils/request-middleware.js'); // Common imports
const { Meta } = require('vitreum/headtags'); import React, { useState, useEffect, useRef } from 'react';
import request from '../../utils/request-middleware.js';
import Markdown from '../../../../shared/markdown.js';
import _ from 'lodash';
const Nav = require('naturalcrit/nav/nav.jsx'); import { DEFAULT_BREW_LOAD } from '../../../../server/brewDefaults.js';
const Navbar = require('../../navbar/navbar.jsx'); import { printCurrentBrew, fetchThemeBundle, splitTextStyleAndMetadata } from '../../../../shared/helpers.js';
const NewBrew = require('../../navbar/newbrew.navitem.jsx'); import SplitPane from '../../../components/splitPane/splitPane.jsx';
const HelpNavItem = require('../../navbar/help.navitem.jsx'); import Editor from '../../editor/editor.jsx';
const PrintNavItem = require('../../navbar/print.navitem.jsx'); import BrewRenderer from '../../brewRenderer/brewRenderer.jsx';
const ErrorNavItem = require('../../navbar/error-navitem.jsx');
const Account = require('../../navbar/account.navitem.jsx');
const RecentNavItem = require('../../navbar/recent.navitem.jsx').both;
const SplitPane = require('naturalcrit/splitPane/splitPane.jsx'); import Nav from '../../navbar/nav.jsx';
const Editor = require('../../editor/editor.jsx'); import Navbar from '../../navbar/navbar.jsx';
const BrewRenderer = require('../../brewRenderer/brewRenderer.jsx'); import NewBrewItem from '../../navbar/newbrew.navitem.jsx';
import AccountNavItem from '../../navbar/account.navitem.jsx';
import ErrorNavItem from '../../navbar/error-navitem.jsx';
import HelpNavItem from '../../navbar/help.navitem.jsx';
import VaultNavItem from '../../navbar/vault.navitem.jsx';
import PrintNavItem from '../../navbar/print.navitem.jsx';
import RecentNavItems from '../../navbar/recent.navitem.jsx';
const { both: RecentNavItem } = RecentNavItems;
const LockNotification = require('./lockNotification/lockNotification.jsx'); // Page specific imports
import { Meta } from 'vitreum/headtags';
const Markdown = require('naturalcrit/markdown.js'); import { md5 } from 'hash-wasm';
import { gzipSync, strToU8 } from 'fflate';
const { DEFAULT_BREW_LOAD } = require('../../../../server/brewDefaults.js'); import { makePatches, stringifyPatches } from '@sanity/diff-match-patch';
const { printCurrentBrew, fetchThemeBundle } = require('../../../../shared/helpers.js');
import ShareNavItem from '../../navbar/share.navitem.jsx';
import LockNotification from './lockNotification/lockNotification.jsx';
import { updateHistory, versionHistoryGarbageCollection } from '../../utils/versionHistory.js'; import { updateHistory, versionHistoryGarbageCollection } from '../../utils/versionHistory.js';
import googleDriveIcon from '../../googleDrive.svg';
const googleDriveIcon = require('../../googleDrive.svg'); const SAVE_TIMEOUT = 10000;
const UNSAVED_WARNING_TIMEOUT = 900000; //Warn user afer 15 minutes of unsaved changes
const UNSAVED_WARNING_POPUP_TIMEOUT = 4000; //Show the warning for 4 seconds
const SAVE_TIMEOUT = 3000;
const EditPage = createClass({ const AUTOSAVE_KEY = 'HB_editor_autoSaveOn';
displayName : 'EditPage', const BREWKEY = 'HB_newPage_content';
getDefaultProps : function() { const STYLEKEY = 'HB_newPage_style';
return { const SNIPKEY = 'HB_newPage_snippets';
brew : DEFAULT_BREW_LOAD const METAKEY = 'HB_newPage_meta';
};
},
getInitialState : function() { const useLocalStorage = false;
return { const neverSaved = false;
brew : this.props.brew,
isSaving : false,
isPending : false,
alertTrashedGoogleBrew : this.props.brew.trashed,
alertLoginToTransfer : false,
saveGoogle : this.props.brew.googleId ? true : false,
confirmGoogleTransfer : false,
error : null,
htmlErrors : Markdown.validate(this.props.brew.text),
url : '',
autoSave : true,
autoSaveWarning : false,
unsavedTime : new Date(),
currentEditorViewPageNum : 1,
currentEditorCursorPageNum : 1,
currentBrewRendererPageNum : 1,
displayLockMessage : this.props.brew.lock || false,
themeBundle : {}
};
},
editor : React.createRef(null), const EditPage = (props)=>{
savedBrew : null, props = {
brew : DEFAULT_BREW_LOAD,
...props
};
componentDidMount : function(){ const [currentBrew , setCurrentBrew ] = useState(props.brew);
this.setState({ const [isSaving , setIsSaving ] = useState(false);
url : window.location.href const [lastSavedTime , setLastSavedTime ] = useState(new Date());
}); const [saveGoogle , setSaveGoogle ] = useState(!!props.brew.googleId);
const [error , setError ] = useState(null);
const [HTMLErrors , setHTMLErrors ] = useState(Markdown.validate(props.brew.text));
const [currentEditorViewPageNum , setCurrentEditorViewPageNum ] = useState(1);
const [currentEditorCursorPageNum, setCurrentEditorCursorPageNum] = useState(1);
const [currentBrewRendererPageNum, setCurrentBrewRendererPageNum] = useState(1);
const [themeBundle , setThemeBundle ] = useState({});
const [unsavedChanges , setUnsavedChanges ] = useState(false);
const [alertTrashedGoogleBrew , setAlertTrashedGoogleBrew ] = useState(props.brew.trashed);
const [alertLoginToTransfer , setAlertLoginToTransfer ] = useState(false);
const [confirmGoogleTransfer , setConfirmGoogleTransfer ] = useState(false);
const [autoSaveEnabled , setAutoSaveEnabled ] = useState(true);
const [warnUnsavedChanges , setWarnUnsavedChanges ] = useState(true);
this.savedBrew = JSON.parse(JSON.stringify(this.props.brew)); //Deep copy const editorRef = useRef(null);
const lastSavedBrew = useRef(_.cloneDeep(props.brew));
const saveTimeout = useRef(null);
const warnUnsavedTimeout = useRef(null);
const trySaveRef = useRef(trySave); // CTRL+S listener lives outside React and needs ref to use trySave with latest copy of brew
const unsavedChangesRef = useRef(unsavedChanges); // Similarly, onBeforeUnload lives outside React and needs ref to unsavedChanges
this.setState({ autoSave: JSON.parse(localStorage.getItem('AUTOSAVE_ON')) ?? true }, ()=>{ useEffect(()=>{
if(this.state.autoSave){ const autoSavePref = JSON.parse(localStorage.getItem(AUTOSAVE_KEY) ?? true);
this.trySave(); setAutoSaveEnabled(autoSavePref);
} else { setWarnUnsavedChanges(!autoSavePref);
this.setState({ autoSaveWarning: true }); setHTMLErrors(Markdown.validate(currentBrew.text));
fetchThemeBundle(setError, setThemeBundle, currentBrew.renderer, currentBrew.theme);
const handleControlKeys = (e)=>{
if(!(e.ctrlKey || e.metaKey)) return;
if(e.keyCode === 83) trySaveRef.current(true);
if(e.keyCode === 80) printCurrentBrew();
if([83, 80].includes(e.keyCode)) {
e.stopPropagation();
e.preventDefault();
} }
}); };
document.addEventListener('keydown', handleControlKeys);
window.onbeforeunload = ()=>{ window.onbeforeunload = ()=>{
if(this.state.isSaving || this.state.isPending){ if(unsavedChangesRef.current)
return 'You have unsaved changes!'; return 'You have unsaved changes!';
}
}; };
return ()=>{
document.removeEventListener('keydown', handleControlKeys);
window.onBeforeUnload = null;
};
}, []);
this.setState((prevState)=>({ useEffect(()=>{
htmlErrors : Markdown.validate(prevState.brew.text) trySaveRef.current = trySave;
})); unsavedChangesRef.current = unsavedChanges;
});
fetchThemeBundle(this, this.props.brew.renderer, this.props.brew.theme); useEffect(()=>{
const hasChange = !_.isEqual(currentBrew, lastSavedBrew.current);
setUnsavedChanges(hasChange);
document.addEventListener('keydown', this.handleControlKeys); if(autoSaveEnabled) trySave(false, hasChange);
}, }, [currentBrew]);
componentWillUnmount : function() {
window.onbeforeunload = function(){};
document.removeEventListener('keydown', this.handleControlKeys);
},
handleControlKeys : function(e){ useEffect(()=>{
if(!(e.ctrlKey || e.metaKey)) return; trySave(true);
const S_KEY = 83; }, [saveGoogle]);
const P_KEY = 80;
if(e.keyCode == S_KEY) this.trySave(true); const handleSplitMove = ()=>{
if(e.keyCode == P_KEY) printCurrentBrew(); editorRef.current?.update();
if(e.keyCode == P_KEY || e.keyCode == S_KEY){ };
e.stopPropagation();
e.preventDefault(); const handleBrewChange = (field)=>(value, subfield)=>{ //'text', 'style', 'snippets', 'metadata'
if(subfield == 'renderer' || subfield == 'theme')
fetchThemeBundle(setError, setThemeBundle, value.renderer, value.theme);
//If there are HTML errors, run the validator on every change to give quick feedback
if(HTMLErrors.length && (field == 'text' || field == 'snippets'))
setHTMLErrors(Markdown.validate(value));
if(field == 'metadata') setCurrentBrew((prev)=>({ ...prev, ...value }));
else setCurrentBrew((prev)=>({ ...prev, [field]: value }));
if(useLocalStorage) {
if(field == 'text') localStorage.setItem(BREWKEY, value);
if(field == 'style') localStorage.setItem(STYLEKEY, value);
if(field == 'snippets') localStorage.setItem(SNIPKEY, value);
if(field == 'metadata') localStorage.setItem(METAKEY, JSON.stringify({
renderer : value.renderer,
theme : value.theme,
lang : value.lang
}));
} }
}, };
handleSplitMove : function(){ const updateBrew = (newData)=>setCurrentBrew((prevBrew)=>({
this.editor.current.update(); ...prevBrew,
}, style : newData.style,
text : newData.text,
snippets : newData.snippets
}));
handleEditorViewPageChange : function(pageNumber){ const resetWarnUnsavedTimer = ()=>{
this.setState({ currentEditorViewPageNum: pageNumber }); setTimeout(()=>setWarnUnsavedChanges(false), UNSAVED_WARNING_POPUP_TIMEOUT); // Hide the warning after 4 seconds
}, clearTimeout(warnUnsavedTimeout.current);
warnUnsavedTimeout.current = setTimeout(()=>setWarnUnsavedChanges(true), UNSAVED_WARNING_TIMEOUT); // 15 minutes between unsaved work warnings
};
handleEditorCursorPageChange : function(pageNumber){ const handleGoogleClick = ()=>{
this.setState({ currentEditorCursorPageNum: pageNumber });
},
handleBrewRendererPageChange : function(pageNumber){
this.setState({ currentBrewRendererPageNum: pageNumber });
},
handleTextChange : function(text){
//If there are errors, run the validator on every change to give quick feedback
let htmlErrors = this.state.htmlErrors;
if(htmlErrors.length) htmlErrors = Markdown.validate(text);
this.setState((prevState)=>({
brew : { ...prevState.brew, text: text },
isPending : true,
htmlErrors : htmlErrors,
}), ()=>{if(this.state.autoSave) this.trySave();});
},
handleStyleChange : function(style){
this.setState((prevState)=>({
brew : { ...prevState.brew, style: style },
isPending : true
}), ()=>{if(this.state.autoSave) this.trySave();});
},
handleMetaChange : function(metadata, field=undefined){
if(field == 'theme' || field == 'renderer') // Fetch theme bundle only if theme or renderer was changed
fetchThemeBundle(this, metadata.renderer, metadata.theme);
this.setState((prevState)=>({
brew : {
...prevState.brew,
...metadata
},
isPending : true,
}), ()=>{if(this.state.autoSave) this.trySave();});
},
hasChanges : function(){
return !_.isEqual(this.state.brew, this.savedBrew);
},
updateBrew : function(newData){
this.setState((prevState)=>({
brew : {
...prevState.brew,
style : newData.style,
text : newData.text
}
}));
},
trySave : function(immediate=false){
if(!this.debounceSave) this.debounceSave = _.debounce(this.save, SAVE_TIMEOUT);
if(this.hasChanges()){
this.debounceSave();
} else {
this.debounceSave.cancel();
}
if(immediate) this.debounceSave.flush();
},
handleGoogleClick : function(){
if(!global.account?.googleId) { if(!global.account?.googleId) {
this.setState({ setAlertLoginToTransfer(true);
alertLoginToTransfer : true
});
return; return;
} }
this.setState((prevState)=>({
confirmGoogleTransfer : !prevState.confirmGoogleTransfer
}));
this.setState({
error : null,
isSaving : false
});
},
closeAlerts : function(event){ setConfirmGoogleTransfer((prev)=>!prev);
event.stopPropagation(); //Only handle click once so alert doesn't reopen setError(null);
this.setState({ };
alertTrashedGoogleBrew : false,
alertLoginToTransfer : false,
confirmGoogleTransfer : false
});
},
toggleGoogleStorage : function(){ const closeAlerts = (e)=>{
this.setState((prevState)=>({ e.stopPropagation(); //Only handle click once so alert doesn't reopen
saveGoogle : !prevState.saveGoogle, setAlertTrashedGoogleBrew(false);
isSaving : false, setAlertLoginToTransfer(false);
error : null setConfirmGoogleTransfer(false);
}), ()=>this.save()); };
},
save : async function(){ const toggleGoogleStorage = ()=>{
if(this.debounceSave && this.debounceSave.cancel) this.debounceSave.cancel(); setSaveGoogle((prev)=>!prev);
setError(null);
};
this.setState((prevState)=>({ const trySave = (immediate = false, hasChanges = true)=>{
isSaving : true, clearTimeout(saveTimeout.current);
error : null, if(isSaving) return;
htmlErrors : Markdown.validate(prevState.brew.text) if(!hasChanges && !immediate) return;
})); const newTimeout = immediate ? 0 : SAVE_TIMEOUT;
updateHistory(this.state.brew); saveTimeout.current = setTimeout(async ()=>{
versionHistoryGarbageCollection(); setIsSaving(true);
setError(null);
const transfer = this.state.saveGoogle == _.isNil(this.state.brew.googleId); await save(currentBrew, saveGoogle)
const brew = this.state.brew;
brew.pageCount = ((brew.renderer=='legacy' ? brew.text.match(/\\page/g) : brew.text.match(/^\\page$/gm)) || []).length + 1;
const params = `${transfer ? `?${this.state.saveGoogle ? 'saveToGoogle' : 'removeFromGoogle'}=true` : ''}`;
const res = await request
.put(`/api/update/${brew.editId}${params}`)
.send(brew)
.catch((err)=>{ .catch((err)=>{
console.log('Error Updating Local Brew'); setError(err);
this.setState({ error: err }); });
setIsSaving(false);
setLastSavedTime(new Date());
if(!autoSaveEnabled) resetWarnUnsavedTimer();
}, newTimeout);
};
const save = async (brew, saveToGoogle)=>{
setHTMLErrors(Markdown.validate(brew.text));
await updateHistory(brew).catch(console.error);
await versionHistoryGarbageCollection().catch(console.error);
//Prepare content to send to server
const brewToSave = {
...brew,
text : brew.text.normalize('NFC'),
pageCount : ((brew.renderer === 'legacy' ? brew.text.match(/\\page/g) : brew.text.match(/^\\page$/gm)) || []).length + 1,
patches : stringifyPatches(makePatches(encodeURI(lastSavedBrew.current.text.normalize('NFC')), encodeURI(brew.text.normalize('NFC')))),
hash : await md5(lastSavedBrew.current.text.normalize('NFC')),
textBin : undefined,
version : lastSavedBrew.current.version
};
const compressedBrew = gzipSync(strToU8(JSON.stringify(brewToSave)));
const transfer = saveToGoogle === _.isNil(brew.googleId);
const params = transfer ? `?${saveToGoogle ? 'saveToGoogle' : 'removeFromGoogle'}=true` : '';
const res = await request
.put(`/api/update/${brewToSave.editId}${params}`)
.set('Content-Encoding', 'gzip')
.set('Content-Type', 'application/json')
.send(compressedBrew)
.catch((err)=>{
console.error('Error Updating Local Brew');
setError(err);
}); });
if(!res) return; if(!res) return;
this.savedBrew = res.body; const updatedFields = {
history.replaceState(null, null, `/edit/${this.savedBrew.editId}`); googleId : res.body.googleId ?? null,
editId : res.body.editId,
shareId : res.body.shareId,
version : res.body.version
};
this.setState((prevState)=>({ lastSavedBrew.current = {
brew : { ...prevState.brew, ...brew,
googleId : this.savedBrew.googleId ? this.savedBrew.googleId : null, ...updatedFields
editId : this.savedBrew.editId, };
shareId : this.savedBrew.shareId,
version : this.savedBrew.version setCurrentBrew((prevBrew)=>({
}, ...prevBrew,
isPending : false, ...updatedFields
isSaving : false,
unsavedTime : new Date()
})); }));
},
renderGoogleDriveIcon : function(){ history.replaceState(null, null, `/edit/${res.body.editId}`);
return <Nav.item className='googleDriveStorage' onClick={this.handleGoogleClick}> };
<img src={googleDriveIcon} className={this.state.saveGoogle ? '' : 'inactive'} alt='Google Drive icon'/>
{this.state.confirmGoogleTransfer && const renderGoogleDriveIcon = ()=>(
<div className='errorContainer' onClick={this.closeAlerts}> <Nav.item className='googleDriveStorage' onClick={handleGoogleClick}>
{ this.state.saveGoogle <img src={googleDriveIcon} className={saveGoogle ? '' : 'inactive'} alt='Google Drive icon' />
? `Would you like to transfer this brew from your Google Drive storage back to the Homebrewery?`
: `Would you like to transfer this brew from the Homebrewery to your personal Google Drive storage?` {confirmGoogleTransfer && (
} <div className='errorContainer' onClick={closeAlerts}>
{saveGoogle
? 'Would you like to transfer this brew from your Google Drive storage back to the Homebrewery?'
: 'Would you like to transfer this brew from the Homebrewery to your personal Google Drive storage?'}
<br /> <br />
<div className='confirm' onClick={this.toggleGoogleStorage}> <div className='confirm' onClick={toggleGoogleStorage}> Yes </div>
Yes <div className='deny'> No </div>
</div>
<div className='deny'>
No
</div>
</div> </div>
} )}
{this.state.alertLoginToTransfer && {alertLoginToTransfer && (
<div className='errorContainer' onClick={this.closeAlerts}> <div className='errorContainer' onClick={closeAlerts}>
You must be signed in to a Google account to transfer You must be signed in to a Google account to transfer between the homebrewery and Google Drive!
between the homebrewery and Google Drive! <a target='_blank' rel='noopener noreferrer' href={`https://www.naturalcrit.com/login?redirect=${window.location.href}`}>
<a target='_blank' rel='noopener noreferrer' <div className='confirm'> Sign In </div>
href={`https://www.naturalcrit.com/login?redirect=${this.state.url}`}>
<div className='confirm'>
Sign In
</div>
</a> </a>
<div className='deny'> <div className='deny'> Not Now </div>
Not Now
</div>
</div> </div>
} )}
{this.state.alertTrashedGoogleBrew && {alertTrashedGoogleBrew && (
<div className='errorContainer' onClick={this.closeAlerts}> <div className='errorContainer' onClick={closeAlerts}>
This brew is currently in your Trash folder on Google Drive!<br />If you want to keep it, make sure to move it before it is deleted permanently!<br /> This brew is currently in your Trash folder on Google Drive!<br />
<div className='confirm'> If you want to keep it, make sure to move it before it is deleted permanently!<br />
OK <div className='confirm'> OK </div>
</div>
</div> </div>
} )}
</Nav.item>; </Nav.item>
}, );
renderSaveButton : function(){ const renderSaveButton = ()=>{
if(this.state.autoSaveWarning && this.hasChanges()){ // #1 - Currently saving, show SAVING
this.setAutosaveWarning(); if(isSaving)
const elapsedTime = Math.round((new Date() - this.state.unsavedTime) / 1000 / 60); return <Nav.item className='save' icon='fas fa-spinner fa-spin'>saving...</Nav.item>;
const text = elapsedTime == 0 ? 'Autosave is OFF.' : `Autosave is OFF, and you haven't saved for ${elapsedTime} minutes.`;
// #2 - Unsaved changes exist, autosave is OFF and warning timer has expired, show AUTOSAVE WARNING
if(unsavedChanges && warnUnsavedChanges) {
resetWarnUnsavedTimer();
const elapsedTime = Math.round((new Date() - lastSavedTime) / 1000 / 60);
const text = elapsedTime === 0
? 'Autosave is OFF.'
: `Autosave is OFF, and you haven't saved for ${elapsedTime} minutes.`;
return <Nav.item className='save error' icon='fas fa-exclamation-circle'> return <Nav.item className='save error' icon='fas fa-exclamation-circle'>
Reminder... Reminder...
<div className='errorContainer'> <div className='errorContainer'>{text}</div>
{text}
</div>
</Nav.item>; </Nav.item>;
} }
if(this.state.isSaving){ // #3 - Unsaved changes exist, click to save, show SAVE NOW
return <Nav.item className='save' icon='fas fa-spinner fa-spin'>saving...</Nav.item>; if(unsavedChanges)
} return <Nav.item className='save' onClick={()=>trySave(true)} color='blue' icon='fas fa-save'>save now</Nav.item>;
if(this.state.isPending && this.hasChanges()){
return <Nav.item className='save' onClick={this.save} color='blue' icon='fas fa-save'>Save Now</Nav.item>;
}
if(!this.state.isPending && !this.state.isSaving && this.state.autoSave){
return <Nav.item className='save saved'>auto-saved.</Nav.item>;
}
if(!this.state.isPending && !this.state.isSaving){
return <Nav.item className='save saved'>saved.</Nav.item>;
}
},
handleAutoSave : function(){ // #4 - No unsaved changes, autosave is ON, show AUTO-SAVED
if(this.warningTimer) clearTimeout(this.warningTimer); if(autoSaveEnabled)
this.setState((prevState)=>({ return <Nav.item className='save saved'>auto-saved</Nav.item>;
autoSave : !prevState.autoSave,
autoSaveWarning : prevState.autoSave
}), ()=>{
localStorage.setItem('AUTOSAVE_ON', JSON.stringify(this.state.autoSave));
});
},
setAutosaveWarning : function(){ // #5 - No unsaved changes, and has never been saved, hide the button
setTimeout(()=>this.setState({ autoSaveWarning: false }), 4000); // 4 seconds to display if(neverSaved)
this.warningTimer = setTimeout(()=>{this.setState({ autoSaveWarning: true });}, 900000); // 15 minutes between warnings return <Nav.item className='save neverSaved'>save now</Nav.item>;
this.warningTimer;
},
errorReported : function(error) { // DEFAULT - No unsaved changes, show SAVED
this.setState({ return <Nav.item className='save saved'>saved</Nav.item>;
error };
});
},
renderAutoSaveButton : function(){ const toggleAutoSave = ()=>{
return <Nav.item onClick={this.handleAutoSave}> clearTimeout(warnUnsavedTimeout.current);
Autosave <i className={this.state.autoSave ? 'fas fa-power-off active' : 'fas fa-power-off'}></i> clearTimeout(saveTimeout.current);
</Nav.item>; localStorage.setItem(AUTOSAVE_KEY, JSON.stringify(!autoSaveEnabled));
}, setAutoSaveEnabled(!autoSaveEnabled);
setWarnUnsavedChanges(autoSaveEnabled);
};
processShareId : function() { const renderAutoSaveButton = ()=>(
return this.state.brew.googleId && !this.state.brew.stubbed ? <Nav.item onClick={toggleAutoSave}>
this.state.brew.googleId + this.state.brew.shareId : Autosave <i className={autoSaveEnabled ? 'fas fa-power-off active' : 'fas fa-power-off'}></i>
this.state.brew.shareId; </Nav.item>
}, );
getRedditLink : function(){ const clearError = ()=>{
setError(null);
const shareLink = this.processShareId(); setIsSaving(false);
const systems = this.props.brew.systems.length > 0 ? ` [${this.props.brew.systems.join(' - ')}]` : ''; };
const title = `${this.props.brew.title} ${systems}`;
const text = `Hey guys! I've been working on this homebrew. I'd love your feedback. Check it out.
**[Homebrewery Link](${global.config.publicUrl}/share/${shareLink})**`;
return `https://www.reddit.com/r/UnearthedArcana/submit?title=${encodeURIComponent(title)}&text=${encodeURIComponent(text)}`;
},
renderNavbar : function(){
const shareLink = this.processShareId();
const renderNavbar = ()=>{
return <Navbar> return <Navbar>
<Nav.section> <Nav.section>
<Nav.item className='brewTitle'>{this.state.brew.title}</Nav.item> <Nav.item className='brewTitle'>{currentBrew.title}</Nav.item>
</Nav.section> </Nav.section>
<Nav.section> <Nav.section>
{this.renderGoogleDriveIcon()} {renderGoogleDriveIcon()}
{this.state.error ? {error
<ErrorNavItem error={this.state.error} parent={this}></ErrorNavItem> : ? <ErrorNavItem error={error} clearError={clearError} />
<Nav.dropdown className='save-menu'> : <Nav.dropdown className='save-menu'>
{this.renderSaveButton()} {renderSaveButton()}
{this.renderAutoSaveButton()} {renderAutoSaveButton()}
</Nav.dropdown> </Nav.dropdown>}
} <NewBrewItem />
<NewBrew />
<HelpNavItem/>
<Nav.dropdown>
<Nav.item color='teal' icon='fas fa-share-alt'>
share
</Nav.item>
<Nav.item color='blue' href={`/share/${shareLink}`}>
view
</Nav.item>
<Nav.item color='blue' onClick={()=>{navigator.clipboard.writeText(`${global.config.publicUrl}/share/${shareLink}`);}}>
copy url
</Nav.item>
<Nav.item color='blue' href={this.getRedditLink()} newTab={true} rel='noopener noreferrer'>
post to reddit
</Nav.item>
</Nav.dropdown>
<PrintNavItem /> <PrintNavItem />
<RecentNavItem brew={this.state.brew} storageKey='edit' /> <HelpNavItem />
<Account /> <VaultNavItem />
<ShareNavItem brew={currentBrew} />
<RecentNavItem brew={currentBrew} storageKey='edit' />
<AccountNavItem/>
</Nav.section> </Nav.section>
</Navbar>; </Navbar>;
}, };
render : function(){ return (
return <div className='editPage sitePage'> <div className='editPage sitePage'>
<Meta name='robots' content='noindex, nofollow' /> <Meta name='robots' content='noindex, nofollow' />
{this.renderNavbar()}
{renderNavbar()}
{currentBrew.lock && <LockNotification shareId={currentBrew.shareId} message={currentBrew.lock.editMessage} reviewRequested={currentBrew.lock.reviewRequested}/>}
<div className='content'> <div className='content'>
{this.props.brew.lock && <LockNotification shareId={this.props.brew.shareId} message={this.props.brew.lock.editMessage} />} <SplitPane onDragFinish={handleSplitMove}>
<SplitPane onDragFinish={this.handleSplitMove}>
<Editor <Editor
ref={this.editor} ref={editorRef}
brew={this.state.brew} brew={currentBrew}
onTextChange={this.handleTextChange} onBrewChange={handleBrewChange}
onStyleChange={this.handleStyleChange} reportError={setError}
onMetaChange={this.handleMetaChange} renderer={currentBrew.renderer}
reportError={this.errorReported} userThemes={props.userThemes}
renderer={this.state.brew.renderer} themeBundle={themeBundle}
userThemes={this.props.userThemes} updateBrew={updateBrew}
snippetBundle={this.state.themeBundle.snippets} onCursorPageChange={setCurrentEditorCursorPageNum}
updateBrew={this.updateBrew} onViewPageChange={setCurrentEditorViewPageNum}
onCursorPageChange={this.handleEditorCursorPageChange} currentEditorViewPageNum={currentEditorViewPageNum}
onViewPageChange={this.handleEditorViewPageChange} currentEditorCursorPageNum={currentEditorCursorPageNum}
currentEditorViewPageNum={this.state.currentEditorViewPageNum} currentBrewRendererPageNum={currentBrewRendererPageNum}
currentEditorCursorPageNum={this.state.currentEditorCursorPageNum}
currentBrewRendererPageNum={this.state.currentBrewRendererPageNum}
/> />
<BrewRenderer <BrewRenderer
text={this.state.brew.text} text={currentBrew.text}
style={this.state.brew.style} style={currentBrew.style}
renderer={this.state.brew.renderer} renderer={currentBrew.renderer}
theme={this.state.brew.theme} theme={currentBrew.theme}
themeBundle={this.state.themeBundle} themeBundle={themeBundle}
errors={this.state.htmlErrors} errors={HTMLErrors}
lang={this.state.brew.lang} lang={currentBrew.lang}
onPageChange={this.handleBrewRendererPageChange} onPageChange={setCurrentBrewRendererPageNum}
currentEditorViewPageNum={this.state.currentEditorViewPageNum} currentEditorViewPageNum={currentEditorViewPageNum}
currentEditorCursorPageNum={this.state.currentEditorCursorPageNum} currentEditorCursorPageNum={currentEditorCursorPageNum}
currentBrewRendererPageNum={this.state.currentBrewRendererPageNum} currentBrewRendererPageNum={currentBrewRendererPageNum}
allowPrint={true} allowPrint={true}
/> />
</SplitPane> </SplitPane>
</div> </div>
</div>; </div>
} );
}); };
module.exports = EditPage; export default EditPage;
+13 -17
View File
@@ -1,29 +1,25 @@
@keyframes glideDown { @keyframes glideDown {
0% {transform : translate(-50% + 3px, 0px); 0% {
opacity : 0;} opacity : 0;transform : translate(-50% + 3px, 0px);}
100% {transform : translate(-50% + 3px, 10px); 100% {
opacity : 1;} opacity : 1;transform : translate(-50% + 3px, 10px);}
} }
.editPage{ .editPage {
.navItem.save{ .navItem.save {
position : relative;
width : 106px; width : 106px;
text-align : center; text-align : center;
position : relative; &.saved {
&.saved{ color : #666666;
cursor : initial; cursor : initial;
color : #666;
} }
} }
.googleDriveStorage { .googleDriveStorage { position : relative; }
position : relative; .googleDriveStorage img {
} height : 18px;
.googleDriveStorage img{
height : 18px;
padding : 0px; padding : 0px;
margin : -5px; margin : -5px;
&.inactive { &.inactive { filter : grayscale(1); }
filter: grayscale(1);
}
} }
} }
@@ -1,17 +1,30 @@
require('./lockNotification.less'); import './lockNotification.less';
const React = require('react'); import * as React from 'react';
import request from '../../../utils/request-middleware.js';
import Dialog from '../../../../components/dialog.jsx'; import Dialog from '../../../../components/dialog.jsx';
function LockNotification(props) { function LockNotification(props) {
props = { props = {
shareId : 0, shareId : 0,
disableLock : ()=>{}, disableLock : ()=>{},
message : '', lock : {},
message : 'Unable to retrieve Lock Message',
reviewRequested : false,
...props ...props
}; };
const removeLock = ()=>{ const [reviewState, setReviewState] = React.useState(props.reviewRequested);
alert(`Not yet implemented - ID ${props.shareId}`);
const removeLock = async ()=>{
await request.put(`/api/lock/review/request/${props.shareId}`)
.then(()=>{
setReviewState(true);
});
};
const renderReviewButton = function(){
if(reviewState){ return <button className='inactive'>REVIEW REQUESTED</button>; };
return <button onClick={removeLock}>REQUEST LOCK REMOVAL</button>;
}; };
return <Dialog className='lockNotification' blocking closeText='CONTINUE TO EDITOR' > return <Dialog className='lockNotification' blocking closeText='CONTINUE TO EDITOR' >
@@ -19,12 +32,12 @@ function LockNotification(props) {
<p>This brew been locked by the Administrators. It will not be accessible by any method other than the Editor until the lock is removed.</p> <p>This brew been locked by the Administrators. It will not be accessible by any method other than the Editor until the lock is removed.</p>
<hr /> <hr />
<h3>LOCK REASON</h3> <h3>LOCK REASON</h3>
<p>{props.message || 'Unable to retrieve Lock Message'}</p> <p>{props.message}</p>
<hr /> <hr />
<p>Once you have resolved this issue, click REQUEST LOCK REMOVAL to notify the Administrators for review.</p> <p>Once you have resolved this issue, click REQUEST LOCK REMOVAL to notify the Administrators for review.</p>
<p>Click CONTINUE TO EDITOR to temporarily hide this notification; it will reappear the next time the page is reloaded.</p> <p>Click CONTINUE TO EDITOR to temporarily hide this notification; it will reappear the next time the page is reloaded.</p>
<button onClick={removeLock}>REQUEST LOCK REMOVAL</button> {renderReviewButton()}
</Dialog>; </Dialog>;
}; };
module.exports = LockNotification; export default LockNotification;
@@ -11,10 +11,12 @@
&::backdrop { background-color : #000000AA; } &::backdrop { background-color : #000000AA; }
button { button {
padding : 2px 15px;
margin : 10px; margin : 10px;
color : white; color : white;
background-color : #333333; background-color : #333333;
&.inactive,
&:hover { background-color : #777777; } &:hover { background-color : #777777; }
} }
@@ -1,8 +1,8 @@
require('./errorPage.less'); import './errorPage.less';
const React = require('react'); import React from 'react';
const UIPage = require('../basePages/uiPage/uiPage.jsx'); import UIPage from '../basePages/uiPage/uiPage.jsx';
const Markdown = require('../../../../shared/naturalcrit/markdown.js'); import Markdown from '../../../../shared/markdown.js';
const ErrorIndex = require('./errors/errorIndex.js'); import ErrorIndex from './errors/errorIndex.js';
const ErrorPage = ({ brew })=>{ const ErrorPage = ({ brew })=>{
// Retrieving the error text based on the brew's error code from ErrorIndex // Retrieving the error text based on the brew's error code from ErrorIndex
@@ -22,4 +22,4 @@ const ErrorPage = ({ brew })=>{
); );
}; };
module.exports = ErrorPage; export default ErrorPage;

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