From 3eaa56f0306ead818f64c3d99fc6d230d9b970a4 Mon Sep 17 00:00:00 2001 From: Max Nanis Date: Wed, 18 Feb 2026 20:42:03 -0500 Subject: HERE WE GO, HERE WE GO, HERE WE GO --- jb-ui/src/components/Footer.tsx | 36 ++ jb-ui/src/components/Leaderboard.tsx | 0 jb-ui/src/components/Profiling.tsx | 759 ++++++++++++++++++++++++++++++++ jb-ui/src/components/Wallet.tsx | 464 +++++++++++++++++++ jb-ui/src/components/ui/button.tsx | 64 +++ jb-ui/src/components/ui/checkbox.tsx | 30 ++ jb-ui/src/components/ui/confetti.tsx | 146 ++++++ jb-ui/src/components/ui/dot-pattern.tsx | 156 +++++++ jb-ui/src/components/ui/field.tsx | 246 +++++++++++ jb-ui/src/components/ui/label.tsx | 22 + jb-ui/src/components/ui/magic-card.tsx | 101 +++++ jb-ui/src/components/ui/pagination.tsx | 127 ++++++ jb-ui/src/components/ui/separator.tsx | 28 ++ jb-ui/src/components/ui/skeleton.tsx | 13 + 14 files changed, 2192 insertions(+) create mode 100644 jb-ui/src/components/Footer.tsx create mode 100644 jb-ui/src/components/Leaderboard.tsx create mode 100644 jb-ui/src/components/Profiling.tsx create mode 100644 jb-ui/src/components/Wallet.tsx create mode 100644 jb-ui/src/components/ui/button.tsx create mode 100644 jb-ui/src/components/ui/checkbox.tsx create mode 100644 jb-ui/src/components/ui/confetti.tsx create mode 100644 jb-ui/src/components/ui/dot-pattern.tsx create mode 100644 jb-ui/src/components/ui/field.tsx create mode 100644 jb-ui/src/components/ui/label.tsx create mode 100644 jb-ui/src/components/ui/magic-card.tsx create mode 100644 jb-ui/src/components/ui/pagination.tsx create mode 100644 jb-ui/src/components/ui/separator.tsx create mode 100644 jb-ui/src/components/ui/skeleton.tsx (limited to 'jb-ui/src/components') diff --git a/jb-ui/src/components/Footer.tsx b/jb-ui/src/components/Footer.tsx new file mode 100644 index 0000000..9248ea0 --- /dev/null +++ b/jb-ui/src/components/Footer.tsx @@ -0,0 +1,36 @@ +import { useAppSelector } from "@/hooks"; + +const Footer = () => { + const bpuid = useAppSelector(state => state.app.bpuid) + const assignment_id = useAppSelector(state => state.app.assignment_id) + + return ( +
+
+

help: + support@jamesbillings67.com + +

+
+ +
+

made with by Max Nanis +

+
+ +
+

open source

+
+ +
+ ) + +} + +export default Footer \ No newline at end of file diff --git a/jb-ui/src/components/Leaderboard.tsx b/jb-ui/src/components/Leaderboard.tsx new file mode 100644 index 0000000..e69de29 diff --git a/jb-ui/src/components/Profiling.tsx b/jb-ui/src/components/Profiling.tsx new file mode 100644 index 0000000..9cefdda --- /dev/null +++ b/jb-ui/src/components/Profiling.tsx @@ -0,0 +1,759 @@ +import { + UpkQuestionChoice +} from "@/api_fsb"; +import { + ChevronRightIcon +} from "lucide-react"; +import { KeyboardEvent, MouseEvent, useEffect, useRef, useState } from "react"; + +import { useAppDispatch, useAppSelector } from "@/hooks"; +import { bpid } from "@/lib/utils"; +import { + createColumnHelper, + flexRender, + getCoreRowModel, + getFilteredRowModel, + getSortedRowModel, + RowModel, + RowSelectionState, + useReactTable, +} from '@tanstack/react-table'; +import { clsx } from "clsx"; + +import { + Pagination, + PaginationContent, + PaginationItem, + PaginationLink +} from "@/components/ui/pagination"; + +import { + addAnswers, + fetchNewQuestions, + goToNextQuestion, + ProfileQuestion, + questionsSelectors, + saveAnswer, + selectActiveQuestion, + selectActiveQuestionValidation, + selectAllQuestions, + setActiveQuestion +} from "@/models/profilingQuestionsSlice"; +import { useSelector } from "react-redux"; +// import {motion} from "framer-motion" + +const TextEntry = () => { + const dispatch = useAppDispatch() + + const activeQuestion = useSelector(selectActiveQuestion); + // const selectAnswer = useMemo(() => selectAnswerForQuestion(question), [question]); + // const selectAnswer = useSelector(selectAnswerForQuestion(question)); + const metadata = activeQuestion?._metadata + const validation = activeQuestion?._validation + const bpuid = useAppSelector(state => state.app.bpuid) + + if (!metadata) return null + if (!validation) return null + + const error = validation?.errors.length > 0 + + const handleInputChange = (event: React.KeyboardEvent) => { + if (!activeQuestion.question_id) return; + + const target = event.target as HTMLInputElement; + dispatch(addAnswers({ questionId: activeQuestion.question_id!, answers: [target.value] as string[] })) + }; + + const handleKeyPress = (event: KeyboardEvent) => { + if (!activeQuestion.question_id) return; + if (!bpuid) return; + + if (event.key === 'Enter') { + dispatch(saveAnswer({ questionId: activeQuestion.question_id!, bpuid: bpuid })) + } + }; + + return ( +
+ + + { + validation.errors.map(e => { + return ( +

{e.message}

+ ) + }) + } +
+ ) +} + + +export default function useKeyboardMode( + rowModel: RowModel, +) { + // const [keyboardEnabled, setKeyboardEnabled] = useState( + // localStorage.getItem(keyboardMode) === "enabled", + // ); + const rowRefs = useRef<(HTMLTableRowElement | null)[]>([]); + + const dispatch = useAppDispatch() + const activeQuestion = useSelector(selectActiveQuestion); + const bpuid = useAppSelector(state => state.app.bpuid) + + const keyboardSelectionIdxRef = useRef(0); + + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + + if (!activeQuestion) return; + if (!bpuid) return; + + // if (!keyboardEnabled) { + // return; + // } + + const { key } = event; + const totalRows = rowRefs.current.length; + const prevIdx = keyboardSelectionIdxRef.current; + let nextIdx = prevIdx; + + if (key === "ArrowDown") nextIdx = Math.min(prevIdx + 1, totalRows - 1); + if (key === "ArrowUp") nextIdx = Math.max(prevIdx - 1, 0); + if (key === " ") { + const active = document.activeElement as HTMLElement | null; + + if (active?.tabIndex === 0) { + return; + } else { + rowModel.rows[keyboardSelectionIdxRef.current].toggleSelected(); + } + } + + if (event.key === 'Enter') { + dispatch(saveAnswer({ questionId: activeQuestion.question_id!, bpuid: bpuid })) + } + + + if (nextIdx !== prevIdx) { + + rowRefs.current[prevIdx]?.classList.remove("bg-blue-400"); + rowRefs.current[nextIdx]?.classList.add("bg-blue-400"); + + rowRefs.current[nextIdx]?.scrollIntoView({ + behavior: "smooth", + block: "center", + }); + keyboardSelectionIdxRef.current = nextIdx; + } + }; + + // I really don't know, and I don't really care enough to make this + // technically type'd correctly. - Max + + // @ts-ignore + window.addEventListener("keydown", handleKeyDown); + // @ts-ignore + return () => window.removeEventListener("keydown", handleKeyDown); + + }, [rowModel.rows]); + + return { + // keyboardEnabled, + // setKeyboardEnabled, + rowRefs, + keyboardSelectionIdxRef, + }; +} + +const MultipleChoice = () => { + const dispatch = useAppDispatch() + const activeQuestion = useSelector(selectActiveQuestion); + + // const error: Boolean = answer?.error_msg.length > 0 + // console.log("Rendering MultipleChoice with answer:", answer, error) + + // TODO! Retrieve store values to use as the initial state for the table + // This is useful for if they tab around before submitting the answer + const [rowSelection, setRowSelection] = useState({}); + const [globalFilter, setGlobalFilter] = useState(''); + + const handleRowSelectionChange = (updaterOrValue: RowSelectionState | ((old: RowSelectionState) => RowSelectionState)) => { + setRowSelection((oldSelection) => { + // Get the new selection state + const newSelection = typeof updaterOrValue === 'function' + ? updaterOrValue(oldSelection) + : updaterOrValue; + + // Find which row was just selected/deselected + const changedRowId = Object.keys(newSelection).find( + key => newSelection[key] !== oldSelection[key] + ); + + if (!changedRowId) return newSelection; + + // Get the actual row data + const row = table.getRow(changedRowId); + const rowData = row.original; // Your row data object + + // Check if "None of the Above" was selected + const normalized = rowData.choice_text.trim().toLowerCase(); + const isNoneOfTheAbove = (normalized === "none of the above") || (rowData.exclusive ?? false); + if (isNoneOfTheAbove && newSelection[changedRowId]) { + // Clear all other selections, keep only this one + return { [changedRowId]: true }; + } + + // Check if a regular option was selected while "None of the Above" exists + const noneOfTheAboveId = Object.keys(newSelection).find(id => { + const r = table.getRow(id); + const rowData = r.original as UpkQuestionChoice; + + const normalized = rowData.choice_text.trim().toLowerCase(); + const isNoneOfTheAbove = (normalized === "none of the above") || (rowData.exclusive ?? false); + + return isNoneOfTheAbove && newSelection[id]; + }); + + if (noneOfTheAboveId && changedRowId !== noneOfTheAboveId) { + // Remove "None of the Above" selection + const { [noneOfTheAboveId]: _, ...rest } = newSelection; + return rest; + } + + return newSelection; + }); + }; + + useEffect(() => { + if (!activeQuestion?.question_id) return; + // Run this anytime a rowSelection changes, to update + // the answer in the store + const selectedChoices = Object.keys(rowSelection) + dispatch(addAnswers({ questionId: activeQuestion.question_id, answers: selectedChoices })) + }, [rowSelection]) + + // Define columns + const columnHelper = createColumnHelper() + const columns = [ + columnHelper.display({ + id: 'select', + cell: ({ row }) => { + const canSelected = row.getCanSelect() + + return ( + + ) + }, + size: 20, + meta: { + align: 'center' + } + }), + + columnHelper.accessor("choice_text", { + header: () => 'Choice Text', + cell: (info) => { + const text = info.getValue(); + const selected = info.row.getIsSelected() + const canSelected = info.row.getCanSelect() + + return ( +

+ {text} +

+ ) + }, + size: 380, + meta: { + align: 'left' + } + }), + ] + + const table = useReactTable({ + 'data': activeQuestion!.choices ?? [], + columns, + getRowId: (row) => row.choice_id, + state: { + rowSelection, + globalFilter, + }, + // enableRowSelection: true, + enableRowSelection: (row) => { + // Allow deselection always, but limit new selections + const currentSelectionCount = Object.keys(rowSelection).length; + const isRowSelected = rowSelection[row.id]; + + const max_selection = activeQuestion?.selector === "SA" ? 1 : activeQuestion?.choices?.length ?? 10 + + // Allow if: row is already selected OR we haven't hit the limit + return isRowSelected || currentSelectionCount < max_selection; + }, + onRowSelectionChange: handleRowSelectionChange, + onGlobalFilterChange: setGlobalFilter, + getCoreRowModel: getCoreRowModel(), + getSortedRowModel: getSortedRowModel(), + getFilteredRowModel: getFilteredRowModel(), + }); + + const selectedCount = table.getSelectedRowModel().rows.length; + + //const { rowRefs, setKeyboardEnabled, keyboardSelectionIdxRef } = useKeyboardMode(table.getRowModel()); + const { rowRefs } = useKeyboardMode(table.getRowModel()); + + return ( + <> + + {/* Controls */} +
+
+ + {/* Search */} +
+ setGlobalFilter(e.target.value)} + className="w-full px-4 py-1 + border border-blue-900 bg-blue-400 rounded + text-white text-sm + focus:outline-none focus:ring-2 focus:ring-indigo-500" + /> +
+ + {/* Selected Count */} + {selectedCount > 0 && ( +
setRowSelection({})}> + {selectedCount} selected + +
+ )} + +
+
+ + {/* Table */} +
+ + + {table.getRowModel().rows.map((row, idx) => ( + { + rowRefs.current[idx] = el; + }} + onClick={() => row.toggleSelected()} + className={`cursor-pointer transition-colors w-full + ${row.getIsSelected() ? 'bg-blue-600 ' : ' ' + }`} + > + + {row.getVisibleCells().map((cell) => { + const align = cell.column.columnDef.meta?.align || 'left'; + const alignClass = align === 'center' ? 'text-center' : + align === 'right' ? 'text-right' : 'text-left'; + + return ( + + ) + })} + + + ))} + +
+ {flexRender(cell.column.columnDef.cell, cell.getContext())} +
+
+ + {/* Empty State */} + {table.getRowModel().rows.length === 0 && ( +
+ No items found matching your search +
+ )} + + {/* Footer */} +
+ + Showing {table.getRowModel().rows.length} of {activeQuestion?.choices?.length} choices + + {selectedCount > 0 && ( + + {selectedCount} choice{selectedCount !== 1 ? 's' : ''} selected + + )} +
+ + + ) + +} + +const ProfilingQuestionTitle = () => { + const activeQuestion = useSelector(selectActiveQuestion); + const question_active_tasks = activeQuestion?.importance?.task_count ?? 0 + + if (!activeQuestion) return null; + + let text = activeQuestion?.question_text + + if (activeQuestion.explanation_template && activeQuestion._validation?.isComplete && activeQuestion._metadata.answers.length == 1) { + const template = activeQuestion.explanation_template; + const pre_code = activeQuestion._metadata.answers[0]; + + const choice = activeQuestion.choices?.find(c => c.choice_id === pre_code) + const choice_text = choice ? choice.choice_text : "your answer" + + text = template.replace("{answer}", choice_text) + } + + + return ( +
+ +

+ {text} +

+ +
+

+ {question_active_tasks.toLocaleString()} +

+
+ Surveys use + this question +
+
+
+ ) +} + +const ProfilingQuestionSubmitButton = () => { + const dispatch = useAppDispatch() + + const activeQuestion = useSelector(selectActiveQuestion); + const activeQuestionValidation = useSelector(selectActiveQuestionValidation) + const bpuid = useAppSelector(state => state.app.bpuid) + + const handleOnClick = () => { + if (!activeQuestion) return + if (!activeQuestionValidation?.isComplete) return + if (!bpuid) return; + + dispatch(saveAnswer({ questionId: activeQuestion.question_id!, bpuid: bpuid })) + } + + return ( + + ) +} + + +export const ProfileQuestionFull = () => { + const activeQuestion = useSelector(selectActiveQuestion); + + const renderContent = () => { + if (!activeQuestion) return null; + switch (activeQuestion.question_type) { + case 'TE': + return + case 'MC': + return + default: + return + } + }; + + if (!activeQuestion) return null + + return ( + <> + {/* {answer && answer.processing && ( + setLoading(false)} + /> + )} */} + + {renderContent()} + + ) +} + +const PaginationIcon: React.FC<{ + question: ProfileQuestion, idx: number, +}> = ({ question, idx }) => { + const dispatch = useAppDispatch() + + // const answers = useAppSelector(state => state.answers) + const isActive = question._metadata?.isActive ?? false + const completed = question._validation?.isComplete ?? false + + const handleSetQuestion = (evt: MouseEvent) => { + if (completed) { + evt.preventDefault() + } else { + dispatch(setActiveQuestion(question.question_id!)) + } + } + + return ( + + + {idx + 1} + + + ) +} + +const ProfilingQuestionPagination = () => { + const dispatch = useAppDispatch() + + const questions = useSelector(selectAllQuestions) + const activeQuestion = useSelector(selectActiveQuestion) + + // All the variables needed for a sliding window + const q_idx = questions.findIndex(q => q.question_id === activeQuestion!.question_id) + + const handleNextClick = () => { + dispatch(goToNextQuestion()); + }; + + const questionsWindow = ( + items: ProfileQuestion[], currentIndex: number, windowSize: number = 5 + ): ProfileQuestion[] => { + const half: number = Math.floor(windowSize / 2) + const total: number = items.length + let start: number = currentIndex - half + let end: number = currentIndex + half + 1 + + if (start < 0) { + end += Math.abs(start) + start = 0 + } + + // Adjust if window goes past the end + if (end > total) { + const overflow: number = end - total + start = Math.max(0, start - overflow) + end = total + } + + return items.slice(start, end) + } + + return ( + + + { + questionsWindow(questions, q_idx).map(q => { + return qq.question_id === q.question_id)} + /> + }) + } + + + + Next + + + + + + + ) +} + +const ProfilingHeader = () => { + const questions = useSelector(questionsSelectors.selectAll); + + return ( +

+ {questions.length} Profiling Questions +

+ ) +} + +const ProfilingModalBody = () => { + const activeQuestion = useSelector(selectActiveQuestion); + + if (!activeQuestion) { + return ( +
+

No Profiling Questions Available

+

Please check back later.

+
+ ) + } + + return ( +
+ {/* */} + +
+ +
+ + {/* Scrollable Content */} +
+ +
+ + {/* Sticky Footer */} +
+
+ +
+
+ +
+
+ +
+ ) +} + +const Profiling = () => { + /* This is the main UI for any User Profiling (before entering a task). It's + primary window and position should be dedictated by it's parent so this + can be positioned as a window or a sidebar as needed. + */ + const [showProfiling, setShowProfiling] = useState(false); + + const dispatch = useAppDispatch() + const bpuid = useAppSelector(state => state.app.bpuid) + + useEffect(() => { + if (!bpuid) return; + dispatch(fetchNewQuestions(bpuid)); + }, [bpid, bpuid]) + + if (!bpuid) return null; + + return ( +
+ +
setShowProfiling(!showProfiling)} + > + + +

+ (Click to {showProfiling ? 'hide' : 'show'}) +

+
+ + {showProfiling && ( + + )} + +
+ ) +} + +export { + Profiling +}; diff --git a/jb-ui/src/components/Wallet.tsx b/jb-ui/src/components/Wallet.tsx new file mode 100644 index 0000000..e4fc694 --- /dev/null +++ b/jb-ui/src/components/Wallet.tsx @@ -0,0 +1,464 @@ +import { + UserLedgerTransactionsResponse, + UserLedgerTransactionsResponseTransactionsInner, + WalletApi +} from "@/api_fsb"; +import { useAppDispatch, useAppSelector } from "@/hooks"; +import { bpid, formatCentsToUSD, } from "@/lib/utils"; +import { + setTxPagination, setTxTotalItems, setTxTotalPages, + setUserLedgerSummary, + setUserLedgerTxs +} from "@/models/appSlice"; +import { + RowData, createColumnHelper, flexRender, getCoreRowModel, + useReactTable +} from "@tanstack/react-table"; +import moment from "moment"; +import { useEffect, useState } from "react"; + +declare module '@tanstack/react-table' { + interface ColumnMeta { + align?: 'left' | 'center' | 'right'; + } +} + +// Function to calculate background color based on balance +const getBackgroundColor = (balance: number | undefined): string => { + if (balance === undefined || balance === null) return 'bg-blue-600'; + + if (balance > 0) { + return 'bg-blue-600'; + } else if (balance <= -100) { + return 'bg-red-600'; + } else { + // Interpolate between blue and red for values between 0 and -100 + // progress goes from 0 (at balance = 0) to 1 (at balance = -100) + const progress = Math.abs(balance) / 100; + + // Blue RGB: (37, 99, 235) - Tailwind blue-600 + // Red RGB: (220, 38, 38) - Tailwind red-600 + const r = Math.round(37 + (220 - 37) * progress); + const g = Math.round(99 + (38 - 99) * progress); + const b = Math.round(235 + (38 - 235) * progress); + + return `rgb(${r}, ${g}, ${b})`; + } +}; + + +const WalletHeader = () => { + const amount = useAppSelector(state => state.app.userWalletBalance)?.amount ?? 0 + + const bgStyle = typeof getBackgroundColor(amount) === 'string' && + getBackgroundColor(amount).startsWith('bg-') + ? {} + : { backgroundColor: getBackgroundColor(amount) }; + + const bgClass = typeof getBackgroundColor(amount) === 'string' && + getBackgroundColor(amount).startsWith('bg-') + ? getBackgroundColor(amount) + : ''; + + return ( +
+

