JS: buildAppearanceStyle

File: tests/js/unit/shared/buildAppearanceStyle.test.js Tests: getResponsiveValue, isVisibleOnDevice in admin/assets/js/src/shared/utils/buildAppearanceStyle.js


What these functions do

Both functions read widget or section values and answer a device-specific question about them.

  • getResponsiveValue( values, fieldName, device ) — returns the correct value for a field at a given device width, following the desktop → tablet → mobile fallback chain.
  • isVisibleOnDevice( values, device ) — returns whether a widget or section should be shown on a given device.

These are used in the page builder's device preview switcher. When you click the tablet or mobile icon in the builder toolbar, the canvas re-renders using these functions to determine which values and which elements to show.


Responsive field naming convention

Fields that support per-device overrides are stored with suffixed keys:

Key Used for
sanilwb_margin_top Desktop base value
sanilwb_margin_top__tablet Tablet override
sanilwb_margin_top__mobile Mobile override

The fallback chain is: mobile → tablet → desktop. If a mobile value is not set, the tablet value is used. If a tablet value is not set, the desktop base is used. This means you only need to set overrides where the design changes — you do not need to repeat the desktop value for every breakpoint.


Tests

getResponsiveValue

Returns the desktop base value on desktop:

const values = { sanilwb_margin_top: '20' };
getResponsiveValue( values, 'sanilwb_margin_top', 'desktop' )
// → '20'

Prefers the __tablet override on tablet:

const values = {
    sanilwb_margin_top:         '20',
    sanilwb_margin_top__tablet: '10',
};
getResponsiveValue( values, 'sanilwb_margin_top', 'tablet' )
// → '10'

The tablet override takes precedence over the desktop base.


Falls back to __tablet on mobile when __mobile is not set:

const values = {
    sanilwb_margin_top:         '20',
    sanilwb_margin_top__tablet: '10',
    // No sanilwb_margin_top__mobile
};
getResponsiveValue( values, 'sanilwb_margin_top', 'mobile' )
// → '10'

This is the most important edge case. Without this fallback, a widget with only a tablet override would revert to the desktop value on mobile — the tablet adjustment would be silently lost.


isVisibleOnDevice

Returns true when the show flag is "1":

isVisibleOnDevice( { sanilwb_show_desktop: '1' }, 'desktop' )
// → true

Returns false when the show flag is "0":

isVisibleOnDevice( { sanilwb_show_mobile: '0' }, 'mobile' )
// → false

Defaults to true (visible) when the key is missing:

isVisibleOnDevice( {}, 'desktop' )  // → true
isVisibleOnDevice( {}, 'tablet' )   // → true
isVisibleOnDevice( {}, 'mobile' )   // → true

This is important for backwards compatibility. Older saved widgets may not have the visibility flags set at all. Without this default, every existing widget would become invisible when the preview switches device.