@charcoal-ui/styled 2.4.0 → 2.6.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.
Files changed (67) hide show
  1. package/dist/SetThemeScript.d.ts +20 -20
  2. package/dist/TokenInjector.d.ts +12 -12
  3. package/dist/TokenInjector.d.ts.map +1 -1
  4. package/dist/builders/border.d.ts +10 -0
  5. package/dist/builders/border.d.ts.map +1 -0
  6. package/dist/builders/borderRadius.d.ts +7 -0
  7. package/dist/builders/borderRadius.d.ts.map +1 -0
  8. package/dist/builders/colors.d.ts +13 -0
  9. package/dist/builders/colors.d.ts.map +1 -0
  10. package/dist/builders/elementEffect.d.ts +7 -0
  11. package/dist/builders/elementEffect.d.ts.map +1 -0
  12. package/dist/builders/o.d.ts +114 -0
  13. package/dist/builders/o.d.ts.map +1 -0
  14. package/dist/builders/outline.d.ts +10 -0
  15. package/dist/builders/outline.d.ts.map +1 -0
  16. package/dist/builders/size.d.ts +23 -0
  17. package/dist/builders/size.d.ts.map +1 -0
  18. package/dist/builders/spacing.d.ts +15 -0
  19. package/dist/builders/spacing.d.ts.map +1 -0
  20. package/dist/builders/transition.d.ts +7 -0
  21. package/dist/builders/transition.d.ts.map +1 -0
  22. package/dist/builders/typography.d.ts +11 -0
  23. package/dist/builders/typography.d.ts.map +1 -0
  24. package/dist/defineThemeVariables.test.d.ts +1 -1
  25. package/dist/{lib.d.ts → factories/lib.d.ts} +88 -89
  26. package/dist/factories/lib.d.ts.map +1 -0
  27. package/dist/helper.d.ts +38 -38
  28. package/dist/helper.d.ts.map +1 -1
  29. package/dist/index.cjs.js +918 -0
  30. package/dist/index.cjs.js.map +1 -0
  31. package/dist/index.d.ts +128 -67
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.esm.js +886 -0
  34. package/dist/index.esm.js.map +1 -0
  35. package/dist/index.story.d.ts +25 -24
  36. package/dist/index.story.d.ts.map +1 -1
  37. package/dist/index.test.d.ts +2 -0
  38. package/dist/index.test.d.ts.map +1 -0
  39. package/dist/internals/index.d.ts +42 -0
  40. package/dist/internals/index.d.ts.map +1 -0
  41. package/dist/util.d.ts +100 -66
  42. package/dist/util.d.ts.map +1 -1
  43. package/package.json +19 -16
  44. package/src/__snapshots__/index.test.tsx.snap +768 -0
  45. package/src/builders/border.ts +63 -0
  46. package/src/builders/borderRadius.ts +32 -0
  47. package/src/builders/colors.ts +198 -0
  48. package/src/builders/elementEffect.ts +54 -0
  49. package/src/builders/o.ts +36 -0
  50. package/src/builders/outline.ts +79 -0
  51. package/src/builders/size.ts +61 -0
  52. package/src/builders/spacing.ts +113 -0
  53. package/src/builders/transition.ts +32 -0
  54. package/src/builders/typography.ts +97 -0
  55. package/src/{lib.ts → factories/lib.ts} +30 -25
  56. package/src/index.story.tsx +2 -2
  57. package/src/index.test.tsx +24 -0
  58. package/src/index.ts +36 -696
  59. package/src/internals/index.ts +84 -0
  60. package/src/util.ts +46 -3
  61. package/dist/index.cjs +0 -1051
  62. package/dist/index.cjs.map +0 -1
  63. package/dist/index.modern.js +0 -826
  64. package/dist/index.modern.js.map +0 -1
  65. package/dist/index.module.js +0 -1034
  66. package/dist/index.module.js.map +0 -1
  67. package/dist/lib.d.ts.map +0 -1
