All files / src/packlets/editor-core tester.ts

94.94% Statements 94/99
94.11% Branches 16/17
94.23% Functions 49/52
94.73% Lines 90/95

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                                                            26x 26x       37x 37x 37x   37x 37x               23x       5x 5x         9x 9x           47x     101x 101x       1x 1x 1x       53x 53x 53x 26x   53x       8x 8x   8x 8x       47x                       51x 4x             47x 47x 47x                   51x 51x   51x 51x 51x       51x 31x   51x       12x       10x       37x       3x       31x 446x 31x 31x       4x       5x       3x       4x       1x       3x       1x               8x     51x   23x     7x       51x   4x               2x 20x 2x 2x 2x       51x   2x 2x 2x 2x     4x       51x   3x 3x 3x   2x   2x 2x 2x           12x 12x   6x     1x     1x   4x   4x 4x 4x            
/**
 * @packageDocumentation
 *
 * Acceptance-test helper for the editor core. Simulates user-level
 * interactions (hover, zoom, scroll) and provides readable assertions
 * against the EditorController state.
 */
 
import { expect } from "vite-plus/test";
import {
  EditorController,
  CHART,
  ViewportSlice,
  SelectionSlice,
  ChartSlice,
  ColumnsSlice,
} from "./index";
import type { ProjectFile } from "../project-format";
import { type Entity, EntityBuilder, entity } from "../entity-manager";
import { createDemoProjectFile } from "../project-store";
 
export { entity };
import { EVENT, BPM_CHANGE, TIME_SIGNATURE, CHART_REF, NOTE, LEVEL_REF, LEVEL } from "./components";
import { Rect, type Point as PointType } from "../geometry";
 
export class ChartBuilder {
  private chartId: string;
  private projectBuilder: ProjectBuilder;
 
  constructor(chartId: string, projectBuilder: ProjectBuilder) {
    this.chartId = chartId;
    this.projectBuilder = projectBuilder;
  }
 
  private addWithChartRef(build: (e: EntityBuilder) => void): Entity {
    const ent = entity((e) => {
      build(e);
      e.with(CHART_REF, { chartId: this.chartId });
    });
    this.projectBuilder.add(ent);
    return ent;
  }
 
  addEntity(callback: (e: EntityBuilder) => void): Entity {
    return this.addWithChartRef(callback);
  }
 
  bpmChange(y: number, bpm: number): Entity {
    return this.addWithChartRef((e) => e.with(EVENT, { y }).with(BPM_CHANGE, { bpm }));
  }
 
  timeSignature(y: number, numerator: number, denominator: number): Entity {
    return this.addWithChartRef((e) =>
      e.with(EVENT, { y }).with(TIME_SIGNATURE, { numerator, denominator }),
    );
  }
 
  note(y: number, lane: number, levelId: string): Entity {
    return this.addWithChartRef((e) =>
      e.with(EVENT, { y }).with(NOTE, { lane }).with(LEVEL_REF, { levelId }),
    );
  }
}
 
export class ProjectBuilder {
  private entities: Entity[] = [];
 
  add(entity: Entity): Entity {
    this.entities.push(entity);
    return entity;
  }
 
  addEntity(callback: (e: EntityBuilder) => void): Entity {
    const ent = entity(callback);
    this.add(ent);
    return ent;
  }
 
  addChart(name: string, callback?: (c: ChartBuilder) => void, size?: number): Entity {
    const chart = entity((e) => e.with(CHART, { name, size }));
    this.add(chart);
    if (callback) {
      callback(new ChartBuilder(chart.id, this));
    }
    return chart;
  }
 
  addLevel(chartId: string, name: string, mode: string, sortOrder?: number): Entity {
    const level = entity((e) =>
      e.with(LEVEL, { name, mode, sortOrder: sortOrder ?? 0 }).with(CHART_REF, { chartId }),
    );
    this.add(level);
    return level;
  }
 
  build(): ProjectFile {
    return {
      schemaVersion: 2,
      version: "test-version",
      metadata: { title: "Test", artist: "Test", genre: "Test" },
      entities: this.entities,
    };
  }
}
 
export function makeProject(
  entitiesOrCallback: Entity[] | ((p: ProjectBuilder) => void) = [],
): ProjectFile {
  if (Array.isArray(entitiesOrCallback)) {
    return {
      schemaVersion: 2,
      version: "test-version",
      metadata: { title: "Test", artist: "Test", genre: "Test" },
      entities: entitiesOrCallback,
    };
  }
  const builder = new ProjectBuilder();
  entitiesOrCallback(builder);
  return builder.build();
}
 
export class EditorTester {
  readonly instance: EditorController;
 
