Widget Design Guide

Use your imagination!

What follows here is a pretty boring guide, telling you what you can and cannot do with widgets in Décor. Although it's important info to know, one part is missing: you, thinking about what you want to make and how you'd like to share it with others. Even if you put a coding agent to the task of creating your widget, it's still up to you to make something that's fun, easy to use and just perfect. And that will take time! So when you get it working, think about all the ways that other people could realistically use it, and decide whether that's something you would want to cater for. Oh, and don't forget that they will probably break the widget in some unexpected ways! But on the other hand: when it's done it's done. Just share the widget and see how it goes.

Many kinds of widgets

Every widget is made with HTML and CSS, and brought alive using JavaScript. That means it can use any common web technique: typography, pictures, gradients, animation, SVG and canvas drawing. So, yes, a widget is just a tiny website! But they also have a permanent home on someone's decor, next to many other fun and useful widgets. So what kind of widgets can you make? Here you'll find some ideas to get started.

Connected to the web

The Weather widget, with today's temperature.

This widget gets its live weather data from an online service.

Many widgets are built around public information from web services and sites. Such widgets get controlled network access, can request the Mac's approximate location, and use the built-in language model on macOS 26 and later.

  • Weather, sunrise and sunset, air quality.
  • Departures, traffic, exchange rates, sports scores.
  • Headlines from a news feed, a word or picture of the day.
  • Any public API that works with https.
  • Décor halts the connection when the widget is hidden.

Bound to the Mac

The Calendar widget, a ring binder sheet listing today's appointments.

This widget presents a unique view of the user's calendar.

Some widgets request information from applications on the Mac. In exchange for that access, those widgets will not be able to connect to the network. That way, personal data really stays private. Décor will ask before installing widgets that read calendar or contact data.

  • Today's events and reminders from Calendar.
  • Birthdays and people from Contacts.
  • Processor, memory, disk, network and battery statistics.

Self-contained

The Calculator widget.

This widget doesn't need anything from the system to work.

Some of the best widgets do not require external information sources at all, but instead contain everything they need in a simple package.

  • Clocks, timers, calendars and (specialized) calculators.
  • Games and puzzles.
  • Notes, lists and counters.
  • Reference cards, unit converters, artwork and animations.

Although these widgets work offline, on macOS 26 and later they can use the built-in language model.

Powertools

The Caffeine widget: a steel and black coffee machine with an empty glass pot.

This widget asks Décor to prevent the Mac's display from sleeping.

Widgets can trigger Shortcuts, and also use APIs built into Décor to access selected system functions. Unlike in macOS Dashboard, access to command-line tools is not available.

  • A widget to trigger Home scenes.
  • Keeping the display awake.
  • Send off a quick note via Shortcuts.
  • Start a break timer via Shortcuts.

There's a lot you can make. Pick one and get started!

How a widget works

So a widget is a small web page on a decor. Let's take a look at how they work.

The widget bundle

When you create a folder with its name ending in .wdgt, your Mac will show that as a special widget bundle. The bundle contains your HTML and other code, but also an Info.plist that specifies the widget's name, version and several other attributes. When you double-click the widget, it will automatically open in Décor, which allows you to install it. To open the folder instead, right-click it and choose Show Package Contents.

The Finder menu for the Weather widget bundle, with Show Package Contents selected.

The widget on the decor

When a widget is installed, it's also added to the decor. The single HTML page is loaded and displayed using a WebKit view, which supports the same web technology as Safari. It's very clean: just the web page, a resizing grip, and sometimes a close button. It may make sense to add multiple instances of one widget to a decor, for example when you would like to show the time in different parts of the world. This is standard in Décor: every widget on screen gets separate storage, and widgets can't communicate with each other.

How people use the decor

Most likely, someone will bring up the decor using the F12 or 🌐︎ hotkey, look for a few seconds, and then dismiss it. So most of the time widgets are not even on screen. This puts some responsibility into the hands of the widget designer: individual widgets should not spend too much memory, and they should generally not perform activities while hidden. Part of the work is done for you, though: when the decor is hidden, WebKit might temporarily unload widgets to save memory, and Décor pauses all network connections.

Widget API

Décor provides a widget object that can be used from JavaScript. That object allows widgets to integrate well into the Décor system: storing settings, turning the widget around using a cute animation, opening a web link in the browser, and many other things. All of these are available to any widget. But the API can also provide access to the user's calendar, or to the Mac's location, Shortcuts can be run, and information fetched from a web service. Those capabilities are not automatically available to every widget, but must be requested by setting a key in the widget's Info.plist.

Design principles

Widgets requires a different kind of design than applications or web sites. Keep the following guidelines in mind.