+ User Wallet: + + {amount >= 0 ? ( + + {`${formatCentsToUSD(Math.abs(amount))}`} + + ) : ( + + {`(${formatCentsToUSD(Math.abs(amount))})`} + + )} + +

+
+ ) +}; + +const WalletSummary = () => { + const summary = useAppSelector(state => state.app.userLedgerSummary) + + const survey_completes = summary?.bp_payment?.entry_count ?? 0 + const survey_completes_f = (survey_completes ?? 0).toLocaleString('en-US') + + const survey_adjustments = summary?.bp_adjustment?.entry_count ?? 0 + const survey_adjustments_f = (survey_adjustments ?? 0).toLocaleString('en-US') + + const min_payout: number = summary?.bp_payment?.min_amount ?? 0 + const max_payout: number = summary?.bp_payment?.max_amount ?? 0 + const adj_total: number = summary?.bp_adjustment?.total_amount ?? 0 + const user_payments_total: number = (summary?.user_payout_request?.total_amount ?? 0) * -1 + + return ( +
+
Completes:
+
{survey_completes_f} surveys
+ +
Avg Payouts:
+
{formatCentsToUSD(min_payout)} – {formatCentsToUSD(max_payout)}
+ +
Survey Adjustments:
+
{survey_adjustments_f}
+ +
Adjustment Amount:
+
+ {adj_total >= 0 ? ( + + {`${formatCentsToUSD(adj_total)}`} + + ) : ( + + {`(${formatCentsToUSD(Math.abs(adj_total))})`} + + )} +
+ +
User Payments:
+
+ {user_payments_total >= 0 ? ( + + {`${formatCentsToUSD(user_payments_total)}`} + + ) : ( + + {`(${formatCentsToUSD(Math.abs(user_payments_total))})`} + + )} + +
+
+ ) +}; + +const WalletTransactionsHeader = () => { + const tx_cnt = useAppSelector(state => state.app.txTotalItems) + const txt_cnt_f = (tx_cnt ?? 0).toLocaleString('en-US') + + const [showTx, setShowTx] = useState(false); + + return ( +
+
setShowTx(!showTx)}> + +

setShowTx(!showTx)} + > + Total Transactions: {txt_cnt_f} +

