import React, { useState, useEffect, useCallback } from 'react'; import { Link, useParams } from 'react-router-dom'; import { HashLink } from 'react-router-hash-link'; import { Helmet } from 'react-helmet'; import moment from 'moment'; import localForage from 'localforage'; import { infoLine, ToggleDot } from './utils.js'; function countComments(c) { return c.comments.reduce((sum, x) => sum + countComments(x), 1); } function Comments({ cache }) { const { id } = useParams(); if (id in cache) console.log('cache hit'); const [story, setStory] = useState(cache[id] || false); const [error, setError] = useState(false); const [collapsed, setCollapsed] = useState([]); const [expanded, setExpanded] = useState([]); useEffect(() => { localForage.getItem(id) .then( (value) => { if (value) { setStory(value); } } ); fetch('/api/' + id) .then(res => res.json()) .then( (result) => { setStory(result.story); localForage.setItem(id, result.story); const hash = window.location.hash.substring(1); if (hash) { setTimeout(() => { const element = document.getElementById(hash); if (element) { element.scrollIntoView(); } }, 0); } }, (error) => { setError(true); } ); }, [id]); const collapseComment = useCallback((cid) => { setCollapsed(prev => [...prev, cid]); setExpanded(prev => prev.filter(x => x !== cid)); }, []); const expandComment = useCallback((cid) => { setCollapsed(prev => prev.filter(x => x !== cid)); setExpanded(prev => [...prev, cid]); }, []); const displayComment = useCallback((story, c, level) => { const cid = c.author+c.date; const isCollapsed = collapsed.includes(cid); const isExpanded = expanded.includes(cid); const hidden = isCollapsed || (level == 4 && !isExpanded); const hasChildren = c.comments.length !== 0; return (
{c.author === story.author ? '[OP]' : ''} {c.author || '[Deleted]'}
{' '} |
Connection error?
} {story ?loading...
}