All files / app-play/src/ui/options course-tables.ts

9.09% Statements 5/55
0% Branches 0/12
5.26% Functions 1/19
10.63% Lines 5/47

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                                4x 4x 4x 4x   1x                                                                                                                                                                                                                                                      
// The Options dialog's list of difficulty tables, in the Course folder: the remembered tables, each with a remove
// button, and a field that adds one. A table added here imports at once; every remembered table imports again each time
// the player opens (`LibraryService.autoLoad`). Removing one takes its courses off the select screen at once.
import { html, render } from 'lit';
import {
  DEFAULT_COURSE_TABLE_URLS,
  normalizeCourseTableURL,
  readStoredCourseTableURLs,
  storeCourseTableURLs,
} from '../../course-table-import.ts';
import { playerText } from '../../player-copy.ts';
import type { LibraryService } from '../../services/library.ts';
import { localized } from '../localized.ts';
 
/** A table's name before it has imported this session: its host and path, which tell tables on one host apart. */
export function courseTableURLLabel(url: string): string {
  try {
    const { host, pathname, search } = new URL(url);
    const path = decodeURIComponent(pathname).replace(/\/$/u, '');
    return `${host}${path}${search}`;
  } catch {
    return url;
  }
}
 
/** Mounts the table list into `root`, which it owns. */
export function mountCourseTableManager(
  root: HTMLElement,
  {
    library,
    setStatus,
    saveSettings,
  }: {
    library: Pick<
      LibraryService,
      'importCourseTables' | 'removeCourseTable' | 'courseTableLabel' | 'onCourseTablesChange'
    >;
    setStatus: (text: string) => void;
    /** Publishes the settings, which carry the table list to the player's other browsers. */
    saveSettings: () => void;
  },
): void {
  let tables = readStoredCourseTableURLs();
  let draft = '';
  let importing = false;
 
  const label = (url: string) => library.courseTableLabel(url) ?? courseTableURLLabel(url);
  /** Imports `urls` and remembers the ones that imported; a table that fails to import stays off the list. */
  const importTables = async (urls: readonly string[]) => {
    importing = true;
    update();
    try {
      await library.importCourseTables(urls, true);
    } finally {
      importing = false;
      tables = readStoredCourseTableURLs();
      saveSettings();
      update();
    }
  };
  const add = (event: Event) => {
    event.preventDefault();
    const url = normalizeCourseTableURL(draft);
    if (url === undefined) {
      setStatus(playerText().shell.invalidCourseTableURL);
      return;
    }
    draft = '';
    if (tables.includes(url)) {
      update();
      return;
    }
    void importTables([url]);
  };
  /** Adds the well-known tables the list lacks (removed, or added to the defaults later) and imports them. */
  const restoreDefaults = () => {
    const missing = DEFAULT_COURSE_TABLE_URLS.filter((url) => !tables.includes(url));
    if (missing.length > 0) void importTables(missing);
  };
  const remove = (url: string) => {
    tables = storeCourseTableURLs(tables.filter((table) => table !== url));
    saveSettings();
    update();
    void library.removeCourseTable(url);
  };
 
  function update(): void {
    render(
      html`
        <section aria-labelledby="course-tables-heading">
          <h3 id="course-tables-heading">${localized('courseTables')}</h3>
          <p>${localized('courseTablesHint')}</p>
          <ul class="remembered-folder-list">
            ${tables.map(
              (url) => html`
                <li>
                  <span title=${url}>${label(url)}</span>
                  <button
                    type="button"
                    class="btn"
                    aria-label=${localized(() => playerText().shell.removeCourseTable(label(url)))}
                    @click=${() => remove(url)}
                  >
                    ${localized('removeFolder')}
                  </button>
                </li>
              `,
            )}
          </ul>
          <form class="bemuse-server-form" @submit=${add}>
            <input
              class="input"
              type="url"
              required
              aria-label=${localized('courseTableURL')}
              placeholder="https://stellabms.xyz/sl/table.html"
              .value=${draft}
              ?disabled=${importing}
              @input=${(event: Event) => {
                draft = (event.target as HTMLInputElement).value;
              }}
            />
            <button type="submit" class="btn" ?disabled=${importing}>${localized('addCourseTable')}</button>
          </form>
          ${
            DEFAULT_COURSE_TABLE_URLS.some((url) => !tables.includes(url))
              ? html`<button type="button" class="btn" ?disabled=${importing} @click=${restoreDefaults}>
                  ${localized('restoreCourseTables')}
                </button>`
              : null
          }
        </section>
      `,
      root,
    );
  }
 
  // Tables import on load after the dialog is built, and the list shows their names once they have.
  library.onCourseTablesChange(() => {
    if (!importing) tables = readStoredCourseTableURLs();
    update();
  });
  update();
}