Skip to content

Commit

Permalink
Add dynamic width javascript
Browse files Browse the repository at this point in the history
  • Loading branch information
Jaime Terreu committed Jul 17, 2021
1 parent 5dbd8cf commit 0bb8341
Showing 1 changed file with 50 additions and 3 deletions.
53 changes: 50 additions & 3 deletions src/dynamicSelectInput.ts
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"),
};
}

0 comments on commit 0bb8341

Please sign in to comment.