Skip to content

refactor: reuse UI5 Web Components Styling #4858

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

Merged
merged 6 commits into from
Jul 10, 2023
Merged
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
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
*.module.css.ts
15 changes: 11 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
"private": true,
"license": "Apache-2.0",
"scripts": {
"start": "lerna run build:i18n && yarn create-cypress-commands-docs && storybook dev -p 6006",
"build:prepare": "lerna run build:i18n && rimraf node_modules/@types/mocha",
"build": "yarn build:prepare && tsc --build && lerna run build:client && lerna run build:wrapper && lerna run build:ssr",
"start": "yarn prepare && yarn create-cypress-commands-docs && npm-run-all -p start:watcher start:storybook",
"start:watcher": "lerna run watch:css",
"start:storybook": "storybook dev -p 6006",
"prepare": "lerna run build:i18n && lerna run build:css && rimraf node_modules/@types/mocha",
"build": "yarn prepare && tsc --build && lerna run build:client && lerna run build:wrapper && lerna run build:ssr",
"build:storybook": "lerna run build:i18n && yarn create-cypress-commands-docs && storybook build -o .out",
"test:prepare": "rimraf temp && lerna run build",
"test:cypress": "cypress run --component --browser chrome --spec 'packages/main/src/components/*/**',packages/base,packages/charts,packages/cypress-commands",
Expand All @@ -25,7 +27,7 @@
"examples:recreate-seed": "rimraf examples/seed-test && npx create-react-app examples/seed-test --template file:./packages/cra-template-seed",
"examples:start-seed": "cd examples/seed-test && SKIP_PREFLIGHT_CHECK=true yarn start",
"chromatic": "cross-env STORYBOOK_ENV=chromatic npx chromatic --build-script-name build:storybook",
"postinstall": "rimraf node_modules/@types/mocha && husky install && lerna run build:i18n",
"postinstall": "husky install && yarn prepare",
"create-cypress-commands-docs": "typedoc && rimraf temp/typedoc"
},
"dependencies": {
Expand Down Expand Up @@ -60,6 +62,7 @@
"@ui5/webcomponents-tools": "1.15.1",
"@vitejs/plugin-react": "^4.0.0",
"chromatic": "^6.5.3",
"cssnano": "^6.0.1",
"cypress": "^12.1.0",
"dedent": "^0.7.0",
"eslint": "^8.35.0",
Expand All @@ -78,6 +81,10 @@
"lerna": "^7.0.0",
"lint-staged": "^13.0.0",
"npm-run-all": "^4.1.5",
"postcss": "^8.4.25",
"postcss-cli": "^10.1.0",
"postcss-import": "^15.1.0",
"postcss-modules": "^6.0.0",
"prettier": "^2.8.4",
"rimraf": "^5.0.0",
"storybook": "7.0.26",
Expand Down
2 changes: 2 additions & 0 deletions packages/base/src/hooks/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { useIsomorphicId } from './useIsomorphicId.js';
import { useIsomorphicLayoutEffect } from './useIsomorphicLayoutEffect.js';
import { useIsRTL } from './useIsRTL.js';
import { useResponsiveContentPadding } from './useResponsiveContentPadding.js';
import { useStylesheet } from './useStylesheet.js';
import { useSyncRef } from './useSyncRef.js';
import { useViewportRange } from './useViewportRange.js';

Expand All @@ -15,5 +16,6 @@ export {
useSyncRef,
useViewportRange,
useIsomorphicId,
useStylesheet,
useCurrentTheme
};
17 changes: 17 additions & 0 deletions packages/base/src/hooks/useStylesheet.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import type { StyleDataCSP } from '@ui5/webcomponents-base/dist/ManagedStyles.js';
import { createOrUpdateStyle, removeStyle } from '@ui5/webcomponents-base/dist/ManagedStyles.js';
import * as React from 'react';

function getUseInsertionEffect(isSSR: boolean) {
return isSSR ? React.useEffect : Reflect.get(React, 'useInsertionEffect') || React.useLayoutEffect;
}

export function useStylesheet(styles: StyleDataCSP, componentName: string) {
getUseInsertionEffect(typeof window === 'undefined')(() => {
createOrUpdateStyle(styles, styles.packageName, componentName);

return () => {
removeStyle(styles.packageName, componentName);
};
}, [styles]);
}
1 change: 1 addition & 0 deletions packages/main/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,4 @@
/wrappers
/ssr
src/i18n/i18n-defaults.ts
src/**/*.css.ts
4 changes: 3 additions & 1 deletion packages/main/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,9 @@
"build:i18n": "node scripts/generateI18n.mjs",
"build:client": "babel src --out-dir dist --extensions .ts,.tsx --env-name client && tsc --declarationDir dist",
"build:ssr": "babel src --out-dir ssr --extensions .ts,.tsx --env-name ssr && tsc --declarationDir ssr",
"build:wrapper": "babel src --out-dir wrappers --extensions .ts,.tsx --env-name wrapper && tsc --declarationDir wrappers"
"build:wrapper": "babel src --out-dir wrappers --extensions .ts,.tsx --env-name wrapper && tsc --declarationDir wrappers",
"build:css": "postcss --dir ../../temp src/**/*.css",
"watch:css": "postcss --watch --dir ../../temp src/**/*.css"
},
"dependencies": {
"@tanstack/react-virtual": "3.0.0-beta.18",
Expand Down
30 changes: 30 additions & 0 deletions packages/main/postcss.config.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
const fs = require('node:fs');
const cssnano = require('cssnano');
const postcssImport = require('postcss-import');
const postcssModules = require('postcss-modules');
const postcssCSStoESM = require('../../scripts/postcss-css-to-esm.cjs');

const packageName = JSON.parse(fs.readFileSync('./package.json').toString()).name;

module.exports = {
plugins: [
postcssImport(),
postcssModules({
// generateScopedName: '[name]__[local]___[hash:base64:5]',
getJSON: (cssFileName, json) => {
return null;
},
globalModulePaths: [/\/\w+(?!\.module)\.css$/]
}),
cssnano({
preset: [
'default',
{
mergeLonghand: false, // https://github.com/cssnano/cssnano/issues/675
mergeRules: false // https://github.com/cssnano/cssnano/issues/730
}
]
}),
postcssCSStoESM({ toReplace: 'src', packageName })
]
};

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
.content {
display: flex;
flex: 1 1 auto;
overflow: hidden;
position: relative;
}
10 changes: 5 additions & 5 deletions packages/main/src/components/AnalyticalCard/index.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
'use client';

import { useStylesheet } from '@ui5/webcomponents-react-base';
import type { ReactNode } from 'react';
import React, { forwardRef } from 'react';
import { createUseStyles } from 'react-jss';
import type { CommonProps } from '../../interfaces/index.js';
import type { CardDomRef } from '../../webComponents/index.js';
import { Card } from '../../webComponents/index.js';
import styles from './AnalyticalCard.jss.js';
import { classNames, styleData } from './AnalyticalCard.module.css.js';

export interface AnalyticalCardPropTypes extends CommonProps {
/**
Expand All @@ -19,18 +19,18 @@ export interface AnalyticalCardPropTypes extends CommonProps {
children: ReactNode | ReactNode[];
}

const useStyles = createUseStyles(styles, { name: 'AnalyticalCard' });
/**
* The `AnalyticalCard` is mainly used for data visualization. It consists of two areas – a header area and a chart area with a visual representation of the data.<br />
*/
const AnalyticalCard = forwardRef<CardDomRef, AnalyticalCardPropTypes>((props, ref) => {
const { children, header, ...rest } = props;
const classes = useStyles();

useStylesheet(styleData, AnalyticalCard.displayName);

return (
<Card ref={ref} {...rest}>
{header}
<div className={classes.content} role="group">
<div className={classNames.content} role="group">
{children}
</div>
</Card>
Expand Down
60 changes: 60 additions & 0 deletions scripts/postcss-css-to-esm.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
// copied from https://github.com/SAP/ui5-webcomponents/blob/main/packages/tools/lib/postcss-css-to-esm/index.js
const fs = require('node:fs');
const path = require('node:path');
const { basename } = require('node:path');

const getTSContent = (targetFile, packageName, css, exportTokens) => {
const typeImport = `import type { StyleDataCSP } from '@ui5/webcomponents-base/dist/types.js';`;

// tabs are intentionally mixed to have proper identation in the produced file
return `${typeImport}
export const styleData: StyleDataCSP = {packageName:'${packageName}',fileName:'${basename(targetFile)}',content:${css}};

export const classNames = ${JSON.stringify(exportTokens)} as const;
`;
};

const proccessCSS = (css) => {
css = css.replace(/\.sapThemeMeta[\s\S]*?:root/, ':root');
css = css.replace(/\.background-image.*{.*}/, '');
css = css.replace(/\.sapContrast[ ]*:root[\s\S]*?}/, '');
css = css.replace(/--sapFontUrl.*\);?/, '');
return JSON.stringify(css);
};

module.exports = function (opts) {
opts = opts || {};

const packageName = opts.packageName;
const toReplace = opts.toReplace;

return {
postcssPlugin: 'postcss-css-to-esm',
OnceExit(root, { result }) {
const css = proccessCSS(root.toString());
const { exportTokens } = result.messages.find(
(message) => message.type === 'export' && message.plugin === 'postcss-modules'
);

const targetFile = root.source.input.from
.replace(`/${toReplace}/`, '/src/')
.replace(`\\${toReplace}\\`, '\\src\\');
fs.mkdirSync(path.dirname(targetFile), { recursive: true });

const filePath = `${targetFile}.ts`;

// it seems slower to read the old content, but writing the same content with no real changes
// (as in initial build and then watch mode) will cause an unnecessary dev server refresh
let oldContent = '';
if (fs.existsSync(filePath)) {
oldContent = fs.readFileSync(filePath).toString();
}

const content = getTSContent(targetFile, packageName, css, exportTokens);
if (content !== oldContent) {
fs.writeFileSync(filePath, content);
}
}
};
};
module.exports.postcss = true;
Loading