@displaycoffee/common 0.0.0-stage → 1.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +169 -2
- package/build/tokens-generate.js +175 -0
- package/build/vite.js +66 -0
- package/package.json +58 -5
- package/src/_core/scripts/hooks.ts +30 -0
- package/src/_core/scripts/tokens.d.ts +45 -0
- package/src/_core/scripts/tokens.js +109 -0
- package/src/_core/scripts/utils-types.d.ts +54 -0
- package/src/_core/scripts/utils.ts +124 -0
- package/src/_core/styles/_functions.scss +44 -0
- package/src/_core/styles/_mixins.scss +269 -0
package/README.md
CHANGED
|
@@ -1,3 +1,170 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @displaycoffee/common
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Resources for every project: Sass functions and mixins, React hooks and utility functions, and design token generation with [Style Dictionary](https://styledictionary.com).
|
|
4
|
+
|
|
5
|
+
Projects get all of this through their kit ([`@displaycoffee/burmecia`](https://www.npmjs.com/package/@displaycoffee/burmecia), [`@displaycoffee/alexandria`](https://www.npmjs.com/package/@displaycoffee/alexandria), or [`@displaycoffee/memoria`](https://www.npmjs.com/package/@displaycoffee/memoria)), which forwards these files, so they only need one package.
|
|
6
|
+
|
|
7
|
+
### Structure
|
|
8
|
+
|
|
9
|
+
- **src/_core/styles** - Sass functions and mixins.
|
|
10
|
+
- **src/_core/scripts** - React hooks, utility functions, and the token helpers. The TypeScript files ship as source, so the project's bundler compiles them.
|
|
11
|
+
- **build** - `tokens-generate` and the Vite helpers, which run in Node during dev and builds.
|
|
12
|
+
|
|
13
|
+
### Install
|
|
14
|
+
|
|
15
|
+
```
|
|
16
|
+
npm install --save-dev @displaycoffee/common sass
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The hooks need `react` and `react-dom` 19. Router and framework hooks (TanStack Router, Next.js, Astro) live in the kits' own `hooks`, alongside these.
|
|
20
|
+
|
|
21
|
+
### Setup
|
|
22
|
+
|
|
23
|
+
Sass files are loaded with `pkg:` URLs, which read the package's `exports`. Add Sass's `NodePackageImporter` to the Sass options:
|
|
24
|
+
|
|
25
|
+
```js
|
|
26
|
+
import { NodePackageImporter } from 'sass';
|
|
27
|
+
|
|
28
|
+
// Vite (or vite.css in an Astro config)
|
|
29
|
+
css: {
|
|
30
|
+
preprocessorOptions: {
|
|
31
|
+
scss: {
|
|
32
|
+
importers: [new NodePackageImporter()],
|
|
33
|
+
},
|
|
34
|
+
},
|
|
35
|
+
},
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
Next.js resolves `pkg:` URLs without any extra config, but it only compiles TypeScript in `node_modules` for listed packages, so add the package to `transpilePackages` in `next.config.ts`:
|
|
39
|
+
|
|
40
|
+
```ts
|
|
41
|
+
const nextConfig: NextConfig = {
|
|
42
|
+
transpilePackages: ['@displaycoffee/common'],
|
|
43
|
+
};
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Sass
|
|
47
|
+
|
|
48
|
+
```scss
|
|
49
|
+
@use 'pkg:@displaycoffee/common/functions';
|
|
50
|
+
@use 'pkg:@displaycoffee/common/mixins';
|
|
51
|
+
|
|
52
|
+
.button {
|
|
53
|
+
@include mixins.flex-layout((flex-flow: row nowrap, align-items: center));
|
|
54
|
+
padding: functions.em(12px);
|
|
55
|
+
@include mixins.respond(768px) {
|
|
56
|
+
padding: functions.em(16px, rem);
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Neither file outputs any CSS on its own, so they're safe to `@use` in any stylesheet.
|
|
62
|
+
|
|
63
|
+
#### functions
|
|
64
|
+
|
|
65
|
+
- **em($pixels, $unit: em, $context: 16px)** - Converts pixels to `em`, or `rem` when `$unit` is `rem`.
|
|
66
|
+
- **string-replace($string, $search, $replace: '')** - Replaces every match in a string.
|
|
67
|
+
- **svg-encode($svg)** - Encodes an SVG string as a `url()` for `background-image`.
|
|
68
|
+
|
|
69
|
+
#### mixins
|
|
70
|
+
|
|
71
|
+
- **Layout** - `flex-layout`, `gap-width`, `grid-layout`, `position`, `position-fill`, `sizing`.
|
|
72
|
+
- **Responsive** - `respond($breakpoint, $rule: 'min-width')` wraps `@content` in a media query. Unitless breakpoints get `px`.
|
|
73
|
+
- **Text** - `ellipsis`, `line-clamp`, `text-decoration`, `placeholder`.
|
|
74
|
+
- **Images and icons** - `object-fit`, `icon-sizing`.
|
|
75
|
+
- **Visuals** - `gradient`, `gradient-stripes`, `scrollbar`.
|
|
76
|
+
- **Animation** - `animate-spin`, `animate-loading`, `toggle-content`.
|
|
77
|
+
- **Utilities** - `clearfix`, `sr-only`.
|
|
78
|
+
|
|
79
|
+
See the comments in `_mixins.scss` for arguments and examples.
|
|
80
|
+
|
|
81
|
+
### Scripts
|
|
82
|
+
|
|
83
|
+
```ts
|
|
84
|
+
import { useFormattedId, useRespond } from '@displaycoffee/common/hooks';
|
|
85
|
+
import { utils, utilsBrowser } from '@displaycoffee/common/utils';
|
|
86
|
+
import type { UtilsType } from '@displaycoffee/common/utils-types';
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
#### utils
|
|
90
|
+
|
|
91
|
+
Safe anywhere, including server rendering.
|
|
92
|
+
|
|
93
|
+
- **getLast(value, delimeter?)** - Last item of an array, or of a string split by `delimeter`.
|
|
94
|
+
- **handleize(value)** - Formats a string for HTML classes (e.g. `Page One!` to `page-one`).
|
|
95
|
+
- **stripHTML(string)** - Removes HTML tags and newlines. Returns an empty string for `null` / `undefined`.
|
|
96
|
+
- **truncate(string, limit)** - Cuts a string to `limit` characters, ending with `...`. Returns an empty string for `null` / `undefined`.
|
|
97
|
+
|
|
98
|
+
#### utilsBrowser
|
|
99
|
+
|
|
100
|
+
These use `window` / `document`, so only call them in `useEffect` or event handlers, never during render.
|
|
101
|
+
|
|
102
|
+
- **isSticky(element, stickyClass)** - Toggles `stickyClass` while the element is stuck. Returns a cleanup function that stops observing.
|
|
103
|
+
- **scrollTo(e?, selector?, offset?)** - Smooth scrolls to an element (or the top) and moves focus to it.
|
|
104
|
+
- **setAttributes(element, attributes)** - Sets several attributes at once.
|
|
105
|
+
- **setAvailableMinHeight(element)** - Sets the element's `min-height` to the viewport space left around it (e.g. so `main` fills the screen between the header and footer), updating when the page or window resizes. Returns a cleanup function that stops watching.
|
|
106
|
+
|
|
107
|
+
#### hooks
|
|
108
|
+
|
|
109
|
+
- **useFormattedId()** - `useId()` formatted for HTML ids and `aria-*` attributes (e.g. `R-1`).
|
|
110
|
+
- **useRespond(bp, rule = 'min-width')** - Whether a media query matches, updating on change. Renders as `false` on the server, then updates after hydration.
|
|
111
|
+
|
|
112
|
+
### Tokens
|
|
113
|
+
|
|
114
|
+
#### tokens-generate
|
|
115
|
+
|
|
116
|
+
Add it as a script in `package.json` (kit projects run it as `burmecia tokens`, `alexandria tokens`, or `memoria tokens` instead):
|
|
117
|
+
|
|
118
|
+
```json
|
|
119
|
+
"generate:tokens": "tokens-generate"
|
|
120
|
+
```
|
|
121
|
+
|
|
122
|
+
It runs from the project root and expects this layout:
|
|
123
|
+
|
|
124
|
+
- **src/_core/tokens/*.json** - The token source files.
|
|
125
|
+
- **src/_core/styles/_root.scss** - Generated. CSS custom properties on `:root`, including the alternate theme. Only import this once, since it outputs CSS.
|
|
126
|
+
- **src/_core/styles/_theme.scss** - Generated. Sass variables that point to the custom properties, safe to `@use` anywhere.
|
|
127
|
+
- **src/_core/tokens/theme.json** - Generated. Resolved values grouped by category, for scripts (e.g. `{ "color": { "bg": "#fdfdfd", "bg-dark": "#1a1a1a" } }`).
|
|
128
|
+
|
|
129
|
+
For a dev server, a plugin can re-run it when token files change. The script's path is exported as `@displaycoffee/common/tokens-generate`:
|
|
130
|
+
|
|
131
|
+
```js
|
|
132
|
+
import { fileURLToPath } from 'url';
|
|
133
|
+
|
|
134
|
+
const scriptPath = fileURLToPath(import.meta.resolve('@displaycoffee/common/tokens-generate'));
|
|
135
|
+
```
|
|
136
|
+
|
|
137
|
+
#### Token options
|
|
138
|
+
|
|
139
|
+
- Exclude from `scss` files by adding `"$extensions": { "sass": false }`. The token still goes to `theme.json`.
|
|
140
|
+
- Add as a static variable in `scss` files by adding `"$extensions": { "static": true }`. The `breakpoint`, `font`, and `spacing` tokens are static by default, so they stay plain Sass values and are left out of `:root`.
|
|
141
|
+
- Customize a value for dark mode by using `"$extensions": { "dark": "#ffffff" }`. This only applies to tokens that end up in `:root`.
|
|
142
|
+
- Themes are set with the `setting.theme` tokens. `setting.theme.default` is the theme `$value` is written for (`light` or `dark`). For a dark-first project, set it to `dark` and use `"$extensions": { "light": "#ffffff" }` instead. Set `setting.theme.system` to `false` if only a manual `[data-theme]` toggle should switch themes, not the OS setting.
|
|
143
|
+
- Set a value to `false` to leave it unset (`$name: null` in Sass, so declarations using it are skipped). The build fails if another token references an unset token.
|
|
144
|
+
|
|
145
|
+
#### Helpers
|
|
146
|
+
|
|
147
|
+
Each helper takes the generated `theme.json` and returns data for the app and build scripts. Every token group is optional, so a project without one gets an empty list (or the default settings).
|
|
148
|
+
|
|
149
|
+
```ts
|
|
150
|
+
import { getFonts } from '@displaycoffee/common/tokens';
|
|
151
|
+
import themeJson from '../tokens/theme.json' with { type: 'json' };
|
|
152
|
+
|
|
153
|
+
export const fonts = getFonts(themeJson);
|
|
154
|
+
```
|
|
155
|
+
|
|
156
|
+
- **getFallbacks(themeJson)** - Fallback `@font-face` details from the `fallback` tokens.
|
|
157
|
+
- **getFavicons(themeJson)** - Favicon links and manifest icons from the `favicon` tokens.
|
|
158
|
+
- **getFonts(themeJson)** - `@font-face` and preload details from the `font` tokens. Supports local fonts like `local('Courier New')`.
|
|
159
|
+
- **getSettings(themeJson)** - Theme settings (`default`, `alternate`, `system`) from the `setting` tokens.
|
|
160
|
+
|
|
161
|
+
The helpers are plain JavaScript, so Node build scripts can import them directly. Types (`Fallback`, `Favicon`, `Font`, `Settings`, `ThemeMode`) are exported for TypeScript projects.
|
|
162
|
+
|
|
163
|
+
### Vite helpers
|
|
164
|
+
|
|
165
|
+
```js
|
|
166
|
+
import { cssTarget, tokensWatch } from '@displaycoffee/common/vite';
|
|
167
|
+
```
|
|
168
|
+
|
|
169
|
+
- **tokensWatch()** - A dev-only plugin that re-runs `tokens-generate` whenever a token file in `src/_core/tokens` changes.
|
|
170
|
+
- **cssTarget** - CSS build targets for `build.cssTarget`. Vite's defaults with Safari / iOS lowered to 16.3, so Lightning CSS keeps `min-width` / `max-width` media queries instead of rewriting them to range syntax like `(width>=768px)`.
|
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/* Packages */
|
|
3
|
+
import StyleDictionary from 'style-dictionary';
|
|
4
|
+
import { getReferences, usesReferences } from 'style-dictionary/utils';
|
|
5
|
+
|
|
6
|
+
/* Get a token's value for the alternate theme from $extensions.dark or $extensions.light (tokens without one keep their default value) */
|
|
7
|
+
const getAlternate = (token, theme) => token.$extensions?.[theme] ?? token.original?.$extensions?.[theme];
|
|
8
|
+
|
|
9
|
+
/* Theme settings come from the setting.theme tokens (settings.json)
|
|
10
|
+
- default: the theme $value is written for, either 'light' or 'dark'
|
|
11
|
+
- system: whether the OS setting can switch to the alternate theme, or only a manual [data-theme] toggle can */
|
|
12
|
+
const getThemeSettings = (dictionary) => {
|
|
13
|
+
const allTokens = dictionary.unfilteredAllTokens ?? dictionary.allTokens;
|
|
14
|
+
const getSetting = (name) => allTokens.find((token) => token.path.join('.') === `setting.theme.${name}`)?.$value;
|
|
15
|
+
const defaultTheme = getSetting('default') ?? 'light';
|
|
16
|
+
if (defaultTheme !== 'light' && defaultTheme !== 'dark') {
|
|
17
|
+
throw new Error(`Token "setting.theme.default" is "${defaultTheme}", but it must be "light" or "dark".`);
|
|
18
|
+
}
|
|
19
|
+
return {
|
|
20
|
+
defaultTheme,
|
|
21
|
+
alternateTheme: defaultTheme === 'dark' ? 'light' : 'dark',
|
|
22
|
+
system: getSetting('system') !== false,
|
|
23
|
+
};
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
/* Fail the build if a token has a value for the default theme in $extensions (e.g. "dark" when the default theme is dark) */
|
|
27
|
+
/* Note: it would never be output, since $value is already the default theme's value */
|
|
28
|
+
const checkThemeExtensions = (dictionary, { defaultTheme, alternateTheme }) => {
|
|
29
|
+
const allTokens = dictionary.unfilteredAllTokens ?? dictionary.allTokens;
|
|
30
|
+
|
|
31
|
+
allTokens.forEach((token) => {
|
|
32
|
+
if (getAlternate(token, defaultTheme) === undefined) return;
|
|
33
|
+
const tokenPath = token.path.join('.');
|
|
34
|
+
throw new Error(
|
|
35
|
+
`Token "${tokenPath}" has a "${defaultTheme}" value, but ${defaultTheme} is the default theme. Put the ${defaultTheme} value in $value and the ${alternateTheme} value in "$extensions": { "${alternateTheme}": ... }.`,
|
|
36
|
+
);
|
|
37
|
+
});
|
|
38
|
+
};
|
|
39
|
+
|
|
40
|
+
/* Static tokens are output as plain Sass values instead of custom properties, for values Sass needs at compile time */
|
|
41
|
+
/* Note: breakpoints are static since var() doesn't work in media queries, and spacing / font since they're used in Sass math (negatives, division, em(), etc.) */
|
|
42
|
+
/* Other tokens can opt in individually with "$extensions": { "static": true } */
|
|
43
|
+
const staticCategories = ['breakpoint', 'font', 'spacing'];
|
|
44
|
+
const isStatic = (token) => staticCategories.includes(token.path[0]) || (token.$extensions?.static ?? token.original?.$extensions?.static) === true;
|
|
45
|
+
|
|
46
|
+
/* Tokens with "$extensions": { "sass": false } are left out of _root.scss and _theme.scss, but still go to theme.json for the build scripts */
|
|
47
|
+
/* Note: e.g. build-only values like font file paths, or values that are only referenced by other tokens */
|
|
48
|
+
const isSassExcluded = (token) => (token.$extensions?.sass ?? token.original?.$extensions?.sass) === false;
|
|
49
|
+
|
|
50
|
+
/* Tokens set to false aren't used in this project, so they're left out of :root and output as $name: null in Sass (Sass skips null declarations) */
|
|
51
|
+
const isUnset = (token) => token.$value === false;
|
|
52
|
+
|
|
53
|
+
/* Fail the build if a token uses an unset (false) token inside a larger value, e.g. color-mix(in srgb, {color.unused} 50%, transparent) */
|
|
54
|
+
/* Note: a token that is only a reference to an unset token (e.g. "{color.unused}") resolves to false, so it's treated as unset itself */
|
|
55
|
+
/* Note: uses the unfiltered tokens so tokens excluded from this file (e.g. sass: false) are still checked */
|
|
56
|
+
const checkUnsetReferences = (dictionary) => {
|
|
57
|
+
const allTokens = dictionary.unfilteredAllTokens ?? dictionary.allTokens;
|
|
58
|
+
const tokens = dictionary.unfilteredTokens ?? dictionary.tokens;
|
|
59
|
+
|
|
60
|
+
allTokens.forEach((token) => {
|
|
61
|
+
const original = token.original.$value;
|
|
62
|
+
if (isUnset(token) || typeof original !== 'string' || !usesReferences(original)) return;
|
|
63
|
+
|
|
64
|
+
const unsetReferences = getReferences(original, tokens).filter(isUnset);
|
|
65
|
+
if (unsetReferences.length !== 0) {
|
|
66
|
+
const tokenPath = token.path.join('.');
|
|
67
|
+
const referencePaths = unsetReferences.map((reference) => reference.path.join('.')).join(', ');
|
|
68
|
+
throw new Error(`Token "${tokenPath}" references "${referencePaths}", which is set to false. Give it a value or update "${tokenPath}".`);
|
|
69
|
+
}
|
|
70
|
+
});
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
/* Set comment for generated files */
|
|
74
|
+
const comment = `// Do not edit directly, this file was auto-generated.`;
|
|
75
|
+
|
|
76
|
+
/* Format tokens as :root custom properties with default / alternate theme values */
|
|
77
|
+
/* Note: this outputs CSS, so it should only be imported once (in container.scss) */
|
|
78
|
+
StyleDictionary.registerFormat({
|
|
79
|
+
name: 'scss/theme-properties',
|
|
80
|
+
format: ({ dictionary }) => {
|
|
81
|
+
const settings = getThemeSettings(dictionary);
|
|
82
|
+
const { defaultTheme, alternateTheme, system } = settings;
|
|
83
|
+
checkUnsetReferences(dictionary);
|
|
84
|
+
checkThemeExtensions(dictionary, settings);
|
|
85
|
+
const tokens = dictionary.allTokens.filter((token) => !isStatic(token) && !isUnset(token));
|
|
86
|
+
const toProperty = (token, value) => `\t--${token.name}: ${value};`;
|
|
87
|
+
const base = tokens.map((token) => toProperty(token, token.$value)).join('\n');
|
|
88
|
+
const alternate = tokens
|
|
89
|
+
.filter((token) => getAlternate(token, alternateTheme) !== undefined)
|
|
90
|
+
.map((token) => toProperty(token, getAlternate(token, alternateTheme)))
|
|
91
|
+
.join('\n');
|
|
92
|
+
|
|
93
|
+
// Only output alternate styles if at least one token has an alternate value, so single-theme projects keep native UI in the default theme
|
|
94
|
+
const hasAlternate = alternate.length !== 0;
|
|
95
|
+
const alternateProperties = `\tcolor-scheme: ${alternateTheme};\n${alternate}`;
|
|
96
|
+
|
|
97
|
+
// Note: the alternate block is output twice - once to follow the OS setting (unless system is false), once for a manual [data-theme] toggle
|
|
98
|
+
const rootDefault = `:root {\n\tcolor-scheme: ${defaultTheme};\n${base}\n}`;
|
|
99
|
+
const prefersAlternate = `@media (prefers-color-scheme: ${alternateTheme}) {\n\t:root:not([data-theme='${defaultTheme}']) {\n${alternateProperties.replace(/^/gm, '\t')}\n\t}\n}`;
|
|
100
|
+
const rootAlternate = `:root[data-theme='${alternateTheme}'] {\n${alternateProperties}\n}`;
|
|
101
|
+
const blocks = !hasAlternate ? [rootDefault] : system ? [rootDefault, prefersAlternate, rootAlternate] : [rootDefault, rootAlternate];
|
|
102
|
+
return `${comment}\n${blocks.join('\n\n')}`;
|
|
103
|
+
},
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
/* Format tokens as Sass variables that point to their custom properties (static tokens get their plain value, unset tokens get null) */
|
|
107
|
+
/* Note: this outputs no CSS, so it's safe to @use in any stylesheet */
|
|
108
|
+
StyleDictionary.registerFormat({
|
|
109
|
+
name: 'scss/theme-variables',
|
|
110
|
+
format: ({ dictionary }) => {
|
|
111
|
+
const sassVars = dictionary.allTokens
|
|
112
|
+
.map((token) => `$${token.name}: ${isUnset(token) ? 'null' : isStatic(token) ? token.$value : `var(--${token.name})`};`)
|
|
113
|
+
.join('\n');
|
|
114
|
+
return `${comment}\n${sassVars}`;
|
|
115
|
+
},
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
/* Format resolved token values as JSON for the build scripts, grouped by category (e.g. { color: { bg, bg-dark } }) */
|
|
119
|
+
/* Note: alternate values are suffixed with the alternate theme, so bg-dark when the default theme is light, or bg-light when it's dark */
|
|
120
|
+
StyleDictionary.registerFormat({
|
|
121
|
+
name: 'json/theme',
|
|
122
|
+
format: ({ dictionary }) => {
|
|
123
|
+
const { alternateTheme } = getThemeSettings(dictionary);
|
|
124
|
+
const theme = {};
|
|
125
|
+
|
|
126
|
+
dictionary.allTokens.forEach((token) => {
|
|
127
|
+
const [category, ...path] = token.path;
|
|
128
|
+
const key = path.join('-');
|
|
129
|
+
const alternate = getAlternate(token, alternateTheme);
|
|
130
|
+
theme[category] ??= {};
|
|
131
|
+
theme[category][key] = token.$value;
|
|
132
|
+
if (alternate !== undefined && !isUnset(token)) theme[category][`${key}-${alternateTheme}`] = alternate;
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
return `${JSON.stringify(theme, null, '\t')}\n`;
|
|
136
|
+
},
|
|
137
|
+
});
|
|
138
|
+
|
|
139
|
+
const sd = new StyleDictionary({
|
|
140
|
+
// Path to your raw JSON token files
|
|
141
|
+
// Note: theme.json is excluded because it's generated into the same folder by the json platform below
|
|
142
|
+
source: ['src/_core/tokens/!(theme).json'],
|
|
143
|
+
platforms: {
|
|
144
|
+
scss: {
|
|
145
|
+
transformGroup: 'scss',
|
|
146
|
+
buildPath: 'src/_core/styles/',
|
|
147
|
+
files: [
|
|
148
|
+
{
|
|
149
|
+
destination: '_root.scss',
|
|
150
|
+
format: 'scss/theme-properties', // Compiles to :root { --variable-name: value; } with alternate theme overrides
|
|
151
|
+
filter: (token) => !isSassExcluded(token),
|
|
152
|
+
},
|
|
153
|
+
{
|
|
154
|
+
destination: '_theme.scss',
|
|
155
|
+
format: 'scss/theme-variables', // Compiles to $variable-name: var(--variable-name);
|
|
156
|
+
filter: (token) => !isSassExcluded(token),
|
|
157
|
+
},
|
|
158
|
+
],
|
|
159
|
+
},
|
|
160
|
+
json: {
|
|
161
|
+
transformGroup: 'scss',
|
|
162
|
+
buildPath: 'src/_core/tokens/',
|
|
163
|
+
files: [
|
|
164
|
+
{
|
|
165
|
+
destination: 'theme.json',
|
|
166
|
+
format: 'json/theme', // Compiles to { "color": { "bg": "#fdfdfd", "bg-dark": "#1a1a1a" } }
|
|
167
|
+
},
|
|
168
|
+
],
|
|
169
|
+
},
|
|
170
|
+
},
|
|
171
|
+
});
|
|
172
|
+
|
|
173
|
+
await sd.buildAllPlatforms();
|
|
174
|
+
|
|
175
|
+
console.log('🚀 Successfully built tokens into _root.scss, _theme.scss, and theme.json.');
|
package/build/vite.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
/* Packages */
|
|
2
|
+
import { execFile } from 'child_process';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { fileURLToPath } from 'url';
|
|
5
|
+
|
|
6
|
+
/* Paths */
|
|
7
|
+
const tokensScriptPath = fileURLToPath(new URL('./tokens-generate.js', import.meta.url));
|
|
8
|
+
|
|
9
|
+
/* CSS build targets: Vite's defaults (Baseline widely available), with Safari / iOS lowered from 16.4 to 16.3 */
|
|
10
|
+
/* Note: Safari 16.3 doesn't support media query range syntax, so Lightning CSS keeps min-width / max-width instead of rewriting them to (width>=768px) */
|
|
11
|
+
export const cssTarget = ['chrome111', 'edge111', 'firefox114', 'safari16.3', 'ios16.3'];
|
|
12
|
+
|
|
13
|
+
/* Vite plugin that rebuilds tokens when a token file changes during dev, so the regenerated Sass hot reloads like any other change */
|
|
14
|
+
/* Note: theme.json is generated into the tokens folder, so it's ignored to avoid a rebuild loop */
|
|
15
|
+
export const tokensWatch = () => {
|
|
16
|
+
let isRunning = false;
|
|
17
|
+
let isQueued = false;
|
|
18
|
+
|
|
19
|
+
return {
|
|
20
|
+
name: 'tokens-watch',
|
|
21
|
+
apply: 'serve',
|
|
22
|
+
configureServer(server) {
|
|
23
|
+
const { logger } = server.config;
|
|
24
|
+
|
|
25
|
+
// The dev server runs from the project root, like the npm scripts
|
|
26
|
+
const projectPath = process.cwd();
|
|
27
|
+
const tokensPath = path.resolve(projectPath, 'src/_core/tokens');
|
|
28
|
+
|
|
29
|
+
// Run tokens-generate, queuing one more run if a token file changes while it's still building
|
|
30
|
+
const buildTokens = () => {
|
|
31
|
+
if (isRunning) {
|
|
32
|
+
isQueued = true;
|
|
33
|
+
return;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
isRunning = true;
|
|
37
|
+
execFile(process.execPath, [tokensScriptPath], { cwd: projectPath }, (error, _stdout, stderr) => {
|
|
38
|
+
isRunning = false;
|
|
39
|
+
|
|
40
|
+
if (error) {
|
|
41
|
+
logger.error(`[tokens] ${stderr || error.message}`, { timestamp: true });
|
|
42
|
+
} else {
|
|
43
|
+
logger.info('[tokens] rebuilt _root.scss, _theme.scss, and theme.json', { timestamp: true });
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
if (isQueued) {
|
|
47
|
+
isQueued = false;
|
|
48
|
+
buildTokens();
|
|
49
|
+
}
|
|
50
|
+
});
|
|
51
|
+
};
|
|
52
|
+
|
|
53
|
+
// Only rebuild for token source files (not the generated theme.json)
|
|
54
|
+
const handleTokenFile = (file) => {
|
|
55
|
+
const filePath = path.resolve(file);
|
|
56
|
+
const isTokenFile = path.dirname(filePath) === tokensPath && filePath.endsWith('.json') && path.basename(filePath) !== 'theme.json';
|
|
57
|
+
if (isTokenFile) buildTokens();
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
server.watcher.add(tokensPath);
|
|
61
|
+
server.watcher.on('add', handleTokenFile);
|
|
62
|
+
server.watcher.on('change', handleTokenFile);
|
|
63
|
+
server.watcher.on('unlink', handleTokenFile);
|
|
64
|
+
},
|
|
65
|
+
};
|
|
66
|
+
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,59 @@
|
|
|
1
1
|
{
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
2
|
+
"name": "@displaycoffee/common",
|
|
3
|
+
"description": "Sass functions and mixins, React hooks, utility functions, design token generation, and Vite helpers shared by every project.",
|
|
4
|
+
"version": "1.0.0",
|
|
5
|
+
"type": "module",
|
|
6
|
+
"author": "displaycoffee",
|
|
7
|
+
"license": "ISC",
|
|
8
|
+
"homepage": "https://github.com/displaycoffee/project-kit/tree/production/common#readme",
|
|
9
|
+
"exports": {
|
|
10
|
+
"./functions": {
|
|
11
|
+
"sass": "./src/_core/styles/_functions.scss"
|
|
12
|
+
},
|
|
13
|
+
"./hooks": "./src/_core/scripts/hooks.ts",
|
|
14
|
+
"./mixins": {
|
|
15
|
+
"sass": "./src/_core/styles/_mixins.scss"
|
|
16
|
+
},
|
|
17
|
+
"./tokens": {
|
|
18
|
+
"types": "./src/_core/scripts/tokens.d.ts",
|
|
19
|
+
"default": "./src/_core/scripts/tokens.js"
|
|
20
|
+
},
|
|
21
|
+
"./tokens-generate": "./build/tokens-generate.js",
|
|
22
|
+
"./utils": "./src/_core/scripts/utils.ts",
|
|
23
|
+
"./utils-types": "./src/_core/scripts/utils-types.d.ts",
|
|
24
|
+
"./vite": "./build/vite.js"
|
|
25
|
+
},
|
|
26
|
+
"bin": {
|
|
27
|
+
"tokens-generate": "build/tokens-generate.js"
|
|
28
|
+
},
|
|
29
|
+
"files": [
|
|
30
|
+
"build",
|
|
31
|
+
"src"
|
|
32
|
+
],
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"style-dictionary": "^5.5.5"
|
|
35
|
+
},
|
|
36
|
+
"peerDependencies": {
|
|
37
|
+
"react": "^19.0.0",
|
|
38
|
+
"react-dom": "^19.0.0"
|
|
39
|
+
},
|
|
40
|
+
"peerDependenciesMeta": {
|
|
41
|
+
"react": {
|
|
42
|
+
"optional": true
|
|
43
|
+
},
|
|
44
|
+
"react-dom": {
|
|
45
|
+
"optional": true
|
|
46
|
+
}
|
|
47
|
+
},
|
|
48
|
+
"repository": {
|
|
49
|
+
"type": "git",
|
|
50
|
+
"url": "git+https://github.com/displaycoffee/project-kit.git",
|
|
51
|
+
"directory": "common"
|
|
52
|
+
},
|
|
53
|
+
"bugs": {
|
|
54
|
+
"url": "https://github.com/displaycoffee/project-kit/issues"
|
|
55
|
+
},
|
|
56
|
+
"publishConfig": {
|
|
57
|
+
"access": "public"
|
|
58
|
+
}
|
|
59
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
/* Packages */
|
|
2
|
+
import { useCallback, useId, useSyncExternalStore } from 'react';
|
|
3
|
+
|
|
4
|
+
export const useFormattedId = () => {
|
|
5
|
+
// Updates the format of useId hook
|
|
6
|
+
const id = useId();
|
|
7
|
+
return id.slice(1, -1).replace(/^_|_$/g, '').replace(/_/g, '-');
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export const useRespond = (bp: string, rule: 'min-width' | 'max-width' = 'min-width') => {
|
|
11
|
+
// Match a media query and update on change
|
|
12
|
+
// Note: the server has no window, so it renders as a non-match (e.g. mobile for 'min-width') and the browser corrects it after hydration
|
|
13
|
+
const query = `(${rule}: ${bp})`;
|
|
14
|
+
|
|
15
|
+
// Note: subscribe is memoized so React only resubscribes when the query changes
|
|
16
|
+
const subscribe = useCallback(
|
|
17
|
+
(onChange: () => void) => {
|
|
18
|
+
const mediaQuery = window.matchMedia(query);
|
|
19
|
+
mediaQuery.addEventListener('change', onChange);
|
|
20
|
+
return () => mediaQuery.removeEventListener('change', onChange);
|
|
21
|
+
},
|
|
22
|
+
[query],
|
|
23
|
+
);
|
|
24
|
+
|
|
25
|
+
return useSyncExternalStore(
|
|
26
|
+
subscribe,
|
|
27
|
+
() => window.matchMedia(query).matches,
|
|
28
|
+
() => false,
|
|
29
|
+
);
|
|
30
|
+
};
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
/* Any generated theme.json works, since every token group is optional */
|
|
2
|
+
export type ThemeJson = Record<string, unknown>;
|
|
3
|
+
|
|
4
|
+
export type Fallback = {
|
|
5
|
+
family: string;
|
|
6
|
+
size: string;
|
|
7
|
+
src: string;
|
|
8
|
+
};
|
|
9
|
+
|
|
10
|
+
export type Favicon = {
|
|
11
|
+
isHead: boolean;
|
|
12
|
+
isManifest: boolean;
|
|
13
|
+
purpose: string;
|
|
14
|
+
rel: string;
|
|
15
|
+
src: string;
|
|
16
|
+
size: string;
|
|
17
|
+
sizes: string;
|
|
18
|
+
type: string;
|
|
19
|
+
};
|
|
20
|
+
|
|
21
|
+
export type Font = {
|
|
22
|
+
display: string;
|
|
23
|
+
ext: string;
|
|
24
|
+
family: string;
|
|
25
|
+
isLocal: boolean;
|
|
26
|
+
isPreload: boolean;
|
|
27
|
+
src: string;
|
|
28
|
+
style: string;
|
|
29
|
+
weight: string | number;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
export type ThemeMode = 'light' | 'dark';
|
|
33
|
+
|
|
34
|
+
export type Settings = {
|
|
35
|
+
theme: {
|
|
36
|
+
default: ThemeMode;
|
|
37
|
+
alternate: ThemeMode;
|
|
38
|
+
system: boolean;
|
|
39
|
+
};
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
export declare const getFallbacks: (themeJson: ThemeJson) => Fallback[];
|
|
43
|
+
export declare const getFavicons: (themeJson: ThemeJson) => Favicon[];
|
|
44
|
+
export declare const getFonts: (themeJson: ThemeJson) => Font[];
|
|
45
|
+
export declare const getSettings: (themeJson: ThemeJson) => Settings;
|
|
@@ -0,0 +1,109 @@
|
|
|
1
|
+
/* Build fallback font families */
|
|
2
|
+
/* Note: fallback tokens are optional, so a project without them gets an empty list */
|
|
3
|
+
export const getFallbacks = (themeJson) => {
|
|
4
|
+
const json = themeJson.fallback ?? {};
|
|
5
|
+
const keys = Object.keys(json).filter((key) => key.startsWith('src-'));
|
|
6
|
+
|
|
7
|
+
return keys.map((fallback) => {
|
|
8
|
+
const key = fallback.includes('header') ? 'header' : 'body';
|
|
9
|
+
|
|
10
|
+
return {
|
|
11
|
+
family: json[`name-${key}`],
|
|
12
|
+
size: json[`size-${key}`],
|
|
13
|
+
src: json[fallback],
|
|
14
|
+
};
|
|
15
|
+
});
|
|
16
|
+
};
|
|
17
|
+
|
|
18
|
+
/* Build favicons */
|
|
19
|
+
/* Note: favicon tokens are optional, so a project without them gets an empty list */
|
|
20
|
+
export const getFavicons = (themeJson) => {
|
|
21
|
+
const json = themeJson.favicon ?? {};
|
|
22
|
+
const keys = Object.keys(json).filter((key) => key.startsWith('src-'));
|
|
23
|
+
|
|
24
|
+
/* Not every favicon has head / manifest / purpose / sizes tokens, so these return a fallback when a token is missing */
|
|
25
|
+
const getBoolean = (name) => json[name] === true;
|
|
26
|
+
const getString = (name) => {
|
|
27
|
+
const value = json[name];
|
|
28
|
+
return typeof value === 'string' ? value : undefined;
|
|
29
|
+
};
|
|
30
|
+
|
|
31
|
+
return keys.map((favicon) => {
|
|
32
|
+
const current = getString(favicon) ?? '';
|
|
33
|
+
const key = favicon.replace('src-', '');
|
|
34
|
+
const size = getString(`size-${key}`) ?? '';
|
|
35
|
+
|
|
36
|
+
// Set type attribute
|
|
37
|
+
let type = 'image/png';
|
|
38
|
+
if (current.includes('.svg')) {
|
|
39
|
+
type = 'image/svg+xml';
|
|
40
|
+
} else if (current.includes('.ico')) {
|
|
41
|
+
type = 'image/x-icon';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return {
|
|
45
|
+
isHead: getBoolean(`head-${key}`),
|
|
46
|
+
isManifest: getBoolean(`manifest-${key}`),
|
|
47
|
+
purpose: getString(`purpose-${key}`) ?? 'any',
|
|
48
|
+
rel: current.includes('apple-touch-icon') ? 'apple-touch-icon' : 'icon',
|
|
49
|
+
src: current,
|
|
50
|
+
size: size,
|
|
51
|
+
sizes: getString(`sizes-${key}`) ?? size,
|
|
52
|
+
type: type,
|
|
53
|
+
};
|
|
54
|
+
});
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
/* Build font families */
|
|
58
|
+
/* Note: font tokens are optional, so a project without them gets an empty list */
|
|
59
|
+
export const getFonts = (themeJson) => {
|
|
60
|
+
const json = themeJson.font ?? {};
|
|
61
|
+
const keys = Object.keys(json).filter((key) => key.startsWith('src-'));
|
|
62
|
+
|
|
63
|
+
/* Get a token as a string (src and name tokens are always strings) */
|
|
64
|
+
const getString = (name) => {
|
|
65
|
+
const value = json[name];
|
|
66
|
+
return typeof value === 'string' ? value : '';
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
return keys.map((font) => {
|
|
70
|
+
const current = getString(font).trim();
|
|
71
|
+
const key = font.includes('header') ? 'header' : 'body';
|
|
72
|
+
const weight = font.includes('bold') ? 700 : 400;
|
|
73
|
+
const srcSplit = current.split('.');
|
|
74
|
+
|
|
75
|
+
// Fonts can be files or already installed on the device (e.g. local('Courier New'))
|
|
76
|
+
const isLocal = current.startsWith('local(');
|
|
77
|
+
|
|
78
|
+
// Preload the non-italic file each family uses first: regular for body text, and the header weight token for headers
|
|
79
|
+
// Note: local fonts aren't downloaded, so they're never preloaded
|
|
80
|
+
const preloadWeight = key === 'header' ? json['weight-header'] : 400;
|
|
81
|
+
const isPreload = !isLocal && !font.includes('italic') && weight === preloadWeight;
|
|
82
|
+
|
|
83
|
+
return {
|
|
84
|
+
display: 'swap',
|
|
85
|
+
ext: isLocal ? '' : srcSplit[srcSplit.length - 1],
|
|
86
|
+
family: getString(`name-${key}`),
|
|
87
|
+
isLocal: isLocal,
|
|
88
|
+
isPreload: isPreload,
|
|
89
|
+
src: current,
|
|
90
|
+
style: font.includes('italic') ? 'italic' : 'normal',
|
|
91
|
+
weight: weight,
|
|
92
|
+
};
|
|
93
|
+
});
|
|
94
|
+
};
|
|
95
|
+
|
|
96
|
+
/* Build project settings */
|
|
97
|
+
/* Note: setting tokens are optional, so a project without them gets the defaults (light theme that follows the OS) */
|
|
98
|
+
export const getSettings = (themeJson) => {
|
|
99
|
+
const json = themeJson.setting ?? {};
|
|
100
|
+
const defaultTheme = json['theme-default'] === 'dark' ? 'dark' : 'light';
|
|
101
|
+
|
|
102
|
+
return {
|
|
103
|
+
theme: {
|
|
104
|
+
default: defaultTheme,
|
|
105
|
+
alternate: defaultTheme === 'dark' ? 'light' : 'dark',
|
|
106
|
+
system: json['theme-system'] !== false,
|
|
107
|
+
},
|
|
108
|
+
};
|
|
109
|
+
};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
/* Packages */
|
|
2
|
+
import type { SyntheticEvent } from 'react';
|
|
3
|
+
|
|
4
|
+
/* Type definitions */
|
|
5
|
+
type Utils = {
|
|
6
|
+
getLast: UtilsGetLast;
|
|
7
|
+
handleize: UtilsHandleize;
|
|
8
|
+
stripHTML: UtilsStripHTML;
|
|
9
|
+
truncate: UtilsTruncate;
|
|
10
|
+
};
|
|
11
|
+
|
|
12
|
+
type UtilsBrowser = {
|
|
13
|
+
isSticky: UtilsIsSticky;
|
|
14
|
+
scrollTo: UtilsScrollTo;
|
|
15
|
+
setAttributes: UtilsSetAttributes;
|
|
16
|
+
setAvailableMinHeight: UtilsSetAvailableMinHeight;
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
type UtilsGetLast = (value: string | string[], delimeter?: string) => string;
|
|
20
|
+
|
|
21
|
+
type UtilsHandleize = (value: string) => string;
|
|
22
|
+
|
|
23
|
+
type UtilsIsSticky = (element: HTMLElement | null, stickyClass: string) => (() => void) | undefined;
|
|
24
|
+
|
|
25
|
+
type UtilsScrollTo = (e?: SyntheticEvent | Event, selector?: string, offset?: number) => void;
|
|
26
|
+
|
|
27
|
+
type UtilsSetAttributes = (element: HTMLElement, attributes: { [key: string]: string }) => void;
|
|
28
|
+
|
|
29
|
+
type UtilsSetAvailableMinHeight = (element: HTMLElement) => () => void;
|
|
30
|
+
|
|
31
|
+
type UtilsStripHTML = (string?: string | null) => string;
|
|
32
|
+
|
|
33
|
+
type UtilsTruncate = (string: string | null | undefined, limit: number) => string;
|
|
34
|
+
|
|
35
|
+
/* Export types */
|
|
36
|
+
export type UtilsType = Utils;
|
|
37
|
+
|
|
38
|
+
export type UtilsBrowserType = UtilsBrowser;
|
|
39
|
+
|
|
40
|
+
export type UtilsGetLastType = UtilsGetLast;
|
|
41
|
+
|
|
42
|
+
export type UtilsHandleizeType = UtilsHandleize;
|
|
43
|
+
|
|
44
|
+
export type UtilsIsStickyType = UtilsIsSticky;
|
|
45
|
+
|
|
46
|
+
export type UtilsScrollToType = UtilsScrollTo;
|
|
47
|
+
|
|
48
|
+
export type UtilsSetAttributesType = UtilsSetAttributes;
|
|
49
|
+
|
|
50
|
+
export type UtilsSetAvailableMinHeightType = UtilsSetAvailableMinHeight;
|
|
51
|
+
|
|
52
|
+
export type UtilsStripHTMLType = UtilsStripHTML;
|
|
53
|
+
|
|
54
|
+
export type UtilsTruncateType = UtilsTruncate;
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/* Scripts */
|
|
2
|
+
import type { UtilsType, UtilsBrowserType } from './utils-types';
|
|
3
|
+
|
|
4
|
+
/* Note: "utils" functions are safe anywhere (Server Components, Client Components, metadata files). */
|
|
5
|
+
/* "utilsBrowser" functions use window / document, so only call them in useEffect or event handlers, never during render. */
|
|
6
|
+
export const utils: UtilsType = {
|
|
7
|
+
getLast: (value, delimeter) => {
|
|
8
|
+
// Get last item in array
|
|
9
|
+
let valueArray: string[] = [];
|
|
10
|
+
if (Array.isArray(value)) {
|
|
11
|
+
valueArray = value;
|
|
12
|
+
} else if (delimeter) {
|
|
13
|
+
valueArray = value.split(delimeter);
|
|
14
|
+
}
|
|
15
|
+
return valueArray[valueArray.length - 1] ?? '';
|
|
16
|
+
},
|
|
17
|
+
handleize: (value) => {
|
|
18
|
+
// Format value for html classes
|
|
19
|
+
return value
|
|
20
|
+
.toLowerCase()
|
|
21
|
+
.trim()
|
|
22
|
+
.replace(/[^\w\s]/g, '')
|
|
23
|
+
.replace(/\s/g, '-')
|
|
24
|
+
.replace(/-+/g, '-');
|
|
25
|
+
},
|
|
26
|
+
stripHTML: (string) => {
|
|
27
|
+
// Remove HTML from string
|
|
28
|
+
if (!string) return '';
|
|
29
|
+
return string
|
|
30
|
+
.replace(/\n/g, ' ')
|
|
31
|
+
.replace(/<[^>]*>/g, '')
|
|
32
|
+
.trim();
|
|
33
|
+
},
|
|
34
|
+
truncate: (string, limit) => {
|
|
35
|
+
// Limit characters in string
|
|
36
|
+
if (!string) return '';
|
|
37
|
+
if (string.length > limit) {
|
|
38
|
+
return `${string.slice(0, limit - 3)}...`;
|
|
39
|
+
} else {
|
|
40
|
+
return string;
|
|
41
|
+
}
|
|
42
|
+
},
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
export const utilsBrowser: UtilsBrowserType = {
|
|
46
|
+
isSticky: (element, stickyClass) => {
|
|
47
|
+
if (element) {
|
|
48
|
+
// Create options and callback for observer
|
|
49
|
+
const stickyOptions = { threshold: [1] };
|
|
50
|
+
const stickyCallback = (e: IntersectionObserverEntry) => {
|
|
51
|
+
e.target.classList.toggle(stickyClass, e.intersectionRatio < 1);
|
|
52
|
+
};
|
|
53
|
+
|
|
54
|
+
// Observe to toggle sticky class
|
|
55
|
+
const stickyObserver = new IntersectionObserver(([e]) => stickyCallback(e), stickyOptions);
|
|
56
|
+
stickyObserver.observe(element);
|
|
57
|
+
|
|
58
|
+
// Return cleanup so callers can stop observing (e.g. in a useEffect cleanup)
|
|
59
|
+
return () => stickyObserver.disconnect();
|
|
60
|
+
}
|
|
61
|
+
return undefined;
|
|
62
|
+
},
|
|
63
|
+
scrollTo: (e, selector, offset) => {
|
|
64
|
+
// Scroll to element on page
|
|
65
|
+
if (e) {
|
|
66
|
+
e.preventDefault();
|
|
67
|
+
}
|
|
68
|
+
const anchor = {
|
|
69
|
+
selector: selector ?? '',
|
|
70
|
+
offset: offset ?? 0,
|
|
71
|
+
position: () => {
|
|
72
|
+
const anchorElement = anchor.selector ? document.querySelector(anchor.selector) : false;
|
|
73
|
+
return anchorElement ? anchorElement.getBoundingClientRect().top + window.scrollY - anchor.offset : -anchor.offset;
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
window.scroll({ top: anchor.position(), left: 0, behavior: 'smooth' });
|
|
77
|
+
|
|
78
|
+
// Move focus to the target so keyboard/screen-reader users know where they landed
|
|
79
|
+
if (anchor.selector) {
|
|
80
|
+
const anchorElement = document.querySelector<HTMLElement>(anchor.selector);
|
|
81
|
+
anchorElement?.focus({ preventScroll: true });
|
|
82
|
+
}
|
|
83
|
+
},
|
|
84
|
+
setAttributes: (element, attributes) => {
|
|
85
|
+
// Set multiple attributes on an element
|
|
86
|
+
for (const attribute in attributes) {
|
|
87
|
+
element.setAttribute(attribute, attributes[attribute]);
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
setAvailableMinHeight: (element) => {
|
|
91
|
+
// Reserves exactly the viewport space around this element — regardless of what surrounds it,
|
|
92
|
+
// or how many pieces (header, nav, footer, none of the above) — so content mounting in later
|
|
93
|
+
// doesn't shift whatever comes after it. Sets min-height directly, no CSS-side setup needed.
|
|
94
|
+
const updateMinHeight = () => {
|
|
95
|
+
// Temporarily clear so this element's own current height can't feed back into the
|
|
96
|
+
// measurement (its min-height from a prior run would otherwise inflate scrollHeight)
|
|
97
|
+
element.style.minHeight = '';
|
|
98
|
+
|
|
99
|
+
const rect = element.getBoundingClientRect();
|
|
100
|
+
const spaceAbove = rect.top + window.scrollY;
|
|
101
|
+
const spaceBelow = document.documentElement.scrollHeight - (rect.bottom + window.scrollY);
|
|
102
|
+
const minHeight = Math.max(0, window.innerHeight - spaceAbove - spaceBelow);
|
|
103
|
+
|
|
104
|
+
element.style.minHeight = `${minHeight}px`;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
// Set it synchronously before paint too — ResizeObserver's first callback is only
|
|
108
|
+
// guaranteed to fire eventually, not synchronously ahead of the next paint
|
|
109
|
+
updateMinHeight();
|
|
110
|
+
|
|
111
|
+
// Watch the whole page rather than individual siblings — anything that changes the
|
|
112
|
+
// page's total height (header, nav, footer, the element's own content, none of the above)
|
|
113
|
+
// should trigger a recompute, without this needing to know what those things are
|
|
114
|
+
const observer = new ResizeObserver(updateMinHeight);
|
|
115
|
+
observer.observe(document.body);
|
|
116
|
+
window.addEventListener('resize', updateMinHeight);
|
|
117
|
+
|
|
118
|
+
// Return cleanup so callers can stop watching (e.g. in a useLayoutEffect cleanup)
|
|
119
|
+
return () => {
|
|
120
|
+
observer.disconnect();
|
|
121
|
+
window.removeEventListener('resize', updateMinHeight);
|
|
122
|
+
};
|
|
123
|
+
},
|
|
124
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// Built-in Sass modules
|
|
2
|
+
@use 'sass:math';
|
|
3
|
+
@use 'sass:string';
|
|
4
|
+
|
|
5
|
+
// PX to EM/REM conversion
|
|
6
|
+
// From https://css-tricks.com/snippets/sass/px-to-em-functions
|
|
7
|
+
@function em($pixels, $unit: em, $context: 16px) {
|
|
8
|
+
@if math.is-unitless($pixels) {
|
|
9
|
+
$pixels: $pixels * 1px;
|
|
10
|
+
}
|
|
11
|
+
@if math.is-unitless($context) {
|
|
12
|
+
$context: $context * 1px;
|
|
13
|
+
}
|
|
14
|
+
$multiplier: if(sass($unit == rem): 1rem; else: 1em);
|
|
15
|
+
@return calc($pixels / $context * $multiplier);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// Helper function to replace characters in a string
|
|
19
|
+
@function string-replace($string, $search, $replace: '') {
|
|
20
|
+
$index: string.index($string, $search);
|
|
21
|
+
// Note: an empty $search would match at position 1 forever, so it returns the string unchanged
|
|
22
|
+
@if not $index or $search == '' {
|
|
23
|
+
@return $string;
|
|
24
|
+
}
|
|
25
|
+
@return string.slice($string, 1, $index - 1) + $replace + string-replace(string.slice($string, $index + string.length($search)), $search, $replace);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Encode svg (mostly for use in background-image)
|
|
29
|
+
@function svg-encode($svg) {
|
|
30
|
+
// Add missing namespace
|
|
31
|
+
@if not string.index($svg, xmlns) {
|
|
32
|
+
$svg: string-replace($svg, '<svg','<svg xmlns="http://www.w3.org/2000/svg"');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
// Encode characters in svg
|
|
36
|
+
$encoded: string-replace($svg, '%', '%25');
|
|
37
|
+
$encoded: string-replace($encoded, '#', '%23');
|
|
38
|
+
$encoded: string-replace($encoded, '{', '%7B');
|
|
39
|
+
$encoded: string-replace($encoded, '}', '%7D');
|
|
40
|
+
$encoded: string-replace($encoded, '<', '%3C');
|
|
41
|
+
$encoded: string-replace($encoded, '>', '%3E');
|
|
42
|
+
|
|
43
|
+
@return url("data:image/svg+xml, #{$encoded}");
|
|
44
|
+
}
|
|
@@ -0,0 +1,269 @@
|
|
|
1
|
+
// Built-in Sass modules
|
|
2
|
+
@use 'sass:list';
|
|
3
|
+
@use 'sass:map';
|
|
4
|
+
@use 'sass:math';
|
|
5
|
+
|
|
6
|
+
// Animate - spin
|
|
7
|
+
// Example: animation: spin 2s infinite linear;
|
|
8
|
+
@mixin animate-spin {
|
|
9
|
+
@keyframes spin {
|
|
10
|
+
0% {
|
|
11
|
+
transform: rotate(0deg);
|
|
12
|
+
}
|
|
13
|
+
to {
|
|
14
|
+
transform: rotate(1turn);
|
|
15
|
+
}
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Animate - loading
|
|
20
|
+
// Example: animation: loading 2s infinite linear;
|
|
21
|
+
// Note: the element needs position: absolute inside a position: relative, overflow: hidden track
|
|
22
|
+
@mixin animate-loading {
|
|
23
|
+
@keyframes loading {
|
|
24
|
+
from {
|
|
25
|
+
left: -200px;
|
|
26
|
+
width: 30%;
|
|
27
|
+
}
|
|
28
|
+
50% {
|
|
29
|
+
width: 30%;
|
|
30
|
+
}
|
|
31
|
+
70% {
|
|
32
|
+
width: 70%;
|
|
33
|
+
}
|
|
34
|
+
80% {
|
|
35
|
+
left: 50%;
|
|
36
|
+
}
|
|
37
|
+
95% {
|
|
38
|
+
left: 120%;
|
|
39
|
+
}
|
|
40
|
+
to {
|
|
41
|
+
left: 100%;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
// Clearfix
|
|
47
|
+
@mixin clearfix($selector) {
|
|
48
|
+
#{$selector}:before, #{$selector}:after {
|
|
49
|
+
content: '';
|
|
50
|
+
display: table;
|
|
51
|
+
}
|
|
52
|
+
#{$selector}:after {
|
|
53
|
+
clear: both;
|
|
54
|
+
zoom: 1;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Set text overflow with ellipsis
|
|
59
|
+
@mixin ellipsis {
|
|
60
|
+
overflow: hidden;
|
|
61
|
+
text-overflow: ellipsis;
|
|
62
|
+
white-space: nowrap;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
// Flex layout - sass map of flex properties / values
|
|
66
|
+
// Example: @include mixins.flex-layout((flex-flow: row nowrap, align-items: center)) or @include mixins.flex-layout
|
|
67
|
+
// If map is not defined, defaults to display: flex and flex-flow: row wrap
|
|
68
|
+
@mixin flex-layout($map: ()) {
|
|
69
|
+
$flow: map.get($map, 'flex-flow');
|
|
70
|
+
@if $flow {
|
|
71
|
+
flex-flow: $flow;
|
|
72
|
+
} @else {
|
|
73
|
+
flex-flow: row wrap;
|
|
74
|
+
}
|
|
75
|
+
$display: map.get($map, 'display');
|
|
76
|
+
@if $display == flex or $display == inline-flex {
|
|
77
|
+
display: $display;
|
|
78
|
+
} @else {
|
|
79
|
+
display: flex;
|
|
80
|
+
}
|
|
81
|
+
@each $name, $value in $map {
|
|
82
|
+
@if $name == align-content or $name == align-items or $name == justify-content {
|
|
83
|
+
#{$name}: $value;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
// Calculate child width when parent has gap (gap calculates differently when child width is a %)
|
|
89
|
+
@mixin gap-width($gap, $columns) {
|
|
90
|
+
$columns-adjust: $columns - 1;
|
|
91
|
+
width: calc((100% - ($gap * $columns-adjust)) / $columns);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Basic linear gradient
|
|
95
|
+
@mixin gradient($color-03, $color-04, $direction-01, $direction-02) {
|
|
96
|
+
background-color: $color-03;
|
|
97
|
+
background-image: linear-gradient($direction-01, $color-03, $color-04);
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Gradient - generate strips for gradients
|
|
101
|
+
@mixin gradient-stripes($map) {
|
|
102
|
+
// Variables for calculating colors for gradients
|
|
103
|
+
$length: list.length($map);
|
|
104
|
+
$divider: calc(100 / $length);
|
|
105
|
+
$separator: ',';
|
|
106
|
+
|
|
107
|
+
// Gradients string
|
|
108
|
+
$gradients: '';
|
|
109
|
+
$gradients-fallback: '';
|
|
110
|
+
|
|
111
|
+
// Loop through colors and process gradient rule
|
|
112
|
+
@each $color in $map {
|
|
113
|
+
$index: list.index($map, $color) - 1;
|
|
114
|
+
$percentage: if(sass($index == 0): ($index + 1) * $divider; else: $index * $divider);
|
|
115
|
+
@if ($index == 0) {
|
|
116
|
+
$gradients: $gradients + ($color ($percentage * 1%));
|
|
117
|
+
$gradients-fallback: $color;
|
|
118
|
+
} @else {
|
|
119
|
+
$first-color: $separator $color ($percentage * 1%);
|
|
120
|
+
$second-color: if(sass($index == $length - 1): ($separator $color); else: ($separator $color (($percentage + $divider) * 1%)));
|
|
121
|
+
$gradients: $gradients + #{$first-color} + #{$second-color};
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
// CSS rules
|
|
126
|
+
background-color: $gradients-fallback;
|
|
127
|
+
background-image: linear-gradient(#{$gradients});
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
// Grid layout - auto-fill columns that are at least $width wide, with a gap
|
|
131
|
+
// Example: @include mixins.grid-layout(10px, 200px)
|
|
132
|
+
@mixin grid-layout($gap: 5px, $width) {
|
|
133
|
+
display: grid;
|
|
134
|
+
grid-template-columns: repeat(auto-fill, minmax($width, 1fr));
|
|
135
|
+
gap: $gap;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
// Resize icons
|
|
139
|
+
@mixin icon-sizing($size) {
|
|
140
|
+
@if $size {
|
|
141
|
+
@include sizing($size, $size);
|
|
142
|
+
line-height: $size;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
// Line clamp settings
|
|
147
|
+
@mixin line-clamp($lines) {
|
|
148
|
+
display: -webkit-box;
|
|
149
|
+
-webkit-box-orient: vertical;
|
|
150
|
+
overflow: hidden;
|
|
151
|
+
-webkit-line-clamp: $lines;
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
// Image / object fit properties
|
|
155
|
+
@mixin object-fit($position, $fit) {
|
|
156
|
+
object-position: $position;
|
|
157
|
+
object-fit: $fit;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Mixin for positioning
|
|
161
|
+
// Note: arguments left as null aren't output (Sass skips null values), so pass $type: null to only set offsets
|
|
162
|
+
@mixin position($type: absolute, $top: null, $bottom: null, $left: null, $right: null, $inset: null, $z: null) {
|
|
163
|
+
// Check if all four offsets are 0, so they can be set with inset
|
|
164
|
+
$horizontal-equal: ($left == 0 or $left == 0px) and ($right == 0 or $right == 0px);
|
|
165
|
+
$vertical-equal: ($top == 0 or $top == 0px) and ($bottom == 0 or $bottom == 0px);
|
|
166
|
+
|
|
167
|
+
// Set styles
|
|
168
|
+
position: $type;
|
|
169
|
+
@if $inset != null {
|
|
170
|
+
inset: $inset;
|
|
171
|
+
} @else if $horizontal-equal and $vertical-equal {
|
|
172
|
+
inset: 0;
|
|
173
|
+
} @else {
|
|
174
|
+
top: $top;
|
|
175
|
+
bottom: $bottom;
|
|
176
|
+
left: $left;
|
|
177
|
+
right: $right;
|
|
178
|
+
}
|
|
179
|
+
z-index: $z;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
// Absolute positioning to fill area
|
|
183
|
+
@mixin position-fill($margin: auto, $z: null) {
|
|
184
|
+
@include position($inset: 0, $z: $z);
|
|
185
|
+
margin: $margin;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
// Responsive media query rule
|
|
189
|
+
@mixin respond($breakpoint, $rule: 'min-width') {
|
|
190
|
+
$unitValues: 'px' 'cm' 'mm' 'in' 'pt' 'pc' 'dpi' 'dpcm' 'dppx' 'em' 'ex' 'rem' '%' 'vw' 'vh' 'vmin' 'vmax';
|
|
191
|
+
@if not list.index(('min-width', 'max-width'), $rule) {
|
|
192
|
+
@error "respond() $rule must be 'min-width' or 'max-width', got '#{$rule}'.";
|
|
193
|
+
}
|
|
194
|
+
@if list.index($unitValues, math.unit($breakpoint)) == null {
|
|
195
|
+
$breakpoint: $breakpoint + 'px';
|
|
196
|
+
}
|
|
197
|
+
@media only screen and (#{$rule}: $breakpoint) {
|
|
198
|
+
@content;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Scrollbar
|
|
203
|
+
// Note: colors left as null aren't output, and Sass drops the empty track or thumb rule
|
|
204
|
+
@mixin scrollbar($selector, $width, $height, $scrollbar-color-track: null, $scrollbar-color-thumb: null) {
|
|
205
|
+
#{$selector}::-webkit-scrollbar {
|
|
206
|
+
width: $width;
|
|
207
|
+
height: $height;
|
|
208
|
+
}
|
|
209
|
+
#{$selector}::-webkit-scrollbar-track {
|
|
210
|
+
background: $scrollbar-color-track;
|
|
211
|
+
}
|
|
212
|
+
#{$selector}::-webkit-scrollbar-thumb {
|
|
213
|
+
background: $scrollbar-color-thumb;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Quick width and height sizing
|
|
218
|
+
@mixin sizing($width, $height) {
|
|
219
|
+
width: $width;
|
|
220
|
+
height: $height;
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
// Screen reader only (hides elements)
|
|
224
|
+
@mixin sr-only($is-important: false) {
|
|
225
|
+
$important: if(sass($is-important == true): ' !important'; else: '');
|
|
226
|
+
position: absolute#{$important};
|
|
227
|
+
width: 1px#{$important};
|
|
228
|
+
height: 1px#{$important};
|
|
229
|
+
padding: 0#{$important};
|
|
230
|
+
margin: -1px#{$important};
|
|
231
|
+
overflow: hidden#{$important};
|
|
232
|
+
clip: rect(0, 0, 0, 0)#{$important};
|
|
233
|
+
white-space: nowrap#{$important};
|
|
234
|
+
border: 0#{$important};
|
|
235
|
+
}
|
|
236
|
+
|
|
237
|
+
// Text-decoration styles - all
|
|
238
|
+
@mixin text-decoration($thickness: 2px, $offset: 2px, $color: inherit) {
|
|
239
|
+
text-decoration: underline;
|
|
240
|
+
text-decoration-color: $color;
|
|
241
|
+
text-decoration-thickness: $thickness;
|
|
242
|
+
text-underline-offset: $offset;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// For hiding / showing content
|
|
246
|
+
@mixin toggle-content($state, $transition: false) {
|
|
247
|
+
@if $state == collapsed {
|
|
248
|
+
opacity: 0;
|
|
249
|
+
visibility: hidden;
|
|
250
|
+
transform: scaleY(0);
|
|
251
|
+
}
|
|
252
|
+
@if $state == expanded {
|
|
253
|
+
visibility: visible;
|
|
254
|
+
opacity: 1;
|
|
255
|
+
transform: scaleY(1);
|
|
256
|
+
transform-origin: top;
|
|
257
|
+
}
|
|
258
|
+
@if $transition == true {
|
|
259
|
+
$transform-props: transform 0.5s ease-in-out, opacity 0.5s ease-in-out;
|
|
260
|
+
transition: $transform-props;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
// Placeholder
|
|
265
|
+
// Examples: @include mixins.placeholder {}, :focus{ @include mixins.placeholder {} }, or input { @include mixins.placeholder {} }
|
|
266
|
+
// Note: placeholder goes at the bottom because it messes up editor highlighting for any mixin below it
|
|
267
|
+
@mixin placeholder {
|
|
268
|
+
&::placeholder {@content}
|
|
269
|
+
}
|