All files / app-play/src inline-search.ts

91.57% Statements 87/95
83.01% Branches 44/53
90% Functions 18/20
95.12% Lines 78/82

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226                                                                7x   7x 7x 7x                             11x                                                                           3x 3x         3x 3x 3x 3x 3x   3x 2x 1x   3x 3x 3x 3x   3x 3x   3x 2x   1x 1x 1x 1x 1x   1x 1x             3x 3x       3x 3x                 1x         3x 3x 3x 3x 3x 3x 3x         7x 7x 7x 7x 7x 7x                         3x 1x 1x 1x 1x 2x 2x 2x 2x   1x       3x 1x 1x 1x 1x 5x 1x 1x         2x 2x 2x 2x             2x 2x 2x 2x 2x 2x 2x 2x      
import { render } from 'lit';
 
/** A rectangle in CSS pixels. */
export interface FieldRect {
  fontSize?: number;
  x: number;
  y: number;
  width: number;
  height: number;
}
 
/** Where and how large the search field sits over a skin's search box, in its containing block's CSS pixels. */
export interface InlineFieldPlacement {
  textScale?: number;
  left: number;
  top: number;
  width: number;
  height: number;
  fontSize: number;
}
 
/**
 * Lays the search field over a skin's search box: `field` is the box on the canvas (from the select scene), `canvas`
 * and `container` are the page boxes of the canvas and of the element the field is positioned in. The text is sized to the box (a little over a third of its height, as the built-in skins set theirs; never
 * under 12 px so it stays readable, and never under 16 px on touch screens, where a smaller font makes iOS zoom in).
 */
export function placeInlineField(
  field: FieldRect,
  canvas: { left: number; top: number },
  container: { left: number; top: number },
  touch = false,
): InlineFieldPlacement {
  const requested = field.fontSize ?? Math.round(field.height * 0.38);
  const fontSize =
    field.fontSize === undefined ? Math.max(touch ? 16 : 12, requested) : Math.max(touch ? 16 : 1, requested);
  const textScale = field.fontSize !== undefined && touch ? Math.min(1, requested / fontSize) : 1;
  return {
    left: canvas.left - container.left + field.x,
    top: canvas.top - container.top + field.y,
    width: field.width / textScale,
    height: field.height / textScale,
    fontSize,
    ...(textScale < 1 ? { textScale } : {}),
  };
}
 
/**
 * The element `element`'s `left` / `top` are measured from: its offset parent (the player's main area, under the
 * header), or `fallback` while it has none (hidden).
 */
export function positioningContainer<T>(element: { readonly offsetParent: unknown }, fallback: T): T {
  return (element.offsetParent as T | null) ?? fallback;
}
 
/** What the inline search needs from the player. */
export interface InlineSearchHost {
  /** A native skin can supply and focus its own input. */
  nativeSearch?(): { focus(): void } | undefined;
  readonly input: HTMLInputElement;
  /** Where the field says why a chart filter expression (`?…`) does not parse; it sits just under the field. */
  readonly error?: HTMLElement;
  /** Where the field and the error are positioned when they have no offset parent of their own. */
  readonly shell: HTMLElement;
  /** The canvas the select scene draws on. */
  canvas(): HTMLCanvasElement | undefined;
  /** The skin's search box on the canvas, or undefined when the scene on screen has none (beatoraja, Plain portrait…). */
  fieldRect(): FieldRect | undefined;
  /** Filters the scene on screen. */
  setQuery(query: string): void;
  /** Why the scene's chart filter expression does not parse, or `undefined` when it does (or is a text search). */
  searchError?(): string | undefined;
  /** Tells the scene whether the field sits over its box, so it leaves the box's text to the field. */
  setEditing(editing: boolean): void;
  /** Whether the page is used by touch first (larger text, no iOS zoom). */
  touch(): boolean;
}
 
/**
 * The search field. Where the skin draws a search box, typing happens in place: the field moves over the box (and
 * follows it while it moves or the window resizes) and the skin stops drawing the box's text until the field is left.
 * Elsewhere — a beatoraja skin, which has no box — the field stays where it is, at the foot of the screen.
 *
 * IME: while a composition is in progress the list is not narrowed by the half-typed reading; the query is applied when
 * the composition commits.
 *
 * A query that starts with `?` is a chart filter expression; while it does not parse, the field is marked invalid and
 * the reason shows under it (the list stays unfiltered).
 */
export class InlineSearch {
  private following = 0;
  private inline = false;
 
