Skip to content

Commit

Permalink
Client side rendering (#179)
Browse files Browse the repository at this point in the history
  • Loading branch information
max-nav authored Jan 19, 2024
1 parent 944f88f commit 43249c3
Show file tree
Hide file tree
Showing 31 changed files with 529 additions and 111 deletions.
Binary file modified bun.lockb
Binary file not shown.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@
},
"dependencies": {
"@grafana/faro-web-sdk": "^1.3.5",
"@navikt/nav-dekoratoren-moduler": "^2.1.5",
"@storybook/addon-essentials": "^7.4.3",
"@storybook/blocks": "^7.4.3",
"@storybook/html": "^7.4.3",
Expand Down
3 changes: 2 additions & 1 deletion packages/client/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,10 @@
"version": "0.0.1",
"scripts": {
"dev": "vite",
"build": "npm run build-main && npm run build-lazy",
"build": "npm run build-main && npm run build-lazy && npm run build-csr",
"build:watch": "vite build --watch --mode main && vite build --watch --mode lazy",
"build-main": "vite build --mode main",
"build-csr": "vite build --mode csr",
"build-lazy": "vite build --mode lazy",
"test": "TZ=UTC vitest run",
"test:watch": "TZ=UTC vitest watch"
Expand Down
19 changes: 10 additions & 9 deletions packages/client/postcss.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,16 @@ const prefixer = require('postcss-prefix-selector');
module.exports = {
plugins: [
require('autoprefixer'),
prefixer({
transform(prefix, selector, prefixedSelector, filePath, rule) {
if ([':root', ':host'].includes(selector)) {
return '#header-withmenu, #footer-withmenu, main';
}

return selector;
},
}),
// To filter out unsued tokens.
// prefixer({
// transform(prefix, selector, prefixedSelector, filePath, rule) {
// if ([':root', ':host'].includes(selector)) {
// return '#header-withmenu, #footer-withmenu, main';
// }
//
// return selector;
// },
// }),

],
};
3 changes: 3 additions & 0 deletions packages/client/src/client.d.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { AppState } from 'decorator-shared/types';
import { Faro } from '@grafana/faro-web-sdk';
import { EventName, CustomEvents, MessageEvents } from './events';
import { Params } from 'decorator-shared/params';
import { Auth } from './api';
import { AnalyticsEventArgs } from './analytics/constants';


declare global {
Expand Down
36 changes: 36 additions & 0 deletions packages/client/src/csr.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import { CsrPayload } from "decorator-shared/types";

const findOrError = (id: string) => {
const el = document.getElementById(id);

if (!el) {
throw new Error(`Could not find element with id ${id}. See documentation on nav-dekoratoren on github.`);
}

return el as HTMLDivElement;
}

function urlToScript(url: string) {
const script = document.createElement('script');
script.src = url;
return script
}

export async function hydrate() {
const [header, footer, envEl] = ['decorator-header', 'decorator-footer', 'decorator-env'].map(findOrError);

const envUrl = envEl.dataset.src as string;

const response = await fetch(envUrl)
const elements = await response.json() as CsrPayload

header.outerHTML = elements.header
footer.outerHTML = elements.footer

// Set decorator state before script evaulation
window.__DECORATOR_DATA__ = elements.data

elements.scripts.map(urlToScript).forEach(script => document.body.appendChild(script))
}

hydrate()
4 changes: 3 additions & 1 deletion packages/client/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/// <reference types="./client.d.ts" />
import { formatParams } from 'decorator-shared/json';
import { LoginLevel, type Context } from 'decorator-shared/params';
import Cookies from 'js-cookie';
Expand Down Expand Up @@ -29,6 +30,8 @@ import { analyticsLoaded, analyticsReady, createEvent } from './events';
import { type ParamKey } from 'decorator-shared/params';
import { param, hasParam, updateDecoratorParams, env } from './params';

console.log('Decorator client loaded');

import.meta.glob('./styles/*.css', { eager: true });

// Just for testing
Expand All @@ -37,7 +40,6 @@ export const CONTEXTS = ['privatperson', 'arbeidsgiver', 'samarbeidspartner'] as

const texts = window.__DECORATOR_DATA__.texts;


updateDecoratorParams({});

if (hasParam('logoutWarning')) {
Expand Down
13 changes: 13 additions & 0 deletions packages/client/vite.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,18 @@ export const lazyConfig = defineConfig({
},
});

export const csrConfig = defineConfig({
build: {
// Don't clear the output, we want to keep the main bundle
emptyOutDir: false,
minify: true,
manifest: '.vite/csr.manifest.json',
rollupOptions: {
input: ['src/csr.ts'],
},
},
});


export default defineConfig(({ mode }) => {
if (mode === 'development') {
Expand All @@ -54,6 +66,7 @@ export default defineConfig(({ mode }) => {
// Build steps
if (mode === 'main') return mainBundleConfig;
if (mode === 'lazy') return lazyConfig;
if (mode === 'csr') return csrConfig;

return mainBundleConfig;
})
2 changes: 2 additions & 0 deletions packages/csr-app/.env
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
VITE_MILJO_URL=http://localhost:8089
VITE_DECORATOR_PARAMS=simple=false
24 changes: 24 additions & 0 deletions packages/csr-app/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
pnpm-debug.log*
lerna-debug.log*

node_modules
dist
dist-ssr
*.local

# Editor directories and files
.vscode/*
!.vscode/extensions.json
.idea
.DS_Store
*.suo
*.ntvs*
*.njsproj
*.sln
*.sw?
Binary file added packages/csr-app/bun.lockb
Binary file not shown.
2 changes: 2 additions & 0 deletions packages/csr-app/bunfig.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
[install.scopes]
"@navikt" = { token = "$NODE_AUTH_TOKEN", url = "https://npm.pkg.github.com" }
18 changes: 18 additions & 0 deletions packages/csr-app/index.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<link rel="icon" type="image/svg+xml" href="/vite.svg" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Vite + Preact + TS</title>
<link href="%VITE_MILJO_URL%/css/client.css" rel="stylesheet" />
</head>
<body>
<div id="decorator-header"></div>
<div id="app"></div>
<div id="decorator-footer"></div>
<div id="decorator-env" data-src="%VITE_MILJO_URL%/env?%VITE_DECORATOR_PARAMS%"></div>
<!-- <script async="true" src="%VITE_MILJO_URL%/client.js"></script> -->
<script type="module" src="/src/main.tsx"></script>
</body>
</html>
21 changes: 21 additions & 0 deletions packages/csr-app/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
{
"name": "csr-app",
"private": true,
"version": "0.0.0",
"type": "module",
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
"preview": "vite preview"
},
"dependencies": {
"decorator-client": "workspace:*",
"@navikt/nav-dekoratoren-moduler": "^2.1.5",
"preact": "^10.19.3"
},
"devDependencies": {
"@preact/preset-vite": "^2.7.0",
"typescript": "^5.2.2",
"vite": "^5.0.8"
}
}
1 change: 1 addition & 0 deletions packages/csr-app/public/vite.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
25 changes: 25 additions & 0 deletions packages/csr-app/src/app.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#app {
max-width: 1280px;
margin: 0 auto;
padding: 2rem;
text-align: center;
}

.logo {
height: 6em;
padding: 1.5em;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.preact:hover {
filter: drop-shadow(0 0 2em #673ab8aa);
}

.card {
padding: 2em;
}

.read-the-docs {
color: #888;
}
30 changes: 30 additions & 0 deletions packages/csr-app/src/app.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import { useState } from 'preact/hooks';
import preactLogo from './assets/preact.svg';
import viteLogo from '/vite.svg';
import './app.css';

export function App() {
const [count, setCount] = useState(0);
// injectDecoratorClientSide()

return (
<>
<div>
<a href="https://vitejs.dev" target="_blank">
<img src={viteLogo} class="logo" alt="Vite logo" />
</a>
<a href="https://preactjs.com" target="_blank">
<img src={preactLogo} class="logo preact" alt="Preact logo" />
</a>
</div>
<h1>Vite + Preact</h1>
<div class="card">
<button onClick={() => setCount((count) => count + 1)}>count is {count}</button>
<p>
Edit <code>src/app.tsx</code> and save to test HMR
</p>
</div>
<p class="read-the-docs">Click on the Vite and Preact logos to learn more</p>
</>
);
}
1 change: 1 addition & 0 deletions packages/csr-app/src/assets/preact.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
71 changes: 71 additions & 0 deletions packages/csr-app/src/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
:root {
font-family: Inter, system-ui, Avenir, Helvetica, Arial, sans-serif;
line-height: 1.5;
font-weight: 400;

color-scheme: light dark;
color: rgba(255, 255, 255, 0.87);
background-color: #242424;

font-synthesis: none;
text-rendering: optimizeLegibility;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}

a {
font-weight: 500;
color: #646cff;
text-decoration: inherit;
}
a:hover {
color: #535bf2;
}

/* body {
*
# VITE_DECORATOR_PARAMS=simple=true
* */
/* margin: 0; */
/* display: flex; */
/* place-items: center; */
/* min-width: 320px; */
/* min-height: 100vh; */
/* } */

h1 {
font-size: 3.2em;
line-height: 1.1;
}

button {
border-radius: 8px;
border: 1px solid transparent;
padding: 0.6em 1.2em;
font-size: 1em;
font-weight: 500;
font-family: inherit;
background-color: #1a1a1a;
cursor: pointer;
transition: border-color 0.25s;
}
button:hover {
border-color: #646cff;
}
button:focus,
button:focus-visible {
outline: 4px auto -webkit-focus-ring-color;
}

@media (prefers-color-scheme: light) {
:root {
color: #213547;
background-color: #ffffff;
}
a:hover {
color: #747bff;
}
button {
background-color: #f9f9f9;
}
}
12 changes: 12 additions & 0 deletions packages/csr-app/src/main.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { render } from 'preact';
import { App } from './app.tsx';
import './index.css';

// injectDecoratorClientSide({
// env: "localhost",
// localUrl: "http://localhost:8089"
// })

render(<App />, document.getElementById('app')!);

import 'decorator-client/src/csr';
1 change: 1 addition & 0 deletions packages/csr-app/src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
30 changes: 30 additions & 0 deletions packages/csr-app/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
"paths": {
"react": ["./node_modules/preact/compat/"],
"react-dom": ["./node_modules/preact/compat/"]
},

/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
"jsxImportSource": "preact",

/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}
Loading

0 comments on commit 43249c3

Please sign in to comment.