satyarohith / sift

Sift is a routing and utility library for Deno Deploy.
https://deno.land/x/sift
MIT License
170 stars 14 forks source link

Use nanojsx #42

Open satyarohith opened 3 years ago

satyarohith commented 3 years ago

It seems to be helpful to build single-page apps quickly. I like how simple this example is.

import { h, ssr, tw } from "https://crux.land/nanossr@0.0.1";

const Hello = (props) => (
  <div class={tw`bg-white flex h-screen`}>
    <h1 class={tw`text-5xl text-gray-600 m-auto mt-20`}>
      Hello {props.name}!
    </h1>
  </div>
);

addEventListener("fetch", (event) => {
  const url = new URL(event.request.url);
  const name = url.searchParams.get("name") ?? "world";
  event.respondWith(ssr(() => <Hello name={name} />));
});
hastebrot commented 2 years ago

nanossr@0.0.1 was not updated for a while. Latest dependencies are now

Based on the example and the ssr dependency I've written some code a few weeks ago. Maybe it is somehow useful.

web.tsx:

// deno run --watch --no-clear-screen --allow-net=0.0.0.0:8000 web.tsx

/// <reference no-default-lib="true"/>
/// <reference lib="dom" />
/// <reference lib="dom.iterable" />
/// <reference lib="dom.asynciterable" />
/// <reference lib="deno.ns" />

/** @jsx h */
import { serve } from "https://deno.land/std@0.114.0/http/server.ts";
import { h, ssr } from "./webssr.ts";
import { sheet, stringify, tw } from "./webtw.ts";

const Hello = (props: { name: string }) => (
  <div class={tw`bg-white flex h-screen`}>
    <h1 class={tw`text-indigo-500 p-5 text-xl font-semibold`}>
      Hello {props.name}!
    </h1>
  </div>
);

if (import.meta.main) {
  console.log("Listening on http://localhost:8000");
  await serve((req) => {
    const url = new URL(req.url);
    const name = url.searchParams.get("name") ?? "world";
    return new Response(
      ssr(
        () => h(<Hello name={name} />),
        () => stringify(sheet.target),
      ),
      { headers: { "content-type": "text/html" } },
    );
  });
}

webssr.ts:

import {
  h,
  Helmet,
  renderSSR,
} from "https://deno.land/x/nano_jsx@v0.0.30/mod.ts";

export function ssr(render: CallableFunction, renderStyles: CallableFunction) {
  const app = renderSSR(render());
  const styles = renderStyles();
  const { body, head, footer } = Helmet.SSR(app);

  return `
    <html>
      <head>
        ${head}
        <style>${styles}</style>
      </head>
      <body>
        ${body}
        ${footer}
      </body>
    </html>
  `;
}

export { h };

webtw.ts:

import {
  stringify,
  twind,
  virtual,
} from "https://cdn.skypack.dev/twind@1.0.0-next.37";
import presetTailwind from "https://cdn.skypack.dev/@twind/preset-tailwind@1.0.0-next.37";

export const sheet = virtual();

export const tw = twind({
  presets: [
    presetTailwind({ disablePreflight: false }),
  ],
}, sheet);

export { stringify };