All files / src/packlets/editor-core/slices render-slice.ts

97.22% Statements 105/108
82.53% Branches 52/63
100% Functions 11/11
100% Lines 97/97

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 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314                                1x   51x     51x 51x 72x   51x 96x   51x 71x         443x       443x 443x 443x 443x 443x 443x 443x 443x 443x   443x 443x 443x 443x 443x 443x 443x 443x 443x 443x 443x   443x     443x 2508x 2508x                         443x 2508x                           443x                       443x 107x 107x 107x 107x   107x 107x   49x 282x   49x   46x 46x                                       1329x 886x 443x 443x   443x 443x 191x 191x 191x 191x 191x   72x                                       443x 443x 41x 41x 41x 41x 41x   12x                                         443x 443x 443x                       443x     188x 188x       188x   188x         188x 431x 431x                               188x   1307x 188x   188x 876x                         188x 188x   4736x   188x 3429x                         188x 188x 9x           9x 9x 9x                         188x      
import { atom } from "nanostores";
import { Slice } from "../slice";
import type { EditorContext } from "../editor-context";
import { ProjectSlice } from "./project-slice";
import { ChartSlice } from "./chart-slice";
import { ViewportSlice } from "./viewport-slice";
import { ColumnsSlice } from "./columns-slice";
import { SelectionSlice } from "./selection-slice";
import { BoxSelectionSlice } from "./box-selection-slice";
import { CursorSlice } from "./cursor-slice";
import { SnapSlice } from "./snap-slice";
import { TimingSlice } from "./timing-slice";
import { EVENT, NOTE, LEVEL_REF, BPM_CHANGE, TIME_SIGNATURE } from "../components";
import type { TimelineRenderSpec } from "../types";
 
export class RenderSlice extends Slice {
  static readonly sliceKey = "render";
 
  $visibleRenderObjects = atom<TimelineRenderSpec[]>([]);
 
  constructor(ctx: EditorContext) {
    super(ctx);
    ctx.get(ProjectSlice).entityManager.$mutationVersion.subscribe(() => {
      this.refresh();
    });
    ctx.get(SelectionSlice).$selection.subscribe(() => {
      this.refresh();
    });
    ctx.get(CursorSlice).$cursorPulse.subscribe(() => {
      this.refresh();
    });
  }
 
  refresh(): void {
    this.$visibleRenderObjects.set(this.computeSpecs());
  }
 
