Files
Bernardo Cardoso 1e757513ce feat(ionic-theme): improve scss architecture for ionic theme (#29345)
Issue number: None

---------

<!-- Please do not submit updates to dependencies unless it fixes an
issue. -->

<!-- Please try to limit your pull request to one type (bugfix, feature,
etc). Submit multiple pull requests if needed. -->

## What is the new behavior?
<!-- Please describe the behavior or changes that are being added by
this PR. -->

This PR follows the architectural changes defined on the _SCSS
Architecture Design Doc_. Due to some of the developments done in the
meantime, not everything that was defined on that document was followed
and some sections were simplified.

Overall, there were two guidelines that supported the work on this PR:
- Have no impact on the current scss partials & CSS architecture for the
`md/iOS` themes.
- Make everything related to the new `Ionic` Theme separated.

Based on these, here're the changes made:

**On Themes folder (private):**
- Renamed current internal scss partials on src/themes, related to
md/iOS, to `native.*.scss` and move them to a new folder, called
`native`. Updated imports on all framework.
- Removed the ionic prefix from the name of the mixins and function
partials on src/themes. Updated imports on all framework.
- Created new folder, named ionic, inside src/themes. This holds the
`ionic.globals.scss`, with all the mixins and functions forwarded, to be
used on other scopes.
- Replaced on already created Ionic theme files, the usage of tokens and
mixins with @use, to instead _@use
"../../themes/ionic/ionic.globals.scss" as globals;_. This ensures an
equal approach is followed everywhere and also makes it easier to change
the files imported or paths, in the future, as its all in the same
global file.
- Updated the foundations `readMe` file, with the new process for using
globals.


![themes](https://github.com/ionic-team/ionic-framework/assets/32780808/1455523c-3ccd-4310-a974-522f9f8ade02)


**On css folder (public):**
- Created new folder, named `ionic`, inside src/css. This holds all the
files related exclusively to Ionic Theme, following the same structure
as exists now for md/iOS, with a core, a bundle, utils, etc. Some files
were a bit duplicated, to eliminate imports from ios or md theme
partials. The only file common to both Themes is the `normalize.scss`.
- No folder structure or renamings were done on the existing output, to
prevent breaking-changes for developers already making imports from this
folder.
- Updated typography and link partials to use globals instead of tokens.
- Changed `font-size` styles on typography to be on `body`, instead of
`html`, to enable correct support of accessibility features on browsers
and devices, related to `font-size`.


![css](https://github.com/ionic-team/ionic-framework/assets/32780808/10bedddc-23c1-4c50-a4e4-77fb7f6c6430)


**Other changes related to global styles new architecture:**
- Updated margin & padding utility-classed generated by token, to
include css variables and padding/margin mixins.
- Updated link test to use new global Ionic bundle, correct
utility-class on ion-content and updated snapshots. The font-size
changed to 16, as its now the default on the body.
- Updated typography snapshots.
- Updated prettier format on all scss files. Later on we should make
sure this is equal for all team members.

## Does this introduce a breaking change?

- [ ] Yes
- [x] No

<!--
  If this introduces a breaking change:
1. Describe the impact and migration path for existing applications
below.
  2. Update the BREAKING.md file with the breaking change.
3. Add "BREAKING CHANGE: [...]" to the commit description when merging.
See
https://github.com/ionic-team/ionic-framework/blob/main/docs/CONTRIBUTING.md#footer
for more information.
-->

---------

Co-authored-by: Sean Perkins <sean@ionic.io>
2024-04-18 17:22:24 +01:00

198 lines
6.6 KiB
JavaScript

/* For generating Design Tokens, we use Style Dictionary for several reasons:
- It's prepared to easily generate tokens for multiple types of outputs (CSS, SCSS, iOS, Android, documentation, etc.).
- It also works very well out of the box with any kind of Design Tokens formats, like Figma Tokens, as well as APIs to adjust to more custom ones.
- It is probably the most well-known and widely used Design Tokens tool. It has also been regularly maintained for a long time.
- It can easily scale to different necessities we might have in the future.
*/
// eslint-disable-next-line @typescript-eslint/no-var-requires
const StyleDictionary = require('style-dictionary');
const { fileHeader } = StyleDictionary.formatHelpers;
// Empty for as an example of how we can add some extra variables, not from the tokens JSON
const customVariables = ``;
// Prefix for all generated variables
const variablesPrefix = 'ionic';
function hexToRgb(hex) {
const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
return result
? {
r: parseInt(result[1], 16),
g: parseInt(result[2], 16),
b: parseInt(result[3], 16),
}
: null;
}
// CSS vanilla :root format
StyleDictionary.registerFormat({
name: 'rootFormat',
formatter({ dictionary, file }) {
// Add a prefix to all variable names
const prefixedVariables = dictionary.allProperties.map((prop) => {
const rgb = hexToRgb(prop.value);
return ` --${variablesPrefix}-${prop.name}: ${prop.value};${
rgb ? `\n --${variablesPrefix}-${prop.name}-rgb: ${rgb.r}, ${rgb.g}, ${rgb.b};` : ``
}`;
});
return (
fileHeader({ file }) +
':root {\n' +
prefixedVariables.join('\n') + // Join all prefixed variables with a newline
customVariables +
'\n}\n'
);
},
});
// scss variables format
StyleDictionary.registerFormat({
name: 'scssVariablesFormat',
formatter({ dictionary, file }) {
// Add a prefix to all variable names
const prefixedVariables = dictionary.allProperties.map((prop) => {
const rgb = hexToRgb(prop.value);
return `$${variablesPrefix}-${prop.name}: var(--${variablesPrefix}-${prop.name}, ${prop.value});${
rgb
? `\n$${variablesPrefix}-${prop.name}-rgb: var(--${variablesPrefix}-${prop.name}-rgb, ${rgb.r}, ${rgb.g}, ${rgb.b});`
: ``
}`;
});
return (
fileHeader({ file }) +
prefixedVariables.join('\n') + // Join all prefixed variables with a newline
customVariables +
'\n'
);
},
});
// Create utility-classes
StyleDictionary.registerFormat({
name: 'cssUtilityClassesFormat',
formatter({ dictionary, file }) {
const utilityClasses = dictionary.allProperties.map((prop) => {
let tokenType = prop.attributes.category;
const className = `${prop.name}`;
let utilityClass = '';
switch (tokenType) {
case 'color':
utilityClass = `.${variablesPrefix}-${className} {\n color: $ionic-${prop.name};\n}
.${variablesPrefix}-background-${className} {\n background-color: $ionic-${prop.name};\n}`;
break;
case 'border':
const borderAttribute = prop.attributes.type === 'radius' ? 'border-radius' : 'border-width';
utilityClass = `.${variablesPrefix}-${className} {\n ${borderAttribute}: $ionic-${prop.name};\n}`;
break;
case 'font':
let fontAttribute;
switch (prop.attributes.type) {
case 'size':
fontAttribute = 'font-size';
break;
case 'weight':
fontAttribute = 'font-weight';
break;
case 'line-height':
fontAttribute = 'line-height';
break;
case 'letter-spacing':
fontAttribute = 'letter-spacing';
break;
case 'family':
return;
}
utilityClass = `.${variablesPrefix}-${className} {\n ${fontAttribute}: $ionic-${prop.name};\n}`;
break;
case 'elevation':
utilityClass = `.${variablesPrefix}-${className} {\n box-shadow: $ionic-${prop.name};\n}`;
break;
case 'space':
utilityClass = `.${variablesPrefix}-margin-${className} {\n --margin-start: #{$ionic-${prop.name}};\n --margin-end: #{$ionic-${prop.name}};\n --margin-top: #{$ionic-${prop.name}};\n --margin-bottom: #{$ionic-${prop.name}};\n\n @include margin(${prop.value});\n};\n
.${variablesPrefix}-padding-${className} {\n --padding-start: #{$ionic-${prop.name}};\n --padding-end: #{$ionic-${prop.name}};\n --padding-top: #{$ionic-${prop.name}};\n --padding-bottom: #{$ionic-${prop.name}};\n\n @include padding(${prop.value});\n};\n`;
break;
default:
utilityClass = `.${variablesPrefix}-${className} {\n ${tokenType}: $ionic-${prop.name};\n}`;
}
return utilityClass;
});
return [
fileHeader({ file }),
'@import "./ionic.vars";\n@import "../themes/mixins";\n',
utilityClasses.join('\n'),
].join('\n');
},
});
// Make Style Dictionary comply with the $ format on properties from W3C Guidelines
const w3cTokenJsonParser = {
pattern: /\.json|\.tokens\.json|\.tokens$/,
parse({ contents }) {
// replace $value with value so that style dictionary recognizes it
var preparedContent = (contents || '{}')
.replace(/"\$?value":/g, '"value":')
// convert $description to comment
.replace(/"\$?description":/g, '"comment":');
//
return JSON.parse(preparedContent);
},
};
StyleDictionary.registerParser(w3cTokenJsonParser);
// Generate Tokens
StyleDictionary.extend({
source: ['./src/foundations/*.json'],
platforms: {
css: {
buildPath: './src/foundations/',
transformGroup: 'css',
files: [
{
destination: 'ionic.root.scss',
format: 'rootFormat',
options: {
outputReferences: true,
fileHeader: `myFileHeader`,
},
},
],
},
scss: {
buildPath: './src/foundations/',
transformGroup: 'scss',
files: [
{
destination: 'ionic.vars.scss',
format: 'scssVariablesFormat',
options: {
outputReferences: true,
fileHeader: `myFileHeader`,
},
},
{
destination: 'ionic.utility.scss',
format: 'cssUtilityClassesFormat',
options: {
outputReferences: true,
fileHeader: `myFileHeader`,
},
},
],
},
},
fileHeader: {
myFileHeader: () => {
return [`This is an auto-generated file, please do not change it directly.`, `Ionic Design System`];
},
},
}).buildAllPlatforms();