One thing well

Give your widget a single purpose. Don't combine several ideas into a single widget, but make multiple widgets instead. Each widget should be simple, and obvious. Making multiple widgets has another advantage, too: you and other users can arrange them to their liking, on their own decor. This provides flexbility and focus.

We ❤️ nice things

Décor widgets all have their own design, something that fits the intended purpose. The decor is emphatically graphical and an alternative for boring text and panel interfaces. That's why we often borrow from physical objects to make widget recognizable. So think how you can represent what you want to communicate in an obvious but fun way.

Keep it clean

Strike a good balance between the clean presentation of information and the niceness of your design. A widget often doesn't present a lot of information, and it needs to be presented efficiently, so users can grasp it in a glance. On the other hand, it's not a sin to leave some room for beautiful and fun design elements.

Your first widget

Quickstart

The Widget Construction Kit provides some tools for making widgets. It is a separate app from Décor, but uses the same widget engine. Download it on the homepage

Open the Widget Construction Kit, choose New Widget... and save it in your Documents directory. This will create a new widget bundle directory and open the widget in the included Simulator. The bundle includes the following files:

MyNewWidget.wdgt/
  Info.plist      widget configuration
  main.html       the widget's single web page
  style.css       a style sheet included in the web page
  script.js       a script file included in the web page
  Default.png     the picture shown briefly while loading the widget
  Icon.png        the icon shown in the widget bar and the install window

The main.html, Info.plist, Default.png and Icon.png are standard names. Other files are optional and may be organized into subfolders.

Info.plist

Now open the bundle in your code editor. The main part of Info.plist looks like this:

<dict>
  <key>CFBundleIdentifier</key>   <string>com.example.tides</string>
  <key>CFBundleName</key>         <string>MyNewWidget</string>
  <key>CFBundleDisplayName</key>  <string>My New Widget</string>
  <key>CFBundleVersion</key>      <string>1.0</string>
  <key>MainHTML</key>             <string>main.html</string>
  <key>Width</key>                <integer>280</integer>
  <key>Height</key>               <integer>160</integer>
  <key>AddShadow</key>            <true/>
</dict>

The Info.plist is a property list, the XML format macOS uses for settings. When you install the command-line tool included in the Widget Construction Kit, you can run wck validate to check that your property list is correct.

Common keys

The following keys should normally be included in every widget:

CFBundleIdentifier
The identifier should be unique to the widget, but stay the same for different versions. That's why it is common to use the inverted domain name style, like com.example.tides. Always change it, ideally to match you own domain name, or using a unique prefix.
CFBundleName
The name of the bundle, same as the file name you used for the widget (Tides).
CFBundleDisplayName
The full widget name shown in the widget bar and the install window.
CFBundleVersion
The widget version.
MainHTML
The HTML page to load.
AddShadow
Draws a drop shadow under the widget. Always set this to true (older widgets added shadows to the included graphics, but this is not needed anymore).

Layout defaults

These keys change default layout properties:

Width, Height
The widget size in points. If you don't provide both, the size of Default.png is used.
CloseBoxInsetX, CloseBoxInsetY
Position of the close button relative to the top-left corner. See The close button.

JavaScript

The JavaScript that's linked from the HTML makes the page dynamic. In the sample, you can click the widget, which will increase the number that's shown. That number is always saved in the widget's preferences, which means that it can be restored when the widget is reloaded or the computer restarted.

var count = 0;

function show() {
  document.getElementById('value').textContent = count;
}

function bump() {
  count += 1;
  // save the count each time it's updated
  widget.setPreferenceForKey(count, 'count');
  show();
}

window.addEventListener('load', function () {
  // only read the count from preferences when the widget is reloaded
  var stored = widget.preferenceForKey('count');
  count = typeof stored === 'number' ? stored : 0;
  show();
  document.getElementById('bump').addEventListener('click', bump);
});

widget.onshow = function () {
  show();
};

Default image

The Default.png image is meant to show an "empty state" for the widget. This could, for example, be a panel or background without data. It's shown for a short time while the widget loads and makes the loading feel faster. The image is removed when the widget is fully loaded.

The icon

Icon.png is used in the widget install screen and also in the widget bar. Make your icon 512 by 512 pixels.

The Widget Construction Kit

The Widget Construction Kit offers the following main functions:

New Widget… Creates a new widget bundle from the default template. You have seen this in the previous chapter.
Load Widget File… Opens a widget you choose. You can also drop a widget on the window, or use File › Open and Open Recent.
Install Command Line Tool Installs the wck command in your ~/.local/bin directory. See Working with a coding agent on how to use it.
Copy Coding Agent Instructions Copies a short prompt that tells a coding agent how to start using the tool. See Working with a coding agent.

