From dc4db40232e6f4a8708c6043756ce90ffc248645 Mon Sep 17 00:00:00 2001 From: en Date: Fri, 14 Feb 2025 14:04:32 +0100 Subject: [PATCH] fix(notes): text limit calculation update Fix #226 --- src/hooks/useTextLimit.tsx | 45 +++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/src/hooks/useTextLimit.tsx b/src/hooks/useTextLimit.tsx index 0f5c0da..e6b304b 100644 --- a/src/hooks/useTextLimit.tsx +++ b/src/hooks/useTextLimit.tsx @@ -1,17 +1,52 @@ import { MAX_VISIBLE_TEXT_PER_COMMENT } from '../constants' import { useState } from 'react' +interface UseTextLimitResult { + text: string + isTextOverflowing: boolean + isExpanded: boolean + toggle: () => void +} + export const useTextLimit = ( text: string, limit: number = MAX_VISIBLE_TEXT_PER_COMMENT -) => { +): UseTextLimitResult => { const [isExpanded, setIsExpanded] = useState(false) - const isTextOverflowing = text.length > limit - const updated = - isExpanded || !isTextOverflowing ? text : text.slice(0, limit) + '…' + + const getFilteredTextAndIndices = (): { + filteredText: string + indices: number[] + } => { + const words = text.split(' ') + const filteredWords: string[] = [] + const indices: number[] = [] + let currentIndex = 0 + + words.forEach((word) => { + if (!word.startsWith('nostr:')) { + filteredWords.push(word) + indices.push(currentIndex) + } + currentIndex += word.length + 1 + }) + + return { filteredText: filteredWords.join(' '), indices } + } + + const { filteredText, indices } = getFilteredTextAndIndices() + const isTextOverflowing = filteredText.length > limit + + const getUpdatedText = (): string => { + if (isExpanded || !isTextOverflowing) { + return text + } + const sliceEndIndex = indices.find((index) => index >= limit) || limit + return text.slice(0, sliceEndIndex) + '…' + } return { - text: updated, + text: getUpdatedText(), isTextOverflowing, isExpanded, toggle: () => setIsExpanded((prev) => !prev)