migrate to react hooks

This commit is contained in:
2025-11-19 20:55:19 -08:00
parent 3c61426a12
commit 1cfcd8ff04
9 changed files with 495 additions and 522 deletions

View File

@@ -1,7 +1,6 @@
import * as Model from "../model";
import { Picture } from "./picture";
import * as React from "react"; import * as React from "react";
import * as Model from "model";
import { Picture } from "components/picture";
export interface Props { export interface Props {
image: Model.Image; image: Model.Image;
@@ -16,93 +15,99 @@ interface TouchStart {
y: number; y: number;
} }
export interface State { export const BigPicture: React.FC<Props> = ({
touchStart?: TouchStart | null; image,
} onClose,
showNext,
showPrevious,
width,
}) => {
const [touchStart, setTouchStart] = React.useState<TouchStart | null>(null);
export class BigPicture extends React.PureComponent<Props, State> { const onEscape = React.useCallback(
static displayName = "BigPicture"; (e: KeyboardEvent) => {
if (e.key === "Escape") {
componentDidMount() { onClose();
window.addEventListener("keyup", this._onEscape as any);
window.addEventListener("touchstart", this._onTouchStart as any);
window.addEventListener("touchend", this._onTouchEnd as any);
document.body.classList.add("no-scroll");
}
componentWillUnmount() {
window.removeEventListener("keyup", this._onEscape as any);
window.removeEventListener("touchstart", this._onTouchStart as any);
window.removeEventListener("touchend", this._onTouchEnd as any);
document.body.classList.remove("no-scroll");
}
render() {
const scaleWidth = this.props.image.width / this.props.width;
const scaleHeight = this.props.image.height / (window.innerHeight - 80);
const scale = Math.max(scaleWidth, scaleHeight);
return (
<div className="BigPicture">
<Picture
image={this.props.image}
onClick={() => {}}
height={this.props.image.height / scale}
width={this.props.image.width / scale}
/>
<div className="BigPicture-footer">
<a
className="BigPicture-footerLink"
href={`img/${this.props.image.src}`}
target="_blank"
>
Download
</a>
<span
className="BigPicture-footerLink"
role="button"
onClick={this.props.onClose}
onKeyPress={this._keyPress}
tabIndex={0}
>
Close
</span>
</div>
</div>
);
}
private _keyPress = (e: React.KeyboardEvent) => {
if (e.key === "Enter") {
this.props.onClose();
}
};
private _onEscape = (e: React.KeyboardEvent) => {
if (e.key === "Escape") {
this.props.onClose();
}
};
private _onTouchStart = (e: React.TouchEvent) => {
const touch = e.touches[0];
this.setState({ touchStart: { x: touch.screenX, y: touch.screenY } });
};
private _onTouchEnd = (e: React.TouchEvent) => {
const touch = e.changedTouches[0];
const touchStart = this.state.touchStart as TouchStart;
const dx = touch.screenX - touchStart.x;
if (Math.abs(dx) / window.innerWidth > 0.05) {
if (dx < 0) {
this.props.showNext();
} else {
this.props.showPrevious();
} }
} },
[onClose]
);
this.setState({ touchStart: null }); const onTouchStart = React.useCallback((e: TouchEvent) => {
}; const touch = e.touches[0];
} setTouchStart({ x: touch.screenX, y: touch.screenY });
}, []);
const onTouchEnd = React.useCallback(
(e: TouchEvent) => {
if (!touchStart) {
return;
}
const touch = e.changedTouches[0];
const dx = touch.screenX - touchStart.x;
if (Math.abs(dx) / window.innerWidth > 0.05) {
if (dx < 0) {
showNext();
} else {
showPrevious();
}
}
setTouchStart(null);
},
[showNext, showPrevious, touchStart]
);
React.useEffect(() => {
window.addEventListener("keyup", onEscape);
window.addEventListener("touchstart", onTouchStart);
window.addEventListener("touchend", onTouchEnd);
document.body.classList.add("no-scroll");
return () => {
window.removeEventListener("keyup", onEscape);
window.removeEventListener("touchstart", onTouchStart);
window.removeEventListener("touchend", onTouchEnd);
document.body.classList.remove("no-scroll");
};
}, [onEscape, onTouchEnd, onTouchStart]);
const scaleWidth = image.width / width;
const scaleHeight = image.height / (window.innerHeight - 80);
const scale = Math.max(scaleWidth, scaleHeight);
return (
<div className="BigPicture">
<Picture
image={image}
onClick={() => {}}
height={image.height / scale}
width={image.width / scale}
/>
<div className="BigPicture-footer">
<a
className="BigPicture-footerLink"
href={`img/${image.src}`}
target="_blank"
rel="noreferrer"
>
Download
</a>
<span
className="BigPicture-footerLink"
role="button"
onClick={onClose}
onKeyPress={(e) => {
if (e.key === "Enter") {
onClose();
}
}}
tabIndex={0}
>
Close
</span>
</div>
</div>
);
};

View File

@@ -1,7 +1,6 @@
import { Picture } from "./picture";
import * as Model from "../model";
import * as React from "react"; import * as React from "react";
import * as Model from "model";
import { Picture } from "components/picture";
export interface Props { export interface Props {
images: Model.Image[]; images: Model.Image[];
@@ -24,72 +23,60 @@ interface BadList {
badness: number; badness: number;
} }
export class Grid extends React.PureComponent<Props, {}> { const badness = (row: Model.Image[], width: number, height: number): number => {
static displayName: string = "Grid"; const rowWidth = row.reduce((w, img) => w + img.width / img.height, 0);
const rowHeight = width / rowWidth;
private gridHeight = 0; return (rowHeight - height) * (rowHeight - height);
};
static badness = ( export const Grid: React.FC<Props> = ({
row: Model.Image[], images,
width: number, onImageSelected,
height: number pageBottom,
): number => { width,
const rowWidth = row.reduce((w, img) => w + img.width / img.height, 0); height,
const rowHeight = width / rowWidth; }) => {
const rowsMemo = React.useRef<Map<number, Map<number, BadList>>>(new Map());
const targetRowHeight = width > 900 ? ROW_HEIGHT : MOBILE_ROW_HEIGHT;
return (rowHeight - height) * (rowHeight - height); React.useEffect(() => {
};
// [width][idx] -> badness
private rowsMemo: Map<number, Map<number, BadList>> = new Map();
componentDidUpdate(prevProps: Props) {
// The memoized rows depend on the image list; clear when the set changes // The memoized rows depend on the image list; clear when the set changes
if (prevProps.images !== this.props.images) { rowsMemo.current.clear();
this.rowsMemo.clear(); }, [images]);
}
}
rows(idx: number): BadList { const rowsFor = (idx: number): BadList => {
const targetHeight = this._rowHeight(); const memo = rowsMemo.current.get(width) ?? new Map();
const memo = this.rowsMemo.get(this.props.width) ?? new Map();
const maybeMemo = memo.get(idx); const maybeMemo = memo.get(idx);
if (maybeMemo) { if (maybeMemo) {
return maybeMemo; return maybeMemo;
} }
if (idx === this.props.images.length) { if (idx === images.length) {
return { return {
splits: [], splits: [],
badness: 0, badness: 0,
}; };
} }
if (idx === this.props.images.length - 1) { if (idx === images.length - 1) {
const img = this.props.images[idx]; const img = images[idx];
const h = (img.height * this.props.width) / img.width; const h = (img.height * width) / img.width;
return { return {
splits: [], splits: [],
badness: (targetHeight - h) * (targetHeight - h), badness: (targetRowHeight - h) * (targetRowHeight - h),
}; };
} }
let bestIdx = -1;
let leastBad = 1e50; let leastBad = 1e50;
let bestSplits: number[] = []; let bestSplits: number[] = [];
for (let i = idx + 1; i <= this.props.images.length; i++) { for (let i = idx + 1; i <= images.length; i++) {
const rowBadness = Grid.badness( const rowBadness = badness(images.slice(idx, i), width, targetRowHeight);
this.props.images.slice(idx, i), const rest = rowsFor(i);
this.props.width, const totalBadness = rest.badness + rowBadness;
targetHeight if (totalBadness < leastBad) {
); leastBad = totalBadness;
const rest = this.rows(i);
const badness = rest.badness + rowBadness;
if (badness < leastBad) {
leastBad = badness;
bestIdx = i;
bestSplits = [i, ...rest.splits]; bestSplits = [i, ...rest.splits];
} }
} }
@@ -101,60 +88,57 @@ export class Grid extends React.PureComponent<Props, {}> {
memo.set(idx, badList); memo.set(idx, badList);
if (!this.rowsMemo.has(this.props.width)) { if (!rowsMemo.current.has(width)) {
this.rowsMemo.set(this.props.width, memo); rowsMemo.current.set(width, memo);
} }
return badList; return badList;
} };
render() { let gridHeight = 0;
this.gridHeight = 0;
const badList = this.rows(0); const badList = rowsFor(0);
let lastBreak = 0; let lastBreak = 0;
const rows: Row[] = badList.splits.map((split) => { const rows: Row[] = badList.splits.map((split) => {
const images = this.props.images.slice(lastBreak, split); const slice = images.slice(lastBreak, split);
lastBreak = split; lastBreak = split;
return { return {
images, images: slice,
width: images.reduce((acc, img) => acc + img.width / img.height, 0), width: slice.reduce((acc, img) => acc + img.width / img.height, 0),
}; };
}); });
const images = rows.map((row) => { const pictures = rows.map((row) => {
const height = Math.min(this.props.height, this.props.width / row.width); const rowHeight = Math.min(height, width / row.width);
const pics = row.images.map((image) => {
return (
<Picture
image={image}
onClick={() => this.props.onImageSelected(image)}
key={image.src}
height={height}
width={(image.width / image.height) * height}
defer={this.gridHeight > this.props.pageBottom}
/>
);
});
this.gridHeight += height;
const pics = row.images.map((image) => {
const scaledWidth = (image.width / image.height) * rowHeight;
const defer = gridHeight > pageBottom;
return ( return (
<div <Picture
className="Grid-row" image={image}
style={{ height: height + "px" }} onClick={() => onImageSelected(image)}
key={row.images.map((image) => image.src).join(",")} key={image.src}
> height={rowHeight}
{pics} width={scaledWidth}
</div> defer={defer}
/>
); );
}); });
return <div className="Grid">{images}</div>; gridHeight += rowHeight;
}
private _rowHeight = (): number => return (
this.props.width > 900 ? ROW_HEIGHT : MOBILE_ROW_HEIGHT; <div
} className="Grid-row"
style={{ height: rowHeight + "px" }}
key={row.images.map((image) => image.src).join(",")}
>
{pics}
</div>
);
});
return <div className="Grid">{pictures}</div>;
};

View File

@@ -1,61 +1,48 @@
import { Grid } from "./grid";
import * as Model from "../model";
import * as React from "react"; import * as React from "react";
import * as Model from "model";
import { Grid } from "components/grid";
export interface Props { export interface Props {
imageSet: Model.ImageSet; imageSet: Model.ImageSet;
onImageSelected: (img: Model.Image) => void; onImageSelected: (img: Model.Image) => void;
onShowHome: () => void; onShowHome: () => void;
setGridHeight: (height: number) => void;
pageBottom: number; pageBottom: number;
width: number; width: number;
height: number; height: number;
} }
export class ImageSet extends React.PureComponent<Props, {}> { export const ImageSet: React.FC<Props> = ({
static displayName = "ImageSet"; imageSet,
onImageSelected,
private divRef = React.createRef<HTMLDivElement>(); onShowHome,
pageBottom,
render() { width,
return ( height,
<div className="ImageSet" ref={this.divRef}> }) => {
<h2> return (
<span className="ImageSet-location"> <div className="ImageSet">
{this.props.imageSet.location} <h2>
</span> <span className="ImageSet-location">{imageSet.location}</span>
<span className="ImageSet-description"> <span className="ImageSet-description">{imageSet.description}</span>
{this.props.imageSet.description} </h2>
</span> <Grid
</h2> images={imageSet.images}
<Grid onImageSelected={onImageSelected}
images={this.props.imageSet.images} pageBottom={pageBottom}
onImageSelected={this.props.onImageSelected} width={width}
pageBottom={this.props.pageBottom} height={height}
width={this.props.width} />
height={this.props.height} <div className="ImageSet-navigation">
/> <a
<div className="ImageSet-navigation"> href="#"
<a href="#" onClick={this.props.onShowHome}> onClick={(e) => {
Back e.preventDefault();
</a> onShowHome();
</div> }}
>
Back
</a>
</div> </div>
); </div>
} );
};
componentDidMount() {
this._setGridHeight();
}
componentDidUpdate() {
this._setGridHeight();
}
private _setGridHeight = () => {
if (this.divRef.current) {
this.props.setGridHeight(this.divRef.current.clientHeight);
}
};
}

View File

@@ -1,6 +1,5 @@
import * as Model from "../model";
import * as React from "react"; import * as React from "react";
import * as Model from "model";
export interface Props { export interface Props {
image: Model.Image; image: Model.Image;
@@ -10,10 +9,6 @@ export interface Props {
defer?: boolean; defer?: boolean;
} }
export interface State {
isMounted: boolean;
}
interface SrcSetInfo { interface SrcSetInfo {
jpeg: string; jpeg: string;
webp: string; webp: string;
@@ -21,46 +16,20 @@ interface SrcSetInfo {
bestSrc: string; bestSrc: string;
} }
export class Picture extends React.PureComponent<Props, State> { export const Picture: React.FC<Props> = ({
static displayName = "Picture"; image,
onClick,
height,
width,
defer,
}) => {
const [isMounted, setIsMounted] = React.useState(false);
state: State = { React.useEffect(() => {
isMounted: false, setIsMounted(true);
}; }, []);
componentDidMount() { const srcSet = React.useMemo(() => {
this.setState({ isMounted: true });
}
render() {
if (this.props.defer || !this.state.isMounted) {
return (
<div
className="Picture-defer"
style={{ width: this.props.width + "px" }}
/>
);
}
const srcSet = this._srcset();
return (
<picture>
<source srcSet={srcSet.avif} type="image/avif" />
<source srcSet={srcSet.webp} type="image/webp" />
<source srcSet={srcSet.jpeg} type="image/jpeg" />
<img
id={this.props.image.src}
onClick={this.props.onClick}
src={srcSet.bestSrc}
height={this.props.height + "px"}
width={Math.floor(this.props.width) + "px"}
/>
</picture>
);
}
private _srcset = (): SrcSetInfo => {
const jpegSrcSet: string[] = []; const jpegSrcSet: string[] = [];
const webpSrcSet: string[] = []; const webpSrcSet: string[] = [];
const avifSrcSet: string[] = []; const avifSrcSet: string[] = [];
@@ -68,15 +37,13 @@ export class Picture extends React.PureComponent<Props, State> {
let bestScale = Infinity; let bestScale = Infinity;
Model.SIZES.forEach((size) => { Model.SIZES.forEach((size) => {
const width = const derivedWidth =
this.props.image.width > this.props.image.height image.width > image.height ? size : (image.width / image.height) * size;
? size
: (this.props.image.width / this.props.image.height) * size;
const scale = width / this.props.width; const scale = derivedWidth / width;
if (scale >= 1 || size === 2400) { if (scale >= 1 || size === 2400) {
const jpeg = `img/${size}/${this.props.image.src}`; const jpeg = `img/${size}/${image.src}`;
const webp = jpeg.replace("jpg", "webp"); const webp = jpeg.replace("jpg", "webp");
const avif = jpeg.replace("jpg", "avif"); const avif = jpeg.replace("jpg", "avif");
jpegSrcSet.push(`${jpeg} ${scale}x`); jpegSrcSet.push(`${jpeg} ${scale}x`);
@@ -93,7 +60,27 @@ export class Picture extends React.PureComponent<Props, State> {
jpeg: jpegSrcSet.join(","), jpeg: jpegSrcSet.join(","),
webp: webpSrcSet.join(","), webp: webpSrcSet.join(","),
avif: avifSrcSet.join(","), avif: avifSrcSet.join(","),
bestSrc: `img/${bestSize}/${this.props.image.src}`, bestSrc: `img/${bestSize}/${image.src}`,
}; };
}; }, [image, width]);
}
if (defer || !isMounted) {
return <div className="Picture-defer" style={{ width: width + "px" }} />;
}
return (
<picture>
<source srcSet={srcSet.avif} type="image/avif" />
<source srcSet={srcSet.webp} type="image/webp" />
<source srcSet={srcSet.jpeg} type="image/jpeg" />
<img
id={image.src}
onClick={onClick}
src={srcSet.bestSrc}
height={height + "px"}
width={Math.floor(width) + "px"}
alt=""
/>
</picture>
);
};

View File

@@ -1,235 +1,255 @@
import { BigPicture } from "./big_picture";
import { ImageSet } from "./image_set";
import { SetCover } from "./set_cover";
import * as Model from "../model";
import * as React from "react"; import * as React from "react";
import * as Model from "model";
import { BigPicture } from "components/big_picture";
import { ImageSet } from "components/image_set";
import { SetCover } from "components/set_cover";
export interface Props {} export interface Props {}
export interface State { const viewWidth = (): number => {
data?: Model.Data | null; const widths = [
selectedImage?: Model.Image | null; window.innerWidth,
selectedSet?: Model.ImageSet | null; window.outerWidth,
gridHeights: number[]; document.documentElement?.clientWidth,
pageBottom: number; document.body?.clientWidth,
width: number; ].filter((w): w is number => typeof w === "number" && w > 0 && isFinite(w));
height: number;
}
export class Root extends React.PureComponent<Props, State> { return widths.length > 0 ? Math.max(...widths) : 0;
static displayName = "Root"; };
// innerWidth gets messed up when rotating phones from landscape -> portrait, const viewHeight = (): number => {
// and chrome seems to not report innerWidth correctly when scrollbars are present const heights = [
private _viewWidth = (): number => { window.innerHeight,
const widths = [ window.outerHeight,
window.innerWidth, document.documentElement?.clientHeight,
window.outerWidth, document.body?.clientHeight,
document.documentElement?.clientWidth, ].filter((h): h is number => typeof h === "number" && h > 0 && isFinite(h));
document.body?.clientWidth,
].filter((w): w is number => typeof w === "number" && w > 0 && isFinite(w));
// Use the largest reasonable value to avoid shrinking the grid when a single return heights.length > 0 ? Math.max(...heights) : 0;
// measurement source temporarily reports something tiny. };
return widths.length > 0 ? Math.max(...widths) : 0;
};
private _viewHeight = (): number => { const formatHash = (set: Model.ImageSet) =>
const heights = [ set.location.replace(/[^a-zA-Z0-9-_]/g, "-") +
window.innerHeight, "-" +
window.outerHeight, set.description.replace(/[^a-zA-Z0-9-_]/g, "-");
document.documentElement?.clientHeight,
document.body?.clientHeight,
].filter((h): h is number => typeof h === "number" && h > 0 && isFinite(h));
return heights.length > 0 ? Math.max(...heights) : 0; export const Root: React.FC<Props> = () => {
}; const [data, setData] = React.useState<Model.Data | null>(null);
const [selectedImage, setSelectedImage] = React.useState<Model.Image | null>(
null
);
const [selectedSet, setSelectedSet] = React.useState<Model.ImageSet | null>(
null
);
const [dimensions, setDimensions] = React.useState(() => {
const height = viewHeight();
return {
pageBottom: height + window.pageYOffset,
width: viewWidth(),
height,
};
});
state: State = { const updateView = React.useCallback(() => {
gridHeights: [], const height = viewHeight();
pageBottom: this._viewHeight() + window.pageYOffset, setDimensions({
width: this._viewWidth(), pageBottom: height + window.pageYOffset,
height: this._viewHeight(), width: viewWidth(),
}; height,
});
}, []);
componentDidMount() { const loadHash = React.useCallback(() => {
if (window.location.hash.length === 0) {
setSelectedImage(null);
setSelectedSet(null);
return;
}
if (!data) {
return;
}
const hash = window.location.hash.slice(1);
let nextImage: Model.Image | null = null;
let nextSet: Model.ImageSet | null = null;
data.sets.forEach((set) => {
if (formatHash(set) === hash) {
nextSet = set;
}
const image = set.images.find((img) => img.src === hash);
if (image) {
nextImage = image;
nextSet = set;
}
});
setSelectedImage(nextImage);
setSelectedSet(nextSet);
}, [data]);
React.useEffect(() => {
let isMounted = true;
window window
.fetch(Model.dataUrl) .fetch(Model.dataUrl)
.then((data) => data.json()) .then((response) => response.json())
.then((json) => this.setState({ data: json })) .then((json) => {
.then(this._loadHash) if (isMounted) {
.then(this._onViewChange) setData(json);
}
})
.catch((e) => console.error("Error fetching data", e)); .catch((e) => console.error("Error fetching data", e));
window.onresize = this._onViewChange; return () => {
window.onscroll = this._onViewChange; isMounted = false;
};
}, []);
try { React.useEffect(() => {
screen.orientation.onchange = this._onViewChange; if (data) {
} catch (e) {} loadHash();
}
}, [data, loadHash]);
try { React.useEffect(() => {
window.onorientationchange = this._onViewChange; const handlePopState = () => loadHash();
} catch (e) {}
window.onpopstate = this._loadHash; window.addEventListener("resize", updateView);
} window.addEventListener("scroll", updateView, { passive: true });
window.addEventListener("orientationchange", updateView);
window.addEventListener("popstate", handlePopState);
private _renderSet(set: Model.ImageSet) { const orientation = (screen as any).orientation;
return ( if (orientation?.addEventListener) {
<ImageSet orientation.addEventListener("change", updateView);
key={set.location + set.description} }
imageSet={set}
pageBottom={this.state.pageBottom} updateView();
setGridHeight={this._setGridHeight(0)}
onImageSelected={this._onImageSelected} return () => {
onShowHome={this._onHomeSelected} window.removeEventListener("resize", updateView);
width={this.state.width} window.removeEventListener("scroll", updateView);
height={this.state.height} window.removeEventListener("orientationchange", updateView);
/> window.removeEventListener("popstate", handlePopState);
); if (orientation?.removeEventListener) {
} orientation.removeEventListener("change", updateView);
}
};
}, [loadHash, updateView]);
React.useEffect(() => {
if (selectedSet) {
document.title =
selectedSet.location +
" " +
selectedSet.description +
" Skiing - Aaron Gutierrez";
} else {
document.title = "Skiing - Aaron Gutierrez";
}
}, [selectedSet]);
const onImageSelected = React.useCallback(
(img: Model.Image) => {
if (selectedImage) {
window.history.replaceState(null, "", `#${img.src}`);
} else {
window.history.pushState(null, "", `#${img.src}`);
}
setSelectedImage(img);
},
[selectedImage]
);
const onSetSelected = React.useCallback((set: Model.ImageSet) => {
setSelectedSet(set);
window.history.pushState(null, "", `#${formatHash(set)}`);
}, []);
const onHomeSelected = React.useCallback(() => {
setSelectedSet(null);
setSelectedImage(null);
window.history.pushState(null, "", "#");
}, []);
const showGrid = React.useCallback(() => {
setSelectedImage(null);
window.history.go(-1);
if (selectedSet) {
onSetSelected(selectedSet);
}
}, [onSetSelected, selectedSet]);
const showNextBigPicture = React.useCallback(() => {
if (!selectedSet || !selectedImage) {
return;
}
const images: Model.Image[] = selectedSet.images;
const current = images.indexOf(selectedImage);
const next = current + 1 >= images.length ? 0 : current + 1;
onImageSelected(images[next]);
}, [onImageSelected, selectedImage, selectedSet]);
const showPreviousBigPicture = React.useCallback(() => {
if (!selectedSet || !selectedImage) {
return;
}
const images: Model.Image[] = selectedSet.images;
const current = images.indexOf(selectedImage);
const previous = current - 1 < 0 ? images.length - 1 : current - 1;
onImageSelected(images[previous]);
}, [onImageSelected, selectedImage, selectedSet]);
const renderSets = () => {
if (!data) {
return null;
}
if (selectedSet) {
return (
<ImageSet
key={selectedSet.location + selectedSet.description}
imageSet={selectedSet}
pageBottom={dimensions.pageBottom}
onImageSelected={onImageSelected}
onShowHome={onHomeSelected}
width={dimensions.width}
height={dimensions.height}
/>
);
}
private _renderSetCovers(sets: Model.ImageSet[]) {
return ( return (
<div className="Root-setCovers"> <div className="Root-setCovers">
{sets.map((set) => ( {data.sets.map((set) => (
<SetCover <SetCover
key={set.location + set.description} key={set.location + set.description}
imageSet={set} imageSet={set}
onClick={() => { onClick={() => {
this._onSetSelected(set); onSetSelected(set);
scrollTo(0, 0); scrollTo(0, 0);
}} }}
width={Math.min(this.state.width, 400)} width={Math.min(dimensions.width, 400)}
/> />
))} ))}
</div> </div>
); );
}
render() {
const imageSets = this.state.data
? this.state.selectedSet
? this._renderSet(this.state.selectedSet)
: this._renderSetCovers(this.state.data.sets)
: null;
return (
<div className="Root">
{this._bigPicture()}
<h1 onClick={this._onHomeSelected}>Aaron's Ski Pictures</h1>
{imageSets}
</div>
);
}
private _bigPicture = () =>
this.state.selectedImage ? (
<BigPicture
image={this.state.selectedImage}
onClose={this._showGrid}
showNext={this._showNextBigPicture}
showPrevious={this._showPreviousBigPicture}
width={this.state.width}
/>
) : null;
private _loadHash = () => {
if (window.location.hash.length > 0 && this.state.data) {
const hash = window.location.hash.slice(1);
let selectedImage: Model.Image | null = null;
let selectedSet: Model.ImageSet | null = null;
this.state.data.sets.forEach((set) => {
if (this._setToHash(set) === hash) {
selectedSet = set;
}
const image = set.images.find((image) => image.src === hash);
if (image) {
selectedImage = image;
selectedSet = set;
}
});
this.setState({ selectedImage, selectedSet });
} else {
this.setState({ selectedImage: null, selectedSet: null });
}
}; };
private _onViewChange = () => { return (
this.setState({ <div className="Root">
pageBottom: this._viewHeight() + window.pageYOffset, {selectedImage ? (
width: this._viewWidth(), <BigPicture
height: this._viewHeight(), image={selectedImage}
}); onClose={showGrid}
}; showNext={showNextBigPicture}
showPrevious={showPreviousBigPicture}
private _onImageSelected = (img: Model.Image) => { width={dimensions.width}
if (this.state.selectedImage) { />
window.history.replaceState(null, "", `#${img.src}`); ) : null}
} else { <h1 onClick={onHomeSelected}>Aaron's Ski Pictures</h1>
window.history.pushState(null, "", `#${img.src}`); {renderSets()}
} </div>
this.setState({ selectedImage: img }); );
}; };
private _onSetSelected = (set: Model.ImageSet) => {
this.setState({ selectedSet: set });
document.title =
set.location + " " + set.description + " Skiing - Aaron Gutierrez";
window.history.pushState(null, "", `#${this._setToHash(set)}`);
};
private _onHomeSelected = () => {
this.setState({
selectedSet: null,
selectedImage: null,
});
window.history.pushState(null, "", "#");
document.title = "Skiing - Aaron Gutierrez";
};
private _setToHash = (set: Model.ImageSet) =>
set.location.replace(/[^a-zA-Z0-9-_]/g, "-") +
"-" +
set.description.replace(/[^a-zA-Z0-9-_]/g, "-");
private _showGrid = () => {
this.setState({ selectedImage: null });
window.history.go(-1);
this._onSetSelected(this.state.selectedSet as Model.ImageSet);
};
private _showNextBigPicture = () => {
const images: Model.Image[] = this.state.selectedSet
?.images as Model.Image[];
const current = images.indexOf(this.state.selectedImage as Model.Image);
const next = current + 1 >= images.length ? 0 : current + 1;
this._onImageSelected(images[next]);
};
private _showPreviousBigPicture = () => {
const images: Model.Image[] = this.state.selectedSet
?.images as Model.Image[];
const current = images.indexOf(this.state.selectedImage as Model.Image);
const previous = current - 1 < 0 ? images.length - 1 : current - 1;
this._onImageSelected(images[previous]);
};
private _setGridHeight = (grid: number) => (height: number) => {
if (this.state.gridHeights[grid] === height) {
return;
}
this.setState((state) => {
const newGridHeights = [...state.gridHeights];
newGridHeights[grid] = height;
return { gridHeights: newGridHeights };
});
};
}

View File

@@ -1,7 +1,6 @@
import { Picture } from "./picture";
import * as Model from "../model";
import * as React from "react"; import * as React from "react";
import * as Model from "model";
import { Picture } from "components/picture";
export interface Props { export interface Props {
imageSet: Model.ImageSet; imageSet: Model.ImageSet;
@@ -9,40 +8,30 @@ export interface Props {
width: number; width: number;
} }
export interface State {} export const SetCover: React.FC<Props> = ({ imageSet, onClick, width }) => {
const coverImage = imageSet.images[0];
const isTall = coverImage.height > coverImage.width;
export class SetCover extends React.PureComponent<Props, State> { const height = isTall
static displayName = "SetCover"; ? width
: (coverImage.height / coverImage.width) * width;
render() { const normalizedWidth = isTall
const image = this.props.imageSet.images[0]; ? (coverImage.width / coverImage.height) * width
const isTall = image.height > image.width; : width;
const height = isTall return (
? this.props.width <div className="SetCover" onClick={onClick}>
: (image.height / image.width) * this.props.width; <Picture
image={coverImage}
const width = isTall onClick={() => {}}
? (image.width / image.height) * this.props.width height={height}
: this.props.width; width={normalizedWidth}
/>
return ( <h2>
<div className="SetCover" onClick={this.props.onClick}> <span className="SetCover-location">{imageSet.location}</span>
<Picture <span className="SetCover-description">{imageSet.description}</span>
image={image} </h2>
onClick={() => {}} </div>
height={height} );
width={width} };
/>
<h2>
<span className="SetCover-location">
{this.props.imageSet.location}
</span>
<span className="SetCover-description">
{this.props.imageSet.description}
</span>
</h2>
</div>
);
}
}

View File

@@ -1,4 +1,4 @@
import { Root } from "./components/root"; import { Root } from "components/root";
import { createRoot } from "react-dom/client"; import { createRoot } from "react-dom/client";

View File

@@ -1,7 +1,7 @@
{ {
"compilerOptions": { "compilerOptions": {
"outDir": "./dist/", "outDir": "./dist/",
"baseUrl": ".", "baseUrl": "./src",
"sourceMap": true, "sourceMap": true,
"noImplicitAny": true, "noImplicitAny": true,
"strictNullChecks": true, "strictNullChecks": true,

View File

@@ -26,7 +26,8 @@ module.exports = (env) => {
resolve: { resolve: {
// Add '.ts' and '.tsx' as resolvable extensions. // Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx", ".js", ".json"] extensions: [".ts", ".tsx", ".js", ".json"],
modules: [path.resolve(__dirname, "src"), "node_modules"],
}, },
module: { module: {