Lit + File Based Routing + Nested Layouts

Overview

Demo

Lit File Based Routing

Lit router for nested layouts and file based routing. Similar to https://remix.run/ but at client side.

Demo

Package

Archived in favor of: https://github.com/rodydavis/vscode-router-generator

Features

  • File based routing
  • Nested layout

Defining a root layout

To layout navigation once you will want to define a root layout that all pages can inherit from.

import { html, css, LitElement } from "lit";
import { customElement } from "lit/decorators.js";

@customElement("root-module")
export class RootModule extends LitElement {
  static styles = css`
    main {
      display: flex;
      flex-direction: row;
      height: 100vh;
      width: 100%;
    }
    aside {
      display: flex;
      flex-direction: column;
      background-color: whitesmoke;
      padding: 8px;
    }
    section {
      flex: 1;
    }
  `;

  render() {
    return html`
      <main>
        <aside>
          <a href="#/">Home</a>
          <a href="#/dashboard/">Dashboard</a>
          <a href="#/settings/">Settings</a>
        </aside>
        <section><slot></slot></section>
      </main>
    `;
  }
}

Defining a base layout

You can define a base layout with the root name. For example: dashboard.ts

import { html, css, LitElement } from "lit";
import { customElement } from "lit/decorators.js";

@customElement("dashboard-module")
export class DashboardModule extends LitElement {
  static styles = css`
    header {
      height: 40px;
      background-color: orange;
      color: white;
      display: flex;
      flex-direction: row;
      align-items: center;
      padding-left: 10px;
      padding-right: 10px;
      justify-content: space-between;
    }
  `;

  render() {
    return html`<main>
      <header>
        <span class="title">Dashboard</span>
        <nav>
          <a href="#/dashboard/overview">Overview</a>
          <a href="#/dashboard/account/">Account</a>
        </nav>
      </header>
      <section><slot></slot></section>
    </main> `;
  }
}

If you notice the <slot> is used for the nested layout.

Defining the index route

You can define the index route for when there are no args needed. For example: dashboard/index.ts

import { html, css, LitElement } from "lit";
import { customElement } from "lit/decorators.js";

@customElement("dashboard-default")
export class DashboardDefault extends LitElement {
  static styles = css``;

  render() {
    return html`<section>Default Dashboard</section>`;
  }
}

Since this is a nested layout all you need to do is provide the component and it will inherit from the parent layout (dashboard.ts).

Defining a named arg

You can define a named arg for a route if there is something that does not need data fetched for. For example: /dashboard/overview.ts

import { html, css, LitElement } from "lit";
import { customElement } from "lit/decorators.js";

@customElement("overview-module")
export class OverviewModule extends LitElement {
  static styles = css``;

  render() {
    return html`<section>Overview</section>`;
  }
}

This is also just a component.

Defining a dynamic arg

Sometimes the arg is generated at runtime or needs to be pulled from a database. For example: dashboard/account/:id.ts

import { html, css, LitElement } from "lit";
import { customElement, property } from "lit/decorators.js";

@customElement("account-details")
export class AccountDetails extends LitElement {
  static styles = css``;

  @property({ type: String }) id = "";

  render() {
    return html`<section>User ID: ${this.id}</section>`;
  }
}

You can see we set the file name with a prefix of : to define an arg to look for and match against. This will be provided in a map.

Usage

If you install the package locally you can run node lit-file-router to have src/generated-app.ts added as a file when it analyzes the src/pages/ directory.

<body>
    <generated-app> </generated-app>
    <script type="module" src="/src/generated-app.ts"></script>
</body>

Dynamic Imports

You can have the components load async with dynamic imports using the following command:

node lit-file-router --dynamic-imports=true

By default it will use static imports and have everything loaded at runtime.

Data caching and loader function

You can export a loader function that will be used to set data on the component:

import { html, css, LitElement } from "lit";
import { customElement, property } from "lit/decorators.js";

export async function loader(
  route: string,
  args: { [key: string]: any }
): Promise<AccountData> {
  await new Promise((resolve) => setTimeout(resolve, 1000));
  const id = args["id"]!;
  return {
    id,
    name: "Name: " + id,
    email: route,
  };
}

@customElement("account-details")
export class AccountDetails extends LitElement {
  static styles = css``;

  @property({ type: String }) id = "";
  @property({ type: Object }) data!: AccountData;

  render() {
    return html`<section>User ID: ${this.data.id}</section>`;
  }
}

interface AccountData {
  id: string;
  name: string;
  email: string;
}

This will call the function to load the data before rendering starts.

If you want to enable caching you can add the following command:

node lit-file-router --cache-all

It is off by default but it will cache the data from the loader function for the component and route and will pass the cached data from memory to the component.

Loading state

You can pass show a progress indicator at the bottom by passing a loading arg:

node lit-file-router --show-loading=true

It is off by default, but this is useful for heavy requests that would hang the UI.

You might also like...

mono-repo for lit-app and dependencies

