• Stars
    star
    268
  • Rank 153,144 (Top 4 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 8 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

🇨🇭Switzerland takes a functional approach to Web Components by applying middleware to your components. Supports Redux, attribute mutations, CSS variables, React-esque setState/state, etc… out-of-the-box, along with Shadow DOM for style encapsulation and Custom Elements for interoperability.

Switzerland

Switzerland takes a functional approach to web components using Preact with shadow DOM for style encapsulation, custom elements for interoperability and server-side rendering for universality.

npm   License MIT   code style: prettier

yarn: yarn add switzerland
npm: npm install switzerland
cdn: https://cdn.jsdelivr.net/npm/switzerland@latest/dist/index.client.js

Screenshot


Contents

  1. Getting Started
  2. Import Maps
  3. Managing State
  4. Applying Styles
  5. Data Fetching
  6. Environment Context
  7. Extending Elements

Getting Started

Switzerland optionally begins with server-side rendering with hydration on the client thanks to declarative shadow DOM — with our components looking very familiar due to our usage of Preact.

import { create } from "switzerland";

export default create("x-countries", () => {
  return (
    <ul>
      <li>Japan</li>
      <li>Croatia</li>
      <li>Singapore</li>
    </ul>
  );
});

Once we've defined our x-countries component we are able to both render it on the server and hydrate it on the client as a standard <x-countries /> DOM element. We can then take a step further and allow our countries to be passed as a HTML attribute on the DOM node using <x-countries list="Japan,Croatia,Singapore">.

import { create, type, use } from "switzerland";

type Attrs = {
  countries: string[];
};

export default create<Attrs>("x-countries", () => {
  const attrs = use.attrs({
    countries: type.Array(type.String),
  });

  return (
    <ul>
      {attrs.countries.map((country) => (
        <li key={country}>{country}</li>
      ))}
    </ul>
  );
});

Using our component from within a Node environment requires us to use the exported asynchronous render function; we can specify an optional second parameter to the function, however our component currently doesn't perform data fetching or media inclusion and so is unnecessary.

import { render } from "switzerland";

app.get("/", async (_, response) => {
  const html = await render(<Countries list="Japan,Croatia,Singapore" />);
  response.send(html);
});

As our components are self-contained modules, any changes to their attributes will initiate a re-render of the component's tree – regardless of whether those attributes change from inside another component or through vanilla DOM accessors.

const node = document.querySelector("x-countries");
node.attributes.values = `${node.attributes.values},Ukraine,Maldives`;

Import Maps

Switzerland doesn't need to be compiled except for optional TypeScript and JSX transpiling because it uses native ES modules in the browser and Node 16+ on the server. It achieves this by using node_modules when rendering on the server using named imports, and in the browser it uses import maps to resolve those named imports to CDN URLs which offers enhanced caching. We provide a utility for the server to automatically generate the import maps for your application based on its dependencies.

import fs from "node:fs";
import { imports, render } from "switzerland";

app.get("/", async (_, response) => {
  const html = await render(<Countries list="Japan,Croatia,Singapore" />);
  const importMap = await imports({ path: path.resolve("../app/src") });

  response.send(`
        <head>
            <script type="importmap">
                ${importMap}
            </script>
        </head>

        <body>
            ${html}
        </body>
    `);
});

You need to give the imports function the base path of your Switzerland components. It will then traverse the files using ts-morph which provides an abstract syntax tree (AST) of your code and allows us to pick out the external dependencies; it then iteratively matches each of those dependencies it finds to the versions installed by your chosen package manager. We use the @jspm/generator package to resolve the dependencies to jspm.io URLs by default – however you may also pass the provider option to change the provider.

Once you have the import map configured, when rendering Switzerland components in the browser it will use those CDN URLs and prevent any need to package up dependencies via a bundler. You can focus purely on the simple task of transpiling TypeScript and JSX into native ES modules using nothing more than tsc – although if you want to minify you may need to add Terser.

{
  "include": ["src"],

  "compilerOptions": {
    "rootDir": "./src",
    "outDir": "./dist",

    "module": "esnext",
    "moduleResolution": "nodenext",
    "esModuleInterop": true,
    "target": "esnext",
    "strict": true,
    "jsx": "react-jsx",
    "jsxImportSource": "preact",
    "declaration": true
  }
}

Managing State

Since we use Preact to render Switzerland's components the API should already be familiar. For ease of use we re-export Preact's hook functions but you may also use them directly from Preact.

import { create, use } from "switzerland";

export default create("x-countries", () => {
  const [countries, setCountries] = use.state([
    "Japan",
    "Croatia",
    "Singapore",
  ]);

  return (
    <ul>
      {countries.map((country) => (
        <li key={country}>{country}</li>
      ))}
    </ul>
  );
});

Applying Styles

Styles within a shadow boundary allow for encapsulation which means we can use regular CSS documents scoped to our component's tree. We can attach our stylesheets to our component by using a regular link node, although Switzerland provides a node utility for StyleSheet and Variables — the latter applies custom variables to your component tree allowing CSS to access those JavaScript variables. We use the use.path hook to resolve media — CSS documents, images, etc... — relative to our component.

import { create, node, use } from "switzerland";

export default create("x-countries", () => {
  const path = use.path(import.meta.url);
  const [countries, setCountries] = use.state([
    "Japan",
    "Croatia",
    "Singapore",
  ]);

  return (
    <>
      <ul>
        {countries.map((country) => (
          <li key={country}>{country}</li>
        ))}
      </ul>

      <node.Variables
        backgroundColour={countries.length === 0 ? "#8ECCD4" : "#FBDEA3"}
      />

      <node.StyleSheet href={path("./styles/default.css")} />
      <node.StyleSheet
        href={path("./styles/mobile.css")}
        media="(max-width: 768px)"
      />
      <node.StyleSheet href={path("./styles/print.css")} media="print" />
    </>
  );
});

We can then be quite loose when applying those styles to our component knowing that the shadow boundary will prevent styles from leaking out — we use a CSS variable to apply a conditional background colour with a fallback.

:host {
  box-shadow: 0 0 5px #e8c5b0;
}

ul {
  background-color: var(--background-color, "#E39AC7");
}

Data Fetching

Since Switzerland allows for server-side rendering by default a use.loader utility hook is provided for fetching data – although you may choose to use any other third-party fetching utility or a simple useEffect and that is fine too. Using loader hook allows for fetching data server-side and then preventing a re-fetch on the client; we achieve this by rendering our components twice in the asynchronous render function we covered earlier and then including the serialised data in the tree.

import { create, use } from "switzerland";

export default create("x-countries", () => {
  const { data, loading, error } = use.loader(
    "x-countries",
    () =>
      fetch("https://www.example.org/countries").then((response) =>
        response.json()
      ),
    null
  );

  return loading ? (
    <p>Loading&hellip;</p>
  ) : (
    <ul>
      {data.map((country) => (
        <li key={country}>{country}</li>
      ))}
    </ul>
  );
});

We provide a unique ID to the loader function which should identify the individual request to prevent duplicates and to allow for reconciliation on the client. With the dependencies argument in third position we can re-invoke the loader client-side whenever a parameter changes; in our case we probably don't want to re-fetch given nothing changes but if fetching by a given list we might expect the current list of countries to be provided as dependencies.

Environment Context

Providing the environment context requires some user configuration on the server side — the render function takes an optional second parameter which allows us to specify both the root directory on the web-server and optionally the domain we're running the server on.

import App from "./App";
import { preload, render } from "switzerland";

const vendor = path.resolve("..");

const options = {
  path: process.env["DOMAIN"]
    ? `https://${process.env["DOMAIN"]}/client`
    : "http://localhost:3000/client",
  root: vendor,
};

app.get("/", async (_, response) => {
  const html = await render(
    <Countries list="Japan,Croatia,Singapore" />,
    options
  );
  response.send(html);
});

We use these options to resolve media using the use.path hook with import.meta.url relative to the component – on the server we need to know the root directory in order to achieve this. On the client-side however it's slightly more simple since we know the root based on each components' path. Likewise with the path option where we specify the domain the web-server is running on; we use this to provide absolute paths to media so that components can be utilised in third-party applications, however since it's optional we use the aforementioned root to specify a relative path which is perfectly fine when we're only using our components on our own web-server.

Using the use.env hook we can access these defined parameters as well as a few additional items.

import { create, use } from "switzerland";

export default create("x-countries", () => {
  const { path, root, node, isServer, isClient } = use.env();

  return (
    <>
      {node && <h1>Hey {node.nodeName}!</h1>}

      <p>Server: {isServer}</p>
      <p>Client: {isClient}</p>

      <ul>
        <li>Japan</li>
        <li>Croatia</li>
        <li>Singapore</li>
      </ul>
    </>
  );
});

Extending Elements

You may also extend native HTML elements using the x-hello:button syntax in the create function – it'll create a x-hello custom element that extends from the button constructor allowing you to add your own twist to it.

import { create, use } from "switzerland";

export default create("x-hello:button", () => {
  const handleClick = use.callback((): void => console.log("Hello!"), []);

  return <button onClick={handleClick}>Say Hello!</button>;
});

More Repositories

1

ReactShadow

🔰 Utilise Shadow DOM in React with all the benefits of style encapsulation.
JavaScript
1,303
star
2

Leaflet.FreeDraw

🌏 FreeDraw allows the free-hand drawing of shapes on your Leaflet.js map layer – providing an intuitive and familiar UX for creating geospatial boundaries similar to Zoopla and others. Included out-of-the-box is the concaving of polygons, polygon merging and simplifying, as well as the ability to add edges and modify existing shapes.
JavaScript
526
star
3

Maple.js

Maple.js is a React webcomponents based framework mixing ES6 with Custom Elements, HTML Imports and Shadow DOM. It has in-built support for SASS and JSX, including a Gulp task for vulcanizing your project.
JavaScript
431
star
4

Magento-on-Angular

Angular.js application using Magento as the backend API
PHP
361
star
5

Legofy

Legofy your images with retina support using SVG.
JavaScript
301
star
6

ngDroplet

Angular.js HTML5 file uploading with drag & drop and image/file preview.
JavaScript
287
star
7

ngVideo

Modularised ~13KB HTML5 audio/video implementation using Angular.js
JavaScript
227
star
8

Keo

Plain functions for a more functional Deku approach to creating stateless React components, with functional goodies such as compose, memoize, etc... for free.
JavaScript
227
star
9

Standalone

Create framework agnostic components that are truly reusable and interoperable with all the benefits of the React ecosystem – using the HTML5 custom elements API to extend HTML's vocabulary.
JavaScript
206
star
10

Snapshot.js

Node.js app for slicing and dicing ~100,000 models in <5ms with easy sorting, paginating, and filtering.
JavaScript
202
star
11

EmberDroplet

Ember.js HTML5 file uploading with drag & drop and image/file preview.
JavaScript
198
star
12

EmberSockets

Socket.io (WebSockets) integrated with Ember.js' observer pattern.
JavaScript
136
star
13

Dory

Dory is a responsive, universal, GitHub collaborated blogging platform built on React and powered by Express. By combining awesome features such as automatic RSS generation, HTML5 offline support, push notifications, with a powerful development environment using hot reloading, SASS and Markdown, Dory allows developers to quickly dive into the depths of blogging.
JavaScript
128
star
14

Interpose

Apply stylesheet variables to your React components for use in your stylesheets. Interpose reduces the clutter of React components by bridging the gap between JS and CSS without resorting to complicating your components with CSS logic.
JavaScript
126
star
15

Mocktail

🍹 Mock all of your ES6 module components with Mocktail using dependency injection.
JavaScript
103
star
16

ngCrossfilter

Usual Angular.js style filtering and sorting with a twist of Crossfilter for improved performance.
JavaScript
87
star
17

ngContextMenu

Handcraft your very own context menus for a richer UX!
JavaScript
80
star
18

gulp-processhtml

Process html files at build time to modify them depending on the release environment
JavaScript
77
star
19

L.Pather

Branching from Leaflet.FreeDraw, L.Pather is a freehand polyline creator that simplifies the polyline for mutability.
JavaScript
69
star
20

Freelancer

👔 An implementation of on-the-fly defined WebWorkers that are created inline using data URIs, rather than separate physical files — for the benefit of all humanity.
JavaScript
67
star
21

Amelie

HTML5 audio visualiser experiment using D3 with a curious Amelie theme.
JavaScript
57
star
22

ngRangeSlider

Multi-handle range slider utilising the native HTML5 input range elements.
JavaScript
54
star
23

EmberCrossfilter

Instead of using Ember DataStore, EmberCrossfilter provides a basic architecture for creating Ember models with Crossfilter; which allows for much quicker sorting and filtering.
JavaScript
48
star
24

DetectFont

Detect which font your system has cherry-picked from font-family.
JavaScript
41
star
25

CloudConvert

Easy-to-use Node.js implementation of the CloudConvert API.
JavaScript
38
star
26

Redecorate

Simple module for reducing immutable nested properties in Redux applications.
JavaScript
27
star
27

ngPourOver

PourOver wrapper for Angular.js with super-quick filtering and sorting.
JavaScript
27
star
28

ReactDelayed

Small component for delaying the mounting and unmounting of a child component for CSS animation purposes.
JavaScript
21
star
29

ngImgur

Take your favourite cat picture, and upload it to Imgur.com w/ Angular!
JavaScript
17
star
30

RedisCache

Simple Node.js based Redis cache for storing large collections of data.
JavaScript
16
star
31

ngRoundabout

Three-dimensional HTML5 carousel implemented in Angular.js.
JavaScript
14
star
32

ReactCrossfilter

Crossfilter.js implemented as a mixin for ultra-fast filtering and sorting techniques baked into React.js components.
JavaScript
13
star
33

ngDonut

Lightweight and extensible Angular implementation of the D3 donut graph.
JavaScript
11
star
34

Readlint

📙Lint all of the code examples in your README documentation using shared configs.
JavaScript
10
star
35

ngObelisk

Easily use Obelisk to create animations using Angular.js.
JavaScript
10
star
36

ngTeleport

Move a section of the DOM and inherit the scope of the target node.
JavaScript
9
star
37

Webmonkey

🙊 Robust and versatile headless monkey testing for the modern web with reproducible steps, error alerts, strategy sharing and many other good things.
JavaScript
9
star
38

Formv

🗳React form validation using the validation native to all recent browsers. Also includes support for handling API validation messages, success messages, memoized and nested form state, and super easy styling.
JavaScript
9
star
39

Taskfile

📦 Yet another attempt at a simple task runner for npm with parallelisation support using bash commands via YAML.
JavaScript
8
star
40

EarthApp

Three.js w/ Angular implementation of planet earth using SketchUp for the models.
JavaScript
7
star
41

EmberRickshaw

Rickshaw façade for Ember which allows automatic redrawing of graphs using Ember's observer pattern.
JavaScript
7
star
42

Memoria

Extensible form storage for memorising user inputs with local storage. Never lose your form data ever again!
JavaScript
7
star
43

Koi

Koi is a time aware interactive bird written in THREE.js with voice recognition, and an artificial IQ.
JavaScript
6
star
44

Pellucid

Experimental module using HTML5's Custom Elements that creates a crystalline blurred background.
JavaScript
6
star
45

Catwalk

Intuitive and fast relational CRUD interface for modelling relationships using vanilla objects written in ES6.
JavaScript
6
star
46

Mapleify

Mapleify is a build tool for Maple.js; it uses Polymer's vulcanize to process HTML imports with a little twist of Maple specific logic for HTML Import paths, and the processing of SASS/JSX documents.
JavaScript
6
star
47

Bi-cycle

Bi-cycle assists in making infinite carousels and sliders by handling the index logic for you.
JavaScript
5
star
48

Openroulette

Openroulette is a Chatroulette implementation built using the WebRTC component.
JavaScript
4
star
49

Vik

CLI Semver autoincrement with major, minor, and patch.
JavaScript
4
star
50

Draught

Drawing tool in ES6 for creating diagrams using D3 with an extensible event driven architecture.
JavaScript
4
star
51

Maducer

An experimental map-reduce concurrency over web workers using shared array buffer for handling large datasets.
JavaScript
3
star
52

OrderlyQueue

Implementation of a promise-based FIFO queuing system using ES2017 async generators.
JavaScript
3
star
53

AnsibleAlexa

Development deployment using Vagrant w/ Ansible provisioner.
PHP
3
star
54

Canvas-Background

A super useful function for applying a background colour to a canvas element before invoking toDataURL.
JavaScript
3
star
55

MayBee

Safe chaining of object properties and functions using ES2015 Proxy.
JavaScript
3
star
56

Angularise

Deferred compilation of Angular.js templates for applications that render HTML from asynchronous processes.
JavaScript
3
star
57

PointerEvents

Allow the emulation of pointer events for browsers without native support, such as Internet Explorer.
JavaScript
3
star
58

Instamap

✈️ Towards the end of 2016, Instagram removed the Photo Maps feature. Instagram says it was unused, but we remember! Instamap brings it back for good, open-source and ad-free.
JavaScript
3
star
59

mundus-meus

Leaflet.js & Angular.js mapping tool for finding entities based on your location.
JavaScript
2
star
60

Typified

🗼An experimental implementation of first class functional types using pure ES at runtime, inspired by Haskell, PureScript and Idris.
JavaScript
2
star
61

Banter.js

Angular based real-time app for communicating with customers via IRC. Individual customers connect to a common IRC channel, giving staff members the ability to see all customers' messages, with the ability to respond directly and individually.
JavaScript
2
star
62

UMLApp

JavaScript
2
star
63

Needle.js

Angular.js style dependency injection using reflection.
JavaScript
2
star
64

Biutiful

🌿 Biutiful transform ES imports into browser usable ECMAScript imports.
JavaScript
2
star
65

Shift.js

Use the shift key to select a range of elements, such as checkboxes.
JavaScript
2
star
66

Lenin

Diagram tool using D3 providing a set of common functions for easy integration and extensibility.
JavaScript
2
star
67

UploadButton

UploadButton is a tiny module for a custom stylable upload button. Using HTML5's Custom Element API and Shadow DOM for encapsulation.
JavaScript
2
star
68

Tail.cat

Modern e-mail client and SMTP/POP server using MongoDB, Ruby, Angular
JavaScript
2
star
69

Tessellate

Small vanilla JavaScript module for gracefully removing floating elements from the page.
JavaScript
2
star
70

PolymerDroplet

Polymer.js adaptation of my popular EmberDroplet module for Ember.js.
JavaScript
2
star
71

DjangoExceptions

Handle and parse Django REST Framework validation messages with aplomb.
JavaScript
2
star
72

Moggy

Miniature ~2kb library that brings immutability to existing prototype functions employing the principle of least astonishment.
JavaScript
2
star
73

NodeURLImports

Transform browser URL imports into Node compatible import/require statements using local dependencies.
JavaScript
2
star
74

Viewport

Determine how much of an element is visible in the viewport.
JavaScript
1
star
75

ReduxLocal

Redux helper for maintaining pseudo-local state in a single tree.
JavaScript
1
star
76

Tdo

Terminal based todo app for managing today's tasks with gentle reminders
Rust
1
star
77

Tidal.js

Socket.io benchmarking with realtime web-based statistics.
JavaScript
1
star
78

Memor

Use memoization for Rust functions to increase performance
Rust
1
star
79

Kiwi.js

DRY interface for Angular.js tests in Jasmine/Karma.
JavaScript
1
star
80

Workex

1
star
81

Funkel

Simple and lightweight functional toolset inspired by Clojure using import.
JavaScript
1
star
82

StickyRice

🍚 React implementation to allow the natural position sticky behaviour in table headers and other elements
JavaScript
1
star
83

Hylian

Quick and easy doubly and singly linked immutable list implementation that allows for inserting, removing and shifting.
JavaScript
1
star
84

DeveloperInk

Facilitates the use of ZURB's Ink for developers using the CLI with SASS, Email Testing, Compilation, etc... 🐙
CSS
1
star
85

WeakTree

🌲WeakMap implementation that allows for composite keys in a tree formation.
JavaScript
1
star
86

Mareos

MapReduce over WebSockets using Goroutines.
Go
1
star
87

SetOrder

Tiny module for sorting by a set order, using a custom sort function for omitting explicits.
JavaScript
1
star
88

Paramo

🌵Swiss-army knife of stringifying, parsing and manipulating URL parameters by applying types to the parameters.
JavaScript
1
star
89

ava-webcomponents

Utility middleware for testing web components in AVA via Puppeteer.
JavaScript
1
star
90

Regrowth

🔬Regrowth is a monstrous laboratory experiment in container queries brought to life.
JavaScript
1
star
91

Cinematic.js

Experimental module for video sequence scrolling with zero dependencies.
JavaScript
1
star
92

Termtodo

Todo app for the terminal for keeping reminders for later
Rust
1
star
93

Honey.js

Simple JavaScript library with auto-updating templates.
JavaScript
1
star
94

ReactAutolist

Browser native implementation of autocomplete using the datalist element.
JavaScript
1
star
95

Relayed

Convenient Node.js app for circumventing CORS issues when developing on localhost.
JavaScript
1
star
96

Doogle

Node.js app for taking HTML snapshots of JavaScript pages to make your dynamic apps Google crawlable.
JavaScript
1
star
97

gulp-envy

Gulp plugin for transferring your chosen environment variables to objects, with module loader, globals, angular, and other strategies.
1
star
98

redux-nest

Redux middleware for wrapping store in a Proxy to help with complex nested states.
JavaScript
1
star
99

Async

Yet another simple Promises/A+ compliant async flow control using ES6 generators.
JavaScript
1
star
100

TravelMap

🌏 Pin visited locations on a simple-to-use map, as well as future places you'd love to see. Then share with the world!
Python
1
star