/// What following one link inside a recorded HTML document does.
enum ArtifactHtmlLinkAction {
/// A place in the same document (`#section`): the view scrolls to it.
inDocument,
/// An `http`, `https` or `mailto` address: it opens outside the artifact
/// (a new browser tab on the web, the system's handler on a phone), never
/// inside the document's view.
external,
/// Anything else (`javascript:`, `file:`, `data:`, a relative path the
/// document has no base for): the link stays inert.
blocked,
}
const _externalSchemes = {'http', 'https', 'mailto'};
/// The documents the views load the recorded HTML as: a web view's
/// `about:blank` and an iframe's `about:srcdoc`.
const _documentUrls = {'about:blank', 'about:srcdoc'};
/// Decides what a link in a recorded HTML document does, from the raw `href`
/// (the web view rewrites anchors before showing the document) or the url a
/// mobile web view resolved it to.
///
/// The document is loaded from a string, so it has no address of its own: a
/// relative link cannot resolve to the artifact's neighbours and stays inert
/// rather than reaching the app's own origin.
ArtifactHtmlLinkAction artifactHtmlLinkAction(String href) {
final link = href.trim();
if (link.isEmpty) return ArtifactHtmlLinkAction.blocked;
if (link.startsWith('#')) return ArtifactHtmlLinkAction.inDocument;
final uri = Uri.tryParse(link);
if (uri == null || !uri.hasScheme) return ArtifactHtmlLinkAction.blocked;
final scheme = uri.scheme.toLowerCase();
if (_externalSchemes.contains(scheme)) {
// `http:foo` with no host is not an address anyone can open.
if (scheme != 'mailto' && uri.host.isEmpty) {
return ArtifactHtmlLinkAction.blocked;
}
return ArtifactHtmlLinkAction.external;
}
if (scheme == 'about') {
final document = link.split('#').first.toLowerCase();
if (_documentUrls.contains(document)) {
return ArtifactHtmlLinkAction.inDocument;
}
}
return ArtifactHtmlLinkAction.blocked;
}