Lit-Apps CAUTION: THIS IS VERY EARLY SOFTWARE - DO NOT USE IN PRODUCTION - VERY LIKELY TO CHANGE Lit-apps an ecosystem of lit-based applications. I

Dec 18, 2022

A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM deffiniation and appropriate file structure.

Welcome to function-stencil 👋 A quickstart AWS Lambda function code generator. Downloads a template function code file, test harness file, sample SAM

Jun 20, 2022

Serve file server with single zip file as file system in Deno.

zipland Serve file server with one-single zip file in Deno. Support zip just zip32 with deflated or uncompressed serving plaintext deflate Examples Yo

Nov 2, 2022

Feel free to create new file, don't hesitate to pull your code, the most important thing is that the file name here must match your nickname so that file does not conflict with other people.

Hacktoberfest Indonesia Apa Itu Hacktoberfest ? Hacktoberfest adalah acara tahunan yang bertujuan untuk mendorong berkontribusi kedalam ekosistem open

Dec 15, 2022

This package is an open source extension for MikroORM, which enables Nested Set Tree for your needs

MikroORM nested set This package is an open source extension for MikroORM, which enables Nested Set Tree for your needs Disclaimer For now, this packa

Dec 15, 2022

Ordered lists, flat or nested, multiple formats ordered lists.

Ordered lists, flat or nested, multiple formats ordered lists.

logseq-plugin-ol 有序列表,单级或多级、多种样式的有序列表。 Ordered lists, flat or nested, multiple formats ordered lists. 使用展示 (Usage) 在想要展示为有序列表的块上添加一个以 #.ol 开头的标签就可以了。有

Jan 1, 2023

javascript library to convert a list of objects to a nested json output format, depending on the names in the list

formToNestedJson javascript "library" to convert a list of objects to a nested json output format, depending on the names in the list Basic usage Give

Aug 2, 2021

Serialize an HTML Form to a JavaScript Object, supporting nested attributes and arrays.

jquery.serializeJSON Adds the method .serializeJSON() to jQuery to serializes a form into a JavaScript Object. Supports the same format for nested par

Dec 12, 2022

Util for calling Prisma middleware for nested write operations.

Prisma Nested Middleware Util for calling Prisma middleware for nested write operations. Existing Prisma middleware is called once for every operation

Dec 7, 2022
Owner
Rody Davis
Developer Advocate for @material-components at @Google
Rody Davis
Nested Sort is a JavaScript library which helps you to sort a nested list of items via drag and drop.

Nested Sort Nested Sort is a vanilla JavaScript library, without any dependencies, which helps you to sort a nested list of items via drag and drop. U

Hesam Bahrami 40 Dec 7, 2022
A refined tool for exploring open-source projects on GitHub with a file tree, rich Markdown and image previews, multi-pane multi-tab layouts and first-class support for Ink syntax highlighting.

Ink codebase browser, "Kin" ?? The Ink codebase browser is a tool to explore open-source code on GitHub, especially my side projects written in the In

Linus Lee 20 Oct 30, 2022
🦄 Lit File Generator

A lit generator for a component, directive, and controller

ngneat 16 Oct 25, 2022
Freewall is a cross-browser and responsive jQuery plugin to help you create grid, image and masonry layouts for desktop, mobile, and tablet...

Freewall Freewall is a cross-browser and responsive jQuery plugin to help you create many types of grid layouts: flexible layouts, images layouts, nes

Minh Nguyen 1.9k Dec 27, 2022
Style definitions for nice terminal layouts 👄

blipgloss Style definitions for nice terminal layouts. Powered by lipgloss and bun:ffi. Install bun add blipgloss Usage Blipgloss takes an expressive,

Robert Soriano 51 Dec 31, 2022
Snippets4Dummies is an easy to use Visual Code Extension which is used for building beautiful layouts as fast as your crush rejects you!

Why Snippets4Dummies? Snippets4Dummies is an easy to use Visual Code Extension which is used for building beautiful layouts as fast as your crush reje

SCHWITZ 6 Oct 11, 2022
Mag🔥Lit - A super fast and easy-to-use free and open source private encrypted Magnet/HTTP(s) Link Shortener

Mag ?? Lit Mag ?? Lit - A super fast and easy-to-use free and open source private encrypted Magnet/HTTP(s) Link Shortener https://maglit.ml Features ✅

null 280 Jan 8, 2023
Minimal example of token gating with Next.js and Lit Protocol

This is a minimal example of how to token-gate a Next.js page using Lit Protocol using getServerSideProps. This token gates a /protected page checking

Nader Dabit 37 Dec 31, 2022
A robust form library for Lit that enriches input components with easy-to-use data validation features.

EliteForms A robust form library for Lit that enriches input components with easy-to-use data validation features. Installation npm install elite-form

OSLabs Beta 33 Jun 28, 2022
An example of Lit web component built with vite for use in capacitor.

Vite + Lit + Capacitor An example of Lit web component built with vite for use in capacitor. Demo Features ✅ Typescript ?? Lit ?? Vite ?? Desktop ?? i

Rody Davis 8 Aug 17, 2022