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