Files
5chan/src/stores/use-reply-modal-store.ts
T

93 lines
2.6 KiB
TypeScript
Raw Normal View History

2025-03-05 12:01:48 +01:00
import { create } from 'zustand';
import useSelectedTextStore from './use-selected-text-store';
interface ReplyModalState {
showReplyModal: boolean;
activeCid: string | null;
parentNumber: number | null;
2025-12-28 22:16:38 +01:00
threadNumber: number | null;
2025-03-05 12:01:48 +01:00
threadCid: string | null;
subplebbitAddress: string | null;
scrollY: number;
quoteInsertRequestId: number;
quoteInsertNumber: number | null;
quoteInsertSelectedText: string | null;
2025-03-05 12:01:48 +01:00
closeModal: () => void;
2025-12-28 22:16:38 +01:00
openReplyModal: (parentCid: string, parentNumber: number | undefined, postCid: string, threadNumber: number | undefined, subplebbitAddress: string) => void;
2025-03-05 12:01:48 +01:00
}
const getQuotedSelection = () => {
const text = document.getSelection()?.toString();
if (!text) return '';
// Keep each selected line as 5chan greentext and normalize newlines.
const normalizedText = text.replace(/\r\n/g, '\n').replace(/\n+$/g, '');
if (!normalizedText) return '';
return normalizedText
.split('\n')
.map((line) => `>${line}`)
.join('\n');
};
2025-03-05 12:01:48 +01:00
const useReplyModalStore = create<ReplyModalState>((set, get) => ({
showReplyModal: false,
activeCid: null,
parentNumber: null,
2025-12-28 22:16:38 +01:00
threadNumber: null,
2025-03-05 12:01:48 +01:00
threadCid: null,
subplebbitAddress: null,
scrollY: 0,
quoteInsertRequestId: 0,
quoteInsertNumber: null,
quoteInsertSelectedText: null,
2025-03-05 12:01:48 +01:00
closeModal: () => {
// Reset selected text if you're using that store
useSelectedTextStore.getState().resetSelectedText();
set({
showReplyModal: false,
activeCid: null,
parentNumber: null,
2025-12-28 22:16:38 +01:00
threadNumber: null,
quoteInsertNumber: null,
quoteInsertSelectedText: null,
2025-03-05 12:01:48 +01:00
});
},
2025-12-28 22:16:38 +01:00
openReplyModal: (parentCid, parentNumber, postCid, threadNumber, subplebbitAddress) => {
const quotedSelection = getQuotedSelection();
// If the reply modal is already open, insert this quote in the current textarea at caret.
if (get().showReplyModal) {
set((state) => ({
quoteInsertRequestId: state.quoteInsertRequestId + 1,
quoteInsertNumber: parentNumber ?? null,
quoteInsertSelectedText: quotedSelection || null,
}));
return;
}
if (quotedSelection) {
useSelectedTextStore.getState().setSelectedText(`${quotedSelection}\n`);
2025-03-05 12:01:48 +01:00
}
// Handle mobile scrollY
const isMobile = window.innerWidth <= 768; // Simple check, adjust as needed
const scrollY = isMobile ? window.scrollY : 0;
set({
activeCid: parentCid,
parentNumber: parentNumber ?? null,
2025-12-28 22:16:38 +01:00
threadNumber: threadNumber ?? null,
2025-03-05 12:01:48 +01:00
threadCid: postCid,
showReplyModal: true,
subplebbitAddress,
scrollY,
});
},
}));
export default useReplyModalStore;