  constructor(options?: {
    getProjectToLoad?: () => ProjectFile;
    viewport?: { width: number; height: number };
  }) {
    const project = options?.getProjectToLoad?.() ?? createDemoProjectFile();
    this.instance = new EditorController({ project });
 
    const viewportWidth = options?.viewport?.width ?? 640;
    const viewportHeight = options?.viewport?.height ?? 480;
    this.instance.setViewportSize(viewportWidth, viewportHeight);
 
    // Subscribe to outbox so scroll notifications (e.g. from onConnected or
    // setZoom) are applied, closing the loop just like the real DOM does.
    this.instance.outbox.on("setScroll", (point) => {
      this.instance.setScroll(point);
    });
    this.instance.onConnected();
  }
 
  pointerMove({ x, y }: { x?: number; y: number }) {
    this.instance.handlePointerMove(x ?? 0, y);
  }
 
  setTool(tool: "select" | "pencil" | "erase" | "pan") {
    this.instance.setTool(tool);
  }
 
  pointerDown(point: PointType, options?: { shiftKey?: boolean }) {
    this.instance.handlePointerDown(point, options?.shiftKey ?? false);
  }
 
  pointerUp() {
    this.instance.handlePointerUp();
  }
 
  eventRect(entityId: string): Rect {
    const specs = this.instance.$visibleRenderObjects.get();
    const spec = specs.find((s) => s.key.endsWith(`-${entityId}`));
    expect(spec).toBeDefined();
    return { x: spec!.x, y: spec!.y, width: spec!.width, height: spec!.height };
  }
 
  zoom(value: number) {
    this.instance.setZoom(value);
  }
 
  scrollTo(point: PointType) {
    this.instance.setScroll(point);
  }
 
  deleteSelection() {
    this.instance.deleteSelection();
  }
 
  undo() {
    this.instance.undo();
  }
 
  redo() {
    this.instance.redo();
  }
 
  navigateUp() {
    this.instance.navigateSnap("up");
  }
 
  navigateDown() {
    this.instance.navigateSnap("down");
  }
 
  get scrollHeight() {
    return this.instance.getContentHeight();
  }
 
  get scrollTop() {
    return this.instance.ctx.get(ViewportSlice).$scroll.get().y;
  }
 
  selection = {
    shouldContain: (id: string) => {
      expect(this.instance.ctx.get(SelectionSlice).$selection.get().has(id)).toBe(true);
    },
    shouldBeEmpty: () => {
      expect(this.instance.ctx.get(SelectionSlice).$selection.get().size).toBe(0);
    },
  };
 
  playhead = {
    shouldBeAtPulse: (expected: number) => {
      expect(this.instance.$cursorPulse.get()).toBe(expected);
    },
    shouldBeAtTime: (expected: string) => {
      const engine = this.instance.getTimingEngine();
      const seconds = engine.pulseToSeconds(this.instance.$cursorPulse.get());
      expect(engine.formatTime(seconds)).toBe(expected);
    },
    shouldHavePositionRelativeToViewport: (expectedY: number) => {
      const specs = this.instance.$visibleRenderObjects.get();
      const playhead = specs.find((s) => s.type === "playhead");
      expect(playhead).toBeDefined();
      const playheadViewportY = playhead!.y - this.instance.ctx.get(ViewportSlice).$scroll.get().y;
      expect(playheadViewportY).toBe(expectedY);
    },
  };
 
  chart = {
    shouldHaveName: (expected: string) => {
      const chart = this.instance.ctx.get(ChartSlice).getSelectedChart();
      expect(chart).toBeDefined();
      const component = this.instance.getEntityManager().getComponent(chart!, CHART);
      expect(component?.name).toBe(expected);
    },
    shouldHaveSize: (expected: number) => {
      expect(this.instance.ctx.get(ChartSlice).getChartSize()).toBe(expected);
    },
  };
 
  timing = {
    shouldHaveMeasureBoundaries: (range: { start: number; end: number }, expected: number[]) => {
      const engine = this.instance.getTimingEngine();
      const boundaries = engine.getMeasureBoundaries(range);
      expect(boundaries).toEqual(expected);
    },
    atPulse: (pulse: number) => ({
      shouldBeAtTime: (expected: string) => {
        const engine = this.instance.getTimingEngine();
        const seconds = engine.pulseToSeconds(pulse);
        expect(engine.formatTime(seconds)).toBe(expected);
      },
    }),
  };
 
  get columns() {
    const instance = this.instance;
    return {
      get count() {
        return instance.ctx.get(ColumnsSlice).$columns.get().length;
      },
      shouldHaveCount: (expected: number) => {
        expect(instance.ctx.get(ColumnsSlice).$columns.get().length).toBe(expected);
      },
      shouldHaveTotalWidth: (expected: number) => {
        expect(instance.getTimelineWidth()).toBe(expected);
      },
      at: (index: number) => ({
        shouldMatch: (expected: Partial<{ id: string; x: number; width: number }>) => {
          const col = instance.ctx.get(ColumnsSlice).$columns.get()[index];
          expect(col).toBeDefined();
          expect(col).toMatchObject(expected);
        },
      }),
    };
  }
}