The Simulator

When opening a widget, it's shown in the Simulator:

The Simulator window: a sticky notes widget in the Simulator sandbox.

The widget is not "installed" like when you open a widget in Décor. It's directly linked to the bundle you opened, and when you change one of the files in the bundle, the widget will automatically reload. You can use the widget as you would normally do, including typing and scaling.

The onshow and onhide event handlers aren't called in the Simulator. To test them, call them yourself, for example from a test button.

Error console

The console is shown as a drawer. You can follow JavaScript console errors and warnings by choosing View › Show Console (it will pop-up automatically). Décor also adds warnings about deprecated widget features. Finally, you can write console logs from the widget JavaScript code. This is a good debugging tool for core widget functionality.

Web inspector

In addition to the console, you can connect the web inspector. Go to Safari's Develop menu, choose the menu item for your computer and then your Widget Construction Kit window. This is particularly useful for debugging layout issues.

Sandbox

The Widget Construction Kit loads your widget in a sandbox environment, offering some safety by isolating the widget's access. For example, widget preferences in the Simulator aren't shared with Décor and widgets do not get access to your personal app data. Instead, you get fake data from widget.calendar, widget.contacts, widget.location.current, widget.shortcuts and widget.metrics. Some APIs work are normal: widget.location.nameSearch, network access, and the local language model.

Designing the front

Widgets often have distinctive designs, and do not routinely use standard-look controls on the front. That's part of the fun and it means that each widget is an exercise in presenting exactly the right information while offering minimal but effective controls.

Controls

Even when a widget looks non-standard, you can still use normal HTML buttons and other standard controls as base elements. Using CSS, you can style the controls to integrate into the design language of the widget.

Make sure you always use appropriate HTML elements for interactive parts of your widget. This makes widgets easier to use in general, but especially so for keyboard and screen reader (VoiceOver) users. Elements that you should probably use:

  • button
  • select with option
  • a for actual web links, but not as buttons
  • input and textarea
  • img

Do not use div elements to mimic buttons or other controls. It's just not needed anymore.

For visual elements you are encouraged to use any technique that's available in reasonably modern browsers, like canvas drawing.

A not so common control that is particularly useful in widget is the search field. Include it in your widget by using <input type="search">. In Décor, this mimics the macOS standard search field. This is what it looks like:

A search field with a magnifier glass icon, as an example.

You can use the input event to detect typing, so you can filter results, or keydown to detect that Enter was pressed. The search field automatically clears when Esc is used.

Note that the look of search fields varies wildly between recent macOS releases (even more than other standard controls), so it's best to test on older versions, too, and see how it integrates into your design. Search field looks can be styled using CSS just like any other control.

Widgets do not get a lot of room to work with, and that's a problem in particular when showing a list of choices or search results. Such a list may work best when it's wider or taller than the widget itself. That is why a widget can show a native macOS pop-up menu.

A native macOS pop-up menu shown over a widget.

It must be noted that menus cannot be used in combination with incremental search or live autocomplete: users can't type into a search box while showing the menu.

  • When your widget would work best with filtering or live results it's best to include the result list in your overall design instead of as a pop-up menu.
  • Consider using a HTML datalist for selecting from a fixed set of options. However, a text field with a datalist is not common on macOS.

To display a menu, create the items and call popup():

var menu = widget.createMenu();
menu.addMenuItem('Celsius');
menu.addMenuItem('Fahrenheit');
var chosen = await menu.popup(x, y);   // the index, or -1 if dismissed

The menu will then popup at the coordinates x, y relative to the widget. Users can select an item and its index is returned to the script. See the reference for more options.

Tooltips

A title attribute creates a tooltip, which is a small grey label macOS shows when you hover over a control with the mouse pointer:

<button type="button" id="refresh" title="Update the forecast">↻</button>

Always use titles for controls that show only a symbol. On the other hand, do not assume everyone reads it: most important is that the controls are in an obvious place, having an obvious function.

The page title

Every widget must have a <title> element in its <head>. It's not shown by default, but when someone uses VoiceOver to read the screen, this name is read.

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Weather</title>
  <link rel="stylesheet" href="style.css">
  <script src="script.js">
</head>

As soon as the widget has started, you should change the title dynamically from JavaScript to provide a live summary of the widget data. Examples are a weather summary, a currents score, or a timer. The title can also carry a short status message. Update it from JavaScript whenever the value changes:

document.title = 'Weather: 14°, light rain';

