@spartan-native/host-web 0.0.0-stage → 0.2.1
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.
- package/AGENTS.md +41 -0
- package/LICENSE +21 -0
- package/README.md +67 -2
- package/fesm2022/spartan-native-host-web.mjs +300 -0
- package/fesm2022/spartan-native-host-web.mjs.map +1 -0
- package/package.json +42 -3
- package/types/spartan-native-host-web.d.ts +47 -0
package/AGENTS.md
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
# AGENTS.md: @spartan-native/host-web
|
|
2
|
+
|
|
3
|
+
Instructions for AI coding agents building an Angular app with `@spartan-native/host-web`.
|
|
4
|
+
|
|
5
|
+
## What this package is
|
|
6
|
+
|
|
7
|
+
The `NativeHost` adapter for browsers and installed PWAs (Layer 04). It implements the contract from `@spartan-native/theme` using browser APIs only, and has no native side. Hand it to `provideSpartanNative()`, and the theme and every component follow the OS live.
|
|
8
|
+
|
|
9
|
+
```ts
|
|
10
|
+
import { provideSpartanNative } from '@spartan-native/theme';
|
|
11
|
+
import { webHost } from '@spartan-native/host-web';
|
|
12
|
+
|
|
13
|
+
providers: [provideSpartanNative({ host: webHost() })];
|
|
14
|
+
// in a desktop shell, fall back to it: isWails() ? wailsHost() : webHost()
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
## Public API (`import … from '@spartan-native/host-web'`)
|
|
18
|
+
|
|
19
|
+
| Symbol | Use |
|
|
20
|
+
| --- | --- |
|
|
21
|
+
| `webHost({ accent?, skin?, window? })` | The host. `accent` applies where the browser hides the OS accent, and `skin` forces a skin |
|
|
22
|
+
| `watchDisplayMode(cb)` / `readDisplayMode(win)` | `'browser' \| 'standalone' \| 'overlay'`. `overlay` means an installed PWA with Window Controls Overlay: use `<sn-title-bar windowControls="native">` |
|
|
23
|
+
| `fromClientHints()`, `fromUserAgent()` | Platform detection, exposed for tests |
|
|
24
|
+
|
|
25
|
+
## What the app gets
|
|
26
|
+
|
|
27
|
+
| Service | Available | Notes |
|
|
28
|
+
| --- | --- | --- |
|
|
29
|
+
| Appearance (scheme, contrast, motion, transparency, text size) | always | Live, through media queries |
|
|
30
|
+
| Accent | Firefox and Safari | Chromium hides the OS accent, so `systemAccent` is `'none'` there and the platform's stock accent is used. Offer an in-app accent picker: `theme.override({ accent })` |
|
|
31
|
+
| `window` | focus only | No `minimize`, `toggleMaximize` or `close`: the browser owns the window |
|
|
32
|
+
| `menus` | never | `<sn-menubar>` and `[snContextMenu]` draw in the page automatically |
|
|
33
|
+
| `dialogs` | Chromium (File System Access) | `openFile`, `saveFile`, `pickFolder` give a `PickedFile` with a `handle` and **no `path`**. There's no `message()`: use an `hlm-alert-dialog` |
|
|
34
|
+
| `notifications` | never | Not specified yet |
|
|
35
|
+
|
|
36
|
+
## Rules
|
|
37
|
+
|
|
38
|
+
1. Check before using an optional service: `host.dialogs?.openFile(…)`, `theme.capability('fileDialogs') !== 'none'`.
|
|
39
|
+
2. To read a picked file in the browser, use `(file.handle as FileSystemFileHandle).getFile()`. Don't expect `path`.
|
|
40
|
+
3. GNOME and KDE can't be told apart in a browser, so GTK is assumed. Let the user pick the skin, or pass `skin: 'qt'`.
|
|
41
|
+
4. Don't call `matchMedia`, `AccentColor` or the File System Access API directly in components. Use the theme service or the host.
|
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Roland Molnár
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,68 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @spartan-native/host-web
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
**Layer 04 · host adapter for browsers and installed PWAs.** It implements `NativeHost` from `@spartan-native/theme` with browser APIs only, so an app picks up the OS settings **live**: accent, light/dark, contrast, transparency, motion, text size and window focus.
|
|
4
|
+
|
|
5
|
+
> Status: **implemented**, and passes `@spartan-native/host-conformance`. Spec: [`07-host-adapters.md`](https://github.com/Spartan-Native/spartan-native/blob/main/docs/07-host-adapters.md).
|
|
6
|
+
|
|
7
|
+
```ts
|
|
8
|
+
// app.config.ts
|
|
9
|
+
import { webHost } from '@spartan-native/host-web';
|
|
10
|
+
import { provideSpartanNative } from '@spartan-native/theme';
|
|
11
|
+
|
|
12
|
+
export const appConfig: ApplicationConfig = {
|
|
13
|
+
providers: [provideSpartanNative({ host: webHost() })],
|
|
14
|
+
};
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
That's all: `SpartanNativeTheme`, the skins and every component now follow the OS. Overrides from an in-app setting still win (`theme.override({ scheme: 'dark' })`; `theme.followSystem()` drops them).
|
|
18
|
+
|
|
19
|
+
## What it reads
|
|
20
|
+
|
|
21
|
+
| Setting | Source | Live | Capability |
|
|
22
|
+
| --- | --- | --- | --- |
|
|
23
|
+
| Light / dark | `prefers-color-scheme` | ✓ | native |
|
|
24
|
+
| Contrast | `prefers-contrast: more`, `forced-colors: active` (Windows contrast themes) | ✓ | native |
|
|
25
|
+
| Reduce transparency | `prefers-reduced-transparency` (Chromium, Safari) | ✓ | partial |
|
|
26
|
+
| Reduce motion | `prefers-reduced-motion` | ✓ | — |
|
|
27
|
+
| Text size | the browser's default font size (`font-size: medium`) | ✓ ResizeObserver | partial |
|
|
28
|
+
| Accent | CSS `AccentColor` where the real OS accent is exposed (Firefox, Safari); otherwise `options.accent` or the platform's stock accent | on focus / tab visible | partial |
|
|
29
|
+
| Window focus | `focus`, `blur`, `visibilitychange` | ✓ | native |
|
|
30
|
+
| OS, version, skin | User-Agent Client Hints (Chromium: real Windows 10/11 and macOS versions), else the user-agent string | once | partial |
|
|
31
|
+
|
|
32
|
+
The other capabilities are reported honestly: `customTitleBar` (Window Controls Overlay), `notifications`, `taskbarProgress` (app badge) and `fileDialogs` (File System Access) are `partial` where the API exists, else `none`. Window materials, native menus and the Linux desktop are `none`.
|
|
33
|
+
|
|
34
|
+
Where the File System Access pickers exist (Chromium), `host.dialogs` opens and saves files and picks folders. You get a `handle` back instead of a path. There is no `message()`: browsers have no OS alert with custom buttons.
|
|
35
|
+
|
|
36
|
+
**Browser limits:**
|
|
37
|
+
|
|
38
|
+
- **Accent on Chromium (Chrome, Edge, Brave, Electron-free PWAs):** Chromium returns its own fixed blue for `AccentColor` (anti-fingerprinting), so the OS accent can't reach the page. The adapter detects it, reports `systemAccent: 'none'`, and uses the platform's stock accent. Offer an in-app accent picker (`theme.override({ accent })`). The desktop adapters (Wails, Tauri, Electron, Photino) will read the real accent natively.
|
|
39
|
+
- **Frozen versions:** without Client Hints, Windows and macOS versions are frozen in the user-agent string. Windows maps to the Windows 11 skin and macOS to macOS 26.
|
|
40
|
+
- **Linux desktop:** GNOME vs KDE is not visible to a web page, so GTK is assumed. Pass `skin: 'qt'` to override.
|
|
41
|
+
|
|
42
|
+
## Display mode (installed apps)
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { watchDisplayMode } from '@spartan-native/host-web';
|
|
46
|
+
|
|
47
|
+
const off = watchDisplayMode((mode) => …); // 'browser' | 'standalone' | 'overlay'
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
`'overlay'` means an installed app with Window Controls Overlay: the OS draws only the window buttons, and the app draws its title bar in `env(titlebar-area-*)`. Use it with `<sn-title-bar windowControls="native">` from `@spartan-native/desktop-ui`. The callback fires again when the user toggles the overlay.
|
|
51
|
+
|
|
52
|
+
## Options
|
|
53
|
+
|
|
54
|
+
```ts
|
|
55
|
+
webHost({
|
|
56
|
+
accent: '#9141ac', // when the browser doesn't expose the system accent
|
|
57
|
+
skin: 'gtk', // force a skin (e.g. from a user setting)
|
|
58
|
+
window, // another window / iframe, or a test double
|
|
59
|
+
});
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
## Tests
|
|
63
|
+
|
|
64
|
+
```bash
|
|
65
|
+
npx ng test host-web # the conformance suite + platform detection, accent, live media and focus changes
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
The spec drives a fake browser window (media queries, `AccentColor`, focus) and runs `describeHostConformance('webHost', …)`.
|
|
@@ -0,0 +1,300 @@
|
|
|
1
|
+
import { CAPABILITIES, normalizeHex, resolveSkin } from "@spartan-native/theme";
|
|
2
|
+
async function detectPlatform(nav) {
|
|
3
|
+
const uaData = nav.userAgentData;
|
|
4
|
+
if (uaData?.platform) {
|
|
5
|
+
let version;
|
|
6
|
+
try {
|
|
7
|
+
version = (await uaData.getHighEntropyValues?.(["platformVersion"]))?.platformVersion ?? null;
|
|
8
|
+
} catch {
|
|
9
|
+
version = null;
|
|
10
|
+
}
|
|
11
|
+
return fromClientHints(uaData.platform, version);
|
|
12
|
+
}
|
|
13
|
+
return fromUserAgent(nav.userAgent);
|
|
14
|
+
}
|
|
15
|
+
function info(os, version, confidence, skin) {
|
|
16
|
+
const base = {
|
|
17
|
+
os,
|
|
18
|
+
version,
|
|
19
|
+
build: null,
|
|
20
|
+
desktop: null
|
|
21
|
+
};
|
|
22
|
+
return {
|
|
23
|
+
...base,
|
|
24
|
+
skin: skin ?? resolveSkin(base),
|
|
25
|
+
confidence
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
function fromClientHints(platform, version) {
|
|
29
|
+
const major = version ? parseInt(version, 10) : NaN;
|
|
30
|
+
switch (platform.toLowerCase()) {
|
|
31
|
+
case "windows": return info("windows", version, version ? "exact" : "hint", Number.isFinite(major) && major > 0 && major < 13 ? "w10" : "win");
|
|
32
|
+
case "macos": return info("macos", version, version ? "exact" : "hint");
|
|
33
|
+
case "chrome os":
|
|
34
|
+
case "chromeos": return info("chromeos", version, "exact");
|
|
35
|
+
case "linux": return info("linux", version, "hint");
|
|
36
|
+
default: return info("unknown", version, "unknown");
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function fromUserAgent(ua) {
|
|
40
|
+
if (/Android|iPhone|iPad|iPod/i.test(ua)) return info("unknown", null, "unknown");
|
|
41
|
+
if (/Windows NT/i.test(ua)) return info("windows", null, "hint", "win");
|
|
42
|
+
if (/Mac OS X|Macintosh/i.test(ua)) return info("macos", null, "hint", "mac");
|
|
43
|
+
if (/CrOS/i.test(ua)) return info("chromeos", null, "hint");
|
|
44
|
+
if (/Linux/i.test(ua)) return info("linux", null, "hint");
|
|
45
|
+
return info("unknown", null, "unknown");
|
|
46
|
+
}
|
|
47
|
+
function supportsFilePickers(win) {
|
|
48
|
+
return !!win && "showOpenFilePicker" in win && "showSaveFilePicker" in win && "showDirectoryPicker" in win;
|
|
49
|
+
}
|
|
50
|
+
function toPickerTypes(filters = []) {
|
|
51
|
+
const matchesAll = filters.length === 0 || filters.some((f) => f.extensions.includes("*"));
|
|
52
|
+
return {
|
|
53
|
+
types: filters.filter((f) => !f.extensions.includes("*") && f.extensions.length > 0).map((f) => ({
|
|
54
|
+
description: f.name,
|
|
55
|
+
accept: { "application/octet-stream": f.extensions.map((e) => "." + e.replace(/^\./, "")) }
|
|
56
|
+
})),
|
|
57
|
+
excludeAcceptAllOption: !matchesAll
|
|
58
|
+
};
|
|
59
|
+
}
|
|
60
|
+
const picked = (handle) => ({
|
|
61
|
+
name: handle.name,
|
|
62
|
+
handle
|
|
63
|
+
});
|
|
64
|
+
async function orCancelled(run, cancelled) {
|
|
65
|
+
try {
|
|
66
|
+
return await run();
|
|
67
|
+
} catch (e) {
|
|
68
|
+
if (e instanceof DOMException && e.name === "AbortError") return cancelled;
|
|
69
|
+
throw e;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
function webDialogs(win) {
|
|
73
|
+
const pickers = win;
|
|
74
|
+
return {
|
|
75
|
+
openFile: (options = {}) => orCancelled(async () => {
|
|
76
|
+
return (await pickers.showOpenFilePicker({
|
|
77
|
+
multiple: !!options.multiple,
|
|
78
|
+
...toPickerTypes(options.filters)
|
|
79
|
+
})).map(picked);
|
|
80
|
+
}, []),
|
|
81
|
+
saveFile: (options = {}) => orCancelled(async () => picked(await pickers.showSaveFilePicker({
|
|
82
|
+
suggestedName: options.fileName,
|
|
83
|
+
...toPickerTypes(options.filters)
|
|
84
|
+
})), null),
|
|
85
|
+
pickFolder: () => orCancelled(async () => picked(await pickers.showDirectoryPicker()), null)
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
const STOCK_ACCENT = {
|
|
89
|
+
win: "#0078d4",
|
|
90
|
+
w10: "#0078d4",
|
|
91
|
+
mac: "#007aff",
|
|
92
|
+
macc: "#007aff",
|
|
93
|
+
gtk: "#3584e4",
|
|
94
|
+
qt: "#3daee9",
|
|
95
|
+
cros: "#0b57d0",
|
|
96
|
+
web: "#0078d4"
|
|
97
|
+
};
|
|
98
|
+
const CHROMIUM_FIXED_ACCENT = "#0075ff";
|
|
99
|
+
const QUERIES = {
|
|
100
|
+
dark: "(prefers-color-scheme: dark)",
|
|
101
|
+
moreContrast: "(prefers-contrast: more)",
|
|
102
|
+
forcedColors: "(forced-colors: active)",
|
|
103
|
+
reduceTransparency: "(prefers-reduced-transparency: reduce)",
|
|
104
|
+
reduceMotion: "(prefers-reduced-motion: reduce)"
|
|
105
|
+
};
|
|
106
|
+
function webHost(options = {}) {
|
|
107
|
+
const win = options.window ?? (typeof window !== "undefined" ? window : void 0);
|
|
108
|
+
const doc = win?.document;
|
|
109
|
+
const media = (q) => win?.matchMedia ? win.matchMedia(q) : null;
|
|
110
|
+
const matches = (q) => media(q)?.matches ?? false;
|
|
111
|
+
const supportsMedia = (q) => {
|
|
112
|
+
const m = media(q);
|
|
113
|
+
return !!m && m.media !== "not all";
|
|
114
|
+
};
|
|
115
|
+
const supportsAccentColor = !!(win?.CSS)?.supports?.("color", "AccentColor");
|
|
116
|
+
let platformPromise = null;
|
|
117
|
+
const platform = () => platformPromise ??= detectPlatform(win?.navigator ?? { userAgent: "" }).then((p) => options.skin ? {
|
|
118
|
+
...p,
|
|
119
|
+
skin: options.skin
|
|
120
|
+
} : p);
|
|
121
|
+
const probe = doc ? createProbe(doc) : null;
|
|
122
|
+
const systemAccent = () => {
|
|
123
|
+
if (!supportsAccentColor || !probe || !win) return null;
|
|
124
|
+
const hex = rgbToHex(win.getComputedStyle(probe.accent).color);
|
|
125
|
+
return hex && hex !== CHROMIUM_FIXED_ACCENT ? hex : null;
|
|
126
|
+
};
|
|
127
|
+
const exposesAccent = systemAccent() !== null;
|
|
128
|
+
const readAccent = (skin) => systemAccent() ?? normalizeHex(options.accent ?? STOCK_ACCENT[skin] ?? STOCK_ACCENT["web"]);
|
|
129
|
+
const readTextScale = () => {
|
|
130
|
+
const px = probe?.text.getBoundingClientRect().width ?? 16;
|
|
131
|
+
return px > 0 ? Math.round(px / 16 * 20) / 20 : 1;
|
|
132
|
+
};
|
|
133
|
+
const read = (skin) => ({
|
|
134
|
+
skin,
|
|
135
|
+
accent: readAccent(skin),
|
|
136
|
+
scheme: matches(QUERIES.dark) ? "dark" : "light",
|
|
137
|
+
contrast: matches(QUERIES.forcedColors) ? "forced" : matches(QUERIES.moreContrast) ? "more" : "normal",
|
|
138
|
+
reduceTransparency: matches(QUERIES.reduceTransparency),
|
|
139
|
+
reduceMotion: matches(QUERIES.reduceMotion),
|
|
140
|
+
textScale: readTextScale()
|
|
141
|
+
});
|
|
142
|
+
let skin = options.skin ?? "web";
|
|
143
|
+
let last = null;
|
|
144
|
+
const appearance = async () => {
|
|
145
|
+
skin = (await platform()).skin;
|
|
146
|
+
return last = read(skin);
|
|
147
|
+
};
|
|
148
|
+
const appearanceListeners = /* @__PURE__ */ new Set();
|
|
149
|
+
const notify = () => {
|
|
150
|
+
if (appearanceListeners.size === 0) return;
|
|
151
|
+
const next = read(skin);
|
|
152
|
+
if (last && sameAppearance(last, next)) return;
|
|
153
|
+
last = next;
|
|
154
|
+
appearanceListeners.forEach((cb) => cb(next));
|
|
155
|
+
};
|
|
156
|
+
let detach = null;
|
|
157
|
+
const attach = () => {
|
|
158
|
+
const offs = [];
|
|
159
|
+
for (const q of Object.values(QUERIES)) {
|
|
160
|
+
const m = media(q);
|
|
161
|
+
if (!m) continue;
|
|
162
|
+
m.addEventListener?.("change", notify);
|
|
163
|
+
offs.push(() => m.removeEventListener?.("change", notify));
|
|
164
|
+
}
|
|
165
|
+
if (probe && typeof ResizeObserver !== "undefined") {
|
|
166
|
+
const ro = new ResizeObserver(notify);
|
|
167
|
+
ro.observe(probe.text);
|
|
168
|
+
offs.push(() => ro.disconnect());
|
|
169
|
+
}
|
|
170
|
+
win?.addEventListener("focus", notify);
|
|
171
|
+
doc?.addEventListener("visibilitychange", notify);
|
|
172
|
+
offs.push(() => win?.removeEventListener("focus", notify), () => doc?.removeEventListener("visibilitychange", notify));
|
|
173
|
+
return () => offs.forEach((off) => off());
|
|
174
|
+
};
|
|
175
|
+
const focusListeners = /* @__PURE__ */ new Set();
|
|
176
|
+
const isFocused = () => doc ? doc.hasFocus() && doc.visibilityState !== "hidden" : true;
|
|
177
|
+
let focusDetach = null;
|
|
178
|
+
const onFocusEvent = () => {
|
|
179
|
+
const f = isFocused();
|
|
180
|
+
focusListeners.forEach((cb) => cb(f));
|
|
181
|
+
};
|
|
182
|
+
const level = (ok, yes = "partial") => ok ? yes : "none";
|
|
183
|
+
const nav = win?.navigator;
|
|
184
|
+
const support = {
|
|
185
|
+
systemAccent: level(exposesAccent),
|
|
186
|
+
colorScheme: level(supportsMedia(QUERIES.dark), "native"),
|
|
187
|
+
highContrast: level(supportsMedia(QUERIES.forcedColors) || supportsMedia(QUERIES.moreContrast), "native"),
|
|
188
|
+
reduceTransparency: level(supportsMedia(QUERIES.reduceTransparency)),
|
|
189
|
+
textScale: level(!!probe),
|
|
190
|
+
windowFocus: level(!!doc, "native"),
|
|
191
|
+
customTitleBar: level(!!nav && "windowControlsOverlay" in nav),
|
|
192
|
+
notifications: level(!!win && "Notification" in win),
|
|
193
|
+
taskbarProgress: level(!!nav && "setAppBadge" in nav),
|
|
194
|
+
fileDialogs: level(supportsFilePickers(win)),
|
|
195
|
+
osVersion: level(!!nav?.userAgentData)
|
|
196
|
+
};
|
|
197
|
+
return {
|
|
198
|
+
runtime: "web",
|
|
199
|
+
capabilities: Object.fromEntries(CAPABILITIES.map((c) => [c, support[c] ?? "none"])),
|
|
200
|
+
platform,
|
|
201
|
+
appearance,
|
|
202
|
+
onAppearanceChange(cb) {
|
|
203
|
+
appearanceListeners.add(cb);
|
|
204
|
+
detach ??= attach();
|
|
205
|
+
return () => {
|
|
206
|
+
appearanceListeners.delete(cb);
|
|
207
|
+
if (appearanceListeners.size === 0) {
|
|
208
|
+
detach?.();
|
|
209
|
+
detach = null;
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
},
|
|
213
|
+
window: {
|
|
214
|
+
isFocused: async () => isFocused(),
|
|
215
|
+
onFocusChange(cb) {
|
|
216
|
+
focusListeners.add(cb);
|
|
217
|
+
if (!focusDetach && win && doc) {
|
|
218
|
+
win.addEventListener("focus", onFocusEvent);
|
|
219
|
+
win.addEventListener("blur", onFocusEvent);
|
|
220
|
+
doc.addEventListener("visibilitychange", onFocusEvent);
|
|
221
|
+
focusDetach = () => {
|
|
222
|
+
win.removeEventListener("focus", onFocusEvent);
|
|
223
|
+
win.removeEventListener("blur", onFocusEvent);
|
|
224
|
+
doc.removeEventListener("visibilitychange", onFocusEvent);
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
return () => {
|
|
228
|
+
focusListeners.delete(cb);
|
|
229
|
+
if (focusListeners.size === 0) {
|
|
230
|
+
focusDetach?.();
|
|
231
|
+
focusDetach = null;
|
|
232
|
+
}
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
},
|
|
236
|
+
...win && supportsFilePickers(win) ? { dialogs: webDialogs(win) } : {}
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
function createProbe(doc) {
|
|
240
|
+
const host = doc.createElement("div");
|
|
241
|
+
host.setAttribute("aria-hidden", "true");
|
|
242
|
+
host.dataset["snWebHostProbe"] = "";
|
|
243
|
+
host.style.cssText = "position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none";
|
|
244
|
+
const accent = doc.createElement("span");
|
|
245
|
+
accent.style.cssText = "color:AccentColor";
|
|
246
|
+
const text = doc.createElement("span");
|
|
247
|
+
text.style.cssText = "display:block;font-size:medium;width:1em;height:1px";
|
|
248
|
+
host.append(accent, text);
|
|
249
|
+
(doc.body ?? doc.documentElement).append(host);
|
|
250
|
+
return {
|
|
251
|
+
accent,
|
|
252
|
+
text
|
|
253
|
+
};
|
|
254
|
+
}
|
|
255
|
+
function rgbToHex(color) {
|
|
256
|
+
const m = color.match(/rgba?\(\s*(\d+)[\s,]+(\d+)[\s,]+(\d+)/i);
|
|
257
|
+
if (!m) return null;
|
|
258
|
+
return "#" + [
|
|
259
|
+
m[1],
|
|
260
|
+
m[2],
|
|
261
|
+
m[3]
|
|
262
|
+
].map((v) => Number(v).toString(16).padStart(2, "0")).join("");
|
|
263
|
+
}
|
|
264
|
+
function sameAppearance(a, b) {
|
|
265
|
+
return a.accent === b.accent && a.scheme === b.scheme && a.contrast === b.contrast && a.reduceTransparency === b.reduceTransparency && a.reduceMotion === b.reduceMotion && a.textScale === b.textScale && a.skin === b.skin;
|
|
266
|
+
}
|
|
267
|
+
function readDisplayMode(win) {
|
|
268
|
+
if (win.navigator.windowControlsOverlay?.visible) return "overlay";
|
|
269
|
+
const media = (q) => win.matchMedia?.(q).matches ?? false;
|
|
270
|
+
if (media("(display-mode: window-controls-overlay)")) return "overlay";
|
|
271
|
+
if (media("(display-mode: standalone)") || media("(display-mode: minimal-ui)") || media("(display-mode: fullscreen)")) return "standalone";
|
|
272
|
+
return "browser";
|
|
273
|
+
}
|
|
274
|
+
function watchDisplayMode(cb, win = globalThis.window) {
|
|
275
|
+
if (!win) {
|
|
276
|
+
cb("browser");
|
|
277
|
+
return () => void 0;
|
|
278
|
+
}
|
|
279
|
+
let last = null;
|
|
280
|
+
const update = () => {
|
|
281
|
+
const mode = readDisplayMode(win);
|
|
282
|
+
if (mode !== last) cb(last = mode);
|
|
283
|
+
};
|
|
284
|
+
const queries = [
|
|
285
|
+
"(display-mode: standalone)",
|
|
286
|
+
"(display-mode: window-controls-overlay)",
|
|
287
|
+
"(display-mode: minimal-ui)"
|
|
288
|
+
].map((q) => win.matchMedia?.(q)).filter((m) => !!m);
|
|
289
|
+
const overlay = win.navigator.windowControlsOverlay;
|
|
290
|
+
queries.forEach((m) => m.addEventListener?.("change", update));
|
|
291
|
+
overlay?.addEventListener("geometrychange", update);
|
|
292
|
+
update();
|
|
293
|
+
return () => {
|
|
294
|
+
queries.forEach((m) => m.removeEventListener?.("change", update));
|
|
295
|
+
overlay?.removeEventListener("geometrychange", update);
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
export { fromClientHints, fromUserAgent, readDisplayMode, watchDisplayMode, webHost };
|
|
299
|
+
|
|
300
|
+
//# sourceMappingURL=spartan-native-host-web.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"spartan-native-host-web.mjs","names":[],"sources":["../../../packages/hosts/host-web/src/lib/detect-platform.ts","../../../packages/hosts/host-web/src/lib/web-dialogs.ts","../../../packages/hosts/host-web/src/lib/web-host.ts","../../../packages/hosts/host-web/src/lib/display-mode.ts"],"sourcesContent":["import { type PlatformInfo, resolveSkin, type Skin } from '@spartan-native/theme';\n\n/**\n * The subset of User-Agent Client Hints this adapter reads (Chromium).\n *\n * @internal Not in the public API; exported for webHost() and the unit tests.\n */\nexport interface UserAgentDataLike {\n readonly platform?: string;\n getHighEntropyValues?(hints: string[]): Promise<{ platformVersion?: string }>;\n}\n\n/** @internal Not in the public API; exported for webHost() and the unit tests. */\nexport interface NavigatorLike {\n readonly userAgent: string;\n readonly userAgentData?: UserAgentDataLike;\n}\n\n/**\n * The OS, its version and the matching skin, from the browser.\n *\n * - Chromium (User-Agent Client Hints): the real OS version. On Windows,\n * platformVersion ≥ 13 means Windows 11; on macOS it is the real macOS version.\n * confidence: 'exact'.\n * - Other browsers: the user-agent string, where Windows and macOS versions are\n * frozen. Windows → Windows 11, macOS → macOS 26 (the current releases).\n * confidence: 'hint'.\n * - The Linux desktop (GNOME / KDE) is never visible to a web page: GTK is assumed.\n *\n * @internal Not in the public API; exported for webHost() and the unit tests.\n */\nexport async function detectPlatform(nav: NavigatorLike): Promise<PlatformInfo> {\n const uaData = nav.userAgentData;\n if (uaData?.platform) {\n let version: string | null;\n try {\n version = (await uaData.getHighEntropyValues?.(['platformVersion']))?.platformVersion ?? null;\n } catch {\n version = null; // permission policy can block high-entropy hints\n }\n return fromClientHints(uaData.platform, version);\n }\n return fromUserAgent(nav.userAgent);\n}\n\nfunction info(\n os: PlatformInfo['os'],\n version: string | null,\n confidence: PlatformInfo['confidence'],\n skin?: Skin,\n): PlatformInfo {\n const base = { os, version, build: null, desktop: null } as const;\n return { ...base, skin: skin ?? resolveSkin(base), confidence };\n}\n\nexport function fromClientHints(platform: string, version: string | null): PlatformInfo {\n const major = version ? parseInt(version, 10) : NaN;\n switch (platform.toLowerCase()) {\n case 'windows':\n // Client Hints: 1–10 = Windows 10, ≥ 13 = Windows 11\n return info(\n 'windows',\n version,\n version ? 'exact' : 'hint',\n Number.isFinite(major) && major > 0 && major < 13 ? 'w10' : 'win',\n );\n case 'macos':\n return info('macos', version, version ? 'exact' : 'hint');\n case 'chrome os':\n case 'chromeos':\n return info('chromeos', version, 'exact');\n case 'linux':\n return info('linux', version, 'hint');\n default:\n return info('unknown', version, 'unknown');\n }\n}\n\nexport function fromUserAgent(ua: string): PlatformInfo {\n if (/Android|iPhone|iPad|iPod/i.test(ua)) return info('unknown', null, 'unknown');\n if (/Windows NT/i.test(ua)) return info('windows', null, 'hint', 'win');\n if (/Mac OS X|Macintosh/i.test(ua)) return info('macos', null, 'hint', 'mac');\n if (/CrOS/i.test(ua)) return info('chromeos', null, 'hint');\n if (/Linux/i.test(ua)) return info('linux', null, 'hint');\n return info('unknown', null, 'unknown');\n}\n","import type { DialogHost, FileFilter, PickedFile } from '@spartan-native/theme';\n\n/** The File System Access pickers (Chromium). Not in TypeScript's DOM types yet. */\ninterface PickerType {\n description?: string;\n accept: Record<string, string[]>;\n}\ninterface PickerWindow {\n showOpenFilePicker(options?: {\n multiple?: boolean;\n types?: PickerType[];\n excludeAcceptAllOption?: boolean;\n }): Promise<FileSystemFileHandle[]>;\n showSaveFilePicker(options?: {\n suggestedName?: string;\n types?: PickerType[];\n excludeAcceptAllOption?: boolean;\n }): Promise<FileSystemFileHandle>;\n showDirectoryPicker(options?: Record<string, never>): Promise<FileSystemDirectoryHandle>;\n}\n\n/** True when the browser has all three pickers. */\nexport function supportsFilePickers(win: Window | undefined): boolean {\n return !!win && 'showOpenFilePicker' in win && 'showSaveFilePicker' in win && 'showDirectoryPicker' in win;\n}\n\n/**\n * Turns the contract's filters into picker types. The pickers key extensions by MIME type;\n * `application/octet-stream` is accepted for any extension, so the extensions do the filtering.\n * A `*` filter means \"all files\": it keeps the browser's own \"All files\" entry instead.\n */\nexport function toPickerTypes(filters: readonly FileFilter[] = []): {\n types: PickerType[];\n excludeAcceptAllOption: boolean;\n} {\n const matchesAll = filters.length === 0 || filters.some((f) => f.extensions.includes('*'));\n const types = filters\n .filter((f) => !f.extensions.includes('*') && f.extensions.length > 0)\n .map((f) => ({\n description: f.name,\n accept: { 'application/octet-stream': f.extensions.map((e) => '.' + e.replace(/^\\./, '')) },\n }));\n return { types, excludeAcceptAllOption: !matchesAll };\n}\n\nconst picked = (handle: FileSystemHandle): PickedFile => ({ name: handle.name, handle });\n\n/** Cancelling a picker rejects with AbortError: that's an answer, not a failure. */\nasync function orCancelled<T>(run: () => Promise<T>, cancelled: T): Promise<T> {\n try {\n return await run();\n } catch (e) {\n if (e instanceof DOMException && e.name === 'AbortError') return cancelled;\n throw e;\n }\n}\n\n/** DialogHost on the File System Access API. No `message()`: browsers have no OS alert with custom buttons. */\nexport function webDialogs(win: Window): DialogHost {\n const pickers = win as unknown as PickerWindow;\n return {\n openFile: (options = {}) =>\n orCancelled(async () => {\n const handles = await pickers.showOpenFilePicker({\n multiple: !!options.multiple,\n ...toPickerTypes(options.filters),\n });\n return handles.map(picked);\n }, [] as PickedFile[]),\n saveFile: (options = {}) =>\n orCancelled(\n async () =>\n picked(\n await pickers.showSaveFilePicker({ suggestedName: options.fileName, ...toPickerTypes(options.filters) }),\n ),\n null,\n ),\n pickFolder: () => orCancelled(async () => picked(await pickers.showDirectoryPicker()), null),\n };\n}\n","import {\n type AppearanceState,\n CAPABILITIES,\n type Capability,\n type CapabilityLevel,\n type HostCapabilities,\n type NativeHost,\n normalizeHex,\n type PlatformInfo,\n type Skin,\n type Unsubscribe,\n} from '@spartan-native/theme';\nimport { detectPlatform, type NavigatorLike } from './detect-platform';\nimport { supportsFilePickers, webDialogs } from './web-dialogs';\n\nexport interface WebHostOptions {\n /** Accent used where the browser does not expose the system accent. Default: the platform's stock accent. */\n accent?: string;\n /** Force a skin instead of detecting it (e.g. a user setting). */\n skin?: Skin;\n /** The window to read from. Default: the global window. For tests and iframes. */\n window?: Window;\n}\n\n/** The platforms' stock accents, used when the browser hides the real one. */\nconst STOCK_ACCENT: Record<string, string> = {\n win: '#0078d4',\n w10: '#0078d4',\n mac: '#007aff',\n macc: '#007aff',\n gtk: '#3584e4',\n qt: '#3daee9',\n cros: '#0b57d0',\n web: '#0078d4',\n};\n\n/**\n * Chromium answers `AccentColor` with its own fixed blue instead of the OS accent\n * (to avoid fingerprinting). That value means \"not exposed\".\n */\nconst CHROMIUM_FIXED_ACCENT = '#0075ff';\n\nconst QUERIES = {\n dark: '(prefers-color-scheme: dark)',\n moreContrast: '(prefers-contrast: more)',\n forcedColors: '(forced-colors: active)',\n reduceTransparency: '(prefers-reduced-transparency: reduce)',\n reduceMotion: '(prefers-reduced-motion: reduce)',\n} as const;\n\n/**\n * NativeHost for browsers and installed PWAs. No native side.\n *\n * | Setting | Source | Live |\n * | --- | --- | --- |\n * | light / dark | `prefers-color-scheme` | yes |\n * | contrast | `prefers-contrast`, `forced-colors` | yes |\n * | reduce transparency | `prefers-reduced-transparency` (where supported) | yes |\n * | reduce motion | `prefers-reduced-motion` | yes |\n * | text size | the browser's default font size | yes (ResizeObserver) |\n * | accent | CSS `AccentColor` where the browser exposes the real one (Firefox, Safari), else `options.accent` / the platform's stock accent | on focus / visibility |\n * | window focus | `focus` / `blur` / `visibilitychange` | yes |\n * | OS and skin | User-Agent Client Hints, else the user-agent string | once |\n * | file dialogs | File System Access pickers (Chromium); absent elsewhere | – |\n *\n * ```ts\n * provideSpartanNative({ host: webHost() })\n * ```\n */\nexport function webHost(options: WebHostOptions = {}): NativeHost {\n const win: Window | undefined = options.window ?? (typeof window !== 'undefined' ? window : undefined);\n const doc = win?.document;\n\n const media = (q: string): MediaQueryList | null => (win?.matchMedia ? win.matchMedia(q) : null);\n const matches = (q: string) => media(q)?.matches ?? false;\n /** A media feature the browser understands (unknown ones parse to \"not all\"). */\n const supportsMedia = (q: string) => {\n const m = media(q);\n return !!m && m.media !== 'not all';\n };\n const css = (win as (Window & { CSS?: { supports?(property: string, value: string): boolean } }) | undefined)?.CSS;\n const supportsAccentColor = !!css?.supports?.('color', 'AccentColor');\n\n let platformPromise: Promise<PlatformInfo> | null = null;\n const platform = () =>\n (platformPromise ??= detectPlatform((win?.navigator ?? { userAgent: '' }) as unknown as NavigatorLike).then((p) =>\n options.skin ? { ...p, skin: options.skin } : p,\n ));\n\n // --- Readers ---------------------------------------------------------------\n const probe = doc ? createProbe(doc) : null;\n\n /** The real system accent, or null when the browser hides it. */\n const systemAccent = (): string | null => {\n if (!supportsAccentColor || !probe || !win) return null;\n const hex = rgbToHex(win.getComputedStyle(probe.accent).color);\n return hex && hex !== CHROMIUM_FIXED_ACCENT ? hex : null;\n };\n const exposesAccent = systemAccent() !== null;\n\n const readAccent = (skin: Skin): string =>\n systemAccent() ?? normalizeHex(options.accent ?? STOCK_ACCENT[skin] ?? STOCK_ACCENT['web']);\n\n const readTextScale = (): number => {\n const px = probe?.text.getBoundingClientRect().width ?? 16;\n return px > 0 ? Math.round((px / 16) * 20) / 20 : 1; // 0.05 steps\n };\n\n const read = (skin: Skin): AppearanceState => ({\n skin,\n accent: readAccent(skin),\n scheme: matches(QUERIES.dark) ? 'dark' : 'light',\n contrast: matches(QUERIES.forcedColors) ? 'forced' : matches(QUERIES.moreContrast) ? 'more' : 'normal',\n reduceTransparency: matches(QUERIES.reduceTransparency),\n reduceMotion: matches(QUERIES.reduceMotion),\n textScale: readTextScale(),\n });\n\n let skin: Skin = options.skin ?? 'web';\n let last: AppearanceState | null = null;\n const appearance = async () => {\n skin = (await platform()).skin;\n return (last = read(skin));\n };\n\n // --- Live changes ------------------------------------------------------------\n const appearanceListeners = new Set<(s: AppearanceState) => void>();\n const notify = () => {\n if (appearanceListeners.size === 0) return;\n const next = read(skin);\n if (last && sameAppearance(last, next)) return;\n last = next;\n appearanceListeners.forEach((cb) => cb(next));\n };\n\n let detach: (() => void) | null = null;\n const attach = () => {\n const offs: (() => void)[] = [];\n for (const q of Object.values(QUERIES)) {\n const m = media(q);\n if (!m) continue;\n m.addEventListener?.('change', notify);\n offs.push(() => m.removeEventListener?.('change', notify));\n }\n if (probe && typeof ResizeObserver !== 'undefined') {\n const ro = new ResizeObserver(notify);\n ro.observe(probe.text);\n offs.push(() => ro.disconnect());\n }\n // the accent has no change event: re-read when the user comes back to the app\n win?.addEventListener('focus', notify);\n doc?.addEventListener('visibilitychange', notify);\n offs.push(\n () => win?.removeEventListener('focus', notify),\n () => doc?.removeEventListener('visibilitychange', notify),\n );\n return () => offs.forEach((off) => off());\n };\n\n const focusListeners = new Set<(f: boolean) => void>();\n const isFocused = () => (doc ? doc.hasFocus() && doc.visibilityState !== 'hidden' : true);\n let focusDetach: (() => void) | null = null;\n const onFocusEvent = () => {\n const f = isFocused();\n focusListeners.forEach((cb) => cb(f));\n };\n\n // --- Capabilities --------------------------------------------------------------\n const level = (ok: boolean, yes: CapabilityLevel = 'partial'): CapabilityLevel => (ok ? yes : 'none');\n const nav = win?.navigator as\n (Navigator & { windowControlsOverlay?: unknown; setAppBadge?: unknown; userAgentData?: unknown }) | undefined;\n const support: Partial<Record<Capability, CapabilityLevel>> = {\n // 'none' when the browser hides the OS accent (Chromium answers a fixed blue)\n systemAccent: level(exposesAccent),\n colorScheme: level(supportsMedia(QUERIES.dark), 'native'),\n highContrast: level(supportsMedia(QUERIES.forcedColors) || supportsMedia(QUERIES.moreContrast), 'native'),\n reduceTransparency: level(supportsMedia(QUERIES.reduceTransparency)),\n textScale: level(!!probe),\n windowFocus: level(!!doc, 'native'),\n customTitleBar: level(!!nav && 'windowControlsOverlay' in nav),\n notifications: level(!!win && 'Notification' in win),\n taskbarProgress: level(!!nav && 'setAppBadge' in nav),\n fileDialogs: level(supportsFilePickers(win)),\n osVersion: level(!!nav?.userAgentData),\n };\n const capabilities = Object.fromEntries(CAPABILITIES.map((c) => [c, support[c] ?? 'none'])) as HostCapabilities;\n\n return {\n runtime: 'web',\n capabilities,\n platform,\n appearance,\n onAppearanceChange(cb): Unsubscribe {\n appearanceListeners.add(cb);\n detach ??= attach();\n return () => {\n appearanceListeners.delete(cb);\n if (appearanceListeners.size === 0) {\n detach?.();\n detach = null;\n }\n };\n },\n window: {\n isFocused: async () => isFocused(),\n onFocusChange(cb): Unsubscribe {\n focusListeners.add(cb);\n if (!focusDetach && win && doc) {\n win.addEventListener('focus', onFocusEvent);\n win.addEventListener('blur', onFocusEvent);\n doc.addEventListener('visibilitychange', onFocusEvent);\n focusDetach = () => {\n win.removeEventListener('focus', onFocusEvent);\n win.removeEventListener('blur', onFocusEvent);\n doc.removeEventListener('visibilitychange', onFocusEvent);\n };\n }\n return () => {\n focusListeners.delete(cb);\n if (focusListeners.size === 0) {\n focusDetach?.();\n focusDetach = null;\n }\n };\n },\n },\n ...(win && supportsFilePickers(win) ? { dialogs: webDialogs(win) } : {}),\n };\n}\n\n/** Two hidden elements: one colored with AccentColor, one 1em wide at the browser's default font size. */\nfunction createProbe(doc: Document): { accent: HTMLElement; text: HTMLElement } {\n const host = doc.createElement('div');\n host.setAttribute('aria-hidden', 'true');\n host.dataset['snWebHostProbe'] = '';\n host.style.cssText = 'position:absolute;width:0;height:0;overflow:hidden;visibility:hidden;pointer-events:none';\n const accent = doc.createElement('span');\n accent.style.cssText = 'color:AccentColor';\n const text = doc.createElement('span');\n // `medium` is the user's default font size, independent of the page's root font-size\n text.style.cssText = 'display:block;font-size:medium;width:1em;height:1px';\n host.append(accent, text);\n (doc.body ?? doc.documentElement).append(host);\n return { accent, text };\n}\n\nfunction rgbToHex(color: string): string | null {\n const m = color.match(/rgba?\\(\\s*(\\d+)[\\s,]+(\\d+)[\\s,]+(\\d+)/i);\n if (!m) return null;\n return '#' + [m[1], m[2], m[3]].map((v) => Number(v).toString(16).padStart(2, '0')).join('');\n}\n\nfunction sameAppearance(a: AppearanceState, b: AppearanceState): boolean {\n return (\n a.accent === b.accent &&\n a.scheme === b.scheme &&\n a.contrast === b.contrast &&\n a.reduceTransparency === b.reduceTransparency &&\n a.reduceMotion === b.reduceMotion &&\n a.textScale === b.textScale &&\n a.skin === b.skin\n );\n}\n","/**\n * How a web app is running:\n * - 'browser' in a browser tab\n * - 'standalone' installed (PWA): the OS draws the whole title bar\n * - 'overlay' installed with Window Controls Overlay: the OS draws only the\n * window buttons; the app draws its own title bar in the\n * `env(titlebar-area-*)` rectangle\n */\nexport type DisplayMode = 'browser' | 'standalone' | 'overlay';\n\ninterface WindowControlsOverlayLike extends EventTarget {\n readonly visible: boolean;\n}\n\nexport function readDisplayMode(win: Window): DisplayMode {\n const overlay = (win.navigator as Navigator & { windowControlsOverlay?: WindowControlsOverlayLike })\n .windowControlsOverlay;\n if (overlay?.visible) return 'overlay';\n const media = (q: string) => win.matchMedia?.(q).matches ?? false;\n if (media('(display-mode: window-controls-overlay)')) return 'overlay';\n if (\n media('(display-mode: standalone)') ||\n media('(display-mode: minimal-ui)') ||\n media('(display-mode: fullscreen)')\n ) {\n return 'standalone';\n }\n return 'browser';\n}\n\n/**\n * Calls `cb` now and whenever the display mode changes (installing, or the user\n * toggling the title bar in an installed app). Returns an unsubscribe function.\n */\nexport function watchDisplayMode(\n cb: (mode: DisplayMode) => void,\n win: Window | undefined = globalThis.window,\n): () => void {\n if (!win) {\n cb('browser');\n return () => undefined;\n }\n let last: DisplayMode | null = null;\n const update = () => {\n const mode = readDisplayMode(win);\n if (mode !== last) cb((last = mode));\n };\n const queries = [\n '(display-mode: standalone)',\n '(display-mode: window-controls-overlay)',\n '(display-mode: minimal-ui)',\n ]\n .map((q) => win.matchMedia?.(q))\n .filter((m): m is MediaQueryList => !!m);\n const overlay = (win.navigator as Navigator & { windowControlsOverlay?: WindowControlsOverlayLike })\n .windowControlsOverlay;\n\n queries.forEach((m) => m.addEventListener?.('change', update));\n overlay?.addEventListener('geometrychange', update);\n update();\n return () => {\n queries.forEach((m) => m.removeEvent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 -1,6 +1,45 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@spartan-native/host-web",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.2.1",
|
|
4
|
+
"description": "NativeHost for browsers and installed PWAs: system accent, light/dark, contrast, transparency, motion, text size and window focus from browser APIs, live.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Roland Molnár",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/Spartan-Native/spartan-native.git",
|
|
10
|
+
"directory": "packages/hosts/host-web"
|
|
11
|
+
},
|
|
12
|
+
"homepage": "https://github.com/Spartan-Native/spartan-native/tree/main/packages/hosts/host-web#readme",
|
|
13
|
+
"bugs": {
|
|
14
|
+
"url": "https://github.com/Spartan-Native/spartan-native/issues"
|
|
15
|
+
},
|
|
16
|
+
"keywords": [
|
|
17
|
+
"spartan-native",
|
|
18
|
+
"native-host",
|
|
19
|
+
"pwa",
|
|
20
|
+
"prefers-color-scheme",
|
|
21
|
+
"accent-color"
|
|
22
|
+
],
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"@spartan-native/theme": "0.2.1"
|
|
25
|
+
},
|
|
26
|
+
"dependencies": {
|
|
27
|
+
"tslib": "^2.3.0"
|
|
28
|
+
},
|
|
29
|
+
"sideEffects": false,
|
|
30
|
+
"publishConfig": {
|
|
31
|
+
"access": "public"
|
|
32
|
+
},
|
|
33
|
+
"module": "fesm2022/spartan-native-host-web.mjs",
|
|
34
|
+
"typings": "types/spartan-native-host-web.d.ts",
|
|
35
|
+
"exports": {
|
|
36
|
+
"./package.json": {
|
|
37
|
+
"default": "./package.json"
|
|
38
|
+
},
|
|
39
|
+
".": {
|
|
40
|
+
"types": "./types/spartan-native-host-web.d.ts",
|
|
41
|
+
"default": "./fesm2022/spartan-native-host-web.mjs"
|
|
42
|
+
}
|
|
43
|
+
},
|
|
44
|
+
"type": "module"
|
|
6
45
|
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import { NativeHost, PlatformInfo, Skin } from "@spartan-native/theme";
|
|
2
|
+
interface WebHostOptions {
|
|
3
|
+
/** Accent used where the browser does not expose the system accent. Default: the platform's stock accent. */
|
|
4
|
+
accent?: string;
|
|
5
|
+
/** Force a skin instead of detecting it (e.g. a user setting). */
|
|
6
|
+
skin?: Skin;
|
|
7
|
+
/** The window to read from. Default: the global window. For tests and iframes. */
|
|
8
|
+
window?: Window;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* NativeHost for browsers and installed PWAs. No native side.
|
|
12
|
+
*
|
|
13
|
+
* | Setting | Source | Live |
|
|
14
|
+
* | --- | --- | --- |
|
|
15
|
+
* | light / dark | `prefers-color-scheme` | yes |
|
|
16
|
+
* | contrast | `prefers-contrast`, `forced-colors` | yes |
|
|
17
|
+
* | reduce transparency | `prefers-reduced-transparency` (where supported) | yes |
|
|
18
|
+
* | reduce motion | `prefers-reduced-motion` | yes |
|
|
19
|
+
* | text size | the browser's default font size | yes (ResizeObserver) |
|
|
20
|
+
* | accent | CSS `AccentColor` where the browser exposes the real one (Firefox, Safari), else `options.accent` / the platform's stock accent | on focus / visibility |
|
|
21
|
+
* | window focus | `focus` / `blur` / `visibilitychange` | yes |
|
|
22
|
+
* | OS and skin | User-Agent Client Hints, else the user-agent string | once |
|
|
23
|
+
* | file dialogs | File System Access pickers (Chromium); absent elsewhere | – |
|
|
24
|
+
*
|
|
25
|
+
* ```ts
|
|
26
|
+
* provideSpartanNative({ host: webHost() })
|
|
27
|
+
* ```
|
|
28
|
+
*/
|
|
29
|
+
export declare function webHost(options?: WebHostOptions): NativeHost;
|
|
30
|
+
export declare function fromClientHints(platform: string, version: string | null): PlatformInfo;
|
|
31
|
+
export declare function fromUserAgent(ua: string): PlatformInfo;
|
|
32
|
+
/**
|
|
33
|
+
* How a web app is running:
|
|
34
|
+
* - 'browser' in a browser tab
|
|
35
|
+
* - 'standalone' installed (PWA): the OS draws the whole title bar
|
|
36
|
+
* - 'overlay' installed with Window Controls Overlay: the OS draws only the
|
|
37
|
+
* window buttons; the app draws its own title bar in the
|
|
38
|
+
* `env(titlebar-area-*)` rectangle
|
|
39
|
+
*/
|
|
40
|
+
type DisplayMode = 'browser' | 'standalone' | 'overlay';
|
|
41
|
+
export declare function readDisplayMode(win: Window): DisplayMode;
|
|
42
|
+
/**
|
|
43
|
+
* Calls `cb` now and whenever the display mode changes (installing, or the user
|
|
44
|
+
* toggling the title bar in an installed app). Returns an unsubscribe function.
|
|
45
|
+
*/
|
|
46
|
+
export declare function watchDisplayMode(cb: (mode: DisplayMode) => void, win?: Window | undefined): () => void;
|
|
47
|
+
export type { DisplayMode, WebHostOptions };
|