Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
30 changes: 30 additions & 0 deletions packages/fluentui/docs/src/examples/components/Flex/Recipes.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -63,3 +63,33 @@ This approach introduces unnecessary nesting level - it is possible to achieve t
</ExampleSnippet>

Note that `Flex.Item` doesn't result in any additional DOM element rendered - its sole purpose is just to pass style props to its child. Please, consider to review set of examples on this page - as there might be an example that suits your needs.

### Using media, container, and feature queries

The `Flex` component supports CSS at-rules such as `@media`, `@container`, and `@supports` within the `styles` prop. This allows you to create responsive layouts that adapt based on viewport size, container dimensions, or browser feature support. In the example below, the box changes its background color depending on which conditions are met — try resizing your browser window or the container to see the different states.

<ExampleSnippet>
<Flex style={{width:'100%', containerType: 'inline-size', containerName:'sidebar' }}>
<Flex
styles={{
width: '100%',
minHeight: '200px',
backgroundColor: 'white',
transition: 'background-color 0.3s ease',

[`@supports (display: grid)`]: {
backgroundColor: 'lightblue',
},

[`@container sidebar (min-width: 800px)`]: {
backgroundColor: 'blue',
},

[`@media screen and (min-width: 1300px)`]: {
backgroundColor: 'darkblue',
},
}}
/>

