Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fallback til client-side rendering #373

Closed
wants to merge 15 commits into from
Closed
2 changes: 1 addition & 1 deletion .github/workflows/build-and-deploy.yml
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,5 @@ jobs:
env:
CLUSTER: ${{ inputs.CLUSTER }}
RESOURCE: .nais/config.yml
VAR: image=${{ steps.docker-push.outputs.image }}
VAR: image=${{ steps.docker-push.outputs.image }},BUILD_ID=${{ github.sha }}
VARS: .nais/vars/${{ inputs.DEPLOY_INSTANCE }}.yml
8 changes: 4 additions & 4 deletions .github/workflows/deploy.prod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ jobs:
env:
CLUSTER: dev-gcp
RESOURCE: .nais/config.yml
VAR: image=${{ needs.build-and-test.outputs.image }}
VAR: image=${{ needs.build-and-test.outputs.image }},BUILD_ID=${{ github.sha }}
VARS: .nais/vars/dev-stable.yml

deploy-beta-navno:
Expand All @@ -73,7 +73,7 @@ jobs:
env:
CLUSTER: dev-gcp
RESOURCE: .nais/config.yml
VAR: image=${{ needs.build-and-test.outputs.image }}
VAR: image=${{ needs.build-and-test.outputs.image }},BUILD_ID=${{ github.sha }}
VARS: .nais/vars/dev-beta-navno.yml

deploy-prod-next:
Expand All @@ -88,7 +88,7 @@ jobs:
env:
CLUSTER: prod-gcp
RESOURCE: .nais/config.yml
VAR: image=${{ needs.build-and-test.outputs.image }}
VAR: image=${{ needs.build-and-test.outputs.image }},BUILD_ID=${{ github.sha }}
VARS: .nais/vars/prod-next.yml

