All files / app-play/src/ui/options layout.ts

90.9% Statements 100/110
86.66% Branches 39/45
89.65% Functions 26/29
93.61% Lines 88/94

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 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282                                                                                                                                          15x 15x 15x 15x 15x 15x 35x 35x 35x   15x             35x 23x 23x 23x 23x 23x 35x 35x 35x   35x 35x     15x           51x 88x 52x             52x 52x 36x 12x 12x 12x 24x 16x 16x 16x 16x 16x 16x   8x       15x 15x                                                                   14x 14x       14x 14x 14x               37x 37x 36x 35x           5x         2x 4x 4x   13x             17x 17x 17x         8x 8x 8x         3x         1x 5x 3x       35x 35x 30x 30x 30x 1x   29x 29x 29x 5x 4x 4x     29x                     36x 36x 36x     33x 33x 2x 2x                 35x 35x 35x      
// Builds the Options dialog's containers from its validated layout and places controls by id.
import type { OptionContainer } from '../options-controls.ts';
import type {
  OptionDefault,
  OptionDefaultValue,
  OptionLayoutItem,
  OptionLayoutTabs,
  OptionRowKind,
  OptionsLayout,
  RuntimeDefaultResolver,
} from '../../options-layout-schema.ts';
 
export * from '../../options-layout-schema.ts';
 
/** A row as the layout sees it: whether the layout leaves it off the dialog. */
export interface LayoutRow {
  omitted: boolean;
}
 
/** Something that holds rows: the dialog, a folder or a page. */
export interface LayoutContainer {
  addFolder(params: { title: string }): LayoutFolder;
  addTab(params: { pages: readonly { title: string }[] }): LayoutTabs;
  /** Moves `row`, one of its rows, to the place of `rank` among the others: after those of a rank up to it. */
  placeAt(row: LayoutRow, rank: number): void;
  addSectionReset?(reset: () => void): void;
}
export interface LayoutFolder extends LayoutContainer, LayoutRow {}
export interface LayoutTabs extends LayoutRow {
  readonly pages: readonly LayoutContainer[];
  /** Leaves a page's tab off the bar, or brings it back. */
  omitPage(index: number, omitted: boolean): void;
}
 
/** Where the code puts an option's or a group's rows. */
export interface LayoutSlot<C> {
  readonly container: C;
  /** Its place among the items of `container`. */
  readonly rank: number;
  /** An option's kind; `undefined` for a group. */
  readonly kind: OptionRowKind | undefined;
  readonly hidden: boolean;
  readonly default?: OptionDefault;
}
 
/** A page of tabs on the way to an item: the tabs' id and the page's index. */
export interface LayoutStep {
  readonly tabs: string;
  readonly page: number;
}
 
/** The containers {@link assembleOptionsLayout} made, by id, and the places the code fills. */
export interface AssembledOptionsLayout<C extends LayoutContainer> {
  readonly folders: ReadonlyMap<string, ReturnType<C['addFolder']>>;
  readonly tabs: ReadonlyMap<string, ReturnType<C['addTab']>>;
  readonly slots: ReadonlyMap<string, LayoutSlot<LayoutContainer>>;
  /** The pages to select, outermost first, to show each item. */
  readonly paths: ReadonlyMap<string, readonly LayoutStep[]>;
  readonly sectionSlots: ReadonlyMap<LayoutContainer, ReadonlySet<string>>;
}
 
/**
 * Makes the dialog's tabs, pages and folders in `root`, in the layout's order, leaving off those it hides, and lists
 * where each option and group goes. The rows themselves are the code's to make ({@link OptionLayout.place}).
 */
