htmlAnchorScript function
String
htmlAnchorScript(
- PreviewPosition? restore, {
- String channelName = HyperlensBridge.channelName,
- bool hold = true,
- PreviewLinkSpace? linkSpace,
- String? linkContext,
生成要注入页面的整段脚本;restore 为 null 时显式落回顶部。
为什么 null 也要落位:同一个 WebView 实例会沿用上一篇的滚动位置(Markdown 侧 实测过:新文档一进来就停在半中腰),不显式说一句「回到 0」,新文件就继承旧位置。
channelName 必须与 WebView 侧 addJavaScriptChannel 注册的名字逐字一致
(默认 HyperlensBridge.channelName):对不上的表现是脚本静默什么都不发 ——
页面里那句 if (window.<name>) 只是守卫,通道不存在就整条位置链路哑掉。
linkSpace / linkContext 是「这一页属于哪个地址空间」(见 PreviewLinkSpace):
给了之后链接回执是 link <space> <ctx> <href>,调用方能认出换页之后的迟到回执;
不给就是旧式的 link <href>。
位置在链接之前上报:脚本正文里那个「点一下就先报位置」的监听比这里的
hyperLensAnchorWatchLinks() 先注册,同一个捕获阶段里按注册顺序执行 ——
所以调用方收到的是「离开的位置 → 链接」两条,顺序反了会把跳转后的位置压进栈。
Implementation
String htmlAnchorScript(
PreviewPosition? restore, {
String channelName = HyperlensBridge.channelName,
bool hold = true,
PreviewLinkSpace? linkSpace,
String? linkContext,
}) {
HyperlensBridge.checkChannelName(channelName);
final String json = jsJson(_restorePayload(restore));
final String script =
_anchorJs.replaceAll(_channelPlaceholder, channelName);
// 命中定位(HyperlensPage.focus)自己会把页面滚到目标处:这时不能再落位,
// 否则两边抢滚动条,读者看到「跳过去又滑走」。
final String holdLine = hold ? 'hyperLensAnchorHold($json);\n' : '';
final String loadBody = 'hyperLensInvalidateSections(); hyperLensSectionsPost();'
'${hold ? ' if (!hyperLensAnchorTouched) { hyperLensAnchorHold($json); }' : ''}';
final String linkPrefix = jsJson(
linkReceiptPrefix(space: linkSpace, context: linkContext),
);
return '$script\n'
'$holdLine'
// 清单先发一次(脚本挂在 </body> 前,前面的标题已经解析完),
// 再在 load / resize 后各补一次:图片撑开布局、旋转屏幕都会改可见性。
// 这两处同时作废章节缓存 —— 缓存按文档高度判活,重排后必须重扫。
'hyperLensSectionsPost();\n'
// 语法树:一次带全(结构由 DOM 决定,折叠不改结构,所以不跟高度重发)
'hyperLensSyntaxPost();\n'
// 同一个入口名字与 Markdown 一致(`HyperlensCommands.requestSyntaxAst`):
// 首屏那一条可能丢(页面重载、白屏重试、站点停止/运行来回切),宿主切到
// 「源镜」页时会调它补一份 —— 没这个,面板就永远停在「还没有解析结果」。
'window.hyperlensSyntaxAst = function () { hyperLensSyntaxPost(); };\n'
// 之后的高度变化(折叠展开、图片撑开)也要重扫,见 hyperLensWatchResize
'hyperLensWatchResize();\n'
// 链接点击回一条 link;页面活了回一条 render(两种文档同一条回执)
'hyperLensAnchorWatchLinks($linkPrefix);\n'
'hyperLensAnchorRenderReady();\n'
"window.addEventListener('load', function () { $loadBody });\n"
"window.addEventListener('resize', function () { "
'hyperLensInvalidateSections(); hyperLensAnchorSchedule(250); '
'setTimeout(hyperLensSectionsPost, 250); }, { passive: true });';
}