@startside/swa 1.0.0 → 1.0.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,2352 @@
1
+ # Startside Widget API (SWA) 1.0
2
+
3
+ **Editor's Draft, 4 November 2026**
4
+
5
+ <dl>
6
+ <dt>This version:</dt><dd><a href="https://startside.app/swa/1.0/">https://startside.app/swa/1.0/</a> (Markdown: <a href="https://startside.app/swa/1.0/spec.md">spec.md</a>; for agents: <a href="https://startside.app/swa/1.0/agents.md">agents.md</a>)</dd>
7
+ <dt>Previous version:</dt><dd><a href="https://startside.app/uwa/1.2/spec.md">Universal Widget API (UWA) 1.2.4</a>, Netvibes, 2008–2010</dd>
8
+ <dt>Specifications built on this one:</dt><dd><a href="https://startside.app/rwa/1.0/spec.md">React Widget API (RWA) 1.0</a></dd>
9
+ <dt>Editor:</dt><dd>François Hodierne (Startside)</dd>
10
+ <dt>Licence:</dt><dd>© 2026 François Hodierne. This document is shared under the <a href="https://creativecommons.org/licenses/by/4.0/">Creative Commons Attribution 4.0 International</a> licence (CC BY 4.0).</dd>
11
+ <dt>Implementation:</dt><dd>Startside, <a href="https://startside.app/">startside.app</a> (its status: <a href="#appendix-c-implementation-status-and-features-at-risk">Appendix C</a>)</dd>
12
+ </dl>
13
+
14
+ ---
15
+
16
+ ## Abstract
17
+
18
+ This specification defines the **Startside Widget API (SWA)**: a format for widgets, small Web applications shown
19
+ many to a page on a personal dashboard, and the interface through which a widget and its host work together. A
20
+ widget is a single HTML document. Its head declares its name and metadata; a hidden form in its body declares its
21
+ settings; its scripts draw it through one object, `widget`, which gives it the host's services: its title bar, its
22
+ settings and memory, a shared article reader, read and unread items, kept content, the page's audio and video
23
+ players, sharing, and its accounts. Hosts run widgets in sandboxed frames, under the same rules for every author.
24
+
25
+ SWA is the successor of the Universal Widget API (UWA) 1.2, whose JavaScript interface it keeps.
26
+
27
+ **New to SWA?** [SWA in 60 lines](https://startside.app/swa/1.0/quickstart.md) has a complete widget, the rules as a table and a checklist;
28
+ this document is the reference behind it.
29
+
30
+ ## Status of This Document
31
+
32
+ *This section describes the status of this document at the time of its publication.*
33
+
34
+ This is an **Editor's Draft**, published by its editor for review by the people and software agents who write
35
+ Startside widgets. It is not a publication of the W3C, the IETF or any standards body, and is not endorsed by one; it
36
+ follows their conventions so that it can be read, implemented and checked as theirs are.
37
+
38
+ This document describes what the Startside host implements on the date above, except the features listed in
39
+ [Appendix C](#appendix-c-implementation-status-and-features-at-risk), which it specifies ahead of their
40
+ implementation: they are **at risk** and may change or be removed. A difference between this document and the
41
+ implementation, other than those, is a bug in one of them.
42
+
43
+ Questions this draft leaves open are listed in [Appendix E](#appendix-e-open-issues). Comments are welcome to its
44
+ editor.
45
+
46
+ ## Table of Contents
47
+
48
+ 1. [Introduction](#1-introduction)
49
+ 2. [Conformance](#2-conformance)
50
+ 3. [Terminology](#3-terminology)
51
+ 4. [Widget files](#4-widget-files)
52
+ 5. [The settings form](#5-the-settings-form)
53
+ 6. [Processing model](#6-processing-model)
54
+ 7. [The `Widget` interface](#7-the-widget-interface)
55
+ 8. [Data access](#8-data-access)
56
+ 9. [Built-in objects](#9-built-in-objects)
57
+ 10. [Execution environments](#10-execution-environments)
58
+ 11. [Compatibility with UWA 1.2](#11-compatibility-with-uwa-12)
59
+ 12. [Security Considerations](#12-security-considerations)
60
+ 13. [Privacy Considerations](#13-privacy-considerations)
61
+ 14. [Accessibility Considerations](#14-accessibility-considerations)
62
+ - [Appendix A. Examples](#appendix-a-examples)
63
+ - [Appendix B. Changes from UWA 1.2.4](#appendix-b-changes-from-uwa-124)
64
+ - [Appendix C. Implementation status and features at risk](#appendix-c-implementation-status-and-features-at-risk)
65
+ - [Appendix D. IDL Index](#appendix-d-idl-index)
66
+ - [Appendix E. Open issues](#appendix-e-open-issues)
67
+ - [Appendix F. Tools for authors](#appendix-f-tools-for-authors)
68
+ - [References](#references)
69
+ - [Acknowledgements](#acknowledgements)
70
+
71
+ ---
72
+
73
+ ## 1. Introduction
74
+
75
+ *This section is non-normative.*
76
+
77
+ A personal dashboard shows many small applications side by side: a weather forecast, a news feed, a radio, a game.
78
+ Each is written by someone else, often for many dashboards at once, and each needs the same few things from the page
79
+ around it: a title bar, settings, somewhere to keep its data, a way to open links, a share in the page's sound. UWA,
80
+ published by Netvibes in 2006–2008, defined such widgets as XHTML files with XML preferences. SWA moves them to
81
+ ordinary HTML and defines what the host adds.
82
+
83
+ A widget file is an HTML document with three conventions:
84
+
85
+ - its settings are a hidden `<form id="preferences">`, which the host reads without running the widget;
86
+ - its code works through one object, `widget`, rather than `document` and `window`;
87
+ - it is written for a sandboxed frame: what it keeps, fetches and opens goes through the host.
88
+
89
+ <div class="example">
90
+
91
+ **Example 1.** A widget greeting the person named in its settings.
92
+
93
+ ```html
94
+ <!doctype html>
95
+ <html>
96
+ <head>
97
+ <script src="https://startside.app/swa/1.0/runtime.js"></script>
98
+ <title>Hello</title>
99
+ <meta name="description" content="Says hello." />
100
+ </head>
101
+ <body>
102
+ <form id="preferences" hidden>
103
+ <label>Who <input type="text" name="who" value="world" /></label>
104
+ </form>
105
+ <p>Hello, <span class="who">world</span>!</p>
106
+ <script>
107
+ widget.addEventListener('load', () => {
108
+ widget.body.querySelector('.who').textContent = String(widget.settings.get('who'));
109
+ });
110
+ </script>
111
+ </body>
112
+ </html>
113
+ ```
114
+
115
+ Its markup is in the file and shows at once; its code only fills the name (7.3.1).
116
+
117
+ </div>
118
+
119
+ The design goals are, in order: one clean file that tools and people can read; metadata and settings declared in
120
+ markup, so a host reads them without running code; the same rules for every widget, the host's own included; and no
121
+ build step.
122
+
123
+ ## 2. Conformance
124
+
125
+ Sections marked as non-normative, examples and notes are non-normative. Everything else is normative, requirements on
126
+ widget authors included.
127
+
128
+ The key words **MAY**, **MUST**, **MUST NOT**, **OPTIONAL**, **RECOMMENDED**, **REQUIRED**, **SHALL**, **SHALL
129
+ NOT**, **SHOULD** and **SHOULD NOT** in this document are to be interpreted as described in BCP 14 [[RFC2119](#ref-rfc2119)]
130
+ [[RFC8174](#ref-rfc8174)] when, and only when, they appear in all capitals, as shown here.
131
+
132
+ This specification defines conformance criteria for three classes of products:
133
+
134
+ - **<a id="dfn-widget-file"></a>widget files**, which satisfy every requirement on widget files and their authors;
135
+ - **<a id="dfn-host"></a>hosts** (user agents), which run widget files as the processing model (section 6) and the
136
+ interfaces (sections 7 to 9) define;
137
+ - **<a id="dfn-checker"></a>conformance checkers**, which verify that a widget file meets the requirements that can
138
+ be checked without running it.
139
+
140
+ Requirements phrased as algorithms (*"run these steps"*) may be implemented in any manner, as long as the result is
141
+ equivalent.
142
+
143
+ A host **MAY** implement only part of section 7: a widget calls a member it depends on only after testing that it is
144
+ present (`if (widget.addWidget) …`), and **MUST** remain usable where it is absent.
145
+
146
+ The interfaces are defined in Web IDL [[WEBIDL](#ref-webidl)]. Where Web IDL describes a member that a host
147
+ implements in a script (the reference implementation does), its argument conversions are those of the description,
148
+ not of a generated binding.
149
+
150
+ ## 3. Terminology
151
+
152
+ This specification uses the terms *event*, *dispatch*, *listener* and *canceled flag* from [[DOM](#ref-dom)],
153
+ *document*, *element*, *script* and *transient activation* from [[HTML](#ref-html)],
154
+ *URL* and *parsing a URL* from [[URL](#ref-url)], *fetch* from [[FETCH](#ref-fetch)],
155
+ and *list*, *map* and *struct* from [[INFRA](#ref-infra)].
156
+
157
+ <dl>
158
+ <dt><a id="dfn-widget"></a><b>widget</b></dt>
159
+ <dd>One instance of a widget file on a page, with its own settings, memory and read state. One file can be
160
+ instantiated many times.</dd>
161
+
162
+ <dt><a id="dfn-dashboard"></a><b>dashboard</b></dt>
163
+ <dd>A host's page holding several widgets, arranged in tabs and columns.</dd>
164
+
165
+ <dt><a id="dfn-standalone-host"></a><b>standalone host</b></dt>
166
+ <dd>The runtime script running a widget file opened on its own, at its URL or from disk.</dd>
167
+
168
+ <dt><a id="dfn-trusted"></a><b>trusted</b></dt>
169
+ <dd>A widget file served from the host's own widget directory (in Startside, <code>/uwa/</code>). Any other file is
170
+ <b>untrusted</b>: one from another site, or dropped from the person's computer.</dd>
171
+
172
+ <dt><a id="dfn-setting"></a><b>setting</b></dt>
173
+ <dd>A named preference of a widget, declared by its settings form (section 5), whose value is a string.</dd>
174
+
175
+ <dt><a id="dfn-key"></a><b>key</b></dt>
176
+ <dd>A widget file's short identifier, derived from its file name (section 4.1), used in the host's addresses.</dd>
177
+
178
+ <dt><a id="dfn-activation"></a><b>activation-gated</b></dt>
179
+ <dd>Said of an operation that a framed widget may perform only while its frame has transient activation: right after
180
+ a click or a key press in it.</dd>
181
+
182
+ <dt><a id="dfn-content-feed"></a><b>content feed</b></dt>
183
+ <dd>A JSON Feed 1.1 document [[JSONFEED](#ref-jsonfeed)], with the extensions of section 8.5.</dd>
184
+
185
+ <dt><a id="dfn-refresh"></a><b>refresh</b></dt>
186
+ <dd>Drawing a widget again and asking for its data again, triggered by the person, by its refresh interval, or by its
187
+ settings changing (section 6.6). What it asks for may still come from a cache, such as the host's proxy's (8.4).</dd>
188
+ </dl>
189
+
190
+ ## 4. Widget files
191
+
192
+ ### 4.1 File names and keys
193
+
194
+ A widget file's name **MUST** be `<name>.swa.html`, where `<name>` consists of one or more ASCII lowercase letters,
195
+ ASCII digits and U+002D (-). Its **key** is `<name>.swa`.
196
+
197
+ <div class="example">
198
+
199
+ **Example 2.** `weather.swa.html` has the key `weather.swa`; Startside adds it from `/add/weather.swa`.
200
+
201
+ </div>
202
+
203
+ Files named otherwise are other formats: UWA 1.2 files (`.uwa.xhtml`, ideally; `.xhtml`), section 11, and RWA files
204
+ (`.rwa.html`) [[RWA](#ref-rwa)], a format that extends this specification with templates.
205
+
206
+ ### 4.2 Document requirements
207
+
208
+ A widget file **MUST** be a document in the HTML syntax [[HTML](#ref-html)], beginning with a DOCTYPE,
209
+ encoded in UTF-8. It needs no namespace, no CDATA section and no XML well-formedness. It **MUST NOT** depend on
210
+ content outside its `head` and `body` other than the resources it links.
211
+
212
+ Its structure, in order:
213
+
214
+ ```html
215
+ <!doctype html>
216
+ <html>
217
+ <head>
218
+ <script src="…/swa/1.0/runtime.js"></script> <!-- 4.3, REQUIRED -->
219
+ <title>…</title> <!-- 4.4, REQUIRED -->
220
+ <meta name="…" content="…" /> <!-- 4.5 -->
221
+ <link rel="icon" href="…" /> <!-- 4.6 -->
222
+ <style>…</style> <!-- 4.7 -->
223
+ <script src="…"></script> <!-- 4.8, a library -->
224
+ </head>
225
+ <body>
226
+ <form id="preferences" hidden>…</form> <!-- 5 -->
227
+ … <!-- 4.9, initial content -->
228
+ <script>…</script> <!-- 4.8 -->
229
+ </body>
230
+ </html>
231
+ ```
232
+
233
+ ### 4.3 The runtime script
234
+
235
+ The head **MUST** contain exactly one `script` element whose `src` is an absolute URL whose path ends with
236
+ `/swa/<version>/runtime.js`, `<version>` being `1.0` for this specification. The URL **SHOULD** use the `https`
237
+ scheme and **SHOULD** name a host that serves the runtime, so that the file runs when opened from disk. In order of
238
+ preference:
239
+
240
+ 1. `https://startside.app/swa/1.0/runtime.js`, which has the runtime's fixes as soon as the site does;
241
+ 2. the npm package `@startside/swa` on a CDN, where startside.app can't be loaded:
242
+ `https://cdn.jsdelivr.net/npm/@startside/swa@1/swa/1.0/runtime.js` or
243
+ `https://unpkg.com/@startside/swa@1/swa/1.0/runtime.js`;
244
+ 3. the runtime inlined, below.
245
+
246
+ A CDN address **SHOULD** name the package's version: `@1` gets the runtime's fixes, an exact version (`@1.0.0`) none,
247
+ and no version or `@latest` can bring a release that breaks the file. The package has its own version; the API's is the
248
+ one in the path, and a release of `@1` keeps `swa/1.0/`. A CDN's copy follows the site's releases.
249
+
250
+ **The runtime's host.** The runtime sends the widget's requests (8) through the proxies of its host: the origin its
251
+ script's `data-host` attribute names, an absolute `https` URL; absent, the origin the runtime is served from when it is
252
+ at that origin's root (its path is exactly `/swa/<version>/runtime.js`: startside.app, another Startside); else
253
+ `https://startside.app` (a CDN, an inlined copy).
254
+
255
+ ```html
256
+ <script src="https://cdn.jsdelivr.net/npm/@startside/swa@1/swa/1.0/runtime.js" data-host="https://startside.app"></script>
257
+ ```
258
+
259
+ **The runtime inlined.** In its place, the head **MAY** contain exactly one `script` element without `src` whose
260
+ `data-runtime` attribute is `swa/<version>` and whose content is that runtime's text, unchanged: for an environment that
261
+ loads no script from another site (a chat's preview of a file, a page offline). Its requests still go to the runtime's
262
+ host, above: where the environment refuses them too (a preview that allows no request to another site), the widget
263
+ runs and draws, and its requests fail as on a page offline. A host treats it
264
+ as it treats the runtime's address: a dashboard **MUST NOT** run it, and reads the file's format from it. Such a copy
265
+ doesn't get the runtime's later fixes: a file **SHOULD** load the runtime by its address, and an inlined copy
266
+ **SHOULD** be made again from that address when the file is published (Appendix F).
267
+
268
+ ```html
269
+ <script data-runtime="swa/1.0" data-host="https://startside.app">
270
+ /* the text of https://startside.app/swa/1.0/runtime.js */
271
+ </script>
272
+ ```
273
+
274
+ The runtime's text contains no `</script`, `<!--` or `<script`, so it can be written into a `script` element as it is.
275
+
276
+ The runtime brings the standalone host and its stylesheet. A dashboard **MUST NOT** run that script: it runs the widget
277
+ with its own implementation of the same version, whatever URL the file names.
278
+
279
+ A host **MUST** also accept, in place of the runtime script, UWA's two platform tags: a stylesheet link whose path is
280
+ `/themes/uwa/style.css` and a script whose path is `/js/UWA/load.js.php`, at any origin; a dashboard ignores them as it
281
+ ignores the runtime script.
282
+
283
+ > **Note:** Startside serves the runtime from its development server and its build; UWA's two tags are those of UWA 1.2
284
+ > files, accepted so that a file moving to SWA can keep them a while.
285
+
286
+ ### 4.4 The title
287
+
288
+ The head **MUST** contain one `title` element. Its text is the widget's name in the host's lists, and its title until
289
+ the widget sets one (section 7.3).
290
+
291
+ ### 4.5 Metadata
292
+
293
+ Metadata are `meta` elements with a `name` and a `content` attribute. A host reads them without running the widget.
294
+ Names are case-sensitive; an unknown name, or a value that doesn't match its syntax below, is ignored. All are
295
+ optional.
296
+
297
+ <table>
298
+ <thead><tr><th>Name</th><th>Value</th><th>Meaning</th></tr></thead>
299
+ <tbody>
300
+ <tr><td colspan="3"><b>Description</b></td></tr>
301
+ <tr><td><code>description</code></td><td>text</td><td>One line describing the widget, in the host's lists</td></tr>
302
+ <tr><td><code>author</code>, <code>email</code>, <code>website</code></td><td>text, an e-mail address, a URL</td><td>Who made it</td></tr>
303
+ <tr><td><code>version</code></td><td>text</td><td>The widget's own version</td></tr>
304
+ <tr><td><code>apiVersion</code></td><td><code>1.0</code></td><td>The SWA version written for</td></tr>
305
+ <tr><td><code>keywords</code></td><td>text</td><td>More words the host's search finds it by</td></tr>
306
+ <tr><td><code>category</code></td><td>text</td><td>The section of the host's catalogue listing it (Startside: <code>Blogs</code>, <code>Games</code>, <code>Music &amp; Radio</code>, <code>News</code>, <code>Social</code>, <code>TV &amp; Video</code>, <code>Art</code>, <code>Vintage widgets</code>)</td></tr>
307
+ <tr><td><code>unlisted</code></td><td><code>true</code></td><td>Listed in no section and no search; still available from its address</td></tr>
308
+ <tr><td><code>addButton</code></td><td><code>false</code></td><td>No button to add it to a host on its own page (10.3): a demonstration, a widget meant for its own page</td></tr>
309
+ <tr><td colspan="3"><b>Appearance</b></td></tr>
310
+ <tr><td><code>chromeColor</code>, <code>chromeColorDark</code></td><td>a CSS color</td><td>Its title bar and border, light and dark</td></tr>
311
+ <tr><td><code>background</code>, <code>backgroundDark</code></td><td>a CSS color</td><td>Its body's color from the first paint, before the file loads, light and dark. <b>SHOULD</b> equal its root element's background</td></tr>
312
+ <tr><td><code>accentColor</code></td><td>a CSS color</td><td>Its brand color, used by the reader for the items it opens</td></tr>
313
+ <tr><td><code>looks</code></td><td><code>own</code>, <code>page</code>, <code>both</code></td><td>Whether it keeps its own colors, follows the page's, or offers both; <code>own</code> for a widget whose colors are its content</td></tr>
314
+ <tr><td><code>maximize</code></td><td><code>column</code>, <code>fill</code>, <code>fit</code></td><td>How it fills the window when maximized; <code>column</code> when absent</td></tr>
315
+ <tr><td><code>maximizeWidth</code></td><td>an integer, 360 to 1600</td><td>Its width in CSS pixels when maximized in a column; 600 when absent</td></tr>
316
+ <tr><td colspan="3"><b>Behaviour</b></td></tr>
317
+ <tr><td><code>autoRefresh</code></td><td>a positive integer</td><td>Minutes between automatic refreshes</td></tr>
318
+ <tr><td><code>livePreferences</code></td><td><code>false</code>, <code>instant</code></td><td>When settings apply (section 6.5)</td></tr>
319
+ <tr><td><code>feed</code></td><td>a URL template</td><td>The feed it reads (section 6.4)</td></tr>
320
+ <tr><td><code>accountService</code></td><td>a service name</td><td>The service of its account (section 7.13)</td></tr>
321
+ <tr><td><code>accountScope</code></td><td>permissions, space-separated</td><td>Only accounts allowing one of them are offered</td></tr>
322
+ <tr><td><code>debugMode</code></td><td><code>true</code></td><td><code>widget.log</code> writes to the console</td></tr>
323
+ <tr><td><code>export</code></td><td><code>false</code></td><td>Not sent as a file: a host offers no way to send this widget with its settings to someone else, and refuses a file claiming it. For a widget showing its signed-in account's own data, which means nothing without it</td></tr>
324
+ </tbody>
325
+ </table>
326
+
327
+ ### 4.6 Icon and thumbnail
328
+
329
+ A `link` element with `rel="icon"` gives the widget's icon, its URL relative to the file. It **MAY** be a `data:` URL
330
+ (an SVG, PNG or WebP image: `href="data:image/svg+xml,…"`), which travels with the file: the one icon a file shared by
331
+ itself, dropped or chosen from a computer, keeps, a relative URL having nothing then to resolve against. A PNG image beside the file,
332
+ with its base name (`weather.png` for `weather.swa.html`), is its thumbnail in the host's catalogue.
333
+
334
+ > **Note:** A best practice, not a requirement. An icon is shown small: 16 pixels in a title bar, 32 in a catalogue's
335
+ > list. An SVG stays sharp at every size and, inline, is a few hundred bytes of text, percent-encoded rather than in
336
+ > base64 (`#` written `%23`, single quotes inside the `href`'s double quotes). A PNG or WebP icon works as well: a
337
+ > square of 64 by 64 pixels, sharp at both sizes on a high-density screen. Either way, a few bold shapes read at 16
338
+ > pixels where fine detail doesn't.
339
+
340
+ ### 4.7 Styles
341
+
342
+ The file's `style` elements and stylesheet links style the widget only (section 10). Rules **SHOULD** target classes of
343
+ the widget's own rather than element types, and **SHOULD** be scoped under the widget's own root class (`.flood .board`,
344
+ not `.board`): on its own page, the widget's styles share the document with the host's title bar and menu, whose
345
+ elements carry plain class names (`title`, `options`, `hint`), which an unscoped rule would restyle (10.3). A host provides these hooks:
346
+
347
+ | Hook | Present when |
348
+ |---|---|
349
+ | `color-scheme` on the root, `light` or `dark` | always: the page's mode; `light-dark()` in the widget's CSS follows it, as do form controls and scrollbars |
350
+ | attribute `data-color-scheme` on the root, `light` or `dark` | always: the same, for what isn't a color (a picture, a shadow, a layout): `:root[data-color-scheme="dark"] .x` |
351
+ | class `uwa-neutral` on the root | the widget follows the page's look, which replaces its own colors |
352
+ | class `uwa-full-size` on the root | the widget is maximized |
353
+ | class `uwa-full-window` on the root | the widget is full screen, alone over the window, whatever its `maximize` says |
354
+ | custom properties `--module-color`, `--module-paper` | the person gave the widget a palette color: its shade, and a pastel of it |
355
+ | custom properties `--text`, `--muted`, `--link`, `--link-visited`, `--widget-bg`, `--border`, `--hover` | always: the page style's colors |
356
+ | custom properties `--accent`, `--accent-ink`, `--accent-glow` | always: the page's accent, its ink (text on it) and its light shade; changed in place, the widget not restarted, when the person picks another accent (a widget reads them in its CSS, not once in script) |
357
+ | custom property `--font-body` | always: the page style's font family |
358
+
359
+ The root is the widget's `html` element, framed and on its own page; a selector such as
360
+ `:root[data-color-scheme="dark"] .x` matches in both.
361
+
362
+ Another host may not set these properties: a widget **SHOULD** give each its own fallback, `var(--text, #222)`.
363
+ Classes in the host's base stylesheet (UWA's `.buttonClean`, `.nv-pager`, `.loading`) are UWA's, not part of this
364
+ specification: an SWA widget styles its own, the only classes it relies on being those this document names (`uwa-read`,
365
+ `ext-link`, 7.10). They still reach its document in Startside, so a widget avoids their names for its own classes
366
+ (`loading`, `spinner`, `buttonClean`, `nv-pager`, `uwa-error`) or prefixes its classes: `.loading`'s `display: flex`
367
+ outweighs the `hidden` attribute, and a "Loading…" so named stays shown.
368
+
369
+ **Light and dark.** A widget writes each of its colors once for both modes with CSS's `light-dark()`
370
+ [[CSS-COLOR-5](#ref-css-color-5)]: `color: light-dark(#293543, #f2f4f6)`, the first for a light page, the second for a
371
+ dark one, as the root's `color-scheme` says. `data-color-scheme` is for the rest. `@media (prefers-color-scheme)` is
372
+ the system's preference, not the page's mode (a framed widget gets it from the system in some browsers, from the page in
373
+ others): a widget **SHOULD NOT** use it for its look. UWA's class, `uwa-dark`, stays for UWA files (section 11).
374
+
375
+ Who draws what depends on the widget's look, which its `looks` metadata (4.5) offers and the person picks:
376
+
377
+ | | Its own look | The page's look (`uwa-neutral`) |
378
+ |---|---|---|
379
+ | The title bar, the border, the corner | the host's; `chromeColor` and `setChromeColor` color it | the host's |
380
+ | The body's background | the widget's (`background`, `backgroundDark`, its CSS) | the page's: the host makes every background transparent over `--widget-bg` |
381
+ | Text, links, borders, shadows | the widget's CSS | the page's: text `--text`, links `--link`, headings `--text`, borders a faint line, no shadows (the host overrides them) |
382
+ | Pictures, icons, form controls, a `canvas` | the widget's | the widget's: kept |
383
+ | The font | the host's base, 11 pixels and `--font-body` in Startside, unless the widget sets its own | the same |
384
+ | The accent | the widget uses `--accent` where it wants the page's | the same |
385
+ | Light and dark | the widget's, by `light-dark()` and `data-color-scheme`; without them its light look on a dark page | the page's colors, light or dark |
386
+
387
+ A widget's CSS **MUST NOT** style the host's elements (the title bar, the page around it, 10.3). A host puts the
388
+ widget's styles in a cascade layer under the page's look [[CSS-CASCADE-5](#ref-css-cascade-5)]: the page's look wins
389
+ over any of the widget's rules, whatever their specificity, and a widget's rule marked `!important` wins over the page's
390
+ look. A widget repairs what the page's look misses with such a rule under `html.uwa-neutral`, sparingly; one that must
391
+ keep its colors (a game's board) draws them in a `canvas` or an image, or declares `looks` `own`.
392
+
393
+ ### 4.8 Scripts
394
+
395
+ A `script` element without a `type` attribute, or whose `type` is `text/javascript`, `application/javascript` or
396
+ `module`, is **widget code**, except the runtime script (4.3) and UWA's platform script, which are **platform
397
+ scripts**. Other `script` elements are data, not run (RWA's templates). Widget code:
398
+
399
+ - **MUST NOT** use `localStorage`, `sessionStorage`, IndexedDB, or cookies: a framed widget has an opaque origin and no
400
+ storage of its own (section 7.8 gives the alternatives);
401
+ - **SHOULD** use `widget.body` and `widget.createElement` rather than `document`, since on its own page the `document` also holds the host's title bar and menu;
402
+ - **SHOULD** keep its functions in one object of its own name, and start from a `load` listener (7.6).
403
+
404
+ A `script` element with a `src` attribute in the head loads a library before the widget code runs; a URL relative to
405
+ the file resolves against it.
406
+
407
+ ### 4.9 Initial content
408
+
409
+ The body's content, the settings form and scripts excluded, is the widget's content until its code draws: a
410
+ placeholder, or a skeleton its code fills.
411
+
412
+ A widget **SHOULD** write its markup in the file, as a skeleton its code fills and updates in place (7.3.1), rather
413
+ than build it in script: a skeleton shows at once, before any code runs and again at every rebuild of the widget; its
414
+ structure, roles and names read as HTML, to its author and to tools; and an update that changes text and attributes
415
+ keeps the elements, and the keyboard focus on them.
416
+
417
+ ## 5. The settings form
418
+
419
+ ### 5.1 The `preferences` form
420
+
421
+ A widget's settings are declared by the first `form` element in its body whose `id` is `preferences`: its **settings
422
+ form**. A widget without settings has none. The settings form:
423
+
424
+ - **MUST** have the `hidden` attribute;
425
+ - **MUST** be static markup: a host reads it without running the widget, and widget code **MUST NOT** create or change
426
+ it;
427
+ - **MUST NOT** contain two controls with the same `name`.
428
+
429
+ ### 5.2 Controls
430
+
431
+ Each `select`, `textarea` and `input` element with a non-empty `name` in the settings form declares one setting, except
432
+ an `input` whose `type` is `submit`, `button`, `reset` or `image`, which is a button, not a setting. Its
433
+ **type** and **default value** are:
434
+
435
+ | Control | Type | Default value |
436
+ |---|---|---|
437
+ | `select` | `list`, its options the `option` elements' `value` (else text) and text | the `value` of the first `option` with `selected`, else of the first `option` |
438
+ | `input type="checkbox"` | `boolean` | `"true"` if `checked`, else `"false"` |
439
+ | `input type="range"` | `range`, with `min`, `max`, `step` | `value` |
440
+ | `input type="number"` | `number`, with `min`, `max`, `step` | `value` |
441
+ | `input type="url"` | `url` | `value` |
442
+ | `input type="password"` | `password` | `value` |
443
+ | `input type="hidden"` | `hidden` | `value` |
444
+ | `textarea` | `text` | its text content |
445
+ | any other `input` | `text` | `value` |
446
+
447
+ Values are read from the controls' attributes as written in the file (not their current state); a missing `value`
448
+ attribute is the empty string.
449
+
450
+ The setting's **label** is the text content of the `label` element containing the control, without the text of the
451
+ controls inside it; else that of the `label` whose `for` is the control's `id`; else its `aria-label`; else its name.
452
+ Labels **SHOULD** be short and in English.
453
+
454
+ ### 5.3 Attributes
455
+
456
+ | Attribute | On | Meaning |
457
+ |---|---|---|
458
+ | `data-hint` | any control | A text completing the label, which the host shows on request beside it |
459
+ | `data-when` | any control | A **condition**, `name=value`, `name=a\|b` or `name!=value`: the setting is shown only while it holds. A hidden setting keeps its value. An unreadable condition is ignored |
460
+ | `data-commit="ok"` | a `text` control | Its value applies only when confirmed (section 6.5) |
461
+ | `data-share` | a `hidden` control | A shared link may carry its value |
462
+ | `data-load` | a `hidden` control with `data-share` | A label, at most 40 characters: a person who already has the widget is offered a button with it, loading the shared value into their copy |
463
+ | `maxlength` | a `hidden` control with `data-share` | The longest value a shared link may carry for it, line breaks and tabs included (a whole text); a host **MAY** cap it (Startside: 16,000). Without it, a short value with no line breaks |
464
+ | `data-file` | a `hidden` control | File extensions, space-separated (`.cook`): a file of one of them, opened in the host (dropped on the page, chosen), makes this widget with the file's text as this setting's value; a host that exports a widget as files **SHOULD** write this setting's value as a file of that extension rather than among the settings. *At risk* (Appendix C) |
465
+ | `data-feed` | an `option` | The feed of that choice (section 6.4); `none`: the choice has no feed |
466
+
467
+ A `button` or `input` with `type="submit"` in the settings form asks the host for a button confirming the settings,
468
+ labelled with its text (*OK* if empty).
469
+
470
+ `data-load` **SHOULD** be used only for what a widget plays once (a board, a set), never for what it is (a feed) or what
471
+ it keeps (a list of tasks).
472
+
473
+ ## 6. Processing model
474
+
475
+ ### 6.1 Widget records
476
+
477
+ A host keeps, for each widget, a **widget record**, a struct with:
478
+
479
+ - **file**: the widget file's URL; **key**; **trusted**, a boolean;
480
+ - **title**, **metadata** (a map), **settings** (a list of setting declarations);
481
+ - **values**: a map from setting names to strings;
482
+ - **memory**, **stored data**, **kept content** and **read keys** (sections 7.8 to 7.10);
483
+ - **environment**: `framed` or `standalone`.
484
+
485
+ ### 6.2 Reading a widget file
486
+
487
+ To **read a widget file** at a URL *url*, a host runs these steps:
488
+
489
+ 1. Fetch *url*. If this fails, report that the widget file can't be found, and stop.
490
+ 2. If *url*'s path ends in `.html`, parse the response body as HTML; otherwise parse it as XML, and if that fails, as
491
+ HTML (section 11).
492
+ 3. If the document is the host's own page, report that it isn't a widget file, and stop.
493
+ 4. Let *title* be the text of the first `title` element, trimmed; if empty, a default name of the host's.
494
+ 5. Let *metadata* be the map of every `meta` element's `name` to its `content`, in document order, a later element of the
495
+ same name replacing an earlier one. The host acts only on the names of 4.5 whose value has the syntax 4.5 gives;
496
+ `widget.metas` exposes the whole map.
497
+ 6. Let *settings* be the settings of a UWA `widget:preferences` element if there is one (section 11), followed by the
498
+ result of **extracting the settings** (6.3) of the document; a name declared in both is the first one's.
499
+ 7. Collect the widget code, the styles and the stylesheet links of the whole document, in document order. Remove the
500
+ settings form, `widget:preferences`, `style`, `link`, `meta`, `title` and the widget code from the body: what remains is
501
+ the initial content.
502
+ 8. For each `script` element that is neither widget code nor a platform script (data for a format built on SWA, such
503
+ as RWA's templates), record the file's name and the line its content starts on, for that format's error reports.
504
+ Errors in widget code are reported at the locations the browser gives (7.15).
505
+ 9. Return *title*, *metadata*, *settings*, the code, the styles and the initial content.
506
+
507
+ ### 6.3 Extracting the settings
508
+
509
+ To **extract the settings** of a document, run these steps:
510
+
511
+ 1. Let *form* be the document's settings form. If there is none, return an empty list.
512
+ 2. Let *settings* be an empty list.
513
+ 3. For each control of *form* that declares a setting (5.2), in tree order, append a
514
+ declaration: its name, type, label and default value (section 5.2); for `list`, its options; for `range` and
515
+ `number`, its `min`, `max` and `step` as numbers; its hint, condition, `commit` flag, `shareable` flag and load
516
+ label (section 5.3), the load label truncated to 40 characters.
517
+ 4. Return *settings*.
518
+
519
+ The value of a setting is the widget's stored value for its name, or else its default value.
520
+
521
+ ### 6.4 Resolving the declared feed
522
+
523
+ A widget **declares its feed** by a `feed` meta, or by `data-feed` on an option of a list setting. To **resolve the
524
+ declared feed** of a widget, run these steps:
525
+
526
+ 1. For each list setting, if its current value's `option` has `data-feed`: if it is `none`, return null; otherwise let
527
+ *url* be that address and go to step 4.
528
+ 2. Let *template* be the `feed` meta's content. If there is none, return null.
529
+ 3. Let *url* be *template* with each `{name}` replaced by the value of the setting *name*: as written for a list
530
+ setting, else URL-encoded, unless the placeholder is the whole template, in which case the value as written.
531
+ 4. Parse *url*. If this fails, or its scheme is neither `http` nor `https`, return null.
532
+ 5. Return *url*.
533
+
534
+ A host **MAY** fetch a widget's declared feed while the widget isn't drawn, to show what's new or unread.
535
+
536
+ ### 6.5 Applying a setting
537
+
538
+ When the person changes a setting, the host applies it:
539
+
540
+ - a `list`, `boolean` or `range` setting at once, grouping changes made within half a second into one;
541
+ - a `text` setting after a pause in typing, or when the settings are confirmed;
542
+ - a `url`, `number` or `data-commit` setting only when confirmed, by the person (Enter, leaving the field, a
543
+ confirming button) or by closing the settings; a `number` outside its range is never applied.
544
+
545
+ If `livePreferences` is `false`, every change waits for the settings to close; if `instant`, changes apply at once,
546
+ ungrouped. Applying settings stores the values, then **refreshes** the widget (6.6).
547
+
548
+ A password setting's value **MUST NOT** be given to a framed widget, nor carried by a link.
549
+
550
+ ### 6.6 Starting and refreshing
551
+
552
+ To **start** a widget, the host runs these steps:
553
+
554
+ 1. Build its environment (section 10) and put its initial content in `widget.body`.
555
+ 2. Run the libraries, then the widget code, in document order.
556
+ 3. **Fire a widget event** (7.6.2) named `load`, and track it as a load (below).
557
+ 4. Fire a widget event named `loadcomplete`.
558
+
559
+ To **refresh** a widget, the host runs these steps:
560
+
561
+ 1. If the widget **listens for** `refresh` (7.6.2), fire a widget event named `refresh`; otherwise fire one named
562
+ `load`.
563
+ 2. Track it as a load.
564
+
565
+ A load is **in progress** from the event's dispatch until the widget calls `setBody`, an error is reported, or every
566
+ promise the event's listeners gave to `waitUntil` has settled, and at most
567
+ 20 seconds; and while the widget has requests in flight. The host **SHOULD** show it in progress.
568
+
569
+ A host refreshes a widget:
570
+
571
+ - when the person asks;
572
+ - when settings are applied (6.5), unless a `settingschange` listener canceled it (7.5);
573
+ - when the widget asks, with `refresh()` (7.5);
574
+ - every `autoRefresh` minutes (or `setAutoRefresh`), counted from the end of the previous load or refresh; a refresh due
575
+ while the page is hidden waits for it to be shown.
576
+
577
+ A widget is **rebuilt**, started anew, when its tab is shown again. What it must keep across that lives in its values,
578
+ memory or stored data (section 7.8), never on its frame's `window`. A host **SHOULD NOT** show a rebuilt widget
579
+ loading when it has content kept to draw.
580
+
581
+ ### 6.7 Activation-gated operations
582
+
583
+ An operation said to be **activation-gated** is, for a framed widget, honoured only if, when the host receives the
584
+ request, either:
585
+
586
+ - the host's own window has transient activation [[HTML](#ref-html)], the widget's frame is the host document's
587
+ focused area, the focus was **given** to the frame rather than taken by it, and the host has seen no click or key
588
+ press of its own since the frame got the focus; or
589
+ - the request answers a user action in the host's own interface meant for that widget (the audio bar's play button).
590
+
591
+ Activation alone isn't enough: a click anywhere on the page, in the host's own controls or in another widget, gives it
592
+ too. Nor is the focus: a frame can focus itself from its own script. The focus counts as given when, as the frame got
593
+ it, the pointer (a mouse or a pen) was over the frame, or a Tab key on the host's page had just moved it, or the host
594
+ had seen no click or key press of its own for longer than an activation lasts (5 seconds). A focus taken counts once
595
+ the host's last click or key press is older than an activation lasts: an activation then is the frame's own.
596
+
597
+ The host checks its own window and document: it never relies on what the frame says of its activation. Otherwise the
598
+ host **MUST** ignore the request.
599
+
600
+ A click or key press of the host's own is one that gives activation [[HTML](#ref-html)]: a mouse's or a pen's as it
601
+ presses, a finger's as it lifts; a scroll of the host's page, which gives none, isn't one. A finger's tap holds a frame
602
+ back for 1 second instead of an activation's 5: a browser on a touch screen may report touches nobody made.
603
+
604
+ > **Note:** A tap in a widget within 5 seconds of a click on the host's page, or 1 second of a tap on it, is ignored: a
605
+ > host can't tell it from a frame taking the focus.
606
+
607
+ ### 6.8 The keyboard coming into a widget
608
+
609
+ A host that lets people go from widget to widget with the keyboard **MAY** move the focus into a widget's document
610
+ on a key of its own. When it does, the focus goes to:
611
+
612
+ 1. the first element of the widget's body that has the `autofocus` attribute [[HTML](#ref-html)], if it can take the
613
+ focus;
614
+ 2. else the first element inside that one that can (a grid whose cells take the focus in turn);
615
+ 3. else the first element of the widget's body that can;
616
+ 4. else the document itself.
617
+
618
+ An element can take the focus here when it is shown, not disabled, and in the sequential focus order. A host
619
+ **SHOULD NOT** let `autofocus` take the focus as a widget loads among others; on a widget's own page the browser's
620
+ own behaviour applies.
621
+
622
+ The focus given this way is given by the host (6.7): what the person then does in the widget counts as theirs.
623
+
624
+ A host **MAY** take the focus back, to its own control for the widget, on an `Escape` `keydown` that reaches the
625
+ widget's `window` uncancelled, with no modifier, while the widget's document has the focus. A widget that uses
626
+ Escape itself (to close a panel of its own) calls `preventDefault()` on it.
627
+
628
+ A host **MUST NOT** act on these keys for a widget that took the focus by itself (6.7): only for one that was given it,
629
+ by the person or by the host. It decides once the event's dispatch is over, whichever listener cancels it.
630
+
631
+ A host **MAY** give a widget that has the focus the directions of a game controller it reads itself (its D-pad) as
632
+ arrow keys: a `keydown` event as a direction is pressed and a `keyup` as it is let go, with `key` and `code` set to
633
+ `ArrowUp`, `ArrowDown`, `ArrowLeft` or `ArrowRight`, dispatched on the widget's focused element (its `body` with none);
634
+ a back button of its choice as `Escape`, and an action button of the controller as `Enter`, after whose uncancelled `keydown` the host activates the focused
635
+ element when it is a button or a link (its `click()`).
636
+ These events are not trusted (`isTrusted` is false) and trigger no default action of the browser's: a widget that
637
+ handles the arrow keys in its own listeners needs nothing more to be played with a controller.
638
+
639
+ When a host gives the focus back to a widget after a window of the host's that the widget opened (7's `openPhoto`,
640
+ `openItems` and the like) closes, the focus **SHOULD** return to the element of the widget that had it; if that element
641
+ is gone, to where the keyboard comes in (the steps above).
642
+
643
+ A host **MAY** likewise act on an arrow key's `keydown` that reaches the widget's `window` uncancelled, with no
644
+ modifier (moving to the next widget that way), unless the event's target is, or is inside, an element where the
645
+ browser uses arrows itself: a text field, a `select`, an editable element, a media element, an element with the role
646
+ `slider`, `spinbutton`, `listbox`, `combobox`, `menu`, `menubar`, `tablist`, `radiogroup`, `tree`, `grid` or
647
+ `application`, or an element that can still scroll that way. A widget that uses the arrows itself (a game's moves)
648
+ calls `preventDefault()` on them.
649
+
650
+ > **Note:** A game marks its board: `<div class="board" tabindex="0" autofocus>`. A widget whose first control is
651
+ > already the one to use needs nothing.
652
+
653
+ ## 7. The `Widget` interface
654
+
655
+ ### 7.1 The `widget` object
656
+
657
+ A host exposes one `Widget` object per widget, as the global `widget` in the widget's realm.
658
+
659
+ ```webidl
660
+ [Exposed=Window]
661
+ interface Widget : EventTarget {
662
+ // 7.2 Identity and environment
663
+ readonly attribute DOMString id;
664
+ readonly attribute DOMString title;
665
+ readonly attribute USVString uwaUrl;
666
+ readonly attribute DOMString lang;
667
+ readonly attribute DOMString locale;
668
+ readonly attribute object metas;
669
+ readonly attribute FrozenArray<object> preferences; // WidgetSettings
670
+ readonly attribute object environment; // a WidgetEnvironment
671
+ readonly attribute HTMLElement? body;
672
+ undefined log(any... data);
673
+
674
+ // 7.3 Content and title
675
+ undefined setBody((DOMString or Node) content);
676
+ undefined addBody((DOMString or Node) content);
677
+ HTMLElement createElement(DOMString tagName, optional object attributes);
678
+ undefined setTitle(DOMString title);
679
+ DOMString getTitle();
680
+ undefined setStyle(DOMString css);
681
+
682
+ // 7.4 Appearance
683
+ undefined setIcon(USVString? url);
684
+ undefined setChromeColor(DOMString? color, optional ChromeColorOptions options = {});
685
+
686
+ // 7.5 Settings
687
+ readonly attribute WidgetSettings settings;
688
+ WidgetSetting? getPreference(DOMString name);
689
+ undefined setMaxValue(DOMString name, long max);
690
+ undefined openPreferences();
691
+ HTMLSpanElement withPreferencesLink(DOMString text);
692
+
693
+ // 7.6 Events and lifecycle (addEventListener and the rest: EventTarget). No callbacks: UWA's are UWA files' (11.3).
694
+ undefined refresh();
695
+ undefined setAutoRefresh(unsigned long minutes);
696
+ undefined setPeriodical(DOMString name, Function callback, unsigned long delay, optional boolean now = false);
697
+ undefined clearPeriodical(DOMString name);
698
+
699
+ // 7.7 Lists and grips
700
+ undefined countGrip(HTMLElement box, DOMString itemSelector, optional CountGripOptions options = {});
701
+ undefined heightGrip(HTMLElement box, HTMLElement scroller, optional HeightGripOptions options = {});
702
+
703
+ // 7.8 Memory and stored data
704
+ readonly attribute WidgetStorage storage;
705
+
706
+ // 8 Data access
707
+ Promise<Response> fetch(RequestInfo input, optional RequestInit init = {});
708
+ Promise<ContentFeed> fetchFeed(USVString url, optional FetchFeedOptions options = {});
709
+
710
+ // 7.10 Read state and counts
711
+ undefined readItems(Element box, DOMString itemSelector, optional ReadItemsOptions options = {});
712
+ boolean isRead(DOMString key);
713
+ undefined setRead(sequence<DOMString> keys, boolean read);
714
+ undefined setUnreadCount(long count);
715
+ undefined setSearchResultCount(long count);
716
+
717
+ // 7.11 The reader
718
+ undefined openURL(USVString url);
719
+ undefined openItems(sequence<ReaderItem> items, unsigned long index, optional OpenItemsOptions options = {});
720
+
721
+ // 7.12 Sound, video, pictures
722
+ readonly attribute object audioState; // an AudioState
723
+ any playAudio(PlayAudioOptions options);
724
+ any pauseAudio();
725
+ any seekAudio(double seconds);
726
+ undefined audioStarted(Function stop, optional AudioControls controls = {});
727
+ undefined audioStopped();
728
+ undefined audioInfo(optional AudioInfo info = {});
729
+ readonly attribute object? videoState; // a VideoState
730
+ any playVideo(VideoSpec video);
731
+ any openPhoto(PhotoSpec photo);
732
+
733
+ // 7.13 The page
734
+ USVString? shareUrl();
735
+ any share(optional ShareData data = {});
736
+ any addWidget(AddWidgetSpec spec);
737
+ boolean dragWidget(Element element, (AddWidgetSpec or DragWidgetCallback) spec);
738
+ readonly attribute boolean canFullSize;
739
+ readonly attribute boolean fullSize;
740
+ undefined openFull();
741
+ undefined closeFull();
742
+ readonly attribute boolean fullScreen;
743
+ undefined setFullScreen(boolean on);
744
+ undefined setActionStates(record<DOMString, WidgetActionState> states);
745
+ Promise<undefined> saveFile(WidgetSaveFile file, optional WidgetSaveOptions options = {});
746
+ };
747
+ ```
748
+
749
+ The members returning `any` return what the host's operation returns (in Startside, a promise for some); widgets
750
+ **MUST NOT** rely on a particular value. The attributes typed `object` hold an object with the members of the
751
+ dictionary their comment names; the host replaces the object when the state changes.
752
+
753
+ The `readonly` attributes have no setter: assigning one changes nothing, and throws a `TypeError` in strict mode code,
754
+ as for a Web IDL attribute. What `metas`, `preferences` (each setting with it), `environment`, `settings`, `storage` and
755
+ `audioState` give is frozen; a widget changes its settings through `settings.set` (7.5), never by writing to
756
+ `preferences`. The `widget` object has the members of this interface and no others a widget can rely on: a host
757
+ **MUST NOT** expose UWA's members to an SWA widget (section 11), and names of its own start with `__` (reserved:
758
+ widgets **MUST NOT** use them).
759
+
760
+ ### 7.2 Identity and environment
761
+
762
+ ```webidl
763
+ dictionary WidgetEnvironment {
764
+ DOMString name; // the host's name
765
+ boolean standalone;
766
+ boolean inline; // false: an SWA widget never runs inline (10.2); kept for UWA files
767
+ DOMString style; // the page's style, or "" standalone
768
+ };
769
+
770
+ dictionary WidgetSetting {
771
+ required DOMString name;
772
+ required DOMString type; // "text", "password", "hidden", "boolean", "list", "range", "number", "url"
773
+ DOMString label;
774
+ DOMString defaultValue;
775
+ sequence<WidgetSettingOption> options;
776
+ double min;
777
+ double max;
778
+ double step;
779
+ DOMString hint;
780
+ DOMString when;
781
+ DOMString commit; // "ok"
782
+ boolean shareable;
783
+ DOMString load;
784
+ };
785
+
786
+ dictionary WidgetSettingOption {
787
+ required DOMString value;
788
+ DOMString label;
789
+ USVString feed;
790
+ };
791
+ ```
792
+
793
+ - `id`: the widget's identifier, unique on the page. `title`: the title it's shown under, the person's name for it if
794
+ they renamed it, else its own (7.3). `uwaUrl`: its file's URL. `lang`,
795
+ `locale`: the person's language (`en_US`) and region (`us`), in UWA's form, kept (11): a language tag for `Intl` is
796
+ `widget.lang.replace('_', '-')`. `metas`: its metadata. `preferences`: its setting
797
+ declarations.
798
+ - `environment.style` names the page's style (in Startside: `classic`, `early`, `coriander`, `ginger`, `mac`, `aw`,
799
+ `neo`, `modern`). A framed widget is rebuilt when it changes.
800
+ - `log(…)` writes its arguments to the console when `debugMode` is `true`.
801
+
802
+ ### 7.3 Content and title
803
+
804
+ - `setBody(content)` replaces the content of `body` with *content*, then fires a widget event named `updatebody`
805
+ (7.6.2): a node is appended once `body` is emptied; a string is parsed as HTML into it. `addBody(content)` appends
806
+ *content* (a string parsed as HTML in a `div` of its own), then fires the same event. `body` is null until the widget
807
+ starts.
808
+
809
+ `setBody` replaces everything, the elements the person was using with them (their focus, a field being typed in, a
810
+ list's scroll): it is for content made whole at each draw; content the person interacts with is drawn in place
811
+ (7.3.1). A string given to `setBody` or `addBody` is parsed as markup, and markup runs code (an `onerror`
812
+ attribute): a widget **SHOULD NOT** give them a string holding anything but its own fixed
813
+ markup, never text it fetched or a person typed, joined in (`'<p>' + title + '</p>'`) or interpolated; such text
814
+ goes into a node by `textContent` or an attribute, the node to `setBody`. The same holds for `innerHTML` and
815
+ `insertAdjacentHTML`. Escaping before joining is no substitute: one value left out, or escaped for the wrong place
816
+ (an attribute, an address), and the text is markup.
817
+ - `createElement(tagName, attributes)` returns a new `HTMLElement` (section 9). In *attributes*,
818
+ `class` sets its class, `styles` its style, `events` its listeners, and any other key an attribute.
819
+ - `setTitle(title)` sets the title shown in its title bar. *title* may contain `a` elements with `http` or `https`
820
+ addresses, shown as links; any other markup is reduced to its text. It is kept as the widget's title, shown
821
+ unless the person renamed the widget. `widget.title` is the title shown: the person's name for the widget, as text,
822
+ else the title as set, its links' markup included; `getTitle()` returns its text. A title is like a setting: when
823
+ the person renames the widget, or empties the name to give it its own back, the host fires `settingschange` with
824
+ the name `title` (7.5), then refreshes it unless the event is canceled; a widget showing its name (lettered on a
825
+ toy, in a heading) redraws it there.
826
+ - `setStyle(css)` adds a style sheet for the widget.
827
+
828
+ #### 7.3.1 Drawing in place
829
+
830
+ *This section is non-normative.* The practices that go with a skeleton (4.9):
831
+
832
+ - **Every state in the skeleton.** The content, and what shows while loading, when there is nothing, and after a
833
+ failure, are elements of the skeleton, shown or hidden with the `hidden` attribute. A style giving one of them a
834
+ `display` overrides `hidden`: add `.x[hidden] { display: none; }`.
835
+ - **Loading at its size.** What shows while loading has the shape and size of what is coming: a skeleton of its
836
+ rows, its picture's box at its proportions, its title's line. A widget that is a line of "Loading…" until its
837
+ content arrives jumps as it draws, and moves the page around it; one drawn from what it kept (7.8, 7.9) shows no
838
+ placeholder at all. On a first load the host knows no height to hold for it: the widget's own placeholder is all
839
+ there is.
840
+ - **Repeated items from a `template`.** A list's row, a grid's cell: a `template` element in the skeleton, its content
841
+ cloned for each item (`template.content.firstElementChild.cloneNode(true)`).
842
+ - **Parts found under `widget.body`.** In the `load` listener, `widget.body.querySelector('.count')`: on its own page
843
+ the document also holds the host's title bar and menu. The widget's document is its own (10.2), so an `id` is fine,
844
+ for `<label for>` and ARIA's references (`aria-describedby`, `aria-labelledby`, `aria-controls`) as for the rest.
845
+ - **Wired once.** Listeners added on the first `load`, on a container rather than on each row (`event.target.closest('.row')`), so
846
+ rows can be redrawn without wiring them again; a widget with a `refresh` listener has its `load` dispatched once
847
+ (6.6).
848
+ - **Filled with text, never markup.** `textContent`, attributes and `hidden`, on the skeleton's elements or a clone of
849
+ its `template`; `append('Posted by ', name)` adds text, never markup. Fetched text is never parsed as HTML (7.3).
850
+ - **HTML that is content.** A feed item's `content_html` is shown by the reader (`openItems`, 7.11), which is made for
851
+ a site's markup, or set with the browser's sanitizing `Element.setHTML()` [[HTML](#ref-html)]; never by `innerHTML`
852
+ or `setBody`.
853
+ - **Updated, not replaced.** A change sets the text, attributes and `hidden` of the elements there; a list replaces
854
+ only its rows. The keyboard focus stays on the element the person used; a widget that must replace that element
855
+ moves the focus to its replacement.
856
+ - **No `setBody`.** It replaces the skeleton. A load that draws in place gives `waitUntil` the promise of its work,
857
+ or none if it draws at once (6.6); the host follows the content's height without being told.
858
+ - **Back from what's kept.** After a rebuild (a tab switch), the skeleton is filled from what the widget kept
859
+ (`fetchFeed`'s kept copy, a setting, `storage.memory`) before anything is asked again (7.8, 7.9).
860
+ - **Changes announced.** A result, an error, new items: the text of a live region of the skeleton (section 14).
861
+ - **Keys heard on the widget's own element.** A `keydown` listener goes on the element that has the focus (the board,
862
+ the list), never on `document` or `window`: on its own page the host's menu shares the document, so a listener there plays the
863
+ game as the person types a title or a setting.
864
+ - **Nothing runs at rest.** A widget nobody uses does no work: an animation that draws the eye (a hint, a new item)
865
+ plays a few times and stops (`animation-iteration-count: 3`), one that runs on is for something under way (a
866
+ download); a timer is for what changes on screen (a clock, a countdown) and stops while `document.hidden`. Each
867
+ frame of an endless animation is drawn by the page, on a laptop's battery, for every widget showing it.
868
+ - **One Tab stop for a composite control.** A game board, a grid, a calendar, a list moved through with the keys is one
869
+ stop in the Tab order: the container focusable (`tabindex="0"`), its cells out of the order (`tabindex="-1"`), the
870
+ arrow keys moving inside it, as WAI-ARIA's Authoring Practices describe for each pattern [[ARIA-APG](#ref-aria-apg)]
871
+ (a grid's roving focus, a listbox's active option); a visible focus on whatever has it; a click inside leaves the
872
+ focus there. Not a Tab stop per cell, and no control disabled to keep the focus from it: a disabled control leaves
873
+ the order, and the keyboard loses its place.
874
+
875
+ `setBody` stays for content made whole at each draw.
876
+
877
+ #### 7.3.2 Size
878
+
879
+ **The width is the host's; the height is the widget's.** A host gives a widget its width (a dashboard's column, the
880
+ standalone page's box, which the person may resize) and fires `resize` when it changes (7.6.1, UWA's `onResize`); a
881
+ widget whose layout follows its width (a canvas, a board) watches its own element with the browser's `ResizeObserver`,
882
+ which also sees it maximized and a font arriving, rather than both; the widget's height is
883
+ its content's, and the host sizes the widget to it, framed by measuring the frame's document. A widget **MUST NOT**
884
+ size itself to the window or the viewport (`100vh`, `height: 100%` of the root): framed, the viewport is its frame,
885
+ whose height follows the widget's, so content sized from it grows without end or collapses.
886
+
887
+ - **Padding.** The host pads the widget's body (6 pixels by 8 in Startside: `.moduleContent`), framed and on its own
888
+ page alike; the widget's own wrapper adds what it wants inside, never a margin outside the body.
889
+ - **Edge to edge.** A widget that is a device (a toy, a console) draws to its edges by asking for the whole viewport as
890
+ a page does on a phone: `viewport-fit=cover` in its viewport meta (`<meta name="viewport" content="width=device-width,
891
+ initial-scale=1, viewport-fit=cover">`). The host then puts no padding round its body, from the first paint, framed
892
+ and on its own page; its frame's corners and border still clip it. What it must keep clear it keeps with
893
+ `env(safe-area-inset-top)` and the other three, as on the web: 0 in a dashboard's frame (the title bar is outside
894
+ it), a phone's notch and rounded corners on its own page. Without it, the host's padding.
895
+ - **Narrow and wide.** A widget lays out for any width from about 300 pixels (a phone's column; Startside's columns are
896
+ 300 at least) to 1600 (maximized): content that needs room wraps, scales
897
+ (`clamp()`, `aspect-ratio`, `max-width`) or scrolls inside its own box (a wide table); the page around it never
898
+ scrolls sideways because of it.
899
+ - **Maximized** (`maximize`, 4.5 and 7.13; `fullsize`'s `detail` true, `html.uwa-full-size` on the root): with
900
+ `column`, a box `maximizeWidth` wide, its height still its content's; with `fill`, the whole window, the widget
901
+ sizing itself to its height (a board filling it); with `fit`, as wide as lets content whose height grows with its
902
+ width fit the window's height (a console's screen).
903
+ - **On its own page in a fixed-height frame** (10.3): the page scrolls; the widget still lays out for its width.
904
+
905
+ A widget never asks for more height: it takes what its content needs ([Issue 30](#issue-30)).
906
+
907
+ ### 7.4 Appearance
908
+
909
+ ```webidl
910
+ dictionary ChromeColorOptions {
911
+ DOMString? background = null;
912
+ };
913
+ ```
914
+
915
+ - `setChromeColor(color, options)` sets the widget's title bar color, and its body's (`background`), while it runs,
916
+ over its `chromeColor` and `background` metadata; the host keeps them, so a reload paints them first; `null` restores
917
+ the metadata. A color the person chose wins over it.
918
+ - `setIcon(url)` sets its title bar's icon while it runs: an image of the host's widget directory (SVG, PNG, ICO or
919
+ WebP), relative to the file; the host keeps it. `null` or any other URL restores the file's icon.
920
+
921
+ ### 7.5 Settings
922
+
923
+ ```webidl
924
+ [Exposed=Window]
925
+ interface WidgetSettings {
926
+ any get(DOMString name);
927
+ undefined set(DOMString name, any value);
928
+ undefined reset(DOMString name);
929
+ };
930
+ ```
931
+
932
+ - `settings.get(name)` returns the setting's value, typed by the control that declares it (5.2): a checkbox's is a
933
+ boolean; a `range`'s or a `number` field's a number, or null when it's empty; any other's (a list, text, an address,
934
+ a password, a hidden field) a string. A name the form doesn't declare gives `undefined`.
935
+ - `settings.set(name, value)` stores *value* as the setting's value, without refreshing the widget (a game's state, a
936
+ choice made in the widget itself): a boolean for a checkbox, a finite number for a `range` or `number` field, else
937
+ anything, converted to a string (`null` and `undefined` to `""`). A value of the wrong type, or a name the form doesn't declare, throws a
938
+ `TypeError`. `settings.reset(name)` restores the declared default.
939
+ - **`title`**, unless the form declares a setting of that name, is the widget's title, like a setting (7.3):
940
+ `settings.get('title')` returns the title shown, as text; `settings.set('title', name)` makes *name* the person's
941
+ name for the widget, as the host's own rename does, for a widget that lets the person rename it in itself (a field
942
+ over the name it shows), right after they acted in it (6.7); `settings.reset('title')`, an empty name or the
943
+ widget's own give it its own title back. The host saves it; no event fires and no refresh follows (the widget made
944
+ the change). A host **MAY** limit a setting's length (the
945
+ Appendix gives Startside's); a value over it isn't kept: `settings.get` returns it until the widget reloads, and the
946
+ host **SHOULD** say so in the widget's console. A widget keeping something that grows (a drawing, a long game) keeps it
947
+ under the limit itself.
948
+ - When the person applies settings (6.5), the host fires `settingschange` (7.6), its `detail.names` the settings whose
949
+ values changed (`title` when the person renamed the widget, 7.3); canceling it skips the refresh that follows, for a
950
+ widget that applies them in place. Nothing
951
+ changed (an OK with the same values): no event, the refresh as before.
952
+ - `refresh()` refreshes the widget as applying settings does (6.6): for a setting the widget changed with its own
953
+ control (a feed, a station chosen in it).
954
+ - `getPreference(name)` returns the setting's declaration, or null.
955
+ - `setMaxValue(name, max)` limits a `range` setting to *max* in the host's settings, never above its declared `max`
956
+ (a feed's length); the host keeps it.
957
+ - `openPreferences()` opens the widget's settings where the host keeps them. Activation-gated.
958
+ - `withPreferencesLink(text)` returns a `span` with *text*, in which each `[[part]]` is a link that opens the settings.
959
+
960
+ ### 7.6 Events and lifecycle
961
+
962
+ `Widget` is an `EventTarget` [[DOM](#ref-dom)]: a widget listens for the host's events with
963
+ `addEventListener`, with any number of listeners, the options `once`, `capture` and `signal`, and
964
+ `removeEventListener`. Events are the only way: an SWA widget has no callbacks to assign (`widget.onLoad`), and no
965
+ `setCallback` or `callback`; a host **MUST NOT** call a function an SWA widget assigns to such a name. UWA's callbacks
966
+ are UWA files' (11.3).
967
+
968
+ #### 7.6.1 Event types
969
+
970
+ ```webidl
971
+ [Exposed=Window]
972
+ interface WidgetEvent : Event {
973
+ constructor(DOMString type, optional WidgetEventInit eventInitDict = {});
974
+ readonly attribute any detail;
975
+ readonly attribute AbortSignal? signal;
976
+ undefined waitUntil(Promise<any> promise);
977
+ };
978
+
979
+ dictionary WidgetEventInit : EventInit {
980
+ any detail = null;
981
+ };
982
+ ```
983
+
984
+ Every event the host fires at a widget is a `WidgetEvent`. None bubbles. `detail` carries the event's data, as the table
985
+ says. `waitUntil(promise)` extends a load (`load`, `refresh`) until *promise* settles; called on another event, or once the
986
+ event's dispatch has returned, it throws an `"InvalidStateError"` `DOMException`. A load's event (`load`, `refresh`)
987
+ carries a `signal` [[DOM](#ref-dom)], aborted when the next load starts or the widget goes: the widget passes it to its
988
+ requests (`fetch(url, { signal })`) so a superseded load stops, and stops drawing when it's aborted. Other events'
989
+ `signal` is null. A rejected promise is reported (7.6.3)
990
+ and ends its part of the load as settling does.
991
+
992
+ | Type | Fired | `detail` | Cancelable | UWA's callback (11.3) |
993
+ |---|---|---|---|---|
994
+ | `load` | as the widget starts, is rebuilt, or refreshes without a `refresh` listener (6.6) | null | no | `onLoad` |
995
+ | `loadcomplete` | after `load` | null | no | `onLoadComplete` |
996
+ | `refresh` | on a refresh (6.6) | null | no | `onRefresh` |
997
+ | `resize` | its width changed | null | no | `onResize` |
998
+ | `updatebody` | after `setBody` or `addBody` | null | no | `onUpdateBody` |
999
+ | `updatepreferences` | its setting declarations changed | null | no | `onUpdatePreferences` |
1000
+ | `hideedit` | its settings closed | null | no | `onHideEdit` |
1001
+ | `readall` | the person activated its unread count, `readItems`' or `setUnreadCount`'s (7.10) | null | yes: canceling skips marking `readItems`' items read | `onReadAll` |
1002
+ | `audiostate` | `audioState` changed | the new `AudioState` | no | `onAudioState` |
1003
+ | `audioresume` | the person asked to resume after a reload | null | no | `onAudioResume` |
1004
+ | `videostate` | `videoState` changed | the new `VideoState`, or null | no | `onVideoState` |
1005
+ | `fullsize` | it was maximized or restored, its box at its new size | `fullSize`'s new value | no | `onFullSize` |
1006
+ | `fullscreen` | it went full screen or left it, after `fullsize` when both change | `fullScreen`'s new value | no | `onFullScreen` |
1007
+ | `settingschange` | the person applied settings that changed, or renamed the widget (7.3, 7.5) | `{ names }`: the settings changed, `title` for a rename | yes: canceling skips the refresh | none |
1008
+ | `action` | the person chose one of the widget's own actions in its options menu (7.13) | `{ id }`: the action's | no | none |
1009
+
1010
+ Event types are lowercase, as the platform's are. A host **MAY** fire other events; their types **MUST** be lowercase and
1011
+ **MUST NOT** begin with `on`. Such an event isn't cancelable, and has a null `detail` unless the host says otherwise.
1012
+
1013
+ #### 7.6.2 Firing a widget event
1014
+
1015
+ A widget **listens for** an event type if, at the moment the host decides (in the widget's own realm, immediately before
1016
+ the event would be fired), it has an event listener for it on `widget`.
1017
+
1018
+ To **fire a widget event** named *type* with *detail*, the host runs these steps:
1019
+
1020
+ 1. Let *event* be a new `WidgetEvent` whose `type` is *type*, `detail` is *detail*, `cancelable` as the table says, and
1021
+ `bubbles` false.
1022
+ 2. Dispatch *event* at `widget` [[DOM](#ref-dom)], with `widget` as each listener's `this`. An exception in a listener
1023
+ is reported (7.6.3), and the other listeners still run.
1024
+ 3. Return whether *event*'s canceled flag is unset.
1025
+
1026
+ Listeners run as DOM dispatch orders them: capture listeners at the target before the others, each group in the order
1027
+ added; `stopImmediatePropagation()` stops those that follow.
1028
+
1029
+ **Framed.** The host doesn't fire the events itself: it sends the frame a message naming what happened (a refresh, a
1030
+ resize, the unread count activated, a new audio state), checked as section 10.1 says, and the runtime in the frame runs
1031
+ the steps above in the widget's realm. So the frame decides whether the widget listens for `refresh` (6.6), and performs
1032
+ `readall`'s default action (7.10); it tells the host when a load ends, as section 6.6 defines its end.
1033
+
1034
+ #### 7.6.3 Lifecycle methods
1035
+
1036
+ - `setAutoRefresh(minutes)` sets the refresh interval, over the `autoRefresh` metadata. Automatic refreshes are for a
1037
+ widget that listens for `refresh` (6.6): one that doesn't has none, whatever its metadata says.
1038
+ - `setPeriodical(name, callback, delay, now)` calls *callback* every *delay* milliseconds, at once too if *now*, until
1039
+ `clearPeriodical(name)` or the widget goes.
1040
+
1041
+ An exception thrown by widget code while the host runs it or by a listener, and a promise given to
1042
+ `waitUntil` that rejects, **MUST** be reported in the widget's box; the rest of the page goes on.
1043
+
1044
+ <div class="example">
1045
+
1046
+ **Example 3.** Listeners, removed together by a signal:
1047
+
1048
+ ```js
1049
+ const stop = new AbortController();
1050
+ widget.addEventListener('load', () => MyWidget.draw());
1051
+ widget.addEventListener('refresh', (e) => e.waitUntil(MyWidget.fetchAndDraw(e.signal)), { signal: stop.signal });
1052
+ widget.addEventListener('fullsize', (e) => MyWidget.layout(e.detail));
1053
+ ```
1054
+
1055
+ </div>
1056
+
1057
+ ### 7.7 Lists and grips
1058
+
1059
+ ```webidl
1060
+ dictionary CountGripOptions {
1061
+ Function onStart; // adds the items not shown yet
1062
+ Function onDone; // (unsigned long count)
1063
+ unsigned long min = 1;
1064
+ DOMString setting; // the setting holding the count: a double-click restores its default
1065
+ };
1066
+
1067
+ dictionary HeightGripOptions {
1068
+ double height;
1069
+ unsigned long min;
1070
+ DOMString items; // a selector: the list's items
1071
+ Function onDone; // (double pixels)
1072
+ };
1073
+ ```
1074
+
1075
+ - `countGrip(box, itemSelector, options)` gives the widget a **corner grip**: dragging the widget's corner shows more or
1076
+ fewer of the items *itemSelector* matches in *box*. As the drag starts, `onStart()`; released, the host settles on whole
1077
+ items and calls `onDone(count)`, which keeps that count. A double-click on the grip calls `onStart()` then
1078
+ `onDone(default)`, *default* being the default value of `setting` (else of the widget's `count` or `limit` setting);
1079
+ maximized, it fits the window again instead.
1080
+ - `heightGrip(box, scroller, options)` gives the same grip to a list that keeps every item and scrolls in *scroller*: its
1081
+ height follows the drag, never taller than the list, then settles on whole items, never ending on a heading among
1082
+ them (a title with nothing under it: it ends on the item before), and calls `onDone(pixels)`. Maximized,
1083
+ the list takes the window's height instead.
1084
+
1085
+ Framed, the host follows the pointer once it leaves the frame and relays its moves. Either grip stays under the
1086
+ pointer: maximized in a centered window, which grows both ways, the height follows twice the pointer's move until the
1087
+ window is full, then the move itself.
1088
+
1089
+ ### 7.8 Memory and stored data
1090
+
1091
+ Where a widget keeps what, in short (the table below): a choice of the person, or a game in progress, is a setting;
1092
+ `memory` is a cache, which a host may drop; `local` lasts across reloads.
1093
+
1094
+ ```webidl
1095
+ [Exposed=Window]
1096
+ interface WidgetStorage {
1097
+ readonly attribute WidgetStorageArea memory;
1098
+ readonly attribute WidgetStorageArea local;
1099
+ };
1100
+
1101
+ [Exposed=Window]
1102
+ interface WidgetStorageArea {
1103
+ Promise<any> get(DOMString key);
1104
+ Promise<undefined> set(DOMString key, any value);
1105
+ Promise<undefined> delete(DOMString key);
1106
+ };
1107
+ ```
1108
+
1109
+ `widget.storage` holds what a widget keeps, in two **storage areas**, each a map of keys to JSON values:
1110
+
1111
+ - **`memory`**: the widget's own, across rebuilds (its tab shown again) and, unless the person turned it off, across
1112
+ reloads; for a cache, what the widget draws at once as it starts. A host **MAY** limit it (Startside: about 2 MB per
1113
+ widget) and refuse the keys it keeps its own data under (Startside: `content`, `uwa-feeds`, rejected with a
1114
+ `TypeError`).
1115
+ - **`local`**: the page's, across reloads, shared by every widget of the same file; for what outlasts a game (its
1116
+ scores). Framed, a widget reads the values as they were when it started, with its own writes since.
1117
+
1118
+ `get(key)` resolves with a copy of the key's value, or `undefined`; `set(key, value)` keeps a copy of *value*, which
1119
+ **MUST** be serializable as JSON (a value that isn't, `undefined` among them, rejects with a `TypeError`); `delete(key)`
1120
+ removes it. A value read is a copy: changing it changes nothing kept. What a widget kept is there as it starts, so its
1121
+ first `get` resolves without waiting on the host (the data is in the widget's realm before its scripts run): a widget **MAY** read in its `load` listener, or as its script
1122
+ starts, and draw what it kept without showing a load.
1123
+
1124
+ UWA's `remember`, `recall`, `setStored` and `getStored` are UWA files' (11.1): the same data, `memory` and `local`.
1125
+
1126
+ | To keep | Use |
1127
+ |---|---|
1128
+ | a choice of the person, or a game in progress | a setting (`settings.set`), hidden if not edited by hand |
1129
+ | data across rebuilds, a cache | `storage.memory` |
1130
+ | data across reloads, shared by copies of the file | `storage.local` |
1131
+ | a feed | nothing: `fetchFeed` keeps it (7.9) |
1132
+
1133
+ Saved data outlives the code that wrote it: widget code **MUST** read it defensively.
1134
+
1135
+ ### 7.9 Kept feeds
1136
+
1137
+ The host keeps the feeds `fetchFeed` (8.3) gives a widget, so that a widget rebuilt (its tab shown again, the page
1138
+ reloaded) draws at once from what it had: for a limited number of feeds per widget (Startside: 6), a feed not asked for in 30 days dropped,
1139
+ each stamped with when it was fetched. A kept feed less than 5 minutes old answers `fetchFeed` with no request; an
1140
+ older one answers it too, while the host asks for the feed behind it and, once the new copy is kept, refreshes the
1141
+ widget (6.6), whose `fetchFeed` then answers with that copy. With `fresh`, `fetchFeed` always asks.
1142
+
1143
+ UWA's `loadContent`, `keptContent` and `keepContent`, which did this by hand, are UWA files' (11.1).
1144
+
1145
+ ### 7.10 Read state and counts
1146
+
1147
+ ```webidl
1148
+ callback ReadKey = DOMString (Element item);
1149
+ dictionary ReadItemsOptions {
1150
+ ReadKey key;
1151
+ };
1152
+ ```
1153
+
1154
+ - `readItems(box, itemSelector, options)` manages a list's read state: each item *itemSelector* matches in *box* has a
1155
+ **read key**, `options.key(item)`, else the address of its first `a.ext-link`, else of its first link; the host adds the
1156
+ class `uwa-read` to read items, makes an item read when one of its links is opened, counts the unread items shown as
1157
+ the widget's unread count, and makes them all read when the count is activated, as `readall`'s default action, unless
1158
+ a listener cancels the event.
1159
+ - `isRead(key)` and `setRead(keys, read)` do it by hand. `setUnreadCount(count)` shows *count*, when positive, after the
1160
+ title and in the tab's count; activating it fires `readall` (7.6). `setSearchResultCount(count)` is accepted.
1161
+
1162
+ A host keeps the last 500 read keys of a widget. A widget file replacing another **MUST** keep its read keys.
1163
+ Headline links to another site **SHOULD** have the class `ext-link`.
1164
+
1165
+ ### 7.11 The reader
1166
+
1167
+ The host's **reader** shows an article over the page, the list it comes from beside it.
1168
+
1169
+ ```webidl
1170
+ dictionary ReaderItem {
1171
+ required USVString url;
1172
+ USVString link; // where its headline points, when not `url`
1173
+ DOMString title;
1174
+ DOMString content; // HTML, the reader's text
1175
+ DOMString prefer; // "feed", "page" or "reader": its first view
1176
+ DOMString date; // an RFC 3339 date, in the reader's list
1177
+ DOMString summary; // a short excerpt, in the reader's list
1178
+ DOMString author;
1179
+ USVString image;
1180
+ boolean read = false;
1181
+ };
1182
+
1183
+ dictionary OpenItemsOptions {
1184
+ DOMString prefer; // "feed", "page" or "reader"
1185
+ sequence<DOMString> frameable; // sites that allow being framed
1186
+ Function onOpen; // (unsigned long index)
1187
+ };
1188
+ ```
1189
+
1190
+ - `openURL(url)` opens *url* in the reader; standalone, in a new tab. Only `http` and `https` URLs.
1191
+ - `openItems(items, index, options)` opens the reader on `items[index]`, the person moving through the others;
1192
+ `prefer` is the first view, `frameable` the sites the reader may show as Web pages, `onOpen(index)` is called as each
1193
+ item shows.
1194
+
1195
+ Framed, both are activation-gated, and never open the host's own addresses.
1196
+
1197
+ ### 7.12 Sound, video and pictures
1198
+
1199
+ ```webidl
1200
+ dictionary PlayAudioOptions {
1201
+ required USVString url; // https
1202
+ boolean relay = false; // played without a Referer, through the host's relay
1203
+ boolean live = true;
1204
+ };
1205
+
1206
+ dictionary AudioState {
1207
+ USVString? url;
1208
+ boolean playing;
1209
+ boolean loading;
1210
+ DOMString? error; // null, "blocked" or "failed"
1211
+ unsigned long? time; // seconds, for a file
1212
+ unsigned long? duration;
1213
+ };
1214
+
1215
+ dictionary AudioControls {
1216
+ Function resume;
1217
+ Function setVolume; // (double volume), 0 to 1
1218
+ };
1219
+
1220
+ dictionary AudioInfo {
1221
+ DOMString source;
1222
+ DOMString title;
1223
+ DOMString artist;
1224
+ USVString artwork;
1225
+ DOMString artworkType;
1226
+ DOMString artworkSizes;
1227
+ };
1228
+
1229
+ dictionary VideoSpec {
1230
+ required DOMString provider; // "youtube", "vimeo" or "arte"
1231
+ required DOMString id;
1232
+ DOMString title;
1233
+ DOMString list; // a YouTube playlist
1234
+ DOMString lang; // an ARTE language
1235
+ };
1236
+
1237
+ dictionary VideoState {
1238
+ DOMString provider;
1239
+ DOMString id;
1240
+ DOMString list;
1241
+ boolean playing;
1242
+ };
1243
+
1244
+ dictionary PhotoSpec {
1245
+ required USVString src;
1246
+ DOMString alt;
1247
+ DOMString title;
1248
+ USVString preview;
1249
+ USVString zoom;
1250
+ unsigned long width;
1251
+ unsigned long height;
1252
+ (PhotoCredit or DOMString) credit;
1253
+ };
1254
+
1255
+ dictionary PhotoCredit {
1256
+ DOMString name;
1257
+ DOMString creator;
1258
+ DOMString creditText;
1259
+ DOMString copyrightNotice;
1260
+ USVString license;
1261
+ USVString url;
1262
+ };
1263
+ ```
1264
+
1265
+ **Sound.** A page plays one sound at a time.
1266
+
1267
+ - `playAudio(options)` plays an `https` stream in the host's page, not in the widget, so that nothing happening to the
1268
+ widget interrupts it; a `live` stream is never played behind its live point. `pauseAudio()`; `seekAudio(seconds)` for a
1269
+ file. `audioState` is its state, and `audiostate` (`onAudioState`) is fired as it changes. Activation-gated.
1270
+ - A widget playing with a player of its own calls `audioStarted(stop, controls)` as it starts: the host stops the sound
1271
+ playing before, and calls *stop* when another starts or the person pauses it. `audioStopped()` says it stopped by itself;
1272
+ `audioInfo(info)` says what plays.
1273
+ - After a reload, the host **MAY** offer to resume; it then fires `audioresume` (`onAudioResume`).
1274
+
1275
+ **Video.** `playVideo(video)` plays a video in the host's player, over the page: only the providers above, by id, never a
1276
+ URL the widget gives. `videoState` and the `videostate` event (`onVideoState`) report what plays, where the provider tells. Activation-gated;
1277
+ standalone, the video opens on its site.
1278
+
1279
+ **Pictures.** `openPhoto(photo)` shows a picture at full size in the host's window: an `https` URL or one of the host's.
1280
+ `preview` is shown while `src` loads; `zoom`, a larger picture of the same, is asked only when the person zooms in
1281
+ (else `src` is enlarged); `width` and `height` give its proportions at once; `credit` is what its licence asks
1282
+ to go with it: a `PhotoCredit`, whose members are schema.org's `ImageObject` properties of the same names (the work's
1283
+ `name`, its `creator` as a name, the `creditText` naming who keeps or gives the picture, the `copyrightNotice` naming who
1284
+ the licence says to name, the `license`'s address, the picture's page `url`; all optional, the addresses `https`), or a
1285
+ plain string, read as its `creditText`. The host shares it with the picture as text and keeps it with what it makes of
1286
+ the picture; it **MAY** shorten its text, and drops what it can't read. Standalone, a new tab. Pictures a widget shows **MUST** be ones it may show: public domain, or under a licence or permission that allows it,
1287
+ their required credits kept.
1288
+
1289
+ ### 7.13 The page
1290
+
1291
+ ```webidl
1292
+ dictionary ShareData {
1293
+ DOMString text;
1294
+ USVString url;
1295
+ };
1296
+
1297
+ dictionary AddWidgetSpec {
1298
+ required DOMString file; // a file of the host's widget directory
1299
+ DOMString title;
1300
+ record<DOMString, DOMString> values; // at most 12, 200 characters each
1301
+ };
1302
+
1303
+ callback DragWidgetCallback = any (DragEvent event); // an AddWidgetSpec; nothing: the drag doesn't start
1304
+
1305
+ dictionary WidgetSaveFile {
1306
+ required DOMString name; // with its extension; cleaned by the host
1307
+ required DOMString type; // one its extension takes; "" for the usual one
1308
+ required (DOMString or Blob or ArrayBuffer) data; // 8 MiB at most
1309
+ };
1310
+
1311
+ dictionary WidgetSaveOptions {
1312
+ WidgetEvent action; // the `action` event of the choice this file answers
1313
+ };
1314
+
1315
+ dictionary WidgetActionState { // a member left out: as it was; null: as the file declares it
1316
+ boolean? disabled; // greyed: nothing to act on
1317
+ boolean? hidden; // not in the menu
1318
+ DOMString? label; // another label, 1 to 40 characters
1319
+ };
1320
+ ```
1321
+
1322
+ - `shareUrl()` returns the widget's address on its host (`/add/<key>`), or null for an untrusted file.
1323
+ - `share(data)` shares *data* through the system's share sheet where there is one, else the clipboard. Activation-gated.
1324
+ - `addWidget(spec)` adds a widget of the host's directory after this one, with *spec*'s title and values. Trusted files
1325
+ only; activation-gated. The member is **absent** where no widget can be added (a preview, standalone).
1326
+ - `dragWidget(element, spec)` makes *element* draggable onto the page, creating the widget *spec* names (or returns, if
1327
+ a function, as the drag starts: it is given the drag's `DragEvent`, and returning nothing cancels the drag) where it
1328
+ is dropped; it returns false, leaving *element* alone, where drags can't
1329
+ reach the page (framed, standalone).
1330
+ - **Maximized.** A person may maximize any widget. `canFullSize` says whether the host can; `openFull()` and
1331
+ `closeFull()` do it from a control of the widget's own; `fullSize` says which; `fullsize` (`onFullSize`) is fired once its
1332
+ box has its new size. `setFullScreen(on)`, activation-gated, puts the widget alone over the window, maximized first if it isn't, in the browser's full screen where there is one; `false` puts
1333
+ the widget back as it was before (on the page if the full screen maximized it). `fullScreen` says whether it is, the
1334
+ person's Esc included; `fullscreen` (`onFullScreen`) is fired as it changes.
1335
+ - **Its own actions.** A widget may have actions of its own in its options menu, for what belongs to the widget but
1336
+ not in its body (a recipe's *Reset*). **They are declared in the file**, as its settings are (section 5), and read
1337
+ by the host without running the widget:
1338
+
1339
+ ```html
1340
+ <menu id="actions" hidden>
1341
+ <button type="button" name="reset" data-icon="reset" data-confirm="Reset checked items and timers?" disabled>Reset</button>
1342
+ </menu>
1343
+ ```
1344
+
1345
+ Each `button` that is a child of the `menu` declares one action, in document order: `name` is its id (1 to 40
1346
+ letters, digits, `-`, `_` or `.`, unique), its text the label (text, never markup, 40 characters at most),
1347
+ `disabled` and `hidden` its state as the widget starts (greyed; not in the menu until the widget says otherwise),
1348
+ `data-icon` and `data-confirm` optional. Five at most, the hidden ones counted. A host reads
1349
+ the declaration strictly: an action whose id, label or question breaks these bounds is left out whole, never
1350
+ shortened, and the ones past the fifth are left out. The declaration is data: the host removes it from the
1351
+ widget's body, as the settings form, and never moves its elements or their handlers into its own page. What makes
1352
+ an action usable (its name, its greyed state, the keyboard, the focus given back) is the host's menu, not these
1353
+ hidden buttons.
1354
+ - `data-icon` hints at the picture the widget would like beside the label: one of the generic names `reset`,
1355
+ `refresh`, `undo`, `redo`, `copy`, `download`, `upload`, `share`, `add`, `remove`, `clear`, `edit`, `search`,
1356
+ `print`, `play`, `pause`, `stop`, `check`, `star`, `info`, `settings`, for which the host draws its own picture,
1357
+ or one emoji (a pictograph, one character as people see it: not a letter or another symbol), shown as given; a
1358
+ host **MAY** ignore it, and shows nothing for anything else.
1359
+ - `data-confirm` is a question (200 characters at most) the host asks in a dialog of its own before firing
1360
+ `action`, the action's label naming the answer that goes ahead; it fires only on that answer, and only if the
1361
+ widget still offers that action, with the same label, then. A host that can't ask **MUST NOT** fire. A widget
1362
+ asks nothing of its own for it (10.1: no browser dialogs).
1363
+ - **The running widget only changes their state**: `setActionStates(states)`, keyed by declared id, sets
1364
+ `disabled`, `hidden` or another `label` (a word that depends on its state, or a translation) of the actions it
1365
+ names, leaving the others and the members not given as they were. A member given as `null` goes back to what
1366
+ the file declares: `{ label: null }` restores the declared label. An id the file doesn't declare, or a label
1367
+ that isn't 1 to 40 characters, throws a `TypeError`. A widget **SHOULD** call it whenever what an action acts on
1368
+ changes. States last while the widget runs: a reload, or a widget the host builds again (6.4), starts from the
1369
+ declaration, and the widget says them again as it loads.
1370
+ - **Declared is not ready.** The host lists a declared action from the start, greyed until the widget has started:
1371
+ its first `load` dispatched, or its first `setActionStates`. One chosen then fires `action` (7.6.1) with its id
1372
+ in `detail.id`; a host **MUST NOT** fire it before, nor for an action disabled or hidden. Started means the
1373
+ `load` event was dispatched, not that what its listeners began has finished: a widget whose `load` fetches its
1374
+ data can be sent `action` before the data is there. A widget whose action needs that data declares the button
1375
+ `disabled` (or `hidden`) and enables it with `setActionStates` once the data has come.
1376
+ - The choice was made in the host's menu, not in the widget: it does not count as activation in the widget (6.7),
1377
+ so an action that needs one (a file picker, the clipboard) opens a control of the widget's own for the person
1378
+ to press. A download is the exception: the host delivers it (`saveFile`, below).
1379
+ - **A file to keep.** An action may produce one file for the person to download. Its declaration says which, in
1380
+ `data-save`: the extensions it may produce, space-separated, each a dot and 1 to 10 letters or digits.
1381
+
1382
+ ```html
1383
+ <button type="button" name="download" data-icon="download" data-save=".cook" disabled>Download as .cook</button>
1384
+ ```
1385
+
1386
+ ```js
1387
+ widget.addEventListener('action', (event) => {
1388
+ if (event.detail.id !== 'download') return;
1389
+ widget.saveFile({ name: title + '.cook', type: 'text/plain;charset=utf-8', data: text }, { action: event });
1390
+ });
1391
+ ```
1392
+
1393
+ The widget builds the content; the host authorizes, checks and delivers it. `data-save` is read from the file
1394
+ with the rest of the declaration, and `setActionStates` can't change it. It is independent of a setting's
1395
+ `data-file` (5.3), which keeps its meaning.
1396
+ - **What a choice allows.** `saveFile(file, { action: event })` answers one choice in the menu: *event* is the
1397
+ `action` event the host fired for it. One file per choice, within 30 seconds of it, and one save at a time
1398
+ per widget. The choice belongs to the widget as it runs then: it ends with a reload or a widget the host
1399
+ builds again (6.4), and never passes to what replaces it. An event the widget makes itself, an id it supplies
1400
+ or a claim of activation allow nothing. A call without `action` rejects with `NotAllowedError`: a download
1401
+ from a control of the widget's own is not specified yet (it needs a host dialog showing the final name and a
1402
+ declaration for the whole widget; [Issue 32](#issue-32)).
1403
+ - **The data** is a string, a `Blob` or an `ArrayBuffer`, 8 MiB at most in bytes (a string counted as UTF-8),
1404
+ copied as the call is made: the caller's buffer stays usable. Never an address, a stream or anything the host
1405
+ would fetch.
1406
+ - **The name** (1,024 characters at most as given, the type 255) is cleaned by the host: its last part only (no folders), no control or direction characters,
1407
+ nothing a disk refuses, no dots or spaces at its ends, never a device's name, 120 characters at most before
1408
+ its extension, a fallback when nothing is left. Its extension is read after cleaning and is the last one; an
1409
+ extension before it loses its dot (`invoice.exe.cook` becomes `invoice-exe.cook`).
1410
+ - **The extension** must be one the action declares **and** one the host allows. A host keeps an allow-list of
1411
+ data formats, never a block-list; Startside's is `.cook`, `.txt`, `.md`, `.csv`, `.json`, `.ics` and `.opml`.
1412
+ An action declaring another extension gets nothing for it.
1413
+ - **The type** must be one the extension takes (Startside: `text/plain` for each of them; also `text/markdown`
1414
+ for `.md`, `text/csv` for `.csv`, `application/json` for `.json`, `text/calendar` for `.ics`, `text/x-opml`,
1415
+ `application/xml` and `text/xml` for `.opml`); `""` asks for the usual one. A `Blob`'s own type is ignored:
1416
+ the host makes the file. A host **MUST NOT** render, preview or open the content, nor give the widget the
1417
+ file's address.
1418
+ - **Delivery.** While the person's choice still counts as activation in the host's page, the download starts.
1419
+ If it no longer does (a handler that computed or fetched first), the host shows a control of its own naming
1420
+ the file ("Download “name”?"), for those exact bytes: pressing it delivers the file, Cancel gives it up. A
1421
+ widget that stops while it is shown (removed, reloaded, built again) takes the control and the file with it. No
1422
+ other question is asked for a declared download: choosing it is the intent. `data-confirm` works as for any
1423
+ action, before `action` fires.
1424
+ - **The promise** resolves once the host has handed the file to the browser, which is not "saved": the browser
1425
+ may still block it or the person cancel it there. It rejects with a `DOMException`: `NotAllowedError` (no
1426
+ such choice, one already used or too old, or another save going on), `NotSupportedError` (a name, an
1427
+ extension, a type or data the action or the host doesn't take), `QuotaExceededError` (over 8 MiB),
1428
+ `AbortError` (the person cancelled the host's control). A refused file uses its choice up. A host shows no
1429
+ "Saved" notice and no path.
1430
+ - On a widget's own page (10.3) the call and its rules are the same; there they shape the API and do not
1431
+ protect, since the widget isn't sandboxed ([Issue 15](#issue-15)).
1432
+ - There is no way to make a list of actions in script: none of the widgets written so far needs one only known as
1433
+ it runs ([Issue 32](#issue-32)).
1434
+ - **Accounts.** A trusted widget declaring `accountService` and a hidden setting named `account` has its account in its
1435
+ settings: the host lists the page's accounts of that service (those allowing one of `accountScope`'s permissions; an
1436
+ account reporting none allows none, an account's permissions read space- or comma-separated) and
1437
+ offers to unlink it, which clears `account`. Its requests reach that service's routes on the host (section 10.1); a
1438
+ sign-in window opens through the host, activation-gated. A widget **MUST NOT** assume one account per service. An
1439
+ untrusted file declaring `accountService` gets nothing.
1440
+
1441
+ ### 7.14 Absent members
1442
+
1443
+ Where the host can't perform an operation (standalone: the reader, adding widgets), the member performs a
1444
+ fallback stated above or does nothing; `addWidget` alone is absent, so that `if (widget.addWidget)` tells.
1445
+
1446
+ ### 7.15 Error reports
1447
+
1448
+ A host **SHOULD** report errors in widget code at the file's own lines: the file's name and the line, with an excerpt.
1449
+
1450
+ ## 8. Data access
1451
+
1452
+ ### 8.1 Fetching
1453
+
1454
+ Framed, the browser's `fetch` [[FETCH](#ref-fetch)] reaches `https` URLs only. The frame's origin is opaque: it has no
1455
+ cookies of its own, and its cross-origin requests carry an `Origin` of `null`, so they reach only APIs that allow any
1456
+ origin. Whether the browser attaches a site's own cookies to a request to that site is the browser's third-party
1457
+ cookie policy, which this specification doesn't change. A relative URL resolves against the host and reaches only its
1458
+ public services, and, for trusted files, the account services of section 7.13. `XMLHttpRequest` and WebSocket are not
1459
+ relayed. For any other site, `widget.fetch` (8.2) goes through the host.
1460
+
1461
+ ### 8.2 `widget.fetch`
1462
+
1463
+ ```webidl
1464
+ dictionary FetchFeedOptions {
1465
+ AbortSignal? signal = null;
1466
+ boolean fresh = false;
1467
+ };
1468
+ ```
1469
+
1470
+ `fetch(input, init)` is the platform's `fetch` [[FETCH](#ref-fetch)] made by the host for the widget, through its
1471
+ proxy, so that it needs no CORS: same arguments, and it resolves to a `Response`. The host **MUST** refuse addresses on
1472
+ local and private networks, including through redirects, and its own addresses other than its public services; it
1473
+ **MAY** answer from a cache of 5 minutes (8.4). In this version:
1474
+
1475
+ - only `GET` requests are made: another `method` rejects with a `TypeError`;
1476
+ - an `Accept` header naming JSON asks with JSON headers (a GraphQL query by `GET`); no other request header is sent;
1477
+ - the `Response` carries the body, as text, with the status 200 for a success (the relay keeps no other); an HTTP
1478
+ error gives a `Response` with its status and no
1479
+ body, `ok` false; a network failure, or a refused address, rejects with a `TypeError`, as the platform's does;
1480
+ - the response's headers aren't given, and a binary body isn't either (a picture is shown with an `img`);
1481
+ - the signal (`init`'s, else the `Request`'s) aborts it: the promise rejects with the signal's reason.
1482
+
1483
+ What the widget does with the body is the platform's: `res.json()` for JSON, `res.text()` for text, and for a page or
1484
+ an XML document `new DOMParser().parseFromString(text, 'text/html')` (or `'application/xml'`), a document whose scripts
1485
+ don't run. Markup from it **MUST NOT** be inserted into the widget as HTML. A widget reading a site's pages or API
1486
+ with `fetch` **MUST** respect the site's robots.txt [[RFC9309](#ref-rfc9309)] and its terms, as any automated client
1487
+ does; a host **MAY** check robots.txt itself for these requests.
1488
+
1489
+ ### 8.3 `widget.fetchFeed`
1490
+
1491
+ `fetchFeed(url, options)` gives the feed at *url*, RSS, Atom or JSON Feed, as a content feed (8.5): the host parses and
1492
+ normalizes it, keeps it (7.9), and resolves with it; a feed with no items is a feed, not a failure. `options.signal`
1493
+ aborts it; `options.fresh` skips the kept copy (a refresh the person asked for, 6.6). A feed that can't be read rejects
1494
+ with an `Error`; a widget showing nothing then gets its load tried again sooner than its automatic refresh. A feed is
1495
+ asked for by kind: a JSON Feed fetched with `fetch` is the file's JSON, unnormalized.
1496
+
1497
+ A feed is fetched as the person's agent, not as a crawler: the feed a widget reads is one a person chose (its settings,
1498
+ the file's declared feed), so a host fetches it, and refreshes it, without consulting robots.txt, as feed readers do.
1499
+ It **MUST** fetch it as a good feed reader does: named in its `User-Agent`, at most every 5 minutes for any number of
1500
+ widgets asking (8.4), with conditional requests (`If-None-Match`, `If-Modified-Since`) once it has a copy, and honouring
1501
+ a `429`'s `Retry-After` (seconds or a date). Given a page's address rather than a feed's, the host **MAY** follow the
1502
+ first feed the page advertises (`<link rel="alternate">`, one more request, as feed readers do); crawling a site to
1503
+ discover feeds is not part of this specification.
1504
+
1505
+ ### 8.4 Freshness
1506
+
1507
+ Responses and feeds through the host's proxy are fresh for 5 minutes; a refresh the person asks for skips that cache.
1508
+ A kept feed answers at once whatever its age, asked again behind it when older than 5 minutes (7.9).
1509
+
1510
+ ### 8.5 Content feeds
1511
+
1512
+ A **content feed** is a JSON Feed 1.1 document [[JSONFEED](#ref-jsonfeed)] whose extension `_myvibes` carries
1513
+ what the host's widgets share (`kicker`, `live`, `featured`, `thumbnail`, `score`, `comments`, and at the feed level
1514
+ `source` and `fetched`), and `_<site>` a site's own data.
1515
+
1516
+ ```webidl
1517
+ typedef object ContentFeed; // a content feed: its schema is Issue 11
1518
+ ```
1519
+
1520
+ To **normalize** a content feed, keep only those members, give every item an `id` (its `url` when it has none, dropping
1521
+ an item with neither), and write dates in [[RFC3339](#ref-rfc3339)] format. The host normalizes the feeds `fetchFeed`
1522
+ gives; UWA's `UWA.Content` helpers are UWA files' (11.1).
1523
+
1524
+ ## 9. Built-in objects
1525
+
1526
+ SWA adds nothing to the objects of the platform. In an SWA widget's realm (its frame, or its own page: 10.2):
1527
+
1528
+ - a host **MUST NOT** add members to the prototypes of built-in objects (`HTMLElement`, `Element`, `Array`, `String`,
1529
+ `Function`…), nor define globals other than `widget` and `WidgetEvent`
1530
+ (`Widget`, `WidgetSettings`, `WidgetStorage` and `WidgetStorageArea` have no interface object: their objects are
1531
+ reached through `widget` alone), save names beginning with `__`, which a host **MAY** use for its own hooks and a
1532
+ widget **MUST NOT** use;
1533
+ - a host **MAY** wrap `fetch` and `window.open` in a framed widget's realm, to relay a request for one of the host's
1534
+ own addresses (8.1) and a sign-in window (7.13); otherwise they behave as the browser's;
1535
+ - a host **MUST NOT** replace a member the browser defines, whether it runs one runtime for several formats or not: an
1536
+ SWA widget calling `setHTML` gets the browser's [[HTML](#ref-html)], never UWA's (11.2, [Issue 13](#issue-13));
1537
+ - widget code **MUST NOT** rely on such members, and **SHOULD NOT** add any itself: it uses the DOM [[DOM](#ref-dom)] and
1538
+ ECMAScript's own (`textContent`, `classList`, `append`, `replaceChildren`, `style`, `Array.prototype.map`).
1539
+
1540
+ `widget.body` and the elements `widget.createElement` returns are ordinary `HTMLElement`s.
1541
+
1542
+ UWA's extensions of built-in objects, its globals (`$`, `$A`, `Class`, `Environment`, `Element(tag)`) and the rest of
1543
+ its `UWA` namespace remain for UWA files (11.2), in their realm only. A host running both formats with one runtime
1544
+ installs them by the file's format; an SWA widget's realm, its frame or its own page (10.2), is its own and never has
1545
+ them.
1546
+
1547
+ <div class="example">
1548
+
1549
+ **Example 5.** UWA's element extensions, and what an SWA widget writes instead.
1550
+
1551
+ | UWA 1.2 | SWA 1.0 |
1552
+ |---|---|
1553
+ | `el.setText(t)`, `el.setHTML(h)`, `el.empty()` | `el.textContent = t`, `el.innerHTML = h` (the widget's own fixed markup only, 7.3), `el.replaceChildren()` |
1554
+ | `el.addClassName(c)`, `el.hasClassName(c)` | `el.classList.add(c)`, `el.classList.contains(c)` |
1555
+ | `el.show()`, `el.hide()`, `el.toggle()` | `el.hidden = false`, `el.hidden = true`, `el.hidden = !el.hidden` |
1556
+ | `el.setStyle('color', 'red')` | `el.style.color = 'red'` |
1557
+ | `el.getElements('a')`, `el.getChildren()` | `el.querySelectorAll('a')`, `el.children` |
1558
+ | `el.addEvent('click', f)` | `el.addEventListener('click', f)` |
1559
+ | `el.inject(target)` | `target.append(el)` |
1560
+ | `$A(list)`, `'…'.stripTags()`, `JSON.encode(v)` | `Array.from(list)`, the text of a parsed document, `JSON.stringify(v)` |
1561
+
1562
+ </div>
1563
+
1564
+ ## 10. Execution environments
1565
+
1566
+ ### 10.1 Framed
1567
+
1568
+ A dashboard **MUST** run every widget in a frame of its own, sandboxed with an opaque origin. In it:
1569
+
1570
+ 1. Connections are limited to `https` URLs by a Content Security Policy [[CSP](#ref-csp)]; requests to the
1571
+ host's addresses are relayed by the host, which answers only its public services and, for a trusted file, the account
1572
+ services of the file's declared service.
1573
+ 2. The frame has no storage; everything a widget keeps goes through the host (section 7.8).
1574
+ 3. Operations that cover or leave the page are activation-gated (section 6.7).
1575
+ 4. The host accepts a message from a frame only from that frame's window, with that load's instance identifier, and
1576
+ checks each field's type and size. Functions never cross the frame: a callback stays in it and is called by message.
1577
+ 5. A drag starting in the frame doesn't reach the page (`dragWidget` returns false).
1578
+ 6. The browser's dialogs are off: `alert()` does nothing, `confirm()` answers false and `prompt()` null, at once. A
1579
+ widget **MUST NOT** use them, on its own page either (they work there, so a widget relying on them behaves
1580
+ differently framed): a question is asked in the widget's own box, its safe answer focused, Esc for it (14).
1581
+
1582
+ A widget **MUST** work framed. One that can't **MUST** say so in its box, and how to change it, rather than fail.
1583
+
1584
+ ### 10.2 No inline mode
1585
+
1586
+ An SWA widget runs framed (10.1) or on its own page (10.3), always in a document and a realm of its own: its `id`s,
1587
+ its globals and its styles meet no other widget's and not the host's. A host **MUST NOT** run an SWA widget in the
1588
+ host's own page because the widget asks; `environment.inline` is `false`. How a host might run widgets of its own in
1589
+ its page, for its own reasons, is outside this specification, and a widget written to it makes no provision for it.
1590
+ UWA 1.2 files keep their `inline` metadata (section 11).
1591
+
1592
+ ### 10.3 Standalone
1593
+
1594
+ Opened on its own, a widget file runs in the standalone host: its box, centred on the page, with a title bar.
1595
+
1596
+ - **The options menu.** The title bar's options button (▾) opens the widget's options menu, as a dashboard's:
1597
+ - its **Title**: a rename the page keeps; emptied, the widget's own;
1598
+ - its **Look**, when it has two: *Own* (its `chromeColor` and `background`) or *Page* (the page's bar and colors, the
1599
+ widget flattened under `html.uwa-neutral`, as on a dashboard);
1600
+ - its **Color**: the dashboard's palette, as `--module-color` and `--module-paper`;
1601
+ - its settings, applied as 6.5 says (addresses, numbers and `data-commit` fields on Enter or as the field is left;
1602
+ `livePreferences`), when it has 6 visible settings or fewer; else *Preferences…*, opening the form in the box with
1603
+ a confirming button;
1604
+ - the actions: **Refresh**, *Maximize*, *Mark all as read* and *Mark all as unread* (7.10).
1605
+
1606
+ `widget.openPreferences()` opens the menu.
1607
+ - **Width.** Maximized (not when it fills the window), the box has a width grip on each side: dragged, or moved with
1608
+ the arrow keys, they set its maximized width, which the host keeps for the page, and fire `resize`; a double-click on
1609
+ one, or Enter, gives it back the width its `maximize` metadata gives. Not maximized, the box has its own width.
1610
+ - **Maximized.** A double-click on the title bar (whose pointer says it can be clicked), or *Maximize*, maximizes the
1611
+ widget as a dashboard does (7.13: `canFullSize`, `fullSize`, `fullsize`, as its `maximize` metadata says; Esc
1612
+ restores it). Maximized in a column, the widget is told the room its content may grow into, so its lists show more
1613
+ whole items.
1614
+ - **The page's look.** It is drawn as the dashboard's Classic style draws one, its colors mixed from an **accent** the
1615
+ dots at the window's bottom pick (a footer under the widget when it's taller than the window; a maximized widget stops
1616
+ above it), light, dark or the system's by the switch beside them (dark: the widget's own dark look, by the root's
1617
+ `color-scheme`, 4.7), both kept for every widget the host shows on its own.
1618
+ - **Add to Startside.** Under the widget, a button opens the host's dashboard on its preview of the widget, by its
1619
+ address (`/add?url=<its address>`: trusted for the host's own files, else framed and untrusted); from disk, only for a
1620
+ file of the host's own widget folder, linked to the host's copy. There is no button when the file's `addButton`
1621
+ metadata is `false`, nor when the page runs in another page's frame (a chat's preview, a code playground, an
1622
+ article): its address there is rarely the file's own.
1623
+ - **Starting from its address.** The address's fragment sets how the page starts, for testing a widget:
1624
+ `#mode=dark` (or `light`, `auto`) and `#width=300` (the box's width in CSS pixels), joined by `&`. Neither is saved,
1625
+ the person's own switch takes over, and the fragment is never part of the address *Add to Startside* sends.
1626
+ - **In a frame.** In a frame shorter than it, the page scrolls.
1627
+ - **The host's page.** The page around the widget (its title bar, menu, footer and their elements' ids and classes) is
1628
+ the host's, not part of this specification, and may change: a widget **MUST NOT** style or script it, and styles
1629
+ only its own content.
1630
+ - **Data and state.** Read and unread work as on a dashboard (7.10): the read keys kept for the page, the unread count
1631
+ after the title. Its data requests go through the runtime's host's proxies. Its memory (7.8) lasts while the page is
1632
+ open, not across reloads; its settings and stored data do; its automatic refreshes keep a fixed interval.
1633
+ - **What differs.** The reader's operations open new tabs, videos their sites, and `addWidget` is absent.
1634
+ - **Without storage.** Where the browser refuses the page's storage, the widget still runs: with its declared defaults,
1635
+ its own width and title, nothing kept.
1636
+
1637
+ ### 10.4 Trust
1638
+
1639
+ | | Trusted file | Untrusted file |
1640
+ |---|---|---|
1641
+ | Framed | yes | yes |
1642
+ | Account services | its declared service's, its chosen account's | no |
1643
+ | `addWidget` | yes | absent |
1644
+ | Everything else | yes | yes, checked by the host |
1645
+
1646
+ A trusted file's account services are bound (Issue 21, resolved): a host **MUST** relay a request to an account
1647
+ service's address, or open its sign-in window, only for the service the file declares (`accountService`, 4.5) and,
1648
+ once the widget has chosen an account (its `account` setting), only for that account: a request naming another, in its
1649
+ address or its body, is refused, and one naming none is for the chosen account (a host names it, so that a service
1650
+ taking the only account connected, or a default, never serves another); a file declaring no service reaches none. Anything else is refused before it reaches the service: the widget's
1651
+ `fetch` rejects with a `TypeError`, a sign-in window isn't opened. UWA files, which declare no service, keep UWA's
1652
+ access to every account service of the host (section 11).
1653
+
1654
+ **Networks** (Issue 22, resolved). The host's relays (`widget.fetch`, `fetchFeed`, a UWA file's `UWA.Data`, and its
1655
+ own addresses) **MUST** refuse local and private network addresses, redirects included. A widget's own requests
1656
+ (`fetch` from its frame, its pictures, media and scripts) go where the browser lets a page of its origin go: a host
1657
+ **MUST NOT** claim more for them. On a host served over `https` from a public address, browsers that enforce Private
1658
+ Network Access keep them off the person's local network; a host **MAY** narrow them further with its frame's policy
1659
+ (Issue 1).
1660
+
1661
+ ## 11. Compatibility with UWA 1.2
1662
+
1663
+ A conforming host **MUST** also run UWA 1.2 widget files [[UWA](#ref-uwa)]: XHTML documents with a
1664
+ `widget:preferences` element and UWA's interface, which sections 7 and 8 extend. A UWA file **SHOULD** be named
1665
+ `<name>.uwa.xhtml`, with the key `<name>.uwa`; `<name>.xhtml`, with the key `<name>`, is accepted.
1666
+
1667
+ ### 11.1 Files and preferences
1668
+
1669
+ UWA's preference types map to section 5.2's: `text`, `password`, `hidden`, `boolean`, `list` and `range`; the
1670
+ attributes `hint`, `when`, `commit`, `type="url"`, `type="number"` and `feed` on an option are the types and
1671
+ attributes of 5.2 and 5.3, the attributes without their `data-` prefix.
1672
+
1673
+ UWA files keep UWA's data access: the `UWA` object, `UWA.Data` (`request`, `getJson`, `getXml`, `getText`, and
1674
+ `getContentFeed` for a content feed), `UWA.Content`, `loadContent`, `keptContent` and `keepContent`, kept content
1675
+ being 7.9's (the same copies `fetchFeed` keeps), and `remember`, `recall`, `setStored` and `getStored`, synchronous,
1676
+ over the same data as `storage.memory` and `storage.local` (7.8); and `getValue`, `getInt`, `getBool`, `setValue` and
1677
+ `deleteValue`, string-valued, over the same settings as `widget.settings` (7.5). They keep UWA's feeds too: `UWA.Data.getFeed(url, callback)` and
1678
+ `request`'s `type: "feed"` give an RSS or Atom feed
1679
+ as UWA's feed object [[UWA](#ref-uwa)], its items with `image` and `author` besides UWA's fields; the host
1680
+ keeps the widget's last 4 feeds, given at once as the widget starts, unless its metadata `keepFeeds` is `false`.
1681
+
1682
+ A host **MAY** omit what UWA 1.2.4 had and SWA doesn't: `onUpdateTitle` (SWA has no `updatetitle` event), `onSearch`, `onResetSearch`, `onKeyboardAction`, `addStar`,
1683
+ `setTooltip`, `UWA.Controls.TabView`, `UWA.Data.Storage`, requests other than GET through the proxy, Flash, and
1684
+ Netvibes' hosted services. `openURL` opens the reader, not a window.
1685
+
1686
+ UWA's `onShowEdit(element)` is **deprecated**: it is not an SWA event, and an SWA widget **MUST NOT** rely on it. A host
1687
+ **MAY** still call it for a UWA file whose settings form it draws in the widget's box (a standalone host's
1688
+ *Preferences…*), with that form's element; a dashboard, which shows settings in its own menu, never calls it.
1689
+
1690
+ ### 11.2 UWA's extensions of built-in objects
1691
+
1692
+ For UWA files, a host provides UWA's extensions of built-in objects [[UWA](#ref-uwa)]: on every `HTMLElement` of the
1693
+ widget's realm, the members below, each returning the element it was called on unless its type says otherwise, without
1694
+ replacing a member the browser already defines (but `setHTML`: [Issue 13](#issue-13)); `$(element)`, `$A(list)`,
1695
+ `Class.create()`, `_(text)` (the translation hook, returning *text*), `UWA.Utils` (`buildUrl`, `setCss`), `UWA.Json`
1696
+ (`encode`, `decode`, also as `JSON.encode` and `JSON.decode`), `UWA.Controls.Pager`; and UWA's `Array`, `String` and
1697
+ `Function` methods (`stripTags`, `truncate`, `bind`…).
1698
+
1699
+ ```webidl
1700
+ interface mixin WidgetElement {
1701
+ HTMLElement setText(DOMString text);
1702
+ HTMLElement setHTML(DOMString html);
1703
+ HTMLElement setContent((DOMString or Node) content);
1704
+ HTMLElement addContent((DOMString or Node) content);
1705
+ HTMLElement appendText(DOMString text);
1706
+ HTMLElement empty();
1707
+ HTMLElement show();
1708
+ HTMLElement hide();
1709
+ HTMLElement toggle();
1710
+ HTMLElement addClassName(DOMString name);
1711
+ HTMLElement removeClassName(DOMString name);
1712
+ boolean hasClassName(DOMString name);
1713
+ HTMLElement setStyle((DOMString or object) property, optional DOMString value);
1714
+ HTMLElement setStyles(object styles);
1715
+ HTMLElement setOpacity(double value);
1716
+ object getDimensions(); // { width, height }
1717
+ Node? getParent();
1718
+ NodeList getChildren(); // childNodes, text and comments included
1719
+ Element? getElement(DOMString selector);
1720
+ sequence<Element> getElements(DOMString selector);
1721
+ HTMLElement inject(Element target, optional DOMString where);
1722
+ HTMLElement setAttributes(object attributes);
1723
+ HTMLElement addListener(DOMString type, Function listener);
1724
+ HTMLElement removeListener(DOMString type, Function listener);
1725
+ HTMLElement addEvent(DOMString type, Function listener);
1726
+ HTMLElement addEvents(object listeners);
1727
+ };
1728
+ HTMLElement includes WidgetElement; // in a UWA file's realm only (section 9)
1729
+ ```
1730
+
1731
+ `setHTML` inserts markup as given: widget code **MUST NOT** pass it markup fetched from elsewhere (section 12).
1732
+
1733
+ ### 11.3 UWA's callbacks
1734
+
1735
+ A UWA file's `widget` also has UWA's callbacks [[UWA](#ref-uwa)]: for each event type of 7.6's table, a **callback
1736
+ attribute** of the name its last column gives (`onLoad`, `onRefresh`…), whose value is a function or null;
1737
+ `setCallback(name, callback)`, a second, **registered callback** for that name, one per name, replacing the previous
1738
+ one, `null` removing it; and `callback(name, argument)`, which fires the event of that name and returns undefined. For
1739
+ a name not in the table, `callback` calls the callback attribute and the registered callback of that name with
1740
+ *argument*, only if *name* begins with `on`; it calls no other member of `widget`.
1741
+
1742
+ For a UWA file, firing a widget event (7.6.2) runs one more step before the dispatch: for the callback attribute of the
1743
+ type's name, then its registered callback, each read as this step reaches it, if it is a function, call it with the
1744
+ event's `detail` and `widget` as `this`; for `load` and `refresh`, if it returns a promise, act as if `waitUntil` had
1745
+ been called with it, except that its rejection isn't reported, as in UWA; if it throws, report the exception and go on.
1746
+ A UWA file listens for an event type (7.6.2) also when that callback attribute or registered callback is a function.
1747
+ `readall`'s default action (7.10) is skipped when the file has an `onReadAll` callback, which marks its items itself,
1748
+ as in UWA.
1749
+
1750
+ ## 12. Security Considerations
1751
+
1752
+ - **Isolation.** The sandboxed frame (10.1) is what lets a person add a widget written by anyone: it never runs in the
1753
+ page, never reads the page's storage or the person's accounts, and reaches the host only through relayed, checked
1754
+ operations. Hosts **MUST NOT** relax it for untrusted files.
1755
+ - **Markup.** Markup from a feed or an API **MUST NOT** be inserted as HTML: parse it inert (with `DOMParser`) and copy
1756
+ what is needed, or insert it as text.
1757
+ - **Proxies.** The host's proxies make requests on the widget's behalf: they **MUST** refuse local and private
1758
+ addresses, through redirects too, and the host's own.
1759
+ - **Activation.** Operations that cover the page (the reader, the video player, full screen) or leave it (sharing,
1760
+ sign-in windows) are activation-gated, so a widget can't take over the page by itself.
1761
+ - **Passwords.** A password setting never reaches a framed widget.
1762
+ - **Code.** Widget code **MUST NOT** evaluate fetched text as code.
1763
+
1764
+ ## 13. Privacy Considerations
1765
+
1766
+ - A widget's settings, memory, stored data, kept content and read keys are kept by the host, as the host's privacy
1767
+ notice describes; a framed widget keeps nothing itself.
1768
+ - A shared link carries only settings marked `data-share`, never a password.
1769
+ - Framed requests come from an opaque origin; whether a site's cookies go with them is the browser's third-party
1770
+ cookie policy. A site asked directly (`fetch` from the frame) sees the person's network address; one asked through the
1771
+ host (`widget.fetch`, `fetchFeed`, `UWA.Data`) sees the host's, and the host sees the address asked.
1772
+ - A widget **SHOULD NOT** send the person's settings or account data to third parties beyond what its function needs,
1773
+ and its `description` **SHOULD** say what it connects to.
1774
+ - Kept content may include data from the person's accounts; a host **SHOULD** limit how long it keeps it and forget it
1775
+ when the account is disconnected.
1776
+
1777
+ ## 14. Accessibility Considerations
1778
+
1779
+ Widgets **SHOULD** conform to WCAG 2.2 at level AA [[WCAG22](#ref-wcag22)] and follow the WAI-ARIA Authoring
1780
+ Practices [[ARIA-APG](#ref-aria-apg)] for each pattern they use: operable with the keyboard alone, with a visible
1781
+ focus; controls named and stating their state; text at 4.5:1 contrast (3:1 for large text and controls' edges) in light
1782
+ and dark; nothing conveyed by color alone; motion honouring `prefers-reduced-motion`; `button` and `a` elements rather
1783
+ than clickable generic elements. A widget's keyboard handling belongs to its own focus, never to the page's. An update
1784
+ keeps the keyboard focus where the person left it (7.3.1). A change the person needs to know of, which they didn't
1785
+ cause where their focus is (a result, a game won, an error, new items), is announced: a live region of the skeleton
1786
+ (`role="status"`, or `role="alert"` for an error; each implies its `aria-live`), present from the start, its text
1787
+ changed. Nothing is announced as the widget first draws (a "New game" at load), only what the person did or needs
1788
+ to know. A change of mode or focus is not announced (a "keyboard active" message at each focus repeats what the
1789
+ focus itself says): help for the keyboard is the control's description (`aria-describedby`), read when it's
1790
+ focused. A composite control (a board, a grid) is one stop in the Tab order, the arrow keys moving inside it (7.3.1).
1791
+ A single-key shortcut (N for a new game, a digit for a color) acts only while the widget's own element has the focus,
1792
+ never on the page's keys; one that throws away what the person did (a game in progress) asks first or can be undone.
1793
+ What a `canvas` shows that matters (a board's state, a score) is also in text: a status line, a label, a description.
1794
+
1795
+ ---
1796
+
1797
+ ## Appendix A. Examples
1798
+
1799
+ *This appendix is non-normative.*
1800
+
1801
+ **Example 4.** A blog's headlines, drawn in place (7.3.1): a skeleton with its states (loading, nothing posted, a
1802
+ failure) and a `template` row, filled with text; one listener on the list for every row; read and unread, the reader. A
1803
+ refresh asks for the feed again; within 5 minutes of the last request, the host's proxy may answer with what it has
1804
+ (8.4); a failed refresh keeps what's shown.
1805
+
1806
+ ```html
1807
+ <!doctype html>
1808
+ <html>
1809
+ <head>
1810
+ <script src="https://startside.app/swa/1.0/runtime.js"></script>
1811
+ <title>My Blog</title>
1812
+ <meta name="description" content="My blog's latest posts." />
1813
+ <meta name="category" content="Blogs" />
1814
+ <meta name="autoRefresh" content="30" />
1815
+ <meta name="chromeColor" content="#3e454c" />
1816
+ <meta name="background" content="#ffffff" />
1817
+ <meta name="backgroundDark" content="#1c1c1e" />
1818
+ <meta name="feed" content="https://example.com/feed.xml" />
1819
+ <link rel="icon" href="myblog.svg" />
1820
+ <style>
1821
+ .blog { padding: 6px 10px; background: light-dark(#ffffff, #1c1c1e); }
1822
+ .blog .posts { list-style: none; margin: 0; padding: 0; }
1823
+ .blog [hidden] { display: none; }
1824
+ .blog .uwa-read a { opacity: 0.7; }
1825
+ </style>
1826
+ </head>
1827
+ <body>
1828
+ <form id="preferences" hidden>
1829
+ <label>Items <input type="range" name="count" min="1" max="20" value="5" /></label>
1830
+ </form>
1831
+ <div class="blog">
1832
+ <p class="state waiting">Loading…</p>
1833
+ <p class="state empty" hidden>Nothing posted yet.</p>
1834
+ <p class="state failed" role="alert" hidden>Could not load the blog.</p>
1835
+ <ul class="posts" hidden></ul>
1836
+ <template><li class="post"><a class="ext-link"></a></li></template>
1837
+ </div>
1838
+ <script>
1839
+ const MyBlog = { feed: 'https://example.com/feed.xml' };
1840
+ MyBlog.show = (state) => {
1841
+ for (const el of widget.body.querySelectorAll('.state')) el.hidden = !el.classList.contains(state);
1842
+ };
1843
+ MyBlog.draw = (feed) => {
1844
+ const list = widget.body.querySelector('.posts');
1845
+ const row = widget.body.querySelector('template').content.firstElementChild;
1846
+ const items = feed.items.slice(0, widget.settings.get('count'));
1847
+ list.replaceChildren(
1848
+ ...items.map((item) => {
1849
+ const li = row.cloneNode(true);
1850
+ const a = li.querySelector('a');
1851
+ a.href = item.url;
1852
+ a.textContent = item.title || item.url;
1853
+ return li;
1854
+ }),
1855
+ );
1856
+ list.hidden = !items.length;
1857
+ MyBlog.show(items.length ? 'none' : 'empty');
1858
+ widget.setMaxValue('count', feed.items.length);
1859
+ };
1860
+ MyBlog.load = (e, fresh) =>
1861
+ widget.fetchFeed(MyBlog.feed, { signal: e.signal, fresh }).then(MyBlog.draw, (err) => {
1862
+ // A failed refresh keeps what's shown; with nothing shown, it says so.
1863
+ if (err.name !== 'AbortError' && !widget.body.querySelector('.post')) MyBlog.show('failed');
1864
+ });
1865
+ widget.addEventListener('load', (e) => {
1866
+ const list = widget.body.querySelector('.posts');
1867
+ list.addEventListener('click', (ev) => {
1868
+ const a = ev.target.closest('a');
1869
+ if (!a) return;
1870
+ ev.preventDefault();
1871
+ widget.openURL(a.href);
1872
+ });
1873
+ widget.readItems(list, '.post');
1874
+ e.waitUntil(MyBlog.load(e, false));
1875
+ });
1876
+ widget.addEventListener('refresh', (e) => e.waitUntil(MyBlog.load(e, true)));
1877
+ </script>
1878
+ </body>
1879
+ </html>
1880
+ ```
1881
+
1882
+ **Example 6.** A game: a sliding puzzle, its board one Tab stop whose arrow keys slide a tile into the space (7.3.1),
1883
+ its nine tiles the skeleton's buttons relabeled at each move; a game in progress kept in a hidden setting (7.8), read
1884
+ defensively; the keyboard's help as the board's description, a win announced by a status line (section 14).
1885
+
1886
+ ```html
1887
+ <!doctype html>
1888
+ <html lang="en">
1889
+ <head>
1890
+ <script src="https://startside.app/swa/1.0/runtime.js"></script>
1891
+ <title>8 Puzzle</title>
1892
+ <meta name="description" content="The 3 by 3 sliding number puzzle." />
1893
+ <meta name="category" content="Games" />
1894
+ <style>
1895
+ .puzzle { padding: 10px; }
1896
+ .board { display: grid; grid-template-columns: repeat(3, 1fr); gap: 6px; max-width: 300px; aspect-ratio: 1; margin: 8px auto; }
1897
+ .board button {
1898
+ font: 700 28px system-ui, sans-serif;
1899
+ border: 0;
1900
+ border-radius: 6px;
1901
+ background: light-dark(#fffaf0, #3a4552);
1902
+ color: light-dark(#293543, #f2f4f6);
1903
+ }
1904
+ .board:focus-visible { outline: 3px solid #1877d2; outline-offset: 3px; }
1905
+ .board button.hole { visibility: hidden; }
1906
+ .help { font-size: 12px; text-align: center; margin: 0; }
1907
+ </style>
1908
+ </head>
1909
+ <body>
1910
+ <form id="preferences" hidden>
1911
+ <input type="hidden" name="game" value="" />
1912
+ </form>
1913
+ <div class="puzzle">
1914
+ <p>Moves: <strong class="moves">0</strong> <button type="button" class="new">New game</button></p>
1915
+ <!-- One Tab stop: the board; the arrows slide a tile, a click too. The tiles are out of the Tab order. -->
1916
+ <div class="board" role="group" tabindex="0" aria-label="Sliding puzzle" aria-describedby="puzzle-help">
1917
+ <button type="button" tabindex="-1"></button><button type="button" tabindex="-1"></button><button type="button" tabindex="-1"></button>
1918
+ <button type="button" tabindex="-1"></button><button type="button" tabindex="-1"></button><button type="button" tabindex="-1"></button>
1919
+ <button type="button" tabindex="-1"></button><button type="button" tabindex="-1"></button><button type="button" tabindex="-1"></button>
1920
+ </div>
1921
+ <p id="puzzle-help" class="help">Arrow keys slide a tile into the space.</p>
1922
+ <p class="status" role="status">Slide the tiles into number order.</p>
1923
+ </div>
1924
+ <script>
1925
+ const Puzzle = { order: [1, 2, 3, 4, 5, 6, 7, 8, 0] };
1926
+ // The places a tile at `i` can slide to.
1927
+ Puzzle.next = (i) => [i > 2 && i - 3, i < 6 && i + 3, i % 3 > 0 && i - 1, i % 3 < 2 && i + 1].filter((n) => n !== false);
1928
+ Puzzle.won = () => Puzzle.game.tiles.every((n, i) => n === Puzzle.order[i]);
1929
+ // Saved data outlives the code that wrote it: read defensively (7.8).
1930
+ Puzzle.saved = () => {
1931
+ try {
1932
+ const g = JSON.parse(widget.settings.get('game') || 'null');
1933
+ const ok = g && Array.isArray(g.tiles) && new Set(g.tiles).size === 9 && g.tiles.every((n) => Number.isInteger(n) && n >= 0 && n <= 8);
1934
+ return ok && Number.isInteger(g.moves) && g.moves >= 0 ? g : null;
1935
+ } catch {
1936
+ return null;
1937
+ }
1938
+ };
1939
+ // A game in progress is a setting, hidden (7.8): saved without a refresh.
1940
+ Puzzle.save = () => widget.settings.set('game', JSON.stringify(Puzzle.game));
1941
+ Puzzle.say = (text) => (widget.body.querySelector('.status').textContent = text);
1942
+ Puzzle.draw = () => {
1943
+ Puzzle.game.tiles.forEach((n, i) => {
1944
+ const b = Puzzle.buttons[i];
1945
+ b.textContent = n ? String(n) : '';
1946
+ b.classList.toggle('hole', !n);
1947
+ b.setAttribute('aria-label', n ? 'Tile ' + n : 'Empty');
1948
+ });
1949
+ widget.body.querySelector('.moves').textContent = String(Puzzle.game.moves);
1950
+ };
1951
+ Puzzle.move = (i) => {
1952
+ const tiles = Puzzle.game.tiles;
1953
+ const hole = tiles.indexOf(0);
1954
+ if (Puzzle.won() || !Puzzle.next(hole).includes(i)) return;
1955
+ [tiles[hole], tiles[i]] = [tiles[i], tiles[hole]];
1956
+ Puzzle.game.moves++;
1957
+ Puzzle.draw();
1958
+ Puzzle.save();
1959
+ if (Puzzle.won()) Puzzle.say('Solved in ' + Puzzle.game.moves + ' moves.');
1960
+ };
1961
+ Puzzle.newGame = () => {
1962
+ const tiles = Puzzle.order.slice();
1963
+ // Legal moves from the solved board: always solvable.
1964
+ for (let k = 0; k < 200; k++) {
1965
+ const hole = tiles.indexOf(0);
1966
+ const next = Puzzle.next(hole);
1967
+ const i = next[Math.floor(Math.random() * next.length)];
1968
+ [tiles[hole], tiles[i]] = [tiles[i], tiles[hole]];
1969
+ }
1970
+ Puzzle.game = { tiles, moves: 0 };
1971
+ if (Puzzle.won()) return Puzzle.newGame();
1972
+ Puzzle.draw();
1973
+ Puzzle.save();
1974
+ Puzzle.say('Slide the tiles into number order.');
1975
+ };
1976
+ // Wired once, on the first load; a refresh only draws again what's saved.
1977
+ widget.addEventListener('load', () => {
1978
+ Puzzle.buttons = [...widget.body.querySelectorAll('.board button')];
1979
+ const board = widget.body.querySelector('.board');
1980
+ board.addEventListener('click', (e) => {
1981
+ const b = e.target.closest('button');
1982
+ if (b) Puzzle.move(Puzzle.buttons.indexOf(b));
1983
+ // The focus stays on the board, the one Tab stop, not on a tile.
1984
+ board.focus();
1985
+ });
1986
+ // An arrow slides the tile on that side of the space towards it: ArrowUp moves the tile below the space up.
1987
+ const from = { ArrowUp: 3, ArrowDown: -3, ArrowLeft: 1, ArrowRight: -1 };
1988
+ board.addEventListener('keydown', (e) => {
1989
+ if (!(e.key in from)) return;
1990
+ e.preventDefault();
1991
+ const hole = Puzzle.game.tiles.indexOf(0);
1992
+ const i = hole + from[e.key];
1993
+ if (Puzzle.next(hole).includes(i)) Puzzle.move(i);
1994
+ });
1995
+ widget.body.querySelector('.new').addEventListener('click', Puzzle.newGame);
1996
+ Puzzle.game = Puzzle.saved();
1997
+ if (Puzzle.game) Puzzle.draw();
1998
+ else Puzzle.newGame();
1999
+ });
2000
+ widget.addEventListener('refresh', () => {
2001
+ Puzzle.game = Puzzle.saved() || Puzzle.game;
2002
+ Puzzle.draw();
2003
+ });
2004
+ </script>
2005
+ </body>
2006
+ </html>
2007
+ ```
2008
+
2009
+ **Example 7.** A small application: a to-do list kept with the widget (a hidden setting, 7.8), its rows from a
2010
+ `template`, filled with text (what's typed is never markup), one listener on the list for every row; the browser's own
2011
+ controls for the keyboard (a form submitted by Enter, checkboxes); the focus moved to the next row when one is removed,
2012
+ and each change announced. An action of its own in the options menu (7.13), declared in the file: *Remove done items*,
2013
+ greyed until an item is done, the host asking before it runs.
2014
+
2015
+ ```html
2016
+ <!doctype html>
2017
+ <html lang="en">
2018
+ <head>
2019
+ <script src="https://startside.app/swa/1.0/runtime.js"></script>
2020
+ <title>To Do</title>
2021
+ <meta name="description" content="A short list of things to do." />
2022
+ <meta name="category" content="Tools" />
2023
+ <style>
2024
+ .todo { padding: 8px 10px; }
2025
+ .todo form { display: flex; gap: 6px; }
2026
+ .todo form input { flex: 1; min-width: 0; font: inherit; padding: 4px 6px; }
2027
+ .todo ul { list-style: none; margin: 8px 0 0; padding: 0; }
2028
+ .todo ul[hidden], .todo .empty[hidden] { display: none; }
2029
+ .todo li { display: flex; align-items: center; gap: 6px; padding: 3px 0; }
2030
+ .todo li label { flex: 1; min-width: 0; overflow-wrap: anywhere; }
2031
+ .todo li.done label { text-decoration: line-through; opacity: 0.7; }
2032
+ .todo .remove { border: 0; background: none; font: inherit; cursor: pointer; padding: 2px 6px; }
2033
+ .todo .empty { margin: 8px 0 0; color: var(--muted, #6b6b6b); }
2034
+ .todo .visually-hidden { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }
2035
+ </style>
2036
+ </head>
2037
+ <body>
2038
+ <form id="preferences" hidden>
2039
+ <input type="hidden" name="items" value="[]" />
2040
+ </form>
2041
+ <menu id="actions" hidden>
2042
+ <button type="button" name="clear" data-icon="clear" data-confirm="Remove the done items?" disabled>Remove done items</button>
2043
+ </menu>
2044
+ <div class="todo">
2045
+ <form class="add">
2046
+ <label class="visually-hidden">New item <input type="text" name="text" maxlength="200" autocomplete="off" required /></label>
2047
+ <button type="submit">Add</button>
2048
+ </form>
2049
+ <ul hidden></ul>
2050
+ <p class="empty">Nothing to do.</p>
2051
+ <template>
2052
+ <li><label><input type="checkbox" /> <span class="text"></span></label><button type="button" class="remove">×</button></li>
2053
+ </template>
2054
+ <p class="visually-hidden" role="status"></p>
2055
+ </div>
2056
+ <script>
2057
+ const Todo = {};
2058
+ // The list is the widget's own, saved with it: a setting, hidden (7.8). Read defensively: saved data outlives code.
2059
+ Todo.read = () => {
2060
+ try {
2061
+ const v = JSON.parse(widget.settings.get('items') || '[]');
2062
+ return Array.isArray(v) ? v.filter((x) => x && typeof x.text === 'string').map((x) => ({ text: x.text.slice(0, 200), done: x.done === true })) : [];
2063
+ } catch {
2064
+ return [];
2065
+ }
2066
+ };
2067
+ Todo.save = () => widget.settings.set('items', JSON.stringify(Todo.items));
2068
+ Todo.say = (text) => (widget.body.querySelector('[role="status"]').textContent = text);
2069
+ // Drawn from the template, each row's text by textContent; the rows replaced, the form and the focus on it kept.
2070
+ Todo.draw = () => {
2071
+ const list = widget.body.querySelector('ul');
2072
+ const row = widget.body.querySelector('template').content.firstElementChild;
2073
+ list.replaceChildren(
2074
+ ...Todo.items.map((item, i) => {
2075
+ const li = row.cloneNode(true);
2076
+ li.dataset.index = String(i);
2077
+ li.classList.toggle('done', item.done);
2078
+ li.querySelector('.text').textContent = item.text;
2079
+ li.querySelector('input').checked = item.done;
2080
+ li.querySelector('.remove').setAttribute('aria-label', 'Remove ' + item.text);
2081
+ return li;
2082
+ }),
2083
+ );
2084
+ list.hidden = !Todo.items.length;
2085
+ widget.body.querySelector('.empty').hidden = !!Todo.items.length;
2086
+ Todo.actions();
2087
+ };
2088
+ // The menu's action follows the list: usable once an item is done (7.13), said again whenever that changes.
2089
+ Todo.actions = () => widget.setActionStates({ clear: { disabled: !Todo.items.some((item) => item.done) } });
2090
+ // Wired once, on the first load: one listener on the list for every row's checkbox and button.
2091
+ widget.addEventListener('load', () => {
2092
+ Todo.items = Todo.read();
2093
+ const form = widget.body.querySelector('form.add');
2094
+ const field = form.querySelector('input');
2095
+ form.addEventListener('submit', (e) => {
2096
+ e.preventDefault();
2097
+ const text = field.value.trim();
2098
+ if (!text) return;
2099
+ Todo.items.push({ text, done: false });
2100
+ Todo.save();
2101
+ Todo.draw();
2102
+ field.value = '';
2103
+ Todo.say('Added: ' + text);
2104
+ });
2105
+ const list = widget.body.querySelector('ul');
2106
+ list.addEventListener('change', (e) => {
2107
+ const li = e.target.closest('li');
2108
+ if (!li) return;
2109
+ const item = Todo.items[Number(li.dataset.index)];
2110
+ item.done = e.target.checked;
2111
+ li.classList.toggle('done', item.done);
2112
+ Todo.save();
2113
+ Todo.actions();
2114
+ });
2115
+ list.addEventListener('click', (e) => {
2116
+ const button = e.target.closest('.remove');
2117
+ if (!button) return;
2118
+ const i = Number(button.closest('li').dataset.index);
2119
+ const [gone] = Todo.items.splice(i, 1);
2120
+ Todo.save();
2121
+ Todo.draw();
2122
+ // The focus goes to the next row's button, else the previous one's, else the field: never lost.
2123
+ const buttons = list.querySelectorAll('.remove');
2124
+ (buttons[i] || buttons[i - 1] || field).focus();
2125
+ Todo.say('Removed: ' + gone.text);
2126
+ });
2127
+ Todo.draw();
2128
+ });
2129
+ // Chosen in the options menu, and confirmed there: the host asked the question the file declares.
2130
+ widget.addEventListener('action', (event) => {
2131
+ if (event.detail.id !== 'clear') return;
2132
+ const before = Todo.items.length;
2133
+ Todo.items = Todo.items.filter((item) => !item.done);
2134
+ Todo.save();
2135
+ Todo.draw();
2136
+ Todo.say('Removed ' + (before - Todo.items.length) + ' done');
2137
+ });
2138
+ widget.addEventListener('refresh', () => {
2139
+ Todo.items = Todo.read();
2140
+ Todo.draw();
2141
+ });
2142
+ </script>
2143
+ </body>
2144
+ </html>
2145
+ ```
2146
+
2147
+ ## Appendix B. Changes from UWA 1.2.4
2148
+
2149
+ *This appendix is non-normative.*
2150
+
2151
+ | | UWA 1.2.4 | SWA 1.0 |
2152
+ |---|---|---|
2153
+ | File | XHTML, well-formed XML, a namespace | HTML, `<name>.swa.html` |
2154
+ | Settings | `widget:preferences` (XML) | the settings form (HTML) |
2155
+ | Setting types | text, password, hidden, boolean, list, range | the same, and url, number, text areas |
2156
+ | Runtime | two tags from netvibes.com | one script, `/swa/1.0/runtime.js` |
2157
+ | Rendering | inline or framed, by platform | framed and sandboxed, or on its own page; no inline mode |
2158
+ | `openURL` | a new window | the host's reader |
2159
+ | Storage | the widget's data; client storage engines | settings, memory, stored data; never the frame's |
2160
+ | Requests | GET and POST through proxies, by callback | `widget.fetch`, a promise of a `Response`, GET through the host; the browser's `fetch` to `https` |
2161
+ | Events | callbacks assigned as properties, one per name (and `setCallback`) | `EventTarget` only: `addEventListener`, any number of listeners, `waitUntil`; no callbacks |
2162
+ | Feeds | UWA's feed object (`getFeed`) | `widget.fetchFeed`, a promise of a JSON Feed 1.1, kept by the host; UWA's stay with UWA files |
2163
+ | Added | | the reader, read state, grips, kept content, sound, video, pictures, sharing, adding widgets, maximizing, accounts, colors and icon at run time, declared feeds, dark looks |
2164
+ | Built-in objects | element, Array, String and Function extensions | none: the DOM's and ECMAScript's own (UWA's kept for UWA files) |
2165
+ | Removed | | search events, keyboard action, stars, TabView, client storage engines, POST through the proxy, Flash, platform compilers |
2166
+
2167
+ ## Appendix C. Implementation status and features at risk
2168
+
2169
+ *This appendix is non-normative.* Startside implements this specification (November 3, 2026: keys for `.swa.html` and `.uwa.xhtml` files, `callback` limited to `on` names, the events of 7.6 and the activation check of 6.7 added; November 4: UWA's API, globals and extensions of built-in objects in UWA files' realms only, section 9, events only, `widget.fetch` and `widget.fetchFeed`, then `widget` with this interface's members only, its readonly attributes read-only, checked against the types of Appendix F), except:
2170
+
2171
+ | Feature | Status |
2172
+ |---|---|
2173
+ | `Widget` as an `EventTarget` (7.6) | listeners, `once`, `capture`, `signal`, `WidgetEvent`, `waitUntil` and a cancelable `readall` implemented; `widget` is an `EventTarget` (`widget instanceof EventTarget`), delegating to one of its own, so an event's `target` is that object, not `widget`; there is no `Widget` interface object |
2174
+ | `apiVersion` `1.0` | read as any metadata |
2175
+ | Readonly attributes and `FrozenArray` (7.1) | accessors without a setter, or non-writable properties, on `widget` itself (not on a `Widget` prototype); `preferences` a frozen array of frozen copies, made again when the declared settings change, so not the same array across such a change |
2176
+ | Starting on its own page (6.6, 10.3) | the widget code runs as the page reads it, before `widget.body` is set: a widget finds its parts in `load` (7.3.1), where every environment has it |
2177
+ | `maxlength` and `data-file` on a `hidden` control (5.3) | added November 8, 2026 for the Recipe widget (a Cooklang text in a link, a `.cook` file opened): implemented in Startside only; `data-file` read from the file by the host's catalogue, the first widget declaring an extension taking it, text only, 16,000 characters at most |
2178
+ | Host limits (unspecified) | a framed widget's settings: a value of 20,000 characters, a name of 100, all of them 100,000 together (a value over isn't kept; the widget's console says so); read keys over 2000 characters dropped; feeds cut to 99 items and an item's HTML to 120,000 characters; the unread count shown up to 99; the reader's list 500 items, titles 300 and content 200,000 characters; an added widget's file name 40 characters |
2179
+ | The keyboard coming into a widget (6.8) | implemented in Startside (November 13, 2026): Enter on a widget's title bar moves the focus in, by `autofocus` and the steps of 6.8; an uncancelled Escape gives it back, an uncancelled arrow goes on to the next widget; a game controller read by the page is given as arrow keys, Enter and Escape. On a widget's own page there is no other widget: the browser's own `autofocus` applies |
2180
+ | A widget's own actions and `saveFile` (7.13) | implemented in Startside (November 12, 2026): actions declared in `<menu id="actions" hidden>`, listed in the options menu, `setActionStates`, the `action` event, `data-confirm` asked by the host, and one file per choice through `saveFile` (8 MiB at most, the extension among the action's `data-save` and the host's allow-list). On a widget's own page the runtime's menu lists them the same way. Used by the Recipe (Reset, Download as .cook), Dial Slate (Reset), Bluesky and Mastodon (Disconnect); Example 7 declares one |
2181
+ | A picture's credit in fields (7.12) | implemented in Startside (November 13, 2026): `PhotoCredit`, schema.org's `ImageObject` property names, or a plain string read as `creditText`; shared with the picture as text |
2182
+
2183
+ The runtime is served at `https://startside.app/swa/1.0/runtime.js` (one minified script, its styles in it, with none of
2184
+ UWA's API, globals or extensions of built-in objects: it runs SWA files only); a Startside
2185
+ page skips it, and its catalogue lists the files that load it. The same runtime and types make the npm package
2186
+ `@startside/swa` (1.0.0 published November 8, 2026; 1.0.1 adds this specification, the quickstart and the guide for
2187
+ agents in Markdown, and the command `validate` and `inline`: Appendix F; 1.0.2, November 16, the API's additions since,
2188
+ declared actions and saved files (7.13), a photo's zoom and credit (7.12), and its types corrected), served by jsDelivr and unpkg (4.3). jsDelivr keeps a
2189
+ range's file (`@1`) up to 12 hours and lets a browser keep it up to 7 days, an exact version's for good; unpkg sends
2190
+ `@1` on to the exact version: a runtime fix reaches a CDN address within those times, startside.app's at once. Startside's own widgets are 57 SWA files (51 of
2191
+ them its UWA widgets, rewritten November 11, 2026), 29 RWA files and one UWA 1.2 file (xkcd), as of November 15, 2026; Appendix A's first example is
2192
+ an SWA one.
2193
+
2194
+ ## Appendix D. IDL Index
2195
+
2196
+ *This appendix is non-normative.* The interfaces defined here: `Widget` (7.1), `WidgetEvent` (7.6.1); the dictionaries `WidgetEnvironment`,
2197
+ `WidgetSetting`, `WidgetSettingOption` (7.2), `ChromeColorOptions` (7.4), `CountGripOptions`, `HeightGripOptions` (7.7),
2198
+ `ReadItemsOptions` (7.10), `ReaderItem`, `OpenItemsOptions` (7.11),
2199
+ `PlayAudioOptions`, `AudioState`, `AudioControls`, `AudioInfo`, `VideoSpec`, `VideoState`, `PhotoSpec` (7.12),
2200
+ `ShareData`, `AddWidgetSpec`, `WidgetActionState` (7.13), `WidgetEventInit` (7.6.1), `FetchFeedOptions` (8.2); the callbacks `ReadKey` (7.10) and `DragWidgetCallback` (7.13); the typedef `ContentFeed` (8.5); the mixin `WidgetElement` (11.2, for UWA files).
2201
+
2202
+ ## Appendix E. Open issues
2203
+
2204
+ *This appendix is non-normative.* Questions this draft leaves open, most raised by a review of the 3 November 2026
2205
+ draft. Each is to be resolved before the specification is considered complete.
2206
+
2207
+ <a id="issue-1"></a>**Issue 1. The sandbox and Content Security Policy profile.** Section 10.1 names the sandbox, the opaque origin and `connect-src https:`, but not the full profile: the `sandbox` tokens, the policy for scripts, images, media, frames, forms and navigation, the referrer policy. A second host needs them to give the same isolation. Distinguish what is prevented (a request) from what is only hidden (its response).
2208
+
2209
+ <a id="issue-2"></a>**Issue 2. Capabilities and the message protocol.** Section 6.7 now tells a focus given from a focus taken by what the host sees (the pointer over the frame, a Tab, its own clicks and keys), which leaves a frame focusing itself while the pointer rests over it and the person types on the host's page, and refuses a tap within 5 seconds of a tap on the page. Only the browser knows where an activation came from: bind activation-gated requests to it if the platform comes to expose it to an embedder, or to a host-owned confirmation for the operations that warrant one (adding a widget), with expiry and consumption. The host checks a message's window, instance and fields (10.1), which says who sent it, not what it may do. Define the capabilities a frame holds (its file, its trust, its account, its services), how each request is authorized, how stale messages are rejected, and the messages between frame and host: events, their acknowledgement, the end of a load (7.6.3), the runtime authenticating the host's messages.
2210
+
2211
+ <a id="issue-3"></a>**Issue 3. Core and optional members.** Section 2 lets a host implement part of section 7, and 7.14 says only `addWidget` may be absent. Define a mandatory core (content, settings, events, data) and named optional capabilities, each with its presence test and fallback.
2212
+
2213
+ <a id="issue-4"></a>**Issue 4. The load state machine.** Section 6.6 ends a load on `setBody`, an error, its promises, a 20-second limit, and requests in flight. Define one state machine: a load's generation, the precedence of its endings, whether drawing kept content ends it, whether `loadcomplete` follows dispatch or completion, and what a refresh during a load does.
2214
+
2215
+ <a id="issue-5"></a>**Issue 5. Asynchronous errors.** Define how rejected promises, errors in `fetch` and `draw` callbacks and in periodicals are reported, their effect on the load and on what is shown, and whether a failing script stops the scripts after it and the `load` event. Error messages are shown as text.
2216
+
2217
+ <a id="issue-6"></a>**Issue 6. Scripts.** Define module scripts, `async` and `defer`, top-level `await`, a library that fails to load, the base URL, event-handler attributes in the initial content, and how widget code is scoped inline, where several widgets share a page.
2218
+
2219
+ <a id="issue-7"></a>**Issue 7. Settings: edge cases and applying them.** Define empty and multiple `select`s, duplicate options, disabled controls, `step="any"`, malformed numbers, labels with several `label`s; the timing of a pause and of grouping; the precedence of `livePreferences`, `data-commit` and the type; the grammar of `data-when`; what applying a password does (an empty field keeping the stored one?); the validation of `url` and `number` values against their `step`; whether `setValue` accepts undeclared names, validates, or fires an event.
2220
+
2221
+ <a id="issue-8"></a>**Issue 8. Passwords on every path.** Section 6.5 keeps a password's value from a framed widget. Name every path it must not take: `preferences`, `getPreference`, restored values, the declared feed's template, shared links, diagnostics; and whether a file may declare a password's default.
2222
+
2223
+ <a id="issue-9"></a>**Issue 9. URLs, proxies and the fetch relay.** Define one URL resolution and authorization algorithm (what a relative URL resolves against, which of the host's addresses are public services), the proxies' address checks (resolved addresses, IPv4 and IPv6, redirects, credentials in URLs), and the subset of Fetch the relay supports: methods, bodies, headers, aborts, redirects, response URLs, CORS.
2224
+
2225
+ <a id="issue-10"></a>**Issue 10. `widget.fetch`'s and `fetchFeed`'s contracts.** Define which `RequestInit` members are honoured or refused, the status and `statusText` of a `Response` for an HTTP error the proxy reports, the bounds of the retries after a failure, binary bodies and response headers (not relayed in this version), and `fetchFeed`'s refresh behind a stale copy (once per feed, its failure silent).
2226
+
2227
+ <a id="issue-11"></a>**Issue 11. The content feed's schema.** Give the feed and item schemas: the JSON Feed members kept, the types and meaning of `_myvibes`' members and of `_<site>`, and what normalization does with missing fields, malformed dates and duplicate ids. Then define `ContentFeed` in IDL.
2228
+
2229
+ <a id="issue-12"></a>**Issue 12. Kept content and stored data.** Define results of an older `fetchFeed` arriving after a newer one, eviction, one freshness boundary (5 minutes, inclusive or not); and for memory and stored data, the storage identity (what "the same file" is), JSON serialization, quotas, failures, deletion.
2230
+
2231
+ <a id="issue-13"></a>**Issue 13. `setHTML` and the HTML Sanitizer API.** UWA's `setHTML(html)` (11.2) inserts markup as given; browsers now define `Element.prototype.setHTML(html, options)`, which sanitizes it. UWA files keep UWA's, which replaces the browser's in their realm. Decide whether a UWA file's `setHTML` should become the browser's, sanitizing, as UWA widgets never pass it fetched markup by design. In an SWA widget's realm UWA's must never replace the browser's (section 9): a runtime shared by both formats installs it only for UWA files.
2232
+
2233
+ <a id="issue-14"></a>**Issue 14. Members' algorithms and states.** Many members are described, not specified: the media states' initial values, the reader's index bounds, the grips' geometry, read items' marking, `setSearchResultCount`. Give each an algorithm or a state table, closed value sets as enums, and say which state fields are always present. Add a table of the activation-gated operations (`openPhoto`, `openFull`, `pauseAudio`?), and say whether `setMaxValue` fires `updatepreferences`.
2234
+
2235
+ <a id="issue-15"></a>**Issue 15. Standalone security.** A file opened on its own runs with its own origin, or from disk: the frame's protections don't apply. State the standalone host's boundary, or run widget code in a sandboxed frame there too; and its passwords, accounts, activation and storage.
2236
+
2237
+ <a id="issue-16"></a>**Issue 16. What the host draws from widgets.** Titles, reader items, photo credits, audio artwork and other strings from widgets enter the host's own interface. Define which are text and which are markup, the markup and URL schemes allowed, how the reader frames pages, and that `frameable` never authorizes anything.
2238
+
2239
+ <a id="issue-17"></a>**Issue 17. Account data.** Make kept content and memory partitioned by account, removed or unreachable when an account is unlinked or changed; define who sees the page's audio state (its URL) and what a shared link may carry, on export and import.
2240
+
2241
+ <a id="issue-18"></a>**Issue 18. The host's accessibility.** Section 14 asks it of widgets; the host draws their settings, grips, counts, reader and windows. Define its duties: keyboard and non-drag alternatives (the grips), focus in and out of windows, names for frames, announcements, keeping the focus through a refresh.
2242
+
2243
+ <a id="issue-19"></a>**Issue 19. Inline styles.** *Resolved* (10.2): SWA has no inline mode; a widget's styles are its document's.
2244
+
2245
+ <a id="issue-20"></a>**Issue 20. Rebuilds, timers and overlapping refreshes.** Define a rebuild's teardown, a dashboard tab against a browser tab, a refresh interval of 0, two periodicals of one name, a refresh during a load, and refreshes while the page is hidden.
2246
+
2247
+ <a id="issue-21"></a>**Issue 21. Account services by declaration.** *Resolved* (10.4): bound to the declared service and the chosen account, for requests (an account named in the address or the body, or none: the chosen one) and sign-in windows; UWA files keep their access (a UWA compatibility profile, Issue 24, to say so).
2248
+
2249
+ <a id="issue-22"></a>**Issue 22. Direct requests and private networks.** *Resolved* (10.4, Networks): the relays refuse local and private addresses; a widget's own requests are the browser's to bound, and a host claims no more. Narrowing them by the frame's policy (images, media, scripts) is Issue 1's.
2250
+
2251
+ <a id="issue-23"></a>**Issue 23. Resource budgets.** A sandbox isolates data, not time or memory: a widget looping, allocating without end, or flooding the host with messages or requests slows the page. Define the host's budgets (messages and requests a second, stored data's size, memory) and what it does past them; stronger isolation (a process per widget) is a separate capability.
2252
+
2253
+ <a id="issue-24"></a>**Issue 24. A UWA compatibility profile.** Section 11 requires running UWA 1.2 files "with UWA's interface", and lists what a host may omit; the historical document (UWA 1.2.4) and Startside's runtime differ in more (UWA Appendix C, D). Define the profile a host implements for UWA files: required members, deviations, and which of the two documents prevails.
2254
+
2255
+ <a id="issue-25"></a>**Issue 25. Conversions and conformance vectors.** Section 2 asks Web IDL's argument conversions of a host implementing the interface in script; Startside's are written by hand (`setMaxValue` floors a number, `long` would convert it). Publish conversion vectors (missing arguments, null, infinities, out-of-range integers) and a host test suite that a second host can run, apart from a document checker, which would say what it covers and that "no finding" isn't "conforming".
2256
+
2257
+ <a id="issue-26"></a>**Issue 26. Handles a widget gets back.** `countGrip`, `heightGrip` and `readItems` return `undefined` in the IDL; Startside's return objects (`readItems(…).paint()`, `.stop()`) that RWA's components use. Define them, or keep them a host's private API.
2258
+
2259
+ <a id="issue-27"></a>**Issue 27. Freshness and cancellation, end to end.** `fetchFeed`'s `fresh` skips the widget's kept copy; the person's refresh also asks the host's proxy to skip its cache, which then answers a copy under 15 seconds old; aborting a request settles the widget's promise but doesn't stop the host's work. Define each intent (the widget's copy, the proxy's cache, the upstream request), how a request carries it, and cancellation through the relay.
2260
+
2261
+ <a id="issue-28"></a>**Issue 28. A widget file's identity.** A widget is known by its file name: a rename needs the host to migrate saved widgets. Consider a stable identifier in the file (`<meta name="id">`), with `version` and `author`.
2262
+
2263
+ <a id="issue-29"></a>**Issue 29. Widgets sharing a realm.** *Resolved* (10.2): SWA has no inline mode, so an SWA widget's realm is its own (section 9).
2264
+
2265
+ <a id="issue-30"></a>**Issue 30. The room a widget has.** A widget's height is its content's (7.3.2). Define whether a host tells a widget the room it has (a window shorter than the widget, a host that frames it at a fixed height: `widget.layout` or a `resize` event's `detail` with the width and the height available), and whether a widget may ask for more.
2266
+
2267
+ <a id="issue-31"></a>**Issue 31. Libraries from npm.** A framed widget's scripts may come from any `https` address today
2268
+ (4.8, 10.1 limits connections, not scripts), and nothing says how. Consider dependencies declared in an import map in
2269
+ the file, from one source (npm through jsDelivr's `/+esm`), at exact versions with integrity: a host can then read them
2270
+ without running the widget, the validator refuse a version that isn't pinned, the person be told code comes from
2271
+ elsewhere (Privacy), a host keep them offline and, later, serve them itself. Its plan: `docs/plans/swa-npm-dependencies.md`.
2272
+
2273
+ <a id="issue-32"></a>**Issue 32. A widget's own actions.** *Resolved* (7.13, November 12, 2026: actions declared in the file, `<menu id="actions">`, their state changed by `setActionStates`, the `action` event, an icon hint and a question the host asks; a first version made the list in script, `setActions`, dropped the same day for the declaration; then a file to keep, `data-save` and `saveFile`, answering a choice in the menu). Open: a list only known as the widget runs, should a widget need one; a download from a control of the widget's own (`saveFile` without `action`: a host dialog showing the final name, and a declaration for the whole widget); opening a file from the menu (the same extension syntax and limits, its own authorization: the host opening the picker from its own click). A widget's options menu (▾; on its own page, 10.3) holds the host's actions
2274
+ only (Refresh, Maximize, Mark all as read). Some actions are the widget's but don't belong in its body: the Recipe
2275
+ widget's *Start over*, which unticks everything and stops its timers, is a button at the bottom of the recipe for now
2276
+ (the Startside user, November 2026: "Start Over should be a widget action"). Consider actions a widget declares (in its
2277
+ metadata, or `widget.setActions([{ id, label }])` as its state changes) that the host lists in the menu with its own,
2278
+ and an `action` event carrying the `id` when one is chosen; a question it then asks stays in the widget's body.
2279
+
2280
+ ---
2281
+
2282
+ ## Appendix F. Tools for authors
2283
+
2284
+ *This appendix is non-normative.*
2285
+
2286
+ - **This specification, published.** `https://startside.app/swa/1.0/`, and as Markdown, `spec.md` beside it; *SWA in
2287
+ 60 lines* at `quickstart.html` (`quickstart.md`); for an agent, `agents.md`, short enough to read whole: the
2288
+ quickstart, these tools, the types and an index of this specification's sections.
2289
+ - **Types.** SWA 1.0's TypeScript types are served beside the runtime, at `https://startside.app/swa/1.0/swa.d.ts`:
2290
+ saved next to a widget's scripts, with `/// <reference path="swa.d.ts" />` (or a `jsconfig.json` naming it),
2291
+ `widget` is typed in an editor, its events with their `detail`, and what the host freezes read-only. The npm package
2292
+ `@startside/swa` carries them too: installed, `"types": ["@startside/swa"]` in a `tsconfig.json` or `jsconfig.json`'s
2293
+ `compilerOptions`.
2294
+ - **The npm package `@startside/swa`.** The runtime (`swa/1.0/runtime.js`, the text startside.app serves) and the types
2295
+ (`swa/1.0/swa.d.ts`), under the MIT licence; and, since 1.0.1, this specification, the quickstart and the guide for
2296
+ agents as published here (`swa/1.0/spec.md`, `quickstart.md`, `agents.md`), under CC BY 4.0, as they were at the
2297
+ package's release: for an author or an agent that can reach npm or a CDN but not this site
2298
+ (`https://cdn.jsdelivr.net/npm/@startside/swa@1/swa/1.0/agents.md`). Served by jsDelivr and unpkg (4.3), installed
2299
+ with `npm install @startside/swa`. Since 1.0.1 too, a command, for Node 20 or later, with nothing else to install:
2300
+ `validate` and `inline`, below.
2301
+ - **Checking a file.** `npx @startside/swa validate my-widget.swa.html` reads a widget file without running it, with no
2302
+ network: the file's name and document, its runtime tag, metadata and settings form, and its scripts against this
2303
+ API, UWA's members and globals named with what replaces them. Each finding is `file:line:col: error|warning:
2304
+ message`, citing its section; `--json` gives them as a list of `{ file, line, col, level, message }`. It exits 1 on
2305
+ an error. Run it after each edit: a file it passes can still fail as it runs, which only trying it shows.
2306
+ - **Trying a widget.** A widget file opened in a browser, from disk or any server, runs on its own page with the
2307
+ runtime its head loads (4.3): its options menu (▾) shows its title, color and settings, applied as they change, and
2308
+ its `fetch` and `fetchFeed` go through Startside's proxies, which answer any origin. Errors show in the widget and
2309
+ in the browser's console. `widget.html#mode=dark&width=300` opens it dark and 300 pixels wide (10.3), for a test or
2310
+ a screenshot, rather than reaching into the page's own menu and switches, which may change.
2311
+ - **A copy with the runtime inlined** (4.3), for a place that loads no script from another site: the file with its
2312
+ runtime tag replaced by `<script data-runtime="swa/1.0">` holding the text of `https://startside.app/swa/1.0/runtime.js`,
2313
+ fetched as the copy is made; nothing else changed. Make it again after the runtime changes, and keep the file that
2314
+ loads the runtime by its address as the widget's own. `npx @startside/swa inline my-widget.swa.html` writes that
2315
+ copy, `my-widget-inline.swa.html` (`-o` names another, never the file itself), with the package's runtime, its
2316
+ `data-host` kept, then checks it; `npx @startside/swa@latest` gets the latest release's runtime.
2317
+
2318
+ ## References
2319
+
2320
+ ### Normative references
2321
+
2322
+ - <a id="ref-csp"></a>**[CSP]** *Content Security Policy Level 3*. W3C. <https://www.w3.org/TR/CSP3/>
2323
+ - <a id="ref-css-cascade-5"></a>**[CSS-CASCADE-5]** *CSS Cascading and Inheritance Level 5*, cascade layers. W3C. <https://www.w3.org/TR/css-cascade-5/#layering>
2324
+ - <a id="ref-css-color-5"></a>**[CSS-COLOR-5]** *CSS Color Module Level 5*, `light-dark()`. W3C. <https://www.w3.org/TR/css-color-5/#light-dark>
2325
+ - <a id="ref-dom"></a>**[DOM]** *DOM Standard*. WHATWG. <https://dom.spec.whatwg.org/>
2326
+ - <a id="ref-fetch"></a>**[FETCH]** *Fetch Standard*. WHATWG. <https://fetch.spec.whatwg.org/>
2327
+ - <a id="ref-html"></a>**[HTML]** *HTML Standard*. WHATWG. <https://html.spec.whatwg.org/>
2328
+ - <a id="ref-infra"></a>**[INFRA]** *Infra Standard*. WHATWG. <https://infra.spec.whatwg.org/>
2329
+ - <a id="ref-jsonfeed"></a>**[JSONFEED]** M. Reece, B. Simmons. *JSON Feed Version 1.1*. <https://jsonfeed.org/version/1.1>
2330
+ - <a id="ref-rfc2119"></a>**[RFC2119]** S. Bradner. *Key words for use in RFCs to Indicate Requirement Levels*. BCP 14, RFC 2119, March 1997.
2331
+ <https://www.rfc-editor.org/rfc/rfc2119>
2332
+ - <a id="ref-rfc3339"></a>**[RFC3339]** G. Klyne, C. Newman. *Date and Time on the Internet: Timestamps*. RFC 3339, July 2002.
2333
+ <https://www.rfc-editor.org/rfc/rfc3339>
2334
+ - <a id="ref-rfc9309"></a>**[RFC9309]** M. Koster, G. Illyes, H. Zeller, L. Sassman. *Robots Exclusion Protocol*. RFC 9309, September 2022. <https://www.rfc-editor.org/rfc/rfc9309>
2335
+ - <a id="ref-rfc8174"></a>**[RFC8174]** B. Leiba. *Ambiguity of Uppercase vs Lowercase in RFC 2119 Key Words*. BCP 14, RFC 8174, May 2017.
2336
+ <https://www.rfc-editor.org/rfc/rfc8174>
2337
+ - <a id="ref-url"></a>**[URL]** *URL Standard*. WHATWG. <https://url.spec.whatwg.org/>
2338
+ - <a id="ref-uwa"></a>**[UWA]** *Universal Widget API (UWA) 1.2.4*, a consolidated edition, Startside, 2026. [uwa-spec.md](https://startside.app/uwa/1.2/spec.md)
2339
+ - <a id="ref-wcag22"></a>**[WCAG22]** *Web Content Accessibility Guidelines (WCAG) 2.2*. W3C Recommendation. <https://www.w3.org/TR/WCAG22/>
2340
+ - <a id="ref-webidl"></a>**[WEBIDL]** *Web IDL Standard*. WHATWG. <https://webidl.spec.whatwg.org/>
2341
+
2342
+ ### Informative references
2343
+
2344
+ - <a id="ref-aria-apg"></a>**[ARIA-APG]** *WAI-ARIA Authoring Practices Guide*. W3C.
2345
+ <https://www.w3.org/WAI/ARIA/apg/>
2346
+ - <a id="ref-rwa"></a>**[RWA]** *React Widget API (RWA) 1.0*. Startside. [docs/rwa-spec.md](https://startside.app/rwa/1.0/spec.md)
2347
+ - <a id="ref-w3c-widgets"></a>**[W3C-WIDGETS]** *Widget Interface*. W3C, 2013; obsolete since 2018. <https://www.w3.org/TR/widgets-apis/>
2348
+
2349
+ ## Acknowledgements
2350
+
2351
+ SWA keeps the interface of the Universal Widget API, designed at Netvibes; its 1.2 Working Draft was edited by Xavier
2352
+ Borderie and François Hodierne (2008).