Compare commits

..
19 changed files with 182 additions and 27 deletions

No files matched your search

+1 -1
View File
@@ -35,7 +35,7 @@ jobs:
sanity_read_no_drafts_token: ${{ secrets.SANITY_READ_NO_DRAFTS }}
- name: Build and push Docker image
uses: nais/docker-build-push@v1
uses: nais/docker-build-push@v0
id: docker-push
with:
team: designsystem
+1 -1
View File
@@ -40,7 +40,7 @@ jobs:
run: cd apps/mcp-server && yarn build
- name: Build and push Docker image
uses: nais/docker-build-push@v1
uses: nais/docker-build-push@v0
id: docker-push
with:
team: designsystem
+1 -1
View File
@@ -68,7 +68,7 @@ jobs:
next_encryption_key: ${{ secrets.NEXT_ENCRYPTION_KEY }}
- name: Build and push Docker image
uses: nais/docker-build-push@v1
uses: nais/docker-build-push@v0
id: docker-push
with:
team: designsystem
+1 -1
View File
@@ -44,7 +44,7 @@ jobs:
shell: bash
- name: Build and push Docker image
uses: nais/docker-build-push@v1
uses: nais/docker-build-push@v0
id: docker-push
with:
team: designsystem
+2 -2
View File
@@ -42,7 +42,7 @@ jobs:
- name: Create release Pull Request or publish to NPM
id: changesets
uses: changesets/action@v2
uses: changesets/action@v1
with:
version: yarn create-version
publish: yarn release
@@ -66,7 +66,7 @@ jobs:
- name: Publish to GPR
if: steps.changesets.outputs.published == 'true'
id: changesets-gpr
uses: changesets/action@v2
uses: changesets/action@v1
with:
publish: yarn changeset publish
createGithubReleases: false
+12
View File
@@ -0,0 +1,12 @@
import { beforeAll } from "vitest";
/*
* WebKit can hold back the first animation frame in a fresh test iframe for over a second on CI.
* Mount focus (e.g. FocusBoundary) waits for a frame, so the first `waitFor(toHaveFocus)` would hit
* its 1s timeout. Waiting for one frame here moves that delay into the hook instead.
*/
beforeAll(async () => {
await new Promise<void>((resolve) => {
requestAnimationFrame(() => resolve());
});
});
+1 -1
View File
@@ -25,7 +25,7 @@
margin-bottom: var(--ax-space-2);
}
/* stylelint-disable-next-line plugin/no-unsupported-browser-features -- :nth-child(of S) in WIP preview component */
/* stylelint-disable-next-line plugin/no-unsupported-browser-features -- Progressive enhancement */
.aksel-listbox__group:first-child &:nth-child(1 of &) {
/* When we scroll to the first option, and that option is in a group,
scroll to the very top so that the group label is visible as well.
@@ -41,6 +41,12 @@ interface ComboboxProps<
* Field name. When provided, the field value will be included in form submissions.
*/
name?: string;
/**
* Maximum width of the trigger (the element that shows the currently selected value).
*
* **NB: Use a unit that scales with the font size, such as rem or em.**
*/
controlMaxWidth?: string;
}
const Combobox = forwardRef(
@@ -49,6 +55,7 @@ const Combobox = forwardRef(
label,
hideLabel,
name,
controlMaxWidth,
size: sizeProp,
error,
errorId: errorIdProp,
@@ -110,7 +117,13 @@ const Combobox = forwardRef(
</BodyShort>
)}
<ComboboxTrigger readOnly={readOnly} {...inputProps}>
<ComboboxField ref={ref} hasError={hasError} />
<ComboboxField
ref={ref}
hasError={hasError}
containerStyle={
controlMaxWidth ? { maxWidth: controlMaxWidth } : undefined
}
/>
</ComboboxTrigger>
<div
className="aksel-form-field__error aksel-combo-box__error"
@@ -127,7 +140,13 @@ const Combobox = forwardRef(
{name &&
rest.value.map((val) => (
<input key={val} type="hidden" name={name} value={val} />
<input
key={val}
type="hidden"
name={name}
value={val}
disabled={inputProps.disabled}
/>
))}
<ComboboxOverlay
@@ -179,7 +198,7 @@ interface ComboboxSingleProps<
*
* **WARNING: This component is in active development and may receive breaking changes outside major releases!**
*
* @see [📝 Documentation](https://aksel.nav.no/komponenter/core/TODO)
* @see [📝 Documentation](https://aksel.nav.no/komponenter/core/combobox-single)
* @see 🏷️ {@link ComboboxSingleProps}
*
* @example
@@ -188,6 +207,7 @@ interface ComboboxSingleProps<
* label="Select country"
* name="country"
* options={countries}
* controlMaxWidth="12rem"
* />
* ```
*/
@@ -10,10 +10,11 @@ import {
interface ComboboxFieldProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
children?: string;
hasError?: boolean;
containerStyle?: React.CSSProperties;
}
const ComboboxField = forwardRef<HTMLButtonElement, ComboboxFieldProps>(
({ children, hasError, ...rest }, ref) => {
({ children, hasError, containerStyle, ...rest }, ref) => {
const { options, value, size } = useComboboxRootContext();
const translate = useI18n("Combobox2");
@@ -35,7 +36,7 @@ const ComboboxField = forwardRef<HTMLButtonElement, ComboboxFieldProps>(
}, [label]);
return (
<div className="aksel-combo-box__field-container">
<div className="aksel-combo-box__field-container" style={containerStyle}>
<button
type="button"
ref={ref}
@@ -31,6 +31,7 @@ export const ComboboxFilter = (props: ComboboxFilterProps) => {
label={translate("filter")}
hideLabel
variant="simple"
clearButton={false}
onKeyUp={(event) => {
if (["ArrowUp", "ArrowDown"].includes(event.key)) {
event.preventDefault(); // Prevents navigation with screen reader
@@ -60,7 +60,7 @@ export const ComboboxPopup = ({ children }: ComboboxPopupProps) => {
}
const inputElm = ref.current?.querySelector<HTMLInputElement>("input");
if (inputElm) {
inputElm.focus();
inputElm.focus({ preventScroll: true });
return;
}
const listElm =
+58 -10
View File
@@ -1,18 +1,66 @@
import { expect, test } from "@playwright/test";
import { type Page, expect, test } from "@playwright/test";
/* Simple Button component without any props */
const previewUrl =
"/sandbox/preview/index.html?code=N4Igxg9gJgpiBcIA8AhArgFwxAdgPgB0cACY9LXIpAenO3xAF8g";
const example = "N4Igxg9gJgpiBcIA8AhArgFwxAdgPgB0cACY9LXIpAenO3xAF8g";
function renderedExample(page: Page) {
return page
.frameLocator("iframe")
.first()
.frameLocator('iframe[title="Example"]')
.locator("#sandbox-wrapper");
}
test.describe("Check website sandbox", () => {
test("Check if sandbox is loading for preview", async ({ page }) => {
await page.goto(previewUrl);
await page.waitForLoadState("domcontentloaded");
test("the editor renders shared code and updates the isolated example", async ({
page,
}) => {
await page.goto(`/sandbox/index.html?code=${example}`);
const wrapper = renderedExample(page);
await expect(wrapper.getByRole("button")).toBeVisible();
expect(await wrapper.evaluate(() => window.origin)).toBe("null");
const frameLocator = page.frameLocator('iframe[src*="sandbox"]');
const sandboxWrapper = frameLocator.locator("#sandbox-wrapper");
await page.locator(".CodeMirror-code").first().click();
await page.keyboard.press("ControlOrMeta+a");
await page.keyboard.insertText("<Button>Updated example</Button>");
await expect(
wrapper.getByRole("button", { name: "Updated example" }),
).toBeVisible();
});
await expect(sandboxWrapper).toBeVisible({ timeout: 2000 });
await expect(sandboxWrapper).not.toBeEmpty();
test("a shared preview renders in the host's sandboxed iframe", async ({
page,
}) => {
await page.goto(`/sandbox/preview/index.html?code=${example}`);
const host = page.frameLocator("iframe");
await expect(host.getByTitle("Example")).toHaveAttribute(
"sandbox",
"allow-scripts",
);
const wrapper = renderedExample(page);
await expect(wrapper.getByRole("button")).toBeVisible();
expect(await wrapper.evaluate(() => window.origin)).toBe("null");
});
test("a direct visit to the renderer is also isolated", async ({ page }) => {
await page.goto("/sandbox/frame.html?code=42");
await expect(page.locator("#sandbox-wrapper")).toHaveText("42");
expect(await page.evaluate(() => window.origin)).toBe("null");
});
test("the renderer refuses to run examples if its CSP is missing", async ({
page,
}) => {
await page.route("**/sandbox/frame.html?*", async (route) => {
const response = await route.fetch();
const headers = response.headers();
delete headers["content-security-policy"];
await route.fulfill({ response, headers });
});
await page.goto("/sandbox/frame.html?code=42");
await expect(
page.getByText("Cannot render this example outside an isolated sandbox."),
).toBeVisible();
await expect(page.locator("#sandbox-wrapper")).toHaveCount(0);
});
});
+21 -2
View File
@@ -24,7 +24,7 @@ const cspHeader = `
img-src 'self' blob: data: cdn.sanity.io ${dekoratorUrl} https://avatars.githubusercontent.com data: ${cdnUrl};
connect-src 'self' ${dekoratorUrl} ${cdnUrl} ${tempChromaticRedirect} https://raw.githubusercontent.com/navikt/ https://hnbe3yhs.apicdn.sanity.io wss://hnbe3yhs.api.sanity.io cdn.sanity.io https://sanity-cdn.com *.api.sanity.io https://reops-event-proxy.ekstern.dev.nav.no https://reops-event-proxy.nav.no https://login.nav.no https://main--66b4b3beb91603ed0ab5c45e.chromatic.com;
${isProduction ? "upgrade-insecure-requests;" : ""}
`;
`.replace(/\n/g, "");
const securityHeaders = [
{
@@ -49,7 +49,7 @@ const securityHeaders = [
},
{
key: "Content-Security-Policy",
value: cspHeader.replace(/\n/g, ""),
value: cspHeader,
},
];
@@ -77,6 +77,25 @@ const nextConfig: NextConfig = {
source: "/:path*",
headers: securityHeaders,
},
{
source: "/sandbox/:path*",
headers: [
{
key: "Content-Security-Policy",
value: `${cspHeader}, script-src 'self'`,
},
],
},
{
// Only the renderer evaluates examples. Isolate it even when opened directly.
source: "/sandbox/frame.html",
headers: [
{
key: "Content-Security-Policy",
value: `${cspHeader}, sandbox allow-scripts; script-src 'self' 'unsafe-eval'; connect-src 'none'; frame-src 'none'; form-action 'none'`,
},
],
},
];
},
redirects: async () => {
+2 -1
View File
@@ -4,7 +4,8 @@
"version": "0.1.0",
"scripts": {
"start": "yarn build:config && yarn sync-imports && playroom start",
"build:playroom": "yarn build:config && yarn sync-imports && playroom build",
"build:playroom": "yarn build:config && yarn sync-imports && playroom build && yarn copy:frame-host",
"copy:frame-host": "node -e \"require('node:fs').cpSync('public', 'dist/sandbox', { recursive: true })\"",
"build:config": "tsc --project ./tsconfig.json",
"sync-imports": "tsx --tsconfig ./scripts/tsconfig.json ./scripts/generate-imports.ts"
},
-1
View File
@@ -20,7 +20,6 @@ module.exports = {
frameComponent: path.resolve("./src/FrameComponent.tsx"),
openBrowser: false,
paramType: "search", // default is 'hash'
iframeSandbox: "allow-scripts allow-same-origin allow-modals allow-forms",
exampleCode: `
<GlobalAlert status="success">
<GlobalAlert.Header>
+21
View File
@@ -0,0 +1,21 @@
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Playroom example</title>
<style>
iframe {
position: fixed;
inset: 0;
width: 100%;
height: 100%;
border: 0;
}
</style>
<script defer src="./frame-host.js"></script>
</head>
<body>
<iframe title="Example" sandbox="allow-scripts"></iframe>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
const renderer = document.querySelector("iframe");
function updateExample() {
// Only the fragment comes from Playroom. The destination is always our renderer.
renderer.contentWindow.location.replace(
`./frame.html${window.location.hash}`,
);
}
window.addEventListener("hashchange", updateExample);
updateExample();
+21
View File
@@ -1,3 +1,4 @@
import type { FrameSettingsValues } from "playroom";
import * as React from "react";
import "@navikt/ds-css";
import { Theme } from "@navikt/ds-react/Theme";
@@ -9,6 +10,11 @@ const FrameComponent = ({
children: React.ReactNode;
theme: "light" | "dark";
}) => {
// Fail closed if this static file is served without its sandbox policy.
if (window.origin !== "null") {
return <p>Cannot render this example outside an isolated sandbox.</p>;
}
return (
<Theme theme={theme} asChild>
<div id="sandbox-wrapper" style={{ minHeight: "100vh" }}>
@@ -18,4 +24,19 @@ const FrameComponent = ({
);
};
FrameComponent.frameSrc = ({
code,
themeName,
frameSettings,
}: {
code: string;
themeName?: string;
frameSettings?: FrameSettingsValues;
}) => {
const params = new URLSearchParams({ code });
if (themeName) params.set("themeName", themeName);
if (frameSettings) params.set("frameSettings", JSON.stringify(frameSettings));
return `./frame-host.html#?${params}`;
};
export default FrameComponent;
+1
View File
@@ -56,6 +56,7 @@ export default defineConfig({
],
test: {
name: "storybook",
setupFiles: ["./.storybook/vitest.setup.ts"],
browser: {
enabled: true,
headless: true,