Keep the name first and the status short. The title does not replace the visible text or an aria-live region. The title is read and shown while browsing widgets, but live regions can announce updates independently.

Designing the back

The back of a widget is reserved for preferences, credits and logos. It's not required to have any of these, but when they're there, they should be on the back. That way, the front of the widget can focus on presenting the widget's useful information.

Layout and positioning

As an example, here is the back of the Clock widget, showing the layout elements:

The back of the clock widget, showing various controls.

Keep the back layout simple.

  • Leave out as much as you can.
  • Use a 13px font size for all controls.
  • Use a 12px padding from the panel edge to the controls.
  • Use a simple CSS layout. The arrangement above uses flexbox.
  • Place the Done button aligned to the bottom right.
  • Do not add the name of the widget on the back (or the front).

Décor controls

Décor provides a base style for controls on the back. To keep the visual interface consistent between widgets, try to integrate the look.

Buttons

Just add a normal HTML button element and give it a widget-glass-button class:

<button class="widget-glass-button" id="done">Done</button>

You can optionally set colors on the button:

#done {
    --widget-tint: #c4cccd;
    --widget-label-color: #3a4245;
}

The tint will be mixed into the button color and works best when it's on the lighted side. If you have multiple buttons you can set the colors on their parent instead of on each separately.

Scrollbars

A list with gloss-styled scrollbars.

For scrolling views, such as long lists, add the widget-scrollbar style to give the scrollbars a glossy look.

Sliders

A gloss-styled slider control.

Add slider controls using input type="range" and style using widget-slider.

<input id="outline" class="widget-slider" type="range"
       min="0" max="10" step="1">

Storing preferences

Each widget that is placed on a decor has a private preferences storage. The main purpose for preferences is to restore the widget when it is reloaded. Reading preferences can be done during first load, before the widget is shown.

// write a preference: first the value, then the key
widget.setPreferenceForKey(value, 'unit');

// read a preference: returns null when it's not set
var unit = widget.preferenceForKey('unit');

// delete a preference: just write null
widget.setPreferenceForKey(null, 'unit');

Use preferences for anything that should be restored after the widget is reloaded, including data that was retrieved from a web service and does not need to be updated for some time. On the other hand, widgets should generally not store documents or data entered by users that they couldn't reproduce themselves. If your widget needs that, consider making a fully fledged Mac app instead. However, widget settings are normally included in computer backups and can be restored together with other user data.

Although localStorage, IndexedDB and cookies work while the widget is loaded, they are not restored when a widget is reloaded. Do not use these.

Flipping the widget

A widget that has a backside should provide a small info button ⓘ that starts a flip. Décor provides a flip animation for this. On the back, the widget should have a Done button that starts a flip back.

The markup for front and back sides are put in the same HTML document, as shown here:

<body>
  <div id="front">
    <button id="info" 
            class="widget-info-button"
            aria-label="Settings"
            onclick="flip(true)"></button>
  </div>
  <div id="back">
    <button class="widget-glass-button" onclick="flip(false)">Done</button>
  </div>
</body>

The actual flip is carefully choreographed to work together with Décor:

function flip(toBack) {
  // signal that we are going to flip
  widget.prepareForTransition(toBack ? 'ToBack' : 'ToFront');

  // activate the widget content for either front or back
  document.getElementById('front').style.display = toBack ? 'none' : 'block';
  document.getElementById('back').style.display = toBack ? 'block' : 'none';

  // start the flip
  widget.performTransition();
}

Always call prepareForTransition before doing anything, because Décor will create a snapshot of the front and then hide the live version. Any changes you make are invisible until you call performTransition, which will show a flip animation. Exactly at the middle of the flip, the widget is shown again, in its changed state.

Universal design

When designing a widget, keep in mind some principles of universal design as they apply to widgets. By doing this, your widget will be accessible to a very diverse group of users:

  • People who use the VoiceOver screen reader.
  • People who control the computer using a switch.
  • People who prefer using the keyboard.
  • People who have a touch-screen Mac.
  • People who need to reduce movement on screen.

Things to keep in mind