export function assembleOptionsLayout<C extends LayoutContainer>(
  layout: OptionsLayout,
  root: C,
): AssembledOptionsLayout<C> {
  const folders = new Map<string, LayoutFolder>();
  const tabs = new Map<string, LayoutTabs>();
  const slots = new Map<string, LayoutSlot<LayoutContainer>>();
  const paths = new Map<string, readonly LayoutStep[]>();
  const sectionSlots = new Map<LayoutContainer, Set<string>>();
  const withSection = (container: LayoutContainer, sections: readonly Set<string>[]): readonly Set<string>[] => {
    const ids = new Set<string>();
    sectionSlots.set(container, ids);
    return [...sections, ids];
  };
  const addTabs = (
    parent: LayoutContainer,
    spec: OptionLayoutTabs,
    rank: number,
    path: readonly LayoutStep[],
    sections: readonly Set<string>[],
  ) => {
    const made = parent.addTab({ pages: spec.pages.map((page) => ({ title: page.title })) });
    parent.placeAt(made, rank);
    made.omitted = spec.hidden;
    tabs.set(spec.tabs, made);
    paths.set(spec.tabs, path);
    spec.pages.forEach((page, index) => {
      made.omitPage(index, page.hidden);
      const container = made.pages[index];
      Iif (container === undefined) return;
      // A page made up entirely of folders already has one reset in each of its sections.
      const pageSections = page.items.some((item) => !('folder' in item)) ? withSection(container, sections) : sections;
      fill(container, page.items, [...path, { tabs: spec.tabs, page: index }], pageSections);
    });
  };
  const fill = (
    container: LayoutContainer,
    items: readonly OptionLayoutItem[],
    path: readonly LayoutStep[],
    sections: readonly Set<string>[],
  ) => {
    items.forEach((item, rank) => {
      if ('option' in item) {
        slots.set(item.option, {
          container,
          rank,
          kind: item.kind,
          hidden: item.hidden,
          ...(item.default === undefined ? {} : { default: item.default }),
        });
        paths.set(item.option, path);
        if (item.default !== undefined) for (const ids of sections) ids.add(item.option);
      } else if ('group' in item) {
        slots.set(item.group, { container, rank, kind: undefined, hidden: item.hidden });
        paths.set(item.group, path);
        if (item.reset === true) for (const ids of sections) ids.add(item.group);
      } else if ('folder' in item) {
        const folder = container.addFolder({ title: item.title });
        container.placeAt(folder, rank);
        folder.omitted = item.hidden;
        folders.set(item.folder, folder);
        paths.set(item.folder, path);
        fill(folder, item.items, path, withSection(folder, sections));
      } else {
        addTabs(container, item, rank, path, sections);
      }
    });
  };
  addTabs(root, layout, 0, [], []);
  return {
    folders: folders as Map<string, ReturnType<C['addFolder']>>,
    tabs: tabs as Map<string, ReturnType<C['addTab']>>,
    slots,
    paths,
    sectionSlots,
  };
}
 
/** A row the code made, as the layout checks it. */
export interface PlacedRow extends LayoutRow {
  readonly kind: OptionRowKind | 'folder' | 'tabs';
  resetToDefault?(value: OptionDefaultValue): void;
}
 
/** The ways a container makes rows, which {@link OptionPlacement} passes on. */
export interface RowMaker {
  addBinding(object: object, key: PropertyKey, params?: object): PlacedRow;
  addButton(params: { title: string }): PlacedRow;
  addElement(content: HTMLElement, localize?: (language: string) => void): PlacedRow;
  addFolder(params: { title: string }): PlacedRow;
  addTab(params: { pages: readonly { title: string }[] }): PlacedRow;
}
 
/** Reports an option the code built as another kind than the layout says; the row still shows. */
export type KindMismatchReporter = (id: string, expected: OptionRowKind, actual: PlacedRow['kind']) => void;
 
/**
 * The dialog's layout once made: the code asks it where each option goes ({@link place}), and reaches the folders and
 * tabs it made by id.
 */
export class OptionLayout<C extends LayoutContainer = LayoutContainer> {
  public readonly spec: OptionsLayout;
  private readonly assembled: AssembledOptionsLayout<C>;
  private readonly claimed = new Map<string, PlacedRow>();
  private readonly resetters = new Map<string, (resolve: RuntimeDefaultResolver) => void>();
  private readonly reportKindMismatch: KindMismatchReporter;
 
  public constructor(spec: OptionsLayout, root: C, reportKindMismatch: KindMismatchReporter) {
    this.spec = spec;
    this.assembled = assembleOptionsLayout(spec, root);
    this.reportKindMismatch = reportKindMismatch;
  }
 
  /**
   * Where the option or group `id` goes: rows made through it land at its place, hidden when the layout hides it. An
   * option takes one row (a row made again after the last was disposed replaces it); a group takes any number.
   */
  public place(id: string): OptionPlacement {
    const slot = this.assembled.slots.get(id);
    if (slot === undefined) throw new Error(`Options layout has no option or group "${id}" (options-layout.json)`);
    return new OptionPlacement(slot.container as unknown as RowMaker & LayoutContainer, slot.rank, (row) =>
      this.claim(id, slot, row),
    );
  }
 
