Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bcdbfcad5a | ||
|
|
e35b61b3db | ||
|
|
a5d3cf5cd7 | ||
|
|
af8c292446 | ||
|
|
1b83aabc68 | ||
|
|
b88b88dd84 | ||
|
|
e1c8c3e636 | ||
|
|
998225ae04 |
No files matched your search
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"domains": [
|
||||
{ "domain": "福云.com", "role": "primary", "access": "requires_proxy", "domainhub": "fuc.main-cn" },
|
||||
{ "domain": "fuuu.cloud", "role": "primary", "access": "requires_proxy", "domainhub": "fuc.main-en" },
|
||||
{ "domain": "福云123.com", "role": "direct", "access": "suspected_blocked", "domainhub": "fuc.direct-cn-backup" },
|
||||
{ "domain": "fuuu.online", "role": "direct", "domainhub": "fuc.fuuu-online" },
|
||||
{ "domain": "fu99.cloud", "role": "direct", "domainhub": "fuc.direct-current", "recommended": true },
|
||||
{ "domain": "fu-nav3.com", "role": "navigation", "domainhub": "fuc.navigation" }
|
||||
]
|
||||
}
|
||||
@@ -1,5 +1,13 @@
|
||||
# Fuc:新版 FUC 用户主题适配
|
||||
|
||||
2026-11-08 Fuc 0.12.25 修复前台的五项问题。登录和用户页按需取模板,故障后可重试。公告请求失败时保留用户中心其余内容及已加载公告。系统深浅色切换保留弹窗和滚动锁。流量重置遵循 XB 原有资格。订单详情随链接保留来源页码。发布基线为 `b88b88dd8450b467469db9e3c4d820750f9932ab`,回退以本次服务器回执为准。
|
||||
|
||||
2026-11-08 Fuc 0.12.24:公开首页的客服窗口层级高于固定导航,覆盖手机全屏和短横屏两种会与导航重叠的布局。业务弹窗优先级仍更高,用户区侧栏与弹窗打开期间隐藏客服控件。验收须在首页和用户中心分别点开、关闭和重新打开,并检查 667/668px 断点及短横屏。
|
||||
|
||||
2026-11-08 Fuc 0.12.22 客服外层样式修复:稳定面板与启动/关闭按钮层级,隐藏后立即释放点击,菜单和业务弹窗遮挡实际控件;统一 667px 手机断点和短横屏高度。仅修改 Fuc 主题 CSS、缓存引用与版本,不改共享客服或业务。上一轮本地 57 项回归、连续开关及多尺寸/菜单/弹窗/回顶组合检查通过;本发布候选现有 55 项主题测试通过。
|
||||
|
||||
用户同时要求移除客服“常见问题”卡片和置顶公告中“注册免费试用3天,签到可获得1天试用时间,一直签到可以一直试用。”段落。卡片通过 FUC 独立收件箱取消 portal_id 关联处理,保留文章和会话;公告只删除匹配的旧段落。生产变更须先保存各自字段备份并逐项回读,不恢复整库。此提交记录方案,最终发布与配置回执在 `codex/output/fuc-theme/support-release-20261108/` 及服务器私有同任务目录,不能仅凭提交推定已部署。
|
||||
|
||||
2026-11-07 Fuc 0.12.21:按用户要求移除用户中心置顶公告旁的每日签到按钮,同时删除旧模板按钮与禁用适配。置顶公告内容、XB 业务和其他页面保持;更新主题及首页模板缓存引用。基于正式 `9971b6fab5197e64c31316dcfae86aaa5ce34d6a` 独立发布,保留已上线客服集成,验收与实际切换状态以任务回执为准。
|
||||
|
||||
2026-11-07 原生标志发布候选 Fuc 0.12.20:用户选择 Cool 主题原生折叠标志,登录/注册/找回密码、侧栏、首页和浏览器图标统一使用旧 FUC `cool1.png` 原始图案。原 PNG 字节嵌入 SVG,首页保留正式「福云」字标。资源引用更新缓存版本。发布范围仅品牌素材及其缓存引用;不包含本地折福试稿或其他未发布 UI/客服修改。回退基线为 `2c92a857e8da54c16c4861b25ea420f560ccc032`;发布验收以任务回执为准。
|
||||
@@ -237,3 +245,7 @@ Fuc在XB中已是系统主题,不能声称通过后台“上传同名主题”
|
||||
侧栏菜单项在鼠标离开时清除悬停状态,避免收起后保留原版悬停缩进。侧栏和账号菜单的「使用教程」使用福云文档中心。用户中心各平台的「安装教程」直达对应文档,macOS Clash Verge Rev 使用原文档已发布的 `/macos/clash-verge-reg/` 路径。
|
||||
|
||||
「立即下载」沿用 DPL 的 Resource 固定安装包地址,覆盖 Clash Verge Rev、Hiddify 和 Android Clash Meta。iOS 使用各自的 App Store 页面,旧 sing-box VT 已下架,入口改为官方 sing-box MT。Resource 未提供 Clash Nyanpasu,本主题的 Windows x64、macOS Apple Silicon 和 Intel 入口使用其官方对应版本安装包。改动限 Fuc 主题,客户端选择和 XB 接口保持原样。
|
||||
|
||||
### 窄屏客服层级(0.12.23)
|
||||
|
||||
667px 及以下的全屏客服层盖过首页固定导航,使客服标题和内嵌关闭按钮可见且可点。桌面客服保持浮窗层级,用户中心的菜单和弹窗仍可暂时隐藏客服。
|
||||
@@ -0,0 +1,24 @@
|
||||
# 项目域名清单与福云导航
|
||||
|
||||
项目面向用户的域名和用途维护在 [config/project-domains/](../../config/project-domains/)。每个项目使用独立的 JSON 文件,文件名为项目代号。DomainHub 继续维护 DNS、资源关系和地址发布台账;清单里的 `domainhub` 是对应记录代号,不包含凭据或私有入口。
|
||||
|
||||
- `role`:`primary` 永久主域名、`direct` 免翻墙域名、`navigation` 导航站域名。
|
||||
- `access`:按需填写 `requires_proxy`(需翻墙)或 `suspected_blocked`(疑似被墙)。未填写表示没有登记额外限制,不表示做过当地线路测试。
|
||||
- `recommended`:最多一个,只用于未标注限制的免翻墙域名。
|
||||
|
||||
```sh
|
||||
node scripts/project-domains/manage.mjs list
|
||||
node scripts/project-domains/manage.mjs list fuc
|
||||
node scripts/project-domains/manage.mjs build fuc
|
||||
node scripts/project-domains/manage.mjs check fuc
|
||||
```
|
||||
|
||||
[比利版福云导航](http://xb.loc/theme/Fuc/assets/connect.html)的设计源为 [connect.html](../../theme/Fuc/assets/connect.html)。调整设计或 [FUC 清单](../../config/project-domains/fuc.json)后重新生成,生成器同步本地预览的入口列表,并从同一设计源生成独立导航站的 HTML 和资源。测速前默认选中 fu99.cloud。两条永久主域名固定在最前,其余入口在每轮测速后按耗时从低到高排列,未测通的放在末尾。福云123.com 的「疑似被墙」是清单标注。导航站本身只登记为导航入口。
|
||||
|
||||
打开页面或点「重新检测」时,浏览器并行请求五个入口的 `/api/v1/guest/comm/config`,确认是 XB 访客响应后显示耗时。每次请求最多 3 秒,不带登录态和邀请码。成功时优先选中最快的入口,手动选择保留;全部失败保留当前选项。只有点击「立即进入」才跳转,邀请码随注册链接传递。本地预览的测速和注册均使用 xb.loc,用于验证交互和本地请求。
|
||||
|
||||
每轮测速结束后,正式导航和反代分别向同源 `POST /_nav-stats` 提交一次五条结果。统计只存按日期、导航来源和域名汇总的成功、超时、其他失败计数。统计量是提交成功的测速轮次,用户在测速结束前离开不计入。北京时间每天 08:00 统计过去 24 小时,并通过 TeleHub 的 `info` 发往 `base`。首期注明开始采集时间。日报正文和回执保存在独立 SQLite,同一天的重试沿用原幂等键。
|
||||
|
||||
采集和日报在 site-jp01 执行。部署从 Git 同步导航资产和统计脚本,使用独立系统服务 `fuc-navigation-stats.service` 和 `fuc-navigation-report.timer`。日报凭据由后者通过 systemd 私有凭据读取。停止统计时先切回上一版导航,再撤销两端的统计入口并停用服务和定时器。保留统计库及已发回执。
|
||||
|
||||
发布只从指定 Git 提交提取 `public/brand/fuc-navigation/` 下的 `index.html`、`clipboard.mjs`、`logo.svg`,落在 `/var/www/wwwroot/fuc-navigation/releases/<SHA>`,再切换 `current`。静态清单不依赖面板或 DomainHub 在线。导航站的 CSP `connect-src` 放行五个面板域名及对应 tomtojapan 反代的测速接口,以及两个导航入口的统计地址。发布时分别核对两个导航域名发起的 CORS 请求,并回读 [导航根域](https://fu-nav3.com/)与已登记的 tomtojapan 反代。异常时将 `current` 指回上一次验收的版本,并恢复上一次导航 CSP。
|
||||
@@ -0,0 +1,9 @@
|
||||
export async function copyText(text,{clipboard=globalThis.navigator?.clipboard,document=globalThis.document}={}){
|
||||
if(clipboard?.writeText){try{await clipboard.writeText(text);return;}catch{}}
|
||||
// Same fallback used by the original ClipboardJS, including HTTP local previews.
|
||||
const active=document.activeElement,input=document.createElement('textarea');
|
||||
input.value=text;input.readOnly=true;input.style.cssText='position:fixed;left:-9999px;top:0';
|
||||
document.body.append(input);
|
||||
try{input.focus({preventScroll:true});input.select();input.setSelectionRange(0,input.value.length);if(!document.execCommand?.('copy'))throw Error('复制失败,请选中链接手动复制');}
|
||||
finally{input.remove();if(active?.isConnected)active.focus();}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
<!doctype html>
|
||||
<!-- 从 theme/Fuc/assets/connect.html 和项目域名清单生成。 -->
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<title>福云地址导航</title>
|
||||
<link id="brand-icon" rel="icon" href="./logo.svg?v=2" type="image/svg+xml" sizes="any">
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--page: #171426;
|
||||
--page-wash: #241b3a;
|
||||
--panel: #201c34;
|
||||
--ink: #f6f1ff;
|
||||
--muted: #bbb2d0;
|
||||
--line: #38304d;
|
||||
--accent: #c6b7ff;
|
||||
--fastest: #b6ff40;
|
||||
--notice-warm-tone: #f4d36c;
|
||||
--action: #7256df;
|
||||
--tint: #332851;
|
||||
--shadow: rgb(0 0 0 / 20%);
|
||||
font: 16px/1.55 system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
color: var(--ink);
|
||||
background: linear-gradient(180deg, var(--page-wash), var(--page) 360px);
|
||||
}
|
||||
|
||||
a { color: inherit; text-decoration: none; }
|
||||
button { color: inherit; font: inherit; cursor: pointer; }
|
||||
:is(a, button):focus-visible,
|
||||
.entry:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: 4px; }
|
||||
|
||||
.wrap { width: min(740px, calc(100% - 48px)); margin-inline: auto; }
|
||||
|
||||
main { padding-block: clamp(32px, 6vw, 64px) 40px; }
|
||||
h1 { margin: 0 0 24px; font-size: clamp(32px, 5vw, 48px); line-height: 1.18; letter-spacing: -.04em; }
|
||||
.email-notice {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
align-items: start;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: color-mix(in srgb, var(--notice-warm-tone) 5%, var(--page));
|
||||
font-size: 15px;
|
||||
}
|
||||
.email-notice-icon {
|
||||
width: 19px;
|
||||
height: 19px;
|
||||
margin-top: 2px;
|
||||
color: var(--accent);
|
||||
}
|
||||
.email-notice p { margin: 0; }
|
||||
.email-notice .email-detail { margin-top: 4px; color: var(--muted); font-size: 14px; line-height: 1.65; text-wrap: pretty; }
|
||||
.copy-control { position: relative; display: inline-block; }
|
||||
.copy-email {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--accent);
|
||||
font-weight: 700;
|
||||
text-underline-offset: 4px;
|
||||
}
|
||||
.copy-email:hover { text-decoration: underline; }
|
||||
.copy-feedback {
|
||||
position: absolute;
|
||||
inset-inline-end: 0;
|
||||
inset-block-end: calc(100% + 6px);
|
||||
z-index: 1;
|
||||
width: max-content;
|
||||
max-width: 100%;
|
||||
padding: 3px 8px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
background: var(--panel);
|
||||
box-shadow: 0 4px 12px var(--shadow);
|
||||
font-size: 12px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.copy-feedback:empty { opacity: 0; }
|
||||
|
||||
.entries {
|
||||
padding: clamp(16px, 4vw, 28px);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 18px;
|
||||
background: var(--panel);
|
||||
box-shadow: 0 18px 48px var(--shadow);
|
||||
}
|
||||
|
||||
.entries h2 { margin: 0 0 16px; font-size: 18px; }
|
||||
.routes { display: grid; gap: 8px; margin: 0; padding: 0; border: 0; min-width: 0; }
|
||||
|
||||
.entry {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto auto;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-height: 60px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: border-color .16s ease, background-color .16s ease;
|
||||
}
|
||||
|
||||
.entry:hover { background: color-mix(in srgb, var(--tint) 50%, var(--panel)); }
|
||||
.entry:has(input:checked) { background: var(--tint); border-color: var(--accent); }
|
||||
.entry input { grid-area: 1 / 3; width: 18px; height: 18px; margin: 0; accent-color: var(--accent); }
|
||||
.entry-info { grid-area: 1 / 1; display: flex; align-items: baseline; gap: 12px; }
|
||||
.entry .latency { grid-area: 1 / 2; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.entry .latency[data-fastest] { color: var(--fastest); font-weight: 700; }
|
||||
|
||||
.entry strong { overflow-wrap: anywhere; font-size: 17px; }
|
||||
.entry small { color: var(--muted); font-size: 13px; }
|
||||
.entry:has(input:checked) small { color: var(--accent); }
|
||||
|
||||
.panel-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
min-height: 36px;
|
||||
margin-block: 12px;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
.recheck { border: 0; background: none; padding: 6px 0; color: var(--accent); white-space: nowrap; }
|
||||
.recheck:hover { text-decoration: underline; }
|
||||
.recheck:disabled { opacity: .55; cursor: wait; }
|
||||
.enter { display: grid; place-items: center; min-height: 46px; border-radius: 9px; font-size: 14px; }
|
||||
.enter { padding-inline: 12px; color: #fff; background: var(--action); font-weight: 700; }
|
||||
.enter:hover { filter: brightness(1.1); }
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.wrap { width: calc(100% - 32px); }
|
||||
h1 { margin-bottom: 18px; }
|
||||
.entry { gap: 10px; padding: 10px 12px; }
|
||||
.entry-info { flex-direction: column; gap: 1px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.entry { transition: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="wrap">
|
||||
<h1>福云地址导航</h1>
|
||||
<aside class="email-notice" aria-label="备用网址获取方式">
|
||||
<svg class="email-notice-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<rect x="2.5" y="5" width="19" height="14" rx="2"/>
|
||||
<path d="m3.5 6.5 8.5 7 8.5-7"/>
|
||||
</svg>
|
||||
<div>
|
||||
<p>务必,请收藏我们的邮箱
|
||||
<span class="copy-control">
|
||||
<button class="copy-email" type="button" aria-label="复制邮箱地址 [email protected]">
|
||||
[email protected]
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true">
|
||||
<path d="M8 8h9l3 3v10H8V8Z M15 8V3H3v13h5"/>
|
||||
</svg>
|
||||
</button>
|
||||
<span class="copy-feedback" role="status"></span>
|
||||
</span>。
|
||||
</p>
|
||||
<p class="email-detail">导航地址也被墙时,可发送任意邮件至该邮箱,会自动回复最新地址,这是最保险的防失联方式。</p>
|
||||
</div>
|
||||
</aside>
|
||||
<section class="entries" aria-labelledby="entry-title">
|
||||
<h2 id="entry-title">访问入口</h2>
|
||||
<fieldset class="routes" aria-labelledby="entry-title">
|
||||
<!-- project-domains:start -->
|
||||
<label class="entry" data-role="primary">
|
||||
<input type="radio" name="route" value="https://xn--9kqy16h.com/" data-domainhub-code="fuc.main-cn">
|
||||
<span class="entry-info"><strong>福云.com</strong><small>永久主域名(需翻墙)</small></span>
|
||||
<span class="latency">—</span>
|
||||
</label>
|
||||
<label class="entry" data-role="primary">
|
||||
<input type="radio" name="route" value="https://fuuu.cloud/" data-domainhub-code="fuc.main-en">
|
||||
<span class="entry-info"><strong>fuuu.cloud</strong><small>永久主域名(需翻墙)</small></span>
|
||||
<span class="latency">—</span>
|
||||
</label>
|
||||
<label class="entry" data-role="direct">
|
||||
<input type="radio" name="route" value="https://fu99.cloud/" data-domainhub-code="fuc.direct-current" checked>
|
||||
<span class="entry-info"><strong>fu99.cloud</strong><small>免翻墙域名</small></span>
|
||||
<span class="latency">—</span>
|
||||
</label>
|
||||
<label class="entry" data-role="direct">
|
||||
<input type="radio" name="route" value="https://fuuu.online/" data-domainhub-code="fuc.fuuu-online">
|
||||
<span class="entry-info"><strong>fuuu.online</strong><small>免翻墙域名</small></span>
|
||||
<span class="latency">—</span>
|
||||
</label>
|
||||
<label class="entry" data-role="direct">
|
||||
<input type="radio" name="route" value="https://xn--123-9i9dj97q.com/" data-domainhub-code="fuc.direct-cn-backup">
|
||||
<span class="entry-info"><strong>福云123.com</strong><small>免翻墙域名(疑似被墙)</small></span>
|
||||
<span class="latency">—</span>
|
||||
</label>
|
||||
<!-- project-domains:end -->
|
||||
</fieldset>
|
||||
<div class="panel-footer">
|
||||
<span id="route-status" role="status">已选择 fu99.cloud</span>
|
||||
<button class="recheck" type="button">重新检测</button>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<a id="enter" class="enter" href="https://fu99.cloud/#/register">立即进入 →</a>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script>
|
||||
const panel = document.querySelector('.entries');
|
||||
const routes = document.querySelector('.routes');
|
||||
const status = document.querySelector('#route-status');
|
||||
const enter = document.querySelector('#enter');
|
||||
const recheck = document.querySelector('.recheck');
|
||||
const invite = new URLSearchParams(location.search).get('code');
|
||||
const entries = [...routes.querySelectorAll('input[name="route"]')].map(input => {
|
||||
const row = input.closest('label');
|
||||
return { input, row, result: row.querySelector('.latency') };
|
||||
});
|
||||
const isLocal = location.hostname === 'xb.loc';
|
||||
const probePath = '/api/v1/guest/comm/config';
|
||||
const probeTimeoutMs = 3000;
|
||||
let manualSelection = false;
|
||||
let testStatus = '';
|
||||
|
||||
function selectRoute() {
|
||||
const selected = routes.querySelector('input:checked');
|
||||
const origin = isLocal ? location.origin : new URL(selected.value).origin;
|
||||
const code = invite && /^[A-Za-z0-9_-]{1,64}$/.test(invite) ? '?code=' + encodeURIComponent(invite) : '';
|
||||
enter.href = origin + '/#/register' + code;
|
||||
const name = selected.closest('label').querySelector('strong').textContent;
|
||||
status.textContent = ['已选择 ' + name, testStatus].filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
async function measure(entry, sample) {
|
||||
const url = new URL(probePath, isLocal ? location.origin : entry.input.value);
|
||||
url.searchParams.set('nav_probe', sample);
|
||||
const controller = new AbortController();
|
||||
const started = performance.now();
|
||||
const timeout = setTimeout(() => controller.abort(), probeTimeoutMs);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
mode: 'cors', cache: 'no-store', credentials: 'omit', redirect: 'error',
|
||||
referrerPolicy: 'no-referrer', signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) throw new Error('Probe failed');
|
||||
const { data } = await response.json();
|
||||
if (typeof data?.app_name !== 'string') throw new Error('Invalid XB response');
|
||||
const elapsed = performance.now() - started;
|
||||
entry.outcome = 'success';
|
||||
entry.result.textContent = Math.max(1, Math.round(elapsed)) + ' ms';
|
||||
return { entry, elapsed };
|
||||
} catch {
|
||||
entry.outcome = controller.signal.aborted ? 'timeout' : 'failure';
|
||||
entry.result.textContent = entry.outcome === 'timeout' ? '超时' : '不可用';
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
async function testRoutes() {
|
||||
if (recheck.disabled) return;
|
||||
recheck.disabled = true;
|
||||
panel.setAttribute('aria-busy', 'true');
|
||||
testStatus = isLocal ? '本地测速中…' : '正在测速…';
|
||||
selectRoute();
|
||||
for (const { result } of entries) {
|
||||
result.removeAttribute('data-fastest');
|
||||
result.textContent = '测速中…';
|
||||
}
|
||||
try {
|
||||
const round = Date.now().toString(36);
|
||||
const results = await Promise.all(entries.map((entry, index) => measure(entry, round + '-' + index)));
|
||||
const ranked = results.filter(Boolean).sort((a, b) => a.elapsed - b.elapsed);
|
||||
const measured = new Set(ranked.map(({ entry }) => entry));
|
||||
const ordered = [...ranked.map(({ entry }) => entry), ...entries.filter(entry => !measured.has(entry))];
|
||||
const focused = document.activeElement;
|
||||
for (const { row } of ordered) {
|
||||
if (row.dataset.role !== 'primary') routes.append(row);
|
||||
}
|
||||
if (routes.contains(focused) && document.activeElement !== focused) focused.focus({ preventScroll: true });
|
||||
const fastest = ranked[0];
|
||||
if (fastest) {
|
||||
fastest.entry.result.setAttribute('data-fastest', '');
|
||||
if (!manualSelection) fastest.entry.input.checked = true;
|
||||
}
|
||||
testStatus = fastest ? (isLocal ? '本地测速完成' : '测速完成') : '未测得可用入口';
|
||||
if (!isLocal) {
|
||||
const outcomes = Object.fromEntries(entries.map(({ input, outcome }) => [input.dataset.domainhubCode, outcome]));
|
||||
fetch('/_nav-stats', {
|
||||
method: 'POST', body: JSON.stringify(outcomes), credentials: 'omit',
|
||||
keepalive: true, referrerPolicy: 'no-referrer', redirect: 'error',
|
||||
}).catch(() => {});
|
||||
}
|
||||
} finally {
|
||||
recheck.disabled = false;
|
||||
panel.removeAttribute('aria-busy');
|
||||
selectRoute();
|
||||
}
|
||||
}
|
||||
|
||||
routes.addEventListener('click', event => {
|
||||
if (event.target.matches('input[name="route"]')) manualSelection = true;
|
||||
});
|
||||
routes.addEventListener('change', () => {
|
||||
manualSelection = true;
|
||||
selectRoute();
|
||||
});
|
||||
recheck.addEventListener('click', testRoutes);
|
||||
selectRoute();
|
||||
testRoutes();
|
||||
</script>
|
||||
<script type="module">
|
||||
import { copyText } from './clipboard.mjs';
|
||||
|
||||
const email = document.querySelector('.copy-email');
|
||||
const feedback = document.querySelector('.copy-feedback');
|
||||
let feedbackTimer;
|
||||
email.addEventListener('click', async () => {
|
||||
clearTimeout(feedbackTimer);
|
||||
feedback.textContent = '';
|
||||
try {
|
||||
await copyText(email.textContent.trim());
|
||||
feedback.textContent = '已复制';
|
||||
feedbackTimer = setTimeout(() => { feedback.textContent = ''; }, 1600);
|
||||
} catch {
|
||||
feedback.textContent = '复制失败,请选中邮箱地址手动复制。';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,5 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="64" height="64" viewBox="0 0 64 64">
|
||||
<title>福云</title>
|
||||
<!-- Original Cool theme logo, embedded unchanged for the local brand preview. -->
|
||||
<image x="4" y="12.465116" width="56" height="39.069768" href="data:image/png;base64,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 truncated
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 7.8 KiB |
@@ -0,0 +1,227 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Count browser probe outcomes and deliver the FUC navigation digest."""
|
||||
|
||||
import argparse
|
||||
import fcntl
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sqlite3
|
||||
import time
|
||||
from contextlib import closing
|
||||
from datetime import date, datetime, timedelta
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import HTTPRedirectHandler, Request, build_opener
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
SHANGHAI = ZoneInfo("Asia/Shanghai")
|
||||
ORIGINS = {
|
||||
"https://fu-nav3.com": "正式导航",
|
||||
"https://fu-nav3.tomtojapan.online": "反代导航",
|
||||
}
|
||||
OUTCOMES = ("success", "timeout", "failure")
|
||||
TERMINAL = {"sent", "failed", "uncertain", "cancelled", "rejected"}
|
||||
REPORT_ENDPOINT = "https://telehub.gemcook.net/api/v1/messages"
|
||||
REPORT_ROUTE = "/_nav-stats"
|
||||
|
||||
|
||||
def current_end(now):
|
||||
return (now - timedelta(hours=8)).date() + timedelta(days=1)
|
||||
|
||||
|
||||
def connect(path):
|
||||
db = sqlite3.connect(path, timeout=4)
|
||||
db.row_factory = sqlite3.Row
|
||||
return db
|
||||
|
||||
|
||||
def initialize(db, now):
|
||||
db.execute("PRAGMA journal_mode=WAL")
|
||||
db.executescript("""
|
||||
CREATE TABLE IF NOT EXISTS metadata (key TEXT PRIMARY KEY, value TEXT NOT NULL);
|
||||
CREATE TABLE IF NOT EXISTS totals (
|
||||
day TEXT NOT NULL, source TEXT NOT NULL, domain TEXT NOT NULL,
|
||||
success INTEGER NOT NULL, timeout INTEGER NOT NULL, failure INTEGER NOT NULL,
|
||||
PRIMARY KEY (day, source, domain)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS reports (
|
||||
day TEXT PRIMARY KEY, text TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending',
|
||||
receipt TEXT, retry_at INTEGER NOT NULL DEFAULT 0, error TEXT
|
||||
);
|
||||
""")
|
||||
with db:
|
||||
db.execute("INSERT OR IGNORE INTO metadata VALUES ('started', ?)", (now.isoformat(),))
|
||||
|
||||
|
||||
def count_round(db, catalog, origin, values, now):
|
||||
if origin not in ORIGINS or not isinstance(values, dict) or set(values) != set(catalog):
|
||||
raise ValueError("invalid sample")
|
||||
if any(value not in OUTCOMES for value in values.values()):
|
||||
raise ValueError("invalid outcome")
|
||||
rows = [
|
||||
(str(current_end(now)), origin, domain, *(outcome == status for status in OUTCOMES))
|
||||
for domain, outcome in values.items()
|
||||
]
|
||||
with db:
|
||||
db.executemany("""
|
||||
INSERT INTO totals VALUES (?, ?, ?, ?, ?, ?)
|
||||
ON CONFLICT(day, source, domain) DO UPDATE SET
|
||||
success = success + excluded.success,
|
||||
timeout = timeout + excluded.timeout,
|
||||
failure = failure + excluded.failure
|
||||
""", rows)
|
||||
|
||||
|
||||
def format_report(db, catalog, day):
|
||||
started = datetime.fromisoformat(db.execute("SELECT value FROM metadata WHERE key='started'").fetchone()[0])
|
||||
first = day - timedelta(days=1)
|
||||
lines = ["【福云 - 导航测速日报】", f"{first} 08:00 至 {day} 08:00(北京时间)"]
|
||||
if day == current_end(started):
|
||||
lines.append(f"本期从 {started:%m-%d %H:%M} 开始采集")
|
||||
rows = db.execute("SELECT * FROM totals WHERE day = ?", (str(day),))
|
||||
totals = {(row["source"], row["domain"]): row for row in rows}
|
||||
for origin, title in ORIGINS.items():
|
||||
lines.extend(("", title))
|
||||
if not any((origin, key) in totals for key in catalog):
|
||||
lines.append("暂无样本")
|
||||
continue
|
||||
for key, name in catalog.items():
|
||||
row = totals.get((origin, key))
|
||||
counts = [row[value] if row else 0 for value in OUTCOMES]
|
||||
total = sum(counts)
|
||||
if not total:
|
||||
lines.append(f"{name}:暂无样本")
|
||||
continue
|
||||
parts = [f"{label} {count / total:.1%}({count})"
|
||||
for label, count in zip(("成功", "超时", "其他失败"), counts)]
|
||||
lines.append(f"{name}:{total} 次," + ",".join(parts))
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
class NoRedirect(HTTPRedirectHandler):
|
||||
def redirect_request(self, *_args, **_kwargs):
|
||||
return None
|
||||
|
||||
|
||||
def telehub_request(token, report):
|
||||
if not re.fullmatch(r"telehub_[a-f0-9]{64}", token):
|
||||
raise ValueError("invalid TeleHub credential format")
|
||||
headers = {"Authorization": "Bearer " + token, "Accept": "application/json"}
|
||||
if report["receipt"]:
|
||||
req = Request(REPORT_ENDPOINT + "/" + report["receipt"], headers=headers)
|
||||
else:
|
||||
headers.update({
|
||||
"Content-Type": "application/json",
|
||||
"Idempotency-Key": "fuc.navigation.latency." + report["day"],
|
||||
})
|
||||
body = json.dumps({"bot": "info", "target": "base", "text": report["text"]}, ensure_ascii=False).encode()
|
||||
req = Request(REPORT_ENDPOINT, data=body, headers=headers)
|
||||
with build_opener(NoRedirect()).open(req, timeout=8) as result:
|
||||
return json.load(result)["data"]
|
||||
|
||||
|
||||
def deliver(db, catalog, now, send):
|
||||
started = datetime.fromisoformat(db.execute("SELECT value FROM metadata WHERE key='started'").fetchone()[0])
|
||||
day = current_end(started)
|
||||
latest = current_end(now) - timedelta(days=1)
|
||||
while day <= latest:
|
||||
if not db.execute("SELECT 1 FROM reports WHERE day=?", (str(day),)).fetchone():
|
||||
with db:
|
||||
db.execute("INSERT INTO reports (day,text) VALUES (?,?)", (str(day), format_report(db, catalog, day)))
|
||||
day += timedelta(days=1)
|
||||
timestamp = int(now.timestamp())
|
||||
reports = db.execute("""
|
||||
SELECT * FROM reports WHERE status IN ('pending','queued','sending') AND retry_at <= ? ORDER BY day LIMIT 4
|
||||
""", (timestamp,)).fetchall()
|
||||
for report in reports:
|
||||
receipt, status, delay, error = report["receipt"], report["status"], 900, None
|
||||
try:
|
||||
response = send(report)
|
||||
if not isinstance(response, dict):
|
||||
raise ValueError("invalid TeleHub response")
|
||||
new_receipt = response.get("id", "")
|
||||
new_status = response.get("status")
|
||||
if (not isinstance(new_receipt, str)
|
||||
or not re.fullmatch(r"[a-f0-9-]{36}", new_receipt)
|
||||
or (receipt and receipt != new_receipt)
|
||||
or new_status not in TERMINAL | {"queued", "sending"}
|
||||
or response.get("bot_code") != "info" or response.get("target_code") != "base"):
|
||||
raise ValueError("invalid TeleHub receipt")
|
||||
receipt, status = new_receipt, new_status
|
||||
except HTTPError as exc:
|
||||
error = "telehub_http_" + str(exc.code)
|
||||
if exc.code == 429:
|
||||
retry = exc.headers.get("Retry-After", "")
|
||||
if retry.isdigit():
|
||||
delay = max(delay, int(retry))
|
||||
elif 400 <= exc.code < 500:
|
||||
status = "rejected"
|
||||
except (ValueError, KeyError, OSError, URLError):
|
||||
error = "telehub_transport_or_response"
|
||||
with db:
|
||||
db.execute("UPDATE reports SET receipt=?, status=?, retry_at=?, error=? WHERE day=?",
|
||||
(receipt, status, timestamp + delay, error, report["day"]))
|
||||
print(report["day"], status, receipt or "-", error or "-", flush=True)
|
||||
|
||||
|
||||
def serve(path, catalog, port):
|
||||
class Handler(BaseHTTPRequestHandler):
|
||||
timeout = 4
|
||||
|
||||
def do_POST(self):
|
||||
if self.path != REPORT_ROUTE:
|
||||
self.send_error(404)
|
||||
return
|
||||
try:
|
||||
origin = self.headers.get("Origin")
|
||||
length = int(self.headers.get("Content-Length", "0"))
|
||||
if origin not in ORIGINS or not 1 <= length <= 1024:
|
||||
raise ValueError("invalid request")
|
||||
values = json.loads(self.rfile.read(length))
|
||||
with closing(connect(path)) as db:
|
||||
count_round(db, catalog, origin, values, datetime.now(SHANGHAI))
|
||||
except (ValueError, OSError, RecursionError):
|
||||
self.send_error(400)
|
||||
return
|
||||
except sqlite3.Error:
|
||||
self.send_error(503)
|
||||
return
|
||||
self.send_response(204)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *_args):
|
||||
pass
|
||||
|
||||
ThreadingHTTPServer(("127.0.0.1", port), Handler).serve_forever()
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--database", type=Path, required=True)
|
||||
parser.add_argument("--catalog", type=Path, required=True)
|
||||
sub = parser.add_subparsers(dest="mode", required=True)
|
||||
sub.add_parser("serve").add_argument("--port", type=int, default=18248)
|
||||
sub.add_parser("report")
|
||||
sub.add_parser("preview").add_argument("day", type=date.fromisoformat)
|
||||
args = parser.parse_args()
|
||||
catalog = {item["domainhub"]: item["domain"] for item in json.loads(args.catalog.read_text())["domains"]
|
||||
if item["role"] in {"primary", "direct"}}
|
||||
now = datetime.now(SHANGHAI)
|
||||
with closing(connect(args.database)) as db:
|
||||
initialize(db, now)
|
||||
if args.mode == "preview":
|
||||
print(format_report(db, catalog, args.day))
|
||||
elif args.mode == "report":
|
||||
credential = Path(os.environ["CREDENTIALS_DIRECTORY"])/"telehub-token"
|
||||
token = credential.read_text().strip()
|
||||
with args.database.with_suffix(".report.lock").open("a") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
deliver(db, catalog, now, lambda report: telehub_request(token, report))
|
||||
if args.mode == "serve":
|
||||
serve(args.database, catalog, args.port)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,119 @@
|
||||
import { readFileSync, readdirSync, writeFileSync } from 'node:fs';
|
||||
import { domainToASCII, domainToUnicode } from 'node:url';
|
||||
|
||||
const configs = new URL('../../config/project-domains/', import.meta.url);
|
||||
const roles = new Map([
|
||||
['primary', '永久主域名'],
|
||||
['direct', '免翻墙域名'],
|
||||
['navigation', '导航站域名'],
|
||||
]);
|
||||
const accessLabels = new Map([
|
||||
['requires_proxy', '需翻墙'],
|
||||
['suspected_blocked', '疑似被墙'],
|
||||
]);
|
||||
|
||||
function load(project) {
|
||||
if (!/^[a-z][a-z0-9-]*$/.test(project)) throw new Error('无效项目代号');
|
||||
const { domains } = JSON.parse(readFileSync(new URL(project + '.json', configs), 'utf8'));
|
||||
if (!Array.isArray(domains) || !domains.length) throw new Error(project + ' 未配置域名');
|
||||
const seenHosts = new Set();
|
||||
const seenCodes = new Set();
|
||||
const records = domains.map(({ domain, role, access, domainhub, recommended = false }) => {
|
||||
const fail = () => { throw new Error(project + ' 域名记录无效:' + domain); };
|
||||
if (typeof domain !== 'string' || /[\s:/@?#%\\]/u.test(domain)) fail();
|
||||
const host = domainToASCII(domain);
|
||||
const labels = host.split('.');
|
||||
if (host.length > 253 || labels.length < 2 || !/[a-z]/.test(labels.at(-1))
|
||||
|| labels.some(label => !/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label))
|
||||
|| seenHosts.has(host)) fail();
|
||||
if (!roles.has(role) || (access !== undefined && !accessLabels.has(access))
|
||||
|| typeof recommended !== 'boolean' || (recommended && (role !== 'direct' || access))) fail();
|
||||
if (domainhub !== undefined) {
|
||||
if (typeof domainhub !== 'string' || !/^[a-z0-9][a-z0-9.-]*$/.test(domainhub)
|
||||
|| !domainhub.startsWith(project + '.') || seenCodes.has(domainhub)) fail();
|
||||
seenCodes.add(domainhub);
|
||||
}
|
||||
seenHosts.add(host);
|
||||
return {
|
||||
name: domainToUnicode(host), origin: 'https://' + host + '/', role, access, domainhub, recommended,
|
||||
label: roles.get(role) + (access ? '(' + accessLabels.get(access) + ')' : ''),
|
||||
};
|
||||
});
|
||||
if (records.filter(record => record.recommended).length > 1) throw new Error(project + ' 有多个默认推荐域名');
|
||||
return records;
|
||||
}
|
||||
|
||||
function escapeHtml(value) {
|
||||
const entities = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };
|
||||
return value.replace(/[&<>"']/g, char => entities[char]);
|
||||
}
|
||||
|
||||
function renderNavigation(project, records, source) {
|
||||
const recommended = records.find(record => record.recommended);
|
||||
if (!recommended || records.filter(record => record.role === 'navigation').length !== 1) {
|
||||
throw new Error(project + ' 导航需要一个导航域名和一个默认推荐域名');
|
||||
}
|
||||
const panels = records.filter(record => record.role !== 'navigation');
|
||||
const priority = ({ recommended, role, access }) => role === 'primary' ? 0
|
||||
: recommended ? 1 : access === 'suspected_blocked' ? 3 : 2;
|
||||
panels.sort((a, b) => priority(a) - priority(b));
|
||||
const options = panels.map(({ origin, name, label, recommended, domainhub, role }) => {
|
||||
const code = domainhub ? ' data-domainhub-code="' + escapeHtml(domainhub) + '"' : '';
|
||||
return [
|
||||
' <label class="entry" data-role="' + role + '">',
|
||||
' <input type="radio" name="route" value="' + escapeHtml(origin) + '"' + code + (recommended ? ' checked' : '') + '>',
|
||||
' <span class="entry-info"><strong>' + escapeHtml(name) + '</strong><small>' + escapeHtml(label) + '</small></span>',
|
||||
' <span class="latency">—</span>',
|
||||
' </label>',
|
||||
].join('\n');
|
||||
}).join('\n');
|
||||
function replaceOnce(html, pattern, replacement) {
|
||||
if ([...html.matchAll(pattern)].length !== 1) throw new Error('导航源标记不唯一:' + pattern);
|
||||
return html.replace(pattern, replacement);
|
||||
}
|
||||
|
||||
const preview = replaceOnce(source, /<!-- project-domains:start -->[\s\S]*?<!-- project-domains:end -->/g,
|
||||
() => '<!-- project-domains:start -->\n' + options + '\n <!-- project-domains:end -->');
|
||||
const withDefault = replaceOnce(preview, /(<span id="route-status" role="status">)[^<]*(<\/span>)/g,
|
||||
(_, start, end) => start + '已选择 ' + escapeHtml(recommended.name) + end);
|
||||
|
||||
// The standalone release serves its own logo and does not require the XB theme path.
|
||||
const withLogo = replaceOnce(withDefault, /(id="brand-icon" rel="icon" href=")\.\/native\/images\/brand\/fuc-mark\.svg/g,
|
||||
(_, start) => start + './logo.svg');
|
||||
const withFallback = replaceOnce(withLogo, /(id="enter" class="enter" href=")\/#\/register"/g,
|
||||
(_, start) => start + escapeHtml(recommended.origin) + '#/register"');
|
||||
return {
|
||||
preview: withDefault,
|
||||
standalone: withFallback.replace('<!doctype html>', '<!doctype html>\n<!-- 从 theme/Fuc/assets/connect.html 和项目域名清单生成。 -->'),
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const [action, project, ...rest] = process.argv.slice(2);
|
||||
if (action === 'list' && rest.length === 0) {
|
||||
const projects = project ? [project] : readdirSync(configs)
|
||||
.filter(name => /^[a-z][a-z0-9-]*\.json$/.test(name)).sort().map(name => name.slice(0, -5));
|
||||
for (const key of projects) {
|
||||
for (const record of load(key)) console.log([key, record.name, record.label, record.domainhub ?? ''].join('\t'));
|
||||
}
|
||||
} else if (['build', 'check'].includes(action) && project === 'fuc' && rest.length === 0) {
|
||||
const source = new URL('../../theme/Fuc/assets/connect.html', import.meta.url);
|
||||
const read = path => readFileSync(new URL('../../' + path, import.meta.url));
|
||||
const { preview, standalone } = renderNavigation(project, load(project), readFileSync(source, 'utf8'));
|
||||
const files = [
|
||||
['theme/Fuc/assets/connect.html', Buffer.from(preview)],
|
||||
['public/brand/fuc-navigation/index.html', Buffer.from(standalone)],
|
||||
['public/brand/fuc-navigation/logo.svg', read('theme/Fuc/assets/native/images/brand/fuc-mark.svg')],
|
||||
['public/brand/fuc-navigation/clipboard.mjs', read('theme/Fuc/assets/clipboard.mjs')],
|
||||
];
|
||||
for (const [path, content] of files) {
|
||||
if (action === 'build') writeFileSync(new URL('../../' + path, import.meta.url), content);
|
||||
else if (!read(path).equals(content)) throw new Error(path + ' 已过期,请重新生成');
|
||||
}
|
||||
} else {
|
||||
throw new Error('用法:manage.mjs list [项目代号] | build fuc | check fuc');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(error.message);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
[Unit]
|
||||
Description=FUC navigation daily TeleHub report
|
||||
After=network-online.target fuc-navigation-stats.service
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=oneshot
|
||||
User=fuc-nav-stats
|
||||
Group=fuc-nav-stats
|
||||
StateDirectory=fuc-navigation-stats
|
||||
StateDirectoryMode=0700
|
||||
UMask=0077
|
||||
LoadCredential=telehub-token:/etc/fuc-navigation-stats/telehub-token
|
||||
ExecStart=/usr/bin/python3 /var/www/wwwroot/fuc-navigation/current/ops/fuc_navigation_stats.py --catalog /var/www/wwwroot/fuc-navigation/current/ops/fuc.json --database /var/lib/fuc-navigation-stats/counters.sqlite3 report
|
||||
TimeoutStartSec=55
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
@@ -0,0 +1,9 @@
|
||||
[Unit]
|
||||
Description=FUC navigation daily report and receipt checks
|
||||
|
||||
[Timer]
|
||||
OnCalendar=*-*-* *:00/15:00 Asia/Shanghai
|
||||
Persistent=true
|
||||
|
||||
[Install]
|
||||
WantedBy=timers.target
|
||||
@@ -0,0 +1,19 @@
|
||||
[Unit]
|
||||
Description=FUC navigation probe counters
|
||||
After=network.target
|
||||
|
||||
[Service]
|
||||
User=fuc-nav-stats
|
||||
Group=fuc-nav-stats
|
||||
StateDirectory=fuc-navigation-stats
|
||||
StateDirectoryMode=0700
|
||||
UMask=0077
|
||||
ExecStart=/usr/bin/python3 /var/www/wwwroot/fuc-navigation/current/ops/fuc_navigation_stats.py --catalog /var/www/wwwroot/fuc-navigation/current/ops/fuc.json --database /var/lib/fuc-navigation-stats/counters.sqlite3 serve
|
||||
Restart=on-failure
|
||||
NoNewPrivileges=true
|
||||
ProtectSystem=strict
|
||||
ProtectHome=true
|
||||
PrivateTmp=true
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
@@ -7,26 +7,37 @@ import {JSDOM,VirtualConsole} from '../../codex/output/fuc-theme/test-tools/node
|
||||
const jsErrors=[],consoleCapture=new VirtualConsole();consoleCapture.on('jsdomError',error=>jsErrors.push(error));
|
||||
const dom=new JSDOM('<html><head><style>.modal.fade .modal-dialog{transition:transform .3s ease-out}.modal-backdrop.fade{transition:opacity .15s linear}</style></head><body><div id="app"></div></body></html>',{url:'http://xb.loc/#/login',runScripts:'outside-only',pretendToBeVisual:true,virtualConsole:consoleCapture});
|
||||
for(const key of ['window','document','DOMParser','localStorage','sessionStorage','location','history','FormData'])globalThis[key]=dom.window[key];
|
||||
globalThis.innerWidth=1280;globalThis.matchMedia=()=>({matches:false,addEventListener(){}});
|
||||
globalThis.innerWidth=1280;
|
||||
let changeSystemColor;
|
||||
globalThis.matchMedia=()=>({matches:false,addEventListener(_,listener){changeSystemColor=listener;}});
|
||||
globalThis.requestAnimationFrame=window.requestAnimationFrame.bind(window);globalThis.cancelAnimationFrame=window.cancelAnimationFrame.bind(window);
|
||||
window.scrollTo=()=>{};window.ApexCharts=class{render(){return Promise.resolve()}destroy(){}};
|
||||
const plans=[{id:1,name:'Paid',month_price:1200,transfer_enable:100},{id:2,name:'Free',month_price:0,transfer_enable:10}];
|
||||
const calls=[];let delayedLogin,delayedCoupon,checkoutAmount=0,checkoutStatus=0,failOrderCheck=false,orders=[];
|
||||
const calls=[],templateRequests=[];
|
||||
let failWalletTemplate=true, failNoticePage=0, subscriptionExpired=false;
|
||||
let delayedLogin,delayedCoupon,checkoutAmount=0,checkoutStatus=0,failOrderCheck=false,orders=[];
|
||||
const payload=(data,status=200)=>({ok:status<400,status,json:async()=>({data})});
|
||||
globalThis.fetch=async(url,options={})=>{
|
||||
if(String(url).startsWith('file:'))return {ok:true,text:()=>fs.readFile(new URL(url),'utf8'),json:async()=>JSON.parse(await fs.readFile(new URL(url),'utf8'))};
|
||||
if(String(url).startsWith('file:')){
|
||||
const name=new URL(url).pathname.split('/').at(-1);
|
||||
if(name.endsWith('.html'))templateRequests.push(name);
|
||||
if(name==='wallet.html'&&failWalletTemplate)return {ok:false,status:503};
|
||||
return {ok:true,text:()=>fs.readFile(new URL(url),'utf8'),json:async()=>JSON.parse(await fs.readFile(new URL(url),'utf8'))};
|
||||
}
|
||||
const path=String(url).replace('/api/v1/','');calls.push({path,body:options.body?JSON.parse(options.body):null});
|
||||
if(path==='guest/comm/config')return payload({is_captcha:0});
|
||||
if(path==='passport/auth/login')return new Promise(resolve=>delayedLogin=()=>resolve(payload({auth_data:'Bearer synthetic'})));
|
||||
if(path==='user/info')return payload({email:'[email protected]',plan_id:2});
|
||||
if(path==='user/info')return payload({email:'[email protected]',plan_id:2,expired_at:subscriptionExpired?1:null,transfer_enable:1000});
|
||||
if(path==='user/getSubscribe')return payload({plan_id:2,plan:plans[1],transfer_enable:1000,u:0,d:0,subscribe_url:'http://xb.loc/s/synthetic'});
|
||||
if(path==='user/comm/config')return payload({withdraw_methods:[]});
|
||||
if(path.startsWith('user/notice/fetch?current=')){
|
||||
const offset=(Number(new URLSearchParams(path.split('?')[1]).get('current'))-1)*5;
|
||||
const notices=Array.from({length:18},(_,i)=>({id:i+1,title:'归档公告 '+(i+1),content:'归档正文',created_at:1793836800}));
|
||||
const current=Number(new URLSearchParams(path.split('?')[1]).get('current'));
|
||||
if(current===failNoticePage)return payload(null,503);
|
||||
const offset=(current-1)*5;
|
||||
const notices=Array.from({length:18},(_,i)=>({id:i+1,title:'归档公告 '+(i+1),content:'归档正文 '+(i+1),created_at:1793836800}));
|
||||
return {ok:true,status:200,json:async()=>({data:notices.slice(offset,offset+5),total:notices.length})};
|
||||
}
|
||||
if(path==='user/plan/fetch')return payload([plans[0]]);
|
||||
if(path==='user/plan/fetch')return payload(subscriptionExpired?[{...plans[1],reset_price:400}]:[plans[0]]);
|
||||
if(path==='user/plan/fetch?id=2')return payload({...plans[1],show:false,sell:false,renew:true,capacity_limit:'Sold out'});
|
||||
if(path==='user/coupon/check')return new Promise(resolve=>delayedCoupon=()=>resolve(payload({name:'QA'})));
|
||||
if(path==='user/order/save')return payload('synthetic-order');
|
||||
@@ -52,7 +63,7 @@ const until=async predicate=>{for(let n=0;n<200;n++){if(predicate())return;await
|
||||
const go=async route=>{location.hash='/'+route;await until(()=>document.body.dataset.nativePage===route);};
|
||||
await import('../../theme/Fuc/assets/app.mjs');
|
||||
test('login uses original pending text and waits for success confirmation before routing',async()=>{
|
||||
await until(()=>document.querySelector('[data-form=login]'));const form=document.querySelector('[data-form=login]'),button=form.querySelector('[type=submit]');
|
||||
await until(()=>document.querySelector('[data-form=login]'));assert.deepEqual(templateRequests,['login.html']);const form=document.querySelector('[data-form=login]'),button=form.querySelector('[type=submit]');
|
||||
form.querySelector('[name=email]').value='[email protected]';form.querySelector('[name=password]').value='synthetic-password';
|
||||
form.dispatchEvent(new window.Event('submit',{bubbles:true,cancelable:true}));
|
||||
assert.equal(button.textContent,'正在登录');assert.equal(button.disabled,true);await until(()=>delayedLogin);delayedLogin();
|
||||
@@ -114,15 +125,18 @@ test('the old plan URL opens the order list, with an unpaid order accessible on
|
||||
assert.equal(document.querySelector('[data-pending-order]'),null);
|
||||
assert.doesNotMatch(document.querySelector('tbody').textContent,/synthetic-order/);
|
||||
document.querySelector('[data-action=next]').click();
|
||||
const unpaidLink=()=>document.querySelector('tbody a[href="#/checkout/synthetic-order?from=orders"]');
|
||||
const unpaidLink=()=>document.querySelector('tbody a[href="#/checkout/synthetic-order?from=orders&page=2"]');
|
||||
await until(unpaidLink);
|
||||
assert.equal(unpaidLink().textContent,'继续支付');
|
||||
unpaidLink().click();
|
||||
await until(()=>document.querySelector('#fuc-checkout-modal.show'));
|
||||
assert.equal(location.hash,'#/checkout/synthetic-order?from=orders');
|
||||
assert.equal(location.hash,'#/checkout/synthetic-order?from=orders&page=2');
|
||||
assert.match(document.querySelector('.fuc-pagination').textContent,/第 2 \/ 2 页/);
|
||||
assert.ok(unpaidLink());
|
||||
document.querySelector('#fuc-checkout-modal [data-action=native-dismiss]').click();
|
||||
await until(()=>document.body.dataset.nativePage==='orders');
|
||||
assert.equal(location.hash,'#/orders');
|
||||
assert.equal(location.hash,'#/orders?page=2');
|
||||
assert.ok(unpaidLink());
|
||||
orders.pop();
|
||||
location.hash='/subscribe';
|
||||
await until(()=>location.hash==='#/orders'&&document.querySelector('tbody tr'));
|
||||
@@ -231,4 +245,57 @@ test('the announcement page shows all four native XB pages in order',async()=>{
|
||||
const headings=[...document.querySelectorAll('h5')].map(node=>node.textContent.trim()).filter(title=>title.startsWith('归档公告 '));
|
||||
assert.deepEqual(headings,Array.from({length:18},(_,i)=>'归档公告 '+(i+1)));
|
||||
});
|
||||
test('a failed wallet template stays isolated and can be retried',async()=>{
|
||||
location.hash='/wallet';
|
||||
await until(()=>document.querySelector('#app [data-action=retry]'));
|
||||
assert.match(document.querySelector('#app [role=alert]').textContent,/模板加载失败/);
|
||||
failWalletTemplate=false;
|
||||
document.querySelector('#app [data-action=retry]').click();
|
||||
await until(()=>document.querySelector('[data-form=gift]'));
|
||||
assert.equal(templateRequests.filter(name=>name==='wallet.html').length,2);
|
||||
});
|
||||
test('the dashboard preserves account details and loaded notices after a notice-page failure',async()=>{
|
||||
try {
|
||||
for(const failedPage of [1,2]){
|
||||
await go('profile');
|
||||
failNoticePage=failedPage;
|
||||
await go('dashboard');
|
||||
const dashboard=document.querySelector('#dashboard-analytics');
|
||||
assert.ok(dashboard);
|
||||
assert.match(dashboard.textContent,/公告暂时无法加载/);
|
||||
assert.equal(dashboard.textContent.includes('归档正文 1'),failedPage===2);
|
||||
assert.equal(document.querySelector('#app [data-action=retry]'),null);
|
||||
}
|
||||
}finally{failNoticePage=0;}
|
||||
});
|
||||
test('system color changes preserve the checkout modal and scroll lock',async()=>{
|
||||
localStorage.setItem('fuc_themeMod','system');
|
||||
try {
|
||||
location.hash='/checkout/synthetic-order?from=orders';
|
||||
await until(()=>document.querySelector('#fuc-checkout-modal.show'));
|
||||
const modal=document.querySelector('#fuc-checkout-modal');
|
||||
for(const matches of [true,false]){
|
||||
changeSystemColor({matches});
|
||||
assert.equal(document.body.classList.contains('dark-layout'),matches);
|
||||
assert.ok(document.body.classList.contains('modal-open'));
|
||||
assert.equal(document.querySelector('#fuc-checkout-modal.show'),modal);
|
||||
assert.equal(document.querySelectorAll('.modal-backdrop').length,1);
|
||||
}
|
||||
modal.querySelector('[data-action=native-dismiss]').click();
|
||||
await until(()=>document.body.dataset.nativePage==='orders');
|
||||
assert.equal(document.body.classList.contains('modal-open'),false);
|
||||
}finally{localStorage.removeItem('fuc_themeMod');}
|
||||
});
|
||||
test('an expired owner can buy a regular period but cannot enter traffic reset',async()=>{
|
||||
subscriptionExpired=true;
|
||||
try {
|
||||
await go('plans');
|
||||
assert.ok(document.querySelector('[data-action=buy][data-period=month_price]:enabled'));
|
||||
assert.equal(document.querySelector('[data-period=reset_price]'),null);
|
||||
location.hash='/purchase/2?period=reset_price';
|
||||
await until(()=>document.querySelector('#app [role=alert]'));
|
||||
assert.match(document.querySelector('#app [role=alert]').textContent,/此套餐或计费周期不可购买/);
|
||||
assert.equal(document.querySelector('[data-form=purchase]'),null);
|
||||
}finally{subscriptionExpired=false;}
|
||||
});
|
||||
test.after(()=>{window.Pace.stop();dom.window.close();});
|
||||
@@ -3,13 +3,17 @@ import assert from 'node:assert/strict';
|
||||
import {createApi, soldOut, safeUrl, bytes, money, paymentResult, routeFromHash,trafficSummary,canPurchase} from '../../theme/Fuc/assets/core.mjs';
|
||||
import {subscriptionUrl,importUrl} from '../../theme/Fuc/assets/subscription.mjs';
|
||||
const response = (body,status=200) => ({ok:status<400,status,json:async()=>body});
|
||||
test('owned renewal is not blocked by new-sale capacity, and reset requires ownership',()=>{
|
||||
test('owned renewal bypasses new-sale capacity and traffic reset requires an active subscription',()=>{
|
||||
const plan={id:7,show:false,sell:false,renew:true,capacity_limit:'Sold out',month_price:1200,reset_price:100};
|
||||
assert.equal(canPurchase(plan,{plan_id:7},'month_price'),true);
|
||||
assert.equal(canPurchase(plan,{plan_id:8},'month_price'),false);
|
||||
assert.equal(canPurchase({...plan,renew:false},{plan_id:7},'month_price'),false);
|
||||
assert.equal(canPurchase(plan,{plan_id:7},'reset_price'),true);
|
||||
assert.equal(canPurchase(plan,{plan_id:8},'reset_price'),false);
|
||||
const active={plan_id:7,expired_at:null,transfer_enable:100,u:100,d:0};
|
||||
assert.equal(canPurchase(plan,active,'reset_price'),true);
|
||||
assert.equal(canPurchase(plan,{...active,plan_id:8},'reset_price'),false);
|
||||
assert.equal(canPurchase(plan,{...active,expired_at:1},'reset_price'),false);
|
||||
assert.equal(canPurchase(plan,{...active,banned:true},'reset_price'),false);
|
||||
assert.equal(canPurchase(plan,{...active,transfer_enable:0},'reset_price'),false);
|
||||
});
|
||||
test('an expired response from a previous token cannot discard a newer login',async()=>{
|
||||
let token='Bearer old',resolve,cleared=false;
|
||||
|
||||
@@ -9,7 +9,8 @@ globalThis.fetch=async url=>({ok:true,text:()=>fs.readFile(new URL(url),'utf8'),
|
||||
const {paymentForm,showPayment}=await import('../../theme/Fuc/assets/payments.mjs');
|
||||
const {richText}=await import('../../theme/Fuc/assets/content.mjs');
|
||||
const {copyText}=await import('../../theme/Fuc/assets/clipboard.mjs');
|
||||
const native=await import('../../theme/Fuc/assets/native.mjs');await native.nativeReady;
|
||||
const native=await import('../../theme/Fuc/assets/native.mjs');
|
||||
await native.prepareNativeTemplates('header','index','home','login','register','plans','profile','article','orders','purchase','checkout');
|
||||
test('touch login waits for a tap while desktop keeps keyboard autofocus',()=>{
|
||||
const original=window.matchMedia;
|
||||
try {
|
||||
|
||||
+67
-20
@@ -7,8 +7,8 @@ import {copyText} from './clipboard.mjs?v=0.12.6';
|
||||
import {createCaptcha} from './captcha.mjs?v=0.12.6';
|
||||
import {showPayment,mountCard} from './payments.mjs?v=0.12.14';
|
||||
import {beginPageProgress,finishPageProgress} from './progress.mjs?v=0.12.6';
|
||||
import {nativeReady,prepareNativeMode,nativeMode,fillPurchaseModal,nativeHeader,nativeFooter,nativeDashboard,nativeHome,nativeAuth,nativeSecondary,paintNativeChart,paintNativeHome} from './native.mjs?v=0.12.21';
|
||||
import {escape as e, money, bytes, date, list, groupedList, periods, orderStates, soldOut, safeUrl, createApi, fetchNotices, routeFromHash,canPurchase} from './core.mjs?v=0.12.13';
|
||||
import {prepareNativeTemplates,prepareNativeMode,nativeMode,syncNativeColor,fillPurchaseModal,nativeHeader,nativeFooter,nativeDashboard,nativeHome,nativeAuth,nativeSecondary,paintNativeChart,paintNativeHome} from './native.mjs?v=ui-flow-1';
|
||||
import {escape as e, money, bytes, date, list, groupedList, periods, orderStates, soldOut, safeUrl, createApi, fetchNotices, routeFromHash,canPurchase,hasActiveSubscription} from './core.mjs?v=ui-flow-1';
|
||||
const settings = window.fucSettings || {};
|
||||
const root = document.querySelector('#app');
|
||||
const preview = settings.preview === true;
|
||||
@@ -24,6 +24,7 @@ const link = (text, href, klass = '') => `<a class="${klass}" href="${e(href)}">
|
||||
const empty=(text='暂无记录',action='')=>`<div class="native-empty">${e(text)}${action?`<p>${action}</p>`:''}</div>`;
|
||||
const card = (title, body, klass = '') => `<section class="card ${klass}"><div class="card-body">${title ? `<h3 class="card-title">${title}</h3>` : ''}${body}</div></section>`;
|
||||
const getRoute = () => routeFromHash(location.hash);
|
||||
const orderListRoute = page => page>1 ? `orders?page=${page}` : 'orders';
|
||||
const go = route => { if (location.hash === `#/${route}`) renderRoute(); else location.hash = `/${route}`; };
|
||||
const toast = (message,type='success') => notify(message,type);
|
||||
const waitFeedback = ms => new Promise(resolve=>setTimeout(resolve,ms));
|
||||
@@ -55,20 +56,23 @@ function shell(name,content,activePage=name){
|
||||
document.title=`${titles[name]?.[0]||(name==='faq'?'常见问题':name)} — ${settings.title||'福云'}`;if(name==='dashboard')void paintNativeChart().catch(()=>{});
|
||||
}
|
||||
const secondary=(name,data,extra={})=>nativeSecondary(name,{user,sub,data,period:cycle,page,config,richText,...extra});
|
||||
async function planPage(name){
|
||||
async function planPage(name,query){
|
||||
await prepareNativeTemplates(name);
|
||||
if(name==='orders'){
|
||||
const orders=list(await api('user/order/fetch'));
|
||||
const pageSize=20,orderTotalPages=Math.max(1,Math.ceil(orders.length/pageSize));
|
||||
const orderPage=Math.min(page,orderTotalPages);
|
||||
const requestedPage=Number(query?.get('page'));
|
||||
const orderPage=Number.isSafeInteger(requestedPage)&&requestedPage>0
|
||||
? Math.min(requestedPage,orderTotalPages) : 1;
|
||||
const data=orders.slice((orderPage-1)*pageSize,orderPage*pageSize);
|
||||
return {data,html:secondary(name,data,{page:orderPage,orderTotalPages})};
|
||||
return {data,page:orderPage,html:secondary(name,data,{page:orderPage,orderTotalPages})};
|
||||
}
|
||||
if(name==='plans'){
|
||||
const [plans,invite]=await Promise.all([api('user/plan/fetch'),api('user/invite/fetch').catch(()=>null)]);
|
||||
const data=[...list(plans)];
|
||||
if(sub.plan_id!=null&&!data.some(plan=>String(plan.id)===String(sub.plan_id))){
|
||||
const own=await api('user/plan/fetch?id='+encodeURIComponent(sub.plan_id)).catch(()=>null);
|
||||
const active=(sub.expired_at==null||Number(sub.expired_at)>Date.now()/1000)&&Number(sub.transfer_enable)>0&&!user.banned;
|
||||
const active=hasActiveSubscription(user);
|
||||
if(own&&(active||(own.show!==false&&own.show!==0))){
|
||||
const plan=active?own:{...own,reset_price:null};
|
||||
if(Object.keys(periods).some(period=>canPurchase(plan,user,period)))data.push(plan);
|
||||
@@ -80,17 +84,35 @@ async function planPage(name){
|
||||
}
|
||||
async function renderRoute() {
|
||||
const ticket=beginPageProgress();
|
||||
try {await renderPage();} finally {finishPageProgress(ticket);}
|
||||
const seq=routeSequence+1;
|
||||
try {
|
||||
await renderPage();
|
||||
} catch (error) {
|
||||
if(seq!==routeSequence)return;
|
||||
disposeInteractions(root);
|
||||
root.innerHTML=card('',`<div class="alert" role="alert">${e(error.message)}</div>${btn('重新加载','retry')}`);
|
||||
} finally {
|
||||
finishPageProgress(ticket);
|
||||
}
|
||||
}
|
||||
async function renderPage() {
|
||||
clearTimeout(paymentTimer);paymentTimer=null;captcha?.dispose();captcha=null;cardPayment?.dispose();cardPayment=null;
|
||||
const seq = ++routeSequence, {name,id,query} = getRoute(); selectedTicket = null; selectedOrder = null; selectedPlan = null;
|
||||
if(name==='orders'&&/^#\/?(?:myplan|subscribe)(?:\?|$)/.test(location.hash))history.replaceState(null,'','#/orders');
|
||||
if (name === 'demo') {if (preview) {sessionStorage.setItem(storageKey,'Bearer local-preview-only');go(['invite','knowledge','tickets'].includes(getRoute().query.get('next')) ? getRoute().query.get('next') : 'dashboard');} else go('login');return;}
|
||||
if (name === 'home') {try {const plans = list(await api('guest/plan/fetch'));if(seq===routeSequence){await prepareNativeMode('home');if(seq===routeSequence)homepage(plans,plans.length?'':'暂无公开展示的套餐');}} catch(error) {if(seq===routeSequence){await prepareNativeMode('home');if(seq===routeSequence)homepage([],error.message);}}return;}
|
||||
if (name === 'home') {
|
||||
const [result]=await Promise.all([
|
||||
api('guest/plan/fetch').then(list).then(plans=>({plans})).catch(error=>({plans:[],error:error.message})),
|
||||
prepareNativeTemplates('home'),prepareNativeMode('home')
|
||||
]);
|
||||
if(seq===routeSequence)homepage(result.plans,result.error||(result.plans.length?'':'暂无公开展示的套餐'));
|
||||
return;
|
||||
}
|
||||
const auth = ['login','register','forget','reset'].includes(name);
|
||||
if(auth){await prepareNativeMode('auth',name);if(seq!==routeSequence)return;}
|
||||
if (!token() && !auth) {go('login'); return;}
|
||||
if(auth){
|
||||
await Promise.all([prepareNativeTemplates(name),prepareNativeMode('auth',name)]);
|
||||
if(seq!==routeSequence)return;
|
||||
}
|
||||
if (name==='login'&&getRoute().query.has('verify')) {
|
||||
const verify=getRoute().query.get('verify'),redirect=getRoute().query.get('redirect');
|
||||
history.replaceState(null,'',location.pathname+location.search+'#/login');
|
||||
@@ -98,15 +120,27 @@ async function renderPage() {
|
||||
catch(error){if(seq===routeSequence)authPage('login',error.message);}return;
|
||||
}
|
||||
if (auth) {authPage(name); return;}
|
||||
const pageTemplate = name==='dashboard'?'index':name==='knowledge'&&id?'article':name;
|
||||
const requiredTemplates = ['header','footer'];
|
||||
if(Object.hasOwn(titles,name)||name==='faq')requiredTemplates.push(pageTemplate);
|
||||
if(name==='invite')requiredTemplates.push('afflog');
|
||||
await prepareNativeTemplates(...requiredTemplates);
|
||||
if(seq!==routeSequence)return;
|
||||
try {
|
||||
const info = await Promise.all([api('user/info'),api('user/getSubscribe'),api('user/comm/config'),api('user/vip').catch(()=>null)]);
|
||||
if (seq !== routeSequence) return; [user,sub] = info;config={...config,...info[2]};
|
||||
if(info[3]?.enabled===true){user.vip=info[3];user.discount=info[3].discount_percent;}
|
||||
let content, nextData=[], nextTicket=null, nextOrder=null, nextPlan=null, nextMethods=[], checkoutBackground=null;
|
||||
if(name==='dashboard'){const [notices,traffic]=await Promise.all([fetchNotices(api,{dashboard:true}),api('user/stat/getTrafficLog').then(list).catch(()=>null)]);content=nativeDashboard(user,sub,list(notices),settings.title||'福云',richText,traffic,settings.nyanpasuDownloadOrigin);}
|
||||
else if(name==='notices')content=secondary('notices',await fetchNotices(api));
|
||||
let content, nextData=[], nextTicket=null, nextOrder=null, nextPlan=null, nextMethods=[], checkoutBackground=null, returnTo=null, orderPage=null;
|
||||
if(name==='dashboard'){
|
||||
const [news,traffic]=await Promise.all([
|
||||
fetchNotices(api,{dashboard:true}),api('user/stat/getTrafficLog').then(list).catch(()=>null)
|
||||
]);
|
||||
content=nativeDashboard(user,sub,news.notices,settings.title||'福云',richText,traffic,settings.nyanpasuDownloadOrigin,news.unavailable);
|
||||
}
|
||||
else if(name==='notices')content=secondary('notices',(await fetchNotices(api)).notices);
|
||||
else if(name==='plans'||name==='orders'){
|
||||
const result=await planPage(name);nextData=result.data;content=result.html;
|
||||
const result=await planPage(name,query);nextData=result.data;content=result.html;
|
||||
orderPage=result.page;
|
||||
}
|
||||
else if(name==='purchase'&&id){
|
||||
const period=query.get('period'),from='plans';
|
||||
@@ -122,7 +156,7 @@ async function renderPage() {
|
||||
const origin=query.get('from'),from=origin==='myplan'?'orders':origin;
|
||||
const [order,background]=await Promise.all([
|
||||
api(`user/order/detail?trade_no=${encodeURIComponent(id)}`),
|
||||
['plans','orders'].includes(from)?planPage(from).catch(()=>null):null
|
||||
['plans','orders'].includes(from)?planPage(from,query).catch(()=>null):null
|
||||
]);
|
||||
nextOrder=order;
|
||||
const [methods,discountBreakdown]=await Promise.all([
|
||||
@@ -133,6 +167,7 @@ async function renderPage() {
|
||||
]);
|
||||
nextMethods=list(methods);
|
||||
checkoutBackground=background?from:null;
|
||||
if(checkoutBackground==='orders')returnTo=orderListRoute(background.page);
|
||||
content=(background?.html||'')+secondary('checkout',order,{methods:nextMethods,discountBreakdown,asModal:!!checkoutBackground});
|
||||
}
|
||||
else if(name==='profile'){content=secondary(name,null,{sessions:list(await api('user/getActiveSession'))});}
|
||||
@@ -148,11 +183,12 @@ async function renderPage() {
|
||||
await prepareNativeMode('user',activePage);
|
||||
if(seq!==routeSequence)return;
|
||||
pageData=nextData;selectedTicket=nextTicket;selectedOrder=nextOrder;selectedPlan=nextPlan;paymentMethods=nextMethods;
|
||||
if(orderPage!=null)history.replaceState(null,'','#/'+orderListRoute(orderPage));
|
||||
shell(name,content,activePage);
|
||||
if(checkoutBackground){
|
||||
const modal=root.querySelector(name==='purchase'?'#fuc-purchase-modal':'#fuc-checkout-modal');
|
||||
window.jQuery(modal).one('hidden.bs.modal',()=>{
|
||||
if(seq===routeSequence)location.replace('#/'+checkoutBackground);
|
||||
if(seq===routeSequence)location.replace('#/'+(returnTo||checkoutBackground));
|
||||
});
|
||||
openModal('#'+modal.id);
|
||||
}
|
||||
@@ -187,7 +223,12 @@ root.addEventListener('click',async event => {
|
||||
if (action === 'menu') {if(button.classList.contains('sidenav-overlay')&&!document.body.classList.contains('menu-open'))return;toggleMenu(root);return;}
|
||||
if (action === 'mode') {const mode=document.documentElement.dataset.color==='dark'?'light':'dark';localStorage.setItem('fuc_color',mode);localStorage.setItem('fuc_themeMod',mode);location.reload();return;}
|
||||
if (action === 'logout') {clearAuth();user={};sub={};go('login');return;}
|
||||
if (action === 'prev' || action === 'next') {page = Math.max(1,page + (action === 'next' ? 1 : -1)); renderRoute(); return;}
|
||||
if (action === 'prev' || action === 'next') {
|
||||
if(button.dataset.orderPage){go(orderListRoute(Number(button.dataset.orderPage)));return;}
|
||||
page = Math.max(1,page + (action === 'next' ? 1 : -1));
|
||||
renderRoute();
|
||||
return;
|
||||
}
|
||||
if (action === 'retry') {renderRoute(); return;}
|
||||
if (action === 'refresh-payment') {
|
||||
const order=selectedOrder;
|
||||
@@ -258,13 +299,19 @@ root.addEventListener('submit',async event => {
|
||||
} catch (error) {if(seq===routeSequence){if(['login','register','forget','reset-code'].includes(type))void authFeedback(error.message||'操作失败','','error');else toast(error.message || '操作失败','error');}}
|
||||
finally {loading=false;if(button.isConnected){button.disabled=false;button.textContent=oldLabel;}}
|
||||
});
|
||||
window.addEventListener('hashchange',()=>{page=1;cycle='';const hash=location.hash;renderRoute().then(()=>{if(location.hash===hash)window.scrollTo(0,0);});});
|
||||
window.addEventListener('hashchange',()=>{
|
||||
page=1;
|
||||
cycle='';
|
||||
const rendered=renderRoute();
|
||||
const seq=routeSequence;
|
||||
void rendered.then(()=>{if(seq===routeSequence)window.scrollTo(0,0);});
|
||||
});
|
||||
document.documentElement.dataset.color = localStorage.getItem('fuc_themeMod')==='system'?(matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'):localStorage.getItem('fuc_color') || 'light';
|
||||
applyPalette();
|
||||
async function start() {
|
||||
const ticket=beginPageProgress();
|
||||
try {
|
||||
try {await Promise.all([nativeReady,interactionsReady]);}
|
||||
try {await interactionsReady;}
|
||||
catch {
|
||||
root.innerHTML='<div class="alert" role="alert">原版主题资源加载失败,请刷新或核对主题包是否完整。</div>';
|
||||
return;
|
||||
@@ -285,7 +332,7 @@ root.addEventListener('input',event=>{if(event.target.id!=='searchbar')return;co
|
||||
|
||||
function subscriptionUrl(client){return makeSubscriptionUrl(sub.subscribe_url||'',client||'general');}
|
||||
|
||||
matchMedia('(prefers-color-scheme: dark)').addEventListener('change',event=>{if(localStorage.getItem('fuc_themeMod')==='system'){document.documentElement.dataset.color=event.matches?'dark':'light';localStorage.setItem('fuc_color',document.documentElement.dataset.color);if(document.body.dataset.nativeMode==='user')nativeMode('user');}});
|
||||
matchMedia('(prefers-color-scheme: dark)').addEventListener('change',event=>{if(localStorage.getItem('fuc_themeMod')==='system'){document.documentElement.dataset.color=event.matches?'dark':'light';localStorage.setItem('fuc_color',document.documentElement.dataset.color);syncNativeColor();}});
|
||||
|
||||
window.addEventListener('scroll',()=>{document.getElementById('navbar')?.classList.toggle('nav-sticky',window.scrollY>=50);},{passive:true});
|
||||
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
<!doctype html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="utf-8">
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1">
|
||||
<meta name="referrer" content="no-referrer">
|
||||
<title>福云地址导航</title>
|
||||
<link id="brand-icon" rel="icon" href="./native/images/brand/fuc-mark.svg?v=2" type="image/svg+xml" sizes="any">
|
||||
<style>
|
||||
:root {
|
||||
color-scheme: dark;
|
||||
--page: #171426;
|
||||
--page-wash: #241b3a;
|
||||
--panel: #201c34;
|
||||
--ink: #f6f1ff;
|
||||
--muted: #bbb2d0;
|
||||
--line: #38304d;
|
||||
--accent: #c6b7ff;
|
||||
--fastest: #b6ff40;
|
||||
--notice-warm-tone: #f4d36c;
|
||||
--action: #7256df;
|
||||
--tint: #332851;
|
||||
--shadow: rgb(0 0 0 / 20%);
|
||||
font: 16px/1.55 system-ui, -apple-system, "PingFang SC", "Microsoft YaHei", sans-serif;
|
||||
}
|
||||
|
||||
*, *::before, *::after { box-sizing: border-box; }
|
||||
|
||||
body {
|
||||
min-height: 100vh;
|
||||
margin: 0;
|
||||
color: var(--ink);
|
||||
background: linear-gradient(180deg, var(--page-wash), var(--page) 360px);
|
||||
}
|
||||
|
||||
a { color: inherit; text-decoration: none; }
|
||||
button { color: inherit; font: inherit; cursor: pointer; }
|
||||
:is(a, button):focus-visible,
|
||||
.entry:has(input:focus-visible) { outline: 2px solid var(--accent); outline-offset: 4px; }
|
||||
|
||||
.wrap { width: min(740px, calc(100% - 48px)); margin-inline: auto; }
|
||||
|
||||
main { padding-block: clamp(32px, 6vw, 64px) 40px; }
|
||||
h1 { margin: 0 0 24px; font-size: clamp(32px, 5vw, 48px); line-height: 1.18; letter-spacing: -.04em; }
|
||||
.email-notice {
|
||||
display: grid;
|
||||
grid-template-columns: auto minmax(0, 1fr);
|
||||
align-items: start;
|
||||
gap: 12px;
|
||||
margin-bottom: 16px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 12px;
|
||||
background: color-mix(in srgb, var(--notice-warm-tone) 5%, var(--page));
|
||||
font-size: 15px;
|
||||
}
|
||||
.email-notice-icon {
|
||||
width: 19px;
|
||||
height: 19px;
|
||||
margin-top: 2px;
|
||||
color: var(--accent);
|
||||
}
|
||||
.email-notice p { margin: 0; }
|
||||
.email-notice .email-detail { margin-top: 4px; color: var(--muted); font-size: 14px; line-height: 1.65; text-wrap: pretty; }
|
||||
.copy-control { position: relative; display: inline-block; }
|
||||
.copy-email {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
padding: 0;
|
||||
border: 0;
|
||||
background: none;
|
||||
color: var(--accent);
|
||||
font-weight: 700;
|
||||
text-underline-offset: 4px;
|
||||
}
|
||||
.copy-email:hover { text-decoration: underline; }
|
||||
.copy-feedback {
|
||||
position: absolute;
|
||||
inset-inline-end: 0;
|
||||
inset-block-end: calc(100% + 6px);
|
||||
z-index: 1;
|
||||
width: max-content;
|
||||
max-width: 100%;
|
||||
padding: 3px 8px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 6px;
|
||||
background: var(--panel);
|
||||
box-shadow: 0 4px 12px var(--shadow);
|
||||
font-size: 12px;
|
||||
pointer-events: none;
|
||||
}
|
||||
.copy-feedback:empty { opacity: 0; }
|
||||
|
||||
.entries {
|
||||
padding: clamp(16px, 4vw, 28px);
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 18px;
|
||||
background: var(--panel);
|
||||
box-shadow: 0 18px 48px var(--shadow);
|
||||
}
|
||||
|
||||
.entries h2 { margin: 0 0 16px; font-size: 18px; }
|
||||
.routes { display: grid; gap: 8px; margin: 0; padding: 0; border: 0; min-width: 0; }
|
||||
|
||||
.entry {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) auto auto;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
min-height: 60px;
|
||||
padding: 12px 16px;
|
||||
border: 1px solid var(--line);
|
||||
border-radius: 10px;
|
||||
cursor: pointer;
|
||||
transition: border-color .16s ease, background-color .16s ease;
|
||||
}
|
||||
|
||||
.entry:hover { background: color-mix(in srgb, var(--tint) 50%, var(--panel)); }
|
||||
.entry:has(input:checked) { background: var(--tint); border-color: var(--accent); }
|
||||
.entry input { grid-area: 1 / 3; width: 18px; height: 18px; margin: 0; accent-color: var(--accent); }
|
||||
.entry-info { grid-area: 1 / 1; display: flex; align-items: baseline; gap: 12px; }
|
||||
.entry .latency { grid-area: 1 / 2; color: var(--muted); font-size: 12px; font-variant-numeric: tabular-nums; white-space: nowrap; }
|
||||
.entry .latency[data-fastest] { color: var(--fastest); font-weight: 700; }
|
||||
|
||||
.entry strong { overflow-wrap: anywhere; font-size: 17px; }
|
||||
.entry small { color: var(--muted); font-size: 13px; }
|
||||
.entry:has(input:checked) small { color: var(--accent); }
|
||||
|
||||
.panel-footer {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
min-height: 36px;
|
||||
margin-block: 12px;
|
||||
color: var(--muted);
|
||||
font-size: 13px;
|
||||
}
|
||||
.recheck { border: 0; background: none; padding: 6px 0; color: var(--accent); white-space: nowrap; }
|
||||
.recheck:hover { text-decoration: underline; }
|
||||
.recheck:disabled { opacity: .55; cursor: wait; }
|
||||
.enter { display: grid; place-items: center; min-height: 46px; border-radius: 9px; font-size: 14px; }
|
||||
.enter { padding-inline: 12px; color: #fff; background: var(--action); font-weight: 700; }
|
||||
.enter:hover { filter: brightness(1.1); }
|
||||
|
||||
@media (max-width: 520px) {
|
||||
.wrap { width: calc(100% - 32px); }
|
||||
h1 { margin-bottom: 18px; }
|
||||
.entry { gap: 10px; padding: 10px 12px; }
|
||||
.entry-info { flex-direction: column; gap: 1px; }
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.entry { transition: none; }
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<main class="wrap">
|
||||
<h1>福云地址导航</h1>
|
||||
<aside class="email-notice" aria-label="备用网址获取方式">
|
||||
<svg class="email-notice-icon" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true">
|
||||
<rect x="2.5" y="5" width="19" height="14" rx="2"/>
|
||||
<path d="m3.5 6.5 8.5 7 8.5-7"/>
|
||||
</svg>
|
||||
<div>
|
||||
<p>务必,请收藏我们的邮箱
|
||||
<span class="copy-control">
|
||||
<button class="copy-email" type="button" aria-label="复制邮箱地址 [email protected]">
|
||||
[email protected]
|
||||
<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" aria-hidden="true">
|
||||
<path d="M8 8h9l3 3v10H8V8Z M15 8V3H3v13h5"/>
|
||||
</svg>
|
||||
</button>
|
||||
<span class="copy-feedback" role="status"></span>
|
||||
</span>。
|
||||
</p>
|
||||
<p class="email-detail">导航地址也被墙时,可发送任意邮件至该邮箱,会自动回复最新地址,这是最保险的防失联方式。</p>
|
||||
</div>
|
||||
</aside>
|
||||
<section class="entries" aria-labelledby="entry-title">
|
||||
<h2 id="entry-title">访问入口</h2>
|
||||
<fieldset class="routes" aria-labelledby="entry-title">
|
||||
<!-- project-domains:start -->
|
||||
<label class="entry" data-role="primary">
|
||||
<input type="radio" name="route" value="https://xn--9kqy16h.com/" data-domainhub-code="fuc.main-cn">
|
||||
<span class="entry-info"><strong>福云.com</strong><small>永久主域名(需翻墙)</small></span>
|
||||
<span class="latency">—</span>
|
||||
</label>
|
||||
<label class="entry" data-role="primary">
|
||||
<input type="radio" name="route" value="https://fuuu.cloud/" data-domainhub-code="fuc.main-en">
|
||||
<span class="entry-info"><strong>fuuu.cloud</strong><small>永久主域名(需翻墙)</small></span>
|
||||
<span class="latency">—</span>
|
||||
</label>
|
||||
<label class="entry" data-role="direct">
|
||||
<input type="radio" name="route" value="https://fu99.cloud/" data-domainhub-code="fuc.direct-current" checked>
|
||||
<span class="entry-info"><strong>fu99.cloud</strong><small>免翻墙域名</small></span>
|
||||
<span class="latency">—</span>
|
||||
</label>
|
||||
<label class="entry" data-role="direct">
|
||||
<input type="radio" name="route" value="https://fuuu.online/" data-domainhub-code="fuc.fuuu-online">
|
||||
<span class="entry-info"><strong>fuuu.online</strong><small>免翻墙域名</small></span>
|
||||
<span class="latency">—</span>
|
||||
</label>
|
||||
<label class="entry" data-role="direct">
|
||||
<input type="radio" name="route" value="https://xn--123-9i9dj97q.com/" data-domainhub-code="fuc.direct-cn-backup">
|
||||
<span class="entry-info"><strong>福云123.com</strong><small>免翻墙域名(疑似被墙)</small></span>
|
||||
<span class="latency">—</span>
|
||||
</label>
|
||||
<!-- project-domains:end -->
|
||||
</fieldset>
|
||||
<div class="panel-footer">
|
||||
<span id="route-status" role="status">已选择 fu99.cloud</span>
|
||||
<button class="recheck" type="button">重新检测</button>
|
||||
</div>
|
||||
<div class="actions">
|
||||
<a id="enter" class="enter" href="/#/register">立即进入 →</a>
|
||||
</div>
|
||||
</section>
|
||||
</main>
|
||||
<script>
|
||||
const panel = document.querySelector('.entries');
|
||||
const routes = document.querySelector('.routes');
|
||||
const status = document.querySelector('#route-status');
|
||||
const enter = document.querySelector('#enter');
|
||||
const recheck = document.querySelector('.recheck');
|
||||
const invite = new URLSearchParams(location.search).get('code');
|
||||
const entries = [...routes.querySelectorAll('input[name="route"]')].map(input => {
|
||||
const row = input.closest('label');
|
||||
return { input, row, result: row.querySelector('.latency') };
|
||||
});
|
||||
const isLocal = location.hostname === 'xb.loc';
|
||||
const probePath = '/api/v1/guest/comm/config';
|
||||
const probeTimeoutMs = 3000;
|
||||
let manualSelection = false;
|
||||
let testStatus = '';
|
||||
|
||||
function selectRoute() {
|
||||
const selected = routes.querySelector('input:checked');
|
||||
const origin = isLocal ? location.origin : new URL(selected.value).origin;
|
||||
const code = invite && /^[A-Za-z0-9_-]{1,64}$/.test(invite) ? '?code=' + encodeURIComponent(invite) : '';
|
||||
enter.href = origin + '/#/register' + code;
|
||||
const name = selected.closest('label').querySelector('strong').textContent;
|
||||
status.textContent = ['已选择 ' + name, testStatus].filter(Boolean).join(' · ');
|
||||
}
|
||||
|
||||
async function measure(entry, sample) {
|
||||
const url = new URL(probePath, isLocal ? location.origin : entry.input.value);
|
||||
url.searchParams.set('nav_probe', sample);
|
||||
const controller = new AbortController();
|
||||
const started = performance.now();
|
||||
const timeout = setTimeout(() => controller.abort(), probeTimeoutMs);
|
||||
try {
|
||||
const response = await fetch(url, {
|
||||
mode: 'cors', cache: 'no-store', credentials: 'omit', redirect: 'error',
|
||||
referrerPolicy: 'no-referrer', signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) throw new Error('Probe failed');
|
||||
const { data } = await response.json();
|
||||
if (typeof data?.app_name !== 'string') throw new Error('Invalid XB response');
|
||||
const elapsed = performance.now() - started;
|
||||
entry.outcome = 'success';
|
||||
entry.result.textContent = Math.max(1, Math.round(elapsed)) + ' ms';
|
||||
return { entry, elapsed };
|
||||
} catch {
|
||||
entry.outcome = controller.signal.aborted ? 'timeout' : 'failure';
|
||||
entry.result.textContent = entry.outcome === 'timeout' ? '超时' : '不可用';
|
||||
return null;
|
||||
} finally {
|
||||
clearTimeout(timeout);
|
||||
}
|
||||
}
|
||||
|
||||
async function testRoutes() {
|
||||
if (recheck.disabled) return;
|
||||
recheck.disabled = true;
|
||||
panel.setAttribute('aria-busy', 'true');
|
||||
testStatus = isLocal ? '本地测速中…' : '正在测速…';
|
||||
selectRoute();
|
||||
for (const { result } of entries) {
|
||||
result.removeAttribute('data-fastest');
|
||||
result.textContent = '测速中…';
|
||||
}
|
||||
try {
|
||||
const round = Date.now().toString(36);
|
||||
const results = await Promise.all(entries.map((entry, index) => measure(entry, round + '-' + index)));
|
||||
const ranked = results.filter(Boolean).sort((a, b) => a.elapsed - b.elapsed);
|
||||
const measured = new Set(ranked.map(({ entry }) => entry));
|
||||
const ordered = [...ranked.map(({ entry }) => entry), ...entries.filter(entry => !measured.has(entry))];
|
||||
const focused = document.activeElement;
|
||||
for (const { row } of ordered) {
|
||||
if (row.dataset.role !== 'primary') routes.append(row);
|
||||
}
|
||||
if (routes.contains(focused) && document.activeElement !== focused) focused.focus({ preventScroll: true });
|
||||
const fastest = ranked[0];
|
||||
if (fastest) {
|
||||
fastest.entry.result.setAttribute('data-fastest', '');
|
||||
if (!manualSelection) fastest.entry.input.checked = true;
|
||||
}
|
||||
testStatus = fastest ? (isLocal ? '本地测速完成' : '测速完成') : '未测得可用入口';
|
||||
if (!isLocal) {
|
||||
const outcomes = Object.fromEntries(entries.map(({ input, outcome }) => [input.dataset.domainhubCode, outcome]));
|
||||
fetch('/_nav-stats', {
|
||||
method: 'POST', body: JSON.stringify(outcomes), credentials: 'omit',
|
||||
keepalive: true, referrerPolicy: 'no-referrer', redirect: 'error',
|
||||
}).catch(() => {});
|
||||
}
|
||||
} finally {
|
||||
recheck.disabled = false;
|
||||
panel.removeAttribute('aria-busy');
|
||||
selectRoute();
|
||||
}
|
||||
}
|
||||
|
||||
routes.addEventListener('click', event => {
|
||||
if (event.target.matches('input[name="route"]')) manualSelection = true;
|
||||
});
|
||||
routes.addEventListener('change', () => {
|
||||
manualSelection = true;
|
||||
selectRoute();
|
||||
});
|
||||
recheck.addEventListener('click', testRoutes);
|
||||
selectRoute();
|
||||
testRoutes();
|
||||
</script>
|
||||
<script type="module">
|
||||
import { copyText } from './clipboard.mjs';
|
||||
|
||||
const email = document.querySelector('.copy-email');
|
||||
const feedback = document.querySelector('.copy-feedback');
|
||||
let feedbackTimer;
|
||||
email.addEventListener('click', async () => {
|
||||
clearTimeout(feedbackTimer);
|
||||
feedback.textContent = '';
|
||||
try {
|
||||
await copyText(email.textContent.trim());
|
||||
feedback.textContent = '已复制';
|
||||
feedbackTimer = setTimeout(() => { feedback.textContent = ''; }, 1600);
|
||||
} catch {
|
||||
feedback.textContent = '复制失败,请选中邮箱地址手动复制。';
|
||||
}
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
+30
-27
@@ -19,10 +19,15 @@ export function trafficSummary(sub,logs=null,now=new Date()) {
|
||||
return {remaining:Math.max(0,total-used),today,history:today===null?used:Math.max(0,used-countedToday),series:[pct(Math.max(0,total-used)),pct(Math.max(0,countedUsed-Math.min(countedUsed,countedToday))),pct(Math.min(countedUsed,countedToday))]};
|
||||
}
|
||||
export function soldOut(plan) { const stock = plan.capacity_remaining ?? plan.capacity_limit; return stock === 0 || stock === '0' || (typeof stock === 'string' && !/^\d+$/.test(stock)); }
|
||||
export function hasActiveSubscription(user) {
|
||||
return user.plan_id!=null && !user.banned && Number(user.transfer_enable)>0
|
||||
&& (user.expired_at===null || Number(user.expired_at)>Date.now()/1000);
|
||||
}
|
||||
|
||||
export function canPurchase(plan,user,period) {
|
||||
if(!plan||!Object.hasOwn(periods,period)||plan[period]==null)return false;
|
||||
const owner=user.plan_id!=null&&String(user.plan_id)===String(plan.id);
|
||||
if(period==='reset_price')return owner;
|
||||
if(period==='reset_price')return owner&&hasActiveSubscription(user);
|
||||
if(owner)return plan.renew!==false&&plan.renew!==0;
|
||||
return plan.show!==false&&plan.show!==0&&plan.sell!==false&&plan.sell!==0&&!soldOut(plan);
|
||||
}
|
||||
@@ -53,34 +58,32 @@ const isDashboardOnlyNotice = notice =>
|
||||
Array.isArray(notice.tags) && notice.tags.includes('dashboard-only');
|
||||
|
||||
export async function fetchNotices(api, {dashboard = false} = {}) {
|
||||
const fetchPage = current => api(`user/notice/fetch?current=${current}`, undefined, 'GET', {keepEnvelope:true});
|
||||
const first = await fetchPage(1);
|
||||
const notices = list(first);
|
||||
const pages = Number.isSafeInteger(first?.total) && notices.length
|
||||
? Math.ceil(first.total / notices.length)
|
||||
: 1;
|
||||
const byId = new Map(notices.map(notice => [notice.id, notice]));
|
||||
const dashboardNotices = () => {
|
||||
const pinned = [...byId.values()].find(isDashboardOnlyNotice);
|
||||
const latest = [...byId.values()].find(notice => !isDashboardOnlyNotice(notice));
|
||||
return {pinned, latest};
|
||||
};
|
||||
|
||||
for (let current = 2; current <= pages; current++) {
|
||||
if (dashboard) {
|
||||
const {pinned, latest} = dashboardNotices();
|
||||
if (pinned && latest) return [pinned, latest];
|
||||
const byId = new Map();
|
||||
let pages = 1;
|
||||
let unavailable = false;
|
||||
for (let current = 1; current <= pages; current++) {
|
||||
try {
|
||||
const result = await api(`user/notice/fetch?current=${current}`, undefined, 'GET', {keepEnvelope:true});
|
||||
const notices = list(result);
|
||||
if (current===1 && Number.isSafeInteger(result?.total) && notices.length) {
|
||||
pages = Math.ceil(result.total / notices.length);
|
||||
}
|
||||
for (const notice of notices) byId.set(notice.id, notice);
|
||||
if (dashboard) {
|
||||
const collected = [...byId.values()];
|
||||
if (collected.some(isDashboardOnlyNotice) && collected.some(notice=>!isDashboardOnlyNotice(notice)))break;
|
||||
}
|
||||
} catch(error) {
|
||||
if(!dashboard)throw error;
|
||||
unavailable = true;
|
||||
break;
|
||||
}
|
||||
for (const notice of list(await fetchPage(current))) byId.set(notice.id, notice);
|
||||
}
|
||||
|
||||
if (dashboard) {
|
||||
const {pinned, latest} = dashboardNotices();
|
||||
if (pinned) return [pinned, latest ?? null];
|
||||
return [...byId.values()].slice(0, 2);
|
||||
}
|
||||
|
||||
return [...byId.values()].filter(notice => !isDashboardOnlyNotice(notice));
|
||||
const notices = [...byId.values()];
|
||||
if (!dashboard) return {notices:notices.filter(notice=>!isDashboardOnlyNotice(notice)), unavailable};
|
||||
const pinned = notices.find(isDashboardOnlyNotice);
|
||||
const latest = notices.find(notice=>!isDashboardOnlyNotice(notice));
|
||||
return {notices:pinned || unavailable ? [pinned,latest] : notices.slice(0,2), unavailable};
|
||||
}
|
||||
|
||||
export function paymentResult(result) {
|
||||
|
||||
+80
-7
@@ -43,15 +43,88 @@
|
||||
padding-inline-end: min(160px, 44vw);
|
||||
}
|
||||
|
||||
:root[data-fuc-support-palette] body[data-native-mode='user'].modal-open > .woot-widget-holder {
|
||||
visibility: hidden;
|
||||
/* Keep SDK controls in stable layers. Its .woot--hide otherwise sends them
|
||||
behind the page and below the viewport before the exit animation finishes.
|
||||
Keep support above content and below business modals. */
|
||||
:root[data-fuc-support-palette] body > .woot-widget-holder {
|
||||
z-index: 1000 !important;
|
||||
transition: opacity .2s ease, transform .2s ease !important;
|
||||
}
|
||||
|
||||
/* The SDK's launcher z-index otherwise covers the mobile navigation drawer. */
|
||||
:root[data-fuc-support-palette] body[data-native-mode='user'].menu-open > :is(#cw-bubble-holder, .woot-widget-holder) {
|
||||
visibility: hidden;
|
||||
:root[data-fuc-support-palette] #cw-bubble-holder > button.woot-widget-bubble {
|
||||
z-index: 1001 !important;
|
||||
top: auto !important;
|
||||
bottom: calc(var(--xb-support-bottom-gap, 24px) + env(safe-area-inset-bottom, 0px)) !important;
|
||||
transition: opacity .15s ease, transform .2s ease, background-color .15s ease !important;
|
||||
}
|
||||
|
||||
:root[data-fuc-support-palette] body[data-native-mode='user']:not(.modal-open):has(> .woot-widget-holder:not(.woot--hide)) #app .scroll-top {
|
||||
visibility: hidden;
|
||||
:root[data-fuc-support-palette] #cw-bubble-holder > .woot-elements--right {
|
||||
right: calc(20px + env(safe-area-inset-right, 0px));
|
||||
}
|
||||
|
||||
/* Hidden controls must never catch clicks during rapid open/close reversals. */
|
||||
:root[data-fuc-support-palette] body > .woot-widget-holder.woot--hide,
|
||||
:root[data-fuc-support-palette] #cw-bubble-holder > button.woot--hide {
|
||||
visibility: hidden !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
/* On short screens the public widget can reach the fixed navigation (1030). */
|
||||
:root[data-fuc-support-palette] body[data-native-mode='home'] > .woot-widget-holder:not(.has-unread-view) {
|
||||
z-index: 1035 !important;
|
||||
}
|
||||
|
||||
@media (min-width: 668px) {
|
||||
:root[data-fuc-support-palette] body > .woot-widget-holder {
|
||||
top: auto !important;
|
||||
bottom: calc(var(--xb-support-bottom-gap, 24px) + var(--xb-support-button-height, 48px) + var(--xb-support-panel-gap, 12px) + env(safe-area-inset-bottom, 0px)) !important;
|
||||
min-height: 0 !important;
|
||||
max-height: min(640px, calc(100vh - 100px - env(safe-area-inset-bottom, 0px))) !important;
|
||||
max-height: min(640px, calc(100dvh - 100px - env(safe-area-inset-bottom, 0px))) !important;
|
||||
max-width: calc(100vw - 40px);
|
||||
}
|
||||
|
||||
:root[data-fuc-support-palette] body > .woot-widget-holder.woot-elements--right {
|
||||
right: calc(20px + env(safe-area-inset-right, 0px));
|
||||
}
|
||||
}
|
||||
|
||||
/* The SDK includes 667px in both mobile and desktop rules. Choose one layout. */
|
||||
@media (max-width: 667px) {
|
||||
:root[data-fuc-support-palette] body > .woot-widget-holder:not(.has-unread-view) {
|
||||
z-index: 1035 !important;
|
||||
inset: 0 !important;
|
||||
width: 100% !important;
|
||||
height: 100vh !important;
|
||||
height: 100dvh !important;
|
||||
min-height: 0 !important;
|
||||
max-height: 100vh !important;
|
||||
max-height: 100dvh !important;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
:root[data-fuc-support-palette] body > .woot-widget-holder.has-unread-view {
|
||||
top: auto !important;
|
||||
bottom: 84px !important;
|
||||
}
|
||||
|
||||
:root[data-fuc-support-palette] #cw-bubble-holder > button.woot--close {
|
||||
visibility: hidden !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
}
|
||||
|
||||
/* Target the actual controls, not only their parent: SDK visibility rules on
|
||||
children can override inherited visibility while a menu/modal is open. */
|
||||
:root[data-fuc-support-palette] body[data-native-mode='user']:is(.modal-open, .menu-open) > .woot-widget-holder,
|
||||
:root[data-fuc-support-palette] body[data-native-mode='user']:is(.modal-open, .menu-open) > #cw-bubble-holder > button {
|
||||
visibility: hidden !important;
|
||||
pointer-events: none !important;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
:root[data-fuc-support-palette] body > .woot-widget-holder,
|
||||
:root[data-fuc-support-palette] #cw-bubble-holder > button.woot-widget-bubble {
|
||||
transition: none !important;
|
||||
}
|
||||
}
|
||||
+51
-15
@@ -1,12 +1,40 @@
|
||||
import {isDesktopLayout} from './layout.mjs?v=0.12.19';
|
||||
import {getPalette,applyPalette} from './palettes.mjs?v=0.12.6';
|
||||
import {catalogGroups} from './catalog.mjs?v=0.12.6';
|
||||
import {escape as e,money,bytes,date,safeUrl,soldOut,trafficSummary,canPurchase,orderAmount} from './core.mjs?v=0.12.13';
|
||||
import {escape as e,money,bytes,date,safeUrl,soldOut,trafficSummary,canPurchase,hasActiveSubscription,orderAmount} from './core.mjs?v=ui-flow-1';
|
||||
const base = new URL('./native/',import.meta.url).href;
|
||||
const bridgeStyle = 'bridge.css?v=0.12.19';
|
||||
let templates = {},sourceStyles={};
|
||||
const styleReady=fetch(base+'styles.json?v=0.12.13').then(r=>r.json()).then(v=>sourceStyles=v);
|
||||
export const nativeReady = Promise.all(['footer','header','index','home','login','register','forget','reset','plans','wallet','invite','profile','tickets','ticket','servers','notices','knowledge','article','faq','orders','purchase','checkout','walletlog','afflog'].map(async name=>{const version={footer:'0.12.17',header:'0.12.20',home:'0.12.20',login:'0.12.20',register:'0.12.20',forget:'0.12.20',reset:'0.12.20',index:'0.12.21',plans:'0.12.13',checkout:'0.12.13',purchase:'0.12.13'}[name]||'ui-unify-1';const r=await fetch(`${base}${name}.html?v=${version}`);if(!r.ok)throw Error('原版模板加载失败');templates[name]=await r.text();})).then(()=>styleReady);
|
||||
const templates = {};
|
||||
const templateRequests = new Map();
|
||||
const templateVersions = {footer:'0.12.17',header:'0.12.20',home:'0.12.20',login:'0.12.20',register:'0.12.20',forget:'0.12.20',reset:'0.12.20',index:'0.12.21',plans:'0.12.13',checkout:'0.12.13',purchase:'0.12.13'};
|
||||
let styleRequest;
|
||||
|
||||
function loadStyles() {
|
||||
if(!styleRequest){
|
||||
styleRequest=fetch(base+'styles.json?v=0.12.13').then(response=>{
|
||||
if(!response.ok)throw Error('原版样式配置加载失败');
|
||||
return response.json();
|
||||
}).catch(error=>{styleRequest=null;throw error;});
|
||||
}
|
||||
return styleRequest;
|
||||
}
|
||||
|
||||
export function prepareNativeTemplates(...names) {
|
||||
return Promise.all(names.map(name=>{
|
||||
if(!templateRequests.has(name)){
|
||||
const version=templateVersions[name]||'ui-unify-1';
|
||||
const request=fetch(`${base}${name}.html?v=${version}`).then(response=>{
|
||||
if(!response.ok)throw Error('原版模板加载失败');
|
||||
return response.text();
|
||||
}).then(html=>{templates[name]=html;}).catch(error=>{
|
||||
templateRequests.delete(name);
|
||||
throw error;
|
||||
});
|
||||
templateRequests.set(name,request);
|
||||
}
|
||||
return templateRequests.get(name);
|
||||
}));
|
||||
}
|
||||
let nativeSwiper=null,swiperLibrary=null;
|
||||
export async function paintNativeHome(){if(!document.querySelector('.native-public .swiper-container'))return;if(!window.Swiper){if(!swiperLibrary)swiperLibrary=new Promise((resolve,reject)=>{const s=document.createElement('script');s.src=base+'assets/cool/swiper.min.js';s.onload=resolve;s.onerror=reject;document.head.append(s);});await swiperLibrary;}const el=document.querySelector('.native-public .swiper-container');if(!el)return;if(nativeSwiper){try{nativeSwiper.destroy(true,true);}catch{}}el.querySelectorAll('.swiper-slide').forEach(n=>{n.style.removeProperty('display');n.style.removeProperty('width');});el.querySelector('.swiper-wrapper')?.removeAttribute('style');nativeSwiper=new window.Swiper(el,{direction:'horizontal',loop:true,autoplay:{delay:5000,disableOnInteraction:true},navigation:{nextEl:'.swiper-button-next',prevEl:'.swiper-button-prev'}});}
|
||||
let currentMode='',currentStyleMode='',styleSequence=0,chartData=null,chartInstance=null,chartLibrary=null;
|
||||
@@ -17,6 +45,8 @@ export async function prepareNativeMode(mode,page='') {
|
||||
const palette=getPalette(),signature=key+':'+palette;
|
||||
if(currentMode===signature)return;
|
||||
const seq=++styleSequence;
|
||||
const sourceStyles=await loadStyles();
|
||||
if(seq!==styleSequence)return;
|
||||
const overrides=[['native-dark','theme/cool/assets/css/theme/dark-layout.css'],['native-bridge',bridgeStyle]].map(([id,path])=>{
|
||||
let n=document.getElementById(id);if(n)return n;
|
||||
n=document.createElement('link');n.id=id;n.rel='stylesheet';n.href=base+path;n.media='not all';
|
||||
@@ -42,17 +72,22 @@ function syncNativeMenu(root){
|
||||
root.querySelectorAll('.main-menu').forEach(n=>{n.classList.toggle('menu-light',!dark);n.classList.toggle('menu-dark',dark);});
|
||||
root.querySelectorAll('.header-navbar').forEach(n=>{n.classList.toggle('navbar-light',!dark);n.classList.toggle('navbar-dark',dark);});
|
||||
}
|
||||
export function syncNativeColor() {
|
||||
const dark=document.body.dataset.nativeMode==='user'&&document.documentElement.dataset.color==='dark';
|
||||
document.body.classList.toggle('dark-layout',dark);
|
||||
const stylesheet=document.getElementById('native-dark');
|
||||
if(stylesheet)stylesheet.disabled=!dark;
|
||||
syncNativeMenu(document);
|
||||
}
|
||||
|
||||
export function nativeMode(mode, page='') {
|
||||
applyPalette();
|
||||
let icon=document.getElementById('native-icon');if(!icon){icon=document.createElement('link');icon.id='native-icon';icon.rel='icon';icon.type='image/svg+xml';icon.href=base+'images/brand/fuc-mark.svg?v=0.12.20';document.head.append(icon);}
|
||||
const key=mode==='home'?'home':mode==='auth'?(page||'login'):(page||document.body.dataset.nativePage||'dashboard');
|
||||
if(mode!=='home'&&nativeSwiper){try{nativeSwiper.destroy(true,true);}catch{}nativeSwiper=null;}
|
||||
if((mode!=='user'||key!=='dashboard')&&chartInstance){try{chartInstance.destroy();}catch{}chartInstance=null;}
|
||||
if(currentMode!==key+':'+getPalette())void prepareNativeMode(mode,page);
|
||||
let dark=document.getElementById('native-dark');if(!dark){dark=document.createElement('link');dark.id='native-dark';dark.rel='stylesheet';dark.href=base+'theme/cool/assets/css/theme/dark-layout.css';document.head.append(dark);}dark.disabled=mode!=='user'||document.documentElement.dataset.color!=='dark';
|
||||
let bridge=document.getElementById('native-bridge');if(!bridge){bridge=document.createElement('link');bridge.id='native-bridge';bridge.rel='stylesheet';bridge.href=base+bridgeStyle;document.head.append(bridge);}
|
||||
document.body.className=mode==='home'?'native-public':mode==='auth'?'vertical-layout vertical-menu-modern 1-column navbar-floating footer-static bg-full-screen-image blank-page':`vertical-layout ${isDesktopLayout()?'vertical-menu-modern menu-expanded':'vertical-overlay-menu'} navbar-floating footer-static ${document.documentElement.dataset.color==='dark'?'dark-layout':''}`;
|
||||
if(mode==='user'&&isDesktopLayout()&&localStorage.getItem('fuc_menuToggle')==='close'){document.body.classList.remove('menu-expanded');document.body.classList.add('menu-collapsed');}document.body.dataset.nativeMode=mode;document.body.dataset.menu=isDesktopLayout()?'vertical-menu-modern':'vertical-overlay-menu';document.body.classList.add(window.Pace?.running?'pace-running':'pace-done');syncNativeMenu(document);
|
||||
if(mode==='user'&&isDesktopLayout()&&localStorage.getItem('fuc_menuToggle')==='close'){document.body.classList.remove('menu-expanded');document.body.classList.add('menu-collapsed');}document.body.dataset.nativeMode=mode;document.body.dataset.menu=isDesktopLayout()?'vertical-menu-modern':'vertical-overlay-menu';document.body.classList.add(window.Pace?.running?'pace-running':'pace-done');syncNativeColor();
|
||||
}
|
||||
|
||||
const routes={'/':'#/home','/user':'#/dashboard','/user/':'#/dashboard','/user/shop':'#/plans','/user/announcement':'#/notices','/user/code':'#/wallet','/user/plan':'#/orders','/user/invite':'#/invite','/user/profile':'#/profile','/user/ticket':'#/tickets','/user/node':'#/servers','/user/faq/1':'#/faq','/auth/login':'#/login','/auth/register':'#/register','/password/reset':'#/forget'};
|
||||
@@ -109,9 +144,9 @@ function dashboardPlanName(plan) {
|
||||
? `${legacyName}(旧)` : name;
|
||||
}
|
||||
|
||||
export function nativeDashboard(user,sub,notices,brand,richText,traffic=null,nyanpasuDownloadOrigin='') {
|
||||
export function nativeDashboard(user,sub,notices,brand,richText,traffic=null,nyanpasuDownloadOrigin='',noticesUnavailable=false) {
|
||||
const usage=trafficSummary(sub,traffic),[remain,pct,today]=usage.series;
|
||||
const data={NAME:e((user.email||'').split('@')[0]),BRAND:e(brand),PLAN:e(sub.plan?.name||'未订阅'),CLASS:e(dashboardPlanName(sub.plan)),BALANCE:e((Number(user.balance||0)/100).toFixed(2)),DAYS:sub.expired_at?Math.max(0,Math.ceil((sub.expired_at*1000-Date.now())/86400000)):'—',TOTAL_PAY:'—',PINNED:notices[0]?richText(notices[0].content):'暂无公告',PIN_DATE:date(notices[0]?.created_at),LATEST:notices[1]?richText(notices[1].content):'暂无公告',LATEST_DATE:date(notices[1]?.created_at),SUB_URL:e(safeUrl(sub.subscribe_url||'')),RESET_DATE:sub.reset_day!=null?`${sub.reset_day} 天后`:'—',REMAIN_PERCENT:remain.toFixed(1),REMAIN_BYTES:bytes(usage.remaining),TODAY_PERCENT:usage.today===null?'—':today.toFixed(1),TODAY_BYTES:usage.today===null?'—':bytes(usage.today),PAST_PERCENT:pct.toFixed(1),PAST_BYTES:bytes(usage.history)};
|
||||
const data={NAME:e((user.email||'').split('@')[0]),BRAND:e(brand),PLAN:e(sub.plan?.name||'未订阅'),CLASS:e(dashboardPlanName(sub.plan)),BALANCE:e((Number(user.balance||0)/100).toFixed(2)),DAYS:sub.expired_at?Math.max(0,Math.ceil((sub.expired_at*1000-Date.now())/86400000)):'—',TOTAL_PAY:'—',PINNED:notices[0]?richText(notices[0].content):noticesUnavailable?'公告暂时无法加载':'暂无公告',PIN_DATE:notices[0]?date(notices[0].created_at):'',LATEST:notices[1]?richText(notices[1].content):noticesUnavailable?'公告暂时无法加载':'暂无公告',LATEST_DATE:notices[1]?date(notices[1].created_at):'',SUB_URL:e(safeUrl(sub.subscribe_url||'')),RESET_DATE:sub.reset_day!=null?`${sub.reset_day} 天后`:'—',REMAIN_PERCENT:remain.toFixed(1),REMAIN_BYTES:bytes(usage.remaining),TODAY_PERCENT:usage.today===null?'—':today.toFixed(1),TODAY_BYTES:usage.today===null?'—':bytes(usage.today),PAST_PERCENT:pct.toFixed(1),PAST_BYTES:bytes(usage.history)};
|
||||
const host=document.createElement('div');host.innerHTML=sanitize(fill(templates.index,data));
|
||||
const downloadOrigin=safeUrl(nyanpasuDownloadOrigin);
|
||||
if(downloadOrigin){
|
||||
@@ -164,7 +199,7 @@ const termLabel=period=>months[period]?months[period]+' 个月':periodLabels[per
|
||||
function pData(p,period){return {P_ID:e(p.id),P_NAME:e(p.name),P_PRICE:(Number(p[period]||0)/100).toFixed(2),P_GB:e(p.transfer_enable??'—'),P_IP:e(p.display_device_limit??p.device_limit??'—'),P_SPEED:e(p.speed_limit??'—'),P_PERIOD:e(termLabel(period)),PERIOD:period};}
|
||||
const detailRow=(label,value,dividerAfter=false)=>`<div class="d-flex align-items-baseline justify-content-between mb-1"${dividerAfter?' data-settlement-divider':''}><dt class="mr-1">${e(label)}</dt><dd class="mb-0 text-right text-break">${e(value)}</dd></div>`;
|
||||
const planSpecs=plan=>[['套餐流量',`${plan.transfer_enable??'—'} GB`],['速率限制',plan.speed_limit?`${plan.speed_limit} Mbps`:'不限制'],['设备限制',(plan.display_device_limit??plan.device_limit)||'不限制']];
|
||||
const orderUrl=order=>`#/checkout/${encodeURIComponent(order.trade_no)}?from=orders`;
|
||||
const orderUrl=(order,page)=>`#/checkout/${encodeURIComponent(order.trade_no)}?from=orders${page>1?'&page='+page:''}`;
|
||||
function cancelOrderButton(order, compact=false) {
|
||||
if(String(order.status)!=='0'||!order.trade_no)return '';
|
||||
return `<button type="button" class="btn btn-outline-danger${compact?' btn-sm':''}" data-action="cancel-order" data-trade-no="${e(order.trade_no)}">取消订单</button>`;
|
||||
@@ -266,7 +301,7 @@ export function nativeSecondary(name,ctx){
|
||||
const common={NAME:e((user.email||'').split('@')[0]),EMAIL:e(user.email),BALANCE:(Number(user.balance||0)/100).toFixed(2),COMMISSION:(Number(user.commission_balance||0)/100).toFixed(2),GB:(Number(sub.transfer_enable||0)/1073741824).toFixed(0),PLAN:e(sub.plan?.name||'未订阅'),RATE:e(ctx.inviteRate??'—'),WITHDRAW_MIN:'—',REWARD_GB:'—',FEE:'—'};
|
||||
let repeats={},values={},template=name;
|
||||
if(name==='plans'){
|
||||
const groups=catalogGroups(data,Object.keys(periodLabels),user.plan_id);
|
||||
const groups=catalogGroups(data,Object.keys(periodLabels),hasActiveSubscription(user)?user.plan_id:null);
|
||||
const cardNames={month_price:'月套餐',quarter_price:'季套餐',half_year_price:'半年套餐',year_price:'年套餐',two_year_price:'两年套餐',three_year_price:'三年套餐',onetime_price:'一次性套餐',reset_price:'流量重置'};
|
||||
const group=g=>({CYCLE:g.key,repeats:{row:g.rows.map(({plan:p,period:k})=>({...pData(p,k),P_ID:e(p.id+'_'+k),P_NAME:e(cardNames[k])}))}});
|
||||
repeats={v:groups.map(group),productGroupValue:groups.map(group)};
|
||||
@@ -291,7 +326,7 @@ export function nativeSecondary(name,ctx){
|
||||
host.querySelectorAll('[data-toggle="collapse"]').forEach(n=>{n.dataset.action='native-accordion';n.dataset.target=n.getAttribute('data-target')||n.getAttribute('href');});
|
||||
host.querySelectorAll('a[href^="/"]').forEach(n=>unavailable(n));
|
||||
if(name==='plans'){
|
||||
const groups=catalogGroups(data,Object.keys(periodLabels),user.plan_id);
|
||||
const groups=catalogGroups(data,Object.keys(periodLabels),hasActiveSubscription(user)?user.plan_id:null);
|
||||
const activeGroup=groups.some(g=>g.key===period)?period:groups[0]?.key;
|
||||
const tabs=[...host.querySelectorAll('.shop_tab a')];tabs.forEach((a,i)=>{const k=a.dataset.target?.replace('top-home-',''),group=groups.find(g=>g.key===k);a.querySelector('i')?.classList.remove('fa');a.querySelector('i')?.classList.add('fab');a.dataset.cycle=k;a.dataset.action='native-cycle';a.classList.toggle('active',k===activeGroup);a.setAttribute('aria-selected',String(k===activeGroup));a.querySelector('span').textContent=group?.name||'';a.id=`cycle-tab-${i}`;});
|
||||
host.querySelectorAll('.tab-pane').forEach(n=>{const active=n.id===`top-home-${activeGroup}`;n.classList.toggle('active',active);n.classList.toggle('show',active);});
|
||||
@@ -343,7 +378,7 @@ export function nativeSecondary(name,ctx){
|
||||
<td>${e(order.trade_no)}</td><td>${e(order.plan?.name||'—')}</td><td>${money(orderAmount(order))}</td>
|
||||
<td>${orderStatus(order.status)}</td><td>${date(order.created_at)}</td>
|
||||
<td><div class="plan-action-links d-flex align-items-center">
|
||||
${cancelOrderButton(order,true)}<a class="btn btn-primary btn-sm" href="${orderUrl(order)}">${String(order.status)==='0'?'继续支付':'查看'}</a>
|
||||
${cancelOrderButton(order,true)}<a class="btn btn-primary btn-sm" href="${orderUrl(order,page)}">${String(order.status)==='0'?'继续支付':'查看'}</a>
|
||||
</div></td>
|
||||
</tr>`).join('');
|
||||
table.append(body);
|
||||
@@ -462,7 +497,8 @@ function unifyUserLayout(host) {
|
||||
function inviteUrl(code){return code?`${location.origin}${location.pathname}#/register?code=${encodeURIComponent(code)}`:'';}
|
||||
function pagination(page,length,totalPages=null){
|
||||
const orderList=totalPages!==null,atEnd=orderList?page>=totalPages:length<20;
|
||||
return `<div class="fuc-pagination d-flex justify-content-end align-items-center${orderList?'':' my-2'}"><button type="button" class="btn btn-outline-primary btn-sm" data-action="prev" ${page<=1?'disabled':''}>上一页</button><span${orderList?'':' class="mx-1"'}>第 ${page}${orderList?' / '+totalPages:''} 页</span><button type="button" class="btn btn-outline-primary btn-sm" data-action="next" ${atEnd?'disabled':''}>下一页</button></div>`;
|
||||
const pageTarget=target=>orderList?` data-order-page="${Math.max(1,target)}"`:'';
|
||||
return `<div class="fuc-pagination d-flex justify-content-end align-items-center${orderList?'':' my-2'}"><button type="button" class="btn btn-outline-primary btn-sm" data-action="prev"${pageTarget(page-1)} ${page<=1?'disabled':''}>上一页</button><span${orderList?'':' class="mx-1"'}>第 ${page}${orderList?' / '+totalPages:''} 页</span><button type="button" class="btn btn-outline-primary btn-sm" data-action="next"${pageTarget(page+1)} ${atEnd?'disabled':''}>下一页</button></div>`;
|
||||
}
|
||||
function country(name){return /日本|Japan|JP/i.test(name)?'jp':/新加坡|Singapore|SG/i.test(name)?'sg':/香港|Hong.?Kong|HK/i.test(name)?'hk':/美国|United.?States|US/i.test(name)?'us':'';}
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "Fuc",
|
||||
"description": "直接复用新版FUC原始用户模板、样式、图标及素材,接入XB接口;XB管理员后台保持原样。",
|
||||
"version": "0.12.21",
|
||||
"version": "0.12.25",
|
||||
"images": "",
|
||||
"configs": [
|
||||
{
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
<meta name="viewport" content="width=device-width,initial-scale=1,viewport-fit=cover">
|
||||
<meta name="referrer" content="same-origin">
|
||||
<title>{{ $title }}</title>
|
||||
<link rel="stylesheet" href="/theme/{{ $theme }}/assets/customer-service.css?v=29">
|
||||
<link rel="stylesheet" href="/theme/{{ $theme }}/assets/customer-service.css?v=ui-support-stacking-2">
|
||||
<script>
|
||||
try {
|
||||
const route = location.hash.match(/^#\/?([^/?]+)/)?.[1];
|
||||
@@ -58,7 +58,7 @@
|
||||
];
|
||||
@endphp
|
||||
<script>window.fucSettings = @json($fucSettings);</script>
|
||||
<script type="module" src="/theme/{{ $theme }}/assets/app.mjs?v=0.12.21"></script>
|
||||
<script type="module" src="/theme/{{ $theme }}/assets/app.mjs?v=ui-flow-1"></script>
|
||||
|
||||
<script type="module" src="/theme/{{ $theme }}/assets/chatwoot.mjs?v=6"></script>
|
||||
</body>
|
||||
|
||||
Reference in new issue
Block a user