DEV Community

Cover image for Component In HappyX
Ethosa
Ethosa

Posted on

Component In HappyX

With HappyX you can create single-page applications. Most often components are used for this purpose.

And HappyX components is really powerful.

Declaration 🍍

Components declaration is very easy, ex:

component MyComponent:
  `template`:
    "Hello, world!"
Enter fullscreen mode Exit fullscreen mode

In this example we declare component named MyComponent.

Body 👨‍🔬

Component body consists of:

  • `template` - HTML
  • `script` - code that calls every rerender
  • `style` - isolated CSS (works with current component)
  • [methods] - methods that can be called.
  • fields - private/public fields
  • constructors - component constructors

Any part of the component is optional.

As JS/CSS:

HappyX provides DSL (Domain-specific language) for HTML, CSS and JS.

Components can use all of these DSLs.

  • `template` uses HTML DSL;
  • `script` as js uses JS DSL;
  • `style` as css uses CSS DSL.

`template`, `script`, `style`

These statements is main in component body.

component A:
  `template`:
    # Here is HTML
    tDiv(id = "..", class = "....", style = "....."):
      "Hello, world!"
  `script`:
    echo "Hello from A"
  # To enable syntax highlight
  # use official HappyX extension
  # for visual studio code
  `style`: """
  div {
    ...
  }
  """
Enter fullscreen mode Exit fullscreen mode

Fields

Component fields may be private or public.

component MyComponent:
  privateField: int
  privateFieldWithDefaultValue: string = ""
  *publicField: float
  *publicFieldWithDefaultValue: seq[int] = @[1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

Methods

Component methods is automatically got self param

component MyComponent:
  left: int = 0
  right: int = 0

  [methods]:
    proc sum(): int =
      self.left + self.right
Enter fullscreen mode Exit fullscreen mode

Constructors

By default you can use component and send some params to it.

component A:
  a: int = 0
  b: string = "asd"
...

appRoutes "app":
  "/":
    # Default constructor usage
    component A()
    component A(a = 100)
    component A(b = "hello")
    component A(a = 1, b = "sss")
Enter fullscreen mode Exit fullscreen mode

Constructors expand component usage:

component A:
  a: int = 0
  b: string = "asd"

  # Constructor
  constructor(a: int):
    self.a = a*a*a
...

appRoutes "app":
  "/":
    # Constructor usage
    component A->constructor(10)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)