forked from ZhuLinsen/daily_stock_analysis
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStockAutocomplete.tsx
More file actions
316 lines (283 loc) · 8.63 KB
/
Copy pathStockAutocomplete.tsx
File metadata and controls
316 lines (283 loc) · 8.63 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
/**
* StockAutocomplete Component
*
* Stock code/name autocomplete input box
* Supports keyboard navigation, IME input method, graceful degradation
*/
import { Component, useRef, useEffect, useMemo, useState } from 'react';
import type { KeyboardEvent } from 'react';
import type { ErrorInfo, ReactNode } from 'react';
import { createPortal } from 'react-dom';
import { useStockIndex } from '../../hooks/useStockIndex';
import { useFuturesIndex } from '../../hooks/useFuturesIndex';
import { useAutocomplete } from '../../hooks/useAutocomplete';
import { SuggestionsList } from './SuggestionsList';
import { cn } from '../../utils/cn';
import type { AssetType } from '../../types/analysis';
const AUTOCOMPLETE_INPUT_CLASS =
'input-surface input-focus-glow h-11 w-full rounded-xl border bg-transparent px-4 text-sm transition-all focus:outline-none disabled:cursor-not-allowed disabled:opacity-60';
export interface StockAutocompleteProps {
/** Input value */
value: string;
/** Value change callback */
onChange: (value: string) => void;
/** Submit callback (code, name, source) */
onSubmit: (code: string, name?: string, source?: 'manual' | 'autocomplete') => void;
/** Whether disabled */
disabled?: boolean;
/** Placeholder text */
placeholder?: string;
/** Additional CSS class name */
className?: string;
/** Instrument universe to search */
assetType?: AssetType;
}
function FallbackInput({
value,
onChange,
onSubmit,
disabled = false,
placeholder = '输入股票代码或名称',
className,
}: StockAutocompleteProps) {
return (
<input
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && !disabled && value) {
onSubmit(value);
}
}}
placeholder={placeholder}
disabled={disabled}
className={cn(AUTOCOMPLETE_INPUT_CLASS, className)}
data-autocomplete-mode="fallback"
/>
);
}
interface StockAutocompleteBoundaryProps extends StockAutocompleteProps {
children: ReactNode;
}
interface StockAutocompleteBoundaryState {
hasError: boolean;
}
class StockAutocompleteBoundary extends Component<
StockAutocompleteBoundaryProps,
StockAutocompleteBoundaryState
> {
override state: StockAutocompleteBoundaryState = { hasError: false };
static getDerivedStateFromError(): StockAutocompleteBoundaryState {
return { hasError: true };
}
override componentDidCatch(error: Error, errorInfo: ErrorInfo) {
console.error('Autocomplete runtime error. Falling back to plain input.', error, errorInfo);
}
override render() {
if (this.state.hasError) {
const { children, ...fallbackProps } = this.props;
void children;
return <FallbackInput {...fallbackProps} />;
}
return this.props.children;
}
}
function StockAutocompleteInner({
value,
onChange,
onSubmit,
disabled = false,
placeholder = '输入股票代码或名称',
className,
assetType = 'stock',
}: StockAutocompleteProps) {
const stockIndexState = useStockIndex();
const futuresIndexState = useFuturesIndex(assetType === 'futures');
const activeIndexState = assetType === 'futures' ? futuresIndexState : stockIndexState;
const searchIndex = useMemo(
() => activeIndexState.index,
[activeIndexState.index],
);
const {
// query,
setQuery,
suggestions,
isOpen,
highlightedIndex,
setHighlightedIndex,
highlightPrevious,
highlightNext,
close,
// reset,
isComposing,
setIsComposing,
runtimeFallback,
error: autocompleteError,
} = useAutocomplete(searchIndex);
const inputRef = useRef<HTMLInputElement>(null);
const prevValueRef = useRef(value);
const [dropdownStyle, setDropdownStyle] = useState<{ top: number; left: number; width: string } | null>(null);
const updateDropdownPosition = () => {
if (!inputRef.current) {
setDropdownStyle(null);
return;
}
const rect = inputRef.current.getBoundingClientRect();
setDropdownStyle({
top: rect.bottom,
left: rect.left,
width: `${rect.width}px`,
});
};
const closeSuggestions = () => {
close();
setDropdownStyle(null);
};
// Sync external value with internal query (only when value truly changes)
useEffect(() => {
if (prevValueRef.current !== value) {
setQuery(value);
prevValueRef.current = value;
}
}, [value, setQuery]);
// Calculate suggestion box position (using fixed positioning)
useEffect(() => {
if (!isOpen) {
return;
}
const frameId = window.requestAnimationFrame(updateDropdownPosition);
window.addEventListener('resize', updateDropdownPosition);
window.addEventListener('scroll', updateDropdownPosition, true);
return () => {
window.cancelAnimationFrame(frameId);
window.removeEventListener('resize', updateDropdownPosition);
window.removeEventListener('scroll', updateDropdownPosition, true);
};
}, [isOpen]);
useEffect(() => {
if (!autocompleteError) {
return;
}
console.error('Autocomplete runtime fallback activated.', autocompleteError);
}, [autocompleteError]);
// Keyboard event handling
const handleKeyDown = (e: KeyboardEvent<HTMLInputElement>) => {
// Skip if composing (IME)
if (isComposing) return;
switch (e.key) {
case 'ArrowDown':
e.preventDefault();
highlightNext();
break;
case 'ArrowUp':
e.preventDefault();
highlightPrevious();
break;
case 'Enter':
e.preventDefault();
if (highlightedIndex >= 0 && suggestions[highlightedIndex]) {
// Select highlighted item
const selected = suggestions[highlightedIndex];
onChange(selected.displayCode);
closeSuggestions();
onSubmit(selected.canonicalCode, selected.nameZh, 'autocomplete');
} else {
// Submit directly
onSubmit(value);
}
break;
case 'Escape':
e.preventDefault();
closeSuggestions();
break;
}
};
// IME handling
const handleCompositionStart = () => {
setIsComposing(true);
};
const handleCompositionEnd = () => {
setIsComposing(false);
};
// Delay closing on blur (avoid immediate close when clicking suggestion items)
const handleBlur = () => {
setTimeout(() => closeSuggestions(), 200);
};
// Fallback mode: use normal input
if ((assetType === 'stock' && (activeIndexState.fallback || activeIndexState.loading)) || runtimeFallback) {
return (
<FallbackInput
value={value}
onChange={onChange}
onSubmit={onSubmit}
disabled={disabled}
placeholder={placeholder}
className={className}
/>
);
}
return (
<div className="relative stock-autocomplete">
<input
ref={inputRef}
type="text"
value={value}
onChange={(e) => onChange(e.target.value)}
onKeyDown={handleKeyDown}
onCompositionStart={handleCompositionStart}
onCompositionEnd={handleCompositionEnd}
onFocus={() => {
if (isOpen) {
updateDropdownPosition();
}
}}
onBlur={handleBlur}
placeholder={placeholder}
disabled={disabled}
className={cn(
AUTOCOMPLETE_INPUT_CLASS,
isOpen && "rounded-b-none",
className
)}
aria-autocomplete="none"
role="combobox"
aria-expanded={isOpen}
aria-haspopup="listbox"
aria-controls="suggestions-list"
/>
{/* Loading indicator */}
{activeIndexState.loading && (
<div className="absolute right-3 top-1/2 -translate-y-1/2">
<div className="w-4 h-4 border-2 border-cyan/20 border-t-cyan rounded-full animate-spin" />
</div>
)}
{/* Suggestion dropdown list */}
{isOpen && dropdownStyle && createPortal(
<SuggestionsList
suggestions={suggestions}
highlightedIndex={highlightedIndex}
onSelect={(s) => {
// Update external value (shown in input box)
onChange(s.displayCode);
// Close dropdown list
closeSuggestions();
// Submit analysis
onSubmit(s.canonicalCode, s.nameZh, 'autocomplete');
}}
onMouseEnter={(index) => setHighlightedIndex(index)}
style={{ position: 'fixed', ...dropdownStyle }}
/>,
document.body
)}
</div>
);
}
export function StockAutocomplete(props: StockAutocompleteProps) {
return (
<StockAutocompleteBoundary {...props}>
<StockAutocompleteInner {...props} />
</StockAutocompleteBoundary>
);
}
export default StockAutocomplete;