Skip to content

Invoke is a leading creative engine that uses image and video generation models to empower professionals, artists, and enthusiasts to generate and create visual media using the latest AI-driven technologies. The solution offers an industry-leading application interface, and serves as the foundation for multiple commercial products.

5.8 KB
Raw Blame
---
import ArrowUpRight from '@lucide/astro/icons/arrow-up-right';
import ChevronDown from '@lucide/astro/icons/chevron-down';
import Copy from '@lucide/astro/icons/copy';

import { splitSitePath } from '../../config/locales.mjs';
import { withBase } from '../base-path';
import { isDocsPage } from '../docs-page';

type Props = {
  /** Distinguishes the element ids of the copies in the right rail and the footer. */
  instance: string;
};

const menuId = `docs-page-actions-menu-${Astro.props.instance}`;

// starlight-markdown serves each docs page's Markdown source at `<page>/index.md`. Pages generated by other plugins,
// such as the changelogs, have none.
const { entry, isFallback } = Astro.locals.starlightRoute;
const { t } = Astro.locals;
const base = import.meta.env.BASE_URL;
const hasMarkdown = await isDocsPage(entry.id);
// A locale's page without a translation shows the English entry, whose source is at the English path.
const pagePath = isFallback ? withBase(splitSitePath(Astro.url.pathname, base)!.path, base) : Astro.url.pathname;
const markdownHref = `${pagePath.replace(/\/?$/, '/')}index.md`;
const prompt = encodeURIComponent(
  t('pageActions.aiPrompt', {
    url: new URL(Astro.url.pathname, Astro.site).href,
    interpolation: { escapeValue: false },
  })
);
const links = [
  { label: t('pageActions.viewMarkdown'), href: markdownHref },
  { label: t('pageActions.openInChatGPT'), href: `https://chatgpt.com/?q=${prompt}` },
  { label: t('pageActions.openInClaude'), href: `https://claude.ai/new?q=${prompt}` },
];
// The copy button's feedback, which the script below shows.
const i18n = {
  copy: t('pageActions.copy'),
  copied: t('pageActions.copyDone'),
  copiedStatus: t('pageActions.copyDoneStatus'),
  copyFailed: t('pageActions.copyFailed'),
  copyFailedStatus: t('pageActions.copyFailedStatus'),
};
---

{
  hasMarkdown && (
    <docs-page-actions class="page-actions" data-markdown-href={markdownHref} data-i18n={JSON.stringify(i18n)}>
      <div class="buttons">
        <button type="button" class="copy docs-button docs-button--secondary">
          <Copy size={14} />
          <span data-label>{i18n.copy}</span>
        </button>
        <button
          type="button"
          class="toggle docs-button docs-button--secondary docs-button--icon"
          aria-expanded="false"
          aria-controls={menuId}
          aria-label={t('pageActions.more')}
        >
          <ChevronDown size={12} />
        </button>
      </div>
      <ul id={menuId} class="menu docs-popup" hidden>
        {links.map(({ label, href }) => (
          <li>
            <a href={href} target="_blank" rel="noopener noreferrer">
              {label}
              <ArrowUpRight size={12} />
            </a>
          </li>
        ))}
      </ul>
      <span class="sr-only" role="status" />
    </docs-page-actions>
  )
}

<script>
  import { bindDisclosure } from '../disclosure';

  const RESET_DELAY_MS = 2000;

  class DocsPageActions extends HTMLElement {
    connectedCallback() {
      const copy = this.querySelector<HTMLButtonElement>('.copy')!;
      const label = copy.querySelector<HTMLElement>('[data-label]')!;
      const status = this.querySelector<HTMLElement>('[role="status"]')!;
      const menu = bindDisclosure(this, this.querySelector('.toggle')!, this.querySelector('ul')!);
      const i18n: Record<string, string> = JSON.parse(this.dataset.i18n!);
      let resetTimer: number | undefined;

      const report = (text: string, announcement: string) => {
        label.textContent = text;
        status.textContent = announcement;
        clearTimeout(resetTimer);
        resetTimer = window.setTimeout(() => {
          label.textContent = i18n.copy;
          status.textContent = '';
        }, RESET_DELAY_MS);
      };

      copy.addEventListener('click', async () => {
        menu.close();
        try {
          // Hand the clipboard a pending blob right away: Safari only allows clipboard writes during the click.
          const markdown = fetch(this.dataset.markdownHref!).then(async (response) => {
            if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);
            return new Blob([await response.text()], { type: 'text/plain' });
          });
          await navigator.clipboard.write([new ClipboardItem({ 'text/plain': markdown })]);
          report(i18n.copied, i18n.copiedStatus);
        } catch (error) {
          console.error('Could not copy the page as Markdown:', error);
          report(i18n.copyFailed, i18n.copyFailedStatus);
        }
      });
      for (const link of this.querySelectorAll('ul a')) link.addEventListener('click', () => menu.close());
    }
  }
  customElements.define('docs-page-actions', DocsPageActions);
</script>

<style>
  .page-actions {
    position: relative;
    display: block;
  }

  .buttons {
    display: flex;
  }

  /* Two buttons joined into one split button. */
  .copy {
    flex: 1;
    justify-content: flex-start;
    border-start-end-radius: 0;
    border-end-end-radius: 0;
  }

  .toggle {
    border-inline-start: 0;
    border-start-start-radius: 0;
    border-end-start-radius: 0;
  }

  .menu {
    position: absolute;
    inset-inline: 0;
    top: calc(100% + 0.375rem);
    z-index: 1;
    margin: 0;
    padding: 0.25rem;
    list-style: none;
    border: 1px solid var(--docs-border-strong);
    border-radius: var(--docs-radius-lg);
    background: var(--docs-control);
    box-shadow: var(--docs-shadow-popup);
  }

  a {
    display: flex;
    align-items: center;
    justify-content: space-between;
    gap: 0.5rem;
    padding: 0.375rem 0.5rem;
    border-radius: var(--docs-radius);
    color: var(--docs-text-strong);
    font-size: var(--sl-text-xs);
    text-decoration: none;

    svg {
      color: var(--docs-text-subtle);
    }

    &:hover {
      background: var(--docs-hover);
    }
  }
</style>