mirror of
https://github.com/naturalcrit/homebrewery.git
synced 2026-01-06 12:12:42 +00:00
Merge branch 'Intersection-Observer' into Observer-Master-merge
This commit is contained in:
@@ -1,7 +1,7 @@
|
|||||||
/*eslint max-lines: ["warn", {"max": 300, "skipBlankLines": true, "skipComments": true}]*/
|
/*eslint max-lines: ["warn", {"max": 300, "skipBlankLines": true, "skipComments": true}]*/
|
||||||
require('./brewRenderer.less');
|
require('./brewRenderer.less');
|
||||||
const React = require('react');
|
const React = require('react');
|
||||||
const { useState, useRef, useCallback, useMemo } = React;
|
const { useState, useRef, useCallback, useMemo, useEffect } = React;
|
||||||
const _ = require('lodash');
|
const _ = require('lodash');
|
||||||
|
|
||||||
const MarkdownLegacy = require('naturalcrit/markdownLegacy.js');
|
const MarkdownLegacy = require('naturalcrit/markdownLegacy.js');
|
||||||
@@ -32,12 +32,54 @@ const INITIAL_CONTENT = dedent`
|
|||||||
//v=====----------------------< Brew Page Component >---------------------=====v//
|
//v=====----------------------< Brew Page Component >---------------------=====v//
|
||||||
const BrewPage = (props)=>{
|
const BrewPage = (props)=>{
|
||||||
props = {
|
props = {
|
||||||
contents : '',
|
contents : '',
|
||||||
index : 0,
|
index : 0,
|
||||||
|
onVisibilityChange : ()=>{},
|
||||||
|
onCenterPageChange : ()=>{},
|
||||||
...props
|
...props
|
||||||
};
|
};
|
||||||
|
const pageRef = useRef(null);
|
||||||
const cleanText = safeHTML(props.contents);
|
const cleanText = safeHTML(props.contents);
|
||||||
return <div className={props.className} id={`p${props.index + 1}`} style={props.style}>
|
|
||||||
|
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); // add page to array of visible pages.
|
||||||
|
} else {
|
||||||
|
props.onVisibilityChange(props.index + 1, 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.onCenterPageChange(props.index + 1); // 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();
|
||||||
|
};
|
||||||
|
}, [props.index, props.onVisibilityChange, props.onCenterPageChange]);
|
||||||
|
|
||||||
|
return <div className={props.className} id={`p${props.index + 1}`} data-index={props.index} ref={pageRef} style={props.style}>
|
||||||
<div className='columnWrapper' dangerouslySetInnerHTML={{ __html: cleanText }} />
|
<div className='columnWrapper' dangerouslySetInnerHTML={{ __html: cleanText }} />
|
||||||
</div>;
|
</div>;
|
||||||
};
|
};
|
||||||
@@ -65,7 +107,9 @@ const BrewRenderer = (props)=>{
|
|||||||
|
|
||||||
const [state, setState] = useState({
|
const [state, setState] = useState({
|
||||||
isMounted : false,
|
isMounted : false,
|
||||||
visibility : 'hidden'
|
visibility : 'hidden',
|
||||||
|
visiblePages : [],
|
||||||
|
centerPage : 1
|
||||||
});
|
});
|
||||||
|
|
||||||
const [displayOptions, setDisplayOptions] = useState({
|
const [displayOptions, setDisplayOptions] = useState({
|
||||||
@@ -75,6 +119,7 @@ const BrewRenderer = (props)=>{
|
|||||||
pageShadows : true
|
pageShadows : true
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const iframeRef = useRef(null);
|
||||||
const mainRef = useRef(null);
|
const mainRef = useRef(null);
|
||||||
|
|
||||||
if(props.renderer == 'legacy') {
|
if(props.renderer == 'legacy') {
|
||||||
@@ -83,33 +128,33 @@ const BrewRenderer = (props)=>{
|
|||||||
rawPages = props.text.split(/^\\page$/gm);
|
rawPages = props.text.split(/^\\page$/gm);
|
||||||
}
|
}
|
||||||
|
|
||||||
const scrollToHash = (hash)=>{
|
// update centerPage (aka "current page") and pass it up to parent components
|
||||||
if(!hash) return;
|
useEffect(()=>{
|
||||||
|
props.onPageChange(state.centerPage);
|
||||||
|
}, [state.centerPage]);
|
||||||
|
|
||||||
const iframeDoc = document.getElementById('BrewRenderer').contentDocument;
|
const handlePageVisibilityChange = useCallback((pageNum, isVisible)=>{
|
||||||
let anchor = iframeDoc.querySelector(hash);
|
setState((prevState)=>{
|
||||||
|
const updatedVisiblePages = new Set(prevState.visiblePages);
|
||||||
|
if(isVisible){
|
||||||
|
updatedVisiblePages.add(pageNum);
|
||||||
|
} else {
|
||||||
|
updatedVisiblePages.delete(pageNum);
|
||||||
|
}
|
||||||
|
const pages = Array.from(updatedVisiblePages);
|
||||||
|
|
||||||
if(anchor) {
|
return { ...prevState,
|
||||||
anchor.scrollIntoView({ behavior: 'smooth' });
|
visiblePages : _.sortBy(pages)
|
||||||
} 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 updateCurrentPage = useCallback(_.throttle((e)=>{
|
const handleCenterPageChange = useCallback((pageNum)=>{
|
||||||
const { scrollTop, clientHeight, scrollHeight } = e.target;
|
setState((prevState)=>({
|
||||||
const totalScrollableHeight = scrollHeight - clientHeight;
|
...prevState,
|
||||||
const currentPageNumber = Math.max(Math.ceil((scrollTop / totalScrollableHeight) * rawPages.length), 1);
|
centerPage : pageNum,
|
||||||
|
}));
|
||||||
props.onPageChange(currentPageNumber);
|
}, []);
|
||||||
}, 200), []);
|
|
||||||
|
|
||||||
const isInView = (index)=>{
|
const isInView = (index)=>{
|
||||||
if(!state.isMounted)
|
if(!state.isMounted)
|
||||||
@@ -139,7 +184,7 @@ const BrewRenderer = (props)=>{
|
|||||||
const renderPage = (pageText, index)=>{
|
const renderPage = (pageText, index)=>{
|
||||||
if(props.renderer == 'legacy') {
|
if(props.renderer == 'legacy') {
|
||||||
const html = MarkdownLegacy.render(pageText);
|
const html = MarkdownLegacy.render(pageText);
|
||||||
return <BrewPage className='page phb' index={index} key={index} contents={html} />;
|
return <BrewPage className='page phb' index={index} key={index} contents={html} style={styles} onVisibilityChange={handlePageVisibilityChange} onCenterPageChange={handleCenterPageChange} />;
|
||||||
} else {
|
} else {
|
||||||
pageText += `\n\n \n\\column\n `; //Artificial column break at page end to emulate column-fill:auto (until `wide` is used, when column-fill:balance will reappear)
|
pageText += `\n\n \n\\column\n `; //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);
|
||||||
@@ -149,7 +194,7 @@ const BrewRenderer = (props)=>{
|
|||||||
// Add more conditions as needed
|
// Add more conditions as needed
|
||||||
};
|
};
|
||||||
|
|
||||||
return <BrewPage className='page' index={index} key={index} contents={html} style={styles} />;
|
return <BrewPage className='page' index={index} key={index} contents={html} style={styles} onVisibilityChange={handlePageVisibilityChange} onCenterPageChange={handleCenterPageChange} />;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -182,7 +227,6 @@ const BrewRenderer = (props)=>{
|
|||||||
};
|
};
|
||||||
|
|
||||||
const frameDidMount = ()=>{ //This triggers when iFrame finishes internal "componentDidMount"
|
const frameDidMount = ()=>{ //This triggers when iFrame finishes internal "componentDidMount"
|
||||||
scrollToHash(window.location.hash);
|
|
||||||
|
|
||||||
setTimeout(()=>{ //We still see a flicker where the style isn't applied yet, so wait 100ms before showing iFrame
|
setTimeout(()=>{ //We still see a flicker where the style isn't applied yet, so wait 100ms before showing iFrame
|
||||||
renderPages(); //Make sure page is renderable before showing
|
renderPages(); //Make sure page is renderable before showing
|
||||||
@@ -222,7 +266,7 @@ const BrewRenderer = (props)=>{
|
|||||||
<>
|
<>
|
||||||
{/*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>
|
||||||
@@ -235,7 +279,7 @@ const BrewRenderer = (props)=>{
|
|||||||
<NotificationPopup />
|
<NotificationPopup />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ToolBar displayOptions={displayOptions} currentPage={props.currentBrewRendererPageNum} totalPages={rawPages.length} onDisplayOptionsChange={handleDisplayOptionsChange} />
|
<ToolBar displayOptions={displayOptions} onDisplayOptionsChange={handleDisplayOptionsChange} centerPage={state.centerPage} visiblePages={state.visiblePages} totalPages={rawPages.length}/>
|
||||||
|
|
||||||
{/*render in iFrame so broken code doesn't crash the site.*/}
|
{/*render in iFrame so broken code doesn't crash the site.*/}
|
||||||
<Frame id='BrewRenderer' initialContent={INITIAL_CONTENT}
|
<Frame id='BrewRenderer' initialContent={INITIAL_CONTENT}
|
||||||
@@ -244,19 +288,18 @@ const BrewRenderer = (props)=>{
|
|||||||
onClick={()=>{emitClick();}}
|
onClick={()=>{emitClick();}}
|
||||||
>
|
>
|
||||||
<div className={`brewRenderer ${global.config.deployment && 'deployment'}`}
|
<div className={`brewRenderer ${global.config.deployment && 'deployment'}`}
|
||||||
onScroll={updateCurrentPage}
|
|
||||||
onKeyDown={handleControlKeys}
|
onKeyDown={handleControlKeys}
|
||||||
tabIndex={-1}
|
tabIndex={-1}
|
||||||
style={ styleObject }>
|
style={ styleObject }
|
||||||
|
>
|
||||||
|
|
||||||
{/* Apply CSS from Style tab and render pages from Markdown tab */}
|
{/* Apply CSS from Style tab and render pages from Markdown tab */}
|
||||||
{state.isMounted
|
{state.isMounted
|
||||||
&&
|
&&
|
||||||
<>
|
<>
|
||||||
{renderStyle()}
|
{renderedStyle}
|
||||||
<div lang={`${props.lang || 'en'}`} style={pagesStyle} className={
|
<div className={`pages ${displayOptions.startOnRight ? 'recto' : 'verso'} ${displayOptions.spread}`} lang={`${props.lang || 'en'}`} style={pagesStyle} ref={iframeRef}>
|
||||||
`pages ${displayOptions.startOnRight ? 'recto' : 'verso'} ${displayOptions.spread}` } >
|
{renderedPages}
|
||||||
{renderPages()}
|
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -4,19 +4,20 @@ const { useState, useEffect } = React;
|
|||||||
const _ = require('lodash');
|
const _ = require('lodash');
|
||||||
|
|
||||||
import { Anchored, AnchoredBox, AnchoredTrigger } from '../../../components/Anchored.jsx';
|
import { Anchored, AnchoredBox, AnchoredTrigger } from '../../../components/Anchored.jsx';
|
||||||
// import * as ZoomIcons from '../../../icons/icon-components/zoomIcons.jsx';
|
|
||||||
|
|
||||||
const MAX_ZOOM = 300;
|
const MAX_ZOOM = 300;
|
||||||
const MIN_ZOOM = 10;
|
const MIN_ZOOM = 10;
|
||||||
|
|
||||||
const ToolBar = ({ displayOptions, currentPage, totalPages, onDisplayOptionsChange })=>{
|
const ToolBar = ({ displayOptions, onDisplayOptionsChange, visiblePages, totalPages })=>{
|
||||||
|
|
||||||
const [pageNum, setPageNum] = useState(currentPage);
|
const [pageNum, setPageNum] = useState(1);
|
||||||
const [toolsVisible, setToolsVisible] = useState(true);
|
const [toolsVisible, setToolsVisible] = useState(true);
|
||||||
|
|
||||||
useEffect(()=>{
|
useEffect(()=>{
|
||||||
setPageNum(currentPage);
|
if(visiblePages.length !== 0){ // If zoomed in enough, it's possible that no page fits the intersection criteria, so don't update.
|
||||||
}, [currentPage]);
|
setPageNum(formatVisiblePages(visiblePages));
|
||||||
|
}
|
||||||
|
}, [visiblePages]);
|
||||||
|
|
||||||
const handleZoomButton = (zoom)=>{
|
const handleZoomButton = (zoom)=>{
|
||||||
handleOptionChange('zoomLevel', _.round(_.clamp(zoom, MIN_ZOOM, MAX_ZOOM)));
|
handleOptionChange('zoomLevel', _.round(_.clamp(zoom, MIN_ZOOM, MAX_ZOOM)));
|
||||||
@@ -28,20 +29,21 @@ const ToolBar = ({ displayOptions, currentPage, totalPages, onDisplayOptionsChan
|
|||||||
};
|
};
|
||||||
|
|
||||||
const handlePageInput = (pageInput)=>{
|
const handlePageInput = (pageInput)=>{
|
||||||
|
console.log(pageInput);
|
||||||
if(/[0-9]/.test(pageInput))
|
if(/[0-9]/.test(pageInput))
|
||||||
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;
|
||||||
@@ -69,6 +71,28 @@ const ToolBar = ({ displayOptions, currentPage, totalPages, onDisplayOptionsChan
|
|||||||
return deltaZoom;
|
return deltaZoom;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// format the visible pages to work with ranges, including separate ranges ("2-7, 10-15")
|
||||||
|
const formatVisiblePages = (pages)=>{
|
||||||
|
if(pages.length === 0) return '';
|
||||||
|
|
||||||
|
const sortedPages = [...pages].sort((a, b)=>a - b); // Copy and sort the array
|
||||||
|
const ranges = [];
|
||||||
|
let start = sortedPages[0];
|
||||||
|
|
||||||
|
for (let i = 1; i <= sortedPages.length; i++) {
|
||||||
|
// If the current page is not consecutive or it's the end of the list
|
||||||
|
if(i === sortedPages.length || sortedPages[i] !== sortedPages[i - 1] + 1) {
|
||||||
|
// Push the range to the list
|
||||||
|
ranges.push(
|
||||||
|
start === sortedPages[i - 1] ? `${start}` : `${start} - ${sortedPages[i - 1]}`
|
||||||
|
);
|
||||||
|
start = sortedPages[i]; // Start a new range
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return ranges.join(', ');
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div id='preview-toolbar' className={`toolBar ${toolsVisible ? 'visible' : 'hidden'}`} role='toolbar'>
|
<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>
|
<button className='toggleButton' title={`${toolsVisible ? 'Hide' : 'Show'} Preview Toolbar`} onClick={()=>{setToolsVisible(!toolsVisible);}}><i className='fas fa-glasses' /></button>
|
||||||
@@ -185,7 +209,10 @@ const ToolBar = ({ displayOptions, currentPage, totalPages, onDisplayOptionsChan
|
|||||||
className='previousPage tool'
|
className='previousPage tool'
|
||||||
type='button'
|
type='button'
|
||||||
title='Previous Page(s)'
|
title='Previous Page(s)'
|
||||||
onClick={()=>scrollToPage(pageNum - 1)}
|
onClick={()=>{
|
||||||
|
const rangeOffset = visiblePages.length > 1 ? 1 : 0;
|
||||||
|
scrollToPage(_.min(visiblePages) - visiblePages.length + rangeOffset);
|
||||||
|
}}
|
||||||
disabled={pageNum <= 1}
|
disabled={pageNum <= 1}
|
||||||
>
|
>
|
||||||
<i className='fas fa-arrow-left'></i>
|
<i className='fas fa-arrow-left'></i>
|
||||||
@@ -200,7 +227,7 @@ const ToolBar = ({ displayOptions, currentPage, totalPages, onDisplayOptionsChan
|
|||||||
title='Current page(s) in view'
|
title='Current page(s) in view'
|
||||||
inputMode='numeric'
|
inputMode='numeric'
|
||||||
pattern='[0-9]'
|
pattern='[0-9]'
|
||||||
value={pageNum}
|
value={`${pageNum}`}
|
||||||
onClick={(e)=>e.target.select()}
|
onClick={(e)=>e.target.select()}
|
||||||
onChange={(e)=>handlePageInput(e.target.value)}
|
onChange={(e)=>handlePageInput(e.target.value)}
|
||||||
onBlur={()=>scrollToPage(pageNum)}
|
onBlur={()=>scrollToPage(pageNum)}
|
||||||
@@ -214,7 +241,10 @@ const ToolBar = ({ displayOptions, currentPage, totalPages, onDisplayOptionsChan
|
|||||||
className='tool'
|
className='tool'
|
||||||
type='button'
|
type='button'
|
||||||
title='Next Page(s)'
|
title='Next Page(s)'
|
||||||
onClick={()=>scrollToPage(pageNum + 1)}
|
onClick={()=>{
|
||||||
|
const rangeOffset = visiblePages.length > 1 ? 0 : 1;
|
||||||
|
scrollToPage(_.max(visiblePages) + rangeOffset);
|
||||||
|
}}
|
||||||
disabled={pageNum >= totalPages}
|
disabled={pageNum >= totalPages}
|
||||||
>
|
>
|
||||||
<i className='fas fa-arrow-right'></i>
|
<i className='fas fa-arrow-right'></i>
|
||||||
|
|||||||
@@ -103,9 +103,9 @@
|
|||||||
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
|
||||||
@@ -140,7 +140,7 @@
|
|||||||
|
|
||||||
// `.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;
|
width : 10ch;
|
||||||
margin-right : 1ch;
|
margin-right : 1ch;
|
||||||
text-align : center;
|
text-align : center;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user