@@ -1,1034 +0,0 @@
1
- import warning from 'warning';
2
- import { filterObject, flatMapObject, customPropertyToken, applyEffect, dur, gradient, applyEffectToGradient, notDisabledSelector, halfLeading, px, disabledSelector } from '@charcoal-ui/utils';
3
- import { columnSystem } from '@charcoal-ui/foundation';
4
- import React, { useEffect, useState, useMemo } from 'react';
5
- import { createGlobalStyle, css } from 'styled-components';
6
-
7
- function _extends() {
8
- _extends = Object.assign ? Object.assign.bind() : function (target) {
9
- for (var i = 1; i < arguments.length; i++) {
10
- var source = arguments[i];
11
-
12
- for (var key in source) {
13
- if (Object.prototype.hasOwnProperty.call(source, key)) {
14
- target[key] = source[key];
15
- }
16
- }
17
- }
18
-
19
- return target;
20
- };
21
- return _extends.apply(this, arguments);
22
- }
23
-
24
- function _taggedTemplateLiteralLoose(strings, raw) {
25
- if (!raw) {
26
- raw = strings.slice(0);
27
- }
28
-
29
- strings.raw = raw;
30
- return strings;
31
- }
32
-
33
- function unreachable(value) {
34
- throw new Error(arguments.length === 0 ? 'unreachable' : "unreachable (" + JSON.stringify(value) + ")");
35
- }
36
- /**
37
- * Check whether a value is non-null and non-undefined
38
- *
39
- * @param value nullable
40
- */
41
-
42
- var isPresent = function isPresent(value) {
43
- return value != null;
44
- }; // eslint-disable-next-line @typescript-eslint/no-explicit-any
45
-
46
- function objectAssign() {
47
- return Object.assign.apply(Object, [{}].concat([].slice.call(arguments)));
48
- }
49
- function objectKeys(obj) {
50
- return Object.keys(obj);
51
- }
52
- var noThemeProvider = new Error('`theme` is invalid. `<ThemeProvider>` is not likely mounted.');
53
- /**
54
- * 子孫要素で使われるカラーテーマの CSS Variables を上書きする
55
- *
56
- * @params colorParams - 上書きしたい色の定義( `theme.color` の一部だけ書けば良い )
57
- * @params effectParams - effect の定義を上書きしたい場合は渡す(必須ではない)
58
- *
59
- * @example
60
- * ```tsx
61
- * const LocalTheme = styled.div`
62
- * ${defineThemeVariables({ text1: '#ff0000' })}
63
- * // `text1` is now defined as red
64
- * ${theme((o) => [o.font.text1])}
65
- * `
66
- * ```
67
- */
68
-
69
- function defineThemeVariables(colorParams, effectParams) {
70
- return function toCssObject(props) {
71
- if (!isPresent(props.theme)) {
72
- throw noThemeProvider;
73
- }
74
-
75
- var colors = filterObject(colorParams, isPresent); // flatMapObject の中で毎回 Object.entries を呼ぶのは無駄なので外で呼ぶ
76
-
77
- var effects = Object.entries(_extends({}, props.theme.effect, effectParams));
78
- return flatMapObject(colors, function (colorKey, color) {
79
- return [[customPropertyToken(colorKey), color]].concat(effects.map(function (_ref3) {
80
- var effectKey = _ref3[0],
81
- effect = _ref3[1];
82
- return [customPropertyToken(colorKey, [effectKey]), applyEffect(color, [effect])];
83
- }));
84
- });
85
- };
86
- }
87
-
88
- /**
89
- * 配列で指定したプロパティを動的に生やす
90
- *
91
- * @param source 拡張するオブジェクト
92
- * @param member オブジェクトに生やすプロパティ一覧
93
- * @param chain プロパティに格納される値を生成する関数
94
- *
95
- * @example
96
- *
97
- * const o = factory({}, ['red', 'blue'],
98
- * color => hex(color)
99
- * )
100
- *
101
- * console.log(o.red) //=> #ff0000
102
- */
103
-
104
- var factory = function factory(source, member, chain) {
105
- return Object.defineProperties(source, Object.fromEntries(member.map(function (key) {
106
- return [key, {
107
- get: function get() {
108
- return chain(key);
109
- },
110
- enumerable: true,
111
- configurable: true
112
- }];
113
- })));
114
- };
115
- /**
116
- * 配列で指定した名前のメソッドを動的に生やす
117
- *
118
- * @param source 拡張するオブジェクト
119
- * @param member オブジェクトに生やすメソッド名一覧
120
- * @param chain メソッドの戻り値になる値を生成する関数
121
- *
122
- * @example
123
- *
124
- * const o = argumentedFactory({}, ['red', 'blue'],
125
- * (color, alpha: number) => hex(color, alpha)
126
- * )
127
- *
128
- * console.log(o.red(0.5)) //=> #ff000077
129
- */
130
-
131
- var argumentedFactory = function argumentedFactory(source, member, chain) {
132
- return Object.defineProperties(source, Object.fromEntries(member.map(function (key) {
133
- return [key, {
134
- value: function value() {
135
- return chain.apply(void 0, [key].concat([].slice.call(arguments)));
136
- },
137
- enumerable: true,
138
- configurable: true
139
- }];
140
- })));
141
- };
142
- /**
143
- * オブジェクトで指定したプロパティ名と値を動的に生やす
144
- *
145
- * @param source 拡張するオブジェクト
146
- * @param def オブジェクトに生やす定義(プロパティ名と値)
147
- *
148
- * @example
149
- *
150
- * const o = constFactory({}, {
151
- * red: '#f00',
152
- * blue: '#00f',
153
- * })
154
- *
155
- * console.log(o.red) //=> #f00
156
- */
157
-
158
- var constFactory = function constFactory(source, def) {
159
- return factory(source, Object.keys(def), function (key) {
160
- return def[key];
161
- });
162
- };
163
- /**
164
- * 配列で指定したモディファイア(プロパティ)をチェーン可能な再帰オブジェクトを動的に生やす
165
- *
166
- * @param modifiers オブジェクトに生やすモディファイヤ一覧
167
- * @param source 指定されたモディファイヤの一覧から値を生成する関数
168
- *
169
- * @example
170
- *
171
- * const o = modifiedArgumentedFactory(['red', 'blue'],
172
- * modifiers => modifiers.map(color => hex(color)).join(',')
173
- * )
174
- *
175
- * console.log(o.red.blue) => #f00,#00f
176
- */
177
-
178
- var modifiedFactory = function modifiedFactory(modifiers, source) {
179
- return function recursiveModifiedFactory(applied) {
180
- var notApplied = modifiers.filter(function (v) {
181
- return !applied.includes(v);
182
- });
183
- return factory(source(applied), notApplied, function (modifier) {
184
- return notApplied.length === 0 ? unreachable() : recursiveModifiedFactory([].concat(applied, [modifier]));
185
- });
186
- }([]);
187
- };
188
- /**
189
- * 配列で指定したモディファイア(メソッド)をチェーン可能な再帰オブジェクトを動的に生やす
190
- *
191
- * @param modifiers オブジェクトに生やすモディファイヤ一覧
192
- * @param source 指定されたモディファイヤの一覧から値を生成する関数
193
- * @param _inferPhantom 関数形式のモディファイヤの引数型を推論するためのメタタイプ(引数の個数に合わせてタプルで指定する)
194
- *
195
- * @example
196
- *
197
- * const o = modifiedArgumentedFactory(['red', 'blue'],
198
- * modifiers => modifiers.map(([color, alpha]) => hex(color, alpha)).join(',')
199
- * , {} as [number])
200
- *
201
- * console.log(o.red(0.5).blue(1)) => #ff000077,#0000ffff
202
- */
203
-
204
- var modifiedArgumentedFactory = function modifiedArgumentedFactory(modifiers, source) {
205
- return function recursiveModifiedFactory(applied) {
206
- var notApplied = modifiers.filter(function (v) {
207
- return !applied.map(function (_ref) {
208
- var w = _ref[0];
209
- return w;
210
- }).includes(v);
211
- });
212
- return argumentedFactory(source(applied), notApplied, function (modifier) {
213
- return notApplied.length === 0 ? unreachable() : recursiveModifiedFactory([].concat(applied, [[modifier].concat([].slice.call(arguments, 1))]));
214
- });
215
- }([]);
216
- };
217
- var variable = function variable(value) {
218
- return "var(" + value + ")";
219
- };
220
-
221
- var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5;
222
- var GlobalStyle = createGlobalStyle(_templateObject || (_templateObject = _taggedTemplateLiteralLoose(["\n ", "\n"])), function (_ref) {
223
- var themeMap = _ref.themeMap,
224
- background = _ref.background;
225
- return Object.entries(themeMap).map(function (_ref2) {
226
- var key = _ref2[0],
227
- theme = _ref2[1];
228
- return key.startsWith('@media') ? css(_templateObject2 || (_templateObject2 = _taggedTemplateLiteralLoose(["\n ", " {\n :root {\n ", "\n ", "\n }\n }\n "])), key, background !== undefined && css(_templateObject3 || (_templateObject3 = _taggedTemplateLiteralLoose(["\n background-color: ", ";\n "])), theme.color[background]), defineColorVariableCSS(theme)) : css(_templateObject4 || (_templateObject4 = _taggedTemplateLiteralLoose(["\n /* stylelint-disable-next-line no-duplicate-selectors */\n ", " {\n ", "\n ", "\n }\n "])), key, background !== undefined && css(_templateObject5 || (_templateObject5 = _taggedTemplateLiteralLoose(["\n background-color: ", ";\n "])), theme.color[background]), defineColorVariableCSS(theme));
229
- });
230
- });
231
- function TokenInjector(_ref3) {
232
- var themeMap = _ref3.theme,
233
- background = _ref3.background;
234
- return /*#__PURE__*/React.createElement(GlobalStyle, {
235
- themeMap: themeMap,
236
- background: background
237
- });
238
- }
239
-
240
- var defineColorVariableCSS = function defineColorVariableCSS(theme) {
241
- return Object.entries(defineThemeVariables(theme.color)({
242
- theme: theme
243
- })).map(function (_ref4) {
244
- var varName = _ref4[0],
245
- value = _ref4[1];
246
- return variableDefinition(varName, value.toString());
247
- }).join(';');
248
- };
249
-
250
- var variableDefinition = function variableDefinition(prop, value) {
251
- return prop + ": " + value;
252
- };
253
-
254
- var LOCAL_STORAGE_KEY = 'charcoal-theme';
255
- var DEFAULT_ROOT_ATTRIBUTE = 'theme';
256
- var keyStringRegExp = new RegExp(/^(\w|-)+$/);
257
- /**
258
- * 文字列が英数字_-のみで構成されているか検証する。不正な文字列ならエラーを投げる
259
- * @param key 検証するキー
260
- */
261
-
262
- function assertKeyString(key) {
263
- if (!keyStringRegExp.test(key)) {
264
- throw new Error("Unexpected key :" + key + ", expect: /^(\\w|-)+$/");
265
- }
266
- }
267
- /**
268
- * `<html data-theme="dark">` のような設定を行うデフォルトのセッター
269
- */
270
-
271
- var themeSetter = function themeSetter(attr) {
272
- if (attr === void 0) {
273
- attr = DEFAULT_ROOT_ATTRIBUTE;
274
- }
275
-
276
- return function (theme) {
277
- assertKeyString(attr);
278
-
279
- if (theme !== undefined) {
280
- document.documentElement.dataset[attr] = theme;
281
- } else {
282
- delete document.documentElement.dataset[attr];
283
- }
284
- };
285
- };
286
- /**
287
- * `<html data-theme="dark">` にマッチするセレクタを生成する
288
- */
289
-
290
- function themeSelector(theme, attr) {
291
- return ":root[data-" + (attr != null ? attr : DEFAULT_ROOT_ATTRIBUTE) + "='" + theme + "']";
292
- }
293
- /**
294
- * prefers-color-scheme を利用する media クエリを生成する
295
- */
296
-
297
- function prefersColorScheme(theme) {
298
- return "@media (prefers-color-scheme: " + theme + ")";
299
- }
300
- /**
301
- * LocalStorageからテーマの情報を取得して、変化時にテーマをセットするhooks
302
- */
303
-
304
- function useThemeSetter(_temp) {
305
- var _ref = _temp === void 0 ? {} : _temp,
306
- _ref$key = _ref.key,
307
- key = _ref$key === void 0 ? LOCAL_STORAGE_KEY : _ref$key,
308
- _ref$setter = _ref.setter,
309
- setter = _ref$setter === void 0 ? themeSetter() : _ref$setter;
310
-
311
- var _useTheme = useTheme(key),
312
- theme = _useTheme[0],
313
- system = _useTheme[2];
314
-
315
- useEffect(function () {
316
- if (theme === undefined) {
317
- return;
318
- } // prefers-color-scheme から値を取っている場合にはcssのみで処理したいのでアンセットする
319
-
320
-
321
- setter(system ? undefined : theme);
322
- }, [setter, system, theme]);
323
- }
324
- /**
325
- * 同期的にLocalStorageからテーマを取得するヘルパ
326
- */
327
-
328
- function getThemeSync(key) {
329
- if (key === void 0) {
330
- key = LOCAL_STORAGE_KEY;
331
- }
332
-
333
- var theme = localStorage.getItem(key);
334
- return theme;
335
- }
336
- /**
337
- * LocalStorage, prefers-color-scheme からテーマの情報を取得して、現在のテーマを返すhooks
338
- *
339
- * `dark` `light` という名前だけは特別扱いされていて、prefers-color-schemeにマッチした場合に返ります
340
- */
341
-
342
- var useTheme = function useTheme(key) {
343
- if (key === void 0) {
344
- key = LOCAL_STORAGE_KEY;
345
- }
346
-
347
- assertKeyString(key);
348
- var isDark = useMedia('(prefers-color-scheme: dark)');
349
- var media = isDark !== undefined ? isDark ? 'dark' : 'light' : undefined;
350
-
351
- var _useLocalStorage = useLocalStorage(key),
352
- local = _useLocalStorage[0],
353
- setTheme = _useLocalStorage[1],
354
- ready = _useLocalStorage[2];
355
-
356
- var theme = !ready || media === undefined ? undefined : local != null ? local : media;
357
- var system = local === undefined;
358
- return [theme, setTheme, system];
359
- };
360
- function useLocalStorage(key, defaultValue) {
361
- var _useState = useState(false),
362
- ready = _useState[0],
363
- setReady = _useState[1];
364
-
365
- var _useState2 = useState(),
366
- state = _useState2[0],
367
- setState = _useState2[1];
368
-
369
- var defaultValueMemo = useMemo(function () {
370
- return defaultValue == null ? void 0 : defaultValue();
371
- }, [defaultValue]);
372
- useEffect(function () {
373
- fetch();
374
- window.addEventListener('storage', handleStorage);
375
- return function () {
376
- window.removeEventListener('storage', handleStorage);
377
- };
378
- });
379
-
380
- var handleStorage = function handleStorage(e) {
381
- if (e.storageArea !== localStorage) {
382
- return;
383
- }
384
-
385
- if (e.key !== key) {
386
- return;
387
- }
388
-
389
- fetch();
390
- };
391
-
392
- var fetch = function fetch() {
393
- var _ref2;
394
-
395
- var raw = localStorage.getItem(key);
396
- setState((_ref2 = raw !== null ? deserialize(raw) : null) != null ? _ref2 : defaultValueMemo);
397
- setReady(true);
398
- };
399
-
400
- var set = function set(value) {
401
- if (value === undefined) {
402
- // undefinedがセットされる場合にはkeyごと削除
403
- localStorage.removeItem(key);
404
- } else {
405
- var raw = serialize(value);
406
- localStorage.setItem(key, raw);
407
- } // 同一ウィンドウではstorageイベントが発火しないので、手動で発火させる
408
-
409
-
410
- var event = new StorageEvent('storage', {
411
- bubbles: true,
412
- cancelable: false,
413
- key: key,
414
- url: location.href,
415
- storageArea: localStorage
416
- });
417
- dispatchEvent(event);
418
- };
419
-
420
- return [state != null ? state : defaultValueMemo, set, ready];
421
- }
422
-
423
- function deserialize(raw) {
424
- try {
425
- return JSON.parse(raw);
426
- } catch (_unused) {
427
- // syntax error はすべて文字列として扱う
428
- return raw;
429
- }
430
- }
431
-
432
- function serialize(value) {
433
- if (typeof value === 'string') {
434
- return value;
435
- } else {
436
- return JSON.stringify(value);
437
- }
438
- }
439
-
440
- function useMedia(query) {
441
- var _useState3 = useState(),
442
- match = _useState3[0],
443
- setState = _useState3[1];
444
-
445
- useEffect(function () {
446
- var matcher = window.matchMedia(query);
447
-
448
- var onChange = function onChange() {
449
- setState(matcher.matches);
450
- };
451
-
452
- matcher.addEventListener('change', onChange);
453
- setState(matcher.matches);
454
- return function () {
455
- matcher.removeEventListener('change', onChange);
456
- };
457
- }, [query]);
458
- return match;
459
- }
460
-
461
- /**
462
- * 同期的にテーマをローカルストレージから取得してhtmlの属性に設定するコードを取得する
463
- * @param props localStorageのキー、htmlのdataになる属性のキーを含むオブジェクト
464
- * @returns ソースコードの文字列
465
- */
466
-
467
- function makeSetThemeScriptCode(_temp) {
468
- var _ref = _temp === void 0 ? defaultProps : _temp,
469
- _ref$localStorageKey = _ref.localStorageKey,
470
- localStorageKey = _ref$localStorageKey === void 0 ? defaultProps.localStorageKey : _ref$localStorageKey,
471
- _ref$rootAttribute = _ref.rootAttribute,
472
- rootAttribute = _ref$rootAttribute === void 0 ? defaultProps.rootAttribute : _ref$rootAttribute;
473
-
474
- assertKeyString(localStorageKey);
475
- assertKeyString(rootAttribute);
476
- return "'use strict';\n(function () {\n var localStorageKey = '" + localStorageKey + "'\n var rootAttribute = '" + rootAttribute + "'\n var currentTheme = localStorage.getItem(localStorageKey);\n if (currentTheme) {\n document.documentElement.dataset[rootAttribute] = currentTheme;\n }\n})();\n";
477
- }
478
- /**
479
- * 同期的にテーマをローカルストレージから取得してhtmlの属性に設定するスクリプトタグ
480
- * @param props localStorageのキー、htmlのdataになる属性のキーを含むオブジェクト
481
- * @returns
482
- */
483
-
484
- function SetThemeScript(props) {
485
- var src = makeSetThemeScriptCode(props);
486
- return /*#__PURE__*/React.createElement("script", {
487
- dangerouslySetInnerHTML: {
488
- __html: src
489
- }
490
- });
491
- }
492
- var defaultProps = {
493
- localStorageKey: LOCAL_STORAGE_KEY,
494
- rootAttribute: DEFAULT_ROOT_ATTRIBUTE
495
- };
496
- SetThemeScript.defaultProps = defaultProps;
497
-
498
- var spacingProperties = ['margin', 'padding'];
499
- var spacingDirections = ['top', 'right', 'bottom', 'left', 'vertical', 'horizontal', 'all'];
500
- var fixedProperties = ['width', 'height'];
501
- var borderDirections = ['top', 'right', 'bottom', 'left'];
502
- var outlineType = ['focus'];
503
- /**
504
- * `theme(o => [...])` の `o` の部分を構築する
505
- *
506
- * @param theme テーマオブジェクト
507
- * @param isPhantom 型推論のためだけに使う場合にランタイムコストをゼロにするフラグ
508
- */
509
-
510
- function builder(theme, isPhantom) {
511
- if (isPhantom === void 0) {
512
- isPhantom = false;
513
- }
514
-
515
- if (isPhantom) {
516
- // eslint-disable-next-line @typescript-eslint/consistent-type-assertions
517
- return {};
518
- }
519
-
520
- var colors = objectKeys(theme.color);
521
- var effects = objectKeys(theme.effect); // 色
522
-
523
- var gradientColors = objectKeys(theme.gradientColor);
524
- var colorCss = createColorCss();
525
- var gradientColorCss = createGradientColorCss(theme);
526
- var colorObject = constFactory({}, {
527
- bg: objectAssign(factory({}, colors, function (color) {
528
- return modifiedFactory(effects, function (modifiers) {
529
- return colorCss('bg', color, modifiers);
530
- });
531
- }), factory({}, gradientColors, function (color) {
532
- return function (direction) {
533
- return modifiedFactory(effects, function (modifiers) {
534
- return gradientColorCss(color, modifiers, direction);
535
- });
536
- };
537
- })),
538
- font: factory({}, colors, function (color) {
539
- return modifiedFactory(effects, function (modifiers) {
540
- return colorCss('font', color, modifiers);
541
- });
542
- })
543
- }); // タイポグラフィ
544
-
545
- var typographyModifiers = [// TODO
546
- 'monospace', 'bold', 'preserveHalfLeading'];
547
- var typographyCss = createTypographyCss(theme);
548
- var typographyObject = factory({}, ['typography'], function (_) {
549
- return function (size) {
550
- return modifiedFactory(typographyModifiers, function (modifiers) {
551
- return typographyCss(size, {
552
- preserveHalfLeading: modifiers.includes('preserveHalfLeading'),
553
- monospace: modifiers.includes('monospace'),
554
- bold: modifiers.includes('bold')
555
- });
556
- });
557
- };
558
- }); // スペーシング
559
-
560
- var spacingCss = createSpacingCss(theme);
561
- var spacingObject = factory({}, spacingProperties, function (spacingProperty) {
562
- return modifiedArgumentedFactory(spacingDirections, function (modifiers) {
563
- return spacingCss(spacingProperty, modifiers);
564
- });
565
- }); // 大きさ
566
-
567
- var fixedPxCss = createFixedPxCss(theme);
568
- var fixedColumnCss = createFixedColumnCss(theme);
569
- var fixedRelativeCss = createFixedRelativeCss();
570
- var fixedObject = factory({}, fixedProperties, function (property) {
571
- return constFactory({}, {
572
- px: function px(size) {
573
- return fixedPxCss(property, size);
574
- },
575
- column: function column(span) {
576
- return fixedColumnCss(property, span);
577
- },
578
- auto: fixedRelativeCss(property, 'auto'),
579
- full: fixedRelativeCss(property, '100%')
580
- });
581
- }); // 要素へのエフェクト (etc: 透過)
582
-
583
- var elementEffectCss = createElementEffectCss(theme);
584
- var elementEffectObject = modifiedFactory(objectKeys(theme.elementEffect), function (modifiers) {
585
- return elementEffectCss(modifiers);
586
- }); // ボーダー
587
-
588
- var borderCss = createBorderCss(theme);
589
- var borderObject = constFactory({}, {
590
- border: factory({}, objectKeys(theme.border), function (variant) {
591
- return modifiedFactory(borderDirections, function (modifiers) {
592
- return borderCss(variant, modifiers);
593
- });
594
- })
595
- }); // 角丸
596
-
597
- var borderRadiusCss = createBorderRadiusCss(theme);
598
- var borderRadiusObject = constFactory({}, {
599
- borderRadius: function borderRadius(radius) {
600
- return borderRadiusCss(radius);
601
- }
602
- }); // アウトライン
603
-
604
- var outlineCss = createOutlineColorCss(theme);
605
- var outlineObject = constFactory({}, {
606
- outline: factory({}, objectKeys(theme.outline), function (variant) {
607
- return modifiedFactory(outlineType, function (modifiers) {
608
- return outlineCss(variant, modifiers);
609
- });
610
- })
611
- });
612
- return objectAssign(colorObject, typographyObject, spacingObject, fixedObject, elementEffectObject, borderObject, borderRadiusObject, outlineObject);
613
- }
614
-
615
- function targetProperty(target) {
616
- return target === 'bg' ? 'background-color' : 'color';
617
- }
618
-
619
- function isSupportedEffect(effect) {
620
- return ['hover', 'press', 'disabled'].includes(effect);
621
- }
622
-
623
- function onEffectPseudo(effect, css) {
624
- var _hover, _active, _ref;
625
-
626
- return effect === 'hover' ? {
627
- '&:hover': (_hover = {}, _hover[notDisabledSelector] = css, _hover)
628
- } : effect === 'press' ? {
629
- '&:active': (_active = {}, _active[notDisabledSelector] = css, _active)
630
- } : // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
631
- effect === 'disabled' ? (_ref = {}, _ref[disabledSelector] = css, _ref) : unreachable(effect);
632
- }
633
-
634
- var createColorCss = function createColorCss(_theme) {
635
- return function (target, color, effects) {
636
- if (effects === void 0) {
637
- effects = [];
638
- }
639
-
640
- return internal(function () {
641
- var _extends2;
642
-
643
- return _extends((_extends2 = {}, _extends2[targetProperty(target)] = variable(customPropertyToken(color.toString())), _extends2), effects.filter(isSupportedEffect).reduce(function (acc, effect) {
644
- var _onEffectPseudo;
645
-
646
- return _extends({}, acc, onEffectPseudo(effect, (_onEffectPseudo = {}, _onEffectPseudo[targetProperty(target)] = variable(customPropertyToken(color.toString(), [effect])), _onEffectPseudo)));
647
- }, {}));
648
- }, effects.length > 0 ? target === 'font' ? {
649
- colorTransition: true
650
- } : {
651
- backgroundColorTransition: true
652
- } : {});
653
- };
654
- }; // TODO: deprecate
655
-
656
-
657
- var TRANSITION_DURATION = 0.2;
658
-
659
- var createGradientColorCss = function createGradientColorCss(theme) {
660
- return function (color, effects, direction) {
661
- if (effects === void 0) {
662
- effects = [];
663
- }
664
-
665
- var toLinearGradient = gradient(direction);
666
- return internal(function (context) {
667
- var optimized = !useHalfLeadingCanceller(context);
668
- var duration = dur(TRANSITION_DURATION);
669
-
670
- if (optimized && effects.length > 0) {
671
- return _extends({
672
- position: 'relative',
673
- zIndex: 0,
674
- overflow: 'hidden'
675
- }, effects.filter(isSupportedEffect).reduce(function (acc, effect) {
676
- var _theme$effect$effect;
677
-
678
- return _extends({}, acc, {
679
- '&::before': _extends({
680
- zIndex: -1
681
- }, overlayElement, {
682
- transition: duration + " background-color"
683
- }),
684
- '&::after': _extends({
685
- zIndex: -2
686
- }, overlayElement, toLinearGradient(theme.gradientColor[color]))
687
- }, onEffectPseudo(effect, {
688
- '&::before': {
689
- backgroundColor: applyEffect(null, (_theme$effect$effect = theme.effect[effect]) != null ? _theme$effect$effect : [])
690
- }
691
- }));
692
- }, {}));
693
- } else {
694
- warning(effects.length === 0, // eslint-disable-next-line max-len
695
- "'Transition' will not be applied. You can get around this by specifying 'preserveHalfLeading' or both 'padding' and 'typograpy'.");
696
- return _extends({}, toLinearGradient(theme.gradientColor[color]), effects.filter(isSupportedEffect).reduce(function (acc, effect) {
697
- var _theme$effect$effect2;
698
-
699
- return _extends({}, acc, onEffectPseudo(effect, _extends({}, toLinearGradient(applyEffectToGradient((_theme$effect$effect2 = theme.effect[effect]) != null ? _theme$effect$effect2 : [])(theme.gradientColor[color])))));
700
- }, {}));
701
- }
702
- });
703
- };
704
- };
705
- /**
706
- * @see https://developer.mozilla.org/ja/docs/Web/CSS/:focus-visible#selectively_showing_the_focus_indicator
707
- */
708
-
709
-
710
- var onFocus = function onFocus(css) {
711
- var _ref2;
712
-
713
- return _ref2 = {}, _ref2[notDisabledSelector] = {
714
- '&:focus, &:active': _extends({
715
- outline: 'none'
716
- }, css),
717
- '&:focus:not(:focus-visible), &:active:not(:focus-visible)': {
718
- outline: 'none'
719
- },
720
- '&:focus-visible': _extends({
721
- outline: 'none'
722
- }, css)
723
- }, _ref2;
724
- };
725
-
726
- var outlineCss = function outlineCss(weight, color) {
727
- return {
728
- boxShadow: "0 0 0 " + px(weight) + " " + color
729
- };
730
- };
731
-
732
- var createOutlineColorCss = function createOutlineColorCss(theme) {
733
- return function (variant, modifiers) {
734
- var weight = theme.outline[variant].weight;
735
- var color = theme.outline[variant].color;
736
- return internal(function () {
737
- var _2;
738
-
739
- return modifiers.includes('focus') ? onFocus(outlineCss(weight, color)) : {
740
- '&&': (_2 = {}, _2[notDisabledSelector] = outlineCss(weight, color), _2)
741
- };
742
- }, {
743
- boxShadowTransition: true
744
- });
745
- };
746
- };
747
-
748
- var overlayElement = {
749
- content: "''",
750
- display: 'block',
751
- position: 'absolute',
752
- width: '100%',
753
- height: '100%',
754
- top: 0,
755
- left: 0
756
- }; // half-leadingをキャンセルするとき && 垂直方向のpaddingが無い時
757
- // -> before/afterを入れる
758
-
759
- var useHalfLeadingCanceller = function useHalfLeadingCanceller(_ref3) {
760
- var cancelHalfLeadingPx = _ref3.cancelHalfLeadingPx,
761
- _ref3$hasVerticalPadd = _ref3.hasVerticalPadding,
762
- hasVerticalPadding = _ref3$hasVerticalPadd === void 0 ? false : _ref3$hasVerticalPadd;
763
- return cancelHalfLeadingPx !== undefined && !hasVerticalPadding;
764
- };
765
-
766
- var createTypographyCss = function createTypographyCss(theme) {
767
- return function (size, options) {
768
- if (options === void 0) {
769
- options = {};
770
- }
771
-
772
- var _options = options,
773
- _options$preserveHalf = _options.preserveHalfLeading,
774
- preserveHalfLeading = _options$preserveHalf === void 0 ? false : _options$preserveHalf,
775
- _options$monospace = _options.monospace,
776
- monospace = _options$monospace === void 0 ? false : _options$monospace,
777
- _options$bold = _options.bold,
778
- bold = _options$bold === void 0 ? false : _options$bold;
779
- var descriptor = theme.typography.size[size];
780
- var margin = -halfLeading(descriptor);
781
- return internal(function (context) {
782
- return _extends({
783
- fontSize: px(descriptor.fontSize),
784
- lineHeight: px(descriptor.lineHeight)
785
- }, monospace && {
786
- fontFamily: 'monospace'
787
- }, bold && {
788
- fontWeight: 'bold'
789
- }, useHalfLeadingCanceller(context) && {
790
- // prevent margin collapsing
791
- display: 'flow-root',
792
- // cancel half-leading with negative margin
793
- '&::before': _extends({}, leadingCancel, {
794
- marginTop: px(margin)
795
- }),
796
- '&::after': _extends({}, leadingCancel, {
797
- marginBottom: px(margin)
798
- })
799
- });
800
- }, !preserveHalfLeading ? {
801
- cancelHalfLeadingPx: margin
802
- } : {});
803
- };
804
- };
805
-
806
- var leadingCancel = {
807
- display: 'block',
808
- width: 0,
809
- height: 0,
810
- content: "''"
811
- };
812
-
813
- function spacingProperty(property, direction) {
814
- return property + "-" + direction;
815
- }
816
-
817
- var createSpacingCss = function createSpacingCss(theme) {
818
- return function (property, modifiers) {
819
- var _modifiers$reduce = modifiers.reduce(function (acc, _ref4) {
820
- var direction = _ref4[0],
821
- size = _ref4[1];
822
-
823
- if (direction === 'all') {
824
- acc.top = size;
825
- acc.right = size;
826
- acc.bottom = size;
827
- acc.left = size;
828
- } else if (direction === 'vertical') {
829
- acc.top = size;
830
- acc.bottom = size;
831
- } else if (direction === 'horizontal') {
832
- acc.right = size;
833
- acc.left = size;
834
- } else {
835
- acc[direction] = size;
836
- }
837
-
838
- return acc;
839
- }, {}),
840
- top = _modifiers$reduce.top,
841
- right = _modifiers$reduce.right,
842
- bottom = _modifiers$reduce.bottom,
843
- left = _modifiers$reduce.left;
844
-
845
- var hasVerticalPadding = property === 'padding' && top !== undefined && bottom !== undefined && top !== 'auto' && bottom !== 'auto';
846
- return internal(function (_ref5) {
847
- var _ref6, _ref7, _ref8, _ref9;
848
-
849
- var _ref5$cancelHalfLeadi = _ref5.cancelHalfLeadingPx,
850
- cancelHalfLeadingPx = _ref5$cancelHalfLeadi === void 0 ? 0 : _ref5$cancelHalfLeadi;
851
- return _extends({}, top !== undefined && (_ref6 = {}, _ref6[spacingProperty(property, 'top')] = top === 'auto' ? 'auto' : px(theme.spacing[top] + (hasVerticalPadding ? cancelHalfLeadingPx : 0)), _ref6), bottom !== undefined && (_ref7 = {}, _ref7[spacingProperty(property, 'bottom')] = bottom === 'auto' ? 'auto' : px(theme.spacing[bottom] + (hasVerticalPadding ? cancelHalfLeadingPx : 0)), _ref7), right !== undefined && (_ref8 = {}, _ref8[spacingProperty(property, 'right')] = right === 'auto' ? 'auto' : px(theme.spacing[right]), _ref8), left !== undefined && (_ref9 = {}, _ref9[spacingProperty(property, 'left')] = left === 'auto' ? 'auto' : px(theme.spacing[left]), _ref9));
852
- }, hasVerticalPadding ? {
853
- hasVerticalPadding: true
854
- } : {});
855
- };
856
- };
857
-
858
- var createFixedPxCss = function createFixedPxCss(theme) {
859
- return function (property, size) {
860
- return internal(function () {
861
- var _ref10;
862
-
863
- return _ref10 = {}, _ref10[property] = size === 'auto' ? 'auto' : px(theme.spacing[size]), _ref10;
864
- });
865
- };
866
- };
867
-
868
- var createFixedRelativeCss = function createFixedRelativeCss(_theme) {
869
- return function (property, amount) {
870
- return internal(function () {
871
- var _ref11;
872
-
873
- return _ref11 = {}, _ref11[property] = amount, _ref11;
874
- });
875
- };
876
- };
877
-
878
- var createFixedColumnCss = function createFixedColumnCss(theme) {
879
- return function (property, span) {
880
- return internal(function () {
881
- var _ref12;
882
-
883
- return _ref12 = {}, _ref12[property] = px(columnSystem(span, theme.grid.unit.column, theme.grid.unit.gutter)), _ref12;
884
- });
885
- };
886
- };
887
-
888
- var createElementEffectCss = function createElementEffectCss(theme) {
889
- return function (effects) {
890
- if (effects === void 0) {
891
- effects = [];
892
- }
893
-
894
- return internal(function () {
895
- return effects.filter(isSupportedEffect).reduce(function (acc, effect) {
896
- var _theme$elementEffect$, _theme$elementEffect$2;
897
-
898
- return _extends({}, acc, onEffectPseudo(effect, {
899
- opacity: !Array.isArray(theme.elementEffect[effect]) && ((_theme$elementEffect$ = theme.elementEffect[effect]) == null ? void 0 : _theme$elementEffect$.type) === 'opacity' ? (_theme$elementEffect$2 = theme.elementEffect[effect]) == null ? void 0 : _theme$elementEffect$2.opacity : unreachable()
900
- }));
901
- }, {});
902
- });
903
- };
904
- };
905
-
906
- function borderProperty(direction) {
907
- return "border-" + direction;
908
- }
909
-
910
- function borderShorthand(color) {
911
- return "solid 1px " + color;
912
- }
913
-
914
- var createBorderCss = function createBorderCss(theme) {
915
- return function (variant, directions) {
916
- var all = directions.length === 0;
917
- var value = borderShorthand(theme.border[variant].color);
918
- return internal(function () {
919
- return _extends({}, all ? {
920
- border: value
921
- } : directions.reduce(function (acc, direction) {
922
- var _extends3;
923
-
924
- return _extends({}, acc, (_extends3 = {}, _extends3[borderProperty(direction)] = value, _extends3));
925
- }, {}));
926
- });
927
- };
928
- };
929
-
930
- var createBorderRadiusCss = function createBorderRadiusCss(theme) {
931
- return function (size) {
932
- return internal(function () {
933
- return {
934
- borderRadius: px(theme.borderRadius[size])
935
- };
936
- });
937
- };
938
- };
939
-
940
- var commonSpec = function commonSpec(_theme) {
941
- var duration = dur(TRANSITION_DURATION);
942
-
943
- var transition = function transition(property) {
944
- return {
945
- transition: property.map(function (v) {
946
- return duration + " " + v;
947
- }).join(', ')
948
- };
949
- };
950
-
951
- return internal(function (_ref13) {
952
- var _ref13$colorTransitio = _ref13.colorTransition,
953
- colorTransition = _ref13$colorTransitio === void 0 ? false : _ref13$colorTransitio,
954
- _ref13$backgroundColo = _ref13.backgroundColorTransition,
955
- backgroundColorTransition = _ref13$backgroundColo === void 0 ? false : _ref13$backgroundColo,
956
- _ref13$boxShadowTrans = _ref13.boxShadowTransition,
957
- boxShadowTransition = _ref13$boxShadowTrans === void 0 ? false : _ref13$boxShadowTrans;
958
- return transition([colorTransition ? 'color' : null, backgroundColorTransition ? 'background-color' : null, boxShadowTransition ? 'box-shadow' : null].filter(isPresent));
959
- });
960
- };
961
-
962
- var internalSym = Symbol('internal');
963
-
964
- function internal(operation, context) {
965
- var _ref14;
966
-
967
- if (context === void 0) {
968
- context = {};
969
- }
970
-
971
- return _ref14 = {}, _ref14[internalSym] = {
972
- operation: operation,
973
- context: context
974
- }, _ref14;
975
- }
976
-
977
- var nonBlank = function nonBlank(value) {
978
- return isPresent(value) && value !== false;
979
- };
980
- /**
981
- * `theme(o => [...])` の `theme` ユーティリティを構築する
982
- *
983
- * @param _styled styled-componnets の `styled` そのもの (型推論のために用いられる)
984
- *
985
- * @example
986
- *
987
- * import styled from 'styled-components'
988
- * const theme = createTheme(styled)
989
- *
990
- * @example
991
- *
992
- * const theme = createTheme<DefaultTheme>()
993
- */
994
-
995
-
996
- function createTheme(_styled) {
997
- // `theme(o => [...])` の `o` の部分の型推論のためだけに使う意味のない変数
998
- // Tを型変数のまま渡してcreateThemeが呼ばれるまで型の具象化が行われないようにする
999
- // eslint-disable-next-line @typescript-eslint/no-unsafe-argument, @typescript-eslint/no-explicit-any
1000
- builder({}, true); // ランタイムの `theme(o => [...])` のインターフェースを構築する
1001
-
1002
-
1003
- return function ( // ユーザー定義
1004
- spec) {
1005
- return function (_ref15) {
1006
- var theme = _ref15.theme;
1007
-
1008
- if (!isPresent(theme)) {
1009
- // テーマが入っていない場合は復旧不可能なのでエラーにする
1010
- throw noThemeProvider;
1011
- } // styled-componentsのランタイムから受け取ったthemeオブジェクトをbuilderに食わせて`o`をつくる
1012
- // さらに、ユーザー定義にbuilderが構築した`o`を食わせる
1013
- // (`o`を一時変数に入れてしまうと型Tの具象化が行われるので関数合成を優先する)
1014
-
1015
-
1016
- var rawSpecDescriptor = spec(builder(theme)); // ユーザー定義の配列を整形
1017
-
1018
- var specDescriptor = [].concat(Array.isArray(rawSpecDescriptor) ? rawSpecDescriptor : [rawSpecDescriptor], [commonSpec()]).filter(nonBlank); // 1パス目
1019
- // 全ユーザー定義を舐めて相互に影響し合う定義をチェックし、その結果(コンテキスト)を取得
1020
-
1021
- var context = specDescriptor.reduce(function (acc, v) {
1022
- return _extends({}, acc, v[internalSym].context);
1023
- }, {}); // 2パス目
1024
- // コンテキストを見ながら最適化されたCSSを構築
1025
-
1026
- return specDescriptor.map(function (v) {
1027
- return v[internalSym].operation(context);
1028
- });
1029
- };
1030
- };
1031
- }
1032
-
1033
- export { SetThemeScript, TokenInjector, createTheme, defineThemeVariables, getThemeSync, makeSetThemeScriptCode, prefersColorScheme, themeSelector, themeSetter, useLocalStorage, useMedia, useTheme, useThemeSetter };
1034
- //# sourceMappingURL=index.module.js.map