macOS provides all kinds of settings and tools that are available in the Accessibility pane of System Settings. Many of these do not require a lot of involvement from developers, but it's also easy to make widgets less accessible by accident. Here are principles that you should take into account:

  • Keep the default font size at 13px, especially on the back with standard controls. On the front, your design might dictate even larger sizes, or some smaller ones. Compare the readability with Mac apps like Notes.

  • Use normal HTML controls that match the role of the element. For example, use a real HTML button when you need a button. You can still use CSS styling to make then look different.

  • Add descriptions to images by describing the content in an alt=".." attribute and to elements that are not labeled with words (like the info button, which is labeled using just the letter i) by using aria-label="..".

  • In your HTML, order the tags in a useful way, so when you browse them sequentially in a screen reader, it all makes sense. This is easy to achieve, whether you use absolute positioning, flexbox or CSS grid.

  • Set the HTML document title dynamically when updates arrive, providing a brief summary of widget information. The summary can be read aloud by a screen reader while browsing the widgets.

  • Use constrasting colors for information and backgrounds. And try not to use just colors for presenting information, but include more explicit symbols and words. This helps users who use a screen reader, but also people who are color blind.

  • Make controls like buttons large enough to press easily, whether with the mouse, trackpad, or touch screen. A box of 24x24px is the reasonable minimum. The info button does this, even if it looks small.

  • Do not remove focus outlines in CSS. When using the keyboard it should be easy to see which control is active, so you can predict what happens when you press Enter. Instead of removing them, integrate the outlines in your design.

  • Show hidden controls when they have focus. The information button is a good example: it not only shows when hovering the mouse pointer over the widget, but also when you focus it using Option-Tab.

    body:hover #info, #info:focus-visible { opacity: 1; }
    
  • Reduce or remove non-essential animations for people who request that, using CSS prefers-reduced-motion. Removing the animation can often be done without giving up functionality.

  • Set the HTML document language by including an attribute like <html lang="en">, so screen readers use the right voice.

  • To add descriptions to any custom element, use this:

    <p class="visually-hidden">Ten past four</p>
    
    .visually-hidden {
      position: absolute; width: 1px; height: 1px;
      overflow: hidden; clip-path: inset(50%); white-space: nowrap;
    }
    
  • If your widget provides status updates, consider adding a hidden HTML element, give it a status role and update its content when the status changes: <div id="announce" role="status"></div>. This will politely announce the updates in a screen reader.

That's is quite the list. Coding agents are very good at checking and applying these ideas. It needs to be set up only once, and then you can do a checkup every now and then to make sure everything is still good.

Try it out yourself

It's really instructive to get to know macOS accessibility settings. You should be able to open your widget in the Widget Construction Kit and test any of the following.

  • VoiceOver can be activated using ⌘ F5. There is a tutorial. The key combinations take a bit of getting used to, but it's the easiest way to hear what a blind person hears when using it.

  • You can try keyboard navigation in Décor using Option Tab to cycle the controls in your widget. And Control Tab to jump from widget to widget in Décor. Check if every control is accessible.

  • Turn on Reduce motion or Increase contrast in System Settings › Accessibility and see how it affects your widget.

  • In System Settings › Accessibility › Display, turn on the grey scale filter and see if all information is still clear and understandable.

Working with Décor

Widgets integrate with Décor in a various ways. The goal is to provide a seamless experience for users.

Scaling

Most widgets have a fixed size. This is reflected in the Info.plist and the size of the Default.png. Décor does provide users the option to scale widgets. The scaling is handled transparently and you can't control it from the widget code.

A minimum font size is enforced as widgets scale down, and it is likely that the widget doesn't look all too well in very small sizes. You do not need to do anything about this. But do consider making your widget not overly large, so users won't feel the need to scale it down.

If you use bitmaps (for example PNG images), make them about twice the required size so they look fine when the widget is scaled up. But prefer SVG graphics, because such a vector format scales effortlessly, whether it's up or down.

Resizing

The Rijksmuseum widget, a painting in a carved gold frame.

The Rijksmuseum widget shows a painting from the Rijksmuseum API each morning, resizing to fit the frame. It's not perfect, because the artworks have wildly varying proportions. That means that the widget looks very different each day in relation to the surrounding space. This artwork is "The Newa river at St. Petersburg in Winter" by Theodor Hildebrandt.

It is possible to resize a widget to change the space available for content. Use window.resizeTo(w, h) to set fixed dimensions, or window.resizeBy(dx, dy) to expand or contract relative to the current size. Resizing using these functions is always applied to the bottom and right edges, with the top-left corner as the anchor.

Resized proportions are not saved by Décor. When the widget reloads it starts at its declared size again. If the previously set size needs to be restored on reload, use a preference.

Resizing changes how the widget looks, both in proportion to the available screen size and in relation to the widgets surrounding it. Your widget may start overlapping another widget, which is always unexpected for users, so use resizing with some restraint.

Zooming

Especially for art widgets it may be interesting to provide a zoom option. Call widget.zoom.start() to zoom, which will make the screen dark and show only the widget in almost full size.

Transparency

The Paradiso widget, a poster listing the next four nights at the venue.