  /** Supplies the reset for a group whose controls are built from runtime data. */
  public setGroupReset(id: string, reset: () => void): void {
    this.resetters.set(id, reset);
  }
 
  /** Adds one reset to each section with settings, using the controls currently placed in it. */
  public installSectionResets(resolve: RuntimeDefaultResolver): void {
    for (const [section, ids] of this.assembled.sectionSlots) {
      Iif (ids.size === 0) continue;
      section.addSectionReset?.(() => {
        // Construction order applies mode switches and choice lists before dependent values.
        for (const [id, reset] of this.resetters) if (ids.has(id)) reset(resolve);
      });
    }
  }
 
  /** A folder the layout made. */
  public folder(id: string): ReturnType<C['addFolder']> {
    const folder = this.assembled.folders.get(id);
    Iif (folder === undefined) throw new Error(`Options layout has no folder "${id}" (options-layout.json)`);
    return folder;
  }
 
  /** A set of tabs the layout made. */
  public tabs(id: string): ReturnType<C['addTab']> {
    const tabs = this.assembled.tabs.get(id);
    Iif (tabs === undefined) throw new Error(`Options layout has no tabs "${id}" (options-layout.json)`);
    return tabs;
  }
 
  /** The pages to select, outermost first, to show the item `id`. */
  public path(id: string): readonly LayoutStep[] {
    return this.assembled.paths.get(id) ?? [];
  }
 
  /** The options of the layout no code has built: one only some browsers have, or a mistake. */
  public unclaimed(): string[] {
    return [...this.assembled.slots]
      .filter(([id, slot]) => slot.kind !== undefined && !this.claimed.has(id))
      .map(([id]) => id);
  }
 
  private claim(id: string, slot: LayoutSlot<LayoutContainer>, row: PlacedRow): void {
    row.omitted = slot.hidden;
    if (slot.kind === undefined) return;
    const previous = this.claimed.get(id);
    const container = slot.container as unknown as { readonly children?: readonly unknown[] };
    if (previous !== undefined && previous !== row && container.children?.includes(previous) === true) {
      throw new Error(`Options layout option "${id}" is built twice; give the second row an id of its own`);
    }
    this.claimed.set(id, row);
    const fallback = slot.default;
    if (fallback !== undefined) {
      this.resetters.set(id, (resolve) => {
        const value = typeof fallback === 'object' ? resolve(fallback.use) : fallback;
        Eif (value !== undefined) row.resetToDefault?.(value);
      });
    }
    if (row.kind !== slot.kind) this.reportKindMismatch(id, slot.kind, row.kind);
  }
}
 
/** Makes rows in a container at one option's or group's place (`OptionLayout.place`), as the container would. */
export class OptionPlacement implements Pick<OptionContainer, keyof RowMaker> {
  private readonly target: RowMaker & LayoutContainer;
  private readonly rank: number;
  private readonly claim: (row: PlacedRow) => void;
 
  public constructor(target: RowMaker & LayoutContainer, rank: number, claim: (row: PlacedRow) => void) {
    this.target = target;
    this.rank = rank;
    this.claim = claim;
  }
 
  public readonly addBinding = ((object: object, key: PropertyKey, params?: object) =>
    this.put(this.target.addBinding(object, key, params))) as OptionContainer['addBinding'];
  public readonly addButton = ((params: { title: string }) =>
    this.put(this.target.addButton(params))) as OptionContainer['addButton'];
  public readonly addElement = ((content: HTMLElement, localize?: (language: string) => void) =>
    this.put(this.target.addElement(content, localize))) as OptionContainer['addElement'];
  public readonly addFolder = ((params: { title: string }) =>
    this.put(this.target.addFolder(params))) as OptionContainer['addFolder'];
  public readonly addTab = ((params: { pages: readonly { title: string }[] }) =>
    this.put(this.target.addTab(params))) as OptionContainer['addTab'];
 
  private put<R extends PlacedRow>(row: R): R {
    this.target.placeAt(row, this.rank);
    this.claim(row);
    return row;
  }
}