import scrollIntoView from "scroll-into-view-if-needed";
import {
  LinkDefinition as BaseLinkDefinition
} from "@makeswift/controls";
function validateElementRef(href) {
  try {
    const hash = new URL(`http://www.example.com/${href}`).hash;
    return href === hash ? hash : void 0;
  } catch (error) {
    return void 0;
  }
}
class LinkDefinition extends BaseLinkDefinition {
  static deserialize(data) {
    if (data.type !== LinkDefinition.type) {
      throw new Error(`Link: expected type ${LinkDefinition.type}, got ${data.type}`);
    }
    const { config } = LinkDefinition.schema.definition.parse(data);
    return Link(config);
  }
  resolveOnClick(data, href, scrollOptions) {
    const onClick = (event) => {
      if (event.defaultPrevented)
        return;
      if (data && data.type === "SCROLL_TO_ELEMENT") {
        const hash = validateElementRef(href);
        if (hash == null) {
          console.error(`Scroll-to-element link received invalid href: ${href}`);
          return;
        }
        event.preventDefault();
        const view = event.view;
        scrollIntoView(view.document.querySelector(hash), {
          behavior: "smooth",
          block: scrollOptions?.block
        });
        if (view.location.hash !== hash)
          view.history.pushState({}, "", hash);
      }
    };
    onClick.$scrollOptions = scrollOptions;
    return onClick;
  }
}
function Link(config) {
  return new LinkDefinition(config ?? {});
}
export {
  Link,
  LinkDefinition,
  validateElementRef
};
//# sourceMappingURL=link.js.map