Svelte: Fix FontInput component infinite loop

This commit is contained in:
Keavon Chambers 2023-02-12 01:01:40 -08:00
parent 717e9c861a
commit 33b5c0f5f4
3 changed files with 12 additions and 19 deletions

View file

@ -30,21 +30,16 @@
let open = false;
let entries: MenuListEntry[] = [];
let activeEntry: MenuListEntry | undefined = undefined;
let highlighted: MenuListEntry | undefined = undefined;
let minWidth = isStyle ? 0 : 300;
$: fontFamily,
(async () => {
entries = await getEntries();
activeEntry = getActiveEntry(entries);
highlighted = activeEntry;
})();
$: fontStyle,
async () => {
entries = await getEntries();
activeEntry = getActiveEntry(entries);
highlighted = activeEntry;
};
$: fontFamily, fontStyle, watchFont();
async function watchFont(): Promise<void> {
// We set this function's result to a local variable to avoid reading from `entries` which causes Svelte to trigger an update that results in an infinite loop
const newEntries = await getEntries();
entries = newEntries;
activeEntry = getActiveEntry(newEntries);
}
async function setOpen(): Promise<void> {
open = true;
@ -106,7 +101,6 @@
entries = await getEntries();
activeEntry = getActiveEntry(entries);
highlighted = activeEntry;
});
</script>

View file

@ -77,6 +77,7 @@
<div class="menu-bar-input" bind:this={self} data-menu-bar-input>
{#each entries as entry, index (index)}
<div class="entry-container">
<!-- svelte-ignore a11y-no-noninteractive-tabindex -->
<div
on:click={(e) => clickEntry(entry, e)}
on:keydown={(e) => entry.ref?.keydown(e, false)}
@ -94,7 +95,9 @@
</div>
{#if entry.children && entry.children.length > 0}
<MenuList
on:open={(e) => (entry.ref.isOpen = e.detail)}
on:open={(e) => {
if (entry.ref) entry.ref.isOpen = e.detail;
}}
open={entry.ref?.isOpen || false}
entries={entry.children || []}
direction="Bottom"

View file

@ -105,7 +105,6 @@ export default defineComponent({
open: false,
entries: [] as MenuListEntry[],
activeEntry: undefined as MenuListEntry | undefined,
highlighted: undefined as MenuListEntry | undefined,
entriesStart: 0,
minWidth: this.isStyle ? 0 : 300,
};
@ -113,7 +112,6 @@ export default defineComponent({
async mounted() {
this.entries = await this.getEntries();
this.activeEntry = this.getActiveEntry(this.entries);
this.highlighted = this.activeEntry;
},
methods: {
async setOpen(): Promise<void> {
@ -175,12 +173,10 @@ export default defineComponent({
async fontFamily() {
this.entries = await this.getEntries();
this.activeEntry = this.getActiveEntry(this.entries);
this.highlighted = this.activeEntry;
},
async fontStyle() {
this.entries = await this.getEntries();
this.activeEntry = this.getActiveEntry(this.entries);
this.highlighted = this.activeEntry;
},
},
components: {