WICG / web-preferences-api

The Web Preference API aims to provide a way for sites to override the value for a given user preference (e.g. color-scheme preference) in a way that fully integrates with existing Web APIs.
https://wicg.github.io/web-preferences-api/
Other
41 stars 2 forks source link

Method to get computed preference value? #7

Closed lukewarlow closed 5 months ago

lukewarlow commented 10 months ago

Do we need a new method to get the computed preference value?

Currently, you'd have to use matchMedia which works but isn't necessarily very ergonomic.

For example to listen to a change in the value you'd have to do multiple matchMedias for each potential value.

For most preferences you could infer based on only 1, but color-scheme is open ended and could include other values in future, and (prefers-contrast) has 3 potential values (technically 4 but this API doesn't really make sense for "custom").

lukewarlow commented 10 months ago

While writing https://demo.lukewarlow.dev/web-preferences-api/ it was quite apparent that the current mechanism using matchMedia really isn't very ergonomic.

While it's not necessary for a first pass at this API I do think it's worth considering.

lukewarlow commented 9 months ago

I could imagine the new PreferenceObject interface extending eventtarget and having an onchange so you can track when the override value changes, but also having a new attribute/function that allows you to get the "computed" value of the preference.

lukewarlow commented 9 months ago

In TypeScript terms something like

interface PreferenceObject extends EventTarget {
    // null means the preference is not overridden
    readonly override: string | null;
    // The computed values of the preference, the override if set or the default if not. Name TBD
    // Array as media queries can technically match multiple values at once
    readonly values: string[];

    requestOverride(value: string): Promise<void>;
    clearOverride(): void;

    onchange: ((this: PreferenceObject, ev: Event) => any) | null;
}