mirror of
https://github.com/muerwre/vault-frontend.git
synced 2025-04-25 04:46:40 +07:00
refactored hooks directory
This commit is contained in:
parent
efa3ba902d
commit
f76a5a4798
106 changed files with 122 additions and 144 deletions
49
src/hooks/dom/useFormatWrapper.ts
Normal file
49
src/hooks/dom/useFormatWrapper.ts
Normal file
|
@ -0,0 +1,49 @@
|
|||
import { useCallback } from 'react';
|
||||
|
||||
/** wraps text inside textarea with tags */
|
||||
export const useFormatWrapper = (
|
||||
target: HTMLTextAreaElement,
|
||||
onChange: (val: string) => void,
|
||||
prefix = '',
|
||||
suffix = ''
|
||||
) => {
|
||||
return useCallback(
|
||||
event => {
|
||||
event.preventDefault();
|
||||
wrapTextInsideInput(target, prefix, suffix, onChange);
|
||||
},
|
||||
[target, onChange, prefix, suffix]
|
||||
);
|
||||
};
|
||||
|
||||
/** wraps text inside textarea with tags */
|
||||
export const wrapTextInsideInput = (
|
||||
target: HTMLTextAreaElement,
|
||||
prefix: string,
|
||||
suffix: string,
|
||||
onChange: (val: string) => void
|
||||
) => {
|
||||
if (!target) return;
|
||||
|
||||
const start = target.selectionStart;
|
||||
const end = target.selectionEnd;
|
||||
const selection = target.value.substring(start, end);
|
||||
|
||||
const replacement = prefix + selection + suffix;
|
||||
|
||||
onChange(
|
||||
target.value.substring(0, start) +
|
||||
replacement +
|
||||
target.value.substring(end, target.value.length)
|
||||
);
|
||||
|
||||
target.focus();
|
||||
|
||||
setTimeout(() => {
|
||||
if (start === end) {
|
||||
target.selectionEnd = end + prefix.length;
|
||||
} else {
|
||||
target.selectionEnd = end + prefix.length + suffix.length;
|
||||
}
|
||||
}, 0);
|
||||
};
|
Loading…
Add table
Add a link
Reference in a new issue