One of each pair of circles in the Paradiso widget is fully transparent, referencing the original poster design by Experimental Jetset, which has cut holes. The widget uses SVG to draw the background and masks to make the holes transparent. Text is placed to match the layout using JavaScript.

The web view used for widgets is transparent. That means that you can use transparency to define the shape of your widget, allowing for irregular forms. You can set the close button's position accordingly, as described in the next section. Shadows added in Info.plist also follow the shape methodically. However, you should consider the placement of the widget scaling grip when designing shapes using transparency, because you cannot change the grip's position. You can preview the grip on your widget in the Widget Construction Kit.

The close button

By default, the close button is positioned on the widget's top-left corner. To move it, you set CloseBoxInsetX and CloseBoxInsetY in Info.plist. They are the distance from the widget's top-left corner to the button's top-left corner, in pixels. Always set both values or it will be ignored.

You can also move the close button dynamically from JavaScript using widget.setCloseBoxOffset(x, y).

widget.setCloseBoxOffset(8, 8);      // 8 pixels from the corner
widget.setCloseBoxOffset();          // back to the default position

Control regions

Widgets can be moved around by dragging any part that's not a control. Décor detects standard HTML controls and makes sure that those are not used for dragging:

  • button
  • input of any kind
  • select
  • textarea
  • a with a href
  • contenteditable elements

The reason that controls should not be a starting point for dragging is to allow full interaction. For example, when someone holds down the mouse button on a button control, it should be possible to cancel the action by moving the mouse pointer off the button and releasing the button. Moving should not start a drag in that case. The same goes for controls where dragging is core part of the interaction, like sliders.

You can declare additional regions that should not be used for dragging the widget. Your widget may, for example, feature a knob drawn with Canvas, or a map that can be panned. Automatic dragging would get in the way of operating those controls. Mark such elements as no-drag in CSS:

#knob {
    app-region: no-drag;
}

In HTML, check boxes and radio buttons are often enclosed in a label element so the label can also be used to operate the control. In that case, an explicit no-drag is warranted:

<label class="check" style="app-region: no-drag">
    <input type="checkbox" id="showcity" aria-label="Show city name">
    <span aria-hidden="true">Show city name</span>
</label>

Add regions as required, but remember that user need a natural way to drag the widget without opening the widget bar.

Keyboard focus

Widgets can be focused by hovering with the mouse or pressing Control Tab on the keyboard. You can define window.onfocus and window.onblur handlers in JavaScript to detect whether the widget is focused. For example, the Calculator widget's display will light up using this technique, so that it's clear that it can be used using the keyboard.

window.onfocus = function () {
    document.body.classList.add('focused');
};
window.onblur = function () {
    document.body.classList.remove('focused');
};

You can also check whether the widget is currently focused via document.hasFocus(). This can be useful, for example, on first load of the widget.

Keyboard focus after the flip

It's best to strictly control keyboard focus surrounding a flip. This helps people who prefer the keyboard, but also VoiceOver users. As an example, take the main panels of the Weather widget:

<div id="front" tabindex="-1">
    ...
</div>
<div id="back">
    <input id="city" aria-label="City">
</div>

When flipping to the back, focus the first setting using JavaScript, so one can change it using the keyboard. Just call focus() right after the sides are swapped:

widget.prepareForTransition('ToBack');
document.getElementById('front').style.display = 'none';
document.getElementById('back').style.display = 'block';
// set focus on the city control
document.getElementById('city').focus();
widget.performTransition();

For flipping to the front it's sometimes different, because many widgets do not have input controls there. If that's the case, add a tabindex="-1" attribute to the front div, like in the HTML example above. And set the selection outline to none, like so:

#front {
    outline: none;
}

Finally, the transition to the front will look like the following:

widget.prepareForTransition('ToFront');
document.getElementById('front').style.display = 'block';
document.getElementById('back').style.display = 'none';
document.getElementById('front').focus();
widget.performTransition();

Only do this when there are no input controls on the front. Also, never use setTimeout() for focusing, because it will only confuse screen reading software.

Try out the result yourself by flipping the widget back and forth using just the keys Option Tab and Return.

Consider the environment

Widgets should not use a lot of resources. This means that widgets should not use a lot of CPU time and memory from the computer. And any web services used by the widget should be called only as often is needed to provide a good experience.

Web services

Some widgets use web services (sometimes called APIs) to request up-to-date information or, for example, daily artwork. Widgets must respect the reasonable expectations of the providers of such services. That means that any request is actually done to provide users with what they need at the moment of the request, and that requests are postponed when they add no current value.

Just updating a weather forecast every minute, or downloading a multi-megabyte artwork every 15 minutes will impose an unreasonable burden on services, making it hard to sustain them.

