Skip to content

Eye Dropper

Reactive EyeDropper API

๐ŸŽฌ Usage

<script>
    import { eye_dropper } from "@sveu/browser"

    const { supported, open, sRGBHex } = eye_dropper()
</script>

๐Ÿ‘ฉโ€๐Ÿ’ปAPI

๐Ÿ™ˆ Options

Read more in the MDN

โ†ฉ๏ธ Returns

Name Description Type
supported Whether the browser supports the EyeDropper API Readable<boolean>
sRGBHex The sRGBHex of the selected color Readable<string>
open Open the eye dropper (open_options?: EyeDropperOpenOptions) => Promise<{sRGBHex:string;} | undefined>

๐Ÿงช Playground

StackBlitz

Source Code ๐Ÿ‘€

Source Code
import { to_readable, to_writable, unstore } from "@sveu/shared"

import { support } from "../support"
import type {
    EyeDropper,
    EyeDropperOpenOptions,
    EyeDropperOptions,
} from "../utils"

/**
 * Reactive [EyeDropper API](https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper_API)
 *
 * @param options - Options
 * - `initial` - Initial sRGBHex.
 *
 * @returns - The eye dropper
 * - `supported` - Whether the browser supports the EyeDropper API
 * - `sRGBHex` - The sRGBHex of the selected color
 * - `open` - Open the eye dropper
 *
 */
export function eye_dropper(options: EyeDropperOptions = {}) {
    const { initial = "" } = options

    const supported = support("EyeDropper", "window")

    const sRGBHex = to_writable(initial)

    /**
     * Open the eye dropper
     *
     * @param open_options - see [EyeDropperOpenOptions](https://developer.mozilla.org/en-US/docs/Web/API/EyeDropper/open)
     *
     * @returns - the dropper result
     */
    async function open(open_options?: EyeDropperOpenOptions) {
        if (!unstore(supported)) return

        const eyeDropper: EyeDropper = new (window as any).EyeDropper()

        const result = await eyeDropper.open(open_options)

        sRGBHex.set(result.sRGBHex)

        return result
    }

    return { supported, sRGBHex: to_readable(sRGBHex), open }
}

Last update: 2023-03-09