stub-pixi.js 2.36 KB
// stub-pixi.js — headless stub Pixi 命名空间(Sprite / Container / Graphics / Application / Assets)。
//
// 让 §8 的纯映射用例(SlotTransform→Sprite 写入、镜像、纵深)在无 GPU 的 Node 下可断言,
// 不依赖真实 pixi.js / WebGL。stub 只实现本包用到的最小 API 面。

class StubPoint {
  constructor(x = 0, y = 0) {
    this.x = x
    this.y = y
  }
  set(x, y = x) {
    this.x = x
    this.y = y
  }
}

class StubContainer {
  constructor() {
    this.children = []
    this.position = new StubPoint()
    this.scale = new StubPoint(1, 1)
    this.pivot = new StubPoint()
    this.zIndex = 0
    this.sortableChildren = false
    this.alpha = 1
    this.visible = true
    this.destroyed = false
  }
  addChild(...c) {
    this.children.push(...c)
    return c[0]
  }
  addChildAt(c, i) {
    this.children.splice(i, 0, c)
    return c
  }
  destroy() {
    this.destroyed = true
  }
}

class StubSprite extends StubContainer {
  constructor(texture = null) {
    super()
    this.texture = texture
    this.anchor = new StubPoint(0.5, 0.5)
    this.width = 0
    this.height = 0
    this.mask = null
    this.rotation = 0
  }
}

class StubGraphics extends StubContainer {
  constructor() {
    super()
    this.calls = []
  }
  poly(points) {
    this.calls.push(['poly', points])
    return this
  }
  fill(color) {
    this.calls.push(['fill', color])
    return this
  }
  rect(...a) {
    this.calls.push(['rect', a])
    return this
  }
}

class StubApplication {
  constructor() {
    this.stage = new StubContainer()
    this.screen = { width: 1280, height: 720 }
    this.canvas = {}
  }
  async init() {}
  destroy() {}
}

/** 创建一个可控的 stub Assets:load 返回可预设的纹理或受控 reject。 */
function makeStubAssets(behavior = {}) {
  return {
    loaded: [],
    async load(url) {
      this.loaded.push(url)
      if (behavior.reject && behavior.reject(url)) throw new Error('load fail ' + url)
      const t = behavior.texture ? behavior.texture(url) : { __tex: url }
      return t
    },
  }
}

/** 组装一个 stub PIXI 命名空间。 */
export function makeStubPixi(behavior = {}) {
  return {
    Container: StubContainer,
    Sprite: StubSprite,
    Graphics: StubGraphics,
    Application: StubApplication,
    Assets: makeStubAssets(behavior),
  }
}

export { StubContainer, StubSprite, StubGraphics, StubApplication }