In practice, consider what is reasonable and check the terms of service. Here, we provide some examples:

  • With the exception of rain radars, regular computer users should not need near-live updates of the weather. The current weather can be safely updated only every 30 minutes and still be very representative of temperature, general cloud cover, sunshine etc. The forecast can be updated even less frequently.

  • Some larger museums provide access to artworks, including large digital versions that can be downloaded and displayed. When making an art widget from such a service, it's reasonable to want to show a single artwork per day. It's probably not reasonable to make an art browser that tries to download many artworks in a short time (a full web site may be better for that than a widget anyway). But it's important to check the terms.

  • You might want to make a website based on information from the public web that's not specifically offered as an API. This is often possible, and it may be considered reasonably if the widget requests as much information as a user normally would when browsing the site. Do consider that a widget often updates on a schedule, which a user probably doesn't do. That will generate more requests and may end up being unreasonable.

Décor limits the number of web connections and how many bytes can be downloaded in a certain amount of time. Well-considered widgets are not expected to exceed these limits. Should your widget run into the limits after all, consider how it could fit and whether a widget is the right medium for what you want to make.

Décor also saves cached versions of your web service requests, so you get that cached version if you request soon enough. Web services can direct for how long a cached answer should be kept, and Décor will adhere to these directions.

Show and hide

You should not update widgets while they are hidden. Animations should stop and regular fetching of data must be paused.

The FIP widget, showing a record sleeve with the title and artist of the song on air.

The FIP widget shows the song that's currently playing on the radio. The bar that shows how far along we are in the song is not constantly updated from the feed, but animated in the widget instead. Also, nothing is fetched from the feed while the decor is hidden.

When the decor is shown by the user, the function assigned to widget.onshow is called, and the same for widget.onhide when the decor is hidden. Define handler functions to react to these events:

widget.onshow = refresh;
widget.onhide = hide;

Those refresh and hide handlers would make sure that widget updating is stopped while the decor is hidden, and restart it when the decor is shown again. Typical tasks to stop are:

  • Timers
  • (Pending) network requests
  • Animations

Be aware that the onshow function will not neccessarily be called when the widget is freshly loaded. To initialize the widget and the first view, use the window.onload handler. But it's not uncommon for both handlers to be called quickly after each other, so make sure they are well-coordinated.

Refreshing data

The best time to refresh a widget's content is when the decor appears and onshow is run. This means that the refresh happens right when a user shows the widgets. However, this can still trigger too many updates when the user is quickly switching back and forth, for example to use the calculator widget. That's why you need to provide for a check whether the widget is actually due for an update.

A good pattern to use is this: make a refresh function that checks the time between updates and can therefore be safely called every time an event arrives. In the example below, it would only update every fifteen minutes. The load() function is called when the data is received, to process it further.

let lastRefresh = 0;
let isRefreshing = false;

// Request new data from the web service
async function refresh() {
    const fifteenMinutes = 15 * 60 * 1000;
    if (isRefreshing || Date.now() - lastRefresh < fifteenMinutes) return;

    isRefreshing = true;
    lastRefresh = Date.now();
    try {
        const response = await fetch("https://data", { signal: AbortSignal.timeout(30000) });
        if (!response.ok) throw new Error("HTTP " + response.status);
        await loadData(await response.text());
    } catch (err) {
        console.error("refresh failed:", err);
    } finally {
        isRefreshing = false;
    }
}

// Load incoming data from the web service
function loadData(text) {
    ...
}

So after setting that up, you can set widget.onshow = refresh; and don't forget to call refresh() as a part of initializing the widget.

Animations

It's tempting to write JavaScript for animations, updating element styles every frame. Using requestAnimationFrame it is possible to reach a 60Hz or higher frame rate. However, even for simple animations this takes considerable processing power. Instead, it's better to use the Web Animation API or CSS animation. The web view will implement these animations smoothly while optimizing for low CPU use, improving battery life.

  • Always pause animations when the widget is hidden or flipped to the back, and respect the prefers-reduced-motion setting.
  • Prefer animating transform and opacity, because these can be done efficiently by the GPU, without redrawing the element itself. Animations for width, top, box-shadow, filter or SVG attributes are redrawn for every change.
  • Put the animated parts in their own HTML element, and keep static content out of it. An SVG image is drawn as a single layer, so animating just a part of it redraws it in full. Instead, you can wrap the animated part in a div and animate that.
  • Don't change the animation while it runs. If the speed has to change, you can change the duration using updateTiming(). Always keep playbackRate at 1.
  • Measure CPU use before and after doing optimizations, so you can see if it really works. You can see CPU use in the Widget Construction Kit, and you can run wck cpu to take measurements.