+ +

setShowTx(!showTx)} + > + (Click to {showTx ? 'hide' : 'show'}) +

+ +
+ + {showTx && ( + <> + + + )} + +
+ ) +}; + + +const WalletTransactions = () => { + const dispatch = useAppDispatch() + const bpuid = useAppSelector(state => state.app.bpuid) + const userLedgerTxs = useAppSelector(state => state.app.userLedgerTxs); + + const txPagination = useAppSelector(state => state.app.txPagination); + const txTotalPages = useAppSelector(state => state.app.txTotalPages); + + useEffect(() => { + if (!bpuid) return; + + new WalletApi().getUserTransactionHistoryProductIdTransactionHistoryGet( + bpid, // productId + bpuid, // bpuid + undefined, // createdAfter + undefined, // createdBefore + "-created", // orderBy + txPagination.pageIndex + 1, // page + txPagination.pageSize // pageSize + ).then(res => { + const response = res.data as UserLedgerTransactionsResponse; + console.log("Wallet: fetched user ledger", response); + dispatch(setUserLedgerSummary(response.summary)); + + dispatch(setUserLedgerTxs(response.transactions ?? [])) + dispatch(setTxTotalItems(response.total!)) + dispatch(setTxTotalPages(response.pages!)) + }); + + }, [bpuid, txPagination.pageIndex, txPagination.pageSize]); + + const columnHelper = createColumnHelper() + const columns = [ + columnHelper.accessor('created', { + header: () => 'Date', + cell: (info) => moment(info.getValue()).format('M/D/YY H:mm'), + size: 110, + meta: { + align: 'left' + } + }), + columnHelper.accessor('description', { + header: () => 'Type', + cell: props => { + const desc = props.getValue(); + switch (desc) { + case 'Task Complete': + return 'Survey 🎉'; + case 'Task Adjustment': + return 'Reject ⚠️'; + case 'Compensation Bonus': + return 'Bonus 🎁'; + case 'HIT Bonus': + return 'Bonus'; + case 'HIT Reward': + return 'Assignment'; + default: + return desc; + } + }, + size: 80, + meta: { + align: 'left' + } + }), + columnHelper.accessor('amount', { + header: () => 'Amount', + cell: (props) => { + const val = props.renderValue() as number; + const isPositive = val >= 0; + const emoji = isPositive ? "⬆\uFE0E" : "⬇\uFE0E"; + const colorClass = isPositive ? 'font-variant-emoji-text text-emerald-300' : 'font-variant-emoji-text text-rose-300'; + + return ( + + {`${emoji} ${formatCentsToUSD(Math.abs(val))}`} + + ) + }, + size: 70, + meta: { + align: 'center' + } + }), + columnHelper.accessor('balance_after', { + header: () => 'Balance', + cell: (props) => { + const val = props.renderValue() as number; + const isPositive = val >= 0; + const colorClass = isPositive ? 'text-emerald-300' : 'text-rose-300'; + + return ( + <> + {isPositive ? ( + + {`${formatCentsToUSD(Math.abs(val))}`} + + ) : ( + + {`(${formatCentsToUSD(Math.abs(val))})`} + + )} + + ) + }, + size: 70, + meta: { + align: 'center' + } + }), + ] + + const table = useReactTable({ + 'data': userLedgerTxs, + 'columns': columns, + getCoreRowModel: getCoreRowModel(), + manualPagination: true, + pageCount: txTotalPages, + onPaginationChange: (updater) => { + dispatch(setTxPagination( + typeof updater === 'function' ? updater(txPagination) : updater + )); + }, + state: { + pagination: txPagination, + }, + }); + + return ( +
+ + + {table.getHeaderGroups().map((headerGroup) => ( + + + {headerGroup.headers.map((header) => { + const align = header.column.columnDef.meta?.align || 'left'; + const alignClass = align === 'center' ? 'text-center' : align === 'right' ? 'text-right' : 'text-left'; + + return ( + + ) + })} + + ))} + + + {table.getRowModel().rows.map((row) => ( + + {row.getVisibleCells().map((cell) => { + const align = cell.column.columnDef.meta?.align || 'left'; + const alignClass = align === 'center' ? 'text-center' : + align === 'right' ? 'text-right' : 'text-left'; + + return ( + + ) + })} + + ))} + + + + + + + + +
+ {flexRender( + header.column.columnDef.header, + header.getContext(), + )} +
+ {flexRender(cell.column.columnDef.cell, cell.getContext())} +
+
+ + {/* Page info */} +
+ Page {table.getState().pagination.pageIndex + 1} of{' '} + {table.getPageCount()} +
+ + {/* Navigation buttons */} +
+ + +
+ + {/* Page size selector */} + +
+
+
+ ) +}; + + +const Wallet = () => { + const dispatch = useAppDispatch() + const bpuid = useAppSelector(state => state.app.bpuid) + const pagination = useAppSelector(state => state.app.txPagination); + + useEffect(() => { + if (!bpuid) return; + + new WalletApi().getUserTransactionHistoryProductIdTransactionHistoryGet( + bpid, // productId + bpuid, // bpuid + undefined, // createdAfter + undefined, // createdBefore + "-created", // orderBy + pagination.pageIndex + 1, // page + pagination.pageSize // pageSize + ).then(res => { + const response = res.data as UserLedgerTransactionsResponse; + dispatch(setUserLedgerSummary(response.summary)); + dispatch(setUserLedgerTxs(response.transactions ?? [])) + + dispatch(setTxPagination({ + pageIndex: (response.page ?? 1) - 1, + pageSize: response.size ?? 10, + })) + dispatch(setTxTotalItems(response.total ?? 0)) + dispatch(setTxTotalPages(response.pages ?? 9)) + }); + + }, [bpuid]) + + if (!bpuid) return null; + + return ( +
+ + + +
+ ) +}; + + +export default Wallet; \ No newline at end of file diff --git a/jb-ui/src/components/ui/button.tsx b/jb-ui/src/components/ui/button.tsx new file mode 100644 index 0000000..b5ea4ab --- /dev/null +++ b/jb-ui/src/components/ui/button.tsx @@ -0,0 +1,64 @@ +import * as React from "react" +import { cva, type VariantProps } from "class-variance-authority" +import { Slot } from "radix-ui" + +import { cn } from "@/lib/utils" + +const buttonVariants = cva( + "inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-all disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4 shrink-0 [&_svg]:shrink-0 outline-none focus-visible:border-ring focus-visible:ring-ring/50 focus-visible:ring-[3px] aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive", + { + variants: { + variant: { + default: "bg-primary text-primary-foreground hover:bg-primary/90", + destructive: + "bg-destructive text-white hover:bg-destructive/90 focus-visible:ring-destructive/20 dark:focus-visible:ring-destructive/40 dark:bg-destructive/60", + outline: + "border bg-background shadow-xs hover:bg-accent hover:text-accent-foreground dark:bg-input/30 dark:border-input dark:hover:bg-input/50", + secondary: + "bg-secondary text-secondary-foreground hover:bg-secondary/80", + ghost: + "hover:bg-accent hover:text-accent-foreground dark:hover:bg-accent/50", + link: "text-primary underline-offset-4 hover:underline", + }, + size: { + default: "h-9 px-4 py-2 has-[>svg]:px-3", + xs: "h-6 gap-1 rounded-md px-2 text-xs has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3", + sm: "h-8 rounded-md gap-1.5 px-3 has-[>svg]:px-2.5", + lg: "h-10 rounded-md px-6 has-[>svg]:px-4", + icon: "size-9", + "icon-xs": "size-6 rounded-md [&_svg:not([class*='size-'])]:size-3", + "icon-sm": "size-8", + "icon-lg": "size-10", + }, + }, + defaultVariants: { + variant: "default", + size: "default", + }, + } +) + +function Button({ + className, + variant = "default", + size = "default", + asChild = false, + ...props +}: React.ComponentProps<"button"> & + VariantProps & { + asChild?: boolean + }) { + const Comp = asChild ? Slot.Root : "button" + + return ( + + ) +} + +export { Button, buttonVariants } diff --git a/jb-ui/src/components/ui/checkbox.tsx b/jb-ui/src/components/ui/checkbox.tsx new file mode 100644 index 0000000..0e2a6cd --- /dev/null +++ b/jb-ui/src/components/ui/checkbox.tsx @@ -0,0 +1,30 @@ +import * as React from "react" +import * as CheckboxPrimitive from "@radix-ui/react-checkbox" +import { CheckIcon } from "lucide-react" + +import { cn } from "@/lib/utils" + +function Checkbox({ + className, + ...props +}: React.ComponentProps) { + return ( + + + + + + ) +} + +export { Checkbox } diff --git a/jb-ui/src/components/ui/confetti.tsx b/jb-ui/src/components/ui/confetti.tsx new file mode 100644 index 0000000..e0d353a --- /dev/null +++ b/jb-ui/src/components/ui/confetti.tsx @@ -0,0 +1,146 @@ +import type { ReactNode } from "react" +import React, { + createContext, + forwardRef, + useCallback, + useEffect, + useImperativeHandle, + useMemo, + useRef, +} from "react" +import type { + GlobalOptions as ConfettiGlobalOptions, + CreateTypes as ConfettiInstance, + Options as ConfettiOptions, +} from "canvas-confetti" +import confetti from "canvas-confetti" + +import { Button } from "@/components/ui/button" + +type Api = { + fire: (options?: ConfettiOptions) => void +} + +type Props = React.ComponentPropsWithRef<"canvas"> & { + options?: ConfettiOptions + globalOptions?: ConfettiGlobalOptions + manualstart?: boolean + children?: ReactNode +} + +export type ConfettiRef = Api | null + +const ConfettiContext = createContext({} as Api) + +// Define component first +const ConfettiComponent = forwardRef((props, ref) => { + const { + options, + globalOptions = { resize: true, useWorker: true }, + manualstart = false, + children, + ...rest + } = props + const instanceRef = useRef(null) + + const canvasRef = useCallback( + (node: HTMLCanvasElement) => { + if (node !== null) { + if (instanceRef.current) return + instanceRef.current = confetti.create(node, { + ...globalOptions, + resize: true, + }) + } else { + if (instanceRef.current) { + instanceRef.current.reset() + instanceRef.current = null + } + } + }, + [globalOptions] + ) + + const fire = useCallback( + async (opts = {}) => { + try { + await instanceRef.current?.({ ...options, ...opts }) + } catch (error) { + console.error("Confetti error:", error) + } + }, + [options] + ) + + const api = useMemo( + () => ({ + fire, + }), + [fire] + ) + + useImperativeHandle(ref, () => api, [api]) + + useEffect(() => { + if (!manualstart) { + ;(async () => { + try { + await fire() + } catch (error) { + console.error("Confetti effect error:", error) + } + })() + } + }, [manualstart, fire]) + + return ( + + + {children} + + ) +}) + +// Set display name immediately +ConfettiComponent.displayName = "Confetti" + +// Export as Confetti +export const Confetti = ConfettiComponent + +interface ConfettiButtonProps extends React.ComponentProps<"button"> { + options?: ConfettiOptions & + ConfettiGlobalOptions & { canvas?: HTMLCanvasElement } +} + +const ConfettiButtonComponent = ({ + options, + children, + ...props +}: ConfettiButtonProps) => { + const handleClick = async (event: React.MouseEvent) => { + try { + const rect = event.currentTarget.getBoundingClientRect() + const x = rect.left + rect.width / 2 + const y = rect.top + rect.height / 2 + await confetti({ + ...options, + origin: { + x: x / window.innerWidth, + y: y / window.innerHeight, + }, + }) + } catch (error) { + console.error("Confetti button error:", error) + } + } + + return ( + + ) +} + +ConfettiButtonComponent.displayName = "ConfettiButton" + +export const ConfettiButton = ConfettiButtonComponent diff --git a/jb-ui/src/components/ui/dot-pattern.tsx b/jb-ui/src/components/ui/dot-pattern.tsx new file mode 100644 index 0000000..9522b7f --- /dev/null +++ b/jb-ui/src/components/ui/dot-pattern.tsx @@ -0,0 +1,156 @@ +import React, { useEffect, useId, useRef, useState } from "react" +import { motion } from "motion/react" + +import { cn } from "@/lib/utils" + +/** + * DotPattern Component Props + * + * @param {number} [width=16] - The horizontal spacing between dots + * @param {number} [height=16] - The vertical spacing between dots + * @param {number} [x=0] - The x-offset of the entire pattern + * @param {number} [y=0] - The y-offset of the entire pattern + * @param {number} [cx=1] - The x-offset of individual dots + * @param {number} [cy=1] - The y-offset of individual dots + * @param {number} [cr=1] - The radius of each dot + * @param {string} [className] - Additional CSS classes to apply to the SVG container + * @param {boolean} [glow=false] - Whether dots should have a glowing animation effect + */ +interface DotPatternProps extends React.SVGProps { + width?: number + height?: number + x?: number + y?: number + cx?: number + cy?: number + cr?: number + className?: string + glow?: boolean + [key: string]: unknown +} + +/** + * DotPattern Component + * + * A React component that creates an animated or static dot pattern background using SVG. + * The pattern automatically adjusts to fill its container and can optionally display glowing dots. + * + * @component + * + * @see DotPatternProps for the props interface. + * + * @example + * // Basic usage + * + * + * // With glowing effect and custom spacing + * + * + * @notes + * - The component is client-side only ("use client") + * - Automatically responds to container size changes + * - When glow is enabled, dots will animate with random delays and durations + * - Uses Motion for animations + * - Dots color can be controlled via the text color utility classes + */ + +export function DotPattern({ + width = 16, + height = 16, + x = 0, + y = 0, + cx = 1, + cy = 1, + cr = 1, + className, + glow = false, + ...props +}: DotPatternProps) { + const id = useId() + const containerRef = useRef(null) + const [dimensions, setDimensions] = useState({ width: 0, height: 0 }) + + useEffect(() => { + const updateDimensions = () => { + if (containerRef.current) { + const { width, height } = containerRef.current.getBoundingClientRect() + setDimensions({ width, height }) + } + } + + updateDimensions() + window.addEventListener("resize", updateDimensions) + return () => window.removeEventListener("resize", updateDimensions) + }, []) + + const dots = Array.from( + { + length: + Math.ceil(dimensions.width / width) * + Math.ceil(dimensions.height / height), + }, + (_, i) => { + const col = i % Math.ceil(dimensions.width / width) + const row = Math.floor(i / Math.ceil(dimensions.width / width)) + return { + x: col * width + cx, + y: row * height + cy, + delay: Math.random() * 5, + duration: Math.random() * 3 + 2, + } + } + ) + + return ( + + ) +} diff --git a/jb-ui/src/components/ui/field.tsx b/jb-ui/src/components/ui/field.tsx new file mode 100644 index 0000000..db0dc12 --- /dev/null +++ b/jb-ui/src/components/ui/field.tsx @@ -0,0 +1,246 @@ +import { useMemo } from "react" +import { cva, type VariantProps } from "class-variance-authority" + +import { cn } from "@/lib/utils" +import { Label } from "@/components/ui/label" +import { Separator } from "@/components/ui/separator" + +function FieldSet({ className, ...props }: React.ComponentProps<"fieldset">) { + return ( +
[data-slot=checkbox-group]]:gap-3 has-[>[data-slot=radio-group]]:gap-3", + className + )} + {...props} + /> + ) +} + +function FieldLegend({ + className, + variant = "legend", + ...props +}: React.ComponentProps<"legend"> & { variant?: "legend" | "label" }) { + return ( + + ) +} + +function FieldGroup({ className, ...props }: React.ComponentProps<"div">) { + return ( +
[data-slot=field-group]]:gap-4", + className + )} + {...props} + /> + ) +} + +const fieldVariants = cva( + "group/field flex w-full gap-3 data-[invalid=true]:text-destructive", + { + variants: { + orientation: { + vertical: ["flex-col [&>*]:w-full [&>.sr-only]:w-auto"], + horizontal: [ + "flex-row items-center", + "[&>[data-slot=field-label]]:flex-auto", + "has-[>[data-slot=field-content]]:items-start has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px", + ], + responsive: [ + "flex-col [&>*]:w-full [&>.sr-only]:w-auto @md/field-group:flex-row @md/field-group:items-center @md/field-group:[&>*]:w-auto", + "@md/field-group:[&>[data-slot=field-label]]:flex-auto", + "@md/field-group:has-[>[data-slot=field-content]]:items-start @md/field-group:has-[>[data-slot=field-content]]:[&>[role=checkbox],[role=radio]]:mt-px", + ], + }, + }, + defaultVariants: { + orientation: "vertical", + }, + } +) + +function Field({ + className, + orientation = "vertical", + ...props +}: React.ComponentProps<"div"> & VariantProps) { + return ( +
+ ) +} + +function FieldContent({ className, ...props }: React.ComponentProps<"div">) { + return ( +
+ ) +} + +function FieldLabel({ + className, + ...props +}: React.ComponentProps) { + return ( +