resolveMarkdownLink function

MarkdownLinkAction resolveMarkdownLink({
  1. required String fromRelPath,
  2. required String href,
})

把 href 按「它写在 fromRelPath 这个文件里」来解析。

支持:./a/b.md、../c.md、/d.md(相对仓库根)、带 #锚点/?query、 %20 转义、<url> 包裹、协议相对 //host/path、以及 http/https/mailto/tel。

跨文件的 #片段 不再丢弃:它随 OpenRepoFile.fragment 交给上层落位 (纯锚点 #x 仍归 IgnoreLink —— 那是同一份文档内部的滚动,页面自己会做)。

Implementation

MarkdownLinkAction resolveMarkdownLink({
  required String fromRelPath,
  required String href,
}) {
  String link = href.trim();
  if (link.isEmpty) {
    return const IgnoreLink();
  }
  // 页内锚点:WebView 自己就能滚,不必绕一圈 Dart
  if (link.startsWith('#')) {
    return const IgnoreLink();
  }
  // Markdown 允许把地址写成 <url>
  if (link.length > 2 && link.startsWith('<') && link.endsWith('>')) {
    link = link.substring(1, link.length - 1).trim();
  }
  // 协议相对://example.com/a → https://example.com/a
  if (link.startsWith('//')) {
    link = 'https:$link';
  }

  final Uri? uri = Uri.tryParse(link);
  if (uri != null && uri.scheme.isNotEmpty) {
    if (kPreviewExternalSchemes.contains(uri.scheme.toLowerCase())) {
      return OpenExternal(link);
    }
    return const IgnoreLink(); // file: / ohos: / javascript: 之类一律不跳
  }

  // 仓库内路径:先切下锚点(片段留着交给落位),再切掉查询串
  String path = link;
  String? fragment;
  final int hash = path.indexOf('#');
  if (hash >= 0) {
    final String raw = path.substring(hash + 1);
    path = path.substring(0, hash);
    if (raw.isNotEmpty) {
      // 作者可能写 `#%E4%B8%AD`:解码一次,落到页面里按 id 找才对得上
      try {
        fragment = Uri.decodeComponent(raw);
      } on ArgumentError {
        fragment = raw;
      }
    }
  }
  final int query = path.indexOf('?');
  if (query >= 0) {
    path = path.substring(0, query);
  }
  if (path.isEmpty) {
    return const IgnoreLink();
  }

  // 反斜杠按分隔符处理;`%20` 这类转义还原(Markdown 里的空格常被编码)
  path = path.replaceAll(r'\', '/');
  // 尾斜杠是「这是目录」的信号,normalize 之后要还回去
  final bool isDir = path.endsWith('/');
  try {
    path = Uri.decodeComponent(path);
  } on ArgumentError {
    // 转义有问题时按原样使用,别把整次点击丢掉
  }

  // 以 `/` 开头 = 相对仓库根;否则相对**当前文件所在目录**
  final String base = path.startsWith('/') ? '' : p.posix.dirname(fromRelPath);
  final String joined = p.posix.normalize(
    p.posix.join(base, path.replaceFirst(RegExp(r'^/+'), '')),
  );
  if (joined.isEmpty ||
      joined == '.' ||
      joined == '..' ||
      joined.startsWith('../')) {
    return const IgnoreLink(); // 越出仓库根(或指向根本身)
  }
  // normalize 是否保留尾斜杠随实现而变,这里统一成「不带尾斜杠」再加
  final String clean =
      joined.endsWith('/') ? joined.substring(0, joined.length - 1) : joined;
  return OpenRepoFile(isDir ? '$clean/' : clean, fragment: fragment);
}