</Flex>
</ExampleSnippet>
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export function createNode(
styleNodeAttributes: FelaRendererStyleNodeAttributes,
): HTMLStyleElement {
const head = targetDocument.head;
const { type, media, support } = attributes;
const { type, media, support, container } = attributes;

const node = targetDocument.createElement('style');

Expand All @@ -18,6 +18,9 @@ export function createNode(
if (support) {
node.setAttribute('data-fela-support', 'true');
}
if (container) {
node.setAttribute('data-fela-container', 'true');
}

if (media) {
node.media = media;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import { FelaRenderer, StyleNodeAttributes } from '../types';
import { createNode } from './createNode';
import { queryNode } from './queryNode';

function getReference({ type, media = '', support = '' }: StyleNodeAttributes): string {
return type + media + support;
function getReference({ type, media = '', support = '', container = '' }: StyleNodeAttributes): string {
return type + media + support + container;
}

export function getNodeFromCache(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { SortMediaQueryFn, StyleNodeAttributes } from '../types';

export function getNodeSibling(
nodes: HTMLStyleElement[],
{ type, media, support }: StyleNodeAttributes,
{ type, media, support, container }: StyleNodeAttributes,
sortMediaQuery: SortMediaQueryFn,
): HTMLElement | undefined {
switch (type) {
Expand All @@ -20,6 +20,10 @@ export function getNodeSibling(
const insertMedia = sorted[index];

if (insertMedia) {
if (insertMedia === media && container) {
// container
return nodes.find(el => el.media === sorted[sorted.indexOf(media) + 2]);
}
if (insertMedia === media && support) {
// support
return nodes.find(el => el.media === sorted[sorted.indexOf(media) + 2]);
Expand All @@ -30,18 +34,33 @@ export function getNodeSibling(
const sorted = filteredNodes.sort(sortMediaQuery);
const insertMedia = sorted[0];

if (!support) {
// if we insert the plain RULE node while there's already a support RULE node
if (!support && !container) {
// if we insert the plain RULE node while there's already a support or container RULE node
// make sure to insert before (whichever comes first in DOM order)
const firstSpecialNode = nodes.find(
el =>
(el.getAttribute('data-fela-support') === 'true' || el.getAttribute('data-fela-container') === 'true') &&
el.media === '' &&
el.getAttribute('data-fela-type') === 'RULE',
);

if (firstSpecialNode) {
return firstSpecialNode;
}
}

if (support && !container) {
// if we insert a support RULE node while there's already a container RULE node
// make sure to insert before
const supportNode = nodes.find(
const containerNode = nodes.find(
el =>
el.getAttribute('data-fela-support') !== undefined &&
el.getAttribute('data-fela-container') === 'true' &&
el.media === '' &&
el.getAttribute('data-fela-type') === 'RULE',
);

if (supportNode) {
return supportNode;
if (containerNode) {
return containerNode;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,16 @@ import {

import type { FelaRenderer, FelaRendererRuleChange } from '../types';

function generateCSSContainerRule(container: string, cssRules: string): string {
return `@container ${container}{${cssRules}}`;
}

export function insertRule(
{ selector, declaration, support, media, pseudo }: FelaRendererRuleChange,
{ selector, declaration, support, media, container, pseudo }: FelaRendererRuleChange,
renderer: FelaRenderer,
node: HTMLStyleElement,
) {
const nodeReference = media + support;
const nodeReference = media + support + container;

try {
const score = getRuleScore(renderer.ruleOrder, pseudo);
Expand Down Expand Up @@ -43,15 +47,18 @@ export function insertRule(
}
}

const cssRule = generateCSSRule(selector, declaration);
let cssRule = generateCSSRule(selector, declaration);

if (support.length > 0) {
const cssSupportRule = generateCSSSupportRule(support, cssRule);
node.sheet!.insertRule(cssSupportRule, index);
} else {
node.sheet!.insertRule(cssRule, index);
cssRule = generateCSSSupportRule(support, cssRule);
}

if (container.length > 0) {
cssRule = generateCSSContainerRule(container, cssRule);
}

node.sheet!.insertRule(cssRule, index);

if (score === 0) {
renderer.scoreIndex[nodeReference] = index;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import type { StyleNodeAttributes } from '../types';

export function queryNode(
{ type, media, support }: StyleNodeAttributes,
{ type, media, support, container }: StyleNodeAttributes,
targetDocument: Document,
): HTMLStyleElement | null {
const mediaQuery = media ? `[media="${media}"]` : ':not([media])';
const supportQuery = support ? '[data-fela-support="true"]' : ':not([data-fela-support="true"])';
const containerQuery = container ? '[data-fela-container="true"]' : ':not([data-fela-container="true"])';

return targetDocument.querySelector<HTMLStyleElement>(`[data-fela-type="${type}"]${supportQuery}${mediaQuery}`);
return targetDocument.querySelector<HTMLStyleElement>(
`[data-fela-type="${type}"]${supportQuery}${containerQuery}${mediaQuery}`,
);
}
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,10 @@ function isPlainObject(val: any) {
return val != null && typeof val === 'object' && Array.isArray(val) === false;
}

function isContainerQuery(property: string): boolean {
return property.substr(0, 10) === '@container';
}

const chars = 'abcdefghijklmnopqrstuvwxyz';
const charLength = chars.length;

Expand Down Expand Up @@ -61,24 +65,32 @@ function generateDeclarationReference(
pseudo: string = '',
media: string = '',
support: string = '',
container: string = '',
): string {
//
// This a single perf change here, it removes `camelCaseProperty()` call
//

// CHANGE:START
return support + media + pseudo + property + value;
return support + media + container + pseudo + property + value;
// CHANGE:END
}

//
type RenderStyleToClassNames = FelaRenderer['_renderStyleToClassNames'];
interface EnahncedFelaRenderer extends Omit<FelaRenderer, '_renderStyleToClassNames'> {
_renderStyleToClassNames: (
...args: [...Parameters<RenderStyleToClassNames>, container: string]
) => ReturnType<RenderStyleToClassNames>;
}

export function felaPerformanceEnhancer(renderer: FelaRenderer) {
export function felaPerformanceEnhancer(renderer: EnahncedFelaRenderer) {
renderer._renderStyleToClassNames = function _renderStyleToClassNames(
{ _className, ...style }: ICSSInJSStyle & { _className?: string },
pseudo: string = '',
media: string = '',
support: string = '',
container: string = '',
): string {
let classNames = _className ? ` ${_className}` : '';

Expand All @@ -92,21 +104,30 @@ export function felaPerformanceEnhancer(renderer: FelaRenderer) {
pseudo + normalizeNestedProperty(property),
media,
support,
container,
);
} else if (isMediaQuery(property)) {
const combinedMediaQuery = generateCombinedMediaQuery(media, property.slice(6).trim());
classNames += renderer._renderStyleToClassNames(value as any, pseudo, combinedMediaQuery, support);
classNames += renderer._renderStyleToClassNames(value as any, pseudo, combinedMediaQuery, support, container);
} else if (isContainerQuery(property)) {
if (container.length !== 0) {
// eslint-disable-next-line no-console
console.warn('You have nested container queries in your style object. This is not supported by Fela.');
continue;
}
const combinedContainerQuery = property.slice(10).trim();
classNames += renderer._renderStyleToClassNames(value as any, pseudo, media, support, combinedContainerQuery);
Comment thread
Yakubko marked this conversation as resolved.
Resolved
} else if (isSupport(property)) {
const combinedSupport = generateCombinedMediaQuery(support, property.slice(9).trim());
classNames += renderer._renderStyleToClassNames(value as any, pseudo, media, combinedSupport);
classNames += renderer._renderStyleToClassNames(value as any, pseudo, media, combinedSupport, container);
} else {
// eslint-disable-next-line no-console
console.warn(`The object key "${property}" is not a valid nested key in Fela.
Maybe you forgot to add a plugin to resolve it?
Check http://fela.js.org/docs/basics/Rules.html#styleobject for more information.`);
}
} else {
const declarationReference = generateDeclarationReference(property, value, pseudo, media, support);
const declarationReference = generateDeclarationReference(property, value, pseudo, media, support, container);

if (!renderer.cache.hasOwnProperty(declarationReference)) {
// we remove undefined values to enable
Expand Down Expand Up @@ -134,6 +155,7 @@ Check http://fela.js.org/docs/basics/Rules.html#styleobject for more information
pseudo,
media,
support,
container,
};

renderer.cache[declarationReference] = change;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import type { IRenderer } from 'fela';
export type StyleNodeAttributes = {
media?: string;
support?: string;
container?: string;

type: 'KEYFRAME' | 'RULE' | 'CLEAR';
};
Expand Down Expand Up @@ -51,6 +52,7 @@ export type FelaRendererRuleChange = {
pseudo: string;
media: string;
support: string;
container: string;
};

export type FelaRendererChange =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,55 @@ exports[`felaRenderer basic styles are rendered 1`] = `
<div class=\\"a\\"></div>"
`;

exports[`felaRenderer combined media, supports, and container query styles are rendered 1`] = `
".a {
background-color: white;
}
.c {
background-color: blue;
}
@supports (display: grid) {
.b {
background-color: lightblue;
}
}
@media screen and (min-width: 1300px) {
.d {
background-color: darkblue;
}
}


<div class=\\"a b c d\\"></div>"
`;

exports[`felaRenderer container query styles are rendered 1`] = `
".a {
color: red;
}
.b {
color: blue;
}


<div class=\\"a b\\"></div>"
`;

exports[`felaRenderer container query with pseudo selector styles are rendered 1`] = `
".a {
color: red;
}
.b {
color: blue;
}
.c:hover {
color: green;
}


<div class=\\"a b c\\"></div>"
`;

exports[`felaRenderer keyframe colors are rendered 1`] = `
"@-webkit-keyframes k1 {
from {
Expand Down Expand Up @@ -136,6 +185,20 @@ exports[`felaRenderer marginLeft is rendered into marginRight due to RTL 1`] = `
<div class=\\"a\\"></div>"
`;

exports[`felaRenderer media query styles are rendered 1`] = `
".a {
color: red;
}
@media screen and (min-width: 1024px) {
.b {
color: blue;
}
}


<div class=\\"a b\\"></div>"
`;

exports[`felaRenderer prefixes required styles 1`] = `
".a {
cursor: -webkit-zoom-in;
Expand Down Expand Up @@ -216,3 +279,17 @@ exports[`felaRenderer styles are expanded to longhand values 1`] = `

<div class=\\"a b c d e f g h\\"></div>"
`;

exports[`felaRenderer supports query styles are rendered 1`] = `
".a {
color: red;
}
@supports (display: grid) {
.b {
color: blue;
}
}


<div class=\\"a b\\"></div>"
`;
Loading