  private readonly host: InlineSearchHost;
 
  constructor(host: InlineSearchHost) {
    this.host = host;
    const { input } = host;
    const setQuery = (query: string): void => {
      host.setQuery(query);
      this.showError();
    };
    input.addEventListener('input', (event) => {
      if ((event as InputEvent).isComposing) return;
      setQuery(input.value);
    });
    input.addEventListener('compositionend', () => setQuery(input.value));
    input.addEventListener('focus', () => {
      this.attach();
      this.placeError();
    });
    input.addEventListener('blur', () => this.detach());
    input.addEventListener('keydown', (event) => {
      // Keys that confirm a conversion belong to the IME.
      if (event.isComposing) return;
      if (event.key === 'Escape') {
        // Clears the filter and gives the keys back to the list.
        event.preventDefault();
        input.value = '';
        setQuery('');
        input.blur();
      } else Eif (event.key === 'Enter') {
        // The query already moved the cursor to the first match: leaving the field lets the next Enter pick it.
        event.preventDefault();
        input.blur();
      }
    });
  }
 
  /** Starts typing: focuses the field (over the skin's box when there is one) with its text selected. */
  open(): void {
    const native = this.host.nativeSearch?.();
    Iif (native) {
      native.focus();
      return;
    }
    this.host.input.focus();
    this.host.input.select();
  }
 
  /**
   * {@link open} for a click on the skin's box. The scene reports the click from its `pointerdown`; the browser's
   * `mousedown` that follows would move focus back to the page and close the field at once, so it opens once the
   * click's events have run.
   */
  openFromPointer(): void {
    setTimeout(() => this.open(), 0);
  }
 
  /** Marks the field invalid and shows why under it while the scene's chart filter expression does not parse. */
  showError(): void {
    const { input, error } = this.host;
    const message = this.host.searchError?.();
    input.setAttribute('aria-invalid', message === undefined ? 'false' : 'true');
    Iif (error === undefined) return;
    render(message ?? '', error);
    error.hidden = message === undefined;
    if (message !== undefined) this.placeError();
  }
 
  /** Puts the error just under the field, wherever the field is now (at the foot, over the skin's box, at the top). */
  private placeError(): void {
    const { input, error, shell } = this.host;
    Iif (error === undefined || error.hidden) return;
    const field = input.getBoundingClientRect();
    const origin = positioningContainer<Element>(error, shell).getBoundingClientRect();
    error.style.left = `${field.left - origin.left}px`;
    error.style.top = `${field.bottom - origin.top + 4}px`;
  }
 
  /** Whether the skin on screen draws its own search box, so the field at the foot of the screen can step aside. */
  get ownsNativeInput(): boolean {
    return this.host.nativeSearch?.() !== undefined;
  }
 
  get skinHasBox(): boolean {
    return this.host.nativeSearch?.() !== undefined || this.host.fieldRect() !== undefined;
  }
 
  private attach(): void {
    if (this.host.fieldRect() === undefined) return;
    this.inline = true;
    this.host.input.classList.add('search-inline');
    this.host.setEditing(true);
    const follow = () => {
      Iif (!this.inline) return;
      this.place();
      this.placeError();
      this.following = requestAnimationFrame(follow);
    };
    follow();
  }
 
  private detach(): void {
    if (!this.inline) return;
    this.inline = false;
    cancelAnimationFrame(this.following);
    const { input } = this.host;
    input.classList.remove('search-inline');
    for (const property of ['left', 'top', 'width', 'height', 'font-size']) input.style.removeProperty(property);
    this.host.setEditing(false);
    this.placeError();
  }
 
  /** Moves the field over the box as it is now; leaves it be when the box went away mid-edit. */
  private place(): void {
    const field = this.host.fieldRect();
    const canvas = this.host.canvas();
    Iif (field === undefined || canvas === undefined) return;
    const placement = placeInlineField(
      field,
      canvas.getBoundingClientRect(),
      // The header sits above the field's containing block, so the shell's box would put the field a header too low.
      positioningContainer<Element>(this.host.input, this.host.shell).getBoundingClientRect(),
      this.host.touch(),
    );
    const { style } = this.host.input;
    style.left = `${placement.left}px`;
    style.top = `${placement.top}px`;
    style.width = `${placement.width}px`;
    style.height = `${placement.height}px`;
    style.fontSize = `${placement.fontSize}px`;
    style.transformOrigin = 'top left';
    style.transform = placement.textScale === undefined ? 'none' : `scale(${placement.textScale})`;
  }
}