DEV Community

Murahashi [Matt] Kenichi
Murahashi [Matt] Kenichi

Posted on

Let's build browser engine! in typescript vol12 Prepare for calculate block width - getStyleNode, toPx, and lookup

test("getStyleNode anonymous block", () => {
  expect(() => {
    LayoutBox.Create(new BoxType.AnonymousBlock()).getStyleNode();
  }).toThrow();
});

test("getStyleNode block node", () => {
  expect(LayoutBox.Create(new BoxType.BlockNode(oneStyledNode)).getStyleNode()).toEqual(
    oneStyledNode
  );
});

test("getStyleNode inline node", () => {
  expect(LayoutBox.Create(new BoxType.InlineNode(oneStyledNode)).getStyleNode()).toEqual(
    oneStyledNode
  );
});
Enter fullscreen mode Exit fullscreen mode
export class LayoutBox {
  (snip)

  getStyleNode(): StyledNode {
    switch (this.boxType.format) {
      case BoxType.Format.AnonymousBlock:
        throw Error("Anonymous block box has no style node");
      case BoxType.Format.BlockNode:
      case BoxType.Format.InlineNode:
        return this.boxType.styledNode;
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

toPx()

test("value to px color", () => {
  expect(new CssValue.ColorValue(new Color(0, 0, 0, 0)).toPx()).toEqual(0.0);
});

test("value to px keyword", () => {
  expect(new CssValue.Keyword("example").toPx()).toEqual(0.0);
});

test("value to px length em", () => {
  expect(new CssValue.Length(1.0, Unit.Em).toPx()).toEqual(0.0);
});

test("value to px length px", () => {
  expect(new CssValue.Length(1.0, Unit.Px).toPx()).toEqual(1.0);
});
Enter fullscreen mode Exit fullscreen mode
export namespace CssValue {
  export class Length {
    (snip)

    toPx(): number {
      switch (this.unit) {
        case Unit.Em:
          return 0.0;
        case Unit.Px:
          return this.length;
      }
    }
  }
Enter fullscreen mode Exit fullscreen mode

lookup

test("lookup target", () => {
  const expected = new CssValue.Keyword("example");
  expect(
    new StyledNode(text("no mean"), new Map([["target", expected]]), []).lookup(
      "target",
      "fallback",
      new CssValue.Keyword("no mean")
    )
  ).toBe(expected);
});

test("lookup fallback", () => {
  const expected = new CssValue.Keyword("example");
  expect(
    new StyledNode(text("no mean"), new Map([["fallback", expected]]), []).lookup(
      "no mean",
      "fallback",
      new CssValue.Keyword("no mean")
    )
  ).toBe(expected);
});

test("lookup none", () => {
  const expected = new CssValue.Keyword("example");
  expect(
    new StyledNode(text("no mean"), new Map([]), []).lookup("no mean", "no mean2", expected)
  ).toBe(expected);
});
Enter fullscreen mode Exit fullscreen mode
export class StyledNode {
  (snip)

  lookup(name: string, fallbackName: string, defaultValue: CssValue): CssValue {
    return this.value(name) || this.value(fallbackName) || defaultValue;
  }
Enter fullscreen mode Exit fullscreen mode

references

series

Top comments (0)