# Kobweb

A [Kobweb](https://github.com/varabyte/kobweb) site is a Gradle project on Compose HTML, and its `.lithe` files can be pages. This documentation site is one,
on Kobweb 0.25.1, with a server for its API routes: every page you're reading is a `.lithe` file or a Markdown file.

Since the project is on Compose HTML, `Lithe { }`, `composeInto` and composable tags work in its pages. `examples/kobweb` is a smaller site with the
complete build files, a good starting point to copy.

## Setup

The Gradle plugin `io.github.ayfri.lithe` adds the task `compileLithe`. It compiles the `.lithe` files of `src/jsMain/kotlin` to the Kotlin of the browser,
which `jsMain` compiles with the rest, and their styles to `public/lithe.css`, which the pages link. The plugin and the libraries come from **Maven Central**,
from version **0.1.0**.

### Settings

The plugin has no marker artifact, so `settings.gradle.kts` maps its id to its module, `io.github.ayfri.lithe:gradle-plugin`, and takes it from Maven Central:

```kotlin
// settings.gradle.kts
pluginManagement {
	repositories {
		mavenCentral()
		gradlePluginPortal()
	}
	resolutionStrategy {
		eachPlugin {
			if (requested.id.id == "io.github.ayfri.lithe") useModule("io.github.ayfri.lithe:gradle-plugin:${requested.version}")
		}
	}
}

dependencyResolutionManagement {
	repositories {
		mavenCentral()
		google()
	}
}
```

To try the code of the repository instead of a release, `./kotlin publish mavenLocal` puts it in the local Maven repository, and a `mavenLocal { content {
includeGroup("io.github.ayfri.lithe") } }` before `mavenCentral()` in both blocks reads it first. The two examples of the repository do that.

### The site module

The module applies the plugin, links the stylesheet that the task writes, and depends on the Lithe libraries:

```kotlin
// site/build.gradle.kts
plugins {
	alias(libs.plugins.kotlin.multiplatform)
	alias(libs.plugins.compose.compiler)
	alias(libs.plugins.kobweb.application)
	alias(libs.plugins.lithe)
}

group = "demo"

kobweb {
	app {
		index {
			head.add { link(rel = "stylesheet", href = "/lithe.css") }
		}
	}
}

kotlin {
	configAsKobwebApplication("kobweb", includeServer = true)

	sourceSets {
		jsMain.dependencies {
			implementation(libs.compose.runtime)
			implementation(libs.compose.html.core)
			implementation(libs.kobweb.core)
			implementation("io.github.ayfri.lithe:kobweb:0.1.0")
			implementation("io.github.ayfri.lithe:runtime-compose:0.1.0")
		}
		jvmMain.dependencies {
			implementation(libs.kobweb.api)
		}
	}
}
```

The site compiles with the Kotlin version of Lithe, 2.4.21, because an older compiler isn't guaranteed to read its libraries. The Kotlin of a `.kt` file
calls a component like any function: `Lithe { Counter(start = { 3 }) }`.

## Pages

A `.lithe` file in the package `<group>.pages`, or under it, is a page: the task writes the `@Page` function that Kobweb looks for, which mounts the
component with `LithePage { }`. Kobweb owns the routes, so the route is the one of the file name and its folders, like a Kotlin file with a `@Page` function:

| File | Route |
|------|-------|
| `pages/Index.lithe` | `/` |
| `pages/Docs.lithe` | `/docs` |
| `pages/blog/Index.lithe` | `/blog/` |
| `pages/GettingStarted.lithe` | `/getting-started` |

A camelCase name becomes a kebab-case route, as Kobweb does for its own pages and Markdown files. A hyphen in a file name isn't possible, because Kobweb
reads the name as a Kotlin identifier.

Leaving a page disposes its components, and coming back mounts new ones.

### Page options

`<page />` gives the options of a page. It goes at the top level of the file, once, and holds no content. Kobweb reads the options while it builds, so they
are written values.

```html
<page prerender={false} route="/me" layout=".components.layouts.PageLayout" />

<h1>Your account, just for you</h1>
```

| Option              | Effect                                                                                                   |
|---------------------|----------------------------------------------------------------------------------------------------------|
| `prerender={false}` | `kobweb export` writes the page without its content, which the browser builds, for content that differs per visitor. `prerender` alone is true. |
| `route="..."`       | The route of the page instead of the one of its file, as `@Page("...")` spells it.                       |
| `layout="..."`      | The layout of the page, as `@Layout("...")` spells it.                                                   |

`ctx.lithe { prerender = false }` in an `@InitKobweb` function changes the default of every page, and `json` the `Json` that `apiData` decodes with.
`<page />` anywhere else is an error, a Lithe site included, whose single page has no route.

## Components in Markdown

A component without required props, outside `pages`, also gets a composable of the same name, which takes the attributes of the `div` that holds it. A
Markdown page of Kobweb renders it like any composable, and so does Compose code, `Clicker()`:

```markdown
{{{ .components.Clicker }}}
```

The live demos of this documentation are written this way: the Markdown of [Bindings](/docs/components/bindings) holds `{{{ .demos.Temperature }}}`.

## Data of API routes

`apiData<T>("quote")` is the value an `@Api` route of the site gives, decoded from JSON, for an `@await`. The routes are functions of `jvmMain` that the site
writes like any Kobweb one, named after their function:

```kotlin
// jvmMain: the route /api/quote
@Api
fun quote(ctx: ApiContext) {
	ctx.res.body = bodyOf("""{"text":"Simplicity is prerequisite for reliability.","author":"Edsger W. Dijkstra"}""")
}
```

```html
<script kotlin>
	import io.github.ayfri.lithe.kobweb.apiData
</script>

@await (val quote = apiData<Map<String, String>>("quote")) {
	<blockquote>{quote.getValue("text")}</blockquote>
} @pending {
	<p>Loading</p>
}
```

While `kobweb export` writes a page, the JSON goes into the head of the page too, and the first load of that HTML reads it from there, so a static site
without a server shows it. A later call asks the server again, which a static site has no more: a route whose answer doesn't depend on the request is
also written as a file of `public/api`, and the static site serves it under the same address. The [performance page](/performance) of this site reads its
figures this way. Its search runs in the browser on a `docs.json` written at build time, and the generated code of the examples of its playground is a
`generated/<name>.json` file the build writes with the compiler. Only the compile of an edited file calls a route that needs a server, the one of the global
`playgroundApiUrl` when it has one.

## How Kobweb renders

A Kobweb export renders each page in a headless browser, so the static rendering of Lithe on the JVM has no part in it: the exported HTML holds what the
components rendered there, and the client builds the page again instead of hydrating it. An `@await` of anything else than `apiData` is in the export only
when its value comes before the `load` event of the page.

## Limits

- A page written in Lithe can't take a route parameter or the page context of Kobweb: the generated function passes neither to the component. A
  `route="{id}"` gives the route, but the component can't read the parameter. A page of that kind is a Kotlin file that mounts a component.
- Calling a component from a `.kt` file of a module that the toolchain also builds isn't possible, because only Lithe builds generate the Kotlin of a
  component.
- A `const val` of a `.kt` file is a value like any other in a style block, a CSS custom property, so it isn't possible where custom properties don't work:
  the task writes the stylesheet as the compiler gives it, and only a site build has the values the Kotlin compiler inlines.
- Applying the plugin by its id alone isn't possible, because it has no marker artifact and isn't on the Gradle Plugin Portal: `settings.gradle.kts` maps its id to
  its module, as shown in [Settings](#settings).
