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.

8.2 KB
Raw Blame
---
/*
 * A screenshot or app sketch with numbered pins over it and a numbered legend under it. Each `Callout` child is one
 * legend entry, and its pin is drawn over the media at the callout's `x`/`y` (percent of the media's width/height):
 *
 *   <Annotated src={screenshot} alt="…">
 *     <Callout x={12} y={30} label="Used">Intermediates that a delete keeps…</Callout>
 *   </Annotated>
 *
 * A sketch passes its drawing in the `sketch` slot instead, with its stage size (`Stage.astro` units) and a `label`
 * naming the picture; see `IntermediatesSettingsSketch.astro`.
 *
 * The legend is the accessible content: each entry's pin is a link to the entry, named by the callout's label, so
 * keyboard users can tab through the pins and screen readers read each entry once. Pins live inside their entries,
 * which links them without script: pointing at or focusing either highlights both (`:hover` and `:focus-within` on
 * the entry). Without JavaScript a pin jumps to its entry and `:target` keeps it highlighted. With it, one entry at
 * most is chosen (`data-active`): a click or tap on a pin or entry, keyboard focus on a pin, or the URL's fragment on
 * load chooses it; Escape, or a click outside the figure's entries, clears it. A chosen pin keeps the page still and
 * scrolls its entry into view only if needed, which is what a tap on a touchscreen needs.
 *
 * Place pins in empty space touching the control they name, with `labelSide` pointing the hover label away from it.
 * Keep pin centres at least 8% of the media's width apart (measure `y` distances in width units: times the media's
 * height over its width): below a 550px-wide media the tap targets shrink to 8% of the width, so closer pins would
 * share tap area on a phone.
 *
 * Pins are absolutely positioned against the media, which fills the top of the size container `.annotated__body`, so
 * their offsets are `cqw` multiples: `x` of the width, and `y` of the height, which is the width times the media's
 * aspect ratio.
 */
import type { ImageMetadata } from 'astro';
import { Image } from 'astro:assets';

import Stage from '../whats-new/Stage.astro';
import { nextFigureIndex, numberCallouts } from './callout-ids.mjs';

type Props = {
  class?: string;
} & (
  | { /** A screenshot. */ src: ImageMetadata; alt: string; label?: never; width?: never; height?: never }
  | {
      src?: never;
      alt?: never;
      /** Names the sketch in the `sketch` slot for screen readers. */
      label: string;
      /** The sketch's stage size, in `Stage.astro` units. */
      width: number;
      height: number;
    }
);

const { class: className, src, alt, label, width, height } = Astro.props;
const { t } = Astro.locals;

const mediaWidth = src ? src.width : width;
const mediaHeight = src ? src.height : height;
if (!mediaWidth || !mediaHeight) throw new Error('Annotated needs an image `src`, or a sketch `width` and `height`.');
if (src && !alt) throw new Error('Annotated needs `alt` text for its image.');
if (!src && !label) throw new Error('Annotated needs a `label` naming its sketch.');

// Entry ids count figures and entries in page order, so links to them survive rebuilds.
const figure = nextFigureIndex(Astro.locals);
const legend = numberCallouts(await Astro.slots.render('default'), figure);
---

<figure class:list={['annotated not-content', className]} data-annotated>
  {/* Marks the figure before first paint, so the no-script highlight rules (`:target`, `:focus-within`) never apply. */}
  <script is:inline>
    document.currentScript.parentElement.dataset.js = '';
  </script>
  <div class="annotated__body" style={`--annotated-ratio: ${mediaHeight / mediaWidth}`}>
    {
      src ? (
        <Image
          class="annotated__media"
          src={src}
          alt={alt}
          widths={[640, src.width]}
          sizes="(min-width: 72rem) 52rem, calc(100vw - 2rem)"
          loading="lazy"
          decoding="async"
        />
      ) : (
        <div class="annotated__media annotated__media--sketch" role="img" aria-label={label}>
          <Stage width={width!} height={height!}>
            <slot name="sketch" />
          </Stage>
        </div>
      )
    }
    {/* `role="list"`: Safari drops list semantics from a list without list markers. */}
    <ol class="annotated__legend" role="list" aria-label={t('annotated.legend')}>
      <Fragment set:html={legend} />
    </ol>
  </div>
