initial commit
This commit is contained in:
157
app/components/LocaleSelector.tsx
Normal file
157
app/components/LocaleSelector.tsx
Normal file
@@ -0,0 +1,157 @@
|
||||
import { useEffect, useMemo, useRef, useState } from "react";
|
||||
import type { KeyboardEvent } from "react";
|
||||
import type { Locale, LocaleOption } from "@/hooks/useI18n";
|
||||
|
||||
type Props = {
|
||||
locale: Locale;
|
||||
onChange: (code: Locale) => void;
|
||||
options: LocaleOption[];
|
||||
label: string;
|
||||
searchPlaceholder: string;
|
||||
};
|
||||
|
||||
export function LocaleSelector({ locale, onChange, options, label, searchPlaceholder }: Props) {
|
||||
const dropdownRef = useRef<HTMLDivElement | null>(null);
|
||||
const searchRef = useRef<HTMLInputElement | null>(null);
|
||||
const [open, setOpen] = useState(false);
|
||||
const [search, setSearch] = useState("");
|
||||
const [focusedIndex, setFocusedIndex] = useState(-1);
|
||||
|
||||
const selected = useMemo(
|
||||
() => options.find((opt) => opt.code === locale) || options[0],
|
||||
[locale, options]
|
||||
);
|
||||
|
||||
const filtered = useMemo(() => {
|
||||
const term = search.trim().toLowerCase();
|
||||
return term ? options.filter((opt) => opt.name.toLowerCase().includes(term)) : options;
|
||||
}, [options, search]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
const clickHandler = (e: MouseEvent) => {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(e.target as Node)) {
|
||||
setOpen(false);
|
||||
setSearch("");
|
||||
setFocusedIndex(-1);
|
||||
}
|
||||
};
|
||||
document.addEventListener("click", clickHandler);
|
||||
setTimeout(() => searchRef.current?.focus(), 0);
|
||||
return () => document.removeEventListener("click", clickHandler);
|
||||
}, [open]);
|
||||
|
||||
const toggle = () => setOpen((prev) => !prev);
|
||||
const close = () => {
|
||||
setOpen(false);
|
||||
setSearch("");
|
||||
setFocusedIndex(-1);
|
||||
};
|
||||
|
||||
const select = (opt: LocaleOption) => {
|
||||
onChange(opt.code);
|
||||
close();
|
||||
};
|
||||
|
||||
const onKeyDownList = (e: KeyboardEvent<HTMLUListElement>) => {
|
||||
if (!open) return;
|
||||
const list = filtered;
|
||||
if (!list.length) return;
|
||||
if (e.key === "ArrowDown") {
|
||||
e.preventDefault();
|
||||
setFocusedIndex((prev) => {
|
||||
const next = (prev + 1) % list.length;
|
||||
scrollIntoView(next);
|
||||
return next;
|
||||
});
|
||||
} else if (e.key === "ArrowUp") {
|
||||
e.preventDefault();
|
||||
setFocusedIndex((prev) => {
|
||||
const next = (prev - 1 + list.length) % list.length;
|
||||
scrollIntoView(next);
|
||||
return next;
|
||||
});
|
||||
} else if (e.key === "Enter" && focusedIndex >= 0) {
|
||||
e.preventDefault();
|
||||
select(list[focusedIndex]);
|
||||
} else if (e.key === "Escape") {
|
||||
e.preventDefault();
|
||||
close();
|
||||
}
|
||||
};
|
||||
|
||||
const scrollIntoView = (index: number) => {
|
||||
requestAnimationFrame(() => {
|
||||
const items = dropdownRef.current?.querySelectorAll(".locale-panel-item");
|
||||
const el = items?.[index] as HTMLElement | undefined;
|
||||
el?.scrollIntoView({ block: "nearest" });
|
||||
});
|
||||
};
|
||||
|
||||
const handleItemKeyDown = (e: KeyboardEvent<HTMLLIElement>, opt: LocaleOption) => {
|
||||
if (e.key === "Enter" || e.key === " ") {
|
||||
e.preventDefault();
|
||||
select(opt);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div ref={dropdownRef} className="locale-dropdown" tabIndex={-1} role="group">
|
||||
<p className="locale-label">{label}</p>
|
||||
<button
|
||||
type="button"
|
||||
className="locale-toggle"
|
||||
aria-expanded={open}
|
||||
aria-haspopup="menu"
|
||||
onClick={toggle}
|
||||
>
|
||||
<span className="locale-flag" aria-hidden>
|
||||
{selected?.emoji}
|
||||
</span>
|
||||
<span className="locale-name">{selected?.name}</span>
|
||||
<svg
|
||||
className={`locale-arrow ${open ? "open" : ""}`}
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
|
||||
</svg>
|
||||
</button>
|
||||
|
||||
{open && (
|
||||
<div className="locale-panel" role="menu" tabIndex={-1}>
|
||||
<div className="locale-panel-search">
|
||||
<input
|
||||
ref={searchRef}
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
type="text"
|
||||
placeholder={searchPlaceholder}
|
||||
/>
|
||||
</div>
|
||||
<ul className="locale-panel-list" role="menu" tabIndex={0} onKeyDown={onKeyDownList}>
|
||||
{filtered.map((opt, index) => (
|
||||
<li
|
||||
key={opt.code}
|
||||
className={`locale-panel-item ${index === focusedIndex ? "focused" : ""}`}
|
||||
role="menuitem"
|
||||
tabIndex={0}
|
||||
onClick={() => select(opt)}
|
||||
onKeyDown={(e) => handleItemKeyDown(e, opt)}
|
||||
onMouseEnter={() => setFocusedIndex(index)}
|
||||
>
|
||||
<span className="locale-item-flag" aria-hidden>
|
||||
{opt.emoji}
|
||||
</span>
|
||||
<span className="locale-item-label">{opt.name}</span>
|
||||
</li>
|
||||
))}
|
||||
{filtered.length === 0 && <li className="locale-no-results">No languages found.</li>}
|
||||
</ul>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
617
app/globals.css
Normal file
617
app/globals.css
Normal file
@@ -0,0 +1,617 @@
|
||||
@import url("https://fonts.googleapis.com/css2?family=Sora:wght@400;500;600;700&display=swap");
|
||||
|
||||
:root {
|
||||
--bg-1: #f1f6ff;
|
||||
--bg-2: #fff4e6;
|
||||
--ink: #0f172a;
|
||||
--muted: #5c677d;
|
||||
--card: rgba(255, 255, 255, 0.9);
|
||||
--surface: #ffffff;
|
||||
--surface-soft: #f7fbff;
|
||||
--surface-secondary: #fff8ed;
|
||||
--border: #d8deea;
|
||||
--accent: #0ea5e9;
|
||||
--accent-strong: #0f766e;
|
||||
--pill: #e1f6ff;
|
||||
--pill-border: #c7ecff;
|
||||
--pill-text: #0f4c5c;
|
||||
--live-ok-bg: #e6ffe8;
|
||||
--live-ok-border: #c4f0d0;
|
||||
--live-ok-text: #0f6d2f;
|
||||
--shadow: 0 12px 60px rgba(15, 23, 42, 0.14);
|
||||
--link: #0ea5e9;
|
||||
--link-disabled: #94a3b8;
|
||||
--status-ok-bg: #e9fff2;
|
||||
--status-ok-border: #c1f3d7;
|
||||
--status-error-bg: #fff2ed;
|
||||
--status-error-border: #ffd2c8;
|
||||
}
|
||||
|
||||
[data-theme="dark"] {
|
||||
--bg-1: #0f172a;
|
||||
--bg-2: #111827;
|
||||
--ink: #e5e7eb;
|
||||
--muted: #a5b4c6;
|
||||
--card: rgba(24, 32, 48, 0.9);
|
||||
--surface: #0f172a;
|
||||
--surface-soft: #1f2937;
|
||||
--surface-secondary: #1c2432;
|
||||
--border: #1f2a3a;
|
||||
--accent: #22d3ee;
|
||||
--accent-strong: #10b981;
|
||||
--pill: #142337;
|
||||
--pill-border: #1f3a5f;
|
||||
--pill-text: #c7e1ff;
|
||||
--live-ok-bg: #15392a;
|
||||
--live-ok-border: #1e4f37;
|
||||
--live-ok-text: #bef0d2;
|
||||
--shadow: 0 20px 60px rgba(0, 0, 0, 0.4);
|
||||
--link: #7dd3fc;
|
||||
--link-disabled: #475569;
|
||||
--status-ok-bg: #102b1f;
|
||||
--status-ok-border: #1e4f37;
|
||||
--status-error-bg: #321717;
|
||||
--status-error-border: #6b2727;
|
||||
}
|
||||
|
||||
*,
|
||||
*::before,
|
||||
*::after {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
body {
|
||||
margin: 0;
|
||||
min-height: 100vh;
|
||||
background: radial-gradient(120% 120% at 20% 20%, rgba(14, 165, 233, 0.18), transparent),
|
||||
radial-gradient(80% 80% at 80% 0%, rgba(255, 159, 67, 0.16), transparent),
|
||||
linear-gradient(135deg, var(--bg-1), var(--bg-2));
|
||||
font-family: "Sora", "Segoe UI", -apple-system, sans-serif;
|
||||
color: var(--ink);
|
||||
padding: 32px;
|
||||
}
|
||||
|
||||
.page {
|
||||
max-width: 1100px;
|
||||
margin: 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 20px;
|
||||
}
|
||||
|
||||
.hero {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.hero-row {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 16px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.hero-text {
|
||||
flex: 1 1 320px;
|
||||
}
|
||||
|
||||
.hero-actions {
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
align-items: flex-start;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.eyebrow {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
padding: 6px 10px;
|
||||
background: rgba(255, 255, 255, 0.7);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
color: var(--muted);
|
||||
width: fit-content;
|
||||
font-size: 13px;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
h1 {
|
||||
margin: 0;
|
||||
font-size: 32px;
|
||||
letter-spacing: -0.02em;
|
||||
}
|
||||
|
||||
.hero-topline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.logo-mark {
|
||||
width: 52px;
|
||||
height: 52px;
|
||||
border-radius: 12px;
|
||||
box-shadow: var(--shadow);
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.lede {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
max-width: 760px;
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
|
||||
gap: 16px;
|
||||
}
|
||||
|
||||
.card {
|
||||
background: var(--card);
|
||||
border-radius: 18px;
|
||||
border: 1px solid var(--border);
|
||||
box-shadow: var(--shadow);
|
||||
padding: 18px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
backdrop-filter: blur(8px);
|
||||
}
|
||||
|
||||
.card-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.label {
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
}
|
||||
|
||||
.muted {
|
||||
margin: 4px 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.stack {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
input,
|
||||
textarea {
|
||||
width: 100%;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
padding: 12px 14px;
|
||||
font: inherit;
|
||||
transition: border-color 0.2s ease, box-shadow 0.2s ease;
|
||||
background: var(--surface);
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
input:focus,
|
||||
textarea:focus {
|
||||
outline: none;
|
||||
border-color: var(--accent);
|
||||
box-shadow: 0 0 0 4px rgba(14, 165, 233, 0.12);
|
||||
}
|
||||
|
||||
textarea {
|
||||
resize: vertical;
|
||||
}
|
||||
|
||||
.input-label {
|
||||
font-weight: 600;
|
||||
font-size: 14px;
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
.button-row {
|
||||
display: flex;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
button {
|
||||
border: none;
|
||||
border-radius: 12px;
|
||||
padding: 12px 14px;
|
||||
font: inherit;
|
||||
cursor: pointer;
|
||||
transition: transform 0.15s ease, box-shadow 0.2s ease, opacity 0.2s ease;
|
||||
}
|
||||
|
||||
button:disabled {
|
||||
opacity: 0.6;
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.primary {
|
||||
background: linear-gradient(135deg, var(--accent), #22c55e);
|
||||
color: #fff;
|
||||
box-shadow: 0 10px 30px rgba(14, 165, 233, 0.3);
|
||||
}
|
||||
|
||||
.ghost {
|
||||
background: transparent;
|
||||
color: var(--ink);
|
||||
border: 1px solid var(--border);
|
||||
}
|
||||
|
||||
button:hover:not(:disabled) {
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.meta {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(140px, 1fr));
|
||||
gap: 10px 18px;
|
||||
padding: 12px;
|
||||
border-radius: 12px;
|
||||
background: var(--surface-soft);
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
.meta dt {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.meta dd {
|
||||
margin: 0;
|
||||
font-weight: 600;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.pill {
|
||||
padding: 8px 12px;
|
||||
border-radius: 999px;
|
||||
font-weight: 600;
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.pill-quiet {
|
||||
background: var(--pill);
|
||||
color: var(--pill-text);
|
||||
border: 1px solid var(--pill-border);
|
||||
}
|
||||
|
||||
.pill-live {
|
||||
background: var(--live-ok-bg);
|
||||
color: var(--live-ok-text);
|
||||
border: 1px solid var(--live-ok-border);
|
||||
}
|
||||
|
||||
.status-card .status-line {
|
||||
padding: 12px;
|
||||
border-radius: 12px;
|
||||
border: 1px dashed var(--border);
|
||||
background: var(--surface-soft);
|
||||
font-weight: 600;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.status-card .secondary {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
font-weight: 500;
|
||||
background: var(--surface-secondary);
|
||||
}
|
||||
|
||||
.status-card .dot {
|
||||
width: 10px;
|
||||
height: 10px;
|
||||
border-radius: 999px;
|
||||
background: #f59e0b;
|
||||
display: inline-block;
|
||||
}
|
||||
|
||||
.hint {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.status-card .hint {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.tx-box {
|
||||
padding: 12px;
|
||||
border-radius: 12px;
|
||||
border: 1px solid var(--border);
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.hash {
|
||||
font-family: "SFMono-Regular", "JetBrains Mono", "Fira Code", monospace;
|
||||
word-break: break-all;
|
||||
margin: 6px 0;
|
||||
}
|
||||
|
||||
.tx-actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.copy-btn {
|
||||
padding: 8px 10px;
|
||||
}
|
||||
|
||||
.link {
|
||||
color: var(--link);
|
||||
font-weight: 600;
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.link:hover {
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
.link.disabled {
|
||||
pointer-events: none;
|
||||
color: var(--link-disabled);
|
||||
text-decoration: none;
|
||||
}
|
||||
|
||||
.locale-dropdown {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
min-width: 180px;
|
||||
}
|
||||
|
||||
.locale-label {
|
||||
margin: 0;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
.locale-toggle {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
background: var(--surface);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 999px;
|
||||
padding: 10px 12px;
|
||||
cursor: pointer;
|
||||
transition: box-shadow 0.2s, background 0.2s;
|
||||
}
|
||||
|
||||
.locale-toggle:hover {
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
|
||||
.locale-toggle:focus {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 4px rgba(14, 165, 233, 0.12);
|
||||
}
|
||||
|
||||
.locale-flag {
|
||||
width: 28px;
|
||||
height: 28px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
background: var(--surface-soft);
|
||||
border-radius: 50%;
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.locale-name {
|
||||
font-weight: 600;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.locale-arrow {
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
color: #6366f1;
|
||||
transition: transform 0.2s;
|
||||
}
|
||||
|
||||
.locale-arrow.open {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.locale-panel {
|
||||
position: absolute;
|
||||
top: calc(100% + 6px);
|
||||
right: 0;
|
||||
background: var(--card);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 14px;
|
||||
box-shadow: var(--shadow);
|
||||
overflow: hidden;
|
||||
z-index: 20;
|
||||
min-width: 220px;
|
||||
}
|
||||
|
||||
.locale-panel-search {
|
||||
padding: 8px;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
|
||||
.locale-panel-search input {
|
||||
width: 100%;
|
||||
padding: 8px 10px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.locale-panel-search input:focus {
|
||||
outline: none;
|
||||
box-shadow: 0 0 0 3px rgba(14, 165, 233, 0.1);
|
||||
}
|
||||
|
||||
.locale-panel-list {
|
||||
list-style: none;
|
||||
margin: 0;
|
||||
padding: 6px 0;
|
||||
max-height: 240px;
|
||||
overflow-y: auto;
|
||||
}
|
||||
|
||||
.locale-panel-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
padding: 8px 12px;
|
||||
cursor: pointer;
|
||||
transition: background 0.15s;
|
||||
}
|
||||
|
||||
.locale-panel-item:hover,
|
||||
.locale-panel-item.focused {
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.locale-item-flag {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 16px;
|
||||
}
|
||||
|
||||
.locale-item-label {
|
||||
font-size: 14px;
|
||||
color: var(--ink);
|
||||
}
|
||||
|
||||
.locale-no-results {
|
||||
padding: 10px 12px;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
font-style: italic;
|
||||
}
|
||||
|
||||
.status-ok {
|
||||
border-color: var(--status-ok-border) !important;
|
||||
background: var(--status-ok-bg) !important;
|
||||
}
|
||||
|
||||
.status-error {
|
||||
border-color: var(--status-error-border) !important;
|
||||
background: var(--status-error-bg) !important;
|
||||
}
|
||||
|
||||
.theme-toggle {
|
||||
min-width: 160px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.history {
|
||||
margin-top: 12px;
|
||||
padding: 12px;
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 12px;
|
||||
background: var(--surface);
|
||||
}
|
||||
|
||||
.history-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
}
|
||||
|
||||
.history-empty {
|
||||
margin: 8px 0 0;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.history-list {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
margin: 10px 0 0;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.history-item {
|
||||
border: 1px solid var(--border);
|
||||
border-radius: 10px;
|
||||
padding: 10px;
|
||||
background: var(--surface-soft);
|
||||
}
|
||||
|
||||
.history-row {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.history-time {
|
||||
font-size: 12px;
|
||||
color: var(--muted);
|
||||
}
|
||||
|
||||
.history-meta {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
margin: 6px 0;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
word-break: break-all;
|
||||
}
|
||||
|
||||
.history-message {
|
||||
font-weight: 600;
|
||||
margin: 4px 0;
|
||||
}
|
||||
|
||||
.history-hash {
|
||||
font-family: "SFMono-Regular", "JetBrains Mono", "Fira Code", monospace;
|
||||
color: var(--muted);
|
||||
font-size: 12px;
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
body {
|
||||
padding: 18px;
|
||||
}
|
||||
|
||||
.card-head {
|
||||
flex-direction: column;
|
||||
align-items: flex-start;
|
||||
}
|
||||
|
||||
.button-row {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.hero-row {
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.locale-dropdown {
|
||||
width: 100%;
|
||||
}
|
||||
}
|
||||
77
app/hooks/useI18n.ts
Normal file
77
app/hooks/useI18n.ts
Normal file
@@ -0,0 +1,77 @@
|
||||
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
|
||||
import de from "@/locales/de.json";
|
||||
import en from "@/locales/en.json";
|
||||
import es from "@/locales/es.json";
|
||||
import fr from "@/locales/fr.json";
|
||||
import it from "@/locales/it.json";
|
||||
import sv from "@/locales/sv.json";
|
||||
|
||||
const bundles = { en, es, fr, de, it, sv } as const;
|
||||
|
||||
export type Locale = keyof typeof bundles;
|
||||
export type MessageKey = string;
|
||||
|
||||
export type LocaleOption = {
|
||||
code: Locale;
|
||||
name: string;
|
||||
emoji: string;
|
||||
};
|
||||
|
||||
const localeOptions: LocaleOption[] = [
|
||||
{ code: "en", name: "English", emoji: "🇺🇸" },
|
||||
{ code: "es", name: "Español", emoji: "🇪🇸" },
|
||||
{ code: "fr", name: "Français", emoji: "🇫🇷" },
|
||||
{ code: "de", name: "Deutsch", emoji: "🇩🇪" },
|
||||
{ code: "it", name: "Italiano", emoji: "🇮🇹" },
|
||||
{ code: "sv", name: "Svenska", emoji: "🇸🇪" },
|
||||
];
|
||||
|
||||
export function useI18n(defaultLocale: Locale = "en") {
|
||||
const [locale, setLocale] = useState<Locale>(defaultLocale);
|
||||
const hasDetectedLocale = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (hasDetectedLocale.current) return;
|
||||
hasDetectedLocale.current = true;
|
||||
const navLangs =
|
||||
typeof navigator !== "undefined" ? navigator.languages || [navigator.language] : [];
|
||||
const mapToLocale = (lang: string | undefined | null): Locale | null => {
|
||||
if (!lang) return null;
|
||||
const lower = lang.toLowerCase();
|
||||
if (lower.startsWith("es")) return "es";
|
||||
if (lower.startsWith("fr")) return "fr";
|
||||
if (lower.startsWith("de")) return "de";
|
||||
if (lower.startsWith("it")) return "it";
|
||||
if (lower.startsWith("sv")) return "sv";
|
||||
if (lower.startsWith("en")) return "en";
|
||||
return null;
|
||||
};
|
||||
const detected = navLangs.map((l) => mapToLocale(l)).find(Boolean);
|
||||
if (detected && detected !== locale) {
|
||||
setLocale(detected);
|
||||
}
|
||||
}, [locale]);
|
||||
|
||||
const t = useCallback(
|
||||
(key: MessageKey, vars?: Record<string, string>): string => {
|
||||
const parts = key.split(".");
|
||||
const dict = bundles[locale] ?? bundles.en;
|
||||
const fallbackDict = bundles.en;
|
||||
const resolveKey = (source: unknown) =>
|
||||
parts.reduce<unknown>(
|
||||
(acc, part) =>
|
||||
acc && typeof acc === "object" ? (acc as Record<string, unknown>)[part] : undefined,
|
||||
source
|
||||
);
|
||||
const value = resolveKey(dict) ?? resolveKey(fallbackDict);
|
||||
const text = typeof value === "string" ? value : key;
|
||||
if (!vars) return text;
|
||||
return text.replace(/\{(\w+)\}/g, (_: string, k: string) => (vars[k] ? vars[k] : `{${k}}`));
|
||||
},
|
||||
[locale]
|
||||
);
|
||||
|
||||
const options = useMemo(() => localeOptions, []);
|
||||
|
||||
return { locale, setLocale, t, localeOptions: options };
|
||||
}
|
||||
38
app/hooks/useTheme.ts
Normal file
38
app/hooks/useTheme.ts
Normal file
@@ -0,0 +1,38 @@
|
||||
import { useEffect, useState } from "react";
|
||||
|
||||
export type Theme = "light" | "dark";
|
||||
|
||||
export function useTheme(initial?: Theme) {
|
||||
const [theme, setTheme] = useState<Theme>(initial ?? "light");
|
||||
|
||||
useEffect(() => {
|
||||
const stored =
|
||||
typeof window !== "undefined" && "localStorage" in window
|
||||
? window.localStorage.getItem("theme")
|
||||
: null;
|
||||
if (stored === "light" || stored === "dark") {
|
||||
setTheme(stored);
|
||||
return;
|
||||
}
|
||||
if (typeof window !== "undefined" && "matchMedia" in window) {
|
||||
const media = window.matchMedia("(prefers-color-scheme: dark)");
|
||||
setTheme(media.matches ? "dark" : "light");
|
||||
const handler = (event: MediaQueryListEvent) => setTheme(event.matches ? "dark" : "light");
|
||||
media.addEventListener("change", handler);
|
||||
return () => media.removeEventListener("change", handler);
|
||||
}
|
||||
setTheme("light");
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (typeof document === "undefined") return;
|
||||
document.documentElement.setAttribute("data-theme", theme);
|
||||
if ("localStorage" in window) {
|
||||
window.localStorage.setItem("theme", theme);
|
||||
}
|
||||
}, [theme]);
|
||||
|
||||
const toggleTheme = () => setTheme((prev) => (prev === "light" ? "dark" : "light"));
|
||||
|
||||
return { theme, setTheme, toggleTheme };
|
||||
}
|
||||
76
app/layout.tsx
Normal file
76
app/layout.tsx
Normal file
@@ -0,0 +1,76 @@
|
||||
import type { Metadata } from "next";
|
||||
import { headers } from "next/headers";
|
||||
import type { ReactNode } from "react";
|
||||
import de from "@/locales/de.json";
|
||||
import en from "@/locales/en.json";
|
||||
import es from "@/locales/es.json";
|
||||
import fr from "@/locales/fr.json";
|
||||
import it from "@/locales/it.json";
|
||||
import sv from "@/locales/sv.json";
|
||||
import "./globals.css";
|
||||
|
||||
type Locale = "en" | "es" | "fr" | "de" | "it" | "sv";
|
||||
|
||||
const descriptions: Record<Locale, string> = {
|
||||
en: en.hero.lede,
|
||||
es: es.hero.lede,
|
||||
fr: fr.hero.lede,
|
||||
de: de.hero.lede,
|
||||
it: it.hero.lede,
|
||||
sv: sv.hero.lede,
|
||||
};
|
||||
|
||||
async function pickLocaleFromHeaders(): Promise<Locale> {
|
||||
const hdrs = await headers();
|
||||
const accept = hdrs.get("accept-language") || "";
|
||||
const entries = accept.split(",").map((entry) => entry.trim().toLowerCase());
|
||||
const match = entries.find((entry) =>
|
||||
["es", "fr", "de", "it", "sv", "en"].some((code) => entry.startsWith(code))
|
||||
);
|
||||
if (!match) return "en";
|
||||
if (match.startsWith("es")) return "es";
|
||||
if (match.startsWith("fr")) return "fr";
|
||||
if (match.startsWith("de")) return "de";
|
||||
if (match.startsWith("it")) return "it";
|
||||
if (match.startsWith("sv")) return "sv";
|
||||
return "en";
|
||||
}
|
||||
|
||||
export async function generateMetadata(): Promise<Metadata> {
|
||||
const locale = await pickLocaleFromHeaders();
|
||||
return {
|
||||
title: "PolyNote",
|
||||
description: descriptions[locale] ?? descriptions.en,
|
||||
metadataBase: new URL("https://polynote.wittrail.com"),
|
||||
openGraph: {
|
||||
title: "PolyNote",
|
||||
description: descriptions[locale] ?? descriptions.en,
|
||||
url: "https://polynote.wittrail.com",
|
||||
siteName: "PolyNote",
|
||||
images: [
|
||||
{
|
||||
url: "/logo.svg",
|
||||
width: 256,
|
||||
height: 256,
|
||||
alt: "PolyNote logo",
|
||||
},
|
||||
],
|
||||
locale,
|
||||
type: "website",
|
||||
},
|
||||
icons: {
|
||||
icon: "/favicon.ico",
|
||||
shortcut: "/favicon.ico",
|
||||
apple: "/favicon.png",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
export default async function RootLayout({ children }: { children: ReactNode }) {
|
||||
const locale = await pickLocaleFromHeaders();
|
||||
return (
|
||||
<html lang={locale}>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
83
app/locales/de.json
Normal file
83
app/locales/de.json
Normal file
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"locale": {
|
||||
"label": "Sprache",
|
||||
"search": "Sprache suchen..."
|
||||
},
|
||||
"theme": {
|
||||
"toggle": "Thema wechseln",
|
||||
"dark": "Dunkler Modus",
|
||||
"light": "Heller Modus"
|
||||
},
|
||||
"hero": {
|
||||
"eyebrow": "Eingebettetes Trust Wallet • Polygon Mainnet",
|
||||
"title": "PolyNote · Trust Wallet zu Polygon",
|
||||
"lede": "Verbinde dich mit der Trust-Wallet-Erweiterung oder dem In-App-Browser. Wir kodieren deinen Text in Hex und senden eine Null-MATIC-Transaktion auf Polygon – nur Gasgebühren fallen an."
|
||||
},
|
||||
"connection": {
|
||||
"title": "Verbindung",
|
||||
"subtitle": "Eingebettetes Trust Wallet (Browser-Erweiterung oder In-App dApp Browser).",
|
||||
"pill": "Nur Polygon",
|
||||
"connect": "Trust Wallet verbinden",
|
||||
"disconnect": "Trennen",
|
||||
"account": "Konto",
|
||||
"chain": "Netzwerk",
|
||||
"status": "Status",
|
||||
"connected": "Verbunden",
|
||||
"notConnected": "Nicht verbunden"
|
||||
},
|
||||
"compose": {
|
||||
"title": "Nachricht verfassen",
|
||||
"subtitle": "Wir kodieren deinen Text in Hex und senden eine 0 MATIC Transaktion mit diesem Payload.",
|
||||
"recipientLabel": "Zieladresse",
|
||||
"recipientHint": "(standardmäßig deine eigene Wallet)",
|
||||
"messageLabel": "Nachricht einbetten",
|
||||
"messagePlaceholder": "Bis zu 280 Zeichen eingeben...",
|
||||
"messageHint": "Wir wandeln dies in Hex um und fügen es in das Datenfeld ein.",
|
||||
"send": "Nachrichten-Transaktion senden",
|
||||
"sending": "Senden…"
|
||||
},
|
||||
"live": {
|
||||
"title": "Live-Feedback",
|
||||
"subtitle": "Wir halten dich über jeden Schritt auf dem Laufenden.",
|
||||
"chainReady": "Auf Polygon Mainnet und bereit.",
|
||||
"chainRequired": "Polygon Mainnet erforderlich.",
|
||||
"lastTx": "Letzter Transaktions-Hash",
|
||||
"trackHint": "Du kannst sie in deiner Wallet oder auf Polygonscan verfolgen.",
|
||||
"viewOnPolygonscan": "In Polygonscan öffnen",
|
||||
"copy": "Hash kopieren",
|
||||
"copySuccess": "Transaktions-Hash kopiert.",
|
||||
"copyFailed": "Hash konnte nicht kopiert werden. Kopiere ihn manuell."
|
||||
},
|
||||
"history": {
|
||||
"title": "Letzte Nachrichten",
|
||||
"subtitle": "Nachrichten, die du in dieser Sitzung gesendet hast.",
|
||||
"empty": "Noch keine Nachrichten.",
|
||||
"sent": "Gesendet",
|
||||
"from": "Von",
|
||||
"to": "An"
|
||||
},
|
||||
"status": {
|
||||
"waiting": "Warten auf Verbindung…",
|
||||
"preparingConnect": "Verbindung wird vorbereitet…",
|
||||
"requesting": "Wallet-Zugriff wird angefordert…",
|
||||
"connectedInjected": "Über eingebetteten Provider verbunden. Du kannst jetzt eine Polygon-Nachricht senden.",
|
||||
"connectFirst": "Verbinde zuerst deine Wallet.",
|
||||
"messageEmpty": "Nachricht darf nicht leer sein.",
|
||||
"recipientInvalid": "Empfänger muss eine gültige Adresse sein.",
|
||||
"switchPolygon": "Bitte wechsel in deiner Wallet zu Polygon Mainnet.",
|
||||
"prepareTx": "Gas wird geschätzt und Transaktion vorbereitet…",
|
||||
"gasFallback": "Gas-Schätzung fehlgeschlagen; verwende ein Fallback-Limit und sende trotzdem.",
|
||||
"feeFallback": "Gebühren konnten nicht geholt werden; neuer Versuch mit Legacy-Gaspreis.",
|
||||
"eoaWarning": "Warnung: Daten an eine EOA zu senden kann bei manchen Wallets/RPCs scheitern.",
|
||||
"submitted": "Transaktion gesendet. Hash: {hash}",
|
||||
"onchain": "Nachricht ist on-chain. Prüfe sie in deiner Wallet oder auf Polygonscan.",
|
||||
"rejected": "Anfrage in der Wallet abgelehnt.",
|
||||
"disconnected": "Getrennt."
|
||||
},
|
||||
"errors": {
|
||||
"noWallet": "Keine eingebettete Wallet gefunden. Verwende die Trust-Wallet-Erweiterung oder den In-App-Browser.",
|
||||
"noAccounts": "Die Wallet hat keine Konten zurückgegeben.",
|
||||
"sendFailed": "Nachrichten-Transaktion konnte nicht gesendet werden.",
|
||||
"connectionFailed": "Verbindung fehlgeschlagen."
|
||||
}
|
||||
}
|
||||
83
app/locales/en.json
Normal file
83
app/locales/en.json
Normal file
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"locale": {
|
||||
"label": "Language",
|
||||
"search": "Search language..."
|
||||
},
|
||||
"theme": {
|
||||
"toggle": "Toggle theme",
|
||||
"dark": "Dark mode",
|
||||
"light": "Light mode"
|
||||
},
|
||||
"hero": {
|
||||
"eyebrow": "Injected Trust Wallet • Polygon mainnet",
|
||||
"title": "PolyNote · Trust Wallet to Polygon",
|
||||
"lede": "Connect with the Trust Wallet extension or the in-app browser. We hex-encode your text and submit a zero-value Polygon transaction that only costs gas."
|
||||
},
|
||||
"connection": {
|
||||
"title": "Connection",
|
||||
"subtitle": "Injected Trust Wallet (browser extension or in-app dApp browser).",
|
||||
"pill": "Polygon only",
|
||||
"connect": "Connect Trust Wallet",
|
||||
"disconnect": "Disconnect",
|
||||
"account": "Account",
|
||||
"chain": "Chain",
|
||||
"status": "Status",
|
||||
"connected": "Connected",
|
||||
"notConnected": "Not connected"
|
||||
},
|
||||
"compose": {
|
||||
"title": "Compose message",
|
||||
"subtitle": "We hex-encode your text and send a 0 MATIC transaction carrying that payload.",
|
||||
"recipientLabel": "Recipient address",
|
||||
"recipientHint": "(defaults to your own wallet)",
|
||||
"messageLabel": "Message to embed",
|
||||
"messagePlaceholder": "Type up to 280 characters...",
|
||||
"messageHint": "We will convert this to hex and attach it to the transaction data field.",
|
||||
"send": "Send message transaction",
|
||||
"sending": "Sending…"
|
||||
},
|
||||
"live": {
|
||||
"title": "Live feedback",
|
||||
"subtitle": "We keep you posted through each step.",
|
||||
"chainReady": "On Polygon mainnet and ready.",
|
||||
"chainRequired": "Polygon mainnet required.",
|
||||
"lastTx": "Last transaction hash",
|
||||
"trackHint": "You can track it in your wallet or on Polygonscan.",
|
||||
"viewOnPolygonscan": "Open in Polygonscan",
|
||||
"copy": "Copy hash",
|
||||
"copySuccess": "Transaction hash copied.",
|
||||
"copyFailed": "Could not copy hash. Copy it manually."
|
||||
},
|
||||
"history": {
|
||||
"title": "Recent messages",
|
||||
"subtitle": "Messages you sent in this session.",
|
||||
"empty": "No messages yet.",
|
||||
"sent": "Sent",
|
||||
"from": "From",
|
||||
"to": "To"
|
||||
},
|
||||
"status": {
|
||||
"waiting": "Waiting to connect…",
|
||||
"preparingConnect": "Preparing to connect…",
|
||||
"requesting": "Requesting wallet access…",
|
||||
"connectedInjected": "Connected via injected provider. You can send a Polygon message now.",
|
||||
"connectFirst": "Connect your wallet first.",
|
||||
"messageEmpty": "Message cannot be empty.",
|
||||
"recipientInvalid": "Recipient must be a valid address.",
|
||||
"switchPolygon": "Please switch to Polygon mainnet in your wallet.",
|
||||
"prepareTx": "Estimating gas and preparing transaction…",
|
||||
"gasFallback": "Gas estimation failed; using a fallback limit and sending anyway.",
|
||||
"feeFallback": "Fee data failed; retrying with a legacy gas price.",
|
||||
"eoaWarning": "Warning: sending data to an EOA can fail in some wallets/RPCs.",
|
||||
"submitted": "Transaction submitted. Hash: {hash}",
|
||||
"onchain": "Message is on-chain. Check your wallet or Polygonscan.",
|
||||
"rejected": "Request rejected in wallet.",
|
||||
"disconnected": "Disconnected."
|
||||
},
|
||||
"errors": {
|
||||
"noWallet": "No injected wallet found. Try the Trust Wallet extension or app browser.",
|
||||
"noAccounts": "No accounts returned from injected wallet.",
|
||||
"sendFailed": "Failed to send message transaction.",
|
||||
"connectionFailed": "Connection failed."
|
||||
}
|
||||
}
|
||||
83
app/locales/es.json
Normal file
83
app/locales/es.json
Normal file
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"locale": {
|
||||
"label": "Idioma",
|
||||
"search": "Buscar idioma..."
|
||||
},
|
||||
"theme": {
|
||||
"toggle": "Cambiar tema",
|
||||
"dark": "Modo oscuro",
|
||||
"light": "Modo claro"
|
||||
},
|
||||
"hero": {
|
||||
"eyebrow": "Trust Wallet inyectado • Polygon mainnet",
|
||||
"title": "PolyNote · Trust Wallet a Polygon",
|
||||
"lede": "Conecta con la extensión de Trust Wallet o el navegador dentro de la app. Codificamos tu texto en hex y enviamos una transacción de valor cero en Polygon; solo pagas gas."
|
||||
},
|
||||
"connection": {
|
||||
"title": "Conexión",
|
||||
"subtitle": "Trust Wallet inyectado (extensión o navegador dentro de la app).",
|
||||
"pill": "Solo Polygon",
|
||||
"connect": "Conectar Trust Wallet",
|
||||
"disconnect": "Desconectar",
|
||||
"account": "Cuenta",
|
||||
"chain": "Red",
|
||||
"status": "Estado",
|
||||
"connected": "Conectado",
|
||||
"notConnected": "No conectado"
|
||||
},
|
||||
"compose": {
|
||||
"title": "Redactar mensaje",
|
||||
"subtitle": "Codificamos tu texto en hex y enviamos una transacción de 0 MATIC con ese payload.",
|
||||
"recipientLabel": "Dirección de destino",
|
||||
"recipientHint": "(por defecto tu propia wallet)",
|
||||
"messageLabel": "Mensaje a incrustar",
|
||||
"messagePlaceholder": "Escribe hasta 280 caracteres...",
|
||||
"messageHint": "Convertiremos esto a hex y lo pondremos en el campo data.",
|
||||
"send": "Enviar transacción con mensaje",
|
||||
"sending": "Enviando…"
|
||||
},
|
||||
"live": {
|
||||
"title": "Estado en vivo",
|
||||
"subtitle": "Te avisamos en cada paso.",
|
||||
"chainReady": "En Polygon mainnet, listo.",
|
||||
"chainRequired": "Se requiere Polygon mainnet.",
|
||||
"lastTx": "Último hash de transacción",
|
||||
"trackHint": "Puedes rastrearlo en tu wallet o Polygonscan.",
|
||||
"viewOnPolygonscan": "Abrir en Polygonscan",
|
||||
"copy": "Copiar hash",
|
||||
"copySuccess": "Hash de transacción copiado.",
|
||||
"copyFailed": "No se pudo copiar el hash. Hazlo manualmente."
|
||||
},
|
||||
"history": {
|
||||
"title": "Mensajes recientes",
|
||||
"subtitle": "Mensajes que enviaste en esta sesión.",
|
||||
"empty": "Aún no hay mensajes.",
|
||||
"sent": "Enviado",
|
||||
"from": "De",
|
||||
"to": "Para"
|
||||
},
|
||||
"status": {
|
||||
"waiting": "Esperando conexión…",
|
||||
"preparingConnect": "Preparando conexión…",
|
||||
"requesting": "Solicitando acceso a la wallet…",
|
||||
"connectedInjected": "Conectado con proveedor inyectado. Ya puedes enviar un mensaje en Polygon.",
|
||||
"connectFirst": "Conecta tu wallet primero.",
|
||||
"messageEmpty": "El mensaje no puede estar vacío.",
|
||||
"recipientInvalid": "El destinatario debe ser una dirección válida.",
|
||||
"switchPolygon": "Cambia a Polygon mainnet en tu wallet.",
|
||||
"prepareTx": "Calculando gas y preparando la transacción…",
|
||||
"gasFallback": "La estimación de gas falló; usamos un límite por defecto e igualmente enviamos.",
|
||||
"feeFallback": "No se pudieron obtener las tarifas; reintentamos con gas price legado.",
|
||||
"eoaWarning": "Aviso: enviar datos a una EOA puede fallar en algunas wallets/RPCs.",
|
||||
"submitted": "Transacción enviada. Hash: {hash}",
|
||||
"onchain": "El mensaje está on-chain. Revísalo en tu wallet o Polygonscan.",
|
||||
"rejected": "Solicitud rechazada en la wallet.",
|
||||
"disconnected": "Desconectado."
|
||||
},
|
||||
"errors": {
|
||||
"noWallet": "No se encontró una wallet inyectada. Usa la extensión de Trust Wallet o el navegador de la app.",
|
||||
"noAccounts": "La wallet no devolvió cuentas.",
|
||||
"sendFailed": "No se pudo enviar la transacción con mensaje.",
|
||||
"connectionFailed": "Fallo de conexión."
|
||||
}
|
||||
}
|
||||
83
app/locales/fr.json
Normal file
83
app/locales/fr.json
Normal file
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"locale": {
|
||||
"label": "Langue",
|
||||
"search": "Rechercher une langue..."
|
||||
},
|
||||
"theme": {
|
||||
"toggle": "Changer de thème",
|
||||
"dark": "Mode sombre",
|
||||
"light": "Mode clair"
|
||||
},
|
||||
"hero": {
|
||||
"eyebrow": "Trust Wallet injecté • Polygon mainnet",
|
||||
"title": "PolyNote · Trust Wallet vers Polygon",
|
||||
"lede": "Connecte-toi avec l’extension Trust Wallet ou le navigateur intégré. Nous encodons ton texte en hex et envoyons une transaction à 0 MATIC sur Polygon ; seuls les frais de gas sont dus."
|
||||
},
|
||||
"connection": {
|
||||
"title": "Connexion",
|
||||
"subtitle": "Trust Wallet injecté (extension navigateur ou navigateur dApp intégré).",
|
||||
"pill": "Polygon uniquement",
|
||||
"connect": "Connecter Trust Wallet",
|
||||
"disconnect": "Déconnecter",
|
||||
"account": "Compte",
|
||||
"chain": "Réseau",
|
||||
"status": "Statut",
|
||||
"connected": "Connecté",
|
||||
"notConnected": "Non connecté"
|
||||
},
|
||||
"compose": {
|
||||
"title": "Composer un message",
|
||||
"subtitle": "Nous encodons ton texte en hex et envoyons une transaction de 0 MATIC avec cette donnée.",
|
||||
"recipientLabel": "Adresse de destination",
|
||||
"recipientHint": "(par défaut ta propre wallet)",
|
||||
"messageLabel": "Message à intégrer",
|
||||
"messagePlaceholder": "Saisis jusqu’à 280 caractères...",
|
||||
"messageHint": "Nous convertissons en hex et plaçons cela dans le champ data.",
|
||||
"send": "Envoyer la transaction message",
|
||||
"sending": "Envoi…"
|
||||
},
|
||||
"live": {
|
||||
"title": "Retour en direct",
|
||||
"subtitle": "Nous te tenons informé à chaque étape.",
|
||||
"chainReady": "Sur Polygon mainnet, prêt.",
|
||||
"chainRequired": "Polygon mainnet requis.",
|
||||
"lastTx": "Dernier hash de transaction",
|
||||
"trackHint": "Suis-la dans ta wallet ou sur Polygonscan.",
|
||||
"viewOnPolygonscan": "Ouvrir dans Polygonscan",
|
||||
"copy": "Copier le hash",
|
||||
"copySuccess": "Hash de transaction copié.",
|
||||
"copyFailed": "Impossible de copier le hash. Copie-le manuellement."
|
||||
},
|
||||
"history": {
|
||||
"title": "Messages récents",
|
||||
"subtitle": "Messages envoyés pendant cette session.",
|
||||
"empty": "Pas encore de messages.",
|
||||
"sent": "Envoyé",
|
||||
"from": "De",
|
||||
"to": "À"
|
||||
},
|
||||
"status": {
|
||||
"waiting": "En attente de connexion…",
|
||||
"preparingConnect": "Préparation de la connexion…",
|
||||
"requesting": "Demande d’accès à la wallet…",
|
||||
"connectedInjected": "Connecté via le provider injecté. Tu peux envoyer un message sur Polygon.",
|
||||
"connectFirst": "Connecte d’abord ta wallet.",
|
||||
"messageEmpty": "Le message ne peut pas être vide.",
|
||||
"recipientInvalid": "Le destinataire doit être une adresse valide.",
|
||||
"switchPolygon": "Passe sur Polygon mainnet dans ta wallet.",
|
||||
"prepareTx": "Estimation du gas et préparation de la transaction…",
|
||||
"gasFallback": "Échec de l’estimation du gas ; utilisation d’une limite de secours.",
|
||||
"feeFallback": "Impossible de récupérer les frais ; nouvel essai avec un gas price legacy.",
|
||||
"eoaWarning": "Attention : envoyer des données à une EOA peut échouer selon les wallets/RPC.",
|
||||
"submitted": "Transaction envoyée. Hash : {hash}",
|
||||
"onchain": "Message on-chain. Vérifie dans ta wallet ou sur Polygonscan.",
|
||||
"rejected": "Demande rejetée dans la wallet.",
|
||||
"disconnected": "Déconnecté."
|
||||
},
|
||||
"errors": {
|
||||
"noWallet": "Aucune wallet injectée trouvée. Utilise l’extension Trust Wallet ou le navigateur de l’app.",
|
||||
"noAccounts": "La wallet n’a renvoyé aucun compte.",
|
||||
"sendFailed": "Impossible d’envoyer la transaction message.",
|
||||
"connectionFailed": "Échec de connexion."
|
||||
}
|
||||
}
|
||||
83
app/locales/it.json
Normal file
83
app/locales/it.json
Normal file
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"locale": {
|
||||
"label": "Lingua",
|
||||
"search": "Cerca lingua..."
|
||||
},
|
||||
"theme": {
|
||||
"toggle": "Cambia tema",
|
||||
"dark": "Modalità scura",
|
||||
"light": "Modalità chiara"
|
||||
},
|
||||
"hero": {
|
||||
"eyebrow": "Trust Wallet iniettato • Polygon mainnet",
|
||||
"title": "PolyNote · Trust Wallet su Polygon",
|
||||
"lede": "Connetti con l’estensione di Trust Wallet o il browser integrato. Codifichiamo il testo in hex e inviamo una transazione a 0 MATIC su Polygon; paghi solo il gas."
|
||||
},
|
||||
"connection": {
|
||||
"title": "Connessione",
|
||||
"subtitle": "Trust Wallet iniettato (estensione o browser dApp integrato).",
|
||||
"pill": "Solo Polygon",
|
||||
"connect": "Connetti Trust Wallet",
|
||||
"disconnect": "Disconnetti",
|
||||
"account": "Account",
|
||||
"chain": "Rete",
|
||||
"status": "Stato",
|
||||
"connected": "Connesso",
|
||||
"notConnected": "Non connesso"
|
||||
},
|
||||
"compose": {
|
||||
"title": "Scrivi il messaggio",
|
||||
"subtitle": "Codifichiamo il testo in hex e inviamo una transazione da 0 MATIC con quel payload.",
|
||||
"recipientLabel": "Indirizzo destinatario",
|
||||
"recipientHint": "(di default il tuo wallet)",
|
||||
"messageLabel": "Messaggio da includere",
|
||||
"messagePlaceholder": "Scrivi fino a 280 caratteri...",
|
||||
"messageHint": "Lo convertiremo in hex e lo inseriremo nel campo data.",
|
||||
"send": "Invia transazione con messaggio",
|
||||
"sending": "Invio…"
|
||||
},
|
||||
"live": {
|
||||
"title": "Aggiornamenti in tempo reale",
|
||||
"subtitle": "Ti aggiorniamo a ogni passo.",
|
||||
"chainReady": "Su Polygon mainnet, pronto.",
|
||||
"chainRequired": "Polygon mainnet necessario.",
|
||||
"lastTx": "Ultimo hash di transazione",
|
||||
"trackHint": "Puoi seguirla nel wallet o su Polygonscan.",
|
||||
"viewOnPolygonscan": "Apri in Polygonscan",
|
||||
"copy": "Copia hash",
|
||||
"copySuccess": "Hash di transazione copiato.",
|
||||
"copyFailed": "Impossibile copiare l’hash. Copialo manualmente."
|
||||
},
|
||||
"history": {
|
||||
"title": "Messaggi recenti",
|
||||
"subtitle": "Messaggi inviati in questa sessione.",
|
||||
"empty": "Ancora nessun messaggio.",
|
||||
"sent": "Inviato",
|
||||
"from": "Da",
|
||||
"to": "A"
|
||||
},
|
||||
"status": {
|
||||
"waiting": "In attesa di connessione…",
|
||||
"preparingConnect": "Preparazione della connessione…",
|
||||
"requesting": "Richiesta di accesso al wallet…",
|
||||
"connectedInjected": "Connesso tramite provider iniettato. Puoi inviare ora su Polygon.",
|
||||
"connectFirst": "Connetti prima il wallet.",
|
||||
"messageEmpty": "Il messaggio non può essere vuoto.",
|
||||
"recipientInvalid": "Il destinatario deve essere un indirizzo valido.",
|
||||
"switchPolygon": "Passa a Polygon mainnet nel wallet.",
|
||||
"prepareTx": "Stima del gas e preparazione transazione…",
|
||||
"gasFallback": "Stima del gas fallita; uso un limite di fallback e invio comunque.",
|
||||
"feeFallback": "Impossibile recuperare le fee; ritento con un gas price legacy.",
|
||||
"eoaWarning": "Avviso: inviare dati a un EOA può fallire in alcuni wallet/RPC.",
|
||||
"submitted": "Transazione inviata. Hash: {hash}",
|
||||
"onchain": "Messaggio on-chain. Controlla nel wallet o su Polygonscan.",
|
||||
"rejected": "Richiesta rifiutata nel wallet.",
|
||||
"disconnected": "Disconnesso."
|
||||
},
|
||||
"errors": {
|
||||
"noWallet": "Nessun wallet iniettato trovato. Usa l’estensione Trust Wallet o il browser dell’app.",
|
||||
"noAccounts": "Il wallet non ha restituito account.",
|
||||
"sendFailed": "Impossibile inviare la transazione con messaggio.",
|
||||
"connectionFailed": "Connessione fallita."
|
||||
}
|
||||
}
|
||||
83
app/locales/sv.json
Normal file
83
app/locales/sv.json
Normal file
@@ -0,0 +1,83 @@
|
||||
{
|
||||
"locale": {
|
||||
"label": "Språk",
|
||||
"search": "Sök språk..."
|
||||
},
|
||||
"theme": {
|
||||
"toggle": "Byt tema",
|
||||
"dark": "Mörkt läge",
|
||||
"light": "Ljust läge"
|
||||
},
|
||||
"hero": {
|
||||
"eyebrow": "Injektad Trust Wallet • Polygon mainnet",
|
||||
"title": "PolyNote · Trust Wallet till Polygon",
|
||||
"lede": "Anslut via Trust Wallets tillägg eller den inbyggda webbläsaren. Vi kodar din text i hex och skickar en 0 MATIC-transaktion på Polygon; du betalar bara gas."
|
||||
},
|
||||
"connection": {
|
||||
"title": "Anslutning",
|
||||
"subtitle": "Injekterad Trust Wallet (tillägg eller in-app dApp-webbläsare).",
|
||||
"pill": "Endast Polygon",
|
||||
"connect": "Anslut Trust Wallet",
|
||||
"disconnect": "Koppla från",
|
||||
"account": "Konto",
|
||||
"chain": "Nätverk",
|
||||
"status": "Status",
|
||||
"connected": "Ansluten",
|
||||
"notConnected": "Inte ansluten"
|
||||
},
|
||||
"compose": {
|
||||
"title": "Skriv meddelande",
|
||||
"subtitle": "Vi kodar din text i hex och skickar en 0 MATIC-transaktion med den datan.",
|
||||
"recipientLabel": "Mottagaradress",
|
||||
"recipientHint": "(standard är din egen plånbok)",
|
||||
"messageLabel": "Meddelande att bädda in",
|
||||
"messagePlaceholder": "Skriv upp till 280 tecken...",
|
||||
"messageHint": "Vi gör om det till hex och lägger det i data-fältet.",
|
||||
"send": "Skicka meddelande-transaktion",
|
||||
"sending": "Skickar…"
|
||||
},
|
||||
"live": {
|
||||
"title": "Status i realtid",
|
||||
"subtitle": "Vi uppdaterar dig vid varje steg.",
|
||||
"chainReady": "På Polygon mainnet och redo.",
|
||||
"chainRequired": "Polygon mainnet krävs.",
|
||||
"lastTx": "Senaste transaktionshash",
|
||||
"trackHint": "Följ den i din plånbok eller på Polygonscan.",
|
||||
"viewOnPolygonscan": "Öppna i Polygonscan",
|
||||
"copy": "Kopiera hash",
|
||||
"copySuccess": "Transaktions-hash kopierad.",
|
||||
"copyFailed": "Kunde inte kopiera hash. Kopiera manuellt."
|
||||
},
|
||||
"history": {
|
||||
"title": "Senaste meddelanden",
|
||||
"subtitle": "Meddelanden du skickade i den här sessionen.",
|
||||
"empty": "Inga meddelanden ännu.",
|
||||
"sent": "Skickat",
|
||||
"from": "Från",
|
||||
"to": "Till"
|
||||
},
|
||||
"status": {
|
||||
"waiting": "Väntar på anslutning…",
|
||||
"preparingConnect": "Förbereder anslutning…",
|
||||
"requesting": "Begär åtkomst till plånboken…",
|
||||
"connectedInjected": "Ansluten via injekterad provider. Du kan skicka ett Polygon-meddelande nu.",
|
||||
"connectFirst": "Anslut plånboken först.",
|
||||
"messageEmpty": "Meddelandet kan inte vara tomt.",
|
||||
"recipientInvalid": "Mottagaren måste vara en giltig adress.",
|
||||
"switchPolygon": "Byt till Polygon mainnet i din plånbok.",
|
||||
"prepareTx": "Beräknar gas och förbereder transaktionen…",
|
||||
"gasFallback": "Gasberäkningen misslyckades; använder ett reservtak och skickar ändå.",
|
||||
"feeFallback": "Kunde inte hämta avgifter; försöker igen med legacy gas price.",
|
||||
"eoaWarning": "Varning: data till en EOA kan misslyckas i vissa wallets/RPC:er.",
|
||||
"submitted": "Transaktion skickad. Hash: {hash}",
|
||||
"onchain": "Meddelandet är on-chain. Kontrollera i plånboken eller på Polygonscan.",
|
||||
"rejected": "Begäran avvisad i plånboken.",
|
||||
"disconnected": "Frånkopplad."
|
||||
},
|
||||
"errors": {
|
||||
"noWallet": "Ingen injekterad plånbok hittades. Använd Trust Wallet-tillägget eller appens webbläsare.",
|
||||
"noAccounts": "Plånboken returnerade inga konton.",
|
||||
"sendFailed": "Det gick inte att skicka meddelande-transaktionen.",
|
||||
"connectionFailed": "Anslutningen misslyckades."
|
||||
}
|
||||
}
|
||||
603
app/page.tsx
Normal file
603
app/page.tsx
Normal file
@@ -0,0 +1,603 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import type { FormEvent } from "react";
|
||||
import Image from "next/image";
|
||||
import { ethers } from "ethers";
|
||||
import { LocaleSelector } from "@/components/LocaleSelector";
|
||||
import { useI18n, type Locale, type MessageKey } from "@/hooks/useI18n";
|
||||
import { useTheme } from "@/hooks/useTheme";
|
||||
|
||||
type StatusTone = "info" | "success" | "error";
|
||||
|
||||
type StatusState = {
|
||||
text: string;
|
||||
tone: StatusTone;
|
||||
key?: string;
|
||||
vars?: Record<string, string>;
|
||||
};
|
||||
|
||||
type Eip1193Provider = {
|
||||
request: (args: { method: string; params?: unknown[] }) => Promise<unknown>;
|
||||
on?: (event: string, fn: (...args: unknown[]) => void | Promise<void>) => void;
|
||||
removeListener?: (event: string, fn: (...args: unknown[]) => void | Promise<void>) => void;
|
||||
providers?: Eip1193Provider[];
|
||||
isTrustWallet?: boolean;
|
||||
isTrust?: boolean;
|
||||
};
|
||||
|
||||
type EthereumWindow = Window & {
|
||||
ethereum?: Eip1193Provider & { providers?: Eip1193Provider[] };
|
||||
trustwallet?: Eip1193Provider;
|
||||
};
|
||||
|
||||
const formatChain = (chainId: number | null) => {
|
||||
if (chainId === 137) return "Polygon";
|
||||
if (typeof chainId === "number" && Number.isFinite(chainId)) return `Chain ${chainId}`;
|
||||
return "—";
|
||||
};
|
||||
|
||||
type MessageEntry = {
|
||||
hash: string;
|
||||
to: string;
|
||||
from: string;
|
||||
message: string;
|
||||
createdAt: number;
|
||||
};
|
||||
|
||||
export default function HomePage() {
|
||||
const { locale, setLocale, t, localeOptions } = useI18n("en");
|
||||
const [account, setAccount] = useState<string>("");
|
||||
const [chainId, setChainId] = useState<number | null>(null);
|
||||
const [txHash, setTxHash] = useState<string>("—");
|
||||
const [status, setStatus] = useState<StatusState>({
|
||||
text: t("status.waiting"),
|
||||
key: "status.waiting",
|
||||
tone: "info",
|
||||
});
|
||||
const [connecting, setConnecting] = useState<boolean>(false);
|
||||
const [sending, setSending] = useState<boolean>(false);
|
||||
const [connected, setConnected] = useState<boolean>(false);
|
||||
const [history, setHistory] = useState<MessageEntry[]>([]);
|
||||
|
||||
const providerRef = useRef<Eip1193Provider | null>(null);
|
||||
const signerRef = useRef<ethers.Signer | null>(null);
|
||||
const formRef = useRef<HTMLFormElement | null>(null);
|
||||
|
||||
const chainLabel = formatChain(chainId);
|
||||
const onPolygon = chainId === 137;
|
||||
const statusClass =
|
||||
status.tone === "success"
|
||||
? "status-line status-ok"
|
||||
: status.tone === "error"
|
||||
? "status-line status-error"
|
||||
: "status-line";
|
||||
const chainPillClass = onPolygon ? "pill pill-live" : "pill pill-quiet";
|
||||
const chainPillText = onPolygon ? "Polygon" : chainLabel || t("live.chainRequired");
|
||||
const disableSend = !connected || sending;
|
||||
const disableConnect = connecting;
|
||||
const disableDisconnect = !connected || connecting;
|
||||
const polygonscanBase = "https://polygonscan.com/tx/";
|
||||
const hasTxHash = Boolean(txHash && txHash !== "—");
|
||||
|
||||
useEffect(() => {
|
||||
if (status.key) {
|
||||
setStatus((prev) => ({
|
||||
...prev,
|
||||
text: t(prev.key as MessageKey, prev.vars),
|
||||
}));
|
||||
}
|
||||
}, [locale, status.key, status.vars, t]);
|
||||
|
||||
function setStatusMessage(
|
||||
text: string,
|
||||
tone: StatusTone = "info",
|
||||
key?: string,
|
||||
vars?: Record<string, string>
|
||||
) {
|
||||
setStatus({ text, tone, key, vars });
|
||||
}
|
||||
|
||||
async function connectWallet() {
|
||||
if (connecting) return;
|
||||
setConnecting(true);
|
||||
setTxHash("—");
|
||||
setStatusMessage(t("status.preparingConnect"), "info", "status.preparingConnect");
|
||||
await disconnect(false);
|
||||
|
||||
try {
|
||||
await connectInjected();
|
||||
} catch (err) {
|
||||
console.error("Connection failed", err);
|
||||
setStatusMessage(normalizeError(err, t("errors.connectionFailed"), t), "error");
|
||||
resetState();
|
||||
} finally {
|
||||
setConnecting(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function connectInjected() {
|
||||
const injected = pickInjectedProvider();
|
||||
if (!injected) {
|
||||
setStatusMessage(t("errors.noWallet"), "error", "errors.noWallet");
|
||||
return;
|
||||
}
|
||||
|
||||
providerRef.current = injected;
|
||||
attachProviderEvents(injected);
|
||||
|
||||
setStatusMessage(t("status.requesting"), "info", "status.requesting");
|
||||
// Try to force a fresh permission prompt when possible
|
||||
try {
|
||||
await injected.request({
|
||||
method: "wallet_requestPermissions",
|
||||
params: [{ eth_accounts: {} }],
|
||||
});
|
||||
} catch (err) {
|
||||
// Some wallets do not support this; fall back silently
|
||||
console.warn("wallet_requestPermissions not supported or rejected", err);
|
||||
}
|
||||
|
||||
const accounts = (await injected.request({
|
||||
method: "eth_requestAccounts",
|
||||
})) as string[];
|
||||
if (!accounts || accounts.length === 0) {
|
||||
throw new Error(t("errors.noAccounts"));
|
||||
}
|
||||
|
||||
const browserProvider = new ethers.BrowserProvider(
|
||||
injected as unknown as ethers.Eip1193Provider
|
||||
);
|
||||
const signer = await browserProvider.getSigner();
|
||||
signerRef.current = signer;
|
||||
const address = await signer.getAddress();
|
||||
const network = await browserProvider.getNetwork();
|
||||
|
||||
setAccount(address);
|
||||
setChainId(Number(network.chainId));
|
||||
setConnected(true);
|
||||
setStatusMessage(t("status.connectedInjected"), "success", "status.connectedInjected");
|
||||
}
|
||||
|
||||
async function disconnect(showMessage = true) {
|
||||
removeProviderEvents(providerRef.current);
|
||||
providerRef.current = null;
|
||||
signerRef.current = null;
|
||||
resetState();
|
||||
if (showMessage) setStatusMessage(t("status.disconnected"), "info", "status.disconnected");
|
||||
}
|
||||
|
||||
function resetState() {
|
||||
setConnected(false);
|
||||
setAccount("");
|
||||
setChainId(null);
|
||||
setTxHash("—");
|
||||
}
|
||||
|
||||
function attachProviderEvents(provider: Eip1193Provider) {
|
||||
if (!provider?.on) return;
|
||||
provider.on("accountsChanged", handleAccountsChanged);
|
||||
provider.on("chainChanged", handleChainChanged);
|
||||
provider.on("disconnect", handleDisconnectEvent);
|
||||
}
|
||||
|
||||
function removeProviderEvents(provider: Eip1193Provider | null) {
|
||||
if (!provider?.removeListener) return;
|
||||
provider.removeListener("accountsChanged", handleAccountsChanged);
|
||||
provider.removeListener("chainChanged", handleChainChanged);
|
||||
provider.removeListener("disconnect", handleDisconnectEvent);
|
||||
}
|
||||
|
||||
function handleDisconnectEvent() {
|
||||
disconnect(true);
|
||||
}
|
||||
|
||||
async function handleAccountsChanged(...args: unknown[]) {
|
||||
const accounts = Array.isArray(args[0]) ? args[0] : [];
|
||||
if (!accounts || accounts.length === 0) {
|
||||
await disconnect(true);
|
||||
return;
|
||||
}
|
||||
const first = accounts.find((acct): acct is string => typeof acct === "string");
|
||||
if (!first) {
|
||||
await disconnect(true);
|
||||
return;
|
||||
}
|
||||
setAccount(first);
|
||||
}
|
||||
|
||||
async function handleChainChanged(newChainId: unknown) {
|
||||
if (typeof newChainId !== "string" && typeof newChainId !== "number") return;
|
||||
const parsed = parseChainId(newChainId);
|
||||
setChainId(parsed);
|
||||
}
|
||||
|
||||
async function ensurePolygonChain() {
|
||||
if (chainId === 137 || !providerRef.current) return true;
|
||||
try {
|
||||
await providerRef.current.request({
|
||||
method: "wallet_switchEthereumChain",
|
||||
params: [{ chainId: "0x89" }],
|
||||
});
|
||||
setChainId(137);
|
||||
return true;
|
||||
} catch (err) {
|
||||
console.warn("Chain switch rejected", err);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function handleCopyHash() {
|
||||
if (!hasTxHash) return;
|
||||
try {
|
||||
if (!("clipboard" in navigator)) {
|
||||
throw new Error("Clipboard API unavailable");
|
||||
}
|
||||
await navigator.clipboard.writeText(txHash);
|
||||
setStatusMessage(t("live.copySuccess"), "success", "live.copySuccess");
|
||||
} catch (err) {
|
||||
console.warn("Copy failed", err);
|
||||
setStatusMessage(t("live.copyFailed"), "error", "live.copyFailed");
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSendMessage(event: FormEvent<HTMLFormElement>) {
|
||||
event.preventDefault();
|
||||
const formEl = event.currentTarget;
|
||||
setTxHash("—");
|
||||
if (!signerRef.current) {
|
||||
setStatusMessage(t("status.connectFirst"), "error", "status.connectFirst");
|
||||
return;
|
||||
}
|
||||
|
||||
const formData = new FormData(event.currentTarget);
|
||||
const message = (formData.get("message") || "").toString().trim();
|
||||
let recipient = (formData.get("to") || "").toString().trim();
|
||||
|
||||
if (!message) {
|
||||
setStatusMessage(t("status.messageEmpty"), "error", "status.messageEmpty");
|
||||
return;
|
||||
}
|
||||
if (!recipient) recipient = account;
|
||||
if (!ethers.isAddress(recipient)) {
|
||||
setStatusMessage(t("status.recipientInvalid"), "error", "status.recipientInvalid");
|
||||
return;
|
||||
}
|
||||
const recipientIsEoa = recipient.toLowerCase() === account.toLowerCase();
|
||||
if (recipientIsEoa) {
|
||||
setStatusMessage(t("status.eoaWarning"), "info", "status.eoaWarning");
|
||||
}
|
||||
|
||||
const canUsePolygon = await ensurePolygonChain();
|
||||
if (!canUsePolygon) {
|
||||
setStatusMessage(t("status.switchPolygon"), "error", "status.switchPolygon");
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
setSending(true);
|
||||
setStatusMessage(t("status.prepareTx"), "info", "status.prepareTx");
|
||||
|
||||
const data = ethers.hexlify(ethers.toUtf8Bytes(message));
|
||||
const txRequest = { to: recipient, value: 0n, data };
|
||||
let gasLimit: bigint;
|
||||
try {
|
||||
gasLimit = await signerRef.current.estimateGas(txRequest);
|
||||
} catch (estimateErr) {
|
||||
console.warn("Gas estimation failed, using fallback", estimateErr);
|
||||
setStatusMessage(t("status.gasFallback"), "info", "status.gasFallback");
|
||||
gasLimit = 250000n;
|
||||
}
|
||||
|
||||
const feeData = await signerRef.current.provider?.getFeeData?.();
|
||||
const feeOverrides =
|
||||
feeData && feeData.maxFeePerGas && feeData.maxPriorityFeePerGas
|
||||
? {
|
||||
maxFeePerGas: feeData.maxFeePerGas,
|
||||
maxPriorityFeePerGas: feeData.maxPriorityFeePerGas,
|
||||
}
|
||||
: {
|
||||
// conservative Polygon fallbacks in gwei
|
||||
maxFeePerGas: ethers.parseUnits("50", "gwei"),
|
||||
maxPriorityFeePerGas: ethers.parseUnits("40", "gwei"),
|
||||
};
|
||||
|
||||
let tx;
|
||||
try {
|
||||
tx = await signerRef.current.sendTransaction({
|
||||
...txRequest,
|
||||
gasLimit,
|
||||
...feeOverrides,
|
||||
});
|
||||
} catch (sendErr) {
|
||||
const code = (sendErr as { code?: number | string })?.code;
|
||||
if (code === 4001 || code === "ACTION_REJECTED") {
|
||||
setStatusMessage(t("status.rejected"), "error", "status.rejected");
|
||||
throw sendErr;
|
||||
}
|
||||
|
||||
// Fallback to legacy gasPrice if EIP-1559 style send fails or simulates a revert
|
||||
setStatusMessage(t("status.feeFallback"), "info", "status.feeFallback");
|
||||
const gasPrice =
|
||||
(await signerRef.current.provider?.getGasPrice?.()) || ethers.parseUnits("50", "gwei");
|
||||
tx = await signerRef.current.sendTransaction({
|
||||
...txRequest,
|
||||
gasLimit,
|
||||
gasPrice,
|
||||
});
|
||||
}
|
||||
|
||||
setTxHash(tx.hash);
|
||||
setStatusMessage(t("status.submitted", { hash: tx.hash }), "success", "status.submitted", {
|
||||
hash: tx.hash,
|
||||
});
|
||||
|
||||
await tx.wait();
|
||||
setStatusMessage(t("status.onchain"), "success", "status.onchain");
|
||||
formEl.reset();
|
||||
setHistory((prev) => [
|
||||
{
|
||||
hash: tx.hash,
|
||||
to: recipient,
|
||||
from: account,
|
||||
message,
|
||||
createdAt: Date.now(),
|
||||
},
|
||||
...prev,
|
||||
]);
|
||||
} catch (err) {
|
||||
console.error("Send failed", err);
|
||||
setStatusMessage(normalizeError(err, t("errors.sendFailed"), t), "error");
|
||||
} finally {
|
||||
setSending(false);
|
||||
}
|
||||
}
|
||||
|
||||
const { theme, toggleTheme } = useTheme();
|
||||
|
||||
return (
|
||||
<main className="page">
|
||||
<header className="hero">
|
||||
<div className="hero-row">
|
||||
<div className="hero-text">
|
||||
<div className="hero-topline">
|
||||
<Image
|
||||
src="/logo.svg"
|
||||
alt="PolyNote logo"
|
||||
width={52}
|
||||
height={52}
|
||||
className="logo-mark"
|
||||
/>
|
||||
<div className="eyebrow">{t("hero.eyebrow")}</div>
|
||||
</div>
|
||||
<h1>{t("hero.title")}</h1>
|
||||
<p className="lede">{t("hero.lede")}</p>
|
||||
</div>
|
||||
<div className="hero-actions">
|
||||
<LocaleSelector
|
||||
locale={locale}
|
||||
onChange={(code) => setLocale(code as Locale)}
|
||||
options={localeOptions}
|
||||
label={t("locale.label")}
|
||||
searchPlaceholder={t("locale.search")}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="ghost theme-toggle"
|
||||
onClick={toggleTheme}
|
||||
aria-pressed={theme === "dark"}
|
||||
title={t("theme.toggle")}
|
||||
>
|
||||
{theme === "dark" ? "🌙" : "☀️"}{" "}
|
||||
{theme === "dark" ? t("theme.light") : t("theme.dark")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
<section className="grid">
|
||||
<article className="card">
|
||||
<div className="card-head">
|
||||
<div>
|
||||
<p className="label">{t("connection.title")}</p>
|
||||
<p className="muted">{t("connection.subtitle")}</p>
|
||||
</div>
|
||||
<span className="pill pill-quiet">{t("connection.pill")}</span>
|
||||
</div>
|
||||
<div className="stack">
|
||||
<div className="button-row">
|
||||
<button
|
||||
id="connectBtn"
|
||||
type="button"
|
||||
onClick={connectWallet}
|
||||
disabled={disableConnect}
|
||||
>
|
||||
{connecting ? t("compose.sending") : t("connection.connect")}
|
||||
</button>
|
||||
<button
|
||||
id="disconnectBtn"
|
||||
type="button"
|
||||
className="ghost"
|
||||
onClick={() => disconnect(true)}
|
||||
disabled={disableDisconnect}
|
||||
>
|
||||
{t("connection.disconnect")}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
<dl className="meta">
|
||||
<div>
|
||||
<dt>{t("connection.account")}</dt>
|
||||
<dd>{account || "—"}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{t("connection.chain")}</dt>
|
||||
<dd>{chainLabel}</dd>
|
||||
</div>
|
||||
<div>
|
||||
<dt>{t("connection.status")}</dt>
|
||||
<dd>{connected ? t("connection.connected") : t("connection.notConnected")}</dd>
|
||||
</div>
|
||||
</dl>
|
||||
</article>
|
||||
|
||||
<article className="card">
|
||||
<div className="card-head">
|
||||
<div>
|
||||
<p className="label">{t("compose.title")}</p>
|
||||
<p className="muted">{t("compose.subtitle")}</p>
|
||||
</div>
|
||||
<span className={chainPillClass}>{chainPillText}</span>
|
||||
</div>
|
||||
<form
|
||||
id="messageForm"
|
||||
ref={formRef}
|
||||
className="stack"
|
||||
noValidate
|
||||
onSubmit={handleSendMessage}
|
||||
>
|
||||
<label className="input-label" htmlFor="toAddress">
|
||||
{t("compose.recipientLabel")}{" "}
|
||||
<span className="muted">{t("compose.recipientHint")}</span>
|
||||
</label>
|
||||
<input
|
||||
id="toAddress"
|
||||
name="to"
|
||||
type="text"
|
||||
placeholder="0x destination (optional)"
|
||||
autoComplete="off"
|
||||
/>
|
||||
|
||||
<label className="input-label" htmlFor="messageInput">
|
||||
{t("compose.messageLabel")}
|
||||
</label>
|
||||
<textarea
|
||||
id="messageInput"
|
||||
name="message"
|
||||
rows={4}
|
||||
maxLength={280}
|
||||
placeholder={t("compose.messagePlaceholder")}
|
||||
disabled={!connected}
|
||||
></textarea>
|
||||
<p className="hint">{t("compose.messageHint")}</p>
|
||||
|
||||
<button id="sendBtn" type="submit" className="primary" disabled={disableSend}>
|
||||
{sending ? t("compose.sending") : t("compose.send")}
|
||||
</button>
|
||||
</form>
|
||||
</article>
|
||||
|
||||
<article className="card status-card">
|
||||
<div className="card-head">
|
||||
<div>
|
||||
<p className="label">{t("live.title")}</p>
|
||||
<p className="muted">{t("live.subtitle")}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div className={statusClass}>{status.text}</div>
|
||||
<div className="status-line secondary">
|
||||
<span className="dot"></span>
|
||||
<span>{onPolygon ? t("live.chainReady") : t("live.chainRequired")}</span>
|
||||
</div>
|
||||
<div className="tx-box">
|
||||
<div className="label">{t("live.lastTx")}</div>
|
||||
<div className="hash">{txHash || "—"}</div>
|
||||
<div className="tx-actions">
|
||||
<button
|
||||
type="button"
|
||||
className="ghost copy-btn"
|
||||
onClick={handleCopyHash}
|
||||
disabled={!hasTxHash}
|
||||
title={t("live.copy")}
|
||||
>
|
||||
{t("live.copy")}
|
||||
</button>
|
||||
<a
|
||||
className={`link ${!hasTxHash ? "disabled" : ""}`}
|
||||
href={hasTxHash ? `${polygonscanBase}${txHash}` : undefined}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
aria-disabled={!hasTxHash}
|
||||
>
|
||||
{t("live.viewOnPolygonscan")}
|
||||
</a>
|
||||
</div>
|
||||
<div className="hint">{t("live.trackHint")}</div>
|
||||
</div>
|
||||
<div className="history">
|
||||
<div className="history-head">
|
||||
<div>
|
||||
<p className="label">{t("history.title")}</p>
|
||||
<p className="muted">{t("history.subtitle")}</p>
|
||||
</div>
|
||||
</div>
|
||||
{history.length === 0 ? (
|
||||
<div className="history-empty">{t("history.empty")}</div>
|
||||
) : (
|
||||
<ul className="history-list">
|
||||
{history.map((item) => (
|
||||
<li key={item.hash} className="history-item">
|
||||
<div className="history-row">
|
||||
<span className="pill pill-quiet">{t("history.sent")}</span>
|
||||
<span className="history-time">
|
||||
{new Date(item.createdAt).toLocaleTimeString()}
|
||||
</span>
|
||||
</div>
|
||||
<div className="history-meta">
|
||||
<span>
|
||||
{t("history.from")}: {item.from}
|
||||
</span>
|
||||
<span>
|
||||
{t("history.to")}: {item.to}
|
||||
</span>
|
||||
</div>
|
||||
<div className="history-message">{item.message}</div>
|
||||
<div className="history-hash">
|
||||
{item.hash.slice(0, 10)}…{item.hash.slice(-6)}
|
||||
</div>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
</div>
|
||||
</article>
|
||||
</section>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
function pickInjectedProvider(): Eip1193Provider | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
const { ethereum, trustwallet } = window as EthereumWindow;
|
||||
if (ethereum?.providers?.length) {
|
||||
const trust = ethereum.providers.find((p) => p.isTrustWallet || p.isTrust);
|
||||
if (trust) return trust;
|
||||
return ethereum.providers[0];
|
||||
}
|
||||
if (trustwallet) return trustwallet;
|
||||
return ethereum || null;
|
||||
}
|
||||
|
||||
function parseChainId(chainId: string | number): number {
|
||||
if (typeof chainId === "string" && chainId.startsWith("0x")) {
|
||||
return parseInt(chainId, 16);
|
||||
}
|
||||
return Number(chainId);
|
||||
}
|
||||
|
||||
function normalizeError(
|
||||
err: unknown,
|
||||
fallback: string,
|
||||
t: (key: string, vars?: Record<string, string>) => string
|
||||
): string {
|
||||
if (!err) return fallback;
|
||||
if (typeof err === "string") return err;
|
||||
if (typeof err === "object") {
|
||||
const maybeError = err as { code?: number | string; message?: string; reason?: string };
|
||||
if (maybeError.code === 4001 || maybeError.message?.toLowerCase().includes("user rejected"))
|
||||
return t("status.rejected");
|
||||
if (maybeError.message) return maybeError.message;
|
||||
if (maybeError.reason) return maybeError.reason;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
Reference in New Issue
Block a user