Merge branch 'master' into v4Metadata

This commit is contained in:
David Bolack
2026-08-21 11:55:31 -05:00
26 changed files with 4051 additions and 4304 deletions
+1 -1
View File
@@ -308,7 +308,7 @@ const CodeEditor = forwardRef(
view.dispatch({
effects : themeCompartment.reconfigure(themeExtension),
});
}, [editorTheme]);
}, [editorTheme, tab]);
useEffect(()=>{
//rebuild syntax highlight when changing tab or renderer
@@ -1,33 +1,44 @@
/* eslint max-lines: ["error", { "max": 300 }] */
import { keymap } from '@codemirror/view';
import { undo, redo, indentMore, deleteLine } from '@codemirror/commands';
import { undo, redo, indentMore, indentLess, deleteLine } from '@codemirror/commands';
import { EditorSelection } from '@codemirror/state';
import { Prec } from '@codemirror/state';
const insertTab = (view)=>{
const { from, to } = view.state.selection.main;
// If any selection spans multiple lines, delegates to CodeMirror's indentMore
// Otherwise inserts two spaces at each cursor/selection
const shouldIndent = view.state.selection.ranges.some((range)=>view.state.doc.lineAt(range.from).number !==
view.state.doc.lineAt(range.to).number
);
if(shouldIndent) return indentMore(view);
const changes = [];
for (const range of view.state.selection.ranges) {
changes.push({
from : range.from,
to : range.to,
insert : ' ' // Insert two spaces, not a tab char!
});
}
// Create a transaction so we can map old positions to
// their new positions after the edits are applied
const mappedChanges = view.state.update({ changes });
view.dispatch({
changes : { from, to, insert: ' ' },
selection : { anchor: from + 2 }
changes,
selection : EditorSelection.create(
view.state.selection.ranges.map((range)=>EditorSelection.cursor(
mappedChanges.changes.mapPos(range.from, 1) + 2
)
)
)
});
return true;
};
const indentLess = (view)=>{
const { from, to } = view.state.selection.main;
const lines = [];
for (let l = view.state.doc.lineAt(from).number; l <= view.state.doc.lineAt(to).number; l++) {
const line = view.state.doc.line(l);
const match = line.text.match(/^ {1,2}/); // match up to 2 spaces
if(match) {
lines.push({ from: line.from, to: line.from + match[0].length, insert: '' });
}
}
if(lines.length > 0) view.dispatch({ changes: lines });
return true;
};
const wrapSelection = (prefix, suffix)=>(view)=>{
const changes = [];
@@ -169,16 +180,16 @@ const newPage = (view)=>{
};
export const generalKeymap = Prec.high(keymap.of([
{ key: 'Tab', run: insertTab },
{ key: 'Mod-z', run: undo }, //i think it may be unnecessary
{ key: 'Tab', run: insertTab }, //runs indentMore if multiple lines selected in a single selection
{ key: 'Shift-Tab', run: indentLess },
{ key: 'Mod-z', run: undo }, //it may be unnecessary
{ key: 'Mod-Shift-z', run: redo },
{ key: 'Mod-y', run: redo },
{ key: 'Mod-d', run: deleteLine },
{ key: 'Mod-y', run: redo }, //user asked, so double keybind
{ key: 'Mod-d', run: deleteLine }, //annoyingly overrides "selectNextOccurrence" because users asked
]));
export const markdownKeymap = Prec.highest(keymap.of([
//{ key: 'Shift-Tab', run: indentMore },
{ key: 'Shift-Tab', run: indentLess },
{ key: 'Mod-b', run: wrapSelection('**', '**') }, // makeBold
{ key: 'Mod-i', run: wrapSelection('*', '*') }, // makeItalic
{ key: 'Mod-u', run: wrapSelection('<u>', '</u>') }, // makeUnderline
+6 -4
View File
@@ -92,12 +92,13 @@ const Dropdown = ({ groupName, className = null, icon, children, color = null, c
};
return (
<div className={['menu-wrapper', className].join(' ')} role='none' >
<li className='menu-wrapper' role='none'>
<button
id={`${menuId}-trigger`}
className={['menu-item', color].join(' ')}
popoverTarget={menuId}
aria-haspopup='menu'
aria-label={groupName}
role='menuitem'
disabled={!React.Children.count(children)}
ref={triggerRef}
@@ -105,18 +106,19 @@ const Dropdown = ({ groupName, className = null, icon, children, color = null, c
{trigger(groupName, icon)}
</button>
<MenuDepthContext.Provider value={depth + 1}>
<div
<ul
ref={menuRef}
id={menuId}
className='menu-list'
popover='auto'
role='menu'
aria-label={`${groupName} Submenu`}
onClick={handleMenuActionClick}
>
{children}
</div>
</ul>
</MenuDepthContext.Provider>
</div>
</li>
);
};
+19 -10
View File
@@ -1,24 +1,33 @@
.menu-wrapper {
position: relative;
&:is(.menu-bar > .menu-section > .menu-wrapper){
display: inline-block;
}
@property --menuColor {
syntax: '<color>';
inherits: true;
initial-value: #DDD;
}
@property --activeTriggerColor {
syntax: '<color>';
inherits: true;
initial-value: #DDD;
}
:root{
--activeTriggerColor : var(--activeTriggerColor);
}
.menu-list {
contain : content;
position : fixed;
z-index : 1000;
top : anchor(bottom);
left : anchor(left);
position-try: flip-inline flip-block;
color: inherit; // [popover] gets a `canvastext` color value from useragent.
> .menu-wrapper {
position:relative;
> .menu-list {
background: var(--menuColor);
li > .menu-list {
margin: 0 0px;
top : anchor(top);
left : anchor(right);
position-try: flip-inline;
}
}
}
.menu-wrapper:has(:popover-open) > button { // if menu is open...
background-color: var(--activeTriggerColor, hsl(from var(--menuColor) h s calc(l * .85))); // tint menu triggers based on menu color
}
@@ -29,6 +29,7 @@ const TOOLBAR_STATE_KEY = 'HB_renderer_toolbarState';
const INITIAL_CONTENT = dedent`
<!DOCTYPE html><html><head>
<title>Rendered Brew Content</title>
<link href='/homebrew/bundle.css' type="text/css" rel='stylesheet' />
<link href="${brewRendererStylesUrl}" rel="stylesheet" />
<link href="${headerNavStylesUrl}" rel="stylesheet" />
@@ -210,7 +211,7 @@ const BrewRenderer = (props)=>{
classes = [classes, injectedTags.classes].join(' ').trim();
attributes = injectedTags.attributes;
if(global.enablev4) {
if (attributes && Object.hasOwn(attributes, 'hbtemplate')) {
if(attributes && Object.hasOwn(attributes, 'hbtemplate')) {
pageTemplates[index] = attributes['hbtemplate'];
}
}
@@ -220,7 +221,7 @@ const BrewRenderer = (props)=>{
if(!pageTemplates[index]) {
for (let i=index;i>=0; i--) {
// If one is found, add the template attribute
if (pageTemplates[i]) attributes['hbtemplate'] = pageTemplates[i];
if(pageTemplates[i]) attributes['hbtemplate'] = pageTemplates[i];
}
}
}
@@ -348,10 +349,11 @@ const BrewRenderer = (props)=>{
<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.*/}
<Frame id='BrewRenderer' initialContent={INITIAL_CONTENT}
<Frame id='BrewRenderer' title="Rendered Brew Content" initialContent={INITIAL_CONTENT}
style={{ width: '100%', height: '100%', visibility: state.visibility }}
contentDidMount={frameDidMount}
onClick={()=>{emitClick();}}
sandbox="allow-same-origin allow-modals allow-top-navigation"
>
<div className='brewRenderer'
onKeyDown={handleControlKeys}
+4 -4
View File
@@ -32,12 +32,12 @@ function safeHTML(htmlString) {
return;
}
// Check remaining elements for blacklisted attributes
for (const attribute of element.attributes){
[...element.attributes].forEach((attribute)=>{
if(blacklistAttrs.some((test)=>{return test(attribute);})) {
element.removeAttribute(attribute.localName);
break;
element.removeAttribute(attribute.name);
return;
};
};
});
});
return div.innerHTML;
@@ -99,11 +99,16 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
return (
<div id='preview-toolbar' className={`toolBar ${toolsVisible ? 'visible' : 'hidden'}`} role='toolbar'>
<div className='toggleButton'>
<button data-tooltip-right={`${toolsVisible ? 'Hide' : 'Show'} Preview Toolbar`} onClick={()=>{
setToolsVisible(!toolsVisible);
localStorage.setItem(TOOLBAR_VISIBILITY, !toolsVisible);
}}><i className='fas fa-glasses' /></button>
<button data-tooltip-right={`${headerState ? 'Hide' : 'Show'} Header Navigation`} onClick={()=>{setHeaderState(!headerState);}}><i className='fas fa-rectangle-list' /></button>
<button data-tooltip-right={`${toolsVisible ? 'Hide' : 'Show'} Preview Toolbar`}
aria-label={`${toolsVisible ? 'Hide' : 'Show'} Preview Toolbar`}
onClick={()=>{ setToolsVisible(!toolsVisible); localStorage.setItem(TOOLBAR_VISIBILITY, !toolsVisible); }}>
<i aria-hidden='true' className='fas fa-glasses' />
</button>
<button data-tooltip-right={`${headerState ? 'Hide' : 'Show'} Header Navigation`}
aria-label={`${headerState ? 'Hide' : 'Show'} Header Navigation`}
onClick={()=>{setHeaderState(!headerState);}}>
<i aria-hidden='true' className='fas fa-rectangle-list' />
</button>
</div>
{/*v=====----------------------< Zoom Controls >---------------------=====v*/}
<div className='group' role='group' aria-label='Zoom' aria-hidden={!toolsVisible}>
@@ -111,17 +116,19 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
id='fill-width'
className='tool'
data-tooltip-bottom='Set zoom to fill preview with one page'
aria-label='Set zoom to fill preview with one page'
onClick={()=>handleZoomButton(displayOptions.zoomLevel + calculateChange('fill'))}
>
<i className='fac fit-width' />
<i aria-hidden='true' className='fac fit-width' />
</button>
<button
id='zoom-to-fit'
className='tool'
data-tooltip-bottom='Set zoom to fit entire page in preview'
aria-label='Set zoom to fit entire page in preview'
onClick={()=>handleZoomButton(displayOptions.zoomLevel + calculateChange('fit'))}
>
<i className='fac zoom-to-fit' />
<i aria-hidden='true' className='fac zoom-to-fit' />
</button>
<button
id='zoom-out'
@@ -129,8 +136,9 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
onClick={()=>handleZoomButton(displayOptions.zoomLevel - 20)}
disabled={displayOptions.zoomLevel <= MIN_ZOOM}
data-tooltip-bottom='Zoom Out'
aria-label='Zoom Out'
>
<i className='fas fa-magnifying-glass-minus' />
<i aria-hidden='true' className='fas fa-magnifying-glass-minus' />
</button>
<input
id='zoom-slider'
@@ -138,6 +146,7 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
type='range'
name='zoom'
list='zoomLevels'
aria-label='Zoom Amount'
min={MIN_ZOOM}
max={MAX_ZOOM}
step='1'
@@ -154,8 +163,9 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
onClick={()=>handleZoomButton(displayOptions.zoomLevel + 20)}
disabled={displayOptions.zoomLevel >= MAX_ZOOM}
data-tooltip-bottom='Zoom In'
aria-label='Zoom In'
>
<i className='fas fa-magnifying-glass-plus' />
<i aria-hidden='true' className='fas fa-magnifying-glass-plus' />
</button>
</div>
@@ -166,27 +176,32 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
id='single-spread'
className='tool'
data-tooltip-bottom='Single Page'
aria-label='Single Page Spread'
onClick={()=>{handleOptionChange('spread', 'single');}}
aria-checked={displayOptions.spread === 'single'}
><i className='fac single-spread' /></button>
><i aria-hidden='true' className='fac single-spread' /></button>
<button role='radio'
id='facing-spread'
className='tool'
data-tooltip-bottom='Facing Pages'
aria-label='Facing Pages Spread'
onClick={()=>{handleOptionChange('spread', 'facing');}}
aria-checked={displayOptions.spread === 'facing'}
><i className='fac facing-spread' /></button>
><i aria-hidden='true' className='fac facing-spread' /></button>
<button role='radio'
id='flow-spread'
className='tool'
data-tooltip-bottom='Flow Pages'
aria-label='Flow Pages Spread'
onClick={()=>{handleOptionChange('spread', 'flow');}}
aria-checked={displayOptions.spread === 'flow'}
><i className='fac flow-spread' /></button>
><i aria-hidden='true' className='fac flow-spread' /></button>
</div>
<Anchored>
<AnchoredTrigger id='spread-settings' className='tool' data-tooltip-bottom='Spread options'><i className='fas fa-gear' /></AnchoredTrigger>
<AnchoredTrigger id='spread-settings' className='tool' aria-label='Spread options' data-tooltip-bottom='Spread options'>
<i aria-hidden='true' className='fas fa-gear' />
</AnchoredTrigger>
<AnchoredBox>
<h1>Options</h1>
<label data-tooltip-left='Modify the horizontal space between pages.'>
@@ -217,10 +232,11 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
className='previousPage tool'
type='button'
data-tooltip-bottom='Previous Page(s)'
aria-label='Previous Page'
onClick={()=>scrollToPage(_.min(visiblePages) - visiblePages.length)}
disabled={visiblePages.includes(1)}
>
<i className='fas fa-arrow-left'></i>
<i aria-hidden='true' className='fas fa-arrow-left'></i>
</button>
<div className='tool'>
@@ -230,6 +246,7 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
type='text'
name='page'
data-tooltip-bottom='Current page(s) in view'
aria-label='Current page in view'
inputMode='numeric'
pattern='[0-9]'
value={pageNum}
@@ -239,7 +256,7 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
onKeyDown={(e)=>e.key == 'Enter' && scrollToPage(pageNum)}
style={{ width: `${pageNum.length}ch` }}
/>
<span id='page-count' data-tooltip-bottom='Total Page Count'>/ {totalPages}</span>
<span id='page-count' aria-label={`${totalPages} Total Pages`} data-tooltip-bottom='Total Page Count'><span aria-hidden='true'>/ {totalPages}</span></span>
</div>
<button
@@ -247,10 +264,11 @@ const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPa
className='tool'
type='button'
data-tooltip-bottom='Next Page(s)'
aria-label='Next Page'
onClick={()=>scrollToPage(_.max(visiblePages) + 1)}
disabled={visiblePages.includes(totalPages)}
>
<i className='fas fa-arrow-right'></i>
<i aria-hidden='true' className='fas fa-arrow-right'></i>
</button>
</div>
</div>
@@ -44,6 +44,7 @@ const MetadataEditor = createReactClass({
getInitialState : function(){
return {
isOwner : global.account?.username && global.account?.username === this.props.metadata?.authors[0],
showThumbnail : true
};
},
@@ -144,6 +145,15 @@ const MetadataEditor = createReactClass({
});
},
handleDeleteAuthor : function(author){
if(!confirm('Are you sure you want to remove this author? They will lose all edit access to this brew, and it will dissapear from their userpage.')) return;
if(!this.props.metadata.authors.includes(author)) return;
this.props.onChange({
...this.props.metadata,
authors : this.props.metadata.authors.filter((a)=>a !== author)
});
},
renderPublish : function(){
if(this.props.metadata.published){
return <button className='unpublish' onClick={()=>this.handlePublish(false)}>
@@ -170,16 +180,54 @@ const MetadataEditor = createReactClass({
},
renderAuthors : function(){
let text = 'None.';
if(this.props.metadata.authors && this.props.metadata.authors.length){
text = this.props.metadata.authors.join(', ');
}
return <div className='field authors'>
<label>authors</label>
<div className='value'>
{text}
const authors = this.props.metadata.authors;
if(!this.state.isOwner || authors.length < 2) return (
<div className='field authors'>
<label>authors</label>
<div className='value'>
{authors.length > 0 && (
<a href={`/user/${authors[0]}`} className='author-link' target="_blank" title={`Owner - Click to open ${authors[0]}'s profile in a new tab`}>
{authors[0]}{authors.length > 1 && ', '}
</a>
)}
{authors.length > 1 && authors.slice(1).map((author, i)=>(
<a href={`/user/${author}`} className='author-link' title={`Author - Click to open ${author}'s profile in a new tab`}>
{author}{i+2 < authors.length && ', '}
</a>
))}
</div>
</div>
</div>;
);
return (
<div className='field authors'>
<label>Authors</label>
<ul className='list'>
{authors.length > 0 && (
<li className='tag owner' title='Owner'>
<a href={`/user/${authors[0]}`} className='author-link' title={`Owner - Click to open ${authors[0]}'s profile in a new tab`}>
{authors[0]}
</a>
</li>
)}
{authors.length > 1 && authors.slice(1).map((author, i)=>(
<li className='tag author' key={i + 1} title='Author'>
<a href={`/user/${author}`} className='author-link' title={`Author - Click to open ${authors[0]}'s profile in a new tab`}>
{author}
</a>
<button
onClick={()=>this.handleDeleteAuthor(author)}
className='delete'
title={`Remove ${author} as an author`}
>
<i className='fa fa-times fa-fw' />
</button>
</li>
))}
</ul>
</div>
);
},
renderThemeDropdown : function(){
@@ -173,7 +173,51 @@
.colorButton(@red);
}
}
.authors.field .value { line-height : 1.5em; }
.authors.field {
.tag {
font-weight:300;
transition:background-color 0.2s;
&.owner {
position: relative;
background-color:@silverLight;
min-width:25px;
display:grid;
place-items:center;
font-weight: 900;
&::after {
content: "\f521";
font-family: "Font Awesome 6 Free";
color:gold;
position: absolute;
top: 0;
left: 0;
width:15px;
height:15px;
rotate:-25deg;
translate:-30% -50%;
transform: scaleY(0.7);
}
}
&:has(button) a {
padding-right:5px;
}
&:has(button:hover) {
background:#d97d7d;
}
button {
color:@red;
}
}
a {
color:black;
text-decoration:unset;
}
}
.themes.field {
& .dropdown-container {
@@ -275,13 +319,17 @@
}
.tag {
padding : 0.3em;
padding : 0.35em;
margin : 2px;
font-size : 0.9em;
font-size : 0.95em;
background-color : #DDDDDD;
border-radius : 0.5em;
.icon { #groupedIcon; }
button {
cursor : pointer;
}
}
.input-group {
@@ -188,7 +188,7 @@ const Snippetbar = createReactClass({
const snippets = this.state.snippets.filter((snippetGroup)=>snippetGroup.view === this.props.view);
if(snippets.length === 0) return null;
return <div className='snippets'>
return <ul className='snippets' role='menubar' aria-label='Snippets Menubar'>
{_.map(snippets, (snippetGroup)=>{
return <SnippetGroup
brew={this.props.brew}
@@ -201,7 +201,7 @@ const Snippetbar = createReactClass({
/>;
})
}
</div>;
</ul>;
},
replaceContent : function(item){
@@ -327,12 +327,14 @@ const SnippetGroup = createReactClass({
return _.map(snippets, (snippet)=>{
if(!snippet.subsnippets){
return (
<button className='menu-item' key={snippet.name} onClick={(e)=>this.handleSnippetClick(e, snippet)} role='menuitem'>
<i className={snippet.icon} />
<span className={`name${snippet.disabled ? ' disabled' : ''}`} title={snippet.name}>{snippet.name}</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>}
</button>
<li key={snippet.name} role='none'>
<button className='menu-item' onClick={(e)=>this.handleSnippetClick(e, snippet)} role='menuitem' aria-label={snippet.name} disabled={snippet.disabled}>
<i className={snippet.icon} />
<span className={`name${snippet.disabled ? ' disabled' : ''}`} title={snippet.name}>{snippet.name}</span>
{snippet.experimental && <span className='status'>beta</span>}
{snippet.disabled && <span className='status' title='temporarily disabled due to large slowdown; under re-design'>disabled</span>}
</button>
</li>
);
} else if(snippet.subsnippets){
return (
@@ -3,6 +3,8 @@
@import (less) '@themes/fonts/5e/fonts.less';
.snippetBar {
--activeTriggerColor: inherit;
--menuColor : #DDDDDD;
@menuHeight : 25px;
position : relative;
display : flex;
@@ -16,12 +18,6 @@
text-transform: uppercase;
font-weight: 800;
.snippets {
display : flex;
justify-content : flex-start;
min-width : 499.35px; //must be controlled every time an item is added, must be hardcoded for the wrapping as it is applied
}
.editors {
display : flex;
justify-content : flex-end;
@@ -118,23 +114,7 @@
}
}
}
.snippetBarButton {
display : inline-block;
height : @menuHeight;
padding : 0px 5px;
font-size : 0.625em;
font-weight : 800;
line-height : @menuHeight;
text-transform : uppercase;
text-wrap : nowrap;
cursor : pointer;
&:hover, &.selected { background-color : #999999; }
i {
margin-right : 3px;
font-size : 1.4em;
vertical-align : middle;
}
}
.toggleMeta {
position : absolute;
top : 0px;
@@ -143,20 +123,15 @@
.tooltipLeft('Edit Brew Properties');
}
.menu-wrapper {
.menu-item:is(.snippets > .menu-wrapper > .menu-item):first-child {
.caret {
display: none;
}
}
.menu-list {
padding : 0px;
background-color : #DDDDDD;
}
.snippets {
display : flex;
justify-content : flex-start;
min-width : 565.95px; //must be controlled every time an item is added, must be hardcoded for the wrapping as it is applied
}
// removed caret for top level items, by request (makes buttons too wide).
.menu-wrapper .menu-item:is(.snippets > .menu-wrapper > .menu-item):first-child .caret { display: none; }
.menu-item {
position : relative;
display : flex;
@@ -166,9 +141,8 @@
padding : 5px;
cursor : pointer;
width: 100%;
.animate(background-color);
&:is(.menu-list .menu-item) [class*="name"] {
padding-inline: 8px;
padding-inline: 8px; // additional space between icon and name (helpful in Fonts menu especially).
}
.menu-name {
flex: 1;
@@ -214,8 +188,7 @@
}
}
.name { margin-right : auto; }
.disabled { text-decoration : line-through; }
.beta {
.status {
align-self : center;
padding : 4px 6px;
margin-left : 5px;
@@ -234,15 +207,8 @@
&:hover { background-color: unset; }
}
}
.disabledSnippets {
color: grey;
cursor: not-allowed;
&:hover { background-color: #DDDDDD;}
}
}
@container editor (width < 750px) {
@container editor (width < 816px) {
.snippetBar {
.editors {
flex : 1;
+25 -54
View File
@@ -1,21 +1,16 @@
import './navbar.less';
import React, { useState, useRef, useEffect } from 'react';
import createReactClass from 'create-react-class';
import _ from 'lodash';
import cx from 'classnames';
import NaturalCritIcon from '@components/svg/naturalcrit-d20.svg.jsx';
const Nav = {
base : createReactClass({
displayName : 'Nav.base',
render : function(){
return <nav>
{this.props.children}
</nav>;
}
}),
logo : function(){
base : ({ children, className, ...props })=>{
return <nav className={className}>
{children}
</nav>;
},
logo : ()=>{
return <a className='navLogo' href='https://www.naturalcrit.com'>
<NaturalCritIcon />
<span className='name'>
@@ -24,50 +19,26 @@ const Nav = {
</a>;
},
section : createReactClass({
displayName : 'Nav.section',
render : function(){
return <div className={`navSection ${this.props.className ?? ''}`}>
{this.props.children}
</div>;
section : ({ children, className, ...props })=>{
return <div className={cx([`navSection`, className])}>
{children}
</div>;
},
item : ({ icon, href, newTab, onClick, color, children, className, ...props })=>{
const classes = cx('navItem', color, className);
if(href){
return <a className={classes} href={href} target={newTab ? '_blank' : '_self'} {...props}>
{children}
{icon && <i className={icon}></i>}
</a>;
} else {
return <button {...props} className={classes} onClick={onClick} >
{children}
{icon && <i className={icon}></i>}
</button>;
}
}),
item : createReactClass({
displayName : 'Nav.item',
getDefaultProps : function() {
return {
icon : null,
href : null,
newTab : false,
onClick : function(){},
color : null
};
},
handleClick : function(e){
this.props.onClick(e);
},
render : function(){
const classes = cx('navItem', this.props.color, this.props.className);
let icon;
if(this.props.icon) icon = <i className={this.props.icon} />;
const props = _.omit(this.props, ['newTab']);
if(this.props.href){
return <a {...props} className={classes} target={this.props.newTab ? '_blank' : '_self'} >
{this.props.children}
{icon}
</a>;
} else {
return <div {...props} className={classes} onClick={this.handleClick} >
{this.props.children}
{icon}
</div>;
}
}
}),
},
dropdown : function dropdown(props) {
props = Object.assign({}, props, {
@@ -39,9 +39,9 @@ const BrewItem = ({
if(!brew.editId) return null;
return (
<a className='deleteLink' onClick={deleteBrew}>
<i className='fas fa-trash-alt' title='Delete' />
</a>
<button aria-label={`Delete ${brew.title}`} className='deleteLink' onClick={deleteBrew}>
<i className='fas fa-trash-alt' aria-hidden='true' title='Delete' />
</button>
);
};
@@ -52,7 +52,7 @@ const BrewItem = ({
if(brew.googleId && !brew.stubbed) editLink = brew.googleId + editLink;
return (
<a className='editLink' href={`/edit/${editLink}`} target='_blank' rel='noopener noreferrer'>
<a className='editLink' href={`/edit/${editLink}`} aria-label={`Edit ${brew.title}`} target='_blank' rel='noopener noreferrer'>
<i className='fas fa-pencil-alt' title='Edit' />
</a>
);
@@ -67,7 +67,7 @@ const BrewItem = ({
}
return (
<a className='shareLink' href={`/share/${shareLink}`} target='_blank' rel='noopener noreferrer'>
<a className='shareLink' href={`/share/${shareLink}`} aria-label={`Share ${brew.title}`} target='_blank' rel='noopener noreferrer'>
<i className='fas fa-share-alt' title='Share' />
</a>
);
@@ -82,7 +82,7 @@ const BrewItem = ({
}
return (
<a className='downloadLink' href={`/download/${shareLink}`}>
<a className='downloadLink' aria-label={`Download ${brew.title}`} href={`/download/${shareLink}`}>
<i className='fas fa-download' title='Download' />
</a>
);
@@ -94,7 +94,7 @@ const BrewItem = ({
return (
<span title={brew.webViewLink ? 'Your Google Drive Storage' : 'Another User\'s Google Drive Storage'}>
<a href={brew.webViewLink} target='_blank'>
<img className='googleDriveIcon' src={googleDriveIcon} alt='googleDriveIcon' />
<img className='googleDriveIcon' src={googleDriveIcon} alt='Google Drive Storage' />
</a>
</span>
);
@@ -102,7 +102,7 @@ const BrewItem = ({
return (
<span title='Homebrewery Storage'>
<img className='homebreweryIcon' src={homebreweryIcon} alt='homebreweryIcon' />
<img className='homebreweryIcon' src={homebreweryIcon} alt='Homebrewery Storage' />
</span>
);
};
@@ -148,19 +148,20 @@ const BrewItem = ({
))}
</span>
<br />
<span title={`Last viewed: ${moment(brew.lastViewed).local().format(dateFormatString)}`}>
<i className='fas fa-eye' /> {brew.views}
<span aria-label={`Viewed ${brew.views} times`} title={`Last viewed: ${moment(brew.lastViewed).local().format(dateFormatString)}`}>
<span aria-hidden='true'><i className='fas fa-eye' /> {brew.views}</span>
</span>
{brew.pageCount && (
<span title={`Page count: ${brew.pageCount}`}>
<i className='far fa-file' /> {brew.pageCount}
<span aria-label={`${brew.pageCount} pages`} title={`Page count: ${brew.pageCount}`}>
<span aria-hidden='true'><i className='far fa-file' /> {brew.pageCount}</span>
</span>
)}
<span
aria-label={`Last updated ${moment(brew.updatedAt).fromNow()}`}
title={dedent` Created: ${moment(brew.createdAt).local().format(dateFormatString)}
Last updated: ${moment(brew.updatedAt).local().format(dateFormatString)}`}
>
<i className='fas fa-sync-alt' /> {moment(brew.updatedAt).fromNow()}
<span aria-hidden='true'><i className='fas fa-sync-alt' /> {moment(brew.updatedAt).fromNow()}</span>
</span>
{renderStorageIcon()}
</div>
@@ -89,7 +89,7 @@
&::before { content : '\f518'; }
}
}
&:hover {
&:hover, &:focus-within {
.links { opacity : 1; }
}
&:nth-child(2n + 1) { margin-right : 0px; }
@@ -103,7 +103,7 @@
text-align : center;
background-color : fade(black, 60%);
opacity : 0;
a {
a, button {
.animate(opacity);
display : block;
margin : 8px 0px;
@@ -111,6 +111,7 @@
color : white;
text-decoration : unset;
opacity : 0.6;
width : 100%;
&:hover { opacity : 1; }
i { cursor : pointer; }
}
+1 -1
View File
@@ -320,7 +320,7 @@ const EditPage = (props)=>{
// #5 - No unsaved changes, and has never been saved, hide the button
if(neverSaved)
return <Nav.item className='save neverSaved'>save now</Nav.item>;
return <Nav.item className='save neverSaved' disabled={true}>save now</Nav.item>;
// DEFAULT - No unsaved changes, show SAVED
return <Nav.item className='save saved'>saved</Nav.item>;
+1 -1
View File
@@ -164,7 +164,7 @@ const HomePage =(props)=>{
// #5 - No unsaved changes, and has never been saved, hide the button
if(neverSaved)
return <Nav.item className='save neverSaved'>save now</Nav.item>;
return <Nav.item className='save neverSaved' disabled={true}>save now</Nav.item>;
// DEFAULT - No unsaved changes, show SAVED
return <Nav.item className='save saved'>saved</Nav.item>;
+1 -1
View File
@@ -207,7 +207,7 @@ const NewPage = (props)=>{
// #5 - No unsaved changes, and has never been saved, hide the button
if(neverSaved)
return <Nav.item className='save neverSaved'>save now</Nav.item>;
return <Nav.item className='save neverSaved' disabled={true}>save now</Nav.item>;
// DEFAULT - No unsaved changes, show SAVED
return <Nav.item className='save saved'>saved</Nav.item>;
+3584 -3918
View File
File diff suppressed because it is too large Load Diff
+22 -21
View File
@@ -86,33 +86,33 @@
]
},
"dependencies": {
"@babel/core": "^7.29.7",
"@babel/plugin-transform-runtime": "^7.29.7",
"@babel/preset-env": "^7.29.5",
"@babel/preset-react": "^7.29.7",
"@babel/runtime": "^7.29.2",
"@babel/core": "^8.0.1",
"@babel/plugin-transform-runtime": "^8.0.1",
"@babel/preset-env": "^8.0.2",
"@babel/preset-react": "^8.0.1",
"@babel/runtime": "^8.0.0",
"@codemirror/autocomplete": "^6.20.3",
"@codemirror/commands": "^6.10.3",
"@codemirror/highlight": "^0.19.8",
"@codemirror/lang-css": "^6.3.1",
"@codemirror/lang-javascript": "^6.2.5",
"@codemirror/lang-markdown": "^6.5.0",
"@codemirror/lang-markdown": "^6.5.2",
"@codemirror/language": "^6.12.2",
"@codemirror/language-data": "^6.5.2",
"@codemirror/search": "^6.6.0",
"@codemirror/state": "^6.6.0",
"@codemirror/view": "^6.43.1",
"@codemirror/view": "^6.43.8",
"@dmsnell/diff-match-patch": "^1.1.0",
"@googleapis/drive": "^20.2.0",
"@lezer/highlight": "^1.2.3",
"@oddbird/css-anchor-positioning": "^0.9.0",
"@oddbird/css-anchor-positioning": "^0.10.1",
"@sanity/diff-match-patch": "^3.2.0",
"@vitejs/plugin-react": "^5.1.2",
"body-parser": "^2.2.0",
"@vitejs/plugin-react": "^6.0.5",
"body-parser": "^2.3.0",
"classnames": "^2.5.1",
"codemirror-5-themes": "^1.5.1",
"cookie-parser": "^1.4.7",
"core-js": "^3.49.0",
"core-js": "^3.50.0",
"cors": "^2.8.5",
"create-react-class": "^15.7.0",
"dedent": "^1.7.2",
@@ -123,13 +123,14 @@
"fs-extra": "^11.3.5",
"hash-wasm": "^4.12.0",
"idb-keyval": "^6.2.5",
"js-yaml": "^4.2.0",
"js-yaml": "^5.3.0",
"jwt-simple": "^0.5.6",
"less": "^4.6.4",
"less": "^4.8.1",
"lodash": "^4.18.1",
"marked": "15.0.12",
"marked-alignment-paragraphs": "^1.0.0",
"marked-definition-lists": "^1.0.1",
"marked-diagrams-markdeep": "^1.0.1",
"marked-emoji": "^2.0.3",
"marked-extended-tables": "^2.0.1",
"marked-gfm-heading-id": "^4.1.4",
@@ -139,34 +140,34 @@
"marked-variables": "^1.0.5",
"markedLegacy": "npm:marked@^0.3.19",
"moment": "^2.30.1",
"mongoose": "^9.7.0",
"nanoid": "5.1.11",
"mongoose": "^9.9.2",
"nanoid": "6.0.1",
"nconf": "^0.13.0",
"node": "^25.9.0",
"node": "^26.7.0",
"react": "^19.2.7",
"react-dom": "^19.2.7",
"react-frame-component": "^5.3.2",
"react-router": "^7.17.0",
"react-router": "^8.3.0",
"sanitize-filename": "1.6.4",
"superagent": "^10.2.1"
},
"devDependencies": {
"@stylistic/stylelint-plugin": "^5.0.1",
"@stylistic/stylelint-plugin": "^5.3.0",
"babel-jest": "^30.4.1",
"babel-plugin-transform-import-meta": "^2.3.3",
"babel-plugin-transform-import-meta": "^3.0.0",
"eslint": "9.7",
"eslint-plugin-jest": "^29.15.1",
"eslint-plugin-react": "^7.37.5",
"globals": "^16.4.0",
"jest": "^30.4.2",
"jest-expect-message": "^1.1.3",
"jsdom": "^28.1.0",
"jsdom": "^30.0.1",
"jsdom-global": "^3.0.2",
"postcss-less": "^6.0.0",
"stylelint": "^17.11.1",
"stylelint-config-recess-order": "^7.7.0",
"stylelint-config-recommended": "^18.0.0",
"supertest": "^7.1.4",
"vite": "^7.3.1"
"vite": "^8.2.1"
}
}
+1 -1
View File
@@ -3,7 +3,7 @@ import createApp from './server/app.js';
import config from './server/config.js';
import { createServer as createViteServer } from 'vite';
const isDev = process.env.NODE_ENV === 'local';
const isDev = config.get('local_environments').includes(process.env.NODE_ENV);
async function start() {
let vite;
+1 -4
View File
@@ -5,7 +5,7 @@ import express from 'express';
import zlib from 'zlib';
import GoogleActions from './googleActions.js';
import Markdown from '../shared/markdown.js';
import yaml from 'js-yaml';
import * as yaml from 'js-yaml';
import asyncHandler from 'express-async-handler';
import { nanoid } from 'nanoid';
import { makePatches, applyPatches, stringifyPatches, parsePatch } from '@sanity/diff-match-patch';
@@ -195,7 +195,6 @@ const api = {
next();
};
},
getCSS : async (req, res)=>{
const { brew } = req;
if(!brew) return res.status(404).send('');
@@ -208,7 +207,6 @@ const api = {
});
return res.status(200).send(brew.style);
},
mergeBrewText : (brew)=>{
let text = brew.text;
if(brew.style !== undefined) {
@@ -234,7 +232,6 @@ const api = {
`${text}`;
return text;
},
getGoodBrewTitle : (text)=>{
const tokens = Markdown.marked.lexer(text);
return (tokens.find((token)=>token.type === 'heading' || token.type === 'paragraph')?.text || 'No Title')
+150 -157
View File
@@ -203,7 +203,6 @@ describe('Tests for api', ()=>{
expect(id).toEqual('abcdefghij');
});
});
describe('getBrew', ()=>{
const toBrewPromise = (brew)=>new Promise((res)=>res({ toObject: ()=>brew }));
const notFoundError = { HBErrorCode: '05', message: 'Brew not found', name: 'BrewLoad Error', status: 404, accessType: 'share', brewId: '1' };
@@ -400,7 +399,68 @@ describe('Tests for api', ()=>{
await expect(fn(req, null, next)).rejects.toEqual({ 'HBErrorCode': '51', 'brewId': '1', 'brewTitle': 'test brew', 'code': 404, 'message': 'brew locked' });
});
});
describe('Get CSS', ()=>{
it('should return brew style content as CSS text', async ()=>{
const testBrew = { title: 'test brew', text: '```css\n\nI Have a style!\n```\n\n' };
const toBrewPromise = (brew)=>new Promise((res)=>res({ toObject: ()=>brew }));
api.getId = jest.fn(()=>({ id: '1', googleId: undefined }));
model.get = jest.fn(()=>toBrewPromise(testBrew));
const fn = api.getBrew('share', true);
const req = { brew: {} };
const next = jest.fn();
await fn(req, null, next);
await api.getCSS(req, res);
expect(req.brew).toEqual(testBrew);
expect(req.brew).toHaveProperty('style', '\nI Have a style!\n');
expect(res.status).toHaveBeenCalledWith(200);
expect(res.send).toHaveBeenCalledWith('\nI Have a style!\n');
expect(res.set).toHaveBeenCalledWith({
'Cache-Control' : 'no-cache',
'Content-Type' : 'text/css'
});
});
it('should return 404 when brew has no style content', async ()=>{
const testBrew = { title: 'test brew', text: 'I don\'t have a style!' };
const toBrewPromise = (brew)=>new Promise((res)=>res({ toObject: ()=>brew }));
api.getId = jest.fn(()=>({ id: '1', googleId: undefined }));
model.get = jest.fn(()=>toBrewPromise(testBrew));
const fn = api.getBrew('share', true);
const req = { brew: {} };
const next = jest.fn();
await fn(req, null, next);
await api.getCSS(req, res);
expect(req.brew).toEqual(testBrew);
expect(req.brew).toHaveProperty('style');
expect(res.status).toHaveBeenCalledWith(404);
expect(res.send).toHaveBeenCalledWith('');
});
it('should return 404 when brew does not exist', async ()=>{
const testBrew = { };
const toBrewPromise = (brew)=>new Promise((res)=>res({ toObject: ()=>brew }));
api.getId = jest.fn(()=>({ id: '1', googleId: undefined }));
model.get = jest.fn(()=>toBrewPromise(testBrew));
const fn = api.getBrew('share', true);
const req = { brew: {} };
const next = jest.fn();
await fn(req, null, next);
await api.getCSS(req, res);
expect(req.brew).toEqual(testBrew);
expect(req.brew).toHaveProperty('style');
expect(res.status).toHaveBeenCalledWith(404);
expect(res.send).toHaveBeenCalledWith('');
});
});
describe('mergeBrewText', ()=>{
it('should set metadata and no style if it is not present', ()=>{
const result = api.mergeBrewText({
@@ -531,7 +591,6 @@ hello yes i am css
brew`);
});
});
describe('exclusion methods', ()=>{
it('excludePropsFromUpdate removes the correct keys', ()=>{
const sent = Object.assign({}, googleBrew);
@@ -568,7 +627,6 @@ brew`);
expect(result.pageCount).toBe(1);
});
});
describe('beforeNewSave', ()=>{
it('sets the title if none', ()=>{
const brew = {
@@ -610,7 +668,6 @@ brew`);
expect(hbBrew.text).toEqual('merged');
});
});
describe('newGoogleBrew', ()=>{
it('should call the correct methods', ()=>{
api.excludeGoogleProps = jest.fn(()=>'newBrew');
@@ -624,7 +681,6 @@ brew`);
expect(google.newGoogleBrew).toHaveBeenCalledWith('client', 'newBrew');
});
});
describe('newBrew', ()=>{
it('should set up a default brew via Homebrew model', async ()=>{
await api.newBrew({ body: { text: 'asdf' }, query: {}, account: { username: 'test user' } }, res);
@@ -754,17 +810,6 @@ brew`);
});
});
});
describe('deleteGoogleBrew', ()=>{
it('should check auth and delete brew', async ()=>{
const result = await api.deleteGoogleBrew({ username: 'test user' }, 'id', 'editId', res);
expect(result).toBe(true);
expect(google.authCheck).toHaveBeenCalledWith({ username: 'test user' }, expect.objectContaining({}));
expect(google.deleteGoogleBrew).toHaveBeenCalledWith('client', 'id', 'editId');
});
});
describe('Theme bundle', ()=>{
it('should return Theme Bundle for a User Theme', async ()=>{
const brews = {
@@ -908,7 +953,94 @@ brew`);
status : 422 });
});
});
describe('updateBrew', ()=>{
it('should return error on version mismatch', async ()=>{
const brewFromClient = { version: 1 };
const brewFromServer = { version: 1000, text: '' };
const req = {
brew : brewFromServer,
body : brewFromClient
};
await api.updateBrew(req, res);
expect(res.status).toHaveBeenCalledWith(409);
expect(res.send).toHaveBeenCalledWith('{\"message\":\"The server version is out of sync with the saved brew. Please save your changes elsewhere, refresh, and try again.\"}');
});
it('should return error on hash mismatch', async ()=>{
const brewFromClient = { version: 1, hash: '1234' };
const brewFromServer = { version: 1, text: 'test' };
const req = {
brew : brewFromServer,
body : brewFromClient
};
await api.updateBrew(req, res);
expect(req.brew.hash).toBe('098f6bcd4621d373cade4e832627b4f6');
expect(res.status).toHaveBeenCalledWith(409);
expect(res.send).toHaveBeenCalledWith('{\"message\":\"The server copy is out of sync with the saved brew. Please save your changes elsewhere, refresh, and try again.\"}');
});
// Commenting this one out for now, since we are no longer throwing this error while we monitor
// it('should return error on applying patches', async ()=>{
// const brewFromClient = { version: 1, hash: '098f6bcd4621d373cade4e832627b4f6', patches: 'not a valid patch string' };
// const brewFromServer = { version: 1, text: 'test', title: 'Test Title', description: 'Test Description' };
// const req = {
// brew : brewFromServer,
// body : brewFromClient,
// };
// let err;
// try {
// await api.updateBrew(req, res);
// } catch (e) {
// err = e;
// }
// expect(err).toEqual(Error('Invalid patch string: not a valid patch string'));
// });
it('should save brew, no ID', async ()=>{
const brewFromClient = { version: 1, hash: '098f6bcd4621d373cade4e832627b4f6', patches: '' };
const brewFromServer = { version: 1, text: 'test', title: 'Test Title', description: 'Test Description' };
model.save = jest.fn((brew)=>{return brew;});
const req = {
brew : brewFromServer,
body : brewFromClient,
query : { saveToGoogle: false, removeFromGoogle: false }
};
await api.updateBrew(req, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.send).toHaveBeenCalledWith(
expect.objectContaining({
_id : '1',
description : 'Test Description',
hash : '098f6bcd4621d373cade4e832627b4f6',
title : 'Test Title',
version : 2
})
);
});
});
describe('deleteGoogleBrew', ()=>{
it('should check auth and delete brew', async ()=>{
const result = await api.deleteGoogleBrew({ username: 'test user' }, 'id', 'editId', res);
expect(result).toBe(true);
expect(google.authCheck).toHaveBeenCalledWith({ username: 'test user' }, expect.objectContaining({}));
expect(google.deleteGoogleBrew).toHaveBeenCalledWith('client', 'id', 'editId');
});
});
describe('deleteBrew', ()=>{
it('should handle case where fetching the brew returns an error', async ()=>{
api.getBrew = jest.fn(()=>async ()=>{ throw { message: 'err', HBErrorCode: '02' }; });
@@ -1129,68 +1261,7 @@ brew`);
expect(saved.googleId).toEqual(brew.googleId);
});
});
describe('Get CSS', ()=>{
it('should return brew style content as CSS text', async ()=>{
const testBrew = { title: 'test brew', text: '```css\n\nI Have a style!\n```\n\n' };
const toBrewPromise = (brew)=>new Promise((res)=>res({ toObject: ()=>brew }));
api.getId = jest.fn(()=>({ id: '1', googleId: undefined }));
model.get = jest.fn(()=>toBrewPromise(testBrew));
const fn = api.getBrew('share', true);
const req = { brew: {} };
const next = jest.fn();
await fn(req, null, next);
await api.getCSS(req, res);
expect(req.brew).toEqual(testBrew);
expect(req.brew).toHaveProperty('style', '\nI Have a style!\n');
expect(res.status).toHaveBeenCalledWith(200);
expect(res.send).toHaveBeenCalledWith('\nI Have a style!\n');
expect(res.set).toHaveBeenCalledWith({
'Cache-Control' : 'no-cache',
'Content-Type' : 'text/css'
});
});
it('should return 404 when brew has no style content', async ()=>{
const testBrew = { title: 'test brew', text: 'I don\'t have a style!' };
const toBrewPromise = (brew)=>new Promise((res)=>res({ toObject: ()=>brew }));
api.getId = jest.fn(()=>({ id: '1', googleId: undefined }));
model.get = jest.fn(()=>toBrewPromise(testBrew));
const fn = api.getBrew('share', true);
const req = { brew: {} };
const next = jest.fn();
await fn(req, null, next);
await api.getCSS(req, res);
expect(req.brew).toEqual(testBrew);
expect(req.brew).toHaveProperty('style');
expect(res.status).toHaveBeenCalledWith(404);
expect(res.send).toHaveBeenCalledWith('');
});
it('should return 404 when brew does not exist', async ()=>{
const testBrew = { };
const toBrewPromise = (brew)=>new Promise((res)=>res({ toObject: ()=>brew }));
api.getId = jest.fn(()=>({ id: '1', googleId: undefined }));
model.get = jest.fn(()=>toBrewPromise(testBrew));
const fn = api.getBrew('share', true);
const req = { brew: {} };
const next = jest.fn();
await fn(req, null, next);
await api.getCSS(req, res);
expect(req.brew).toEqual(testBrew);
expect(req.brew).toHaveProperty('style');
expect(res.status).toHaveBeenCalledWith(404);
expect(res.send).toHaveBeenCalledWith('');
});
});
describe('Split Text, Style, and Metadata', ()=>{
it('basic splitting', async ()=>{
@@ -1301,83 +1372,5 @@ brew`);
expect(testBrew.text).toEqual('text\n');
});
});
describe('updateBrew', ()=>{
it('should return error on version mismatch', async ()=>{
const brewFromClient = { version: 1 };
const brewFromServer = { version: 1000, text: '' };
const req = {
brew : brewFromServer,
body : brewFromClient
};
await api.updateBrew(req, res);
expect(res.status).toHaveBeenCalledWith(409);
expect(res.send).toHaveBeenCalledWith('{\"message\":\"The server version is out of sync with the saved brew. Please save your changes elsewhere, refresh, and try again.\"}');
});
it('should return error on hash mismatch', async ()=>{
const brewFromClient = { version: 1, hash: '1234' };
const brewFromServer = { version: 1, text: 'test' };
const req = {
brew : brewFromServer,
body : brewFromClient
};
await api.updateBrew(req, res);
expect(req.brew.hash).toBe('098f6bcd4621d373cade4e832627b4f6');
expect(res.status).toHaveBeenCalledWith(409);
expect(res.send).toHaveBeenCalledWith('{\"message\":\"The server copy is out of sync with the saved brew. Please save your changes elsewhere, refresh, and try again.\"}');
});
// Commenting this one out for now, since we are no longer throwing this error while we monitor
// it('should return error on applying patches', async ()=>{
// const brewFromClient = { version: 1, hash: '098f6bcd4621d373cade4e832627b4f6', patches: 'not a valid patch string' };
// const brewFromServer = { version: 1, text: 'test', title: 'Test Title', description: 'Test Description' };
// const req = {
// brew : brewFromServer,
// body : brewFromClient,
// };
// let err;
// try {
// await api.updateBrew(req, res);
// } catch (e) {
// err = e;
// }
// expect(err).toEqual(Error('Invalid patch string: not a valid patch string'));
// });
it('should save brew, no ID', async ()=>{
const brewFromClient = { version: 1, hash: '098f6bcd4621d373cade4e832627b4f6', patches: '' };
const brewFromServer = { version: 1, text: 'test', title: 'Test Title', description: 'Test Description' };
model.save = jest.fn((brew)=>{return brew;});
const req = {
brew : brewFromServer,
body : brewFromClient,
query : { saveToGoogle: false, removeFromGoogle: false }
};
await api.updateBrew(req, res);
expect(res.status).toHaveBeenCalledWith(200);
expect(res.send).toHaveBeenCalledWith(
expect.objectContaining({
_id : '1',
description : 'Test Description',
hash : '098f6bcd4621d373cade4e832627b4f6',
title : 'Test Title',
version : 2
})
);
});
});
});
+1 -1
View File
@@ -1,5 +1,5 @@
import _ from 'lodash';
import yaml from 'js-yaml';
import * as yaml from 'js-yaml';
import request from '../client/homebrew/utils/request-middleware.js';
// Convert the templates from a brew to a Snippets Structure.
+5
View File
@@ -14,6 +14,8 @@ import { markedVariables,
import { markedSmartypantsLite as MarkedSmartypantsLite } from 'marked-smartypants-lite';
import { gfmHeadingId as MarkedGFMHeadingId, resetHeadings as MarkedGFMResetHeadingIDs } from 'marked-gfm-heading-id';
import { markedEmoji as MarkedEmojis } from 'marked-emoji';
import MarkedDiagramsMarkdeep from 'marked-diagrams-markdeep';
//Icon fonts included so they can appear in emoji autosuggest dropdown
import diceFont from '../themes/fonts/iconFonts/diceFont.js';
@@ -353,7 +355,10 @@ const tableTerminators = [
` *{{[^{\n]*\n.*?\n}}` // mustacheDiv
];
const markdeepOptions = { langs: ['asciiArt'] };
Marked.use(markedVariables());
Marked.use(MarkedDiagramsMarkdeep(markdeepOptions));
Marked.use(MarkedDefinitionLists());
Marked.use({ extensions: [forcedParagraphBreaks, mustacheSpans, mustacheDivs, mustacheInjectInline] });
Marked.use(mustacheInjectBlock);
+6
View File
@@ -43,6 +43,12 @@ test('Javascript via inline event handler - onMouseOver', function() {
expect(rendered).toBe('<div>Hover over me</div>');
});
test('Javascript via multiple inline event handlers - onClick + onMouseOver', function() {
const source = `<div onclick="alert('This is a JavaScript injection via inline event handler')" onmouseover="alert('This is a JavaScript injection via inline event handler')">Hover over or Click me</div>`;
const rendered = safeHTML(source);
expect(rendered).toBe('<div>Hover over or Click me</div>');
});
test('Javascript via data attribute', function() {
const source = `<div data-code="javascript:alert('This is a JavaScript injection via data attribute')">Test</div>`;
const rendered = safeHTML(source);
+1 -1
View File
@@ -9,7 +9,7 @@ String.prototype.trimReturns = function(){
return this.replace(/\r?\n|\r/g, '').trim();
};
renderAllPages = function(pages){
const renderAllPages = function(pages){
const outputs = [];
pages.forEach((page, index)=>{
const output = Markdown.render(page, index);