Working with a coding agent

A coding agent, such as Claude Code or Codex, can write widgets and use the Widget Construction Kit to take a screenshot, read the console or run JavaScript in the page. Coding agents can use the wck command line tool as a remote control. Simultaneously, you can watch and try the widget in the Simulator window and provide feedback to the coding agent.

Installing the wck tool

Click Install Command Line Tool in the Widget Construction Kit. It creates a link at ~/.local/bin/wck. If that directory is on the path, you can start wck from the command line and instruct a coding agent to use it.

Starting a session

In the Widget Construction Kit main window, click Copy Coding Agent Instructions and provide the text to the agent, followed by initial descriptions of your widget. The instructions tell the agent to load wck docs before starting work. This is especially useful because agents will otherwise use 2005 Dashboard API knowledge to write the widget code.

The first time a coding agent tries to load a widget using the wck open command, you're asked to confirm that the coding agent gets access to the tool. Then, every time a coding agent wants to open a widget for development, you are asked to confirm that, too.

One agent session can run at a time.

Guiding the work

An agent can build and check results, even visually, but it's a poor judge for design details. That's why you can observe the Simulator while the agent is generating code. Nevertheless, when you provide specific design instructions, agent skills may come a long way:

  • Try to describe an object that you would like to use as a base for your widget: "a sheet from a classic paper organiser", "a plain graph with highs and lows marked with a small dot on the line".

  • Iterate on the design, adding specifics as you go. When you push hard, coding agents will try various ways to get something done.

  • Instruct the agent to show widget states that are easy to forget: an empty view, a failed data request, extreme weather conditions, transitions when loading new data.

It's best to put your code under version control, and commit after each change, so you can easily inspect the changes made by the agent.

As a tip to create widgets that look less uniform, try to forbid the coding agent to load its "design skill". You must do this at the start of a new session because information from a skill can not be unloaded.

Agent tooling

You can try wck yourself, but the commands are intended mostly for coding agents. First, the general commands:

wck new <Name>
Makes a widget from the included template.
wck validate <widget>
Checks a widget for various requirements and deprecations (see below).
wck docs [topic]
Shows the widget API reference, or just a specific topic.

Other commands are used to open a development session and perform operations during the session. wck open and wck close make the start and end:

wck open <widget.wdgt>
Opens the widget development session.
wck screenshot
Saves a screenshot of the widget in its current state. -o to provide a filename, --scale 2 to zoom.
wck logs
Shows console logs. --follow keeps running; --level, -n and --since help narrow it down.
wck eval '<js>'
Runs JavaScript in the widget, printing the result. This can also be used to inject design changes in HTML and CSS.
wck reload
Reloads the widget, for example to reset injected changes.
wck info
Prints the widget's file paths, current size, and the actual data access permissions.
wck cpu [--seconds n] [--warmup n]
Measures the widget's CPU use and prints the average and peak. It first waits until the widget has loaded and settled (--warmup, 2 seconds by default), then measures for --seconds (3 by default). Measure before and after a code change to compare.
wck prefs get [key]
Prints the widget's stored preferences.
wck prefs set <key> <value>
Changes a preferences and reloads the widget.
wck status
Reports on the Widget Construction Kit status.
wck close
Closes the widget development session.

Add --json to any command for structured output.

Validating a widget

wck validate reads the widget's files and reports:

  • missing keys in Info.plist like MainHTML or CFBundleIdentifier;
  • unknown or misspelled keys;
  • wrong types, such as a Width written as a string;
  • missing files that are referenced in the code;
  • data access that is denied because of an invalid combination;
  • plist keys that are unused.

It exits with an error when the widget will not load. Instruct the agent to run it for final checks, and also before you share the widget.

Sharing widgets

Packaging

To put a widget on a web site, create a zipped archive: in the Finder, right-click the widget and choose Compress. To send a widget to one person, you can also right-click it on the decor and choose Share Widget…. AirDrop, Messages and Mail all work.

Before you share the widget, run wck validate. Consider moving out files that aren't needed to run the widget, such as artwork originals. This helps keep the widget size down.

Identifiers and versions

Décor uses CFBundleIdentifier to identify versions of the same widget. You should use the inverse of you own domain name as a base, adding the widget's name. For example:

com.example.MyNewWidget

If you do not have your own domain name, you can consider using a variant of your own name to identify yourself as the developer. Do not use other people's domain names for widget identifiers.

Keep the widget identifier the same for every version, but increase CFBundleVersion when you share a new one. The Décor install window will note that it's a new version of the same widget, and replace the old one after user confirmation.