diff --git a/core/scripts/testing/scripts.js b/core/scripts/testing/scripts.js index a2aef48ab3f..5a4fe76b06c 100644 --- a/core/scripts/testing/scripts.js +++ b/core/scripts/testing/scripts.js @@ -139,8 +139,11 @@ const DEFAULT_PALETTE = 'light'; // Store existing theme set from the app initialization const customTheme = window.Ionic?.config?.customTheme; // Load the default tokens for the theme - const themeLoaded = import(`/themes/${themeName}/default.tokens.js`).then((defaultTokens) => - buildTheme(defaultTokens.defaultTheme, customTheme, paletteName) + const themeLoaded = Promise.all([ + import(`/themes/${themeName}/default.tokens.js`), + import('/themes/utils/theme.js'), + ]).then(([defaultTokens, themeUtils]) => + buildTheme(defaultTokens.defaultTheme, customTheme, paletteName, themeUtils) ); /* @@ -224,11 +227,13 @@ const DEFAULT_PALETTE = 'light'; } // TODO(FW-6750): Determine if this function can be removed once the theme tokens can be imported directly into the test pages - function buildTheme(tokensTheme, customTheme, paletteName) { + function buildTheme(tokensTheme, customTheme, paletteName, themeUtils) { let theme = tokensTheme; - // Merge with existing theme to preserve any customizations + // Merge with existing theme to preserve any customizations. A custom + // value replaces the theme's media query values for the same key, as + // it does in the app (refer to `mergeTheme`). if (customTheme) { - theme = deepMerge(theme, customTheme); + theme = themeUtils.mergeTheme(theme, customTheme); } // If a specific palette is requested, modify the palette structure diff --git a/core/src/components/divider/_divider.docs.scss b/core/src/components/divider/_divider.docs.scss index 88b50f0a0ec..373b3d0a3a7 100644 --- a/core/src/components/divider/_divider.docs.scss +++ b/core/src/components/divider/_divider.docs.scss @@ -14,5 +14,5 @@ * @prop --ion-divider-spacing-xlarge-margin-bottom: Bottom margin of the `xlarge` divider spacing * @prop --ion-divider-spacing-xxlarge-margin-top: Top margin of the `xxlarge` divider spacing * @prop --ion-divider-spacing-xxlarge-margin-bottom: Bottom margin of the `xxlarge` divider spacing - * @prop --ion-divider-thickness: Thickness of the divider line + * @prop --ion-divider-thickness: Thickness of the divider line. The ios theme changes it with screen density, so the line stays one screen pixel thick. */ diff --git a/core/src/components/divider/divider.interface.ts b/core/src/components/divider/divider.interface.ts index aee6c0353ff..ee968075b7f 100644 --- a/core/src/components/divider/divider.interface.ts +++ b/core/src/components/divider/divider.interface.ts @@ -1,9 +1,16 @@ -import type { IonMargin } from '../../themes/themes.interfaces'; +import type { IonMargin, IonMediaQuery } from '../../themes/themes.interfaces'; export type IonDividerRecipe = { /** Color of the divider line. */ color?: string; + /** + * Thickness used inside media queries, such as a thinner line on denser screens. + * A `thickness` that a custom theme sets outside this key replaces the base + * theme's values here, so it applies on every screen. + */ + mediaQuery?: IonMediaQuery>; + /** Applies for each value of the `spacing` property, except `"none"`, which is always 0. */ spacing?: { [K in Exclude]?: { diff --git a/core/src/components/divider/divider.scss b/core/src/components/divider/divider.scss index 7d5b3ba1b1b..7cf9f9669bf 100644 --- a/core/src/components/divider/divider.scss +++ b/core/src/components/divider/divider.scss @@ -28,11 +28,13 @@ $spacings: xxsmall, xsmall, small, medium, large, xlarge, xxlarge; display: block; width: 100%; + height: var(--ion-divider-thickness); border: none; - border-top-width: var(--ion-divider-thickness); - border-top-style: solid; - border-top-color: var(--ion-divider-color); + + // A filled box instead of a border: WebKit skips a border thinner than one + // CSS pixel at some positions on the page. + background: var(--ion-divider-color); } // Divider Spacing diff --git a/core/src/components/item/test/hairlines/index.html b/core/src/components/item/test/hairlines/index.html new file mode 100644 index 00000000000..31a9eac9b03 --- /dev/null +++ b/core/src/components/item/test/hairlines/index.html @@ -0,0 +1,111 @@ + + + + + Item - Hairlines + + + + + + + + + + + + + +
+ + + Item - Hairlines + + + + + + + Item - Hairlines + + +
+

