@iyulab/components 3.1.0 → 3.2.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/CHANGELOG.md +118 -0
- package/README.md +5 -0
- package/dist/components/UElement.d.ts +11 -0
- package/dist/components/UElement.js +14 -0
- package/dist/components/UElement.styles.js +9 -0
- package/dist/components/UFloatingElement.d.ts +4 -0
- package/dist/components/UFloatingElement.js +7 -0
- package/dist/components/UFormControlElement.d.ts +20 -3
- package/dist/components/UFormControlElement.js +46 -4
- package/dist/components/UOverlayElement.d.ts +4 -0
- package/dist/components/UOverlayElement.js +7 -0
- package/dist/components/alert/UAlert.d.ts +4 -0
- package/dist/components/alert/UAlert.js +7 -0
- package/dist/components/auto-scroll/UAutoScroll.d.ts +6 -2
- package/dist/components/auto-scroll/UAutoScroll.js +7 -0
- package/dist/components/avatar/UAvatar.d.ts +4 -0
- package/dist/components/avatar/UAvatar.js +11 -0
- package/dist/components/badge/UBadge.d.ts +6 -0
- package/dist/components/badge/UBadge.js +36 -1
- package/dist/components/badge/UBadge.styles.js +8 -0
- package/dist/components/breadcrumb-item/UBreadcrumbItem.js +2 -2
- package/dist/components/button/UButton.d.ts +7 -0
- package/dist/components/button/UButton.js +41 -1
- package/dist/components/button/UButton.styles.js +8 -0
- package/dist/components/button-group/UButtonGroup.d.ts +4 -0
- package/dist/components/button-group/UButtonGroup.js +13 -0
- package/dist/components/calendar/UCalendar.d.ts +8 -0
- package/dist/components/calendar/UCalendar.js +30 -14
- package/dist/components/calendar/UCalendar.styles.js +3 -0
- package/dist/components/calendar/dates.d.ts +12 -0
- package/dist/components/calendar/dates.js +25 -1
- package/dist/components/card/UCard.d.ts +6 -0
- package/dist/components/card/UCard.js +15 -0
- package/dist/components/carousel/UCarousel.d.ts +4 -0
- package/dist/components/carousel/UCarousel.js +7 -0
- package/dist/components/checkbox/UCheckbox.d.ts +6 -0
- package/dist/components/checkbox/UCheckbox.js +25 -1
- package/dist/components/chip/UChip.d.ts +5 -0
- package/dist/components/chip/UChip.js +30 -0
- package/dist/components/command-palette/UCommandPalette.js +3 -0
- package/dist/components/copy-button/UCopyButton.d.ts +4 -0
- package/dist/components/copy-button/UCopyButton.js +13 -0
- package/dist/components/date-picker/UDatePicker.d.ts +11 -5
- package/dist/components/date-picker/UDatePicker.js +13 -0
- package/dist/components/date-range-picker/UDateRangePicker.d.ts +9 -2
- package/dist/components/date-range-picker/UDateRangePicker.js +13 -0
- package/dist/components/date-range-picker/presets.d.ts +2 -1
- package/dist/components/date-range-picker/presets.js +5 -5
- package/dist/components/dialog/UDialog.d.ts +5 -0
- package/dist/components/dialog/UDialog.js +17 -0
- package/dist/components/divider/UDivider.d.ts +5 -0
- package/dist/components/divider/UDivider.js +17 -1
- package/dist/components/divider/UDivider.styles.js +5 -0
- package/dist/components/drawer/UDrawer.d.ts +5 -0
- package/dist/components/drawer/UDrawer.js +12 -0
- package/dist/components/field/UField.d.ts +4 -0
- package/dist/components/field/UField.js +7 -0
- package/dist/components/icon-button/UIconButton.d.ts +4 -0
- package/dist/components/icon-button/UIconButton.js +13 -0
- package/dist/components/input/UInput.d.ts +7 -0
- package/dist/components/input/UInput.js +31 -0
- package/dist/components/input/UInput.styles.js +9 -0
- package/dist/components/menu/UMenu.d.ts +7 -0
- package/dist/components/menu/UMenu.js +18 -0
- package/dist/components/menu-item/UMenuItem.d.ts +5 -0
- package/dist/components/menu-item/UMenuItem.js +13 -1
- package/dist/components/option/UOption.d.ts +4 -0
- package/dist/components/option/UOption.js +8 -1
- package/dist/components/pagination/UPagination.d.ts +4 -0
- package/dist/components/pagination/UPagination.js +11 -0
- package/dist/components/popover/UPopover.d.ts +5 -0
- package/dist/components/popover/UPopover.js +13 -0
- package/dist/components/progress-bar/UProgressBar.d.ts +4 -0
- package/dist/components/progress-bar/UProgressBar.js +14 -1
- package/dist/components/progress-bar/UProgressBar.styles.js +5 -0
- package/dist/components/progress-ring/UProgressRing.d.ts +4 -0
- package/dist/components/progress-ring/UProgressRing.js +13 -0
- package/dist/components/radio/URadio.d.ts +7 -0
- package/dist/components/radio/URadio.js +14 -1
- package/dist/components/rating/URating.d.ts +5 -1
- package/dist/components/rating/URating.js +6 -2
- package/dist/components/select/USelect.d.ts +7 -0
- package/dist/components/select/USelect.js +19 -1
- package/dist/components/skeleton/USkeleton.d.ts +5 -0
- package/dist/components/skeleton/USkeleton.js +16 -0
- package/dist/components/spinner/USpinner.d.ts +4 -0
- package/dist/components/spinner/USpinner.js +24 -0
- package/dist/components/split-panel/USplitPanel.d.ts +4 -0
- package/dist/components/split-panel/USplitPanel.js +7 -0
- package/dist/components/steps/USteps.d.ts +4 -0
- package/dist/components/steps/USteps.js +12 -1
- package/dist/components/switch/USwitch.js +1 -1
- package/dist/components/tab/UTab.d.ts +4 -0
- package/dist/components/tab/UTab.js +12 -1
- package/dist/components/tab/UTab.styles.js +7 -0
- package/dist/components/tab-nav/UTabNav.d.ts +6 -2
- package/dist/components/tab-nav/UTabNav.js +7 -0
- package/dist/components/tab-panel/UTabPanel.d.ts +5 -0
- package/dist/components/tab-panel/UTabPanel.js +18 -0
- package/dist/components/tag/UTag.d.ts +6 -0
- package/dist/components/tag/UTag.js +32 -1
- package/dist/components/text/UText.d.ts +5 -0
- package/dist/components/text/UText.js +21 -0
- package/dist/components/textarea/UTextarea.d.ts +7 -0
- package/dist/components/textarea/UTextarea.js +24 -0
- package/dist/components/tree/UTree.d.ts +4 -0
- package/dist/components/tree/UTree.js +7 -0
- package/dist/components/tree-item/UTreeItem.d.ts +4 -0
- package/dist/components/tree-item/UTreeItem.js +8 -1
- package/dist/custom-elements.json +46557 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -1
- package/dist/plugins/cem-check.d.ts +29 -0
- package/dist/plugins/cem-check.js +90 -0
- package/dist/plugins/cem-config.d.ts +17 -0
- package/dist/plugins/cem-config.js +22 -0
- package/dist/plugins/cem-enumerated-plugin.d.ts +20 -0
- package/dist/plugins/cem-enumerated-plugin.js +105 -0
- package/dist/plugins/cem-events-plugin.d.ts +18 -0
- package/dist/plugins/cem-events-plugin.js +96 -0
- package/dist/utilities/enumerated.d.ts +20 -0
- package/dist/utilities/enumerated.js +24 -0
- package/dist/utilities/format.js +49 -15
- package/package.json +18 -15
- package/skills/iyulab-components/SKILL.md +5 -1
- package/skills/iyulab-components/references/components/checkbox.md +1 -1
- package/skills/iyulab-components/references/components/date-picker.md +2 -2
- package/skills/iyulab-components/references/components/date-range-picker.md +4 -4
- package/skills/iyulab-components/references/components/field.md +5 -0
- package/skills/iyulab-components/references/components/file-input.md +1 -1
- package/skills/iyulab-components/references/components/input.md +1 -1
- package/skills/iyulab-components/references/components/select.md +1 -1
- package/skills/iyulab-components/references/components/textarea.md +1 -1
package/dist/index.d.ts
CHANGED
|
@@ -70,6 +70,7 @@ export * from './utilities/collation.js';
|
|
|
70
70
|
export * from './utilities/converters.js';
|
|
71
71
|
export * from './utilities/dateValue.js';
|
|
72
72
|
export * from './utilities/devWarning.js';
|
|
73
|
+
export * from './utilities/enumerated.js';
|
|
73
74
|
export * from './utilities/Dialog.js';
|
|
74
75
|
export * from './utilities/elements.js';
|
|
75
76
|
export * from './utilities/listenInShadow.js';
|
package/dist/index.js
CHANGED
|
@@ -61,6 +61,7 @@ import { compareText, getCollator } from "./utilities/collation.js";
|
|
|
61
61
|
import { arrayAttrConverter, booleanAttrConverter, dateAttrConverter, jsonAttrConverter, urlAttrConverter } from "./utilities/converters.js";
|
|
62
62
|
import { localOffset, readDateValue, writeInstant, writePlainDate, writePlainDateTime } from "./utilities/dateValue.js";
|
|
63
63
|
import { createDevWarner, devWarnOnce, resetDevWarnings } from "./utilities/devWarning.js";
|
|
64
|
+
import { enumeratedValues } from "./utilities/enumerated.js";
|
|
64
65
|
import { Dialog } from "./utilities/Dialog.js";
|
|
65
66
|
import { getParentElement, isCoarsePointer, isFocusCandidate, isFromControl, querySelectorAllWithin, querySelectorDeep, querySelectorWithin } from "./utilities/elements.js";
|
|
66
67
|
import { delegate, listenInShadow } from "./utilities/listenInShadow.js";
|
|
@@ -75,4 +76,4 @@ import { OverlayManager } from "./utilities/OverlayManager.js";
|
|
|
75
76
|
import { Theme } from "./utilities/Theme.js";
|
|
76
77
|
import { Toast } from "./utilities/Toast.js";
|
|
77
78
|
import { decodeDelimited, decodeTsv, encodeTsv } from "./utilities/tsv.js";
|
|
78
|
-
export { ALERT_STATUSES, BrowserStorage, CompositionTracker, Dialog, IconCache, IconRegistry, Locale, OverlayManager, Theme, Toast, UAlert, UAutoScroll, UAvatar, UBadge, UBreadcrumb, UBreadcrumbItem, UButton, UButtonGroup, UCard, UCarousel, UCheckbox, UChip, UCommandPalette, UCopyButton, UDatePicker, UDateRangePicker, UDialog, UDivider, UDrawer, UElement, UExpander, UField, UFileInput, UFloatingElement, UForm, UFormControlElement, UIcon, UIconButton, UInput, UMenu, UMenuItem, UOption, UOptionGroup, UOverlayElement, UPagination, UPanel, UPopover, UProgressBar, UProgressRing, URadio, URating, USelect, USkeleton, USlider, USpinner, USplitPanel, USteps, USwitch, UTab, UTabNav, UTabPanel, UTag, UText, UTextarea, UTooltip, UTree, UTreeItem, applyNumberFormat, arrayAttrConverter, booleanAttrConverter, collectOptions, compareText, copyFromKey, createDevWarner, dateAttrConverter, dateTextPattern, decodeDelimited, decodeTsv, defaultSearchMatch, delegate, devWarnOnce, encodeTsv, filterCommands, foldForSearch, formatCurrency, formatDate, formatDateRange, formatDateRangeText, formatDateText, formatDateTimeRangeText, formatDateTimeText, formatNumber, getCollator, getDefaultBaseUrl, getParentElement, hangulKeystrokes, initialsOf, isCoarsePointer, isFocusCandidate, isFromControl, isHangul, isImeComposing, isTextEntry, jsonAttrConverter, listenInShadow, localOffset, parseDate, parseDateRange, parseDateTime, parseDateTimeRange, parseNumber, pasteFromKey, querySelectorAllWithin, querySelectorDeep, querySelectorWithin, readDateValue, replayInput, resetDevWarnings, setDefaultBaseUrl, urlAttrConverter, writeInstant, writePlainDate, writePlainDateTime };
|
|
79
|
+
export { ALERT_STATUSES, BrowserStorage, CompositionTracker, Dialog, IconCache, IconRegistry, Locale, OverlayManager, Theme, Toast, UAlert, UAutoScroll, UAvatar, UBadge, UBreadcrumb, UBreadcrumbItem, UButton, UButtonGroup, UCard, UCarousel, UCheckbox, UChip, UCommandPalette, UCopyButton, UDatePicker, UDateRangePicker, UDialog, UDivider, UDrawer, UElement, UExpander, UField, UFileInput, UFloatingElement, UForm, UFormControlElement, UIcon, UIconButton, UInput, UMenu, UMenuItem, UOption, UOptionGroup, UOverlayElement, UPagination, UPanel, UPopover, UProgressBar, UProgressRing, URadio, URating, USelect, USkeleton, USlider, USpinner, USplitPanel, USteps, USwitch, UTab, UTabNav, UTabPanel, UTag, UText, UTextarea, UTooltip, UTree, UTreeItem, applyNumberFormat, arrayAttrConverter, booleanAttrConverter, collectOptions, compareText, copyFromKey, createDevWarner, dateAttrConverter, dateTextPattern, decodeDelimited, decodeTsv, defaultSearchMatch, delegate, devWarnOnce, encodeTsv, enumeratedValues, filterCommands, foldForSearch, formatCurrency, formatDate, formatDateRange, formatDateRangeText, formatDateText, formatDateTimeRangeText, formatDateTimeText, formatNumber, getCollator, getDefaultBaseUrl, getParentElement, hangulKeystrokes, initialsOf, isCoarsePointer, isFocusCandidate, isFromControl, isHangul, isImeComposing, isTextEntry, jsonAttrConverter, listenInShadow, localOffset, parseDate, parseDateRange, parseDateTime, parseDateTimeRange, parseNumber, pasteFromKey, querySelectorAllWithin, querySelectorDeep, querySelectorWithin, readDateValue, replayInput, resetDevWarnings, setDefaultBaseUrl, urlAttrConverter, writeInstant, writePlainDate, writePlainDateTime };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @param {{ root: string, manifest: Manifest }} input `root` 는 패키지 루트(`src/` 가 있는 곳)
|
|
3
|
+
* @returns {string[]} 위반 목록 — 비어 있으면 정합
|
|
4
|
+
*/
|
|
5
|
+
export function checkManifest({ root, manifest }: {
|
|
6
|
+
root: string;
|
|
7
|
+
manifest: Manifest;
|
|
8
|
+
}): string[];
|
|
9
|
+
export type ManifestEvent = {
|
|
10
|
+
name?: string;
|
|
11
|
+
description?: string;
|
|
12
|
+
inheritedFrom?: unknown;
|
|
13
|
+
type?: {
|
|
14
|
+
text: string;
|
|
15
|
+
};
|
|
16
|
+
};
|
|
17
|
+
export type ManifestDeclaration = {
|
|
18
|
+
kind: string;
|
|
19
|
+
name: string;
|
|
20
|
+
tagName?: string;
|
|
21
|
+
description?: string;
|
|
22
|
+
events?: ManifestEvent[];
|
|
23
|
+
};
|
|
24
|
+
export type Manifest = {
|
|
25
|
+
modules: {
|
|
26
|
+
path: string;
|
|
27
|
+
declarations?: ManifestDeclaration[];
|
|
28
|
+
}[];
|
|
29
|
+
};
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Custom Elements Manifest 정합 검사 — `custom-elements.json` 이 **소스와 같은 말을 하는가** 를 소스에서 도출한 기대로 잰다.
|
|
4
|
+
* 시험 러너에 기대지 않는 순수 함수라 컴포넌트 패키지마다 자기 `npm test` 에서 부른다(단독 클론의 CI 도 같은 판정).
|
|
5
|
+
*
|
|
6
|
+
* 대상(등록된 태그 · 이벤트 이름)은 소스에서 읽고, 규칙(무엇이 위반인가)만 여기 있다.
|
|
7
|
+
*/
|
|
8
|
+
import { readdirSync, readFileSync, statSync } from 'node:fs';
|
|
9
|
+
import { join, relative, sep } from 'node:path';
|
|
10
|
+
/**
|
|
11
|
+
* @typedef {{ name?: string, description?: string, inheritedFrom?: unknown, type?: { text: string } }} ManifestEvent
|
|
12
|
+
* @typedef {{ kind: string, name: string, tagName?: string, description?: string, events?: ManifestEvent[] }} ManifestDeclaration
|
|
13
|
+
* @typedef {{ modules: { path: string, declarations?: ManifestDeclaration[] }[] }} Manifest
|
|
14
|
+
*/
|
|
15
|
+
/** 소스 파일(시험 · 스타일 · 선언 제외) — 경로는 패키지 루트 기준 `/` 구분.
|
|
16
|
+
* @param {string} root */
|
|
17
|
+
function sourceFiles(root) {
|
|
18
|
+
/** @type {{ path: string, text: string }[]} */
|
|
19
|
+
const out = [];
|
|
20
|
+
const walk = (/** @type {string} */ dir) => {
|
|
21
|
+
for (const name of readdirSync(dir)) {
|
|
22
|
+
const p = join(dir, name);
|
|
23
|
+
if (statSync(p).isDirectory())
|
|
24
|
+
walk(p);
|
|
25
|
+
else if (p.endsWith('.ts') && !/\.(test|styles|d)\.ts$/.test(p)) {
|
|
26
|
+
out.push({ path: relative(root, p).split(sep).join('/'), text: readFileSync(p, 'utf8') });
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
walk(join(root, 'src'));
|
|
31
|
+
return out;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* @param {{ root: string, manifest: Manifest }} input `root` 는 패키지 루트(`src/` 가 있는 곳)
|
|
35
|
+
* @returns {string[]} 위반 목록 — 비어 있으면 정합
|
|
36
|
+
*/
|
|
37
|
+
export function checkManifest({ root, manifest }) {
|
|
38
|
+
const files = sourceFiles(root);
|
|
39
|
+
const problems = [];
|
|
40
|
+
const elements = manifest.modules.flatMap((m) => (m.declarations ?? []).filter((d) => d.tagName).map((d) => ({ ...d, module: m.path })));
|
|
41
|
+
// 1. 매니페스트의 요소 = 소스가 등록한 요소
|
|
42
|
+
const registered = new Set(files.flatMap((f) => [
|
|
43
|
+
...f.text.matchAll(/@customElement\(\s*['"]([a-z0-9-]+)['"]\s*\)/g),
|
|
44
|
+
...f.text.matchAll(/customElements\.define\(\s*['"]([a-z0-9-]+)['"]/g),
|
|
45
|
+
// `static define(name)` 를 가진 클래스의 `Class.define('tag')` 호출(dimension-timeline) — 매니페스트는 클래스의 JSDoc `@customElement tag` 로 안다
|
|
46
|
+
...f.text.matchAll(/\b[A-Z]\w*\.define\(\s*['"]([a-z0-9-]+)['"]/g),
|
|
47
|
+
].map((m) => m[1])));
|
|
48
|
+
if (!registered.size)
|
|
49
|
+
problems.push('the source registers no element — nothing to check');
|
|
50
|
+
const listed = new Set(elements.map((e) => e.tagName));
|
|
51
|
+
for (const tag of registered)
|
|
52
|
+
if (!listed.has(tag))
|
|
53
|
+
problems.push(`registered but missing from the manifest: ${tag}`);
|
|
54
|
+
for (const tag of listed)
|
|
55
|
+
if (!registered.has(String(tag)))
|
|
56
|
+
problems.push(`in the manifest but not registered by the source: ${tag}`);
|
|
57
|
+
// 2. 모든 요소에 설명이 있다 — 클래스 주석이 다른 선언 위에 붙으면 그 선언의 설명이 된다
|
|
58
|
+
for (const e of elements)
|
|
59
|
+
if (!e.description?.trim())
|
|
60
|
+
problems.push(`no description: ${e.tagName} (is its comment attached to a neighbouring declaration?)`);
|
|
61
|
+
// 3. 이름 없는 이벤트, 소스의 «이벤트 이름 자리» 에 리터럴로 없는 이름의 이벤트는 분석기가 변수 이름에서 지어낸 것이다
|
|
62
|
+
// (물려받은 것은 상위 매니페스트의 몫). «이벤트 이름 자리» = `fire('x')` · `new XEvent('x')` 의 첫 인자, 또는 JSDoc `@fires x`.
|
|
63
|
+
// 아무 문자열 리터럴이나 세지 않는다 — `'name'` 은 속성 이름으로 소스 어디에나 있어서 가짜 `name` 이벤트를 가리게 된다.
|
|
64
|
+
const eventNames = new Set(files.flatMap((f) => [
|
|
65
|
+
...f.text.matchAll(/\b(?:fire|emit|new\s+\w*Event)(?:<[^>]*>)?\(\s*['"`]([a-z][a-z0-9:_.-]*)['"`]/gi),
|
|
66
|
+
...f.text.matchAll(/@(?:fires|event)\s+(?:\{[^}]*\}\s+)?([a-z][a-z0-9:_.-]*)/gi),
|
|
67
|
+
].map((m) => m[1])));
|
|
68
|
+
for (const e of elements) {
|
|
69
|
+
for (const ev of e.events ?? []) {
|
|
70
|
+
if (ev.inheritedFrom)
|
|
71
|
+
continue;
|
|
72
|
+
if (!ev.name)
|
|
73
|
+
problems.push(`${e.tagName}: an event without a name`);
|
|
74
|
+
else if (!eventNames.has(ev.name))
|
|
75
|
+
problems.push(`${e.tagName}: event '${ev.name}' is not an event name anywhere in the source (invented from a variable name?)`);
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
// 4. 클래스가 리터럴 이름으로 내는 이벤트는 전부 그 모듈의 선언에 있다
|
|
79
|
+
for (const f of files) {
|
|
80
|
+
const fired = new Set([...f.text.matchAll(/this\.(?:(?:fire|emit)(?:<[^>]*>)?\(\s*|dispatchEvent\(\s*new\s+\w*Event\(\s*)['"`]([a-z][a-z0-9:_.-]*)['"`]/gi)].map((m) => m[1]));
|
|
81
|
+
if (!fired.size)
|
|
82
|
+
continue;
|
|
83
|
+
const mod = manifest.modules.find((m) => m.path === f.path);
|
|
84
|
+
const have = new Set((mod?.declarations ?? []).flatMap((d) => (d.events ?? []).map((e) => e.name)));
|
|
85
|
+
for (const name of fired)
|
|
86
|
+
if (!have.has(name))
|
|
87
|
+
problems.push(`${f.path}: fires '${name}' but the manifest does not list it`);
|
|
88
|
+
}
|
|
89
|
+
return problems;
|
|
90
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Custom Elements Manifest 분석기 설정의 공통 몸 — 컴포넌트 패키지마다 `custom-elements-manifest.config.mjs` 에서
|
|
3
|
+
* `export default cemConfig()` 로 쓴다. 소스 전체를 읽고(대상을 열거하지 않는다 — 분석기가 `@customElement` 를 찾는다) 시험 ·
|
|
4
|
+
* 스타일 · 선언 파일만 뺀다. `package.json` 의 `customElements` 필드는 분석기에 쓰게 하지 않고 패키지가 직접 적는다.
|
|
5
|
+
*
|
|
6
|
+
* 다른 패키지의 기반 클래스(`UElement` …)를 물려받은 요소는 매니페스트의 `superclass` 가 그 패키지와 모듈을 가리킨다 —
|
|
7
|
+
* 도구는 그 패키지의 매니페스트를 따라간다(CEM 의 방식). 분석기의 `dependencies` 옵션은 켜지 않는다: 켜도 상위 멤버를 펼쳐 주지
|
|
8
|
+
* 않았고(실측), 소비 의존성을 훑느라 경고만 늘었다.
|
|
9
|
+
*/
|
|
10
|
+
export function cemConfig(): {
|
|
11
|
+
globs: string[];
|
|
12
|
+
exclude: string[];
|
|
13
|
+
outdir: string;
|
|
14
|
+
litelement: boolean;
|
|
15
|
+
packagejson: boolean;
|
|
16
|
+
plugins: import("@custom-elements-manifest/analyzer").Plugin[];
|
|
17
|
+
};
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
import eventsPlugin from './cem-events-plugin.js';
|
|
3
|
+
import enumeratedPlugin from './cem-enumerated-plugin.js';
|
|
4
|
+
/**
|
|
5
|
+
* Custom Elements Manifest 분석기 설정의 공통 몸 — 컴포넌트 패키지마다 `custom-elements-manifest.config.mjs` 에서
|
|
6
|
+
* `export default cemConfig()` 로 쓴다. 소스 전체를 읽고(대상을 열거하지 않는다 — 분석기가 `@customElement` 를 찾는다) 시험 ·
|
|
7
|
+
* 스타일 · 선언 파일만 뺀다. `package.json` 의 `customElements` 필드는 분석기에 쓰게 하지 않고 패키지가 직접 적는다.
|
|
8
|
+
*
|
|
9
|
+
* 다른 패키지의 기반 클래스(`UElement` …)를 물려받은 요소는 매니페스트의 `superclass` 가 그 패키지와 모듈을 가리킨다 —
|
|
10
|
+
* 도구는 그 패키지의 매니페스트를 따라간다(CEM 의 방식). 분석기의 `dependencies` 옵션은 켜지 않는다: 켜도 상위 멤버를 펼쳐 주지
|
|
11
|
+
* 않았고(실측), 소비 의존성을 훑느라 경고만 늘었다.
|
|
12
|
+
*/
|
|
13
|
+
export function cemConfig() {
|
|
14
|
+
return {
|
|
15
|
+
globs: ['src/**/*.ts'],
|
|
16
|
+
exclude: ['**/*.test.ts', '**/*.styles.ts', '**/*.d.ts'],
|
|
17
|
+
outdir: 'dist',
|
|
18
|
+
litelement: true,
|
|
19
|
+
packagejson: false,
|
|
20
|
+
plugins: [eventsPlugin(), enumeratedPlugin()],
|
|
21
|
+
};
|
|
22
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Custom Elements Manifest 분석기 플러그인 — 열거형 속성의 **허용 값**을 매니페스트에 싣는다.
|
|
3
|
+
*
|
|
4
|
+
* 분석기는 속성의 타입을 쓰인 그대로(`ButtonAppearance`)만 적는다 — 별칭을 풀 타입 체커가 없다. 그래서 «소스를 읽지 않고도 속성을
|
|
5
|
+
* 안다» 는 매니페스트의 목적에서 가장 쓸모 있는 정보(어떤 값이 유효한가)가 빠져 있었다. 편집기의 값 완성과 에이전트가 그것을 못 쓰고,
|
|
6
|
+
* 목록 밖의 값(`appearance="filled"`)이 에러 없이 기본 모양이 되는 실수를 도구 쪽에서 못 막았다.
|
|
7
|
+
*
|
|
8
|
+
* 요소는 이미 그 목록을 한 번 적는다 — `static enumerated`(속성 → `enumeratedValues<유니온>()([...])`, 런타임 개발 모드 경고와 컴파일러의
|
|
9
|
+
* 유니온 일치 검사가 읽는다). 이 플러그인은 **같은 목록**으로 매니페스트의 필드 · 속성 `type.text` 를 `"a" | "b"` 로 펼치고(원래 타입 텍스트에
|
|
10
|
+
* `undefined` 가 있으면 유지), 구현 세부인 `enumerated` 정적 멤버는 매니페스트에서 뺀다 — 런타임 경고 · 컴파일 강제 · 매니페스트가 한 출처를
|
|
11
|
+
* 공유하므로 서로 어긋날 수 없다.
|
|
12
|
+
*
|
|
13
|
+
* 상속: 목록은 그 속성을 **선언한 클래스**의 것이다(하위 클래스는 `...super.enumerated` 로 펼칠 뿐 키를 다시 적지 않는다). 매니페스트의 필드는
|
|
14
|
+
* 선언한 클래스에 있고 하위 요소는 `inheritedFrom` 으로 따라가므로 같은 규칙으로 닫힌다.
|
|
15
|
+
*
|
|
16
|
+
* 대상(클래스 · 키 · 값)은 소스에서 도출하고 규칙만 여기 있다.
|
|
17
|
+
*
|
|
18
|
+
* @returns {import('@custom-elements-manifest/analyzer').Plugin}
|
|
19
|
+
*/
|
|
20
|
+
export default function enumeratedPlugin(): import("@custom-elements-manifest/analyzer").Plugin;
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Custom Elements Manifest 분석기 플러그인 — 열거형 속성의 **허용 값**을 매니페스트에 싣는다.
|
|
4
|
+
*
|
|
5
|
+
* 분석기는 속성의 타입을 쓰인 그대로(`ButtonAppearance`)만 적는다 — 별칭을 풀 타입 체커가 없다. 그래서 «소스를 읽지 않고도 속성을
|
|
6
|
+
* 안다» 는 매니페스트의 목적에서 가장 쓸모 있는 정보(어떤 값이 유효한가)가 빠져 있었다. 편집기의 값 완성과 에이전트가 그것을 못 쓰고,
|
|
7
|
+
* 목록 밖의 값(`appearance="filled"`)이 에러 없이 기본 모양이 되는 실수를 도구 쪽에서 못 막았다.
|
|
8
|
+
*
|
|
9
|
+
* 요소는 이미 그 목록을 한 번 적는다 — `static enumerated`(속성 → `enumeratedValues<유니온>()([...])`, 런타임 개발 모드 경고와 컴파일러의
|
|
10
|
+
* 유니온 일치 검사가 읽는다). 이 플러그인은 **같은 목록**으로 매니페스트의 필드 · 속성 `type.text` 를 `"a" | "b"` 로 펼치고(원래 타입 텍스트에
|
|
11
|
+
* `undefined` 가 있으면 유지), 구현 세부인 `enumerated` 정적 멤버는 매니페스트에서 뺀다 — 런타임 경고 · 컴파일 강제 · 매니페스트가 한 출처를
|
|
12
|
+
* 공유하므로 서로 어긋날 수 없다.
|
|
13
|
+
*
|
|
14
|
+
* 상속: 목록은 그 속성을 **선언한 클래스**의 것이다(하위 클래스는 `...super.enumerated` 로 펼칠 뿐 키를 다시 적지 않는다). 매니페스트의 필드는
|
|
15
|
+
* 선언한 클래스에 있고 하위 요소는 `inheritedFrom` 으로 따라가므로 같은 규칙으로 닫힌다.
|
|
16
|
+
*
|
|
17
|
+
* 대상(클래스 · 키 · 값)은 소스에서 도출하고 규칙만 여기 있다.
|
|
18
|
+
*
|
|
19
|
+
* @returns {import('@custom-elements-manifest/analyzer').Plugin}
|
|
20
|
+
*/
|
|
21
|
+
export default function enumeratedPlugin() {
|
|
22
|
+
/** `경로#클래스` → 속성 이름 → 허용 값(소스 순서)
|
|
23
|
+
* @type {Map<string, Map<string, string[]>>} */
|
|
24
|
+
const lists = new Map();
|
|
25
|
+
/** @type {import('@custom-elements-manifest/analyzer').Plugin} */
|
|
26
|
+
const plugin = {
|
|
27
|
+
name: 'u-enumerated',
|
|
28
|
+
analyzePhase({ ts, node, moduleDoc }) {
|
|
29
|
+
if (!ts.isClassDeclaration(node) || !node.name)
|
|
30
|
+
return;
|
|
31
|
+
const key = `${moduleDoc.path}#${node.name.text}`;
|
|
32
|
+
for (const member of node.members) {
|
|
33
|
+
if (!ts.isPropertyDeclaration(member) || !member.initializer)
|
|
34
|
+
continue;
|
|
35
|
+
const isStatic = member.modifiers?.some((m) => m.kind === ts.SyntaxKind.StaticKeyword);
|
|
36
|
+
if (!isStatic || !ts.isIdentifier(member.name) || member.name.text !== 'enumerated')
|
|
37
|
+
continue;
|
|
38
|
+
if (!ts.isObjectLiteralExpression(member.initializer))
|
|
39
|
+
continue;
|
|
40
|
+
for (const prop of member.initializer.properties) {
|
|
41
|
+
// `...super.enumerated` 같은 펼침은 건너뛴다 — 부모의 키는 부모 클래스의 몫이다.
|
|
42
|
+
if (!ts.isPropertyAssignment(prop))
|
|
43
|
+
continue;
|
|
44
|
+
const name = ts.isIdentifier(prop.name) || ts.isStringLiteralLike(prop.name) ? prop.name.text : null;
|
|
45
|
+
if (!name)
|
|
46
|
+
continue;
|
|
47
|
+
// `enumeratedValues<유니온>()([...])` — 바깥 호출의 첫 인자가 문자열 리터럴 배열이다.
|
|
48
|
+
const call = prop.initializer;
|
|
49
|
+
if (!ts.isCallExpression(call) || !ts.isCallExpression(call.expression))
|
|
50
|
+
continue;
|
|
51
|
+
const arr = call.arguments[0];
|
|
52
|
+
if (!arr || !ts.isArrayLiteralExpression(arr))
|
|
53
|
+
continue;
|
|
54
|
+
const values = [];
|
|
55
|
+
for (const el of arr.elements) {
|
|
56
|
+
if (!ts.isStringLiteralLike(el)) {
|
|
57
|
+
values.length = 0;
|
|
58
|
+
break;
|
|
59
|
+
} // 리터럴이 아니면 판정하지 않는다
|
|
60
|
+
values.push(el.text);
|
|
61
|
+
}
|
|
62
|
+
if (!values.length)
|
|
63
|
+
continue;
|
|
64
|
+
let byName = lists.get(key);
|
|
65
|
+
if (!byName)
|
|
66
|
+
lists.set(key, (byName = new Map()));
|
|
67
|
+
byName.set(name, values);
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
},
|
|
71
|
+
moduleLinkPhase({ moduleDoc }) {
|
|
72
|
+
for (const declaration of moduleDoc.declarations ?? []) {
|
|
73
|
+
if (declaration.kind !== 'class')
|
|
74
|
+
continue;
|
|
75
|
+
// 매니페스트 스키마의 클래스 선언(`members` · `attributes` 를 가진다) — 분석기 타입은 선언 종류의 합집합이라 좁힌다.
|
|
76
|
+
const decl = /** @type {{ name: string, members?: { kind?: string, name?: string, static?: boolean, type?: { text: string } }[], attributes?: { name?: string, fieldName?: string, type?: { text: string } }[] }} */ (declaration);
|
|
77
|
+
const byName = lists.get(`${moduleDoc.path}#${decl.name}`);
|
|
78
|
+
/** 원래 타입 텍스트의 `undefined`(선택 속성)를 유지하며 값 목록 유니온으로 바꾼다.
|
|
79
|
+
* @param {{ type?: { text: string } }} target @param {string[]} values */
|
|
80
|
+
const expand = (target, values) => {
|
|
81
|
+
const optional = /\bundefined\b/.test(target.type?.text ?? '');
|
|
82
|
+
const text = values.map((v) => JSON.stringify(v)).join(' | ');
|
|
83
|
+
target.type = { text: optional ? `${text} | undefined` : text };
|
|
84
|
+
};
|
|
85
|
+
if (byName) {
|
|
86
|
+
for (const [prop, values] of byName) {
|
|
87
|
+
for (const m of decl.members ?? [])
|
|
88
|
+
if (m.kind === 'field' && !m.static && m.name === prop)
|
|
89
|
+
expand(m, values);
|
|
90
|
+
for (const a of decl.attributes ?? [])
|
|
91
|
+
if (a.fieldName === prop)
|
|
92
|
+
expand(a, values);
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
// 구현 세부 — 값 목록은 위 유니온에 이미 있고, 이 멤버의 `default` 는 소스 텍스트일 뿐이다.
|
|
96
|
+
if (decl.members) {
|
|
97
|
+
const kept = decl.members.filter((m) => !(m.kind === 'field' && m.static && m.name === 'enumerated'));
|
|
98
|
+
if (kept.length !== decl.members.length)
|
|
99
|
+
decl.members = kept;
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
},
|
|
103
|
+
};
|
|
104
|
+
return plugin;
|
|
105
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Custom Elements Manifest 분석기 플러그인 — 요소가 내는 이벤트를 코드에서 빠짐없이, 거짓 없이 읽는다.
|
|
3
|
+
*
|
|
4
|
+
* 분석기는 **메서드** 안의 `this.dispatchEvent(new X('이름'))` 만 이벤트로 읽는다. 이 리포는 세 가지가 어긋난다:
|
|
5
|
+
*
|
|
6
|
+
* 1. 기반 클래스의 `fire()`(또는 같은 일을 하는 `emit()`)로 내는 이벤트(`this.fire<Detail>('이름', …)`)는 분석기가 모른다 → 매니페스트에서 빠진다.
|
|
7
|
+
* 여기서 소스의 호출을 읽어 `CustomEvent<Detail>` 로 더한다(JSDoc `@fires` 로 적힌 설명과 타입은 덮지 않는다).
|
|
8
|
+
* 1b. 화살표 함수 필드(`private onClick = () => { this.dispatchEvent(…) }`) 안의 발화도 분석기는 놓친다 — 같은 규칙으로 더한다.
|
|
9
|
+
* 2. `fire()` 자신의 `this.dispatchEvent(new CustomEvent(name, …))` 는 이름이 문자열이 아니라 변수라, 분석기가
|
|
10
|
+
* 변수 이름(`name`)과 이름 없는 항목을 이벤트로 적고 모든 하위 요소가 그것을 물려받는다 → 걷어 낸다.
|
|
11
|
+
* 판별은 «이름이 문자열 리터럴이 아닌 `dispatchEvent(new …)` 에서 나온, 설명 없는 항목» 이다(문서화된
|
|
12
|
+
* 이벤트는 건드리지 않는다).
|
|
13
|
+
*
|
|
14
|
+
* 대상(클래스 · 이벤트 이름)은 소스에서 도출하고 규칙만 여기 있다.
|
|
15
|
+
*
|
|
16
|
+
* @returns {import('@custom-elements-manifest/analyzer').Plugin}
|
|
17
|
+
*/
|
|
18
|
+
export default function eventsPlugin(): import("@custom-elements-manifest/analyzer").Plugin;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
/**
|
|
3
|
+
* Custom Elements Manifest 분석기 플러그인 — 요소가 내는 이벤트를 코드에서 빠짐없이, 거짓 없이 읽는다.
|
|
4
|
+
*
|
|
5
|
+
* 분석기는 **메서드** 안의 `this.dispatchEvent(new X('이름'))` 만 이벤트로 읽는다. 이 리포는 세 가지가 어긋난다:
|
|
6
|
+
*
|
|
7
|
+
* 1. 기반 클래스의 `fire()`(또는 같은 일을 하는 `emit()`)로 내는 이벤트(`this.fire<Detail>('이름', …)`)는 분석기가 모른다 → 매니페스트에서 빠진다.
|
|
8
|
+
* 여기서 소스의 호출을 읽어 `CustomEvent<Detail>` 로 더한다(JSDoc `@fires` 로 적힌 설명과 타입은 덮지 않는다).
|
|
9
|
+
* 1b. 화살표 함수 필드(`private onClick = () => { this.dispatchEvent(…) }`) 안의 발화도 분석기는 놓친다 — 같은 규칙으로 더한다.
|
|
10
|
+
* 2. `fire()` 자신의 `this.dispatchEvent(new CustomEvent(name, …))` 는 이름이 문자열이 아니라 변수라, 분석기가
|
|
11
|
+
* 변수 이름(`name`)과 이름 없는 항목을 이벤트로 적고 모든 하위 요소가 그것을 물려받는다 → 걷어 낸다.
|
|
12
|
+
* 판별은 «이름이 문자열 리터럴이 아닌 `dispatchEvent(new …)` 에서 나온, 설명 없는 항목» 이다(문서화된
|
|
13
|
+
* 이벤트는 건드리지 않는다).
|
|
14
|
+
*
|
|
15
|
+
* 대상(클래스 · 이벤트 이름)은 소스에서 도출하고 규칙만 여기 있다.
|
|
16
|
+
*
|
|
17
|
+
* @returns {import('@custom-elements-manifest/analyzer').Plugin}
|
|
18
|
+
*/
|
|
19
|
+
export default function eventsPlugin() {
|
|
20
|
+
/** `경로#클래스` → 이벤트 이름 → 생성자와 상세 타입 텍스트(없으면 null)
|
|
21
|
+
* @type {Map<string, Map<string, { ctor: string, detail: string | null }>>} */
|
|
22
|
+
const fired = new Map();
|
|
23
|
+
/** `경로#클래스` → 리터럴이 아닌 이름 식별자 텍스트
|
|
24
|
+
* @type {Map<string, Set<string>>} */
|
|
25
|
+
const dynamic = new Map();
|
|
26
|
+
/** 같은 이름을 여러 곳에서 내면 처음 본 쪽을 남긴다.
|
|
27
|
+
* @param {string} key @param {string} name @param {{ ctor: string, detail: string | null }} info */
|
|
28
|
+
const record = (key, name, info) => {
|
|
29
|
+
let events = fired.get(key);
|
|
30
|
+
if (!events)
|
|
31
|
+
fired.set(key, (events = new Map()));
|
|
32
|
+
if (!events.has(name))
|
|
33
|
+
events.set(name, info);
|
|
34
|
+
};
|
|
35
|
+
/** @type {import('@custom-elements-manifest/analyzer').Plugin} */
|
|
36
|
+
const plugin = {
|
|
37
|
+
name: 'u-events',
|
|
38
|
+
analyzePhase({ ts, node, moduleDoc }) {
|
|
39
|
+
if (!ts.isClassDeclaration(node) || !node.name)
|
|
40
|
+
return;
|
|
41
|
+
const key = `${moduleDoc.path}#${node.name.text}`;
|
|
42
|
+
// 분석기가 번들한 TypeScript 의 노드 타입 — 우리 TypeScript 와 판이 달라 `import('typescript')` 로 쓰면 어긋난다.
|
|
43
|
+
/** @param {import('@custom-elements-manifest/analyzer').AnalyzePhaseParams['node']} n */
|
|
44
|
+
const visit = (n) => {
|
|
45
|
+
if (ts.isCallExpression(n) && ts.isPropertyAccessExpression(n.expression)
|
|
46
|
+
&& n.expression.expression.kind === ts.SyntaxKind.ThisKeyword) {
|
|
47
|
+
const method = n.expression.name.text;
|
|
48
|
+
const first = n.arguments[0];
|
|
49
|
+
// `fire` 는 components 의 기반 클래스, `emit` 은 같은 일을 하는 도우미(dimension-timeline) — 이름 하나가 이벤트 이름인 호출이다.
|
|
50
|
+
if ((method === 'fire' || method === 'emit') && first && ts.isStringLiteralLike(first)) {
|
|
51
|
+
record(key, first.text, { ctor: 'CustomEvent', detail: n.typeArguments?.[0]?.getText() ?? null });
|
|
52
|
+
}
|
|
53
|
+
else if (method === 'dispatchEvent' && first && ts.isNewExpression(first)) {
|
|
54
|
+
const nameArg = first.arguments?.[0];
|
|
55
|
+
if (nameArg && ts.isStringLiteralLike(nameArg)) {
|
|
56
|
+
// 분석기는 메서드만 훑는다 — 화살표 함수 필드(`private onClick = () => { … }`) 안의 발화는 놓친다. 같은 규칙으로 더한다.
|
|
57
|
+
record(key, nameArg.text, { ctor: first.expression.getText(), detail: first.typeArguments?.[0]?.getText() ?? null });
|
|
58
|
+
}
|
|
59
|
+
else if (nameArg) {
|
|
60
|
+
let names = dynamic.get(key);
|
|
61
|
+
if (!names)
|
|
62
|
+
dynamic.set(key, (names = new Set()));
|
|
63
|
+
names.add(nameArg.getText());
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
ts.forEachChild(n, visit);
|
|
68
|
+
};
|
|
69
|
+
visit(node);
|
|
70
|
+
},
|
|
71
|
+
moduleLinkPhase({ moduleDoc }) {
|
|
72
|
+
for (const declaration of moduleDoc.declarations ?? []) {
|
|
73
|
+
if (declaration.kind !== 'class')
|
|
74
|
+
continue;
|
|
75
|
+
// 매니페스트 스키마의 클래스 선언(`events` 를 가진다) — 분석기 타입은 선언 종류의 합집합이라 좁힌다.
|
|
76
|
+
const decl = /** @type {{ name: string, events?: { name?: string, description?: string, type?: { text: string } }[] }} */ (declaration);
|
|
77
|
+
const key = `${moduleDoc.path}#${decl.name}`;
|
|
78
|
+
const names = dynamic.get(key);
|
|
79
|
+
const events = (decl.events ?? []).filter((e) => e.name && !(names?.has(e.name) && !e.description));
|
|
80
|
+
for (const [name, { ctor, detail }] of fired.get(key) ?? []) {
|
|
81
|
+
const type = { text: detail ? `${ctor}<${detail}>` : ctor };
|
|
82
|
+
const existing = events.find((e) => e.name === name);
|
|
83
|
+
if (!existing)
|
|
84
|
+
events.push({ name, type });
|
|
85
|
+
else if (!existing.type)
|
|
86
|
+
existing.type = type;
|
|
87
|
+
}
|
|
88
|
+
if (events.length)
|
|
89
|
+
decl.events = events;
|
|
90
|
+
else
|
|
91
|
+
delete decl.events;
|
|
92
|
+
}
|
|
93
|
+
},
|
|
94
|
+
};
|
|
95
|
+
return plugin;
|
|
96
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* 열거형 속성의 «허용 값 목록» 을 한 자리에서 적고, 그것이 **타입의 유니온과 어긋나지 않음을 컴파일러가 잰다**.
|
|
3
|
+
*
|
|
4
|
+
* 왜 이 모양인가 — 템플릿의 속성 문자열(버튼의 외형에 목록에 없는 이름을 적은 것)은 타입 검사를 받지 않고, 목록 밖의 값은 어떤
|
|
5
|
+
* 스타일 규칙에도 안 걸려 **에러 없이 기본 모양으로 떨어진다**(소비자 실측: 현재 탭 표시가 통째로 사라졌는데 콘솔이 비어
|
|
6
|
+
* 있었다). 그 값을 개발 모드에서 한 번 알리려면 런타임에 허용 값 목록이 있어야 하는데, 타입은 지워진다.
|
|
7
|
+
*
|
|
8
|
+
* - 유니온 별칭은 **그대로 리터럴 유니온으로 둔다** — `attr-value-check` 가 같은 파일의 `export type X = "a" | "b"` 를 읽어
|
|
9
|
+
* 소비 코드의 속성값을 잰다. 별칭을 `typeof LIST[number]` 로 바꾸면 그 검사가 조용히 눈이 먼다.
|
|
10
|
+
* - 목록은 이 도우미로 적는다: 유니온에 있는 값을 하나라도 빠뜨리면 **컴파일이 실패한다**(목록 ⊇ 유니온), 유니온에 없는 값을
|
|
11
|
+
* 적어도 실패한다(목록 ⊆ 유니온). 그래서 둘이 낡는 일이 없다.
|
|
12
|
+
*
|
|
13
|
+
* ```ts
|
|
14
|
+
* type ButtonSize = 'sm' | 'md' | 'lg';
|
|
15
|
+
* static override enumerated = { size: enumeratedValues<ButtonSize>()(['sm', 'md', 'lg']) };
|
|
16
|
+
* ```
|
|
17
|
+
*
|
|
18
|
+
* 빠뜨렸을 때의 컴파일 오류는 «`never` 에 할당할 수 없다» 로 보인다 — 인자 목록이 유니온을 다 덮지 못한다는 뜻이다.
|
|
19
|
+
*/
|
|
20
|
+
export declare function enumeratedValues<T extends string>(): <const L extends readonly T[]>(values: L & ([T] extends [L[number]] ? unknown : never)) => readonly T[];
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// src/utilities/enumerated.ts
|
|
2
|
+
/**
|
|
3
|
+
* 열거형 속성의 «허용 값 목록» 을 한 자리에서 적고, 그것이 **타입의 유니온과 어긋나지 않음을 컴파일러가 잰다**.
|
|
4
|
+
*
|
|
5
|
+
* 왜 이 모양인가 — 템플릿의 속성 문자열(버튼의 외형에 목록에 없는 이름을 적은 것)은 타입 검사를 받지 않고, 목록 밖의 값은 어떤
|
|
6
|
+
* 스타일 규칙에도 안 걸려 **에러 없이 기본 모양으로 떨어진다**(소비자 실측: 현재 탭 표시가 통째로 사라졌는데 콘솔이 비어
|
|
7
|
+
* 있었다). 그 값을 개발 모드에서 한 번 알리려면 런타임에 허용 값 목록이 있어야 하는데, 타입은 지워진다.
|
|
8
|
+
*
|
|
9
|
+
* - 유니온 별칭은 **그대로 리터럴 유니온으로 둔다** — `attr-value-check` 가 같은 파일의 `export type X = "a" | "b"` 를 읽어
|
|
10
|
+
* 소비 코드의 속성값을 잰다. 별칭을 `typeof LIST[number]` 로 바꾸면 그 검사가 조용히 눈이 먼다.
|
|
11
|
+
* - 목록은 이 도우미로 적는다: 유니온에 있는 값을 하나라도 빠뜨리면 **컴파일이 실패한다**(목록 ⊇ 유니온), 유니온에 없는 값을
|
|
12
|
+
* 적어도 실패한다(목록 ⊆ 유니온). 그래서 둘이 낡는 일이 없다.
|
|
13
|
+
*
|
|
14
|
+
* ```ts
|
|
15
|
+
* type ButtonSize = 'sm' | 'md' | 'lg';
|
|
16
|
+
* static override enumerated = { size: enumeratedValues<ButtonSize>()(['sm', 'md', 'lg']) };
|
|
17
|
+
* ```
|
|
18
|
+
*
|
|
19
|
+
* 빠뜨렸을 때의 컴파일 오류는 «`never` 에 할당할 수 없다» 로 보인다 — 인자 목록이 유니온을 다 덮지 못한다는 뜻이다.
|
|
20
|
+
*/
|
|
21
|
+
function enumeratedValues() {
|
|
22
|
+
return (values) => values;
|
|
23
|
+
}
|
|
24
|
+
export { enumeratedValues };
|
package/dist/utilities/format.js
CHANGED
|
@@ -77,6 +77,37 @@ function decimalSeparatorOf(locale) {
|
|
|
77
77
|
}
|
|
78
78
|
/** Space-like characters and apostrophes that locales use to group digits (fr/ru NBSP, de-CH ’). */
|
|
79
79
|
var GROUP_MARKS = /[\s\u00A0\u202F\u2009'\u2019]/;
|
|
80
|
+
/** The direction marks a formatted number can carry (`formatNumber` in Arabic and Hebrew puts one before the minus sign). */
|
|
81
|
+
var DIRECTION_MARKS = /[--]/g;
|
|
82
|
+
var DECIMAL_DIGIT = /^\p{Nd}$/u;
|
|
83
|
+
/**
|
|
84
|
+
* The value `0`–`9` of a decimal digit written in any script. Unicode lays every script's ten digits out in one run, zero
|
|
85
|
+
* first, and runs that touch are still whole multiples of ten, so the distance from the start of the run decides it — no
|
|
86
|
+
* table of scripts to keep.
|
|
87
|
+
*/
|
|
88
|
+
function digitValue(digit) {
|
|
89
|
+
const code = digit.codePointAt(0);
|
|
90
|
+
if (code < 128) return digit;
|
|
91
|
+
let start = code;
|
|
92
|
+
while (start > 0 && DECIMAL_DIGIT.test(String.fromCodePoint(start - 1))) start--;
|
|
93
|
+
return String((code - start) % 10);
|
|
94
|
+
}
|
|
95
|
+
/**
|
|
96
|
+
* Text as a person types or pastes it, brought to the ASCII digits the readers below know: the digits of any script
|
|
97
|
+
* (Arabic-Indic `٠`–`٩`, Persian `۰`–`۹`, Bengali, Devanagari, full-width `0`–`9` from an IME …) become `0`–`9`, and the
|
|
98
|
+
* direction marks a formatted Arabic or Hebrew text carries are dropped. Text without any of these comes back unchanged.
|
|
99
|
+
*/
|
|
100
|
+
function asciiDigits(text) {
|
|
101
|
+
return text.replace(DIRECTION_MARKS, "").replace(/\p{Nd}/gu, digitValue);
|
|
102
|
+
}
|
|
103
|
+
/**
|
|
104
|
+
* {@link asciiDigits}, and the separators of an Arabic keyboard brought to the ones the number reader below knows: the Arabic
|
|
105
|
+
* decimal separator `٫` becomes `.` and the Arabic thousands separator `٬` the apostrophe group mark (kept as a mark, so a
|
|
106
|
+
* leading one is still an error).
|
|
107
|
+
*/
|
|
108
|
+
function readableDigits(text) {
|
|
109
|
+
return asciiDigits(text).replace(/٫/g, ".").replace(/٬/g, "'");
|
|
110
|
+
}
|
|
80
111
|
/**
|
|
81
112
|
* Reads a number the way a person types it, in any locale — the inverse of {@link formatNumber}.
|
|
82
113
|
* Returns `null` for text that is not a number; never a partial number (`"1,5x"` is `null`, not 1.5).
|
|
@@ -99,7 +130,7 @@ var GROUP_MARKS = /[\s\u00A0\u202F\u2009'\u2019]/;
|
|
|
99
130
|
* `locale` defaults to the active `Locale`.
|
|
100
131
|
*/
|
|
101
132
|
function parseNumber(text, locale) {
|
|
102
|
-
const signed = text.trim().match(/^([+\-\u2212]?)(.*)$/s);
|
|
133
|
+
const signed = readableDigits(text).trim().match(/^([+\-\u2212]?)(.*)$/s);
|
|
103
134
|
const negative = signed[1] === "-" || signed[1] === "−";
|
|
104
135
|
const scientific = signed[2].match(/^(.*?)[eE]([+-]?)(\d+)$/s);
|
|
105
136
|
const body = scientific ? scientific[1] : signed[2];
|
|
@@ -130,13 +161,20 @@ function parseNumber(text, locale) {
|
|
|
130
161
|
const value = Number(`${negative ? "-" : ""}${digits || "0"}.${fracPart || "0"}e${exponent}`);
|
|
131
162
|
return Number.isFinite(value) ? value : null;
|
|
132
163
|
}
|
|
164
|
+
/**
|
|
165
|
+
* A date in a text field is always Gregorian, whatever calendar the locale prefers (`fa` writes the Persian year 1405, `th` the
|
|
166
|
+
* Buddhist 2569): the value is a Gregorian ISO date and the calendar next to the field is Gregorian, so a text in another
|
|
167
|
+
* calendar would read back as a different day.
|
|
168
|
+
*/
|
|
169
|
+
var TEXT_DATE_OPTIONS = {
|
|
170
|
+
calendar: "gregory",
|
|
171
|
+
year: "numeric",
|
|
172
|
+
month: "2-digit",
|
|
173
|
+
day: "2-digit"
|
|
174
|
+
};
|
|
133
175
|
/** The year/month/day order and separator the locale's numeric date uses (`en-US` → month/day/year · `/`). */
|
|
134
176
|
function numericDateLayout(locale) {
|
|
135
|
-
const parts = new Intl.DateTimeFormat(locale,
|
|
136
|
-
year: "numeric",
|
|
137
|
-
month: "2-digit",
|
|
138
|
-
day: "2-digit"
|
|
139
|
-
}).formatToParts(new Date(2026, 9, 2));
|
|
177
|
+
const parts = new Intl.DateTimeFormat(locale, TEXT_DATE_OPTIONS).formatToParts(new Date(2026, 9, 2));
|
|
140
178
|
return {
|
|
141
179
|
order: parts.filter((p) => p.type === "year" || p.type === "month" || p.type === "day").map((p) => p.type),
|
|
142
180
|
separator: parts.find((p) => p.type === "literal")?.value ?? "-"
|
|
@@ -150,11 +188,7 @@ function numericDateLayout(locale) {
|
|
|
150
188
|
function formatDateText(iso, format = "iso", locale) {
|
|
151
189
|
const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(iso);
|
|
152
190
|
if (!m || format === "iso") return iso;
|
|
153
|
-
return new Intl.DateTimeFormat(locale ?? Locale.get(),
|
|
154
|
-
year: "numeric",
|
|
155
|
-
month: "2-digit",
|
|
156
|
-
day: "2-digit"
|
|
157
|
-
}).format(new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
|
|
191
|
+
return new Intl.DateTimeFormat(locale ?? Locale.get(), TEXT_DATE_OPTIONS).format(new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3])));
|
|
158
192
|
}
|
|
159
193
|
/** The pattern a person should type for `format` — `YYYY-MM-DD`, or e.g. `MM/DD/YYYY` for `locale` in `en-US`. */
|
|
160
194
|
function dateTextPattern(format = "iso", locale) {
|
|
@@ -179,7 +213,7 @@ function dateTextPattern(format = "iso", locale) {
|
|
|
179
213
|
* (today by default). Two-digit years are not read.
|
|
180
214
|
*/
|
|
181
215
|
function parseDate(text, options = {}) {
|
|
182
|
-
const t = text.trim().replace(/\.$/, "");
|
|
216
|
+
const t = asciiDigits(text).trim().replace(/\.$/, "");
|
|
183
217
|
if (!t) return null;
|
|
184
218
|
let y, mo, d;
|
|
185
219
|
const compact = /^(\d{4})(\d{2})(\d{2})$/.exec(t);
|
|
@@ -226,7 +260,7 @@ function parseDate(text, options = {}) {
|
|
|
226
260
|
* takes `defaultTime` (`00:00` unless given). An hour above 23, or a minute or second above 59, is `null`.
|
|
227
261
|
*/
|
|
228
262
|
function parseDateTime(text, options = {}) {
|
|
229
|
-
const t = text.trim();
|
|
263
|
+
const t = asciiDigits(text).trim();
|
|
230
264
|
const words = meridiemWords(options.locale ?? Locale.get());
|
|
231
265
|
const joined = words.unspaced ? `|(?=${words.unspaced})` : "";
|
|
232
266
|
const m = new RegExp(`^(.*?)(?:(?:[T\\s]+${joined})(${words.timeOfDay}))?$`, "iu").exec(t);
|
|
@@ -304,7 +338,7 @@ var RANGE_SEPARATOR = /\s*[~–—]\s*|\s+-\s+/;
|
|
|
304
338
|
* fall before the first day (`2025-12-20 ~ 01-05`).
|
|
305
339
|
*/
|
|
306
340
|
function parseDateRange(text, options = {}) {
|
|
307
|
-
const t = text.trim();
|
|
341
|
+
const t = asciiDigits(text).trim();
|
|
308
342
|
if (!t) return null;
|
|
309
343
|
let parts = t.split(RANGE_SEPARATOR);
|
|
310
344
|
if (parts.length === 1) {
|
|
@@ -354,7 +388,7 @@ function formatDateRangeText(start, end, format = "iso", locale) {
|
|
|
354
388
|
* `YYYY-MM-DDTHH:mm:ss` (see {@link parseDateTime}).
|
|
355
389
|
*/
|
|
356
390
|
function parseDateTimeRange(text, options = {}) {
|
|
357
|
-
const t = text.trim();
|
|
391
|
+
const t = asciiDigits(text).trim();
|
|
358
392
|
if (!t) return null;
|
|
359
393
|
const startTime = options.startTime ?? "00:00";
|
|
360
394
|
const endTime = options.endTime ?? "23:59";
|