  private computeSpecs(): TimelineRenderSpec[] {
    const chartSlice = this.ctx.get(ChartSlice);
    const viewport = this.ctx.get(ViewportSlice);
    const columnsSlice = this.ctx.get(ColumnsSlice);
    const selection = this.ctx.get(SelectionSlice);
    const boxSelection = this.ctx.get(BoxSelectionSlice);
    const cursor = this.ctx.get(CursorSlice);
    const snapSlice = this.ctx.get(SnapSlice);
    const timing = this.ctx.get(TimingSlice);
    const entityManager = this.ctx.get(ProjectSlice).entityManager;
 
    const size = chartSlice.getChartSize();
    const scaleY = viewport.getScaleY();
    const trackHeight = viewport.getTrackHeight();
    const contentHeight = viewport.getContentHeight();
    const pulseRange = viewport.getVisiblePulseRange();
    const pulseStart = pulseRange.start;
    const pulseEnd = pulseRange.end;
    const rawPulseStart = pulseRange.rawStart;
    const rawPulseEnd = pulseRange.rawEnd;
    const timelineWidth = columnsSlice.$timelineWidth.get();
    const columns = columnsSlice.$columns.get();
 
    const specs: TimelineRenderSpec[] = [];
 
    // --- Column backgrounds (scroll layer) ---
    for (let i = 0; i < columns.length; i++) {
      const col = columns[i]!;
      specs.push({
        key: `column-bg-${col.id}`,
        type: "column-bg",
        x: col.x,
        y: 0,
        width: col.width,
        height: contentHeight,
        data: { backgroundColor: col.backgroundColor, showBorder: i > 0 },
        testId: "timeline-column-bg",
      });
    }
 
    // --- Column titles (sticky layer) ---
    for (const col of columns) {
      specs.push({
        key: `column-title-${col.id}`,
        type: "column-title",
        x: col.x,
        y: 4,
        width: col.width,
        height: 16,
        layer: "sticky",
        data: { title: col.title },
        testId: "timeline-column-title",
      });
    }
 
    // --- Trailing border after last column ---
    specs.push({
      key: "trailing-border",
      type: "trailing-border",
      x: timelineWidth - 1,
      y: 0,
      width: 1,
      height: contentHeight,
      data: {},
      testId: "trailing-border",
    });
 
    // --- Gameplay notes ---
    for (const entity of entityManager.entitiesWithComponent(NOTE)) {
      const event = entityManager.getComponent(entity, EVENT);
      const note = entityManager.getComponent(entity, NOTE);
      const levelRef = entityManager.getComponent(entity, LEVEL_REF);
      Iif (!event || !note || !levelRef) continue;
 
      const pulse = event.y;
      if (pulse < pulseStart || pulse >= pulseEnd) continue;
 
      const laneCol = columns.find(
        (c) => c.levelId === levelRef.levelId && c.laneIndex === note.lane,
      );
      if (!laneCol) continue;
 
      const colIndex = columns.indexOf(laneCol);
      specs.push({
        key: `note-${entity.id}`,
        type: "event-marker",
        x: laneCol.x,
        y: trackHeight - pulse * scaleY - 14,
        width: laneCol.width,
        height: 14,
        data: {
          text: "",
          backgroundColor: laneCol.noteColor ?? "var(--accent-9)",
          textColor: "#fff",
          selected:
            selection.$selection.get().has(entity.id) || boxSelection.isInBox(pulse, colIndex),
        },
        testId: "note",
        entityId: entity.id,
      });
    }
 
    // --- Timing event markers ---
    const bpmColumn = columns.find((c) => c.id === "bpm");
    const tsColumn = columns.find((c) => c.id === "time-sig");
    const bpmColIndex = bpmColumn ? columns.indexOf(bpmColumn) : -1;
    const tsColIndex = tsColumn ? columns.indexOf(tsColumn) : -1;
 
    Eif (bpmColumn) {
      for (const entity of entityManager.entitiesWithComponent(BPM_CHANGE)) {
        const event = entityManager.getComponent(entity, EVENT);
        const bpm = entityManager.getComponent(entity, BPM_CHANGE);
        Iif (!event || !bpm) continue;
        const pulse = event.y;
        if (pulse < pulseStart || pulse >= pulseEnd) continue;
 
        specs.push({
          key: `bpm-${entity.id}`,
          type: "event-marker",
          x: bpmColumn.x,
          y: trackHeight - pulse * scaleY - 14,
          width: bpmColumn.width,
          height: 14,
          data: {
            text: String(bpm.bpm),
            backgroundColor: "var(--yellow-6)",
            textColor: "#fff",
            selected:
              selection.$selection.get().has(entity.id) || boxSelection.isInBox(pulse, bpmColIndex),
          },
          testId: "bpm-change-marker",
          entityId: entity.id,
        });
      }
    }
 
    Eif (tsColumn) {
      for (const entity of entityManager.entitiesWithComponent(TIME_SIGNATURE)) {
        const event = entityManager.getComponent(entity, EVENT);
        const ts = entityManager.getComponent(entity, TIME_SIGNATURE);
        Iif (!event || !ts) continue;
        const pulse = event.y;
        if (pulse < pulseStart || pulse >= pulseEnd) continue;
 
        specs.push({
          key: `ts-${entity.id}`,
          type: "event-marker",
          x: tsColumn.x,
          y: trackHeight - pulse * scaleY - 14,
          width: tsColumn.width,
          height: 14,
          data: {
            text: `${ts.numerator}/${ts.denominator}`,
            backgroundColor: "var(--tomato-6)",
            textColor: "#fff",
            selected:
              selection.$selection.get().has(entity.id) || boxSelection.isInBox(pulse, tsColIndex),
          },
          testId: "time-sig-marker",
          entityId: entity.id,
        });
      }
    }
 
    // --- Playhead ---
    const cursorPulse = cursor.$cursorPulse.get();
    Eif (cursorPulse >= 0 && cursorPulse <= size) {
      specs.push({
        key: "playhead",
        type: "playhead",
        x: 0,
        y: trackHeight - cursorPulse * scaleY - 1,
        width: timelineWidth,
        height: 1,
        data: {},
        testId: "playhead",
      });
    }
 
    if (rawPulseStart >= rawPulseEnd) return specs;
 
    // --- Measure lines ---
    const engine = timing.getTimingEngine();
    const measureBoundaries = engine.getMeasureBoundaries({
      start: rawPulseStart,
      end: rawPulseEnd,
    });
    const measureSet = new Set(measureBoundaries);
 
    const allBoundaries = engine.getMeasureBoundaries({
      start: 0,
      end: rawPulseEnd,
    });
 
    for (const pulse of measureBoundaries) {
      const measureIndex = allBoundaries.indexOf(pulse);
      specs.push({
        key: `measure-${pulse}`,
        type: "grid-line",
        x: 0,
        y: trackHeight - pulse * scaleY - 1,
        width: timelineWidth,
        height: 1,
        data: {
          color: "var(--gray-8)",
          label: measureIndex >= 0 ? String(measureIndex + 1) : undefined,
        },
        testId: "measure-line",
      });
    }
 
    // --- Beat lines (1/4, exclude measure boundaries) ---
    const beatPoints = engine
      .getSnapPoints("1/4", { start: rawPulseStart, end: rawPulseEnd })
      .filter((p) => !measureSet.has(p));
    const beatSet = new Set(beatPoints);
 
    for (const pulse of beatPoints) {
      specs.push({
        key: `beat-${pulse}`,
        type: "grid-line",
        x: 0,
        y: trackHeight - pulse * scaleY - 1,
        width: timelineWidth,
        height: 1,
        data: { color: "var(--gray-7)" },
        testId: "beat-line",
      });
    }
 
    // --- Snap lines at current snap resolution (exclude measures and beats) ---
    const snap = snapSlice.$snap.get();
    const gridPoints = engine
      .getSnapPoints(snap, { start: rawPulseStart, end: rawPulseEnd })
      .filter((p) => !measureSet.has(p) && !beatSet.has(p));
 
    for (const pulse of gridPoints) {
      specs.push({
        key: `grid-${pulse}`,
        type: "grid-line",
        x: 0,
        y: trackHeight - pulse * scaleY - 1,
        width: timelineWidth,
        height: 1,
        data: { color: "var(--gray-6)" },
        testId: "snap-line",
      });
    }
 
    // --- Selection box (during drag) ---
    const boxRect = boxSelection.getBoxRect();
    if (boxRect) {
      Eif (
        boxRect.minCol >= 0 &&
        boxRect.maxCol >= 0 &&
        boxRect.minCol < columns.length &&
        boxRect.maxCol < columns.length
      ) {
        const startCol = columns[boxRect.minCol]!;
        const endCol = columns[boxRect.maxCol]!;
        specs.push({
          key: "selection-box",
          type: "selection-box",
          x: startCol.x,
          y: trackHeight - boxRect.maxPulse * scaleY,
          width: endCol.x + endCol.width - startCol.x,
          height: (boxRect.maxPulse - boxRect.minPulse) * scaleY,
          data: {},
          testId: "selection-box",
        });
      }
    }
 
    return specs;
  }
}