zent
Version:
一套前端设计语言和基于React的实现
73 lines (72 loc) • 3.56 kB
JavaScript
import { __assign, __spreadArray } from "tslib";
import { useContext, useState, useRef, useCallback, useEffect } from 'react';
import { IMECompositionContext } from './context';
var defaultOption = {
getEventValue: function (e) { return e.target.value; },
};
export function createUseIMEComposition(option) {
var getEventValue = __assign(__assign({}, defaultOption), option).getEventValue;
return function useIMEComposition(propValue, onChangeProp, onCompositionStartProp, onCompositionEndProp) {
var ctx = useContext(IMECompositionContext);
var isCompositionRef = useRef(false);
var _a = useState(propValue), compositionValue = _a[0], setCompositionValue = _a[1];
var onChangeRef = useRef(onChangeProp);
var onCompositionStartRef = useRef(onCompositionStartProp);
var onCompositionEndRef = useRef(onCompositionEndProp);
useEffect(function () {
onChangeRef.current = onChangeProp;
onCompositionStartRef.current = onCompositionStartProp;
onCompositionEndRef.current = onCompositionEndProp;
}, [onChangeProp, onCompositionStartProp, onCompositionEndProp]);
useEffect(function () {
setCompositionValue(propValue);
}, [propValue]);
var onCompositionValueChange = useCallback((function () {
var _a;
var args = [];
for (var _i = 0; _i < arguments.length; _i++) {
args[_i] = arguments[_i];
}
var targetValue = getEventValue.apply(void 0, args);
if (targetValue === compositionValue) {
return;
}
if (isCompositionRef.current) {
setCompositionValue(targetValue);
return;
}
return (_a = onChangeRef.current) === null || _a === void 0 ? void 0 : _a.call.apply(_a, __spreadArray([onChangeRef], args));
}), [compositionValue, onChangeRef]);
var onCompositionStart = useCallback(function (e) {
var _a;
isCompositionRef.current = true;
(_a = onCompositionStartRef.current) === null || _a === void 0 ? void 0 : _a.call(onCompositionStartRef, e);
}, [onCompositionStartRef]);
var onCompositionEnd = useCallback(function (e) {
var _a, _b;
isCompositionRef.current = false;
(_a = onCompositionEndRef.current) === null || _a === void 0 ? void 0 : _a.call(onCompositionEndRef, e);
var currentValue = e.currentTarget.value;
setCompositionValue(currentValue);
if (currentValue !== propValue) {
e.type = 'change';
(_b = onChangeRef.current) === null || _b === void 0 ? void 0 : _b.call(onChangeRef, e);
}
}, [propValue, onCompositionEndRef, onChangeRef]);
var isControlled = propValue !== undefined;
var passCompositionHandler = isControlled && ctx.enable;
var passCompositionValue = isControlled && ctx.enable && isCompositionRef.current;
return {
value: passCompositionValue ? compositionValue : propValue,
onChange: passCompositionHandler
? onCompositionValueChange
: onChangeProp,
onCompositionStart: passCompositionHandler
? onCompositionStart
: onCompositionStartProp,
onCompositionEnd: passCompositionHandler
? onCompositionEnd
: onCompositionEndProp,
};
};
}