An open source design system that's fully customizable and agent ready
TypeScript
feat: add example-nextjs-source with split-layer StyleX plugin (#1421)
Cindy Zhang6f40bcc221f9
diff --git a/apps/example-nextjs-source/.gitignore b/apps/example-nextjs-source/.gitignorenew file mode 100644index 0000000000..a680367ef5--- /dev/null+++ b/apps/example-nextjs-source/.gitignore@@ -0,0 +1 @@+.nextdiff --git a/apps/example-nextjs-source/babel.config.js b/apps/example-nextjs-source/babel.config.jsnew file mode 100644index 0000000000..5e5a440054--- /dev/null+++ b/apps/example-nextjs-source/babel.config.js@@ -0,0 +1,27 @@+/* global module, process, __dirname, require */+// eslint-disable-next-line @typescript-eslint/no-require-imports+const path = require('path');++const dev = process.env.NODE_ENV !== 'production';++module.exports = {+ presets: ['next/babel'],+ plugins: [+ [+ '@stylexjs/babel-plugin',+ {+ dev,+ runtimeInjection: false,+ enableInlinedConditionalMerge: true,+ treeshakeCompensation: true,+ aliases: {+ '@xds/core/*': [path.join(__dirname, 'node_modules/@xds/core/*')],+ '@xds/core': [path.join(__dirname, 'node_modules/@xds/core')],+ },+ unstable_moduleResolution: {+ type: 'commonJS',+ },+ },+ ],+ ],+};diff --git a/apps/example-nextjs-source/next.config.mjs b/apps/example-nextjs-source/next.config.mjsnew file mode 100644index 0000000000..c616176c79--- /dev/null+++ b/apps/example-nextjs-source/next.config.mjs@@ -0,0 +1,6 @@+/** @type {import('next').NextConfig} */+const nextConfig = {+ transpilePackages: ['@xds/core', '@xds/theme-default'],+};++export default nextConfig;diff --git a/apps/example-nextjs-source/package.json b/apps/example-nextjs-source/package.jsonnew file mode 100644index 0000000000..28c4d7775e--- /dev/null+++ b/apps/example-nextjs-source/package.json@@ -0,0 +1,32 @@+{+ "name": "@xds/example-nextjs-source",+ "version": "0.0.1",+ "private": true,+ "scripts": {+ "dev": "next dev",+ "build": "next build",+ "start": "next start"+ },+ "dependencies": {+ "@stylexjs/stylex": "^0.18.2",+ "@xds/core": "*",+ "@xds/theme-default": "*",+ "next": "^15.5.15",+ "react": "^19.2.5",+ "react-dom": "^19.2.5"+ },+ "devDependencies": {+ "@stylexjs/babel-plugin": "^0.18.2",+ "@stylexjs/postcss-plugin": "^0.18.2",+ "@babel/preset-react": "^7.25.0",+ "@babel/preset-typescript": "^7.25.0",+ "@types/react": "^19.2.14",+ "@types/react-dom": "^19.2.3",+ "autoprefixer": "^10.4.0",+ "typescript": "^5.7.0",+ "@xds/postcss-plugin": "*"+ },+ "browserslist": [+ "last 1 Chrome version"+ ]+}diff --git a/apps/example-nextjs-source/postcss.config.js b/apps/example-nextjs-source/postcss.config.jsnew file mode 100644index 0000000000..5d19c6ed63--- /dev/null+++ b/apps/example-nextjs-source/postcss.config.js@@ -0,0 +1,13 @@+/* global module, require */+// eslint-disable-next-line @typescript-eslint/no-require-imports+const babelConfig = require('./babel.config');++module.exports = {+ plugins: {+ '@xds/postcss-plugin': {+ appDir: 'src',+ babelPlugins: babelConfig.plugins,+ },+ autoprefixer: {},+ },+};diff --git a/apps/example-nextjs-source/src/app/globals.css b/apps/example-nextjs-source/src/app/globals.cssnew file mode 100644index 0000000000..f62e74dddd--- /dev/null+++ b/apps/example-nextjs-source/src/app/globals.css@@ -0,0 +1,5 @@+@import "./layers.css";+@import "@xds/core/reset.css";+@import "@xds/theme-default/theme.css";++@stylex;diff --git a/apps/example-nextjs-source/src/app/layers.css b/apps/example-nextjs-source/src/app/layers.cssnew file mode 100644index 0000000000..3399fb4f5c--- /dev/null+++ b/apps/example-nextjs-source/src/app/layers.css@@ -0,0 +1,5 @@+/* Layer order declaration — must be the first CSS in the bundle.+ Separate file because webpack hoists @import content above inline+ CSS, so an inline @layer statement in globals.css would appear+ after reset.css and theme.css content in the output. */+@layer reset, xds-base, xds-theme, product;diff --git a/apps/example-nextjs-source/src/app/layout.tsx b/apps/example-nextjs-source/src/app/layout.tsxnew file mode 100644index 0000000000..376f5ba1a2--- /dev/null+++ b/apps/example-nextjs-source/src/app/layout.tsx@@ -0,0 +1,18 @@+import type {Metadata} from 'next';+import './globals.css';+import {Providers} from './providers';++export const metadata: Metadata = {+ title: 'XDS Example — Next.js (Source)',+ description: 'Reference example compiling @xds/core from source with StyleX',+};++export default function RootLayout({children}: {children: React.ReactNode}) {+ return (+ <html lang="en">+ <body>+ <Providers>{children}</Providers>+ </body>+ </html>+ );+}diff --git a/apps/example-nextjs-source/src/app/page.tsx b/apps/example-nextjs-source/src/app/page.tsxnew file mode 100644index 0000000000..05e55a96e8--- /dev/null+++ b/apps/example-nextjs-source/src/app/page.tsx@@ -0,0 +1,209 @@+'use client';++import {useState} from 'react';+import * as stylex from '@stylexjs/stylex';+import {XDSVStack, XDSHStack} from '@xds/core/Layout';+import {XDSButton} from '@xds/core/Button';+import {XDSText, XDSHeading} from '@xds/core/Text';+import {XDSTextInput} from '@xds/core/TextInput';+import {XDSBadge} from '@xds/core/Badge';+import {XDSDivider} from '@xds/core';++const styles = stylex.create({+ main: {+ display: 'flex',+ alignItems: 'center',+ justifyContent: 'center',+ minHeight: '100vh',+ padding: '2rem',+ },+ container: {+ maxWidth: 640,+ width: '100%',+ },+ card: {+ borderRadius: 8,+ border: '1px solid var(--color-border)',+ padding: '1rem',+ backgroundColor: 'var(--color-background-body)',+ },+ layerDemo: {+ padding: '1.5rem',+ borderRadius: 12,+ backgroundColor: 'var(--color-background-secondary)',+ },+ customButton: {+ borderRadius: 999,+ },+ wideButton: {+ width: '100%',+ },+ brandSecondary: {+ backgroundColor: 'mediumseagreen',+ color: 'white',+ },+});++export default function Home() {+ const [email, setEmail] = useState('');++ return (+ <main {...stylex.props(styles.main)}>+ <div {...stylex.props(styles.container)}>+ <XDSVStack gap={6}>+ <XDSVStack gap={2}>+ <XDSHeading level={1}>XDS + Next.js (Source Build)</XDSHeading>+ <XDSText type="body" color="secondary">+ This example compiles{' '}+ <XDSText type="body" weight="bold">+ @xds/core+ </XDSText>{' '}+ from raw TypeScript + StyleX source. Both XDS component styles and+ product styles are compiled together at build time — fully+ tree-shaken, zero unused CSS.+ </XDSText>+ </XDSVStack>++ <XDSDivider />++ {/* Layer Demo */}+ <XDSVStack gap={3}>+ <XDSHeading level={2}>Layer Demo</XDSHeading>+ <XDSText type="body" color="secondary">+ Product StyleX styles override XDS component defaults via CSS+ layer ordering. No <code>!important</code> needed — the{' '}+ <code>product</code> layer sits above <code>xds-base</code> in the+ cascade.+ </XDSText>++ <div {...stylex.props(styles.layerDemo)}>+ <XDSVStack gap={3}>+ <XDSVStack gap={1}>+ <XDSText type="supporting" weight="bold">+ Default XDS buttons (xds-base layer)+ </XDSText>+ <XDSHStack gap={3} vAlign="center">+ <XDSButton label="Default" variant="primary" />+ <XDSButton label="Default" variant="secondary" />+ </XDSHStack>+ </XDSVStack>++ <XDSVStack gap={1}>+ <XDSText type="supporting" weight="bold">+ Product-styled buttons (product layer overrides)+ </XDSText>+ <XDSHStack gap={3} vAlign="center">+ <XDSButton+ label="Pill shape"+ variant="primary"+ xstyle={styles.customButton}+ />+ <XDSButton+ label="Pill shape"+ variant="secondary"+ xstyle={styles.customButton}+ />+ </XDSHStack>+ </XDSVStack>++ <XDSVStack gap={1}>+ <XDSText type="supporting" weight="bold">+ Three-layer cascade: base → theme → product+ </XDSText>+ <XDSText type="supporting" color="secondary">+ The secondary button's background goes through three layers:+ XDS base sets the default, the theme overrides it with a+ brand tint, and product code overrides again with green.+ </XDSText>+ <XDSHStack gap={3} vAlign="center">+ <XDSButton label="Theme color" variant="secondary" />+ <XDSButton+ label="Product override"+ variant="secondary"+ xstyle={styles.brandSecondary}+ />+ </XDSHStack>+ </XDSVStack>++ <XDSVStack gap={1}>+ <XDSText type="supporting" weight="bold">+ Full-width product override+ </XDSText>+ <XDSButton+ label="Full width button"+ variant="primary"+ xstyle={styles.wideButton}+ />+ </XDSVStack>+ </XDSVStack>+ </div>+ </XDSVStack>++ <XDSDivider />++ {/* Standard components */}+ <XDSVStack gap={3}>+ <XDSHeading level={2}>Components</XDSHeading>+ <XDSHStack gap={3} vAlign="center">+ <XDSButton label="Primary" variant="primary" />+ <XDSButton label="Secondary" variant="secondary" />+ <XDSButton label="Ghost" variant="ghost" />+ </XDSHStack>+ </XDSVStack>++ <XDSDivider />++ <XDSVStack gap={3}>+ <XDSHeading level={2}>Badges</XDSHeading>+ <XDSHStack gap={3} vAlign="center">+ <XDSBadge variant="info" label="Info" />+ <XDSBadge variant="success" label="Success" />+ <XDSBadge variant="warning" label="Warning" />+ <XDSBadge variant="error" label="Error" />+ </XDSHStack>+ </XDSVStack>++ <XDSDivider />++ <XDSVStack gap={3}>+ <XDSHeading level={2}>Text Input</XDSHeading>+ <XDSTextInput+ label="Email address"+ placeholder="[email protected]"+ value={email}+ onChange={setEmail}+ />+ </XDSVStack>++ <XDSDivider />++ <XDSVStack gap={3}>+ <XDSHeading level={2}>Typography</XDSHeading>+ <XDSText type="large" weight="bold">+ Large bold text+ </XDSText>+ <XDSText type="body">Default body text</XDSText>+ <XDSText type="supporting" color="secondary">+ Supporting text in secondary color+ </XDSText>+ </XDSVStack>++ <XDSDivider />++ <XDSVStack gap={3}>+ <XDSHeading level={2}>Source Build</XDSHeading>+ <div {...stylex.props(styles.card)}>+ <XDSText type="body">+ Open devtools → inspect the CSS. You'll see separate{' '}+ <code>@layer xds-base</code> and <code>@layer product</code>{' '}+ blocks. The layer order{' '}+ <code>reset < xds-base < xds-theme < product</code>{' '}+ ensures product styles always win without specificity hacks.+ </XDSText>+ </div>+ </XDSVStack>+ </XDSVStack>+ </div>+ </main>+ );+}diff --git a/apps/example-nextjs-source/src/app/providers.tsx b/apps/example-nextjs-source/src/app/providers.tsxnew file mode 100644index 0000000000..ac36e5e29f--- /dev/null+++ b/apps/example-nextjs-source/src/app/providers.tsx@@ -0,0 +1,14 @@+'use client';++import Link from 'next/link';+import {XDSTheme} from '@xds/core/theme';+import {XDSLinkProvider} from '@xds/core/Link';+import {defaultTheme} from '@xds/theme-default';++export function Providers({children}: {children: React.ReactNode}) {+ return (+ <XDSTheme theme={defaultTheme}>+ <XDSLinkProvider component={Link}>{children}</XDSLinkProvider>+ </XDSTheme>+ );+}diff --git a/apps/example-nextjs-source/tsconfig.json b/apps/example-nextjs-source/tsconfig.jsonnew file mode 100644index 0000000000..d2bba220e4--- /dev/null+++ b/apps/example-nextjs-source/tsconfig.json@@ -0,0 +1,40 @@+{+ "compilerOptions": {+ "target": "ES2017",+ "lib": [+ "dom",+ "dom.iterable",+ "esnext"+ ],+ "allowJs": true,+ "skipLibCheck": true,+ "strict": true,+ "noEmit": true,+ "esModuleInterop": true,+ "module": "esnext",+ "moduleResolution": "bundler",+ "resolveJsonModule": true,+ "isolatedModules": true,+ "jsx": "preserve",+ "incremental": true,+ "plugins": [+ {+ "name": "next"+ }+ ],+ "paths": {+ "@/*": [+ "./src/*"+ ]+ }+ },+ "include": [+ "next-env.d.ts",+ "**/*.ts",+ "**/*.tsx",+ ".next/types/**/*.ts"+ ],+ "exclude": [+ "node_modules"+ ]+}diff --git a/eslint.config.js b/eslint.config.jsindex e69a8df605..a150fc48aa 100644--- a/eslint.config.js+++ b/eslint.config.js@@ -34,7 +34,9 @@ export default tseslint.config("**/*.test-violations.tsx","apps/example-nextjs/*.js","apps/example-nextjs/next-env.d.ts",+ "apps/example-nextjs-source/*.js","apps/sandbox/*.js",+ "packages/postcss-plugin/**",],},{diff --git a/packages/postcss-plugin/package.json b/packages/postcss-plugin/package.jsonnew file mode 100644index 0000000000..76f69389e0--- /dev/null+++ b/packages/postcss-plugin/package.json@@ -0,0 +1,29 @@+{+ "name": "@xds/postcss-plugin",+ "version": "0.0.1",+ "description": "PostCSS plugin for XDS source builds \u2014 splits StyleX output into library and product CSS layers",+ "license": "MIT",+ "main": "src/index.js",+ "exports": {+ ".": "./src/index.js"+ },+ "files": [+ "src"+ ],+ "keywords": [+ "xds",+ "postcss",+ "stylex",+ "css-layers",+ "design-system"+ ],+ "peerDependencies": {+ "@stylexjs/babel-plugin": ">=0.18.0",+ "@babel/core": ">=7.0.0"+ },+ "dependencies": {+ "fast-glob": "^3.3.0",+ "glob-parent": "^6.0.0",+ "is-glob": "^4.0.0"+ }+}diff --git a/packages/postcss-plugin/src/index.js b/packages/postcss-plugin/src/index.jsnew file mode 100644index 0000000000..d4cd8b5367--- /dev/null+++ b/packages/postcss-plugin/src/index.js@@ -0,0 +1,254 @@+"use strict";++/**+ * @xds/postcss-plugin+ *+ * PostCSS plugin for XDS source builds. Compiles StyleX from both+ * XDS library source and product code, then splits the output into+ * separate named CSS layers:+ *+ * reset < xds-base (library styles) < xds-theme < product (app styles)+ *+ * Usage:+ * // postcss.config.js+ * const babelConfig = require('./babel.config');+ *+ * module.exports = {+ * plugins: {+ * '@xds/postcss-plugin': {+ * appDir: 'src',+ * babelPlugins: babelConfig.plugins,+ * },+ * },+ * };+ */++const path = require('node:path');+const fs = require('node:fs');+const postcss = require('postcss');+const babel = require('@babel/core');+const stylexBabelPlugin = require('@stylexjs/babel-plugin');+const {globSync} = require('fast-glob');+const isGlob = require('is-glob');+const globParent = require('glob-parent');++const PLUGIN_NAME = '@xds/postcss-plugin';++// XDS-specific defaults — the user shouldn't need to specify these+const XDS_LIBRARY_GLOB = 'node_modules/@xds/**/*.{ts,tsx}';+const XDS_LIBRARY_PATTERN = 'node_modules/@xds/';+const STYLEX_IMPORT_SOURCE = '@stylexjs/stylex';++function parseDependency(fileOrGlob, cwd) {+ if (fileOrGlob.startsWith('!')) return null;+ if (isGlob(fileOrGlob)) {+ const base = globParent(fileOrGlob);+ let glob = fileOrGlob.substring(base === '.' ? 0 : base.length);+ if (glob.charAt(0) === '/') glob = glob.substring(1);+ return {+ type: 'dir-dependency',+ dir: path.normalize(path.resolve(cwd, base)),+ glob,+ };+ }+ return {+ type: 'dependency',+ file: path.normalize(path.resolve(cwd, fileOrGlob)),+ };+}++function createPlugin() {+ const isDev = process.env.NODE_ENV === 'development';++ // Persists across rebuilds for watch mode+ const styleXRulesMap = new Map();+ const fileModifiedMap = new Map();++ const plugin = ({+ cwd = process.cwd(),++ // --- User-facing options ---++ // Directory containing your app source (default: 'src')+ appDir = 'src',++ // StyleX babel plugins from your babel.config.js+ babelPlugins = [],++ // Layer names (override if you need different names)+ layers = {+ library: 'xds-base',+ product: 'product',+ },++ // --- Advanced options (rarely needed) ---++ // Additional include globs beyond appDir and @xds packages+ extraInclude = [],++ // Exclude globs+ exclude = [],+ }) => {+ // Build the include list: app code + all @xds packages+ const include = [+ `${appDir}/**/*.{js,jsx,ts,tsx}`,+ XDS_LIBRARY_GLOB,+ ...extraInclude,+ ];++ const excludeWithDefaults = ['**/*.d.ts', '**/*.flow', ...exclude];++ // Build babel config from the user's plugins+ const babelConfig = {+ babelrc: false,+ parserOpts: {+ plugins: ['typescript', 'jsx'],+ },+ plugins: babelPlugins,+ };++ let shouldSkipTransformError = false;++ return {+ postcssPlugin: PLUGIN_NAME,+ plugins: [+ async function (root, result) {+ const fileName = result.opts.from;++ // Find @stylex at-rule+ let styleXAtRule = null;+ root.walkAtRules((atRule) => {+ if (atRule.name === 'stylex' && !atRule.params) {+ styleXAtRule = atRule;+ }+ });+ if (styleXAtRule == null) return;++ // Discover files+ const files = new Set();+ for (const pattern of include) {+ const matched = globSync(pattern, {+ onlyFiles: true,+ ignore: excludeWithDefaults,+ cwd,+ });+ for (const f of matched) {+ files.add(path.normalize(path.resolve(cwd, f)));+ }+ }++ // Watch dependencies+ for (const pattern of include) {+ const dep = parseDependency(pattern, cwd);+ if (dep) {+ result.messages.push({+ plugin: PLUGIN_NAME,+ parent: fileName,+ ...dep,+ });+ }+ }++ // Remove deleted files+ for (const f of fileModifiedMap.keys()) {+ if (!files.has(f)) {+ fileModifiedMap.delete(f);+ styleXRulesMap.delete(f);+ }+ }++ // Transform changed files+ const transforms = [];+ for (const filePath of files) {+ const mtimeMs = fs.existsSync(filePath)+ ? fs.statSync(filePath).mtimeMs+ : -Infinity;+ if (+ fileModifiedMap.has(filePath) &&+ mtimeMs === fileModifiedMap.get(filePath)+ ) {+ continue;+ }+ fileModifiedMap.set(filePath, mtimeMs);++ const contents = fs.readFileSync(filePath, 'utf-8');++ // Quick check: does this file import stylex?+ if (!contents.includes(STYLEX_IMPORT_SOURCE)) continue;++ transforms.push(+ babel+ .transformAsync(contents, {+ filename: filePath,+ caller: {name: PLUGIN_NAME, platform: 'web', isDev},+ ...babelConfig,+ })+ .then(({metadata}) => {+ const stylex = metadata?.stylex;+ if (stylex != null && stylex.length > 0) {+ styleXRulesMap.set(filePath, stylex);+ }+ })+ .catch((error) => {+ if (shouldSkipTransformError) {+ console.warn(+ `[${PLUGIN_NAME}] Failed to transform "${filePath}": ${error.message}`,+ );+ } else {+ throw error;+ }+ }),+ );+ }+ await Promise.all(transforms);++ // Partition rules by source path+ const libraryRules = [];+ const productRules = [];+ for (const [filePath, rules] of styleXRulesMap.entries()) {+ if (filePath.includes(XDS_LIBRARY_PATTERN)) {+ libraryRules.push(...rules);+ } else {+ productRules.push(...rules);+ }+ }++ // Process each group separately+ const libraryCss = libraryRules.length+ ? stylexBabelPlugin.processStylexRules(libraryRules, {+ useLayers: true,+ })+ : '';+ const productCss = productRules.length+ ? stylexBabelPlugin.processStylexRules(productRules, {+ useLayers: true,+ })+ : '';++ // Wrap in named layers+ const parts = [];+ if (libraryCss) {+ parts.push(`@layer ${layers.library} {\n${libraryCss}\n}`);+ }+ if (productCss) {+ parts.push(`@layer ${layers.product} {\n${productCss}\n}`);+ }++ const finalCss = parts.join('\n\n');+ const parsed = await postcss.parse(finalCss, {from: fileName});+ styleXAtRule.replaceWith(parsed);+ result.root = root;++ if (!shouldSkipTransformError) {+ shouldSkipTransformError = true;+ }+ },+ ],+ };+ };++ plugin.postcss = true;+ return plugin;+}++module.exports = createPlugin();diff --git a/yarn.lock b/yarn.lockindex 974a4b3db5..9cce9de812 100644--- a/yarn.lock+++ b/yarn.lock@@ -3767,7 +3767,7 @@ fast-equals@^5.0.1:resolved "https://registry.yarnpkg.com/fast-equals/-/fast-equals-5.4.0.tgz#b60073b8764f27029598447f05773c7534ba7f1e"integrity sha512-jt2DW/aNFNwke7AUd+Z+e6pz39KO5rzdbbFCg2sGafS4mk13MI7Z8O5z9cADNn5lhGODIgLwug6TZO2ctf7kcw==-fast-glob@^3.2.9, fast-glob@^3.3.2:+fast-glob@^3.2.9, fast-glob@^3.3.0, fast-glob@^3.3.2:version "3.3.3"resolved "https://registry.npmjs.org/fast-glob/-/fast-glob-3.3.3.tgz"integrity sha512-7MptL8U0cqcFdzIzwOTHoilX9x5BrNqye7Z/LuC7kCMRio1EMSyqRK3BEAUD7sXRq4iT4AzTVuZdhgQ2TCvYLg==@@ -4003,7 +4003,7 @@ glob-parent@^5.1.2:dependencies:is-glob "^4.0.1"-glob-parent@^6.0.2:+glob-parent@^6.0.0, glob-parent@^6.0.2:version "6.0.2"resolved "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz"integrity sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==