Files
novalon-website/public/js/main.js
T
zhangxiang 901e1025a8 feat(novavis): 睿视 landing 原样迁入官网 public(独立站拆分 Phase 0)
- novavis-authority/landing → public/{novavis/index.html,assets,css,js,images/logos},
  内容零修改;资产绝对路径按源站 URL 语义落 public 根(命名空间冲突检查全空闲)
- next.config 加一条 rewrite:/novavis → /novavis/index.html(Next public 层
  不做目录默认文档补全,实测 /novavis/ 308→/novavis→404)
- lint-staged glob 改 !(public)/**——landing 的 main.js 是迁移原件(「不作修改」),
  其 6 处既有 no-unused-vars 不属本仓门禁面
- 验证:与线上源站 novavis.p.novalon.cn 逐字段一致(title/h1/h2/CTA/CSS/背景/图片数),
  4 张信创 logo 为懒加载时序假象,服务端两侧全 200;生产 CSP 实测放行,零内联脚本
- 授权边界:内测标识、导航外链、novavis-authority 仓库均未动(用户裁定「系统不动」)
2026-12-02 10:10:09 +08:00

861 lines
32 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/* ============================================
睿视 NovaVis Landing Page — Scripts
============================================ */
/* --------------------------------------------
渐进生长动效(GROW)
--------------------------------------------
机制:读取图形元素上的 data-grow 阶段号,按阶段串行推进,
阶段内元素依次点亮;进入视口才播放,离开视口复位。
三个设计要点:
1. html.js-grow 仅在本模块成功初始化后保留——中途报错会移除,
避免图形停在"已隐藏但动画没跑"的空白状态。
2. 资金流向的 SMIL 流动粒子由本模块统一启停,
不再一进页面就无条件循环空转。
3. 尊重 prefers-reduced-motion——直接呈现终态,不排时间轴。
-------------------------------------------- */
const GROW = (() => {
const STAGGER = 70; // 阶段内相邻元素的点亮间隔(毫秒)
const PHASE_GAP = 240; // 相邻阶段之间的间隔(毫秒)
const reduced = window.matchMedia
? window.matchMedia('(prefers-reduced-motion: reduce)')
: { matches: false };
// 取待点亮目标:容器 <g> 取其子元素,独立图形元素取自身
function targetsOf(el) {
if (el.tagName.toLowerCase() === 'g') return Array.from(el.children);
return [el];
}
// 按 data-grow 阶段号分组收集
function collect(root) {
const phases = {};
let max = 0;
root.querySelectorAll('[data-grow]').forEach((el) => {
const n = parseInt(el.getAttribute('data-grow'), 10) || 1;
(phases[n] = phases[n] || []).push(el);
if (n > max) max = n;
});
return { phases, max };
}
class Player {
constructor(root) {
this.root = root;
this.svg = root.querySelector('svg');
this.timers = [];
this.hasSmil = !!(this.svg && this.svg.querySelectorAll('animate').length);
if (this.hasSmil) this.holdSmil();
}
holdSmil() {
try {
this.svg.pauseAnimations();
this.svg.setCurrentTime(0);
} catch (e) { /* 浏览器不支持 SMIL 控制时忽略 */ }
}
releaseSmil() {
try { this.svg.unpauseAnimations(); } catch (e) { /* 同上 */ }
}
stop() {
this.timers.forEach(clearTimeout);
this.timers = [];
}
reset() {
this.stop();
if (this.hasSmil) this.holdSmil();
this.root.querySelectorAll('.is-grown').forEach((el) => {
el.classList.remove('is-grown');
});
}
play() {
this.reset();
const { phases, max } = collect(this.root);
// 减弱动效偏好:一次性点亮到终态,不排时间轴
if (reduced.matches) {
for (let p = 1; p <= max; p++) {
(phases[p] || []).forEach((el) => {
targetsOf(el).forEach((t) => t.classList.add('is-grown'));
});
}
return;
}
let cursor = 0;
for (let p = 1; p <= max; p++) {
const group = phases[p];
if (!group) continue;
const targets = [];
group.forEach((el) => targetsOf(el).forEach((t) => targets.push(t)));
targets.forEach((t, i) => {
this.timers.push(setTimeout(() => {
t.classList.add('is-grown');
}, cursor + i * STAGGER));
});
cursor += targets.length * STAGGER + PHASE_GAP;
}
// 所有阶段走完后再放开 SMIL 粒子
if (this.hasSmil) {
this.timers.push(setTimeout(() => this.releaseSmil(), cursor));
}
}
}
return {
reduced,
create(root) { return new Player(root); },
};
})();
// 尽早标记,避免图形先完整显示再被隐藏造成闪烁。
// 若后续动效初始化失败,DOMContentLoaded 里会移除该标记,让图形恢复静态可见。
document.documentElement.classList.add('js-grow');
/* --------------------------------------------
Hero Live Demo(软件演示动画编排)
--------------------------------------------
机制:在 #heroDemo 上轮流挂 demo-step-1~4 类驱动 CSS,
剧本:导入数据 → 构建图谱(复用 GROW 渐进生长)→
异常检测(可疑路径脉冲 + 指标滚动)→ AI 结论,播完循环。
尊重 prefers-reduced-motion——挂 demo-final 一次呈现终态。
-------------------------------------------- */
const DEMO = (() => {
// 各步骤时长(毫秒):总计约 14.6s 后循环
const DUR = { s1: 2600, s2: 3400, s3: 3200, s4: 3800, hold: 1600 };
class Player {
constructor(root, growPlayer) {
this.root = root;
this.grow = growPlayer;
this.timers = [];
this.raf = null;
this.frozen = false;
}
stop() {
this.timers.forEach(clearTimeout);
this.timers = [];
if (this.raf) cancelAnimationFrame(this.raf);
this.raf = null;
}
// 冻结:停在当前画面(WCAG 2.2.2)——清时间轴,CSS 动画由 demo-paused 挂起
freeze() {
if (this.frozen) return;
this.frozen = true;
this.stop();
if (this.grow) {
this.grow.stop();
try { if (this.grow.svg) this.grow.svg.pauseAnimations(); } catch (e) { /* 不支持 SMIL 控制时忽略 */ }
}
this.root.classList.add('demo-paused');
}
unfreeze() {
this.frozen = false;
this.root.classList.remove('demo-paused');
}
reset() {
this.stop();
this.frozen = false;
this.root.classList.remove('demo-paused');
this.root.classList.remove('demo-step-1', 'demo-step-2', 'demo-step-3', 'demo-step-4', 'demo-final');
if (this.grow) this.grow.reset();
// 注:原此处把 [data-count-to] 归零再滚动。hero 换 /home 后该属性已无消费方
// (台账读数是静态数据,写成 0 会出现"共 0 个任务"却列着 4 行),
// 故 countUp 与这段归零一并删除(2026-11-07 §28.2 评审 BLOCKING-1 的连带清理)。
}
// 侧边栏高亮切换(模拟软件内导航点击)
setNav(key) {
this.root.querySelectorAll('[data-nav]').forEach((el) => {
el.classList.toggle('active', el.getAttribute('data-nav') === key);
});
}
play() {
this.reset();
const root = this.root;
// 每一步**先清掉其它步的类再加自己的**。
// 为什么必须清:`.demo-step-N` 是"该步的样式"选择器,类若只加不删,后一步会继承
// 前面所有步的样式(2026-11-07 §28.2 评审 BLOCKING-1 实测:5.6s 起类名恒为
// `demo-step-2 demo-step-3 demo-step-4`,导致 `.demo-step-2 .nv-home-row:not(.is-current)
// {opacity:.55}` 一直不撤销)。
const STEPS_ALL = ['demo-step-1', 'demo-step-2', 'demo-step-3', 'demo-step-4'];
const enterStep = (n) => {
const want = 'demo-step-' + n;
STEPS_ALL.forEach((c) => { if (c !== want) root.classList.remove(c); });
root.classList.add(want);
};
// 减弱动效偏好:一次性呈现终态,不排时间轴
if (GROW.reduced.matches) {
root.classList.add('demo-final');
this.setNav('graph');
return;
}
const t = (fn, ms) => this.timers.push(setTimeout(fn, ms));
// ---- /home 任务工作台的四步剧本(2026-11-07 重写)----
// 原剧本是图窗专属(导入卡片 → 图谱生长 → 可疑路径 → AI 结论)。hero 改画 /home 后,
// 那些元素在 DOM 里不存在,剧本会作用在空气上。四步与真源一一对应:
// step-1 新建任务 ← 卡体工具条「新任务名称 + 新建任务」(TaskHomePage:797-841)
// step-2 打开任务 ← 行内主操作「打开」(:99);当前行变 is-current
// step-3 导入数据 ← 右栏「当前任务」卡的动作「导入数据」(:600-641)
// step-4 就绪 ← 终态(任务已打开、数据已导入)
// 徽标(index.html 的 data-badge)与这四步**同义同步**,不得错位。
// 步骤 1 · 新建任务
enterStep(1);
this.setNav('import');
// 步骤 2 · 打开任务
t(() => {
enterStep(2);
this.setNav('graph');
}, DUR.s1);
// 步骤 3 · 导入数据
t(() => {
enterStep(3);
}, DUR.s1 + DUR.s2);
// 步骤 4 · 就绪
t(() => {
enterStep(4);
}, DUR.s1 + DUR.s2 + DUR.s3);
// 停顿后从头循环
t(() => this.play(), DUR.s1 + DUR.s2 + DUR.s3 + DUR.s4 + DUR.hold);
}
}
return {
create(root, growPlayer) { return new Player(root, growPlayer); },
};
})();
document.addEventListener('DOMContentLoaded', () => {
// ---- 滚动渐显:自动扫描各 section 内容,进入视口后 stagger 入场 ----
// 目标由选择器清单声明(HTML 零改动);hero/highlights 首屏直出不参与。
// 基础隐藏态由 html.js-reveal 门控:初始化失败时移除标记,全量可见。
try {
const REVEAL_SELECTOR = [
'.showcase-header > *',
'.features .section-title', '.features .section-desc', '.feature-card',
'.product-matrix .section-title', '.product-matrix .section-desc', '.product-card',
'.process .section-title', '.process .section-desc', '.process-step',
'.scenarios .section-title', '.scenarios .section-desc', '.scenario-card',
'.social-proof .section-title', '.social-proof .section-desc',
'.trust .section-title', '.trust .section-desc', '.trust-grid > *',
'.faq .section-title', '.faq .section-desc', '.faq-item',
'.cta-inner > *'
].join(', ');
const revealEls = Array.from(document.querySelectorAll(REVEAL_SELECTOR))
.filter(el => !el.closest('.hero') && !el.closest('.hero-highlights'));
// 同容器内兄弟 stagger:序号 × 60ms,封顶 240ms。
// 2026-11-07 由 90/450 收敛(P3-1):qoder 实测无滚动渐显,本页保留但必须"轻"——
// 450ms 的尾延迟在 B 端"快速查看"场景里读作卡顿。
const siblingIndex = new Map();
for (const el of revealEls) {
const parent = el.parentElement;
const key = parent;
const i = siblingIndex.get(key) ?? 0;
siblingIndex.set(key, i + 1);
el.classList.add('rv');
el.style.setProperty('--rv-d', Math.min(i * 60, 240) + 'ms');
}
const revealIn = (el) => el.classList.add('in');
if ('IntersectionObserver' in window && !GROW.reduced.matches) {
const io = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) { revealIn(entry.target); io.unobserve(entry.target); }
});
}, { threshold: 0.12, rootMargin: '0px 0px -36px 0px' });
revealEls.forEach((el) => io.observe(el));
} else {
revealEls.forEach(revealIn);
}
document.documentElement.classList.add('js-reveal');
} catch (err) {
document.documentElement.classList.remove('js-reveal');
}
const nav = document.getElementById('nav');
const navToggle = document.getElementById('navToggle');
const navLinks = document.getElementById('navLinks');
// ---- Nav scroll state ----
function updateNav() {
nav.classList.toggle('scrolled', window.scrollY > 10);
}
window.addEventListener('scroll', updateNav, { passive: true });
updateNav();
// ---- Nav scroll-spy:标出当前所在章节(aria-current=location,不只靠颜色) ----
const navSectionLinks = Array.from(
navLinks.querySelectorAll('a[href^="#"]')
).filter((a) => document.querySelector(a.getAttribute('href')));
function updateActiveSection() {
const marker = window.scrollY + 180;
let current = null;
for (const link of navSectionLinks) {
const section = document.querySelector(link.getAttribute('href'));
if (section && section.getBoundingClientRect().top + window.scrollY <= marker) {
current = link;
}
}
for (const link of navSectionLinks) {
const isCurrent = link === current;
link.classList.toggle('active', isCurrent);
if (isCurrent) link.setAttribute('aria-current', 'location');
else link.removeAttribute('aria-current');
}
}
window.addEventListener('scroll', updateActiveSection, { passive: true });
updateActiveSection();
// ---- Features:静态三列网格(qoder 无轮播;2026-11-24 移除 Swiper 依赖) ----
// ---- Showcase tabs (ARIA tab pattern with keyboard support) ----
// 限定在外层分段控件内:窗内 TabBar 复用同名类,若一并选中,点击它拿不到 aria-controls,会把四个 panel 全部 hidden(2026-11-24 实测缺陷)。
const showcaseTabs = Array.from(document.querySelectorAll('.showcase-tabs .showcase-tab'));
const showcasePanels = Array.from(document.querySelectorAll('.showcase-panel'));
// roving tabindex:整组只留一只 tab 可被 Tab 键到达,指向 active。
// 守卫——焦点仍停在某只 tab 上时不摘它的 tabindex(摘了会把键盘用户正在操作的控件移出
// 序列):点击/方向键路径已先 focus 目标再同步,故此处实际保护的是自动轮播那条
// `focus: false` 的路径(回调已在 focusin 之前入队的竞态)。复评 P2-9。
function syncRovingTabindex() {
showcaseTabs.forEach(t => {
const isActive = t.classList.contains('active');
// 只在「持焦且已非 active」时不摘(自动轮播 focus:false 路径的竞态兜底);
// 持焦且就是 active 时必须照常写 0,否则整组会一只都不在 Tab 序列里。
if (!isActive && document.activeElement === t) return;
t.setAttribute('tabindex', isActive ? '0' : '-1');
});
}
function activateShowcaseTab(targetTab, opts) {
const noFocus = opts && opts.focus === false;
const targetId = targetTab.getAttribute('aria-controls');
showcaseTabs.forEach(t => {
const isTarget = t === targetTab;
t.classList.toggle('active', isTarget);
t.setAttribute('aria-selected', String(isTarget));
});
showcasePanels.forEach(p => {
const isTarget = p.id === targetId;
p.classList.toggle('active', isTarget);
p.hidden = !isTarget;
});
// 切换后重播该 panel 的渐进生长动画
const panel = document.getElementById(targetId);
if (panel && growPlayers.has(panel)) growPlayers.get(panel).play();
if (!noFocus) targetTab.focus();
// 必须在 focus() 之后同步:focus() 之前持焦的还是旧 tab,会被上面的守卫跳过,
// 于是「方向键切换」后旧 tab 残留 tabindex="0" —— 整组出现两只可 Tab 到达的 tab
syncRovingTabindex();
}
showcaseTabs.forEach((tab, index) => {
tab.addEventListener('click', () => { activateShowcaseTab(tab); scheduleCycle(); });
tab.addEventListener('keydown', (e) => {
let nextIndex = index;
if (e.key === 'ArrowRight') {
nextIndex = (index + 1) % showcaseTabs.length;
} else if (e.key === 'ArrowLeft') {
nextIndex = (index - 1 + showcaseTabs.length) % showcaseTabs.length;
} else if (e.key === 'Home') {
nextIndex = 0;
} else if (e.key === 'End') {
nextIndex = showcaseTabs.length - 1;
} else {
return;
}
e.preventDefault();
activateShowcaseTab(showcaseTabs[nextIndex]);
scheduleCycle();
});
});
// ---- Showcase 自动轮播(演示动画)----
// 机制:视口内每 CYCLE_MS 自动切到下一个 tab(面板入场动画照播);
// 悬停卡片暂停(进度条冻结在当前位置),移出恢复;点击/键盘切换会重置进度。
// 减弱动效偏好:不轮播、进度条由 CSS 隐藏。
const CYCLE_MS = 5500;
const showcaseCard = document.querySelector('.showcase-card');
let cycleTimer = null;
let showcaseInView = false;
let showcaseHovered = false;
let showcaseFocused = false;
let showcasePaused = false;
function resetProgress(animate) {
showcaseTabs.forEach((tab) => {
const bar = tab.querySelector('.tab-progress span');
if (!bar) return;
bar.style.transition = 'none';
bar.style.width = '0';
if (animate && tab.classList.contains('active')) {
void bar.offsetWidth; // 强制回流,确保进度从头开始
bar.style.transition = `width ${CYCLE_MS}ms linear`;
bar.style.width = '100%';
}
});
}
function scheduleCycle() {
clearTimeout(cycleTimer);
cycleTimer = null;
// 悬停/焦点/暂停/不在视口/减弱动效下不重播进度条,也不排下一次切换
if (!showcaseInView || showcaseHovered || showcaseFocused || showcasePaused || GROW.reduced.matches) return;
resetProgress(true);
cycleTimer = setTimeout(() => {
const idx = showcaseTabs.findIndex((t) => t.classList.contains('active'));
const next = showcaseTabs[(idx + 1) % showcaseTabs.length];
activateShowcaseTab(next, { focus: false });
scheduleCycle();
}, CYCLE_MS);
}
function freezeProgress() {
// 进度条冻结在当前位置
showcaseTabs.forEach((tab) => {
const bar = tab.querySelector('.tab-progress span');
if (!bar) return;
const w = getComputedStyle(bar).width;
bar.style.transition = 'none';
bar.style.width = w;
});
}
function holdCycle() {
clearTimeout(cycleTimer);
cycleTimer = null;
// 冻结在当前位置,让位结束后由 scheduleCycle 重新计时
freezeProgress();
}
function pauseCycle() {
showcaseHovered = true;
holdCycle();
}
// ---- 轮播暂停开关(WCAG 2.2.2:自动移动内容须提供显式停止手段)----
const showcasePauseBtn = document.getElementById('showcasePause');
function setCyclePaused(paused) {
showcasePaused = paused;
if (!showcasePauseBtn) return;
showcasePauseBtn.setAttribute('aria-pressed', String(paused));
showcasePauseBtn.setAttribute('aria-label', paused ? '继续自动轮播' : '暂停自动轮播');
const txt = showcasePauseBtn.querySelector('.showcase-pause-text');
if (txt) txt.textContent = paused ? '继续' : '暂停';
showcasePauseBtn.querySelectorAll('.showcase-pause-icon').forEach((icon, i) => {
icon.style.display = (paused ? i === 1 : i === 0) ? '' : 'none';
});
if (paused) {
holdCycle();
} else {
scheduleCycle();
}
}
if (showcasePauseBtn) {
if (GROW.reduced.matches) showcasePauseBtn.hidden = true;
showcasePauseBtn.addEventListener('click', () => setCyclePaused(!showcasePaused));
}
if (showcaseCard && 'IntersectionObserver' in window && !GROW.reduced.matches) {
new IntersectionObserver((entries) => {
entries.forEach((entry) => {
showcaseInView = entry.isIntersecting;
if (showcaseInView) scheduleCycle();
else { clearTimeout(cycleTimer); resetProgress(false); }
});
}, { threshold: 0.35 }).observe(showcaseCard);
showcaseCard.addEventListener('mouseenter', pauseCycle);
showcaseCard.addEventListener('mouseleave', () => {
showcaseHovered = false;
scheduleCycle();
});
// 键盘焦点进入卡片即让位(与悬停暂停同理:读不完就被切走,WCAG 2.2.2)
showcaseCard.addEventListener('focusin', () => {
showcaseFocused = true;
holdCycle();
});
showcaseCard.addEventListener('focusout', (e) => {
if (showcaseCard.contains(e.relatedTarget)) return; // 卡片内部移动不恢复
showcaseFocused = false;
syncRovingTabindex(); // 焦点离开后收敛回「只有 active 可 Tab 到达」
scheduleCycle();
});
}
// ---- Hero Live Demo + 渐进生长动效:Showcase 四个 panel ----
// growPlayers 在此声明,确保 activateShowcaseTab 引用时始终可用(即便初始化失败)
const growPlayers = new Map();
try {
// Hero 走 DEMO 编排器(内部复用 GROW 点亮图谱),Showcase 仍走 GROW
const heroDemo = document.getElementById('heroDemo');
const heroGrow = heroDemo ? GROW.create(heroDemo) : null;
const demoPlayer = heroDemo ? DEMO.create(heroDemo, heroGrow) : null;
showcasePanels.forEach(root => growPlayers.set(root, GROW.create(root)));
const growObserver = 'IntersectionObserver' in window
? new IntersectionObserver((entries) => {
entries.forEach(entry => {
const player = growPlayers.get(entry.target);
if (!player) return;
// 隐藏的 panel(非当前 tab)交给 tab 切换时重播,此处不处理
if (entry.target.hidden) return;
if (entry.isIntersecting) player.play();
else player.reset();
});
}, { threshold: 0.25 })
: null;
function observeGrow(root) {
if (growObserver) growObserver.observe(root);
else growPlayers.get(root).play(); // 不支持 IntersectionObserver 时直接播放
}
showcasePanels.forEach(observeGrow);
// Hero Live Demo:进视口播放、离场复位循环;支持显式暂停与悬停冻结(WCAG 2.2.2)
if (demoPlayer) {
document.documentElement.classList.add('js-demo');
const demoPauseBtn = document.getElementById('demoPause');
let userPaused = false;
let pointerInside = false;
function setDemoPausedUI(paused) {
userPaused = paused;
if (!demoPauseBtn) return;
demoPauseBtn.setAttribute('aria-pressed', String(paused));
demoPauseBtn.setAttribute('aria-label', paused ? '继续播放首屏演示动画' : '暂停首屏演示动画');
const txt = demoPauseBtn.querySelector('.demo-pause-text');
if (txt) txt.textContent = paused ? '继续' : '暂停';
demoPauseBtn.querySelectorAll('.demo-pause-icon').forEach((icon, i) => {
icon.style.display = (paused ? i === 1 : i === 0) ? '' : 'none';
});
}
function applyDemoState() {
if (userPaused || pointerInside) demoPlayer.freeze();
else if (demoPlayer.frozen) { demoPlayer.unfreeze(); demoPlayer.play(); }
}
if (demoPauseBtn) {
if (GROW.reduced.matches) demoPauseBtn.hidden = true;
else demoPauseBtn.addEventListener('click', () => { setDemoPausedUI(!userPaused); applyDemoState(); });
}
const heroVisual = heroDemo.parentElement;
if (heroVisual) {
['mouseenter', 'focusin'].forEach(evt => heroVisual.addEventListener(evt, () => { pointerInside = true; applyDemoState(); }));
['mouseleave', 'focusout'].forEach(evt => heroVisual.addEventListener(evt, () => { pointerInside = false; applyDemoState(); }));
}
const demoObserver = 'IntersectionObserver' in window
? new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (!entry.isIntersecting) { demoPlayer.reset(); return; }
if (userPaused) { setDemoPausedUI(true); demoPlayer.freeze(); }
else if (!demoPlayer.frozen) demoPlayer.play();
});
}, { threshold: 0.25 })
: null;
if (demoObserver) {
// Hero 在首屏:延后到 load 之后再启动,避免与首屏渲染争抢资源
if (document.readyState === 'complete') demoObserver.observe(heroDemo);
else window.addEventListener('load', () => demoObserver.observe(heroDemo), { once: true });
} else {
demoPlayer.play();
}
}
} catch (err) {
// 动效初始化失败:移除标记,图形恢复为完整可见的静态态
document.documentElement.classList.remove('js-grow');
document.documentElement.classList.remove('js-demo');
growPlayers.clear();
}
// ---- Mobile nav toggle with aria ----
// 可访问名随状态变化:读屏用户听到的是「打开菜单 / 关闭菜单」,而不是固定的「菜单」
function setNavExpanded(expanded) {
navToggle.setAttribute('aria-expanded', String(expanded));
navToggle.setAttribute('aria-label', expanded ? '关闭菜单' : '打开菜单');
navLinks.classList.toggle('open', expanded);
}
navToggle.addEventListener('click', () => {
setNavExpanded(navToggle.getAttribute('aria-expanded') !== 'true');
});
navLinks.querySelectorAll('a').forEach(link => {
link.addEventListener('click', () => setNavExpanded(false));
});
// Close mobile nav on Escape
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && navLinks.classList.contains('open')) {
setNavExpanded(false);
navToggle.focus();
}
});
// ---- Back to top button ----
const backToTop = document.getElementById('backToTop');
function updateBackToTop() {
backToTop.classList.toggle('visible', window.scrollY > 600);
}
window.addEventListener('scroll', updateBackToTop, { passive: true });
updateBackToTop();
backToTop.addEventListener('click', () => {
window.scrollTo({ top: 0, behavior: 'smooth' });
});
// ---- FAQ accordion: close siblings on open ----
document.querySelectorAll('.faq-item').forEach(item => {
item.addEventListener('toggle', () => {
if (item.open) {
const faqList = item.closest('.faq-list');
faqList.querySelectorAll('.faq-item').forEach(sibling => {
if (sibling !== item) sibling.open = false;
});
}
});
});
// ---- Trial form validation ----
const form = document.getElementById('trialForm');
if (!form) return;
const nameInput = document.getElementById('name');
const orgInput = document.getElementById('org');
const phoneInput = document.getElementById('phone');
const emailInput = document.getElementById('email');
const submitBtn = document.getElementById('submitBtn');
const submitBtnHtml = submitBtn.innerHTML;
function setError(input, errorEl, msg) {
input.setAttribute('aria-invalid', 'true');
errorEl.textContent = msg || '';
}
function clearError(input, errorEl) {
input.removeAttribute('aria-invalid');
errorEl.textContent = '';
}
function validatePhone(value) {
return /^1[3-9]\d{9}$/.test(value.replace(/\s/g, ''));
}
function validateEmail(value) {
return !value || /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);
}
function validateField(input, errorEl, validator, emptyMsg, invalidMsg) {
const value = input.value.trim();
if (!value) {
// emptyMsg 为 null 表示选填字段:留空即通过
if (!emptyMsg) {
clearError(input, errorEl);
return true;
}
setError(input, errorEl, emptyMsg);
return false;
}
if (validator && !validator(value)) {
setError(input, errorEl, invalidMsg);
return false;
}
clearError(input, errorEl);
return true;
}
// Live validation on blur
nameInput.addEventListener('blur', () => {
validateField(nameInput, document.getElementById('nameError'), null, '请输入您的姓名');
});
orgInput.addEventListener('blur', () => {
validateField(orgInput, document.getElementById('orgError'), null, '请输入您所在的单位名称');
});
phoneInput.addEventListener('blur', () => {
validateField(
phoneInput,
document.getElementById('phoneError'),
validatePhone,
'请输入您的联系电话',
'请输入正确的手机号码'
);
});
emailInput.addEventListener('blur', () => {
validateField(
emailInput,
document.getElementById('emailError'),
validateEmail,
null,
'请输入正确的邮箱地址'
);
});
// Clear error on input
[nameInput, orgInput, phoneInput, emailInput].forEach(input => {
input.addEventListener('input', () => {
const errorEl = document.getElementById(input.name + 'Error');
if (errorEl) clearError(input, errorEl);
});
});
// ---- Failure & copy helpers ----
function requestText(name, org, phone, email, message) {
return `姓名:${name}\n单位:${org}\n电话:${phone}${email ? '\n邮箱:' + email : ''}${message ? '\n\n需求描述:\n' + message : ''}`;
}
function legacyCopy(text) {
const ta = document.createElement('textarea');
ta.value = text;
ta.setAttribute('readonly', '');
ta.style.position = 'fixed';
ta.style.opacity = '0';
document.body.appendChild(ta);
ta.select();
let ok = false;
try { ok = document.execCommand('copy'); } catch (err) { ok = false; }
document.body.removeChild(ta);
return ok;
}
function copyText(text) {
if (navigator.clipboard && navigator.clipboard.writeText) {
return navigator.clipboard.writeText(text).then(() => true).catch(() => legacyCopy(text));
}
return Promise.resolve(legacyCopy(text));
}
// 失败时保留已填内容,显示可见错误提示,并给出「邮件发送 / 复制内容」两个出口
function showFailureAlert(reason, fields) {
submitBtn.disabled = false;
submitBtn.style.opacity = '1';
submitBtn.innerHTML = submitBtnHtml;
const old = form.querySelector('.cta-form-alert');
if (old) old.parentNode.removeChild(old);
const alertBox = document.createElement('div');
alertBox.className = 'cta-form-alert';
alertBox.setAttribute('role', 'alert');
const msg = document.createElement('p');
msg.className = 'cta-form-alert-msg';
msg.textContent = reason;
alertBox.appendChild(msg);
const actions = document.createElement('div');
actions.className = 'cta-form-alert-actions';
const mailLink = document.createElement('a');
mailLink.className = 'cta-form-alert-link';
mailLink.href = 'mailto:contact@novalon.cn?subject=' +
encodeURIComponent('睿视 NovaVis 试用申请 — ' + fields.org) +
'&body=' + encodeURIComponent(requestText(fields.name, fields.org, fields.phone, fields.email, fields.message));
mailLink.textContent = '通过邮件发送申请';
actions.appendChild(mailLink);
const copyBtn = document.createElement('button');
copyBtn.type = 'button';
copyBtn.className = 'cta-form-alert-btn';
copyBtn.textContent = '复制申请内容';
copyBtn.addEventListener('click', () => {
copyText(requestText(fields.name, fields.org, fields.phone, fields.email, fields.message))
.then( ok => { copyBtn.textContent = ok ? '已复制,粘贴到邮件即可发送' : '复制失败,请手动选择文本'; });
});
actions.appendChild(copyBtn);
alertBox.appendChild(actions);
form.insertBefore(alertBox, form.querySelector('.cta-form-submit'));
}
// Submit: POST to backend, show failure alert with recovery paths
form.addEventListener('submit', (e) => {
e.preventDefault();
const nameOk = validateField(nameInput, document.getElementById('nameError'), null, '请输入您的姓名');
const orgOk = validateField(orgInput, document.getElementById('orgError'), null, '请输入您所在的单位名称');
const phoneOk = validateField(
phoneInput,
document.getElementById('phoneError'),
validatePhone,
'请输入您的联系电话',
'请输入正确的手机号码'
);
const emailOk = validateField(
emailInput,
document.getElementById('emailError'),
validateEmail,
null,
'请输入正确的邮箱地址'
);
if (!nameOk || !orgOk || !phoneOk || !emailOk) {
const firstInvalid = form.querySelector('[aria-invalid="true"]');
if (firstInvalid) firstInvalid.focus();
return;
}
const name = nameInput.value.trim();
const org = orgInput.value.trim();
const phone = phoneInput.value.trim();
const email = emailInput.value.trim();
const message = document.getElementById('message').value.trim();
// Disable button during submission
submitBtn.disabled = true;
submitBtn.style.opacity = '0.7';
submitBtn.textContent = '提交中...';
const payload = { name, org, phone };
if (email) payload.email = email;
if (message) payload.message = message;
const fields = { name, org, phone, email, message };
fetch('/api/v1/contact', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload)
})
.then(res => res.json().then(data => ({ ok: res.ok, data })))
.then(({ ok, data }) => {
if (ok && data.code === 200) {
// 成功:确认块可被屏幕阅读器播报,焦点随之移动
form.innerHTML = '<div class="cta-form-success" role="status" tabindex="-1"><p>✓ 感谢您的申请!我们将在 1 个工作日内与您联系。</p></div>';
const successBox = form.querySelector('.cta-form-success');
if (successBox) successBox.focus();
} else {
showFailureAlert('提交未成功:' + ((data && data.message) || '服务器返回异常,请稍后重试'), fields);
}
})
.catch(() => {
showFailureAlert('提交失败(网络异常),请检查网络后重试,或通过以下方式联系我们。', fields);
});
});
});