+ Check in Safari on an iPhone or the iOS simulator. With the bug, the line between two items is missing + at some scroll positions, so the items run together. +

+

+ Each tap on the Shift button moves the list down by a tenth of a pixel, so every line + lands on a new position. +

+
+ +
+
+
+ + + + Hairlines + + +
+
+ + + + diff --git a/core/src/themes/ios/default.tokens.ts b/core/src/themes/ios/default.tokens.ts index 69dae45c523..6329836d6b9 100644 --- a/core/src/themes/ios/default.tokens.ts +++ b/core/src/themes/ios/default.tokens.ts @@ -1986,6 +1986,21 @@ export const defaultTheme: DefaultTheme = { IonDivider: { color: '#e0e0e0', + // One screen pixel at each density, like native iOS separators. + mediaQuery: { + min: { + resolution: { + '2dppx': { + thickness: '0.5px', + }, + + '3dppx': { + thickness: '0.3334px', + }, + }, + }, + }, + spacing: { xxsmall: { margin: { diff --git a/core/src/themes/themes.interfaces.ts b/core/src/themes/themes.interfaces.ts index 60e9fad187d..bab58c93085 100644 --- a/core/src/themes/themes.interfaces.ts +++ b/core/src/themes/themes.interfaces.ts @@ -380,6 +380,28 @@ type Components = { IonModal?: any; }; +/** + * Values a component uses inside media queries. The path builds the query: + * `min.resolution['2dppx']` applies inside `@media (min-resolution: 2dppx)`. + * The values set the same CSS variables as the component's own. + * + * A value set by a custom theme replaces the base theme's media query values + * for that key, so it applies on every screen. + */ +export type IonMediaQuery = { + /** Applies when the screen is at least the given value. When several match, the largest wins. */ + min?: { + /** Screen density, in screen pixels per CSS pixel. */ + resolution?: { [K in IonMediaQueryResolution]?: T }; + }; +}; + +/** + * The screen densities a recipe can target. iPhones are 2x or 3x. Add a + * density when a component needs it. + */ +export type IonMediaQueryResolution = '2dppx' | '3dppx'; + export type IonMargin = { top?: string | number; end?: string | number; diff --git a/core/src/utils/test/theme.spec.ts b/core/src/utils/test/theme.spec.ts index 52205881eec..242e6f33526 100644 --- a/core/src/utils/test/theme.spec.ts +++ b/core/src/utils/test/theme.spec.ts @@ -24,6 +24,7 @@ import { getCustomTheme, hexToRgb, injectCSS, + mergeTheme, mix, overlay, } from '../theme'; @@ -1095,6 +1096,192 @@ describe('generateComponentsThemeCSS', () => { }); }); +describe('media queries', () => { + /** + * Removes whitespace and the recipe path comments, so the expected CSS + * only lists the rules. + */ + const minify = (css: string) => css.replace(/\/\*.*?\*\//g, '').replace(/\s/g, ''); + + const resolution = (dppx: string, tokens: Record) => ({ + min: { resolution: { [dppx]: tokens } }, + }); + + it('should set the same variables inside each media query', () => { + const css = generateComponentsThemeCSS({ + IonDivider: { + thickness: '1px', + mediaQuery: { + min: { + resolution: { + '2dppx': { thickness: '0.5px' }, + '3dppx': { thickness: '0.3334px' }, + }, + }, + }, + }, + }); + + const expectedCSS = ` + ion-divider { + --ion-divider-thickness: 1px; + } + @media (min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 2) { + ion-divider { + --ion-divider-thickness: 0.5px; + } + } + @media (min-resolution: 3dppx), (-webkit-min-device-pixel-ratio: 3) { + ion-divider { + --ion-divider-thickness: 0.3334px; + } + } + `; + + expect(minify(css)).toBe(minify(expectedCSS)); + }); + + it('should name the recipe path above each media query', () => { + const css = generateComponentsThemeCSS({ + IonDivider: { mediaQuery: resolution('2dppx', { thickness: '0.5px' }) }, + }); + + expect(css).toContain(`/* ion-divider: mediaQuery.min.resolution['2dppx'] */`); + }); + + it('should only add the prefixed query for dppx resolutions', () => { + const css = generateComponentsThemeCSS({ + IonDivider: { + mediaQuery: { min: { width: { '768px': { thickness: '2px' } } } }, + }, + }); + + expect(minify(css)).toBe('@media(min-width:768px){ion-divider{--ion-divider-thickness:2px;}}'); + }); + + it('should use the same selectors as the base block', () => { + const css = generateComponentsThemeCSS({ + IonBackdrop: { mediaQuery: resolution('2dppx', { opacity: '0.5' }) }, + }); + + expect(minify(css)).toContain( + 'ion-backdrop,ion-menu,ion-modal,ion-popover,ion-datetime{--ion-backdrop-opacity:0.5;}' + ); + }); + + it('should let a parent value win over the child media queries', () => { + const css = generateComponentsThemeCSS({ + IonDivider: { + thickness: '1px', + mediaQuery: resolution('2dppx', { thickness: '0.5px' }), + }, + IonItem: { + IonDivider: { thickness: '2px' }, + }, + }); + + const expectedCSS = ` + ion-divider { + --ion-divider-thickness: 1px; + } + @media (min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 2) { + ion-divider { + --ion-divider-thickness: 0.5px; + } + } + :where(ion-item) ion-divider { + --ion-divider-thickness: 2px; + } + `; + + expect(minify(css)).toBe(minify(expectedCSS)); + }); + + it('should generate the media queries a parent nests for a child', () => { + const css = generateComponentsThemeCSS({ + IonItem: { + IonDivider: { mediaQuery: resolution('2dppx', { thickness: '0.5px' }) }, + }, + }); + + expect(minify(css)).toBe( + '@media(min-resolution:2dppx),(-webkit-min-device-pixel-ratio:2){:where(ion-item)ion-divider{--ion-divider-thickness:0.5px;}}' + ); + }); + + it('should drop the base theme values a custom theme overrides', () => { + const base = { + components: { + IonDivider: { + color: 'gray', + thickness: '1px', + mediaQuery: resolution('2dppx', { color: 'black', thickness: '0.5px' }), + }, + }, + }; + + const theme = mergeTheme(base, { + components: { IonDivider: { thickness: '3px' } }, + }); + + expect(theme.components.IonDivider).toEqual({ + color: 'gray', + thickness: '3px', + mediaQuery: resolution('2dppx', { color: 'black' }), + }); + expect(base.components.IonDivider.mediaQuery.min.resolution['2dppx'].thickness).toBe('0.5px'); + }); + + it('should skip a media query with no values left', () => { + const base = { + IonDivider: { + thickness: '1px', + mediaQuery: resolution('2dppx', { thickness: '0.5px' }), + }, + }; + + const theme = mergeTheme(base, { IonDivider: { thickness: '3px' } }); + + expect(minify(generateComponentsThemeCSS(theme))).toBe('ion-divider{--ion-divider-thickness:3px;}'); + }); + + it('should drop the values a mode override replaces', () => { + const theme = getCustomTheme( + { + components: { + IonDivider: { + thickness: '1px', + mediaQuery: resolution('2dppx', { thickness: '0.5px' }), + }, + }, + ios: { components: { IonDivider: { thickness: '3px' } } }, + }, + 'ios' + ); + + expect(theme.components.IonDivider).toEqual({ + thickness: '3px', + mediaQuery: resolution('2dppx', {}), + }); + }); + + it('should keep the media query values a custom theme sets', () => { + const base = { + IonDivider: { mediaQuery: resolution('2dppx', { thickness: '0.5px' }) }, + }; + const custom = { + IonDivider: { + thickness: '3px', + mediaQuery: resolution('2dppx', { thickness: '2px' }), + }, + }; + + const theme = mergeTheme(base, custom); + + expect(theme.IonDivider.mediaQuery).toEqual(resolution('2dppx', { thickness: '2px' })); + }); +}); + describe('nested child components', () => { const isChild = (key: string) => /^Ion[A-Z]/.test(key); diff --git a/core/src/utils/theme.ts b/core/src/utils/theme.ts index 489202d855a..ab4812a3629 100644 --- a/core/src/utils/theme.ts +++ b/core/src/utils/theme.ts @@ -84,13 +84,9 @@ export const getCustomTheme = (customTheme: any, mode: string): any => { const { ios, md, ...baseCustomTheme } = customTheme; // Flatten the mode-specific overrides based on current mode - if (mode === 'ios' && ios) { - return deepMerge(baseCustomTheme, ios); - } else if (mode === 'md' && md) { - return deepMerge(baseCustomTheme, md); - } + const modeTheme = mode === 'ios' ? ios : mode === 'md' ? md : undefined; - return baseCustomTheme; + return modeTheme ? mergeTheme(baseCustomTheme, modeTheme) : baseCustomTheme; } return customTheme; @@ -430,7 +426,7 @@ export const applyGlobalTheme = (baseTheme: any, userTheme?: any): any => { } // Merge themes and apply - const mergedTheme = deepMerge(baseTheme, userTheme); + const mergedTheme = mergeTheme(baseTheme, userTheme); injectCSS(generateGlobalThemeCSS(mergedTheme)); return mergedTheme; }; @@ -760,14 +756,182 @@ const lowerSpecificity = (selector: string): string => { }; /** - * Generates one block of `---` custom properties for a list of selectors. + * Generates one block of `---` custom properties for a list of selectors, + * followed by a block inside each of its media queries (refer to `MEDIA_QUERY_KEY`). */ -const generateBlock = (selectors: string[], tokens: Record, tag: string): string => ` +const generateBlock = (selectors: string[], tokens: Record, tag: string): string => { + const { [MEDIA_QUERY_KEY]: mediaQuery, ...ownTokens } = tokens; + + const block = (blockTokens: Record) => ` ${selectors.join(',\n ')} { - ${generateCSSVars(tokens, `--${tag}-`)} + ${generateCSSVars(blockTokens, `--${tag}-`) ?? ''} } `; + /** + * Each block names the recipe path it comes from, so it can be traced back + * to the tokens from the browser's developer tools. + */ + const mediaQueryBlocks = getMediaQueries(mediaQuery).map( + ({ path, query, tokens: queryTokens }) => ` + /* ${tag}: ${path} */ + @media ${query} {${block(queryTokens)}}` + ); + + /** + * A component with only media query tokens gets no base block, but an + * empty component still gets an empty one (refer to + * `generateComponentsThemeCSS`). + */ + const ownBlock = Object.keys(ownTokens).length > 0 || mediaQueryBlocks.length === 0 ? [block(ownTokens)] : []; + + return [...ownBlock, ...mediaQueryBlocks].join(''); +}; + +/** + * The recipe key that holds the values a component uses inside media queries. + * Its path builds the query: `min.resolution['2dppx']` becomes + * `(min-resolution: 2dppx)`. The values set the same variables as the + * component's own, so unlike a state, the key is left out of the variable names: + * + * ```ts + * IonDivider: { + * thickness: '1px', + * mediaQuery: { + * min: { resolution: { '2dppx': { thickness: '0.5px' } } }, + * }, + * } + * ``` + * + * Becomes: + * + * ```css + * ion-divider { + * --ion-divider-thickness: 1px; + * } + * @media (min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 2) { + * ion-divider { + * --ion-divider-thickness: 0.5px; + * } + * } + * ``` + * + * The blocks follow the order of the keys, so when several queries match, the + * last one wins. List `min` values from smallest to largest. + */ +export const MEDIA_QUERY_KEY = 'mediaQuery'; + +type MediaQueryBlock = { path: string; query: string; tokens: Record }; + +/** + * Flattens a `mediaQuery` object (`..`) into one + * query and its tokens per value. Values with no tokens left are skipped + * (refer to `mergeTheme`). + */ +const getMediaQueries = (mediaQuery: unknown): MediaQueryBlock[] => + Object.entries(isObject(mediaQuery) ? mediaQuery : {}).flatMap(([range, features]) => + Object.entries(isObject(features) ? features : {}).flatMap(([feature, values]) => + Object.entries(isObject(values) ? values : {}) + .filter(([, tokens]) => isObject(tokens) && Object.keys(tokens).length > 0) + .map(([value, tokens]) => ({ + path: `${MEDIA_QUERY_KEY}.${range}.${feature}['${value}']`, + query: getMediaQuery(range, convertToKebabCase(feature), value), + tokens: tokens as Record, + })) + ) + ); + +/** + * Builds a media query such as `(min-resolution: 2dppx)`. + */ +const getMediaQuery = (range: string, feature: string, value: string): string => { + const query = `(${range}-${feature}: ${value})`; + const dppx = feature === 'resolution' ? value.match(/^([\d.]+)dppx$/) : null; + + /** + * Safari 15 and older do not support `resolution`, so the query also + * matches the prefixed device pixel ratio. + */ + return dppx ? `${query}, (-webkit-${range}-device-pixel-ratio: ${dppx[1]})` : query; +}; + +const isObject = (value: unknown): value is Record => + value !== null && typeof value === 'object' && !Array.isArray(value); + +/** + * Merges a custom theme into the theme it overrides. + * + * A value the custom theme sets also replaces the base theme's media query + * values for that key, so it applies on every screen. Otherwise the base + * theme's media query would still win where it matches: setting + * `IonDivider: { thickness: '3px' }` over the ios theme would only reach 1x + * screens. Media query values that the custom theme sets itself are merged + * as usual. + * + * @param base The theme the custom theme is merged into. + * @param custom The custom theme. + * @returns The merged theme. + */ +export const mergeTheme = (base: any, custom: any): any => + deepMerge(removeOverriddenMediaQueries(base, custom), custom); + +/** + * Returns `base` without the media query values for each token that `custom` + * sets (refer to `mergeTheme`). + */ +const removeOverriddenMediaQueries = (base: any, custom: any): any => { + if (!isObject(base) || !isObject(custom)) { + return base; + } + + const result: Record = { ...base }; + + for (const [key, value] of Object.entries(custom)) { + if (key !== MEDIA_QUERY_KEY && isObject(base[key])) { + result[key] = removeOverriddenMediaQueries(base[key], value); + } + } + + const mediaQuery = base[MEDIA_QUERY_KEY]; + + if (isObject(mediaQuery)) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const { [MEDIA_QUERY_KEY]: customMediaQuery, ...overrides } = custom; + + result[MEDIA_QUERY_KEY] = mapValues(mediaQuery, (features) => + mapValues(features, (values) => mapValues(values, (tokens) => omitTokens(tokens, overrides))) + ); + } + + return result; +}; + +const mapValues = (obj: unknown, fn: (value: unknown) => unknown): unknown => + isObject(obj) ? Object.fromEntries(Object.entries(obj).map(([key, value]) => [key, fn(value)])) : obj; + +/** + * Returns `tokens` without the values that `overrides` sets. + */ +const omitTokens = (tokens: unknown, overrides: Record): unknown => { + if (!isObject(tokens)) { + return tokens; + } + + const result: Record = {}; + + for (const [key, value] of Object.entries(tokens)) { + const override = overrides[key]; + + if (override === undefined) { + result[key] = value; + } else if (isObject(value) && isObject(override)) { + result[key] = omitTokens(value, override); + } + } + + return result; +}; + /** * Applies a component theme to an element if it exists in the custom theme * @param element The element to apply the theme to diff --git a/docs/themes/recipes.md b/docs/themes/recipes.md index ccb57ef7ff4..41886880d43 100644 --- a/docs/themes/recipes.md +++ b/docs/themes/recipes.md @@ -94,6 +94,53 @@ state: { If resting values moved into `state.default`, adding the first state to a property would rename its variable. +### Media queries + +Use a top-level `mediaQuery` object only when no single value works on every screen. For example, an ios line that stays one screen pixel thick needs a different value at each density. The path builds the query: + +```ts +IonDivider: { + thickness: 'var(--ion-border-width-xxs)', + mediaQuery: { + min: { + resolution: { + '2dppx': { thickness: '0.5px' }, + '3dppx': { thickness: '0.3334px' }, + }, + }, + }, +}, +``` + +Becomes: + +```css +ion-divider { + --ion-divider-thickness: var(--ion-border-width-xxs); +} + +/* ion-divider: mediaQuery.min.resolution['2dppx'] */ +@media (min-resolution: 2dppx), (-webkit-min-device-pixel-ratio: 2) { + ion-divider { + --ion-divider-thickness: 0.5px; + } +} + +/* ion-divider: mediaQuery.min.resolution['3dppx'] */ +@media (min-resolution: 3dppx), (-webkit-min-device-pixel-ratio: 3) { + ion-divider { + --ion-divider-thickness: 0.3334px; + } +} +``` + +- **The key isn't part of the variable name**, unlike a state. The stylesheet reads one variable, `--ion-divider-thickness`, on every screen. +- **List values from smallest to largest.** When several queries match, the last one wins. +- **An app's value applies on every screen.** A custom theme that sets `IonDivider.thickness` drops the theme's `mediaQuery` values for `thickness`. To change the value per screen, the custom theme sets its own `mediaQuery`. +- **A parent's value also applies on every screen.** `IonItem.IonDivider.thickness` comes after the divider's media queries, so it wins. A parent can nest its own `mediaQuery` under the child. +- **To debug**, check the computed value of the variable. Each generated `@media` block has a comment naming the recipe path it came from. +- **Type the key** with `IonMediaQuery` from `themes.interfaces.ts`, and `Pick` only the keys that change per screen. Only `min.resolution` is typed so far, at `2dppx` and `3dppx` (`IonMediaQueryResolution`). Add a feature or a density to the type when a component needs it. + ## Values ### Set a value in every theme