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

[WIP] Polaris tokens base/variant themes #9877

Draft
wants to merge 15 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion polaris-react/.storybook/preview.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,11 @@ import enTranslations from '../locales/en.json';
import {GridOverlay} from './GridOverlay';
import {RenderPerformanceProfiler} from './RenderPerformanceProfiler';
import {gridOptions, featureFlagOptions} from './manager';
import {breakpoints} from '@shopify/polaris-tokens';
import {
breakpoints,
themeNameDefault,
themeNames,
} from '@shopify/polaris-tokens';

function StrictModeDecorator(Story, context) {
const {strictMode} = context.globals;
Expand All @@ -22,12 +26,14 @@ function AppProviderDecorator(Story, context) {
const {
polarisSummerEditions2023,
polarisSummerEditions2023ShadowBevelOptOut,
theme,
} = context.globals;

if (context.args.omitAppProvider) return <Story {...context} />;

return (
<AppProvider
theme={theme}
features={{
polarisSummerEditions2023:
process.env.STORYBOOK_SE23 === 'on'
Expand Down Expand Up @@ -129,6 +135,16 @@ export const globalTypes = {
],
},
},
theme: {
description: 'Global theme for components',
defaultValue: themeNameDefault,
toolbar: {
title: 'Theme',
icon: 'circlehollow',
items: themeNames,
dynamicTitle: true,
},
},
...featureFlagOptions,
...gridOptions,
};
Expand Down
6 changes: 5 additions & 1 deletion polaris-react/playground/Playground.tsx
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import React from 'react';

import {Page} from '../src';
import {Page, useThemeVars} from '../src';

export function Playground() {
const themeVars = useThemeVars();

console.log('themeVars:', themeVars);

return (
<Page title="Playground">
{/* Add the code you want to test in here */}
Expand Down
59 changes: 40 additions & 19 deletions polaris-react/src/components/AppProvider/AppProvider.tsx
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
import React, {Component} from 'react';
import type {ThemeName} from '@shopify/polaris-tokens';
import {
themeNames,
themeNameDefault,
createThemeClassName,
} from '@shopify/polaris-tokens';

import {EphemeralPresenceManager} from '../EphemeralPresenceManager';
import {MediaQueryProvider} from '../MediaQueryProvider';
import {FocusManager} from '../FocusManager';
import {PortalsManager} from '../PortalsManager';
import {I18n, I18nContext} from '../../utilities/i18n';
import {ThemeNameContext} from '../../utilities/use-theme-name';
import {
ScrollLockManager,
ScrollLockManagerContext,
Expand All @@ -31,6 +38,7 @@ interface State {
}

export interface AppProviderProps {
theme?: ThemeName;
/** A locale object or array of locale objects that overrides default translations. If specifying an array then your primary language dictionary should come first, followed by your fallback language dictionaries */
i18n: ConstructorParameters<typeof I18n>[0];
/** A custom component to use for all links used by Polaris components */
Expand Down Expand Up @@ -92,6 +100,14 @@ export class AppProvider extends Component<AppProviderProps, State> {

setRootAttributes = () => {
const features = this.getFeatures();
const theme = this.getTheme();

themeNames.forEach((themeName) => {
document.documentElement.classList.toggle(
createThemeClassName(themeName),
theme === themeName,
);
});

document.documentElement.classList.toggle(
classNamePolarisSummerEditions2023,
Expand All @@ -104,6 +120,8 @@ export class AppProvider extends Component<AppProviderProps, State> {
);
};

getTheme = () => this.props.theme ?? themeNameDefault;

getFeatures = () => {
const {features} = this.props;

Expand All @@ -118,29 +136,32 @@ export class AppProvider extends Component<AppProviderProps, State> {
render() {
const {children} = this.props;
const features = this.getFeatures();
const theme = this.getTheme();

const {intl, link} = this.state;

return (
<FeaturesContext.Provider value={features}>
<I18nContext.Provider value={intl}>
<ScrollLockManagerContext.Provider value={this.scrollLockManager}>
<StickyManagerContext.Provider value={this.stickyManager}>
<LinkContext.Provider value={link}>
<MediaQueryProvider>
<PortalsManager>
<FocusManager>
<EphemeralPresenceManager>
{children}
</EphemeralPresenceManager>
</FocusManager>
</PortalsManager>
</MediaQueryProvider>
</LinkContext.Provider>
</StickyManagerContext.Provider>
</ScrollLockManagerContext.Provider>
</I18nContext.Provider>
</FeaturesContext.Provider>
<ThemeNameContext.Provider value={theme}>
<FeaturesContext.Provider value={features}>
<I18nContext.Provider value={intl}>
<ScrollLockManagerContext.Provider value={this.scrollLockManager}>
<StickyManagerContext.Provider value={this.stickyManager}>
<LinkContext.Provider value={link}>
<MediaQueryProvider>
<PortalsManager>
<FocusManager>
<EphemeralPresenceManager>
{children}
</EphemeralPresenceManager>
</FocusManager>
</PortalsManager>
</MediaQueryProvider>
</LinkContext.Provider>
</StickyManagerContext.Provider>
</ScrollLockManagerContext.Provider>
</I18nContext.Provider>
</FeaturesContext.Provider>
</ThemeNameContext.Provider>
);
}
}
3 changes: 3 additions & 0 deletions polaris-react/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import './configure';

export {themeVars} from '@shopify/polaris-tokens';

// Key is an enum, not a type. It probably shouldn't live in a file called types
export {Key} from './types';

Expand Down Expand Up @@ -422,6 +424,7 @@ export {

export {ScrollLockManagerContext as _SECRET_INTERNAL_SCROLL_LOCK_MANAGER_CONTEXT} from './utilities/scroll-lock-manager';
export {WithinContentContext as _SECRET_INTERNAL_WITHIN_CONTENT_CONTEXT} from './utilities/within-content-context';
export {useThemeVarDecl} from './utilities/use-theme-var-decl';
export {useEventListener} from './utilities/use-event-listener';
export {useIndexResourceState} from './utilities/use-index-resource-state';
export {
Expand Down
94 changes: 94 additions & 0 deletions polaris-react/src/utilities/use-css-decl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import {useReducer} from 'react';

import {useIsomorphicLayoutEffect} from './use-isomorphic-layout-effect';

export type CSSDeclAction =
| {
type: 'updated';
declValue: string;
element: Element;
}
| {
type: 'errored';
error: string;
};

export interface CSSDeclState {
prop: string;
value: string;
element: Element | null;
status: 'init' | 'success' | 'error';
error: string | undefined;
}

function cssDeclReducer(
state: CSSDeclState,
action: CSSDeclAction,
): CSSDeclState {
switch (action.type) {
case 'updated':
return {
...state,
status: 'success',
value: action.declValue.trim(),
element: action.element,
error: undefined,
};
case 'errored':
return {
...state,
status: 'error',
value: '',
element: null,
error: action.error,
};
default:
return state;
}
}

// Derived from https://github.com/JCofman/react-use-css-custom-property/blob/73e89aac1260ec9e120c8b259975cb95735c1171/src/index.tsx#L74
export function useCSSDecl(
declProp: string,
selectors = ':root',
): CSSDeclState {
const [state, dispatch] = useReducer(cssDeclReducer, {
status: 'init',
prop: declProp,
value: '',
element: null,
error: undefined,
});

useIsomorphicLayoutEffect(() => {
const element = document.querySelector(selectors);

if (!element) {
dispatch({
type: 'errored',
error: `No element matching ${selectors}`,
});
return;
}

const declValue = window
.getComputedStyle(element)
.getPropertyValue(declProp);

if (!declValue) {
dispatch({
type: 'errored',
error: `No CSS declaration value for ${declProp} on ${selectors}`,
});
return;
}

dispatch({
type: 'updated',
declValue,
element,
});
}, [declProp, selectors]);

return state;
}
17 changes: 17 additions & 0 deletions polaris-react/src/utilities/use-theme-name.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type {ThemeName} from '@shopify/polaris-tokens';
import {themeNameDefault} from '@shopify/polaris-tokens';
import {createContext, useContext} from 'react';

export const ThemeNameContext = createContext<ThemeName>(themeNameDefault);

export function useThemeName() {
const themeName = useContext(ThemeNameContext);

if (!themeName) {
throw new Error(
'No themeName was provided. Your application must be wrapped in an <AppProvider> component. See https://polaris.shopify.com/components/app-provider for implementation instructions.',
);
}

return themeName;
}
14 changes: 14 additions & 0 deletions polaris-react/src/utilities/use-theme-var-decl.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type {ThemeVarName} from '@shopify/polaris-tokens';
import {createThemeSelector, themeNameDefault} from '@shopify/polaris-tokens';

import {useCSSDecl} from './use-css-decl';
import {useThemeName} from './use-theme-name';

export function useThemeVarDecl(themeVarName: ThemeVarName) {
const themeName = useThemeName();

return useCSSDecl(
themeVarName,
themeName === themeNameDefault ? ':root' : createThemeSelector(themeName),
);
}
13 changes: 12 additions & 1 deletion polaris-tokens/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,11 @@
"import": "./dist/esm/build/index.mjs",
"require": "./dist/cjs/build/index.js"
},
"./themes": {
"types": "./dist/types/build/themes.d.ts",
"import": "./dist/esm/build/themes.mjs",
"require": "./dist/cjs/build/themes.js"
},
"./json/*": "./dist/json/*",
"./css/*": "./dist/css/*",
"./scss/*": "./dist/scss/*"
Expand Down Expand Up @@ -55,5 +60,11 @@
],
"files": [
"dist"
]
],
"dependencies": {
"deepmerge": "^4.3.1"
},
"devDependencies": {
"change-case": "^4.1.2"
}
}
2 changes: 1 addition & 1 deletion polaris-tokens/rollup.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const extensions = ['.js', '.jsx', '.ts', '.tsx'];

/** @type {import('rollup').RollupOptions} */
export default {
input: 'build/index.ts',
input: ['build/index.ts', 'build/themes.ts'],
output: [
{
format: /** @type {const} */ ('cjs'),
Expand Down
12 changes: 6 additions & 6 deletions polaris-tokens/scripts/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import {metadata} from '../src';
import {themes, themesPartials} from '../src/themes';

import {toTokenValues} from './toTokenValues';
import {toValues} from './toValues';
import {toJSON} from './toJSON';
import {toMediaConditions} from './toMediaConditions';
import {toStyleSheet} from './toStyleSheet';

(async () => {
await Promise.all([
toTokenValues(metadata),
toJSON(metadata),
toMediaConditions(metadata.breakpoints),
toStyleSheet(metadata),
toValues(themes),
toJSON(themes),
toMediaConditions(themes.light.breakpoints),
toStyleSheet(themes, themesPartials),
]);
})();
Loading
Loading