@intlayer/design-system 8.7.6 → 8.7.8-canary.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/dist/esm/components/Breadcrumb/index.mjs.map +1 -1
- package/dist/esm/components/Browser/Browser.mjs.map +1 -1
- package/dist/esm/components/Carousel/index.mjs.map +1 -1
- package/dist/esm/components/ContentEditor/ContentEditorTextArea.mjs +1 -1
- package/dist/esm/components/DictionaryEditor/NodeWrapper/BooleanWrapper.mjs.map +1 -1
- package/dist/esm/components/DictionaryEditor/NodeWrapper/NestedObjectWrapper.mjs.map +1 -1
- package/dist/esm/components/DictionaryEditor/NodeWrapper/NumberWrapper.mjs.map +1 -1
- package/dist/esm/components/DictionaryEditor/NodeWrapper/index.mjs.map +1 -1
- package/dist/esm/components/DictionaryFieldEditor/ContentEditorView/TextEditor.mjs +2 -2
- package/dist/esm/components/DictionaryFieldEditor/DictionaryCreationForm/DictionaryCreationForm.mjs +1 -1
- package/dist/esm/components/DictionaryFieldEditor/DictionaryDetails/DictionaryDetailsForm.mjs +3 -3
- package/dist/esm/components/DictionaryFieldEditor/DictionaryFieldEditor.mjs +1 -1
- package/dist/esm/components/DictionaryFieldEditor/EnumKeyInput.mjs.map +1 -1
- package/dist/esm/components/DictionaryFieldEditor/KeyPathBreadcrumb.mjs.map +1 -1
- package/dist/esm/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.mjs +2 -2
- package/dist/esm/components/DictionaryFieldEditor/NavigationView/NavigationViewNode.mjs.map +1 -1
- package/dist/esm/components/DictionaryFieldEditor/NodeTypeSelector.mjs.map +1 -1
- package/dist/esm/components/DictionaryFieldEditor/SaveForm/SaveForm.mjs +2 -2
- package/dist/esm/components/DictionaryFieldEditor/SaveForm/SaveForm.mjs.map +1 -1
- package/dist/esm/components/DictionaryFieldEditor/StructureView/StructureView.mjs +1 -1
- package/dist/esm/components/DictionaryFieldEditor/StructureView/StructureView.mjs.map +1 -1
- package/dist/esm/components/EditableField/EditableFieldInput.mjs.map +1 -1
- package/dist/esm/components/Flags/Flag.mjs.map +1 -1
- package/dist/esm/components/Form/FormField.mjs.map +1 -1
- package/dist/esm/components/Form/FormItem.mjs.map +1 -1
- package/dist/esm/components/Form/elements/FormElementWrapper.mjs.map +1 -1
- package/dist/esm/components/Form/elements/OTPElement.mjs +1 -1
- package/dist/esm/components/HTMLRender/HTMLRender.mjs.map +1 -1
- package/dist/esm/components/Headers/index.mjs.map +1 -1
- package/dist/esm/components/HeightResizer/index.mjs +25 -0
- package/dist/esm/components/HeightResizer/index.mjs.map +1 -1
- package/dist/esm/components/IDE/Code.mjs +96 -13
- package/dist/esm/components/IDE/Code.mjs.map +1 -1
- package/dist/esm/components/IDE/CodeBlockHighlight.mjs +77 -0
- package/dist/esm/components/IDE/CodeBlockHighlight.mjs.map +1 -0
- package/dist/esm/components/IDE/CodeBlockServer.mjs.map +1 -1
- package/dist/esm/components/IDE/CodeConditionalRenderer.mjs +15 -4
- package/dist/esm/components/IDE/CodeConditionalRenderer.mjs.map +1 -1
- package/dist/esm/components/IDE/CodeFormatSelector.mjs +5 -4
- package/dist/esm/components/IDE/CodeFormatSelector.mjs.map +1 -1
- package/dist/esm/components/IDE/FileTree.mjs.map +1 -1
- package/dist/esm/components/IDE/IDE.mjs.map +1 -1
- package/dist/esm/components/IDE/codeTransformer.mjs +228 -0
- package/dist/esm/components/IDE/codeTransformer.mjs.map +1 -0
- package/dist/esm/components/Input/OTPInput.mjs.map +1 -1
- package/dist/esm/components/KeyboardShortcut/KeyboardShortcut.mjs.map +1 -1
- package/dist/esm/components/LocaleSwitcherContentDropDown/LocaleSwitcherContent.mjs +1 -1
- package/dist/esm/components/LocaleSwitcherContentDropDown/LocaleSwitcherContent.mjs.map +1 -1
- package/dist/esm/components/LocaleSwitcherDropDown/LocaleSwitcher.mjs.map +1 -1
- package/dist/esm/components/MarkDownRender/MarkDownIframe.mjs +101 -0
- package/dist/esm/components/MarkDownRender/MarkDownIframe.mjs.map +1 -0
- package/dist/esm/components/MarkDownRender/MarkDownRender.mjs +2 -9
- package/dist/esm/components/MarkDownRender/MarkDownRender.mjs.map +1 -1
- package/dist/esm/components/Modal/Modal.mjs +2 -2
- package/dist/esm/components/Navbar/MobileNavbar.mjs +1 -1
- package/dist/esm/components/Navbar/index.mjs +1 -3
- package/dist/esm/components/Navbar/index.mjs.map +1 -1
- package/dist/esm/components/Navbar/useNavigation.mjs +3 -0
- package/dist/esm/components/Navbar/useNavigation.mjs.map +1 -1
- package/dist/esm/components/Pagination/Pagination.mjs +1 -1
- package/dist/esm/components/Popover/dynamic.mjs.map +1 -1
- package/dist/esm/components/RightDrawer/RightDrawer.mjs +3 -3
- package/dist/esm/components/Select/Multiselect.mjs.map +1 -1
- package/dist/esm/components/Tab/Tab.mjs.map +1 -1
- package/dist/esm/components/TechLogo/TechLogo.mjs.map +1 -1
- package/dist/esm/components/TextArea/AutocompleteTextArea.mjs.map +1 -1
- package/dist/esm/components/TextArea/ContentEditableTextArea.mjs.map +1 -1
- package/dist/esm/components/Toaster/Toast.mjs +6 -1
- package/dist/esm/components/Toaster/Toast.mjs.map +1 -1
- package/dist/esm/components/WithResizer/index.mjs +24 -0
- package/dist/esm/components/WithResizer/index.mjs.map +1 -1
- package/dist/esm/hooks/index.mjs +11 -11
- package/dist/esm/hooks/reactQuery.mjs +49 -2
- package/dist/esm/hooks/reactQuery.mjs.map +1 -1
- package/dist/esm/hooks/useAuth/useOAuth2.mjs +1 -1
- package/dist/esm/hooks/useAuth/useOAuth2.mjs.map +1 -1
- package/dist/esm/hooks/useAuth/useSession.mjs +1 -1
- package/dist/esm/hooks/useAuth/useSession.mjs.map +1 -1
- package/dist/esm/hooks/useDevice.mjs.map +1 -1
- package/dist/esm/hooks/useHorizontalSwipe.mjs.map +1 -1
- package/dist/esm/hooks/useIsDarkMode.mjs.map +1 -1
- package/dist/esm/hooks/useKeyboardDetector.mjs.map +1 -1
- package/dist/esm/hooks/useScrollBlockage/useScrollBlockageStore.mjs.map +1 -1
- package/dist/esm/libs/auth.mjs +1 -1
- package/dist/esm/libs/auth.mjs.map +1 -1
- package/dist/esm/providers/ReactQueryProvider.mjs.map +1 -1
- package/dist/esm/tailwind.config.mjs.map +1 -1
- package/dist/types/components/Badge/index.d.ts +2 -2
- package/dist/types/components/Button/Button.d.ts +4 -4
- package/dist/types/components/Command/index.d.ts +1 -1
- package/dist/types/components/Container/index.d.ts +7 -7
- package/dist/types/components/HeightResizer/index.d.ts.map +1 -1
- package/dist/types/components/IDE/Code.d.ts +3 -3
- package/dist/types/components/IDE/Code.d.ts.map +1 -1
- package/dist/types/components/IDE/CodeBlockHighlight.d.ts +20 -0
- package/dist/types/components/IDE/CodeBlockHighlight.d.ts.map +1 -0
- package/dist/types/components/IDE/CodeConditionalRenderer.d.ts.map +1 -1
- package/dist/types/components/IDE/CodeFormatSelector.d.ts +5 -1
- package/dist/types/components/IDE/CodeFormatSelector.d.ts.map +1 -1
- package/dist/types/components/IDE/codeTransformer.d.ts +25 -0
- package/dist/types/components/IDE/codeTransformer.d.ts.map +1 -0
- package/dist/types/components/Input/Checkbox.d.ts +2 -2
- package/dist/types/components/Link/Link.d.ts +4 -4
- package/dist/types/components/MarkDownRender/MarkDownIframe.d.ts +7 -0
- package/dist/types/components/MarkDownRender/MarkDownIframe.d.ts.map +1 -0
- package/dist/types/components/MarkDownRender/MarkDownRender.d.ts.map +1 -1
- package/dist/types/components/Pagination/Pagination.d.ts +1 -1
- package/dist/types/components/SwitchSelector/index.d.ts +1 -1
- package/dist/types/components/Tab/Tab.d.ts +1 -1
- package/dist/types/components/TabSelector/TabSelector.d.ts +1 -1
- package/dist/types/components/Tag/index.d.ts +3 -3
- package/dist/types/components/Toaster/Toast.d.ts +1 -1
- package/dist/types/components/WithResizer/index.d.ts.map +1 -1
- package/dist/types/hooks/index.d.ts +2 -2
- package/dist/types/hooks/reactQuery.d.ts +8 -1
- package/dist/types/hooks/reactQuery.d.ts.map +1 -1
- package/package.json +25 -25
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
//#region src/components/IDE/codeTransformer.ts
|
|
2
|
+
const trim = (text) => text.trim();
|
|
3
|
+
/**
|
|
4
|
+
* Given a string like `{ A, type B, C as D }`, return the non-type named
|
|
5
|
+
* members preserving aliases: `[{ name:'A', alias:undefined }, { name:'C', alias:'D' }]`.
|
|
6
|
+
*/
|
|
7
|
+
const parseNamedImports = (inner) => inner.split(",").map(trim).filter(Boolean).map((member) => {
|
|
8
|
+
const isType = /^type\s+/.test(member);
|
|
9
|
+
const asParts = member.replace(/^type\s+/, "").trim().split(/\s+as\s+/);
|
|
10
|
+
return {
|
|
11
|
+
name: trim(asParts[0]),
|
|
12
|
+
alias: asParts[1] ? trim(asParts[1]) : void 0,
|
|
13
|
+
isType
|
|
14
|
+
};
|
|
15
|
+
});
|
|
16
|
+
/** Render a named imports list back to `{ A, B as C }` style. */
|
|
17
|
+
const renderNamedImports = (members) => {
|
|
18
|
+
return `{ ${members.map((member) => member.alias ? `${member.name} as ${member.alias}` : member.name).join(", ")} }`;
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* Parse all import statements from `code`.
|
|
22
|
+
* Returns them in order together with their start/end char positions.
|
|
23
|
+
*/
|
|
24
|
+
const parseImports = (code) => {
|
|
25
|
+
const result = [];
|
|
26
|
+
const importStatementRegex = /^import\s+(type\s+)?(?:([^\s{,;"'`]+)\s*,?\s*)?(?:\{([^}]*)\}\s*,?\s*)?(?:from\s+["']([^"']+)["'])?(?:\s*["']([^"']+)["'])?;?/gm;
|
|
27
|
+
let importMatch = importStatementRegex.exec(code);
|
|
28
|
+
while (importMatch !== null) {
|
|
29
|
+
const isTypeOnly = !!importMatch[1];
|
|
30
|
+
const defaultPart = importMatch[2] ? trim(importMatch[2]) : void 0;
|
|
31
|
+
const namedPart = importMatch[3] ?? "";
|
|
32
|
+
const fromModule = importMatch[4] ?? importMatch[5] ?? "";
|
|
33
|
+
const isSideEffect = !defaultPart && !namedPart && !isTypeOnly && !!fromModule;
|
|
34
|
+
const named = namedPart ? parseNamedImports(namedPart) : [];
|
|
35
|
+
result.push({
|
|
36
|
+
raw: importMatch[0],
|
|
37
|
+
start: importMatch.index,
|
|
38
|
+
end: importMatch.index + importMatch[0].length,
|
|
39
|
+
source: fromModule,
|
|
40
|
+
defaultImport: defaultPart,
|
|
41
|
+
named,
|
|
42
|
+
isSideEffect,
|
|
43
|
+
isTypeOnly
|
|
44
|
+
});
|
|
45
|
+
importMatch = importStatementRegex.exec(code);
|
|
46
|
+
}
|
|
47
|
+
return result;
|
|
48
|
+
};
|
|
49
|
+
/** Build map: typeName → module path, from parsed imports. */
|
|
50
|
+
const buildTypeMap = (imports) => {
|
|
51
|
+
const map = /* @__PURE__ */ new Map();
|
|
52
|
+
for (const parsedImport of imports) if (parsedImport.isTypeOnly) {
|
|
53
|
+
for (const namedMember of parsedImport.named) if (!map.has(namedMember.name)) map.set(namedMember.name, parsedImport.source);
|
|
54
|
+
} else for (const namedMember of parsedImport.named) if (namedMember.isType && !map.has(namedMember.name)) map.set(namedMember.name, parsedImport.source);
|
|
55
|
+
return map;
|
|
56
|
+
};
|
|
57
|
+
const renderImportESM = (parsedImport) => {
|
|
58
|
+
if (parsedImport.isTypeOnly) return null;
|
|
59
|
+
const valueNamed = parsedImport.named.filter((namedMember) => !namedMember.isType);
|
|
60
|
+
if (!valueNamed.length && !parsedImport.defaultImport && !parsedImport.isSideEffect) return null;
|
|
61
|
+
if (parsedImport.isSideEffect) return `import '${parsedImport.source}';`;
|
|
62
|
+
if (parsedImport.defaultImport && valueNamed.length) return `import ${parsedImport.defaultImport}, ${renderNamedImports(valueNamed)} from '${parsedImport.source}';`;
|
|
63
|
+
if (parsedImport.defaultImport) return `import ${parsedImport.defaultImport} from '${parsedImport.source}';`;
|
|
64
|
+
return `import ${renderNamedImports(valueNamed)} from '${parsedImport.source}';`;
|
|
65
|
+
};
|
|
66
|
+
const renderImportCJS = (parsedImport) => {
|
|
67
|
+
if (parsedImport.isTypeOnly) return null;
|
|
68
|
+
const valueNamed = parsedImport.named.filter((namedMember) => !namedMember.isType);
|
|
69
|
+
const hasDefault = !!parsedImport.defaultImport;
|
|
70
|
+
const hasNamed = valueNamed.length > 0;
|
|
71
|
+
if (parsedImport.isSideEffect) return `require('${parsedImport.source}');`;
|
|
72
|
+
if (hasDefault && hasNamed) return `const ${renderNamedImports([{
|
|
73
|
+
name: "default",
|
|
74
|
+
alias: parsedImport.defaultImport
|
|
75
|
+
}, ...valueNamed])} = require('${parsedImport.source}');`;
|
|
76
|
+
if (hasDefault && !hasNamed) return `const ${parsedImport.defaultImport} = require('${parsedImport.source}');`;
|
|
77
|
+
if (!hasDefault && hasNamed) return `const ${renderNamedImports(valueNamed)} = require('${parsedImport.source}');`;
|
|
78
|
+
return null;
|
|
79
|
+
};
|
|
80
|
+
/**
|
|
81
|
+
* Strip TypeScript type annotations from a code string (line by line with
|
|
82
|
+
* some multi-line awareness). Returns the stripped code and a list of JSDoc
|
|
83
|
+
* comments to insert before specific lines (indexed by original line number).
|
|
84
|
+
*/
|
|
85
|
+
const stripTypeAnnotations = (code, typeMap) => {
|
|
86
|
+
const lines = code.split("\n");
|
|
87
|
+
const jsdocInserts = /* @__PURE__ */ new Map();
|
|
88
|
+
const out = [];
|
|
89
|
+
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
|
|
90
|
+
let line = lines[lineIndex];
|
|
91
|
+
const varTypeMatch = line.match(/^(\s*(?:export\s+)?(?:const|let|var)\s+\w+)\s*:\s*([A-Z]\w*)\s*=/);
|
|
92
|
+
if (varTypeMatch) {
|
|
93
|
+
const typeName = varTypeMatch[2];
|
|
94
|
+
const modulePath = typeMap.get(typeName);
|
|
95
|
+
if (modulePath) jsdocInserts.set(out.length, `/** @type {import('${modulePath}').${typeName}} */`);
|
|
96
|
+
line = line.replace(/^(\s*(?:export\s+)?(?:const|let|var)\s+\w+)\s*:\s*[A-Z][\w<>, ]*?\s*=/, "$1 =");
|
|
97
|
+
}
|
|
98
|
+
line = line.replace(/^(\s*(?:export\s+)?(?:const|let|var)\s+\w+)\s*:\s*\w+<[^>]*>\s*=/, "$1 =");
|
|
99
|
+
line = line.replace(/\}\s*:\s*\w[\w<>, .]*\s*\)/, "})");
|
|
100
|
+
line = line.replace(/\)\s*:\s*\w[\w<>, .]*\s*(=>|\{)/, ") $1");
|
|
101
|
+
line = line.replace(/\s+satisfies\s+\w[\w<>, .]*\s*;/, ";");
|
|
102
|
+
line = line.replace(/\s+as\s+(?!const\b)\w[\w<>, .]*/, "");
|
|
103
|
+
line = line.replace(/(<\w+>)\(/, "(");
|
|
104
|
+
line = line.replace(/(\w+)<[A-Z]\w*(?:,\s*[A-Z]\w*)*>\(/g, "$1(");
|
|
105
|
+
line = line.replace(/(\w)\s*:\s*[A-Z]\w*(\))/g, "$1$2");
|
|
106
|
+
out.push(line);
|
|
107
|
+
}
|
|
108
|
+
const insertPositions = [...jsdocInserts.entries()].sort((first, second) => second[0] - first[0]);
|
|
109
|
+
for (const [pos, jsdoc] of insertPositions) {
|
|
110
|
+
const indent = (out[pos] ?? "").match(/^(\s*)/)?.[1] ?? "";
|
|
111
|
+
out.splice(pos, 0, indent + jsdoc);
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
code: out.join("\n"),
|
|
115
|
+
jsdocInserts
|
|
116
|
+
};
|
|
117
|
+
};
|
|
118
|
+
const processExportsCJS = (code) => {
|
|
119
|
+
const lines = code.split("\n");
|
|
120
|
+
const collected = [];
|
|
121
|
+
let defaultExport = null;
|
|
122
|
+
const requireLines = [];
|
|
123
|
+
const out = [];
|
|
124
|
+
for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {
|
|
125
|
+
const line = lines[lineIndex];
|
|
126
|
+
const defMatch = line.match(/^(\s*)export\s+default\s+(.+?);?\s*$/);
|
|
127
|
+
if (defMatch) {
|
|
128
|
+
defaultExport = trim(defMatch[2]);
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
const exportConstMatch = line.match(/^(\s*)export\s+(const|let|var)\s+(\w+)/);
|
|
132
|
+
if (exportConstMatch) {
|
|
133
|
+
const name = exportConstMatch[3];
|
|
134
|
+
collected.push({
|
|
135
|
+
localName: name,
|
|
136
|
+
exportedName: name
|
|
137
|
+
});
|
|
138
|
+
out.push(line.replace(/^(\s*)export\s+/, "$1"));
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
const exportFnMatch = line.match(/^(\s*)export\s+(?:async\s+)?function\s+(\w+)/);
|
|
142
|
+
if (exportFnMatch) {
|
|
143
|
+
const name = exportFnMatch[2];
|
|
144
|
+
collected.push({
|
|
145
|
+
localName: name,
|
|
146
|
+
exportedName: name
|
|
147
|
+
});
|
|
148
|
+
out.push(line.replace(/^(\s*)export\s+/, "$1"));
|
|
149
|
+
continue;
|
|
150
|
+
}
|
|
151
|
+
const reexportFromMatch = line.match(/^(\s*)export\s+\{([^}]+)\}\s+from\s+["']([^"']+)["'];?\s*$/);
|
|
152
|
+
if (reexportFromMatch) {
|
|
153
|
+
const members = parseNamedImports(reexportFromMatch[2]);
|
|
154
|
+
const modulePath = reexportFromMatch[3];
|
|
155
|
+
const valueMembers = members.filter((namedMember) => !namedMember.isType);
|
|
156
|
+
if (valueMembers.length) {
|
|
157
|
+
const origNames = valueMembers.map((namedMember) => namedMember.name);
|
|
158
|
+
requireLines.push(`const ${renderNamedImports(origNames.map((name) => ({ name })))} = require('${modulePath}');`);
|
|
159
|
+
for (const namedMember of valueMembers) collected.push({
|
|
160
|
+
localName: namedMember.name,
|
|
161
|
+
exportedName: namedMember.alias ?? namedMember.name
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
continue;
|
|
165
|
+
}
|
|
166
|
+
const namedExportMatch = line.match(/^(\s*)export\s+\{([^}]+)\};?\s*$/);
|
|
167
|
+
if (namedExportMatch) {
|
|
168
|
+
const members = parseNamedImports(namedExportMatch[2]).filter((namedMember) => !namedMember.isType);
|
|
169
|
+
for (const namedMember of members) collected.push({
|
|
170
|
+
localName: namedMember.name,
|
|
171
|
+
exportedName: namedMember.alias ?? namedMember.name
|
|
172
|
+
});
|
|
173
|
+
continue;
|
|
174
|
+
}
|
|
175
|
+
out.push(line);
|
|
176
|
+
}
|
|
177
|
+
const finalLines = requireLines.length ? [
|
|
178
|
+
...requireLines,
|
|
179
|
+
"",
|
|
180
|
+
...out
|
|
181
|
+
] : out;
|
|
182
|
+
if (defaultExport !== null && collected.length === 0) finalLines.push(`module.exports = ${defaultExport};`);
|
|
183
|
+
else if (defaultExport !== null && collected.length > 0) {
|
|
184
|
+
const parts = collected.map((exportEntry) => exportEntry.localName === exportEntry.exportedName ? exportEntry.localName : `${exportEntry.exportedName}: ${exportEntry.localName}`);
|
|
185
|
+
finalLines.push(`module.exports = { default: ${defaultExport}, ${parts.join(", ")} };`);
|
|
186
|
+
} else if (collected.length > 0) {
|
|
187
|
+
const parts = collected.map((exportEntry) => exportEntry.localName === exportEntry.exportedName ? exportEntry.localName : `${exportEntry.exportedName}: ${exportEntry.localName}`);
|
|
188
|
+
finalLines.push(`module.exports = { ${parts.join(", ")} };`);
|
|
189
|
+
}
|
|
190
|
+
return finalLines.join("\n");
|
|
191
|
+
};
|
|
192
|
+
const transformCode = (code, target) => {
|
|
193
|
+
const imports = parseImports(code);
|
|
194
|
+
const typeMap = buildTypeMap(imports);
|
|
195
|
+
let result = code;
|
|
196
|
+
const sorted = [...imports].sort((firstImport, secondImport) => secondImport.start - firstImport.start);
|
|
197
|
+
for (const parsedImport of sorted) {
|
|
198
|
+
const replacement = (target === "esm" ? renderImportESM(parsedImport) : renderImportCJS(parsedImport)) ?? "";
|
|
199
|
+
result = result.slice(0, parsedImport.start) + replacement + result.slice(parsedImport.end);
|
|
200
|
+
}
|
|
201
|
+
result = result.replace(/\n{3,}/g, "\n\n");
|
|
202
|
+
result = stripTypeAnnotations(result, typeMap).code;
|
|
203
|
+
if (target === "commonjs") result = processExportsCJS(result);
|
|
204
|
+
result = result.replace(/\n{3,}/g, "\n\n");
|
|
205
|
+
result = result.replace(/^\n+/, "").replace(/\n+$/, "");
|
|
206
|
+
return result;
|
|
207
|
+
};
|
|
208
|
+
/**
|
|
209
|
+
* Derive the file name for a transformed format.
|
|
210
|
+
* `next.config.ts` → `next.config.mjs` (ESM) / `next.config.cjs` (CJS)
|
|
211
|
+
* `layout.tsx` → `layout.jsx` (ESM or CJS — JSX always stays .jsx)
|
|
212
|
+
*/
|
|
213
|
+
const deriveFileName = (fileName, target) => {
|
|
214
|
+
if (target === "esm") return fileName.replace(/\.tsx$/, ".jsx").replace(/\.ts$/, ".mjs");
|
|
215
|
+
return fileName.replace(/\.tsx$/, ".jsx").replace(/\.ts$/, ".cjs");
|
|
216
|
+
};
|
|
217
|
+
/**
|
|
218
|
+
* Derive the syntax-highlighting language for a transformed format.
|
|
219
|
+
* `typescript` → `javascript`; `tsx` → `jsx`
|
|
220
|
+
*/
|
|
221
|
+
const deriveLanguage = (language, target) => {
|
|
222
|
+
if (target === "typescript") return language;
|
|
223
|
+
return language === "tsx" ? "jsx" : language === "typescript" ? "javascript" : language;
|
|
224
|
+
};
|
|
225
|
+
|
|
226
|
+
//#endregion
|
|
227
|
+
export { deriveFileName, deriveLanguage, transformCode };
|
|
228
|
+
//# sourceMappingURL=codeTransformer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"codeTransformer.mjs","names":[],"sources":["../../../../src/components/IDE/codeTransformer.ts"],"sourcesContent":["/**\n * Runtime transformer: converts TypeScript source code to ESM or CommonJS format.\n *\n * Design constraints:\n * - Regex/string based (no AST) — runs in the browser\n * - Handles patterns that actually appear in the Intlayer docs\n * - Intentionally limited: exotic TypeScript features may not transform perfectly\n */\n\nexport type TargetCodeFormat = 'esm' | 'commonjs' | 'typescript';\n\n// ── Helpers ─────────────────────────────────────────────────────────────────\n\nconst trim = (text: string) => text.trim();\n\n/**\n * Given a string like `{ A, type B, C as D }`, return the non-type named\n * members preserving aliases: `[{ name:'A', alias:undefined }, { name:'C', alias:'D' }]`.\n */\nconst parseNamedImports = (\n inner: string\n): Array<{ name: string; alias?: string; isType: boolean }> =>\n inner\n .split(',')\n .map(trim)\n .filter(Boolean)\n .map((member) => {\n const isType = /^type\\s+/.test(member);\n const clean = member.replace(/^type\\s+/, '').trim();\n const asParts = clean.split(/\\s+as\\s+/);\n return {\n name: trim(asParts[0]),\n alias: asParts[1] ? trim(asParts[1]) : undefined,\n isType,\n };\n });\n\n/** Render a named imports list back to `{ A, B as C }` style. */\nconst renderNamedImports = (\n members: Array<{ name: string; alias?: string }>\n) => {\n return `{ ${members.map((member) => (member.alias ? `${member.name} as ${member.alias}` : member.name)).join(', ')} }`;\n};\n\n// ── Import parser ────────────────────────────────────────────────────────────\n\ninterface ParsedImport {\n raw: string; // original source lines (may be multi-line)\n source: string;\n defaultImport?: string;\n named: Array<{ name: string; alias?: string; isType: boolean }>;\n isSideEffect: boolean; // `import 'mod'`\n isTypeOnly: boolean; // `import type { ... }`\n}\n\n/**\n * Parse all import statements from `code`.\n * Returns them in order together with their start/end char positions.\n */\nconst parseImports = (\n code: string\n): Array<ParsedImport & { start: number; end: number }> => {\n const result: Array<ParsedImport & { start: number; end: number }> = [];\n // Match the full import statement (possibly multi-line), stopping at the semicolon.\n // Do NOT consume trailing whitespace/newlines — those belong to the surrounding code.\n const importStatementRegex =\n /^import\\s+(type\\s+)?(?:([^\\s{,;\"'`]+)\\s*,?\\s*)?(?:\\{([^}]*)\\}\\s*,?\\s*)?(?:from\\s+[\"']([^\"']+)[\"'])?(?:\\s*[\"']([^\"']+)[\"'])?;?/gm;\n\n let importMatch: RegExpExecArray | null = importStatementRegex.exec(code);\n while (importMatch !== null) {\n const isTypeOnly = !!importMatch[1];\n const defaultPart = importMatch[2] ? trim(importMatch[2]) : undefined;\n const namedPart = importMatch[3] ?? '';\n const fromModule = importMatch[4] ?? importMatch[5] ?? '';\n\n const isSideEffect =\n !defaultPart && !namedPart && !isTypeOnly && !!fromModule;\n\n const named = namedPart ? parseNamedImports(namedPart) : [];\n\n result.push({\n raw: importMatch[0],\n start: importMatch.index,\n end: importMatch.index + importMatch[0].length,\n source: fromModule,\n defaultImport: defaultPart,\n named,\n isSideEffect,\n isTypeOnly,\n });\n importMatch = importStatementRegex.exec(code);\n }\n return result;\n};\n\n// ── Type map ─────────────────────────────────────────────────────────────────\n\n/** Build map: typeName → module path, from parsed imports. */\nconst buildTypeMap = (imports: ParsedImport[]): Map<string, string> => {\n const map = new Map<string, string>();\n for (const parsedImport of imports) {\n if (parsedImport.isTypeOnly) {\n for (const namedMember of parsedImport.named) {\n if (!map.has(namedMember.name))\n map.set(namedMember.name, parsedImport.source);\n }\n } else {\n for (const namedMember of parsedImport.named) {\n if (namedMember.isType && !map.has(namedMember.name))\n map.set(namedMember.name, parsedImport.source);\n }\n }\n }\n return map;\n};\n\n// ── Import renderers ─────────────────────────────────────────────────────────\n\nconst renderImportESM = (parsedImport: ParsedImport): string | null => {\n if (parsedImport.isTypeOnly) return null; // remove entirely\n const valueNamed = parsedImport.named.filter(\n (namedMember) => !namedMember.isType\n );\n if (\n !valueNamed.length &&\n !parsedImport.defaultImport &&\n !parsedImport.isSideEffect\n )\n return null;\n if (parsedImport.isSideEffect) return `import '${parsedImport.source}';`;\n\n if (parsedImport.defaultImport && valueNamed.length) {\n return `import ${parsedImport.defaultImport}, ${renderNamedImports(valueNamed)} from '${parsedImport.source}';`;\n }\n if (parsedImport.defaultImport)\n return `import ${parsedImport.defaultImport} from '${parsedImport.source}';`;\n return `import ${renderNamedImports(valueNamed)} from '${parsedImport.source}';`;\n};\n\nconst renderImportCJS = (parsedImport: ParsedImport): string | null => {\n if (parsedImport.isTypeOnly) return null;\n const valueNamed = parsedImport.named.filter(\n (namedMember) => !namedMember.isType\n );\n const hasDefault = !!parsedImport.defaultImport;\n const hasNamed = valueNamed.length > 0;\n\n if (parsedImport.isSideEffect) return `require('${parsedImport.source}');`;\n\n if (hasDefault && hasNamed) {\n // e.g. import express, { Router } from 'express'\n // → const { default: express, Router } = require('express') OR two lines\n const allMembers = [\n { name: 'default', alias: parsedImport.defaultImport },\n ...valueNamed,\n ];\n return `const ${renderNamedImports(allMembers)} = require('${parsedImport.source}');`;\n }\n if (hasDefault && !hasNamed) {\n return `const ${parsedImport.defaultImport} = require('${parsedImport.source}');`;\n }\n if (!hasDefault && hasNamed) {\n return `const ${renderNamedImports(valueNamed)} = require('${parsedImport.source}');`;\n }\n return null;\n};\n\n// ── Type annotation stripping ────────────────────────────────────────────────\n\n/**\n * Strip TypeScript type annotations from a code string (line by line with\n * some multi-line awareness). Returns the stripped code and a list of JSDoc\n * comments to insert before specific lines (indexed by original line number).\n */\nconst stripTypeAnnotations = (\n code: string,\n typeMap: Map<string, string>\n): { code: string; jsdocInserts: Map<number, string> } => {\n const lines = code.split('\\n');\n const jsdocInserts = new Map<number, string>();\n const out: string[] = [];\n\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n let line = lines[lineIndex];\n\n // 1. `const/let/var name: SimpleType =` — simple variable type annotation\n // Add JSDoc if the type resolves to a known import module.\n const varTypeMatch = line.match(\n /^(\\s*(?:export\\s+)?(?:const|let|var)\\s+\\w+)\\s*:\\s*([A-Z]\\w*)\\s*=/\n );\n if (varTypeMatch) {\n const typeName = varTypeMatch[2];\n const modulePath = typeMap.get(typeName);\n if (modulePath) {\n jsdocInserts.set(\n out.length,\n `/** @type {import('${modulePath}').${typeName}} */`\n );\n }\n line = line.replace(\n /^(\\s*(?:export\\s+)?(?:const|let|var)\\s+\\w+)\\s*:\\s*[A-Z][\\w<>, ]*?\\s*=/,\n '$1 ='\n );\n }\n\n // 2. `const/let/var name: FC<Props> =` — generic type annotation (no JSDoc)\n line = line.replace(\n /^(\\s*(?:export\\s+)?(?:const|let|var)\\s+\\w+)\\s*:\\s*\\w+<[^>]*>\\s*=/,\n '$1 ='\n );\n\n // 3. Destructured parameter with type: `}: TypeName):` → `}):`\n // Also handles return type: `): ReturnType =>` → `) =>`\n line = line.replace(/\\}\\s*:\\s*\\w[\\w<>, .]*\\s*\\)/, '})');\n\n // 4. Return type after `)`: `): Promise<X> =>` or `): Type {`\n line = line.replace(/\\)\\s*:\\s*\\w[\\w<>, .]*\\s*(=>|\\{)/, ') $1');\n\n // 5. `satisfies TypeName` at end of expression\n line = line.replace(/\\s+satisfies\\s+\\w[\\w<>, .]*\\s*;/, ';');\n\n // 6. `as TypeName` type casts (excluding `as const`)\n line = line.replace(/\\s+as\\s+(?!const\\b)\\w[\\w<>, .]*/, '');\n\n // 7. Generic type parameter in arrow function: `<T>(` at start of arrow fn\n // e.g. `const t = <T>(content: IConfigLocales<T>) =>`\n line = line.replace(/(<\\w+>)\\(/, '(');\n\n // 8. Generic calls: `fn<Type>(` → `fn(`\n // Only strip when angle brackets look like type params, not JSX\n line = line.replace(/(\\w+)<[A-Z]\\w*(?:,\\s*[A-Z]\\w*)*>\\(/g, '$1(');\n\n // 9. Remove typed function parameters: `(param: Type)`, `param: Type,`\n // Simple single-param-with-type: `: TypeName)` → `)`\n // Avoid breaking object spread or return annotation already handled\n line = line.replace(/(\\w)\\s*:\\s*[A-Z]\\w*(\\))/g, '$1$2');\n\n out.push(line);\n }\n\n // Insert JSDoc lines (reverse order so indices stay valid)\n const insertPositions = [...jsdocInserts.entries()].sort(\n (first, second) => second[0] - first[0]\n );\n for (const [pos, jsdoc] of insertPositions) {\n // Preserve indent of the following line\n const indent = (out[pos] ?? '').match(/^(\\s*)/)?.[1] ?? '';\n out.splice(pos, 0, indent + jsdoc);\n }\n\n return { code: out.join('\\n'), jsdocInserts };\n};\n\n// ── Export processing (CJS) ──────────────────────────────────────────────────\n\ninterface CollectedExport {\n localName: string;\n exportedName: string;\n}\n\nconst processExportsCJS = (code: string): string => {\n const lines = code.split('\\n');\n const collected: CollectedExport[] = [];\n let defaultExport: string | null = null;\n const requireLines: string[] = []; // for re-exports\n const out: string[] = [];\n\n for (let lineIndex = 0; lineIndex < lines.length; lineIndex++) {\n const line = lines[lineIndex];\n\n // `export default X;` or `export default X`\n const defMatch = line.match(/^(\\s*)export\\s+default\\s+(.+?);?\\s*$/);\n if (defMatch) {\n defaultExport = trim(defMatch[2]);\n continue; // skip line, emit module.exports later\n }\n\n // `export const/let/var name = ...`\n const exportConstMatch = line.match(\n /^(\\s*)export\\s+(const|let|var)\\s+(\\w+)/\n );\n if (exportConstMatch) {\n const name = exportConstMatch[3];\n collected.push({ localName: name, exportedName: name });\n out.push(line.replace(/^(\\s*)export\\s+/, '$1'));\n continue;\n }\n\n // `export function name(...)` or `export async function name(...)`\n const exportFnMatch = line.match(\n /^(\\s*)export\\s+(?:async\\s+)?function\\s+(\\w+)/\n );\n if (exportFnMatch) {\n const name = exportFnMatch[2];\n collected.push({ localName: name, exportedName: name });\n out.push(line.replace(/^(\\s*)export\\s+/, '$1'));\n continue;\n }\n\n // `export { A, B as C } from 'mod'` — re-export\n const reexportFromMatch = line.match(\n /^(\\s*)export\\s+\\{([^}]+)\\}\\s+from\\s+[\"']([^\"']+)[\"'];?\\s*$/\n );\n if (reexportFromMatch) {\n const members = parseNamedImports(reexportFromMatch[2]);\n const modulePath = reexportFromMatch[3];\n // Only value members (no types)\n const valueMembers = members.filter((namedMember) => !namedMember.isType);\n if (valueMembers.length) {\n // require the original names\n const origNames = valueMembers.map((namedMember) => namedMember.name);\n requireLines.push(\n `const ${renderNamedImports(origNames.map((name) => ({ name })))} = require('${modulePath}');`\n );\n for (const namedMember of valueMembers) {\n collected.push({\n localName: namedMember.name,\n exportedName: namedMember.alias ?? namedMember.name,\n });\n }\n }\n continue;\n }\n\n // `export { A, B as C }` — named re-export (same module)\n const namedExportMatch = line.match(/^(\\s*)export\\s+\\{([^}]+)\\};?\\s*$/);\n if (namedExportMatch) {\n const members = parseNamedImports(namedExportMatch[2]).filter(\n (namedMember) => !namedMember.isType\n );\n for (const namedMember of members) {\n collected.push({\n localName: namedMember.name,\n exportedName: namedMember.alias ?? namedMember.name,\n });\n }\n continue;\n }\n\n out.push(line);\n }\n\n // Prepend any require lines for re-exports\n const finalLines = requireLines.length ? [...requireLines, '', ...out] : out;\n\n // Append module.exports\n if (defaultExport !== null && collected.length === 0) {\n finalLines.push(`module.exports = ${defaultExport};`);\n } else if (defaultExport !== null && collected.length > 0) {\n const parts = collected.map((exportEntry) =>\n exportEntry.localName === exportEntry.exportedName\n ? exportEntry.localName\n : `${exportEntry.exportedName}: ${exportEntry.localName}`\n );\n finalLines.push(\n `module.exports = { default: ${defaultExport}, ${parts.join(', ')} };`\n );\n } else if (collected.length > 0) {\n const parts = collected.map((exportEntry) =>\n exportEntry.localName === exportEntry.exportedName\n ? exportEntry.localName\n : `${exportEntry.exportedName}: ${exportEntry.localName}`\n );\n finalLines.push(`module.exports = { ${parts.join(', ')} };`);\n }\n\n return finalLines.join('\\n');\n};\n\n// ── Main transform entry point ────────────────────────────────────────────────\n\nexport const transformCode = (\n code: string,\n target: TargetCodeFormat\n): string => {\n // 1. Parse all imports\n const imports = parseImports(code);\n const typeMap = buildTypeMap(imports);\n\n // 2. Replace import statements in the code\n let result = code;\n // Process in reverse order so string offsets stay valid\n const sorted = [...imports].sort(\n (firstImport, secondImport) => secondImport.start - firstImport.start\n );\n for (const parsedImport of sorted) {\n const rendered =\n target === 'esm'\n ? renderImportESM(parsedImport)\n : renderImportCJS(parsedImport);\n // rendered === null means remove the import\n const replacement = rendered ?? '';\n result =\n result.slice(0, parsedImport.start) +\n replacement +\n result.slice(parsedImport.end);\n }\n\n // 3. Collapse consecutive blank lines that may result from removed imports\n result = result.replace(/\\n{3,}/g, '\\n\\n');\n\n // 4. Strip TypeScript type annotations\n const stripped = stripTypeAnnotations(result, typeMap);\n result = stripped.code;\n\n // 5. Process exports (CJS only)\n if (target === 'commonjs') {\n result = processExportsCJS(result);\n }\n\n // 6. Final cleanup: collapse any triple+ blank lines introduced by export processing,\n // then trim leading/trailing blank lines.\n result = result.replace(/\\n{3,}/g, '\\n\\n');\n result = result.replace(/^\\n+/, '').replace(/\\n+$/, '');\n\n return result;\n};\n\n/**\n * Derive the file name for a transformed format.\n * `next.config.ts` → `next.config.mjs` (ESM) / `next.config.cjs` (CJS)\n * `layout.tsx` → `layout.jsx` (ESM or CJS — JSX always stays .jsx)\n */\nexport const deriveFileName = (\n fileName: string,\n target: TargetCodeFormat\n): string => {\n if (target === 'esm') {\n // TSX → .jsx (standard ESM JSX), TS → .mjs (standard ESM module)\n return fileName.replace(/\\.tsx$/, '.jsx').replace(/\\.ts$/, '.mjs');\n }\n // CJS: TSX → .jsx (JSX stays .jsx), TS → .cjs\n return fileName.replace(/\\.tsx$/, '.jsx').replace(/\\.ts$/, '.cjs');\n};\n\n/**\n * Derive the syntax-highlighting language for a transformed format.\n * `typescript` → `javascript`; `tsx` → `jsx`\n */\nexport const deriveLanguage = (\n language: string,\n target: TargetCodeFormat\n): string => {\n if (target === 'typescript') return language;\n return language === 'tsx'\n ? 'jsx'\n : language === 'typescript'\n ? 'javascript'\n : language;\n};\n"],"mappings":";AAaA,MAAM,QAAQ,SAAiB,KAAK,MAAM;;;;;AAM1C,MAAM,qBACJ,UAEA,MACG,MAAM,IAAI,CACV,IAAI,KAAK,CACT,OAAO,QAAQ,CACf,KAAK,WAAW;CACf,MAAM,SAAS,WAAW,KAAK,OAAO;CAEtC,MAAM,UADQ,OAAO,QAAQ,YAAY,GAAG,CAAC,MACxB,CAAC,MAAM,WAAW;AACvC,QAAO;EACL,MAAM,KAAK,QAAQ,GAAG;EACtB,OAAO,QAAQ,KAAK,KAAK,QAAQ,GAAG,GAAG;EACvC;EACD;EACD;;AAGN,MAAM,sBACJ,YACG;AACH,QAAO,KAAK,QAAQ,KAAK,WAAY,OAAO,QAAQ,GAAG,OAAO,KAAK,MAAM,OAAO,UAAU,OAAO,KAAM,CAAC,KAAK,KAAK,CAAC;;;;;;AAkBrH,MAAM,gBACJ,SACyD;CACzD,MAAM,SAA+D,EAAE;CAGvE,MAAM,uBACJ;CAEF,IAAI,cAAsC,qBAAqB,KAAK,KAA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G,YAAY,aAAa,IAAI,YAAY,YACjD;AACD,aAAW,KAAK,sBAAsB,MAAM,KAAK,KAAK,CAAC,KAAK;;AAG9D,QAAO,WAAW,KAAK,KAAK;;AAK9B,MAAa,iBACX,MACA,WACW;CAEX,MAAM,UAAU,aAAa,KAAK;CAClC,MAAM,UAAU,aAAa,QAAQ;CAGrC,IAAI,SAAS;CAEb,MAAM,SAAS,CAAC,GAAG,QAAQ,CAAC,MACzB,aAAa,iBAAiB,aAAa,QAAQ,YAAY,MACjE;AACD,MAAK,MAAM,gBAAgB,QAAQ;EAMjC,MAAM,eAJJ,WAAW,QACP,gBAAgB,aAAa,GAC7B,gBAAgB,aAAa,KAEH;AAChC,WACE,OAAO,MAAM,GAAG,aAAa,MAAM,GACnC,cACA,OAAO,MAAM,aAAa,IAAI;;AAIlC,UAAS,OAAO,QAAQ,WAAW,OAAO;AAI1C,UADiB,qBAAqB,QAAQ,QAC7B,CAAC;AAGlB,KAAI,WAAW,WACb,UAAS,kBAAkB,OAAO;AAKpC,UAAS,OAAO,QAAQ,WAAW,OAAO;AAC1C,UAAS,OAAO,QAAQ,QAAQ,GAAG,CAAC,QAAQ,QAAQ,GAAG;AAEvD,QAAO;;;;;;;AAQT,MAAa,kBACX,UACA,WACW;AACX,KAAI,WAAW,MAEb,QAAO,SAAS,QAAQ,UAAU,OAAO,CAAC,QAAQ,SAAS,OAAO;AAGpE,QAAO,SAAS,QAAQ,UAAU,OAAO,CAAC,QAAQ,SAAS,OAAO;;;;;;AAOpE,MAAa,kBACX,UACA,WACW;AACX,KAAI,WAAW,aAAc,QAAO;AACpC,QAAO,aAAa,QAChB,QACA,aAAa,eACX,eACA"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"OTPInput.mjs","names":[],"sources":["../../../../src/components/Input/OTPInput.tsx"],"sourcesContent":["'use client';\n\n/**\n * This component is a fork of https://github.com/guilhermerodz/input-otp\n */\n\nimport { cn } from '@utils/cn';\nimport { cva } from 'class-variance-authority';\nimport { MinusIcon } from 'lucide-react';\nimport {\n type ChangeEvent,\n type ClipboardEvent,\n type ComponentProps,\n type CSSProperties,\n createContext,\n type FC,\n type InputHTMLAttributes,\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type RefObject,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react';\nimport { Button, type ButtonProps } from '../Button';\n\n// ---------------- Utilities ----------------\n\nconst syncTimeouts = (cb: (...args: any[]) => unknown): number[] => {\n const t1 = setTimeout(cb, 0); // For faster machines\n const t2 = setTimeout(cb, 1_0);\n const t3 = setTimeout(cb, 5_0);\n return [t1, t2, t3];\n};\n\nconst safeInsertRule = (sheet: CSSStyleSheet, rule: string) => {\n try {\n sheet.insertRule(rule);\n } catch {\n console.error('input-otp could not insert CSS rule:', rule);\n }\n};\n\n// Decided to go with <noscript>\n// instead of `scripting` CSS media query\n// because it's a fallback for initial page load\n// and the <script> tag won't be loaded\n// unless the user has JS disabled.\nconst NOSCRIPT_CSS_FALLBACK = `\n[data-input-otp] {\n --nojs-bg: white !important;\n --nojs-fg: black !important;\n\n background-color: var(--nojs-bg) !important;\n color: var(--nojs-fg) !important;\n caret-color: var(--nojs-fg) !important;\n letter-spacing: .25em !important;\n text-align: center !important;\n border: 1px solid var(--nojs-fg) !important;\n border-radius: 4px !important;\n width: 100% !important;\n}\n@media (prefers-color-scheme: dark) {\n [data-input-otp] {\n --nojs-bg: black !important;\n --nojs-fg: white !important;\n }\n}`;\n\n// ---------------- Constants ----------------\n\nconst PWM_BADGE_MARGIN_RIGHT = 18;\nconst PWM_BADGE_SPACE_WIDTH_PX = 40;\nconst PWM_BADGE_SPACE_WIDTH = `${PWM_BADGE_SPACE_WIDTH_PX}px` as const;\n\nconst PASSWORD_MANAGERS_SELECTORS = [\n '[data-lastpass-icon-root]', // LastPass\n 'com-1password-button', // 1Password\n '[data-dashlanecreated]', // Dashlane\n '[style$=\"2147483647 !important;\"]', // Bitwarden\n].join(',');\n\n// ---------------- Types ----------------\n\nexport type SlotProps = {\n isActive: boolean;\n char: string | null;\n placeholderChar: string | null;\n hasFakeCaret: boolean;\n};\n\nexport type RenderProps = {\n slots: SlotProps[];\n isFocused: boolean;\n isHovering: boolean;\n setSelection: (index: number) => void;\n};\n\ntype OverrideProps<T, R> = Omit<T, keyof R> & R;\n\ntype OTPInputBaseProps = OverrideProps<\n InputHTMLAttributes<HTMLInputElement>,\n {\n value?: string;\n onChange?: (newValue: string) => unknown;\n\n maxLength: number;\n\n onComplete?: (...args: any[]) => unknown;\n onActiveSlotChange?: (activeSlotIndex: number | null) => unknown;\n pushPasswordManagerStrategy?: 'increase-width' | 'none';\n pasteTransformer?: (pasted: string) => string;\n\n containerClassName?: string;\n\n noScriptCSSFallback?: string | null;\n }\n>;\n\ntype InputOTPRenderFn = (props: RenderProps) => ReactNode;\n\nexport type OTPInputProps = OTPInputBaseProps &\n (\n | {\n render: InputOTPRenderFn;\n children?: never;\n }\n | {\n render?: never;\n children: ReactNode;\n }\n );\n\n// ---------------- Hooks ----------------\n\nexport const usePasswordManagerBadge = ({\n containerRef,\n inputRef,\n pushPasswordManagerStrategy,\n isFocused,\n}: {\n containerRef: RefObject<HTMLDivElement | null>;\n inputRef: RefObject<HTMLInputElement | null>;\n pushPasswordManagerStrategy: OTPInputProps['pushPasswordManagerStrategy'];\n isFocused: boolean;\n}) => {\n /** Password managers have a badge\n * and I'll use this state to push them\n * outside the input */\n const [hasPWMBadge, setHasPWMBadge] = useState(false);\n const [hasPWMBadgeSpace, setHasPWMBadgeSpace] = useState(false);\n const [done, setDone] = useState(false);\n\n const willPushPWMBadge =\n pushPasswordManagerStrategy === 'none'\n ? false\n : (pushPasswordManagerStrategy === 'increase-width' ||\n // TODO: remove 'experimental-no-flickering' support in 2.0.0\n pushPasswordManagerStrategy === 'experimental-no-flickering') &&\n hasPWMBadge &&\n hasPWMBadgeSpace;\n\n const trackPWMBadge = () => {\n const container = containerRef.current;\n const input = inputRef.current;\n if (\n !container ||\n !input ||\n done ||\n pushPasswordManagerStrategy === 'none'\n ) {\n return;\n }\n\n const elementToCompare = container;\n\n // Get the top right-center point of the container.\n // That is usually where most password managers place their badge.\n const rightCornerX =\n elementToCompare.getBoundingClientRect().left +\n elementToCompare.offsetWidth;\n const centereredY =\n elementToCompare.getBoundingClientRect().top +\n elementToCompare.offsetHeight / 2;\n const x = rightCornerX - PWM_BADGE_MARGIN_RIGHT;\n const y = centereredY;\n\n // Do an extra search to check for famous password managers\n const pmws = document.querySelectorAll(PASSWORD_MANAGERS_SELECTORS);\n\n // If no password manager is automatically detect,\n // we'll try to dispatch document.elementFromPoint\n // to identify badges\n if (pmws.length === 0) {\n const maybeBadgeEl = document.elementFromPoint(x, y);\n\n // If the found element is the input itself,\n // then we assume it's not a password manager badge.\n // We are not sure. Most times that means there isn't a badge.\n if (maybeBadgeEl === container) {\n return;\n }\n }\n\n setHasPWMBadge(true);\n setDone(true);\n };\n\n useEffect(() => {\n const container = containerRef.current;\n if (!container || pushPasswordManagerStrategy === 'none') {\n return;\n }\n\n // Check if the PWM area is 100% visible\n const checkHasSpace = () => {\n const viewportWidth = window.innerWidth;\n const distanceToRightEdge =\n viewportWidth - container.getBoundingClientRect().right;\n setHasPWMBadgeSpace(distanceToRightEdge >= PWM_BADGE_SPACE_WIDTH_PX);\n };\n\n checkHasSpace();\n const interval = setInterval(checkHasSpace, 1000);\n\n return () => {\n clearInterval(interval);\n };\n }, [containerRef, pushPasswordManagerStrategy]);\n\n useEffect(() => {\n const _isFocused = isFocused || document.activeElement === inputRef.current;\n\n if (pushPasswordManagerStrategy === 'none' || !_isFocused) {\n return;\n }\n const t1 = setTimeout(trackPWMBadge, 0);\n const t2 = setTimeout(trackPWMBadge, 2000);\n const t3 = setTimeout(trackPWMBadge, 5000);\n const t4 = setTimeout(() => {\n setDone(true);\n }, 6000);\n return () => {\n clearTimeout(t1);\n clearTimeout(t2);\n clearTimeout(t3);\n clearTimeout(t4);\n };\n }, [inputRef, isFocused, pushPasswordManagerStrategy]);\n\n return { hasPWMBadge, willPushPWMBadge, PWM_BADGE_SPACE_WIDTH };\n};\n\nexport const usePrevious = <T,>(value: T): T | undefined => {\n const ref = useRef<T | undefined>(undefined);\n useEffect(() => {\n ref.current = value;\n });\n return ref.current;\n};\n\n// ---------------- Context ----------------\n\nexport const OTPInputContext = createContext<RenderProps>({} as RenderProps);\n\n// ---------------- Core Component ----------------\n\nexport const OTPInput: FC<OTPInputProps> = ({\n value: uncheckedValue,\n onChange: uncheckedOnChange,\n maxLength,\n pattern,\n placeholder,\n inputMode = 'numeric',\n onComplete,\n onActiveSlotChange,\n pushPasswordManagerStrategy = 'increase-width',\n pasteTransformer,\n containerClassName,\n noScriptCSSFallback = NOSCRIPT_CSS_FALLBACK,\n render,\n children,\n ...props\n}) => {\n // Only used when `value` state is not provided\n const [internalValue, setInternalValue] = useState(\n typeof props.defaultValue === 'string' ? props.defaultValue : ''\n );\n\n // Definitions\n const value = uncheckedValue ?? internalValue;\n const previousValue = usePrevious(value);\n const onChange = (newValue: string) => {\n uncheckedOnChange?.(newValue);\n setInternalValue(newValue);\n };\n const regexp =\n pattern !== undefined\n ? typeof pattern === 'string'\n ? new RegExp(pattern)\n : pattern\n : null;\n\n /** useRef */\n const inputRef = useRef<HTMLInputElement>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n const initialLoadRef = useRef({\n value,\n onChange,\n isIOS:\n typeof window !== 'undefined' &&\n window?.CSS?.supports?.('-webkit-touch-callout', 'none'),\n });\n const inputMetadataRef = useRef<{\n prev: [number | null, number | null, 'none' | 'forward' | 'backward'];\n }>({\n prev: [\n inputRef.current?.selectionStart ?? null,\n inputRef.current?.selectionEnd ?? null,\n inputRef.current?.selectionDirection ?? 'none',\n ],\n });\n useEffect(() => {\n const input = inputRef.current;\n const container = containerRef.current;\n\n if (!input || !container) {\n return;\n }\n\n // Sync input value\n if (initialLoadRef.current.value !== input.value) {\n initialLoadRef.current.onChange(input.value);\n }\n\n // Previous selection\n inputMetadataRef.current.prev = [\n input.selectionStart,\n input.selectionEnd,\n input.selectionDirection ?? 'none',\n ];\n const onDocumentSelectionChange = () => {\n if (document.activeElement !== input) {\n setMirrorSelectionStart(null);\n setMirrorSelectionEnd(null);\n setActualCaretPosition(null);\n return;\n }\n\n const selectionStart = input.selectionStart;\n const selectionEnd = input.selectionEnd;\n const selectionDirection = input.selectionDirection;\n const maxLength = input.maxLength;\n const value = input.value;\n const previousSelection = inputMetadataRef.current.prev;\n\n let calculatedStart = -1;\n let calculatedEnd = -1;\n let calculatedDirection: 'forward' | 'backward' | 'none' =\n selectionDirection ?? 'none';\n\n if (\n value.length !== 0 &&\n selectionStart !== null &&\n selectionEnd !== null\n ) {\n const isSingleCaret = selectionStart === selectionEnd;\n const isInsertMode =\n selectionStart === value.length && value.length < maxLength;\n\n if (isSingleCaret && !isInsertMode) {\n const caretPosition = selectionStart;\n if (caretPosition === 0) {\n calculatedStart = 0;\n calculatedEnd = 1;\n calculatedDirection = 'forward';\n } else if (caretPosition === maxLength) {\n calculatedStart = caretPosition - 1;\n calculatedEnd = caretPosition;\n calculatedDirection = 'backward';\n } else if (maxLength > 1 && value.length > 1) {\n let offset = 0;\n if (\n previousSelection[0] !== null &&\n previousSelection[1] !== null\n ) {\n calculatedDirection =\n caretPosition < previousSelection[1] ? 'backward' : 'forward';\n const wasPreviouslyInserting =\n previousSelection[0] === previousSelection[1] &&\n previousSelection[0] < maxLength;\n if (\n calculatedDirection === 'backward' &&\n !wasPreviouslyInserting\n ) {\n offset = -1;\n }\n }\n\n calculatedStart = offset + caretPosition;\n calculatedEnd = offset + caretPosition + 1;\n }\n }\n\n if (\n calculatedStart !== -1 &&\n calculatedEnd !== -1 &&\n calculatedStart !== calculatedEnd\n ) {\n inputRef.current?.setSelectionRange(\n calculatedStart,\n calculatedEnd,\n calculatedDirection\n );\n }\n }\n\n const finalSelectionStart =\n calculatedStart !== -1 ? calculatedStart : selectionStart;\n const finalSelectionEnd =\n calculatedEnd !== -1 ? calculatedEnd : selectionEnd;\n const finalDirection = calculatedDirection;\n\n // Track actual caret position (before expansion) for active slot detection\n if (selectionStart !== null && selectionEnd !== null) {\n const isSingleCaret = selectionStart === selectionEnd;\n if (isSingleCaret) {\n setActualCaretPosition(selectionStart);\n } else {\n // When selection is expanded, use the start position as the caret\n setActualCaretPosition(finalSelectionStart);\n }\n } else {\n setActualCaretPosition(null);\n }\n\n setMirrorSelectionStart(finalSelectionStart);\n setMirrorSelectionEnd(finalSelectionEnd);\n inputMetadataRef.current.prev = [\n finalSelectionStart,\n finalSelectionEnd,\n finalDirection,\n ];\n };\n document.addEventListener('selectionchange', onDocumentSelectionChange, {\n capture: true,\n });\n\n // Set initial mirror state\n onDocumentSelectionChange();\n if (document.activeElement === input) {\n setIsFocused(true);\n }\n\n // Apply needed styles\n if (!document.getElementById('input-otp-style')) {\n const styleEl = document.createElement('style');\n styleEl.id = 'input-otp-style';\n document.head.appendChild(styleEl);\n\n if (styleEl.sheet) {\n const autofillStyles =\n 'background: transparent !important; color: transparent !important; border-color: transparent !important; opacity: 0 !important; box-shadow: none !important; -webkit-box-shadow: none !important; -webkit-text-fill-color: transparent !important;';\n\n safeInsertRule(\n styleEl.sheet,\n '[data-input-otp]::selection { background: transparent !important; color: transparent !important; }'\n );\n safeInsertRule(\n styleEl.sheet,\n `[data-input-otp]:autofill { ${autofillStyles} }`\n );\n safeInsertRule(\n styleEl.sheet,\n `[data-input-otp]:-webkit-autofill { ${autofillStyles} }`\n );\n // iOS\n safeInsertRule(\n styleEl.sheet,\n `@supports (-webkit-touch-callout: none) { [data-input-otp] { letter-spacing: -.6em !important; font-weight: 100 !important; font-stretch: ultra-condensed; font-optical-sizing: none !important; left: -1px !important; right: 1px !important; } }`\n );\n // PWM badges\n safeInsertRule(\n styleEl.sheet,\n `[data-input-otp] + * { pointer-events: all !important; }`\n );\n }\n }\n // Track root height\n const updateRootHeight = () => {\n if (container) {\n container.style.setProperty('--root-height', `${input.clientHeight}px`);\n }\n };\n updateRootHeight();\n const resizeObserver = new ResizeObserver(updateRootHeight);\n resizeObserver.observe(input);\n\n return () => {\n document.removeEventListener(\n 'selectionchange',\n onDocumentSelectionChange,\n { capture: true }\n );\n resizeObserver.disconnect();\n };\n }, []);\n\n /** Mirrors for UI rendering purpose only */\n const [isHoveringInput, setIsHoveringInput] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const [mirrorSelectionStart, setMirrorSelectionStart] = useState<\n number | null\n >(null);\n const [mirrorSelectionEnd, setMirrorSelectionEnd] = useState<number | null>(\n null\n );\n const [actualCaretPosition, setActualCaretPosition] = useState<number | null>(\n null\n );\n\n /** Effects */\n useEffect(() => {\n syncTimeouts(() => {\n // Forcefully remove :autofill state\n inputRef.current?.dispatchEvent(new Event('input'));\n\n // Update the selection state\n const s = inputRef.current?.selectionStart ?? null;\n const e = inputRef.current?.selectionEnd ?? null;\n const dir = inputRef.current?.selectionDirection ?? 'none';\n if (s !== null && e !== null) {\n setMirrorSelectionStart(s);\n setMirrorSelectionEnd(e);\n // Track actual caret position (use start position as caret)\n setActualCaretPosition(s);\n inputMetadataRef.current.prev = [s, e, dir];\n }\n });\n }, [value, isFocused]);\n\n useEffect(() => {\n if (previousValue === undefined) {\n return;\n }\n\n if (\n value !== previousValue &&\n previousValue.length < maxLength &&\n value.length === maxLength\n ) {\n onComplete?.(value);\n }\n }, [maxLength, onComplete, previousValue, value]);\n\n // Track active slot changes\n const previousActiveSlot = useRef<number | null>(null);\n useEffect(() => {\n const activeSlotIndex =\n isFocused && actualCaretPosition !== null ? actualCaretPosition : null;\n\n if (activeSlotIndex !== previousActiveSlot.current) {\n previousActiveSlot.current = activeSlotIndex;\n onActiveSlotChange?.(activeSlotIndex);\n }\n }, [isFocused, actualCaretPosition, onActiveSlotChange]);\n\n const pwmb = usePasswordManagerBadge({\n containerRef,\n inputRef,\n pushPasswordManagerStrategy,\n isFocused,\n });\n\n /** Event handlers */\n const _changeListener = (e: ChangeEvent<HTMLInputElement>) => {\n const newValue = e.currentTarget.value.slice(0, maxLength);\n if (newValue.length > 0 && regexp && !regexp.test(newValue)) {\n e.preventDefault();\n return;\n }\n const maybeHasDeleted =\n typeof previousValue === 'string' &&\n newValue.length < previousValue.length;\n if (maybeHasDeleted) {\n // Since cutting/deleting text doesn't trigger\n // selectionchange event, we'll have to dispatch it manually.\n // NOTE: The following line also triggers when cmd+A then pasting\n // a value with smaller length, which is not ideal for performance.\n document.dispatchEvent(new Event('selectionchange'));\n }\n onChange(newValue);\n };\n const _focusListener = () => {\n if (inputRef.current) {\n const start = Math.min(inputRef.current.value.length, maxLength - 1);\n const end = inputRef.current.value.length;\n inputRef.current?.setSelectionRange(start, end);\n setMirrorSelectionStart(start);\n setMirrorSelectionEnd(end);\n }\n setIsFocused(true);\n };\n // Fix iOS pasting\n const _pasteListener = (e: ClipboardEvent<HTMLInputElement>) => {\n const input = inputRef.current;\n if (\n !pasteTransformer &&\n (!initialLoadRef.current.isIOS || !e.clipboardData || !input)\n ) {\n return;\n }\n\n const _content = e.clipboardData.getData('text/plain');\n const content = pasteTransformer ? pasteTransformer(_content) : _content;\n e.preventDefault();\n\n const start = inputRef.current?.selectionStart;\n const end = inputRef.current?.selectionEnd;\n\n const isReplacing = start !== end;\n\n const newValueUncapped = isReplacing\n ? value.slice(0, start ?? 0) + content + value.slice(end ?? 0) // Replacing\n : value.slice(0, start ?? 0) + content + value.slice(start ?? 0); // Inserting\n const newValue = newValueUncapped.slice(0, maxLength);\n\n if (newValue.length > 0 && regexp && !regexp.test(newValue)) {\n return;\n }\n\n if (input) {\n input.value = newValue;\n onChange(newValue);\n\n const _start = Math.min(newValue.length, maxLength - 1);\n const _end = newValue.length;\n\n input.setSelectionRange(_start, _end);\n setMirrorSelectionStart(_start);\n setMirrorSelectionEnd(_end);\n }\n };\n\n /** Styles - dynamic styles that can't be converted to Tailwind */\n const dynamicInputStyle: CSSProperties = {\n width: pwmb.willPushPWMBadge\n ? `calc(100% + ${pwmb.PWM_BADGE_SPACE_WIDTH})`\n : '100%',\n clipPath: pwmb.willPushPWMBadge\n ? `inset(0 ${pwmb.PWM_BADGE_SPACE_WIDTH} 0 0)`\n : undefined,\n fontSize: 'var(--root-height)',\n };\n\n /** Rendering */\n const renderedInput = (\n <input\n autoComplete={props.autoComplete || 'one-time-code'}\n {...props}\n data-input-otp\n data-input-otp-placeholder-shown={value.length === 0 || undefined}\n data-input-otp-mss={mirrorSelectionStart}\n data-input-otp-mse={mirrorSelectionEnd}\n inputMode={inputMode}\n pattern={regexp?.source}\n aria-placeholder={placeholder}\n className=\"pointer-events-auto absolute inset-0 -z-10 flex h-full border-0 border-transparent bg-transparent text-center font-mono text-transparent tabular-nums leading-none tracking-[-.5em] caret-transparent opacity-100 shadow-none outline-none\"\n style={dynamicInputStyle}\n maxLength={maxLength}\n value={value}\n ref={inputRef}\n onPaste={(e) => {\n _pasteListener(e);\n props.onPaste?.(e);\n }}\n onChange={_changeListener}\n onMouseOver={(e) => {\n setIsHoveringInput(true);\n props.onMouseOver?.(e);\n }}\n onMouseLeave={(e) => {\n setIsHoveringInput(false);\n props.onMouseLeave?.(e);\n }}\n onKeyDown={(e) => {\n // Track arrow key navigation to ensure active slot updates correctly\n if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {\n // Use requestAnimationFrame to check selection after browser has processed the key\n requestAnimationFrame(() => {\n const input = inputRef.current;\n if (input && document.activeElement === input) {\n const s = input.selectionStart;\n const end = input.selectionEnd;\n if (s !== null && end !== null) {\n // Update actual caret position - use start position as caret\n setActualCaretPosition(s);\n }\n }\n });\n }\n props.onKeyDown?.(e);\n }}\n onFocus={(e) => {\n _focusListener();\n props.onFocus?.(e);\n }}\n onBlur={(e) => {\n setIsFocused(false);\n props.onBlur?.(e);\n }}\n />\n );\n\n const setSelection = (index: number) => {\n const input = inputRef.current;\n if (!input || props.disabled) {\n return;\n }\n\n // Clamp index to valid range\n const clampedIndex = Math.max(0, Math.min(index, maxLength - 1));\n\n // Focus the input if not already focused\n if (document.activeElement !== input) {\n input.focus();\n }\n\n // Set selection to the clicked slot\n // If there's a character at that position, select it; otherwise just position the caret\n const hasChar = value[clampedIndex] !== undefined;\n const start = clampedIndex;\n const end = hasChar ? clampedIndex + 1 : clampedIndex;\n\n input.setSelectionRange(start, end);\n setMirrorSelectionStart(start);\n setMirrorSelectionEnd(end);\n setIsFocused(true);\n };\n\n const contextValue: RenderProps = {\n slots: Array.from({ length: maxLength }).map((_, slotIdx) => {\n const isActive =\n isFocused &&\n mirrorSelectionStart !== null &&\n mirrorSelectionEnd !== null &&\n ((mirrorSelectionStart === mirrorSelectionEnd &&\n slotIdx === mirrorSelectionStart) ||\n (slotIdx >= mirrorSelectionStart && slotIdx < mirrorSelectionEnd));\n\n const char = value[slotIdx] !== undefined ? value[slotIdx] : null;\n const placeholderChar =\n value[0] !== undefined ? null : (placeholder?.[slotIdx] ?? null);\n\n return {\n char,\n placeholderChar,\n isActive,\n hasFakeCaret: isActive && char === null,\n };\n }),\n isFocused,\n isHovering: !props.disabled && isHoveringInput,\n setSelection,\n };\n\n const renderedChildren =\n render !== undefined ? (\n render(contextValue)\n ) : (\n <OTPInputContext.Provider value={contextValue}>\n {children}\n </OTPInputContext.Provider>\n );\n\n return (\n <>\n {noScriptCSSFallback !== null && (\n <noscript>\n <style>{noScriptCSSFallback}</style>\n </noscript>\n )}\n\n <div\n ref={containerRef}\n className={cn(\n 'relative',\n props.disabled ? 'cursor-default' : 'cursor-text',\n containerClassName\n )}\n >\n {renderedChildren}\n\n <div className=\"absolute inset-0\">{renderedInput}</div>\n </div>\n </>\n );\n};\n\n// ---------------- Root ----------------\n\ntype InputOTPProps = Omit<ComponentProps<typeof OTPInput>, 'children'>;\n\nexport const inputSlotVariants = cva('block text-center', {\n variants: {\n size: {\n sm: 'h-4 w-3 text-sm',\n md: 'h-5 w-4 text-base',\n lg: 'h-6 w-5 text-lg',\n xl: 'h-7 w-6 text-xl',\n },\n },\n defaultVariants: {\n size: 'md',\n },\n});\n\nexport const InputOTP: FC<InputOTPProps> = ({\n className,\n render,\n ...props\n}) => (\n <OTPInput\n containerClassName=\"relative flex items-center gap-2 has-disabled:opacity-50\"\n className={cn('disabled:cursor-not-allowed', className)}\n render={render!}\n {...props}\n />\n);\n\n// ---------------- Group ----------------\n\nexport const InputOTPGroup = ({\n className,\n ...props\n}: ComponentProps<'div'>) => (\n <div className={cn('z-10 flex items-center gap-3', className)} {...props} />\n);\n\n// ---------------- Slot ----------------\n\ntype InputOTPSlotProps = Omit<ButtonProps, 'variant' | 'label'> & {\n index: number;\n};\n\nexport const InputOTPSlot: FC<InputOTPSlotProps> = ({\n index,\n className,\n onClick,\n onKeyDown,\n ...props\n}) => {\n const inputOTPContext = useContext(OTPInputContext);\n const { char, isActive } = inputOTPContext?.slots[index] ?? {};\n const { setSelection } = inputOTPContext ?? {};\n\n const handleClick = (e: MouseEvent<HTMLButtonElement>) => {\n setSelection?.(index);\n onClick?.(e);\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLButtonElement>) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n setSelection?.(index);\n }\n onKeyDown?.(e);\n };\n\n return (\n <Button\n isSelected={isActive}\n variant=\"input\"\n color=\"custom\"\n tabIndex={-1}\n className={cn('relative z-10 px-2!', isActive && 'ring-4!', className)}\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n label={null}\n {...props}\n >\n {/* value */}\n <span className=\"relative z-10 flex h-6 w-4 items-center justify-center\">\n {char}\n </span>\n </Button>\n );\n};\n\n// ---------------- Separator ----------------\n\nexport const InputOTPSeparator: FC<ComponentProps<'div'>> = (props) => (\n <div\n aria-hidden\n className=\"z-0 table h-0.5 w-3 rounded-full bg-border text-text/50\"\n {...props}\n >\n <MinusIcon />\n </div>\n);\n\nexport const InputIndicator: FC<ComponentProps<'div'>> = (props) => (\n <div\n data-indicator\n className=\"absolute top-0 z-0 h-full w-auto rounded-xl bg-text/20 ring-4 ring-text/20 transition-[left,width] duration-300 ease-in-out [corner-shape:squircle] supports-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,IAAI;EACL,EACF;CACD,iBAAiB,EACf,MAAM,MACP;CACF,CAAC;AAEF,MAAa,YAA+B,EAC1C,WACA,QACA,GAAG,YAEH,oBAAC,UAAD;CACE,oBAAmB;CACnB,WAAW,GAAG,+BAA+B,UAAU;CAC/C;CACR,GAAI;CACJ;AAKJ,MAAa,iBAAiB,EAC5B,WACA,GAAG,YAEH,oBAAC,OAAD;CAAK,WAAW,GAAG,gCAAgC,UAAU;CAAE,GAAI;CAAS;AAS9E,MAAa,gBAAuC,EAClD,OACA,WACA,SACA,WACA,GAAG,YACC;CACJ,MAAM,kBAAkB,WAAW,gBAAgB;CACnD,MAAM,EAAE,MAAM,aAAa,iBAAiB,MAAM,UAAU,EAAE;CAC9D,MAAM,EAAE,iBAAiB,mBAAmB,EAAE;CAE9C,MAAM,eAAe,MAAqC;AACxD,iBAAe,MAAM;AACrB,YAAU,EAAE;;CAGd,MAAM,iBAAiB,MAAwC;AAC7D,MAAI,EAAE,QAAQ,WAAW,EAAE,QAAQ,KAAK;AACtC,KAAE,gBAAgB;AAClB,kBAAe,MAAM;;AAEvB,cAAY,EAAE;;AAGhB,QACE,oBAAC,QAAD;EACE,YAAY;EACZ,SAAQ;EACR,OAAM;EACN,UAAU;EACV,WAAW,GAAG,uBAAuB,YAAY,WAAW,UAAU;EACtE,SAAS;EACT,WAAW;EACX,OAAO;EACP,GAAI;YAGJ,oBAAC,QAAD;GAAM,WAAU;aACb;GACI;EACA;;AAMb,MAAa,qBAAgD,UAC3D,oBAAC,OAAD;CACE;CACA,WAAU;CACV,GAAI;WAEJ,oBAAC,WAAD,EAAa;CACT;AAGR,MAAa,kBAA6C,UACxD,oBAAC,OAAD;CACE;CACA,WAAU;CACV,GAAI;CACJ"}
|
|
1
|
+
{"version":3,"file":"OTPInput.mjs","names":[],"sources":["../../../../src/components/Input/OTPInput.tsx"],"sourcesContent":["'use client';\n\n/**\n * This component is a fork of https://github.com/guilhermerodz/input-otp\n */\n\nimport { cn } from '@utils/cn';\nimport { cva } from 'class-variance-authority';\nimport { MinusIcon } from 'lucide-react';\nimport {\n type ChangeEvent,\n type ClipboardEvent,\n type ComponentProps,\n type CSSProperties,\n createContext,\n type FC,\n type InputHTMLAttributes,\n type KeyboardEvent,\n type MouseEvent,\n type ReactNode,\n type RefObject,\n useContext,\n useEffect,\n useRef,\n useState,\n} from 'react';\nimport { Button, type ButtonProps } from '../Button';\n\n// ---------------- Utilities ----------------\n\nconst syncTimeouts = (cb: (...args: any[]) => unknown): number[] => {\n const t1 = setTimeout(cb, 0); // For faster machines\n const t2 = setTimeout(cb, 1_0);\n const t3 = setTimeout(cb, 5_0);\n return [t1, t2, t3];\n};\n\nconst safeInsertRule = (sheet: CSSStyleSheet, rule: string) => {\n try {\n sheet.insertRule(rule);\n } catch {\n console.error('input-otp could not insert CSS rule:', rule);\n }\n};\n\n// Decided to go with <noscript>\n// instead of `scripting` CSS media query\n// because it's a fallback for initial page load\n// and the <script> tag won't be loaded\n// unless the user has JS disabled.\nconst NOSCRIPT_CSS_FALLBACK = `\n[data-input-otp] {\n --nojs-bg: white !important;\n --nojs-fg: black !important;\n\n background-color: var(--nojs-bg) !important;\n color: var(--nojs-fg) !important;\n caret-color: var(--nojs-fg) !important;\n letter-spacing: .25em !important;\n text-align: center !important;\n border: 1px solid var(--nojs-fg) !important;\n border-radius: 4px !important;\n width: 100% !important;\n}\n@media (prefers-color-scheme: dark) {\n [data-input-otp] {\n --nojs-bg: black !important;\n --nojs-fg: white !important;\n }\n}`;\n\n// ---------------- Constants ----------------\n\nconst PWM_BADGE_MARGIN_RIGHT = 18;\nconst PWM_BADGE_SPACE_WIDTH_PX = 40;\nconst PWM_BADGE_SPACE_WIDTH = `${PWM_BADGE_SPACE_WIDTH_PX}px` as const;\n\nconst PASSWORD_MANAGERS_SELECTORS = [\n '[data-lastpass-icon-root]', // LastPass\n 'com-1password-button', // 1Password\n '[data-dashlanecreated]', // Dashlane\n '[style$=\"2147483647 !important;\"]', // Bitwarden\n].join(',');\n\n// ---------------- Types ----------------\n\nexport type SlotProps = {\n isActive: boolean;\n char: string | null;\n placeholderChar: string | null;\n hasFakeCaret: boolean;\n};\n\nexport type RenderProps = {\n slots: SlotProps[];\n isFocused: boolean;\n isHovering: boolean;\n setSelection: (index: number) => void;\n};\n\ntype OverrideProps<T, R> = Omit<T, keyof R> & R;\n\ntype OTPInputBaseProps = OverrideProps<\n InputHTMLAttributes<HTMLInputElement>,\n {\n value?: string;\n onChange?: (newValue: string) => unknown;\n\n maxLength: number;\n\n onComplete?: (...args: any[]) => unknown;\n onActiveSlotChange?: (activeSlotIndex: number | null) => unknown;\n pushPasswordManagerStrategy?: 'increase-width' | 'none';\n pasteTransformer?: (pasted: string) => string;\n\n containerClassName?: string;\n\n noScriptCSSFallback?: string | null;\n }\n>;\n\ntype InputOTPRenderFn = (props: RenderProps) => ReactNode;\n\nexport type OTPInputProps = OTPInputBaseProps &\n (\n | {\n render: InputOTPRenderFn;\n children?: never;\n }\n | {\n render?: never;\n children: ReactNode;\n }\n );\n\n// ---------------- Hooks ----------------\n\nexport const usePasswordManagerBadge = ({\n containerRef,\n inputRef,\n pushPasswordManagerStrategy,\n isFocused,\n}: {\n containerRef: RefObject<HTMLDivElement | null>;\n inputRef: RefObject<HTMLInputElement | null>;\n pushPasswordManagerStrategy: OTPInputProps['pushPasswordManagerStrategy'];\n isFocused: boolean;\n}) => {\n /** Password managers have a badge\n * and I'll use this state to push them\n * outside the input */\n const [hasPWMBadge, setHasPWMBadge] = useState(false);\n const [hasPWMBadgeSpace, setHasPWMBadgeSpace] = useState(false);\n const [done, setDone] = useState(false);\n\n const willPushPWMBadge =\n pushPasswordManagerStrategy === 'none'\n ? false\n : (pushPasswordManagerStrategy === 'increase-width' ||\n // TODO: remove 'experimental-no-flickering' support in 2.0.0\n pushPasswordManagerStrategy === 'experimental-no-flickering') &&\n hasPWMBadge &&\n hasPWMBadgeSpace;\n\n const trackPWMBadge = () => {\n const container = containerRef.current;\n const input = inputRef.current;\n if (\n !container ||\n !input ||\n done ||\n pushPasswordManagerStrategy === 'none'\n ) {\n return;\n }\n\n const elementToCompare = container;\n\n // Get the top right-center point of the container.\n // That is usually where most password managers place their badge.\n const rightCornerX =\n elementToCompare.getBoundingClientRect().left +\n elementToCompare.offsetWidth;\n const centereredY =\n elementToCompare.getBoundingClientRect().top +\n elementToCompare.offsetHeight / 2;\n const x = rightCornerX - PWM_BADGE_MARGIN_RIGHT;\n const y = centereredY;\n\n // Do an extra search to check for famous password managers\n const pmws = document.querySelectorAll(PASSWORD_MANAGERS_SELECTORS);\n\n // If no password manager is automatically detect,\n // we'll try to dispatch document.elementFromPoint\n // to identify badges\n if (pmws.length === 0) {\n const maybeBadgeEl = document.elementFromPoint(x, y);\n\n // If the found element is the input itself,\n // then we assume it's not a password manager badge.\n // We are not sure. Most times that means there isn't a badge.\n if (maybeBadgeEl === container) {\n return;\n }\n }\n\n setHasPWMBadge(true);\n setDone(true);\n };\n\n useEffect(() => {\n const container = containerRef.current;\n if (!container || pushPasswordManagerStrategy === 'none') {\n return;\n }\n\n // Check if the PWM area is 100% visible\n const checkHasSpace = () => {\n const viewportWidth = window.innerWidth;\n const distanceToRightEdge =\n viewportWidth - container.getBoundingClientRect().right;\n setHasPWMBadgeSpace(distanceToRightEdge >= PWM_BADGE_SPACE_WIDTH_PX);\n };\n\n checkHasSpace();\n const interval = setInterval(checkHasSpace, 1000);\n\n return () => {\n clearInterval(interval);\n };\n }, [containerRef, pushPasswordManagerStrategy]);\n\n useEffect(() => {\n const _isFocused = isFocused || document.activeElement === inputRef.current;\n\n if (pushPasswordManagerStrategy === 'none' || !_isFocused) {\n return;\n }\n const t1 = setTimeout(trackPWMBadge, 0);\n const t2 = setTimeout(trackPWMBadge, 2000);\n const t3 = setTimeout(trackPWMBadge, 5000);\n const t4 = setTimeout(() => {\n setDone(true);\n }, 6000);\n return () => {\n clearTimeout(t1);\n clearTimeout(t2);\n clearTimeout(t3);\n clearTimeout(t4);\n };\n }, [inputRef, isFocused, pushPasswordManagerStrategy]);\n\n return { hasPWMBadge, willPushPWMBadge, PWM_BADGE_SPACE_WIDTH };\n};\n\nexport const usePrevious = <T,>(value: T): T | undefined => {\n const ref = useRef<T | undefined>(undefined);\n useEffect(() => {\n ref.current = value;\n });\n return ref.current;\n};\n\n// ---------------- Context ----------------\n\nexport const OTPInputContext = createContext<RenderProps>({} as RenderProps);\n\n// ---------------- Core Component ----------------\n\nexport const OTPInput: FC<OTPInputProps> = ({\n value: uncheckedValue,\n onChange: uncheckedOnChange,\n maxLength,\n pattern,\n placeholder,\n inputMode = 'numeric',\n onComplete,\n onActiveSlotChange,\n pushPasswordManagerStrategy = 'increase-width',\n pasteTransformer,\n containerClassName,\n noScriptCSSFallback = NOSCRIPT_CSS_FALLBACK,\n render,\n children,\n ...props\n}) => {\n // Only used when `value` state is not provided\n const [internalValue, setInternalValue] = useState(\n typeof props.defaultValue === 'string' ? props.defaultValue : ''\n );\n\n // Definitions\n const value = uncheckedValue ?? internalValue;\n const previousValue = usePrevious(value);\n const onChange = (newValue: string) => {\n uncheckedOnChange?.(newValue);\n setInternalValue(newValue);\n };\n const regexp =\n pattern !== undefined\n ? typeof pattern === 'string'\n ? new RegExp(pattern)\n : pattern\n : null;\n\n /** useRef */\n const inputRef = useRef<HTMLInputElement>(null);\n const containerRef = useRef<HTMLDivElement>(null);\n const initialLoadRef = useRef({\n value,\n onChange,\n isIOS:\n typeof window !== 'undefined' &&\n window?.CSS?.supports?.('-webkit-touch-callout', 'none'),\n });\n const inputMetadataRef = useRef<{\n prev: [number | null, number | null, 'none' | 'forward' | 'backward'];\n }>({\n prev: [\n inputRef.current?.selectionStart ?? null,\n inputRef.current?.selectionEnd ?? null,\n inputRef.current?.selectionDirection ?? 'none',\n ],\n });\n useEffect(() => {\n const input = inputRef.current;\n const container = containerRef.current;\n\n if (!input || !container) {\n return;\n }\n\n // Sync input value\n if (initialLoadRef.current.value !== input.value) {\n initialLoadRef.current.onChange(input.value);\n }\n\n // Previous selection\n inputMetadataRef.current.prev = [\n input.selectionStart,\n input.selectionEnd,\n input.selectionDirection ?? 'none',\n ];\n const onDocumentSelectionChange = () => {\n if (document.activeElement !== input) {\n setMirrorSelectionStart(null);\n setMirrorSelectionEnd(null);\n setActualCaretPosition(null);\n return;\n }\n\n const selectionStart = input.selectionStart;\n const selectionEnd = input.selectionEnd;\n const selectionDirection = input.selectionDirection;\n const maxLength = input.maxLength;\n const value = input.value;\n const previousSelection = inputMetadataRef.current.prev;\n\n let calculatedStart = -1;\n let calculatedEnd = -1;\n let calculatedDirection: 'forward' | 'backward' | 'none' =\n selectionDirection ?? 'none';\n\n if (\n value.length !== 0 &&\n selectionStart !== null &&\n selectionEnd !== null\n ) {\n const isSingleCaret = selectionStart === selectionEnd;\n const isInsertMode =\n selectionStart === value.length && value.length < maxLength;\n\n if (isSingleCaret && !isInsertMode) {\n const caretPosition = selectionStart;\n if (caretPosition === 0) {\n calculatedStart = 0;\n calculatedEnd = 1;\n calculatedDirection = 'forward';\n } else if (caretPosition === maxLength) {\n calculatedStart = caretPosition - 1;\n calculatedEnd = caretPosition;\n calculatedDirection = 'backward';\n } else if (maxLength > 1 && value.length > 1) {\n let offset = 0;\n if (\n previousSelection[0] !== null &&\n previousSelection[1] !== null\n ) {\n calculatedDirection =\n caretPosition < previousSelection[1] ? 'backward' : 'forward';\n const wasPreviouslyInserting =\n previousSelection[0] === previousSelection[1] &&\n previousSelection[0] < maxLength;\n if (\n calculatedDirection === 'backward' &&\n !wasPreviouslyInserting\n ) {\n offset = -1;\n }\n }\n\n calculatedStart = offset + caretPosition;\n calculatedEnd = offset + caretPosition + 1;\n }\n }\n\n if (\n calculatedStart !== -1 &&\n calculatedEnd !== -1 &&\n calculatedStart !== calculatedEnd\n ) {\n inputRef.current?.setSelectionRange(\n calculatedStart,\n calculatedEnd,\n calculatedDirection\n );\n }\n }\n\n const finalSelectionStart =\n calculatedStart !== -1 ? calculatedStart : selectionStart;\n const finalSelectionEnd =\n calculatedEnd !== -1 ? calculatedEnd : selectionEnd;\n const finalDirection = calculatedDirection;\n\n // Track actual caret position (before expansion) for active slot detection\n if (selectionStart !== null && selectionEnd !== null) {\n const isSingleCaret = selectionStart === selectionEnd;\n if (isSingleCaret) {\n setActualCaretPosition(selectionStart);\n } else {\n // When selection is expanded, use the start position as the caret\n setActualCaretPosition(finalSelectionStart);\n }\n } else {\n setActualCaretPosition(null);\n }\n\n setMirrorSelectionStart(finalSelectionStart);\n setMirrorSelectionEnd(finalSelectionEnd);\n inputMetadataRef.current.prev = [\n finalSelectionStart,\n finalSelectionEnd,\n finalDirection,\n ];\n };\n document.addEventListener('selectionchange', onDocumentSelectionChange, {\n capture: true,\n });\n\n // Set initial mirror state\n onDocumentSelectionChange();\n if (document.activeElement === input) {\n setIsFocused(true);\n }\n\n // Apply needed styles\n if (!document.getElementById('input-otp-style')) {\n const styleEl = document.createElement('style');\n styleEl.id = 'input-otp-style';\n document.head.appendChild(styleEl);\n\n if (styleEl.sheet) {\n const autofillStyles =\n 'background: transparent !important; color: transparent !important; border-color: transparent !important; opacity: 0 !important; box-shadow: none !important; -webkit-box-shadow: none !important; -webkit-text-fill-color: transparent !important;';\n\n safeInsertRule(\n styleEl.sheet,\n '[data-input-otp]::selection { background: transparent !important; color: transparent !important; }'\n );\n safeInsertRule(\n styleEl.sheet,\n `[data-input-otp]:autofill { ${autofillStyles} }`\n );\n safeInsertRule(\n styleEl.sheet,\n `[data-input-otp]:-webkit-autofill { ${autofillStyles} }`\n );\n // iOS\n safeInsertRule(\n styleEl.sheet,\n `@supports (-webkit-touch-callout: none) { [data-input-otp] { letter-spacing: -.6em !important; font-weight: 100 !important; font-stretch: ultra-condensed; font-optical-sizing: none !important; left: -1px !important; right: 1px !important; } }`\n );\n // PWM badges\n safeInsertRule(\n styleEl.sheet,\n `[data-input-otp] + * { pointer-events: all !important; }`\n );\n }\n }\n // Track root height\n const updateRootHeight = () => {\n if (container) {\n container.style.setProperty('--root-height', `${input.clientHeight}px`);\n }\n };\n updateRootHeight();\n const resizeObserver = new ResizeObserver(updateRootHeight);\n resizeObserver.observe(input);\n\n return () => {\n document.removeEventListener(\n 'selectionchange',\n onDocumentSelectionChange,\n { capture: true }\n );\n resizeObserver.disconnect();\n };\n }, []);\n\n /** Mirrors for UI rendering purpose only */\n const [isHoveringInput, setIsHoveringInput] = useState(false);\n const [isFocused, setIsFocused] = useState(false);\n const [mirrorSelectionStart, setMirrorSelectionStart] = useState<\n number | null\n >(null);\n const [mirrorSelectionEnd, setMirrorSelectionEnd] = useState<number | null>(\n null\n );\n const [actualCaretPosition, setActualCaretPosition] = useState<number | null>(\n null\n );\n\n /** Effects */\n useEffect(() => {\n syncTimeouts(() => {\n // Forcefully remove :autofill state\n inputRef.current?.dispatchEvent(new Event('input'));\n\n // Update the selection state\n const s = inputRef.current?.selectionStart ?? null;\n const e = inputRef.current?.selectionEnd ?? null;\n const dir = inputRef.current?.selectionDirection ?? 'none';\n if (s !== null && e !== null) {\n setMirrorSelectionStart(s);\n setMirrorSelectionEnd(e);\n // Track actual caret position (use start position as caret)\n setActualCaretPosition(s);\n inputMetadataRef.current.prev = [s, e, dir];\n }\n });\n }, [value, isFocused]);\n\n useEffect(() => {\n if (previousValue === undefined) {\n return;\n }\n\n if (\n value !== previousValue &&\n previousValue.length < maxLength &&\n value.length === maxLength\n ) {\n onComplete?.(value);\n }\n }, [maxLength, onComplete, previousValue, value]);\n\n // Track active slot changes\n const previousActiveSlot = useRef<number | null>(null);\n useEffect(() => {\n const activeSlotIndex =\n isFocused && actualCaretPosition !== null ? actualCaretPosition : null;\n\n if (activeSlotIndex !== previousActiveSlot.current) {\n previousActiveSlot.current = activeSlotIndex;\n onActiveSlotChange?.(activeSlotIndex);\n }\n }, [isFocused, actualCaretPosition, onActiveSlotChange]);\n\n const pwmb = usePasswordManagerBadge({\n containerRef,\n inputRef,\n pushPasswordManagerStrategy,\n isFocused,\n });\n\n /** Event handlers */\n const _changeListener = (e: ChangeEvent<HTMLInputElement>) => {\n const newValue = e.currentTarget.value.slice(0, maxLength);\n if (newValue.length > 0 && regexp && !regexp.test(newValue)) {\n e.preventDefault();\n return;\n }\n const maybeHasDeleted =\n typeof previousValue === 'string' &&\n newValue.length < previousValue.length;\n if (maybeHasDeleted) {\n // Since cutting/deleting text doesn't trigger\n // selectionchange event, we'll have to dispatch it manually.\n // NOTE: The following line also triggers when cmd+A then pasting\n // a value with smaller length, which is not ideal for performance.\n document.dispatchEvent(new Event('selectionchange'));\n }\n onChange(newValue);\n };\n const _focusListener = () => {\n if (inputRef.current) {\n const start = Math.min(inputRef.current.value.length, maxLength - 1);\n const end = inputRef.current.value.length;\n inputRef.current?.setSelectionRange(start, end);\n setMirrorSelectionStart(start);\n setMirrorSelectionEnd(end);\n }\n setIsFocused(true);\n };\n // Fix iOS pasting\n const _pasteListener = (e: ClipboardEvent<HTMLInputElement>) => {\n const input = inputRef.current;\n if (\n !pasteTransformer &&\n (!initialLoadRef.current.isIOS || !e.clipboardData || !input)\n ) {\n return;\n }\n\n const _content = e.clipboardData.getData('text/plain');\n const content = pasteTransformer ? pasteTransformer(_content) : _content;\n e.preventDefault();\n\n const start = inputRef.current?.selectionStart;\n const end = inputRef.current?.selectionEnd;\n\n const isReplacing = start !== end;\n\n const newValueUncapped = isReplacing\n ? value.slice(0, start ?? 0) + content + value.slice(end ?? 0) // Replacing\n : value.slice(0, start ?? 0) + content + value.slice(start ?? 0); // Inserting\n const newValue = newValueUncapped.slice(0, maxLength);\n\n if (newValue.length > 0 && regexp && !regexp.test(newValue)) {\n return;\n }\n\n if (input) {\n input.value = newValue;\n onChange(newValue);\n\n const _start = Math.min(newValue.length, maxLength - 1);\n const _end = newValue.length;\n\n input.setSelectionRange(_start, _end);\n setMirrorSelectionStart(_start);\n setMirrorSelectionEnd(_end);\n }\n };\n\n /** Styles - dynamic styles that can't be converted to Tailwind */\n const dynamicInputStyle: CSSProperties = {\n width: pwmb.willPushPWMBadge\n ? `calc(100% + ${pwmb.PWM_BADGE_SPACE_WIDTH})`\n : '100%',\n clipPath: pwmb.willPushPWMBadge\n ? `inset(0 ${pwmb.PWM_BADGE_SPACE_WIDTH} 0 0)`\n : undefined,\n fontSize: 'var(--root-height)',\n };\n\n /** Rendering */\n const renderedInput = (\n <input\n autoComplete={props.autoComplete || 'one-time-code'}\n {...props}\n data-input-otp\n data-input-otp-placeholder-shown={value.length === 0 || undefined}\n data-input-otp-mss={mirrorSelectionStart}\n data-input-otp-mse={mirrorSelectionEnd}\n inputMode={inputMode}\n pattern={regexp?.source}\n aria-placeholder={placeholder}\n className=\"pointer-events-auto absolute inset-0 -z-10 flex h-full border-0 border-transparent bg-transparent text-center font-mono text-transparent tabular-nums leading-none tracking-[-.5em] caret-transparent opacity-100 shadow-none outline-none\"\n style={dynamicInputStyle}\n maxLength={maxLength}\n value={value}\n ref={inputRef}\n onPaste={(e) => {\n _pasteListener(e);\n props.onPaste?.(e);\n }}\n onChange={_changeListener}\n onMouseOver={(e) => {\n setIsHoveringInput(true);\n props.onMouseOver?.(e);\n }}\n onMouseLeave={(e) => {\n setIsHoveringInput(false);\n props.onMouseLeave?.(e);\n }}\n onKeyDown={(e) => {\n // Track arrow key navigation to ensure active slot updates correctly\n if (e.key === 'ArrowLeft' || e.key === 'ArrowRight') {\n // Use requestAnimationFrame to check selection after browser has processed the key\n requestAnimationFrame(() => {\n const input = inputRef.current;\n if (input && document.activeElement === input) {\n const s = input.selectionStart;\n const end = input.selectionEnd;\n if (s !== null && end !== null) {\n // Update actual caret position - use start position as caret\n setActualCaretPosition(s);\n }\n }\n });\n }\n props.onKeyDown?.(e);\n }}\n onFocus={(e) => {\n _focusListener();\n props.onFocus?.(e);\n }}\n onBlur={(e) => {\n setIsFocused(false);\n props.onBlur?.(e);\n }}\n />\n );\n\n const setSelection = (index: number) => {\n const input = inputRef.current;\n if (!input || props.disabled) {\n return;\n }\n\n // Clamp index to valid range\n const clampedIndex = Math.max(0, Math.min(index, maxLength - 1));\n\n // Focus the input if not already focused\n if (document.activeElement !== input) {\n input.focus();\n }\n\n // Set selection to the clicked slot\n // If there's a character at that position, select it; otherwise just position the caret\n const hasChar = value[clampedIndex] !== undefined;\n const start = clampedIndex;\n const end = hasChar ? clampedIndex + 1 : clampedIndex;\n\n input.setSelectionRange(start, end);\n setMirrorSelectionStart(start);\n setMirrorSelectionEnd(end);\n setIsFocused(true);\n };\n\n const contextValue: RenderProps = {\n slots: Array.from({ length: maxLength }).map((_, slotIdx) => {\n const isActive =\n isFocused &&\n mirrorSelectionStart !== null &&\n mirrorSelectionEnd !== null &&\n ((mirrorSelectionStart === mirrorSelectionEnd &&\n slotIdx === mirrorSelectionStart) ||\n (slotIdx >= mirrorSelectionStart && slotIdx < mirrorSelectionEnd));\n\n const char = value[slotIdx] !== undefined ? value[slotIdx] : null;\n const placeholderChar =\n value[0] !== undefined ? null : (placeholder?.[slotIdx] ?? null);\n\n return {\n char,\n placeholderChar,\n isActive,\n hasFakeCaret: isActive && char === null,\n };\n }),\n isFocused,\n isHovering: !props.disabled && isHoveringInput,\n setSelection,\n };\n\n const renderedChildren =\n render !== undefined ? (\n render(contextValue)\n ) : (\n <OTPInputContext.Provider value={contextValue}>\n {children}\n </OTPInputContext.Provider>\n );\n\n return (\n <>\n {noScriptCSSFallback !== null && (\n <noscript>\n <style>{noScriptCSSFallback}</style>\n </noscript>\n )}\n\n <div\n ref={containerRef}\n className={cn(\n 'relative',\n props.disabled ? 'cursor-default' : 'cursor-text',\n containerClassName\n )}\n >\n {renderedChildren}\n\n <div className=\"absolute inset-0\">{renderedInput}</div>\n </div>\n </>\n );\n};\n\n// ---------------- Root ----------------\n\ntype InputOTPProps = Omit<ComponentProps<typeof OTPInput>, 'children'>;\n\nexport const inputSlotVariants = cva('block text-center', {\n variants: {\n size: {\n sm: 'h-4 w-3 text-sm',\n md: 'h-5 w-4 text-base',\n lg: 'h-6 w-5 text-lg',\n xl: 'h-7 w-6 text-xl',\n },\n },\n defaultVariants: {\n size: 'md',\n },\n});\n\nexport const InputOTP: FC<InputOTPProps> = ({\n className,\n render,\n ...props\n}) => (\n <OTPInput\n containerClassName=\"relative flex items-center gap-2 has-disabled:opacity-50\"\n className={cn('disabled:cursor-not-allowed', className)}\n render={render!}\n {...props}\n />\n);\n\n// ---------------- Group ----------------\n\nexport const InputOTPGroup = ({\n className,\n ...props\n}: ComponentProps<'div'>) => (\n <div className={cn('z-10 flex items-center gap-3', className)} {...props} />\n);\n\n// ---------------- Slot ----------------\n\ntype InputOTPSlotProps = Omit<ButtonProps, 'variant' | 'label'> & {\n index: number;\n};\n\nexport const InputOTPSlot: FC<InputOTPSlotProps> = ({\n index,\n className,\n onClick,\n onKeyDown,\n ...props\n}) => {\n const inputOTPContext = useContext(OTPInputContext);\n const { char, isActive } = inputOTPContext?.slots[index] ?? {};\n const { setSelection } = inputOTPContext ?? {};\n\n const handleClick = (e: MouseEvent<HTMLButtonElement>) => {\n setSelection?.(index);\n onClick?.(e);\n };\n\n const handleKeyDown = (e: KeyboardEvent<HTMLButtonElement>) => {\n if (e.key === 'Enter' || e.key === ' ') {\n e.preventDefault();\n setSelection?.(index);\n }\n onKeyDown?.(e);\n };\n\n return (\n <Button\n isSelected={isActive}\n variant=\"input\"\n color=\"custom\"\n tabIndex={-1}\n className={cn('relative z-10 px-2!', isActive && 'ring-4!', className)}\n onClick={handleClick}\n onKeyDown={handleKeyDown}\n label={null}\n {...props}\n >\n {/* value */}\n <span className=\"relative z-10 flex h-6 w-4 items-center justify-center\">\n {char}\n </span>\n </Button>\n );\n};\n\n// ---------------- Separator ----------------\n\nexport const InputOTPSeparator: FC<ComponentProps<'div'>> = (props) => (\n <div\n aria-hidden\n className=\"z-0 table h-0.5 w-3 rounded-full bg-border text-text/50\"\n {...props}\n >\n <MinusIcon />\n </div>\n);\n\nexport const InputIndicator: FC<ComponentProps<'div'>> = (props) => (\n <div\n data-indicator\n className=\"absolute top-0 z-0 h-full w-auto rounded-xl bg-text/20 ring-4 ring-text/20 transition-[left,width] duration-300 ease-in-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;EACJ,IAAI;EACJ,IAAI;EACL,EACF;CACD,iBAAiB,EACf,MAAM,MACP;CACF,CAAC;AAEF,MAAa,YAA+B,EAC1C,WACA,QACA,GAAG,YAEH,oBAAC,UAAD;CACE,oBAAmB;CACnB,WAAW,GAAG,+BAA+B,UAAU;CAC/C;CACR,GAAI;CACJ;AAKJ,MAAa,iBAAiB,EAC5B,WACA,GAAG,YAEH,oBAAC,OAAD;CAAK,WAAW,GAAG,gCAAgC,UAAU;CAAE,GAAI;CAAS;AAS9E,MAAa,gBAAuC,EAClD,OACA,WACA,SACA,WACA,GAAG,YACC;CACJ,MAAM,kBAAkB,WAAW,gBAAgB;CACnD,MAAM,EAAE,MAAM,aAAa,iBAAiB,MAAM,UAAU,EAAE;CAC9D,MAAM,EAAE,iBAAiB,mBAAmB,EAAE;CAE9C,MAAM,eAAe,MAAqC;AACxD,iBAAe,MAAM;AACrB,YAAU,EAAE;;CAGd,MAAM,iBAAiB,MAAwC;AAC7D,MAAI,EAAE,QAAQ,WAAW,EAAE,QAAQ,KAAK;AACtC,KAAE,gBAAgB;AAClB,kBAAe,MAAM;;AAEvB,cAAY,EAAE;;AAGhB,QACE,oBAAC,QAAD;EACE,YAAY;EACZ,SAAQ;EACR,OAAM;EACN,UAAU;EACV,WAAW,GAAG,uBAAuB,YAAY,WAAW,UAAU;EACtE,SAAS;EACT,WAAW;EACX,OAAO;EACP,GAAI;YAGJ,oBAAC,QAAD;GAAM,WAAU;aACb;GACI;EACA;;AAMb,MAAa,qBAAgD,UAC3D,oBAAC,OAAD;CACE;CACA,WAAU;CACV,GAAI;WAEJ,oBAAC,WAAD,EAAa;CACT;AAGR,MAAa,kBAA6C,UACxD,oBAAC,OAAD;CACE;CACA,WAAU;CACV,GAAI;CACJ"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"KeyboardShortcut.mjs","names":[],"sources":["../../../../src/components/KeyboardShortcut/KeyboardShortcut.tsx"],"sourcesContent":["'use client';\n\nimport { useDevice } from '@hooks/useDevice';\nimport { cn } from '@utils/cn';\nimport { type FC, useEffect, useState } from 'react';\n\n/**\n * Enum for available keyboard keys\n */\nexport enum KeyList {\n '⌘' = '⌘',\n Ctrl = 'Ctrl',\n Alt = 'Alt',\n '⌥' = '⌥',\n Shift = 'Shift',\n Meta = 'Meta',\n F = 'F',\n K = 'K',\n L = 'L',\n P = 'P',\n S = 'S',\n A = 'A',\n B = 'B',\n C = 'C',\n D = 'D',\n E = 'E',\n G = 'G',\n H = 'H',\n I = 'I',\n J = 'J',\n M = 'M',\n N = 'N',\n O = 'O',\n Q = 'Q',\n R = 'R',\n T = 'T',\n U = 'U',\n V = 'V',\n W = 'W',\n X = 'X',\n Y = 'Y',\n Z = 'Z',\n Enter = 'Enter',\n Escape = 'Escape',\n Backspace = 'Backspace',\n Tab = 'Tab',\n Space = 'Space',\n ArrowUp = 'ArrowUp',\n ArrowDown = 'ArrowDown',\n ArrowLeft = 'ArrowLeft',\n ArrowRight = 'ArrowRight',\n '↑' = '↑',\n '↓' = '↓',\n '←' = '←',\n '→' = '→',\n}\n\n/**\n * Type-safe keyboard shortcut combinations\n * Note: Using string type to avoid union type complexity issues\n * Expected format: \"Key + Key\" (e.g., \"⌘ + F\", \"Ctrl + Shift + K\")\n */\nexport type KeyboardShortcutType = string;\n\nexport type KeyboardShortcutProps = {\n /** The keyboard shortcut combination (e.g., \"⌘ + F\" or \"Ctrl + K\") */\n shortcut: KeyboardShortcutType;\n /** Callback function triggered when the shortcut is pressed */\n onTriggered?: () => void;\n /** Whether to display the shortcut visually (default: true) */\n display?: boolean;\n /** Whether to disable the shortcut trigger (default: false) */\n disabled?: boolean;\n /** Additional CSS classes */\n className?: string;\n /** Size of the keyboard shortcut display */\n size?: 'sm' | 'md' | 'lg';\n};\n\n/**\n * Parse keyboard shortcut string into individual keys\n */\nconst parseShortcut = (shortcut: string): string[] => {\n return shortcut.split(' + ').map((key) => key.trim());\n};\n\n/**\n * Normalize key name for event comparison\n */\nconst normalizeKey = (key: string): string => {\n const keyMap: Record<string, string> = {\n '⌘': 'Meta',\n Ctrl: 'Control',\n Control: 'Control',\n Alt: 'Alt',\n '⌥': 'Alt',\n Shift: 'Shift',\n Meta: 'Meta',\n '↑': 'ArrowUp',\n '↓': 'ArrowDown',\n '←': 'ArrowLeft',\n '→': 'ArrowRight',\n ArrowUp: 'ArrowUp',\n ArrowDown: 'ArrowDown',\n ArrowLeft: 'ArrowLeft',\n ArrowRight: 'ArrowRight',\n };\n\n return keyMap[key] || key;\n};\n\n/**\n * Check if the keyboard event matches the shortcut\n */\nconst matchesShortcut = (event: KeyboardEvent, keys: string[]): boolean => {\n const normalizedKeys = keys.map(normalizeKey);\n const hasModifiers = {\n Meta: normalizedKeys.includes('Meta'),\n Control: normalizedKeys.includes('Control'),\n Alt: normalizedKeys.includes('Alt'),\n Shift: normalizedKeys.includes('Shift'),\n };\n\n // Check if all required modifiers are pressed\n if (\n hasModifiers.Meta !== event.metaKey ||\n hasModifiers.Control !== event.ctrlKey ||\n hasModifiers.Alt !== event.altKey ||\n hasModifiers.Shift !== event.shiftKey\n ) {\n return false;\n }\n\n // Find the non-modifier key\n const nonModifierKey = keys.find(\n (key) =>\n !['⌘', 'Ctrl', 'Control', 'Alt', '⌥', 'Shift', 'Meta'].includes(\n normalizeKey(key)\n )\n );\n\n if (!nonModifierKey) return false;\n\n // Normalize the key for comparison\n const normalizedNonModifierKey = normalizeKey(nonModifierKey);\n\n // Compare the main key\n // For arrow keys, compare directly with event.key\n if (normalizedNonModifierKey.startsWith('Arrow')) {\n return event.key === normalizedNonModifierKey;\n }\n\n // For other keys, compare case-insensitive\n return event.key.toLowerCase() === normalizedNonModifierKey.toLowerCase();\n};\n\n/**\n * Get display key symbol for better visual representation\n */\nconst getDisplayKey = (key: string): string => {\n const displayMap: Record<string, string> = {\n ArrowUp: '↑',\n ArrowDown: '↓',\n ArrowLeft: '←',\n ArrowRight: '→',\n };\n\n return displayMap[key] || key;\n};\n\n/**\n * Get display shortcut based on OS (Mac uses ⌘ and ⌥, others use Ctrl and Alt)\n */\nconst getDisplayShortcut = (shortcut: string, isMac: boolean): string => {\n let result = shortcut;\n\n if (isMac) {\n result = result.replace(/Ctrl/g, '⌘');\n result = result.replace(/Alt/g, '⌥');\n } else {\n result = result.replace(/⌘/g, 'Ctrl');\n result = result.replace(/⌥/g, 'Alt');\n }\n\n // Replace arrow key names with symbols\n result = result.replace(/ArrowUp/g, '↑');\n result = result.replace(/ArrowDown/g, '↓');\n result = result.replace(/ArrowLeft/g, '←');\n result = result.replace(/ArrowRight/g, '→');\n\n return result;\n};\n\n/**\n * KeyboardShortcut Component\n *\n * A reusable component that displays keyboard shortcuts and listens for key combinations.\n * Automatically adapts to Mac (⌘, ⌥) and Windows/Linux (Ctrl, Alt) conventions.\n *\n * @example\n * ```tsx\n * <KeyboardShortcut\n * shortcut=\"⌘ + F\"\n * onTriggered={() => setShowSearch(true)}\n * />\n * ```\n */\nexport const KeyboardShortcut: FC<KeyboardShortcutProps> = ({\n shortcut,\n onTriggered,\n display = true,\n disabled = false,\n className,\n size = 'md',\n}) => {\n const { isMac } = useDevice();\n const displayShortcut = getDisplayShortcut(shortcut, isMac ?? false);\n const keys = parseShortcut(displayShortcut);\n const [pressedKeys, setPressedKeys] = useState<Set<string>>(new Set());\n\n useEffect(() => {\n const handleKeyDown = (event: KeyboardEvent) => {\n // 1. Identify input fields\n const target = event.target as HTMLElement;\n const isInputField =\n target.tagName === 'INPUT' ||\n target.tagName === 'TEXTAREA' ||\n target.isContentEditable;\n\n // ... (Your existing key visualization logic here) ...\n // Note: Copied your key tracking logic for context\n const currentKey = event.key;\n const normalizedEventKeys = new Set<string>();\n if (event.metaKey) normalizedEventKeys.add('⌘');\n if (event.ctrlKey) normalizedEventKeys.add('Ctrl');\n if (event.altKey) normalizedEventKeys.add(isMac ? '⌥' : 'Alt');\n if (event.shiftKey) normalizedEventKeys.add('Shift');\n\n if (currentKey.startsWith('Arrow')) {\n normalizedEventKeys.add(currentKey);\n normalizedEventKeys.add(getDisplayKey(currentKey));\n } else {\n normalizedEventKeys.add(currentKey.toUpperCase());\n }\n setPressedKeys(normalizedEventKeys);\n\n // 2. Trigger callback if shortcut matches\n if (!disabled && onTriggered && matchesShortcut(event, keys)) {\n // FIX: Check if the required shortcut is \"Escape\"\n const isEscapeShortcut = keys.includes('Escape');\n\n // Only block if it is an input field AND the shortcut is NOT Escape\n if (isInputField && !isEscapeShortcut) {\n return;\n }\n\n event.preventDefault();\n onTriggered();\n }\n };\n\n const handleKeyUp = () => {\n setPressedKeys(new Set());\n };\n\n window.addEventListener('keydown', handleKeyDown);\n window.addEventListener('keyup', handleKeyUp);\n window.addEventListener('blur', handleKeyUp);\n\n return () => {\n window.removeEventListener('keydown', handleKeyDown);\n window.removeEventListener('keyup', handleKeyUp);\n window.removeEventListener('blur', handleKeyUp);\n };\n }, [keys, onTriggered, isMac, disabled]);\n if (!display) return null;\n\n /**\n * Check if a key is currently pressed\n */\n const isKeyPressed = (key: string): boolean => {\n const upperKey = key.toUpperCase();\n const normalizedKey = normalizeKey(key);\n\n return (\n pressedKeys.has(key) ||\n pressedKeys.has(upperKey) ||\n pressedKeys.has(normalizedKey) ||\n // Check for modifier key matches\n (key === '⌘' && pressedKeys.has('Meta')) ||\n (key === 'Ctrl' && pressedKeys.has('Control')) ||\n (key === '⌥' && pressedKeys.has('Alt')) ||\n (key === 'Alt' && pressedKeys.has('Alt')) ||\n // Check for arrow key symbols\n (key === '←' && pressedKeys.has('ArrowLeft')) ||\n (key === '→' && pressedKeys.has('ArrowRight')) ||\n (key === '↑' && pressedKeys.has('ArrowUp')) ||\n (key === '↓' && pressedKeys.has('ArrowDown'))\n );\n };\n\n return (\n <kbd\n className={cn(\n 'inline-flex items-center justify-center gap-0.5 p-0.5',\n 'rounded-lg [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-xl',\n 'font-medium font-sans',\n 'border-1 border-neutral/20 text-neutral',\n size === 'sm' && 'text-xs',\n size === 'md' && 'text-sm',\n size === 'lg' && 'text-base',\n className\n )}\n >\n {keys.map((key, index) => {\n const keyId = `${key}-${index}-${shortcut}`;\n const displayKey = getDisplayKey(key);\n return (\n <span key={keyId} className=\"inline-flex items-center\">\n {index > 0 && <span className=\"text-neutral/50\">+</span>}\n <span\n className={cn(\n 'min-w-4 px-0.5 text-center',\n isKeyPressed(key) && 'scale-120 font-bold text-text'\n )}\n suppressHydrationWarning\n >\n {displayKey}\n </span>\n </span>\n );\n })}\n </kbd>\n );\n};\n"],"mappings":";;;;;;;;;;;AASA,IAAY,UAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;KACD;;;;AA2BD,MAAM,iBAAiB,aAA+B;AACpD,QAAO,SAAS,MAAM,MAAM,CAAC,KAAK,QAAQ,IAAI,MAAM,CAAC;;;;;AAMvD,MAAM,gBAAgB,QAAwB;AAmB5C,QAlBuC;EACrC,KAAK;EACL,MAAM;EACN,SAAS;EACT,KAAK;EACL,KAAK;EACL,OAAO;EACP,MAAM;EACN,KAAK;EACL,KAAK;EACL,KAAK;EACL,KAAK;EACL,SAAS;EACT,WAAW;EACX,WAAW;EACX,YAAY;EACb,CAEa,QAAQ;;;;;AAMxB,MAAM,mBAAmB,OAAsB,SAA4B;CACzE,MAAM,iBAAiB,KAAK,IAAI,aAAa;CAC7C,MAAM,eAAe;EACnB,MAAM,eAAe,SAAS,OAAO;EACrC,SAAS,eAAe,SAAS,UAAU;EAC3C,KAAK,eAAe,SAAS,MAAM;EACnC,OAAO,eAAe,SAAS,QAAQ;EACxC;AAGD,KACE,aAAa,SAAS,MAAM,WAC5B,aAAa,YAAY,MAAM,WAC/B,aAAa,QAAQ,MAAM,UAC3B,aAAa,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IAEvC,QAAQ,OAAO,YAAY,IAAI,YAAY,IAC3C,QAAQ,OAAO,YAAY,IAAI,aAAa,IAC5C,QAAQ,OAAO,YAAY,IAAI,UAAU,IACzC,QAAQ,OAAO,YAAY,IAAI,YAAY;;AAIhD,QACE,oBAAC,OAAD;EACE,WAAW,GACT,yDACA,kFACA,yBACA,2CACA,SAAS,QAAQ,WACjB,SAAS,QAAQ,WACjB,SAAS,QAAQ,aACjB,UACD;YAEA,KAAK,KAAK,KAAK,UAAU;GACxB,MAAM,QAAQ,GAAG,IAAI,GAAG,MAAM,GAAG;GACjC,MAAM,aAAa,cAAc,IAAI;AACrC,UACE,qBAAC,QAAD;IAAkB,WAAU;cAA5B,CACG,QAAQ,KAAK,oBAAC,QAAD;KAAM,WAAU;eAAkB;KAAQ,GACxD,oBAAC,QAAD;KACE,WAAW,GACT,8BACA,aAAa,IAAI,IAAI,gCACtB;KACD;eAEC;KACI,EACF;MAXI,MAWJ;IAET;EACE"}
|
|
1
|
+
{"version":3,"file":"KeyboardShortcut.mjs","names":[],"sources":["../../../../src/components/KeyboardShortcut/KeyboardShortcut.tsx"],"sourcesContent":["'use client';\n\nimport { useDevice } from '@hooks/useDevice';\nimport { cn } from '@utils/cn';\nimport { type FC, useEffect, useState } from 'react';\n\n/**\n * Enum for available keyboard keys\n */\nexport enum KeyList {\n '⌘' = '⌘',\n Ctrl = 'Ctrl',\n Alt = 'Alt',\n '⌥' = '⌥',\n Shift = 'Shift',\n Meta = 'Meta',\n F = 'F',\n K = 'K',\n L = 'L',\n P = 'P',\n S = 'S',\n A = 'A',\n B = 'B',\n C = 'C',\n D = 'D',\n E = 'E',\n G = 'G',\n H = 'H',\n I = 'I',\n J = 'J',\n M = 'M',\n N = 'N',\n O = 'O',\n Q = 'Q',\n R = 'R',\n T = 'T',\n U = 'U',\n V = 'V',\n W = 'W',\n X = 'X',\n Y = 'Y',\n Z = 'Z',\n Enter = 'Enter',\n Escape = 'Escape',\n Backspace = 'Backspace',\n Tab = 'Tab',\n Space = 'Space',\n ArrowUp = 'ArrowUp',\n ArrowDown = 'ArrowDown',\n ArrowLeft = 'ArrowLeft',\n ArrowRight = 'ArrowRight',\n '↑' = '↑',\n '↓' = '↓',\n '←' = '←',\n '→' = '→',\n}\n\n/**\n * Type-safe keyboard shortcut combinations\n * Note: Using string type to avoid union type complexity issues\n * Expected format: \"Key + Key\" (e.g., \"⌘ + F\", \"Ctrl + Shift + K\")\n */\nexport type KeyboardShortcutType = string;\n\nexport type KeyboardShortcutProps = {\n /** The keyboard shortcut combination (e.g., \"⌘ + F\" or \"Ctrl + K\") */\n shortcut: KeyboardShortcutType;\n /** Callback function triggered when the shortcut is pressed */\n onTriggered?: () => void;\n /** Whether to display the shortcut visually (default: true) */\n display?: boolean;\n /** Whether to disable the shortcut trigger (default: false) */\n disabled?: boolean;\n /** Additional CSS classes */\n className?: string;\n /** Size of the keyboard shortcut display */\n size?: 'sm' | 'md' | 'lg';\n};\n\n/**\n * Parse keyboard shortcut string into individual keys\n */\nconst parseShortcut = (shortcut: string): string[] => {\n return shortcut.split(' + ').map((key) => key.trim());\n};\n\n/**\n * Normalize key name for event comparison\n */\nconst normalizeKey = (key: string): string => {\n const keyMap: Record<string, string> = {\n '⌘': 'Meta',\n Ctrl: 'Control',\n Control: 'Control',\n Alt: 'Alt',\n '⌥': 'Alt',\n Shift: 'Shift',\n Meta: 'Meta',\n '↑': 'ArrowUp',\n '↓': 'ArrowDown',\n '←': 'ArrowLeft',\n '→': 'ArrowRight',\n ArrowUp: 'ArrowUp',\n ArrowDown: 'ArrowDown',\n ArrowLeft: 'ArrowLeft',\n ArrowRight: 'ArrowRight',\n };\n\n return keyMap[key] || key;\n};\n\n/**\n * Check if the keyboard event matches the shortcut\n */\nconst matchesShortcut = (event: KeyboardEvent, keys: string[]): boolean => {\n const normalizedKeys = keys.map(normalizeKey);\n const hasModifiers = {\n Meta: normalizedKeys.includes('Meta'),\n Control: normalizedKeys.includes('Control'),\n Alt: normalizedKeys.includes('Alt'),\n Shift: normalizedKeys.includes('Shift'),\n };\n\n // Check if all required modifiers are pressed\n if (\n hasModifiers.Meta !== event.metaKey ||\n hasModifiers.Control !== event.ctrlKey ||\n hasModifiers.Alt !== event.altKey ||\n hasModifiers.Shift !== event.shiftKey\n ) {\n return false;\n }\n\n // Find the non-modifier key\n const nonModifierKey = keys.find(\n (key) =>\n !['⌘', 'Ctrl', 'Control', 'Alt', '⌥', 'Shift', 'Meta'].includes(\n normalizeKey(key)\n )\n );\n\n if (!nonModifierKey) return false;\n\n // Normalize the key for comparison\n const normalizedNonModifierKey = normalizeKey(nonModifierKey);\n\n // Compare the main key\n // For arrow keys, compare directly with event.key\n if (normalizedNonModifierKey.startsWith('Arrow')) {\n return event.key === normalizedNonModifierKey;\n }\n\n // For other keys, compare case-insensitive\n return event.key.toLowerCase() === normalizedNonModifierKey.toLowerCase();\n};\n\n/**\n * Get display key symbol for better visual representation\n */\nconst getDisplayKey = (key: string): string => {\n const displayMap: Record<string, string> = {\n ArrowUp: '↑',\n ArrowDown: '↓',\n ArrowLeft: '←',\n ArrowRight: '→',\n };\n\n return displayMap[key] || key;\n};\n\n/**\n * Get display shortcut based on OS (Mac uses ⌘ and ⌥, others use Ctrl and Alt)\n */\nconst getDisplayShortcut = (shortcut: string, isMac: boolean): string => {\n let result = shortcut;\n\n if (isMac) {\n result = result.replace(/Ctrl/g, '⌘');\n result = result.replace(/Alt/g, '⌥');\n } else {\n result = result.replace(/⌘/g, 'Ctrl');\n result = result.replace(/⌥/g, 'Alt');\n }\n\n // Replace arrow key names with symbols\n result = result.replace(/ArrowUp/g, '↑');\n result = result.replace(/ArrowDown/g, '↓');\n result = result.replace(/ArrowLeft/g, '←');\n result = result.replace(/ArrowRight/g, '→');\n\n return result;\n};\n\n/**\n * KeyboardShortcut Component\n *\n * A reusable component that displays keyboard shortcuts and listens for key combinations.\n * Automatically adapts to Mac (⌘, ⌥) and Windows/Linux (Ctrl, Alt) conventions.\n *\n * @example\n * ```tsx\n * <KeyboardShortcut\n * shortcut=\"⌘ + F\"\n * onTriggered={() => setShowSearch(true)}\n * />\n * ```\n */\nexport const KeyboardShortcut: FC<KeyboardShortcutProps> = ({\n shortcut,\n onTriggered,\n display = true,\n disabled = false,\n className,\n size = 'md',\n}) => {\n const { isMac } = useDevice();\n const displayShortcut = getDisplayShortcut(shortcut, isMac ?? false);\n const keys = parseShortcut(displayShortcut);\n const [pressedKeys, setPressedKeys] = useState<Set<string>>(new Set());\n\n useEffect(() => {\n const handleKeyDown = (event: KeyboardEvent) => {\n // 1. Identify input fields\n const target = event.target as HTMLElement;\n const isInputField =\n target.tagName === 'INPUT' ||\n target.tagName === 'TEXTAREA' ||\n target.isContentEditable;\n\n // ... (Your existing key visualization logic here) ...\n // Note: Copied your key tracking logic for context\n const currentKey = event.key;\n const normalizedEventKeys = new Set<string>();\n if (event.metaKey) normalizedEventKeys.add('⌘');\n if (event.ctrlKey) normalizedEventKeys.add('Ctrl');\n if (event.altKey) normalizedEventKeys.add(isMac ? '⌥' : 'Alt');\n if (event.shiftKey) normalizedEventKeys.add('Shift');\n\n if (currentKey.startsWith('Arrow')) {\n normalizedEventKeys.add(currentKey);\n normalizedEventKeys.add(getDisplayKey(currentKey));\n } else {\n normalizedEventKeys.add(currentKey.toUpperCase());\n }\n setPressedKeys(normalizedEventKeys);\n\n // 2. Trigger callback if shortcut matches\n if (!disabled && onTriggered && matchesShortcut(event, keys)) {\n // FIX: Check if the required shortcut is \"Escape\"\n const isEscapeShortcut = keys.includes('Escape');\n\n // Only block if it is an input field AND the shortcut is NOT Escape\n if (isInputField && !isEscapeShortcut) {\n return;\n }\n\n event.preventDefault();\n onTriggered();\n }\n };\n\n const handleKeyUp = () => {\n setPressedKeys(new Set());\n };\n\n window.addEventListener('keydown', handleKeyDown);\n window.addEventListener('keyup', handleKeyUp);\n window.addEventListener('blur', handleKeyUp);\n\n return () => {\n window.removeEventListener('keydown', handleKeyDown);\n window.removeEventListener('keyup', handleKeyUp);\n window.removeEventListener('blur', handleKeyUp);\n };\n }, [keys, onTriggered, isMac, disabled]);\n if (!display) return null;\n\n /**\n * Check if a key is currently pressed\n */\n const isKeyPressed = (key: string): boolean => {\n const upperKey = key.toUpperCase();\n const normalizedKey = normalizeKey(key);\n\n return (\n pressedKeys.has(key) ||\n pressedKeys.has(upperKey) ||\n pressedKeys.has(normalizedKey) ||\n // Check for modifier key matches\n (key === '⌘' && pressedKeys.has('Meta')) ||\n (key === 'Ctrl' && pressedKeys.has('Control')) ||\n (key === '⌥' && pressedKeys.has('Alt')) ||\n (key === 'Alt' && pressedKeys.has('Alt')) ||\n // Check for arrow key symbols\n (key === '←' && pressedKeys.has('ArrowLeft')) ||\n (key === '→' && pressedKeys.has('ArrowRight')) ||\n (key === '↑' && pressedKeys.has('ArrowUp')) ||\n (key === '↓' && pressedKeys.has('ArrowDown'))\n );\n };\n\n return (\n <kbd\n className={cn(\n 'inline-flex items-center justify-center gap-0.5 p-0.5',\n 'rounded-lg [corner-shape:squircle] supports-[corner-shape:squircle]:rounded-xl',\n 'font-medium font-sans',\n 'border-1 border-neutral/20 text-neutral',\n size === 'sm' && 'text-xs',\n size === 'md' && 'text-sm',\n size === 'lg' && 'text-base',\n className\n )}\n >\n {keys.map((key, index) => {\n const keyId = `${key}-${index}-${shortcut}`;\n const displayKey = getDisplayKey(key);\n return (\n <span key={keyId} className=\"inline-flex items-center\">\n {index > 0 && <span className=\"text-neutral/50\">+</span>}\n <span\n className={cn(\n 'min-w-4 px-0.5 text-center',\n isKeyPressed(key) && 'scale-120 font-bold text-text'\n )}\n suppressHydrationWarning\n >\n {displayKey}\n </span>\n </span>\n );\n })}\n </kbd>\n );\n};\n"],"mappings":";;;;;;;;;;;AASA,IAAY,UAAL;AACL;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA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;KACE,WAAW,GACT,8BACA,aAAa,IAAI,IAAI,gCACtB;KACD;eAEC;KACI,EACF;MAXI,MAWJ;IAET;EACE"}
|
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
'use client';
|
|
2
2
|
|
|
3
|
+
import { usePersistedStore } from "../../hooks/usePersistedStore.mjs";
|
|
3
4
|
import { Container } from "../Container/index.mjs";
|
|
4
5
|
import { Button, ButtonColor, ButtonSize, ButtonTextAlign, ButtonVariant } from "../Button/Button.mjs";
|
|
5
6
|
import { Input } from "../Input/Input.mjs";
|
|
6
7
|
import { SwitchSelector, SwitchSelectorColor, SwitchSelectorSize } from "../SwitchSelector/index.mjs";
|
|
7
|
-
import { usePersistedStore } from "../../hooks/usePersistedStore.mjs";
|
|
8
8
|
import { DropDown } from "../DropDown/index.mjs";
|
|
9
9
|
import { useLocaleSwitcherContent } from "./LocaleSwitcherContentContext.mjs";
|
|
10
10
|
import { useMemo, useRef, useState } from "react";
|