-
Notifications
You must be signed in to change notification settings - Fork 6
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Jaime Terreu
committed
Jul 17, 2021
1 parent
5dbd8cf
commit 0bb8341
Showing
1 changed file
with
50 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,53 @@ | ||
const noop = () => {}; | ||
|
||
export function dynamicSelectInput(el: HTMLElement, props: {}) { | ||
console.log("Hi from defo"); | ||
return { destroy: noop, update: () => console.log("Hi from defo") }; | ||
let activeMutationObserver: MutationObserver | undefined; | ||
|
||
const config: MutationObserverInit = { characterData: true, subtree: true }; | ||
|
||
type DynamicSelectInputProps = { | ||
sizerId: string; | ||
defaultInputWidth: number; | ||
}; | ||
const sizerCallback = ( | ||
sizer: HTMLElement, | ||
input: HTMLElement, | ||
initialWidth: number, | ||
data: DynamicSelectInputProps | ||
): MutationCallback => () => { | ||
// Need to remove the initial width of the sizer to account for empty space. | ||
const currentSizerWidth: number = | ||
sizer.getBoundingClientRect().width - initialWidth; | ||
// We also need to add the default width of the input which accounts for the cursor | ||
const calculatedInputWidth = | ||
currentSizerWidth < data.defaultInputWidth | ||
? data.defaultInputWidth | ||
: currentSizerWidth + data.defaultInputWidth; | ||
input.style.width = `${calculatedInputWidth.toString()}px`; | ||
}; | ||
|
||
const initObserver = ( | ||
sizer: HTMLElement, | ||
input: HTMLElement, | ||
nodeData: DynamicSelectInputProps | ||
): MutationObserver => { | ||
// The sizer does not start at 0px, we need to record the width and account for it in the calculation | ||
const initialSizerWidth: number = sizer.getBoundingClientRect().width; | ||
activeMutationObserver = new MutationObserver( | ||
sizerCallback(sizer, input, initialSizerWidth, nodeData) | ||
); | ||
return activeMutationObserver; | ||
}; | ||
|
||
export function dynamicSelectInput( | ||
inputElement: HTMLElement, | ||
props: DynamicSelectInputProps | ||
) { | ||
const sizerNode = document.getElementById(props.sizerId); | ||
if (sizerNode) { | ||
initObserver(sizerNode, inputElement, props).observe(sizerNode, config); | ||
} | ||
return { | ||
destroy: noop, | ||
update: () => console.log("Update from defo"), | ||
}; | ||
} |