/*
  Copyright (c) Microsoft Corporation.

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
*/
import React from 'react';
// Recalculates the value when dependencies change.
export function useAsyncMemo(fn, deps, initialValue, resetValue) {
    const [value, setValue] = React.useState(initialValue);
    React.useEffect(() => {
        let canceled = false;
        if (resetValue !== undefined)
            setValue(resetValue);
        fn().then(value => {
            if (!canceled)
                setValue(value);
        });
        return () => {
            canceled = true;
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, deps);
    return value;
}
// Tracks the element's bounding box.
export function useMeasure() {
    const ref = React.useRef(null);
    const [measure] = useMeasureForRef(ref);
    return [measure, ref];
}
export function useMeasureForRef(ref) {
    const [measure, setMeasure] = React.useState(new DOMRect(0, 0, 10, 10));
    const recalculateMeasure = React.useCallback(() => {
        const target = ref?.current;
        if (target)
            setMeasure(target.getBoundingClientRect());
    }, [ref]);
    React.useLayoutEffect(() => {
        const target = ref?.current;
        if (!target)
            return;
        recalculateMeasure();
        const resizeObserver = new ResizeObserver(recalculateMeasure);
        resizeObserver.observe(target);
        window.addEventListener('resize', recalculateMeasure);
        return () => {
            resizeObserver.disconnect();
            window.removeEventListener('resize', recalculateMeasure);
        };
    }, [recalculateMeasure, ref]);
    return [measure, recalculateMeasure];
}
export function lowerBound(array, object, comparator, left, right) {
    let l = left || 0;
    let r = right !== undefined ? right : array.length;
    while (l < r) {
        const m = (l + r) >> 1;
        if (comparator(object, array[m]) > 0)
            l = m + 1;
        else
            r = m;
    }
    return r;
}
export function upperBound(array, object, comparator, left, right) {
    let l = left || 0;
    let r = right !== undefined ? right : array.length;
    while (l < r) {
        const m = (l + r) >> 1;
        if (comparator(object, array[m]) >= 0)
            l = m + 1;
        else
            r = m;
    }
    return r;
}
export function copy(text) {
    const textArea = document.createElement('textarea');
    textArea.style.position = 'absolute';
    textArea.style.zIndex = '-1000';
    textArea.value = text;
    document.body.appendChild(textArea);
    textArea.select();
    document.execCommand('copy');
    textArea.remove();
}
export function useSetting(name, defaultValue) {
    if (name)
        defaultValue = settings.getObject(name, defaultValue);
    const [value, setValue] = React.useState(defaultValue);
    const setValueWrapper = React.useCallback((value) => {
        if (name)
            settings.setObject(name, value);
        else
            setValue(value);
    }, [name, setValue]);
    React.useEffect(() => {
        if (name) {
            const onStoreChange = () => setValue(settings.getObject(name, defaultValue));
            settings.onChangeEmitter.addEventListener(name, onStoreChange);
            return () => settings.onChangeEmitter.removeEventListener(name, onStoreChange);
        }
    }, [defaultValue, name]);
    return [value, setValueWrapper];
}
const partitions = new Map();
const hooks = new Map();
let currentPartition;
export function usePartitionedState(name, defaultValue) {
    const [value, setValue] = React.useState();
    hooks.set(name, { setter: setValue, defaultValue });
    const setValueWrapper = React.useCallback((newValue) => {
        const state = partitions.get(currentPartition || 'default') || {};
        state[name] = newValue;
        partitions.set(currentPartition || 'default', state);
        setValue(newValue);
    }, [name]);
    return [value, setValueWrapper];
}
export function togglePartition(partition) {
    if (currentPartition === partition)
        return;
    currentPartition = partition;
    const store = partitions.get(partition) || {};
    for (const [name, value] of hooks.entries())
        value.setter(store[name] || value.defaultValue);
}
export class Settings {
    onChangeEmitter = new EventTarget();
    getString(name, defaultValue) {
        return localStorage[name] || defaultValue;
    }
    setString(name, value) {
        localStorage[name] = value;
        this.onChangeEmitter.dispatchEvent(new Event(name));
        window.saveSettings?.();
    }
    getObject(name, defaultValue) {
        if (!localStorage[name])
            return defaultValue;
        try {
            return JSON.parse(localStorage[name]);
        }
        catch {
            return defaultValue;
        }
    }
    setObject(name, value) {
        localStorage[name] = JSON.stringify(value);
        this.onChangeEmitter.dispatchEvent(new Event(name));
        window.saveSettings?.();
    }
}
export const settings = new Settings();
// inspired by https://www.npmjs.com/package/clsx
export function clsx(...classes) {
    return classes.filter(Boolean).join(' ');
}
export async function sha1(str) {
    const buffer = new TextEncoder().encode(str);
    return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-1', buffer))).map(b => b.toString(16).padStart(2, '0')).join('');
}
export function scrollIntoViewIfNeeded(element) {
    if (!element)
        return;
    if (element?.scrollIntoViewIfNeeded)
        element.scrollIntoViewIfNeeded(false);
    else
        element?.scrollIntoView();
}
const kControlCodesRe = '\\u0000-\\u0020\\u007f-\\u009f';
export const kWebLinkRe = new RegExp('(?:[a-zA-Z][a-zA-Z0-9+.-]{2,}:\\/\\/|www\\.)[^\\s' + kControlCodesRe + '"]{2,}[^\\s' + kControlCodesRe + '"\')}\\],:;.!?]', 'ug');
/**
 * Manages flash animation state.
 * Calling `trigger` will turn `flash` to true for a second, and then back to false.
 * If `trigger` is called while a flash is ongoing, the ongoing flash will be cancelled and after 50ms a new flash is started.
 * @returns [flash, trigger]
 */
export function useFlash() {
    const [flash, setFlash] = React.useState(false);
    const trigger = React.useCallback(() => {
        const timeouts = [];
        setFlash(currentlyFlashing => {
            timeouts.push(setTimeout(() => setFlash(false), 1000));
            if (!currentlyFlashing)
                return true;
            timeouts.push(setTimeout(() => setFlash(true), 50));
            return false;
        });
        return () => timeouts.forEach(clearTimeout);
    }, [setFlash]);
    return [flash, trigger];
}
export function useCookies() {
    const cookies = React.useMemo(() => {
        return document.cookie.split('; ').filter(v => v.includes('=')).map(kv => {
            const separator = kv.indexOf('=');
            return [kv.substring(0, separator), kv.substring(separator + 1)];
        });
    }, []);
    return cookies;
}
//# sourceMappingURL=uiUtils.js.map