deploy-prod:
Expand All @@ -103,5 +103,5 @@ jobs:
env:
CLUSTER: prod-gcp
RESOURCE: .nais/config.yml
VAR: image=${{ needs.build-and-test.outputs.image }}
VAR: image=${{ needs.build-and-test.outputs.image }},BUILD_ID=${{ github.sha }}
VARS: .nais/vars/prod.yml
2 changes: 2 additions & 0 deletions .nais/config.yml
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,8 @@ spec:
- application: "*"
namespace: "*"
env:
- name: BUILD_ID
value: {{BUILD_ID}}
{{#each env as |var|}}
- name: {{var.name}}
value: {{var.value}}
Expand Down
Binary file modified bun.lockb
Binary file not shown.
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,11 @@
"dev": "concurrently \"bun run --cwd packages/client dev\" \"bun run --cwd packages/server dev\"",
"build": "bun run --cwd packages/client build && bun run --cwd packages/server build && bun run copy-assets",
"copy-assets": "mkdir -p packages/server/public && cp -r packages/client/dist/assets packages/server/public/",
"copy-assets-temp": "bun run copy-97 && bun run copy-96 && bun run copy-95 && bun run copy-94",
"copy-97": "cp packages/client/dist/assets/csr-*.js packages/client/dist/assets/main-GjdQNcNv.js",
"copy-96": "cp packages/client/dist/assets/csr-*.js packages/client/dist/assets/main-BTg_tyx3.js",
"copy-95": "cp packages/client/dist/assets/csr-*.js packages/client/dist/assets/main-Dn44Sa6d.js",
"copy-94": "cp packages/client/dist/assets/csr-*.js packages/client/dist/assets/main-B0G_DFXG.js",
"prepare": "husky",
"benchmarking": "./benchmarking/run",
"clean": "rm -rf node_modules packages/**/node_modules bun.lockb packages/**/bun.lockb",
Expand Down
36 changes: 0 additions & 36 deletions packages/client/src/auth.ts

This file was deleted.

39 changes: 39 additions & 0 deletions packages/client/src/client-state-update.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import { ClientStateResponse } from "decorator-shared/auth";
import { CustomEvents, createEvent } from "./events";
import { endpointUrlWithParams } from "./helpers/urls";
import { env, param } from "./params";

const fetchClientState = async (): Promise<ClientStateResponse> => {
const url = endpointUrlWithParams("/client-state");

return fetch(url, {
credentials: "include",
})
.then((res) => res.json() as Promise<ClientStateResponse>)
.catch((error) => {
console.error(`Failed to fetch init data - ${error}`);
return { auth: { authenticated: false }, buildId: env("BUILD_ID") };
});
};

const updateClientState = () =>
fetchClientState().then((response) => {
dispatchEvent(
createEvent("client-state-updated", { detail: response }),
);
return response;
});

const updateOnContextSwitch = (
e: CustomEvent<CustomEvents["paramsupdated"]>,
) => {
if (e.detail.params.context) {
updateClientState();
}
};

export const initClientState = () =>
updateClientState().then((response) => {
window.addEventListener("paramsupdated", updateOnContextSwitch);
return response;
});
18 changes: 18 additions & 0 deletions packages/client/src/csr-bundle.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { fetchAndRenderClientSide } from "./csr";

const hydrate = () => {
const url = document.getElementById("decorator-env")?.dataset?.src;
if (!url) {
throw Error(
`decorator-env for CSR not found - See github.com/navikt/decorator-next`,
);
}

fetchAndRenderClientSide(url);
};

if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", hydrate);
} else {
hydrate();
}
58 changes: 34 additions & 24 deletions packages/client/src/csr.ts
Original file line number Diff line number Diff line change
@@ -1,32 +1,42 @@
import { CsrPayload } from "decorator-shared/types";
import { buildHtmlElement } from "./helpers/html-element-builder";
import { buildHtmlElement, htmlElementExists } from "./helpers/html-elements";
import type { CsrPayload } from "decorator-shared/types";

const findOrError = (id: string) => {
const el = document.getElementById(`decorator-${id}`);
export const fetchAndRenderClientSide = async (url: string) => {
const csrAssets = await fetch(url)
.then((res) => res.json() as Promise<CsrPayload>)
.catch((e) => {
console.error("Error fetching CSR assets: ", e);
return null;
});

if (!el) {
throw new Error(`No elem:${id}. See github.com/navikt/decorator-next`);
if (!csrAssets) {
console.error("Failed to fetch CSR assets!");
return;
}

return el;
};
const headerEl = document.getElementById("decorator-header");
if (headerEl) {
headerEl.outerHTML = csrAssets.header;
}

const hydrate = () =>
fetch(findOrError("env").dataset.src!)
.then((res) => res.json())
.then((elements: CsrPayload) => {
(["header", "footer"] as const).forEach(
(key) => (findOrError(key).outerHTML = elements[key]),
);
window.__DECORATOR_DATA__ = elements.data;
const footerEl = document.getElementById("decorator-footer");
if (footerEl) {
footerEl.outerHTML = csrAssets.footer;
}

elements.scripts
.map(buildHtmlElement)
.forEach((script) => document.body.appendChild(script));
window.__DECORATOR_DATA__ = csrAssets.data;

csrAssets.css
.filter((props) => !htmlElementExists(props))
.map(buildHtmlElement)
.forEach((cssElement) => {
document.head.appendChild(cssElement);
});

if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", hydrate);
} else {
hydrate();
}
csrAssets.scripts
.filter((props) => !htmlElementExists(props))
.map(buildHtmlElement)
.forEach((scriptElement) => {
document.body.appendChild(scriptElement);
});
};
4 changes: 2 additions & 2 deletions packages/client/src/events.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import { Context, Params } from "decorator-shared/params";
import { AuthDataResponse } from "decorator-shared/auth";
import { ClientStateResponse } from "decorator-shared/auth";

export type CustomEvents = {
activecontext: { context: Context };
paramsupdated: {
params: Partial<Params>;
};
authupdated: AuthDataResponse;
"client-state-updated": ClientStateResponse;
menuopened: void;
menuclosed: void;
clearsearch: void;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,18 @@
import { HtmlElementProps } from "decorator-shared/types";

export const htmlElementExists = ({ tag, attribs }: HtmlElementProps) => {
const selector = Object.entries(attribs).reduce(
(acc, [key, value]) => `${acc}[${key}="${value}"]`,
tag,
);

const result = !!document.querySelector(selector);

console.log(`Result for ${selector}: ${result}`);

return result;
};

export const buildHtmlElement = ({ tag, attribs, body }: HtmlElementProps) => {
const element = document.createElement(tag);

Expand Down
Loading
Loading