</figure>

<script>
  /*
   * The chosen entry (`data-active`), at most one per page: listeners sit on the document, so Escape and clicks
   * outside a figure clear it wherever focus is.
   */
  const ENTRY = '[data-annotated-entry]';
  const PIN = '[data-annotated-pin]';
  const reducedMotion = window.matchMedia('(prefers-reduced-motion: reduce)');

  const choose = (entry: HTMLElement | null) => {
    for (const other of document.querySelectorAll<HTMLElement>(`${ENTRY}[data-active]`)) {
      if (other !== entry) delete other.dataset.active;
    }
    if (entry) entry.dataset.active = '';
  };

  const entryOf = (target: EventTarget | null) =>
    target instanceof Element ? target.closest<HTMLElement>(`[data-annotated] ${ENTRY}`) : null;

  document.addEventListener('click', (event) => {
    const target = event.target as Element;
    const entry = entryOf(target);
    // A link in an entry's description keeps its own behaviour.
    if (entry && target.closest(`a:not(${PIN})`)) return;
    choose(entry);
    if (entry && target.closest(PIN)) {
      event.preventDefault();
      entry.scrollIntoView({ block: 'nearest', behavior: reducedMotion.matches ? 'auto' : 'smooth' });
    }
  });

  // Keyboard focus on a pin chooses its entry; focus leaving the pins clears it, unless a click chose an entry.
  document.addEventListener('focusin', (event) => {
    if ((event.target as Element).matches?.(`[data-annotated] ${PIN}`)) choose(entryOf(event.target));
  });
  document.addEventListener('focusout', (event) => {
    if ((event.target as Element).matches?.(PIN) && !(event.relatedTarget as Element | null)?.matches?.(PIN)) {
      const entry = entryOf(event.target);
      // A click inside an entry lands after focus leaves, and chooses again.
      if (entry) delete entry.dataset.active;
    }
  });

  document.addEventListener('keydown', (event) => {
    if (event.key !== 'Escape' || !document.querySelector(`${ENTRY}[data-active]`)) return;
    choose(null);
    const focused = document.activeElement;
    if (focused instanceof HTMLElement && focused.matches(PIN)) focused.blur();
  });

  // A link to an entry chooses it, as `:target` does without script.
  const fromHash = () => {
    let id = location.hash.slice(1);
    try {
      id = decodeURIComponent(id);
    } catch {
      // A malformed fragment names no entry.
    }
    const entry = id ? entryOf(document.getElementById(id)) : null;
    if (entry) choose(entry);
  };
  fromHash();
  window.addEventListener('hashchange', fromHash);
</script>

<style>
  .annotated {
    /* The tour frames' shell: see `.compare` in compare/ImageCompare.astro. */
    --frame-inset: 0.375rem;
    --inner-radius: calc(var(--docs-radius-container) - var(--frame-inset) - 1px);
    margin: 0;
    /* A hover label near an edge must not widen the page. */
    overflow: clip;
    padding: var(--frame-inset);
    border: 1px solid var(--docs-border);
    border-radius: var(--docs-radius-container);
    background-color: var(--docs-surface);
  }

  .annotated__body {
    position: relative;
    container-type: inline-size;
  }

  .annotated__media {
    display: block;
    overflow: hidden;
    width: 100%;
    height: auto;
    border-radius: var(--inner-radius);
  }

  .annotated__media--sketch {
    --stage-width: 100%;
    background-color: var(--docs-bg);
  }

  /*
   * Two columns where each gets 20rem, one on narrower screens. Entries flow down the first column and on into the
   * second, as text does, so entries of different heights leave no holes, and the numbers read down each column in
   * DOM order. An entry never splits across columns.
   */
  .annotated__legend {
    columns: 2 20rem;
    column-gap: 0.5rem;
    margin: 0;
    padding: 0.375rem 0 0;
    list-style: none;
    counter-reset: annotated;

    > :global(*) {
      break-inside: avoid;
    }

    > :global(* + *) {
      margin-top: 0.125rem;
    }
  }
</style>