@tik-choco/mistvault 0.2.0 → 0.3.0

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/README.ja.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # mistvault
2
2
 
3
- TypeScript アプリ向けの分散保管庫ライブラリーです。ブラウザー内で暗号化し、mistl の `tc-escrow v1` プロトコルで保存します。コアに実行時依存はなく、設定 UI は任意で Preact 10 を利用できます。
3
+ TypeScript アプリ向けの分散保管庫ライブラリーです。ブラウザー内で暗号化し、mistl の `tc-escrow v1` プロトコルで保存します。コアに実行時依存はなく、任意の設定 UI はフレームワークに依存しない Web Components で提供し、Preact 10 用のラッパーも利用できます。
4
4
 
5
5
  [English / API 一覧](README.md) · [中文](README.zh.md)
6
6
 
@@ -44,6 +44,44 @@ import '@tik-choco/mistvault/ui.css'
44
44
 
45
45
  配色は `--mv-fg`、`--mv-muted`、`--mv-border`、`--mv-accent`、`--mv-bg` で調整できます。狭い画面で折り返し、システムのライト・ダーク設定に従います。
46
46
 
47
+ ## Web Components
48
+
49
+ `@tik-choco/mistvault/elements` を読み込むと、フレームワーク不要の `<mistvault-panel>` と `<mistvault-scope-panel>` が登録されます。どちらもライト DOM を使います。`./preact` のパネルはこれらの薄いラッパーです。`./elements.css` と `./ui.css` は同じスタイルを提供します。
50
+
51
+ 0.3.0 から、`VaultPanel` と `ScopeVaultPanel` の Preact の props とコールバックはそのままですが、ルート要素は `<section>` からそれぞれ `<mistvault-panel>` と `<mistvault-scope-panel>` のホスト要素に変わります。`.mv-panel` の section はホスト内のライト DOM に配置されます。従来のルート要素に依存する直接子セレクター、レイアウト指定、DOM の検索処理は調整してください。
52
+
53
+ パネルはクライアント側で描画され、サーバーサイドレンダリング(SSR)では内部のコントロールは生成されません。ネイティブの `HTMLElement` と `customElements` が利用可能なブラウザーで読み込み、マウントしてください。DOM のない環境でも `./elements` や `./preact` の読み込み自体は可能ですが、読み込み時にネイティブの `HTMLElement` がなければ要素クラスは代替の基底クラスを使うため、その後 DOM を導入して `defineMistvaultElements()` を呼んでも同じモジュール実行環境では登録できません。別のブラウザー実行環境を使うか、DOM が利用可能になるまで UI の読み込みを遅らせてください。
54
+
55
+ 通常の HTML(パッケージの `dist/` を `/vendor/mistvault/` で配信する場合):
56
+
57
+ ```html
58
+ <link rel="stylesheet" href="/vendor/mistvault/preact/ui.css">
59
+ <mistvault-panel id="settings" locale="ja" app-name="ノート"></mistvault-panel>
60
+ <script type="module">
61
+ import '/vendor/mistvault/elements/index.js'
62
+ import { vault } from './vault.js'
63
+ document.querySelector('#settings').controller = vault
64
+ </script>
65
+ ```
66
+
67
+ React(アプリのコントローラーを `vault` として渡す JSX の例):
68
+
69
+ ```jsx
70
+ import { useLayoutEffect, useRef } from 'react'
71
+ import '@tik-choco/mistvault/elements'
72
+ import '@tik-choco/mistvault/elements.css'
73
+
74
+ function Settings({ vault }) {
75
+ const ref = useRef(null)
76
+ useLayoutEffect(() => { ref.current.controller = vault }, [vault])
77
+ return <mistvault-panel ref={ref} locale="ja" app-name="ノート" />
78
+ }
79
+ ```
80
+
81
+ `controller`、`extraRooms`、`pendingCode` は属性ではなく JavaScript のプロパティで指定します。`locale` と `appName` は文字列属性 `locale`、`app-name` でも指定できます。バブリングする `mistvault-pending-handled` イベントの `detail` は `"imported"` または `"cancelled"` です。リスナー内で `pendingCode` をクリアしてください。`<mistvault-scope-panel>` には `vault` プロパティと任意の `locale` を指定します。Vue では `:controller.prop="vault"` のようにプロパティをバインドできます。
82
+
83
+ 共通テーマ変数 `--mist-fg`、`--mist-bg`、`--mist-muted`、`--mist-border`、`--mist-accent`、`--mist-error` に対応し、個別の `--mv-*` が優先されます。
84
+
47
85
  ## コードとルーム
48
86
 
49
87
  初期状態は無効です。有効にすると 128 ビットのランダムな保管庫コードを生成し、自動モードになります。同一オリジンのアプリは `tc-vault:settings-v1` を共有し、他のタブの変更にも追従します。アプリ別の進行状況は `tc-vault:app:<app>:v1` に保存します。別のコードに切り替えると、各アプリのシーケンス、ハッシュ、添付情報をリセットします。アプリのローカルデータと有効・無効の設定は残ります。
package/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # mistvault
2
2
 
3
- Browser-encrypted distributed vaults for TypeScript applications. Compatible with the `tc-escrow v1` protocol served by mistl. The portable core has no runtime dependencies; the settings panel optionally uses Preact 10.
3
+ Browser-encrypted distributed vaults for TypeScript applications. Compatible with the `tc-escrow v1` protocol served by mistl. The portable core has no runtime dependencies; optional framework-independent settings panels use Web Components, with Preact 10 wrappers available.
4
4
 
5
5
  [日本語](README.ja.md) · [中文](README.zh.md)
6
6
 
@@ -74,6 +74,44 @@ If the application consumes a device link before mounting the panel, pass its pr
74
74
 
75
75
  Set `--mv-fg`, `--mv-muted`, `--mv-border`, `--mv-accent`, and `--mv-bg` to match your application. Controls wrap at narrow widths and follow the system color scheme. Multiple panels can coexist without duplicate control IDs.
76
76
 
77
+ ## Web Components
78
+
79
+ Import `@tik-choco/mistvault/elements` to register `<mistvault-panel>` and `<mistvault-scope-panel>` without a UI framework. Both use light DOM. The `./preact` panels are thin wrappers around these elements. `./elements.css` and `./ui.css` provide the same styles.
80
+
81
+ Since 0.3.0, `VaultPanel` and `ScopeVaultPanel` keep their Preact props and callbacks, but render `<mistvault-panel>` and `<mistvault-scope-panel>` hosts instead of a root `<section>`. The `.mv-panel` section is now inside the host in light DOM. Update direct-child CSS selectors, layout rules and DOM queries that relied on the previous root.
82
+
83
+ The panels are client-rendered: server-side rendering (SSR) does not produce their inner controls. Import and mount them in a browser with native `HTMLElement` and `customElements` available. Importing `./elements` or `./preact` without a DOM is safe, but if native `HTMLElement` is unavailable at import time, the element classes use a fallback base and cannot be registered later in the same module runtime, even by calling `defineMistvaultElements()` after installing a DOM. Use a separate browser runtime or defer the UI import until the DOM is available.
84
+
85
+ Plain HTML (serve the package's `dist/` directory at `/vendor/mistvault/`):
86
+
87
+ ```html
88
+ <link rel="stylesheet" href="/vendor/mistvault/preact/ui.css">
89
+ <mistvault-panel id="settings" locale="en" app-name="Notebook"></mistvault-panel>
90
+ <script type="module">
91
+ import '/vendor/mistvault/elements/index.js'
92
+ import { vault } from './vault.js'
93
+ document.querySelector('#settings').controller = vault
94
+ </script>
95
+ ```
96
+
97
+ React (JSX, with the application controller passed as `vault`):
98
+
99
+ ```jsx
100
+ import { useLayoutEffect, useRef } from 'react'
101
+ import '@tik-choco/mistvault/elements'
102
+ import '@tik-choco/mistvault/elements.css'
103
+
104
+ function Settings({ vault }) {
105
+ const ref = useRef(null)
106
+ useLayoutEffect(() => { ref.current.controller = vault }, [vault])
107
+ return <mistvault-panel ref={ref} locale="en" app-name="Notebook" />
108
+ }
109
+ ```
110
+
111
+ Set `controller`, `extraRooms` and `pendingCode` as JavaScript properties, not attributes. `locale` and `appName` also accept the `locale` and `app-name` string attributes. Listen for the bubbling `mistvault-pending-handled` event; its `detail` is `"imported"` or `"cancelled"`. Clear `pendingCode` in the listener. For `<mistvault-scope-panel>`, set its `vault` property and optional `locale`. In Vue, use a property binding such as `:controller.prop="vault"`.
112
+
113
+ Set shared theme variables `--mist-fg`, `--mist-bg`, `--mist-muted`, `--mist-border`, `--mist-accent` and `--mist-error`; corresponding `--mv-*` overrides take precedence.
114
+
77
115
  ## Personal code and provider room
78
116
 
79
117
  The default is **off**. Enabling generates a random 128-bit code and selects automatic mode. All applications on one origin share `tc-vault:settings-v1`; storage events update other tabs. Each application has separate encryption and signing keys and its own `tc-vault:app:<app>:v1` metadata. Importing another code resets every stored application's sequence, hashes and part inventory while retaining local application data and app preferences.
package/README.zh.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # mistvault
2
2
 
3
- 面向 TypeScript 应用的分布式保管库。数据在浏览器中加密,通过 mistl 的 `tc-escrow v1` 协议保存。核心没有运行时依赖;可选的设置面板使用 Preact 10。
3
+ 面向 TypeScript 应用的分布式保管库。数据在浏览器中加密,通过 mistl 的 `tc-escrow v1` 协议保存。核心没有运行时依赖;可选的设置面板使用不依赖框架的 Web Components,并提供 Preact 10 封装。
4
4
 
5
5
  [English / 完整 API](README.md) · [日本語](README.ja.md)
6
6
 
@@ -44,6 +44,44 @@ import '@tik-choco/mistvault/ui.css'
44
44
 
45
45
  通过 `--mv-fg`、`--mv-muted`、`--mv-border`、`--mv-accent` 和 `--mv-bg` 调整颜色。布局会在窄屏换行,并遵循系统的明暗主题。
46
46
 
47
+ ## Web Components
48
+
49
+ 导入 `@tik-choco/mistvault/elements` 即可注册不依赖 UI 框架的 `<mistvault-panel>` 和 `<mistvault-scope-panel>`。两者均使用 Light DOM。`./preact` 面板是这些元素的轻量封装。`./elements.css` 和 `./ui.css` 提供相同样式。
50
+
51
+ 自 0.3.0 起,`VaultPanel` 和 `ScopeVaultPanel` 保留原有的 Preact props 与回调,但根节点由 `<section>` 改为 `<mistvault-panel>` 和 `<mistvault-scope-panel>` 宿主元素。`.mv-panel` 对应的 section 现在位于宿主的 Light DOM 内。请调整依赖旧根节点的直接子元素 CSS 选择器、布局规则和 DOM 查询。
52
+
53
+ 面板在客户端渲染,服务端渲染(SSR)不会生成内部控件。请在原生 `HTMLElement` 和 `customElements` 可用的浏览器中导入并挂载面板。在没有 DOM 的环境中导入 `./elements` 或 `./preact` 不会报错,但如果导入时原生 `HTMLElement` 不可用,元素类会使用备用基类,之后即使安装 DOM 并调用 `defineMistvaultElements()`,也无法在同一模块运行环境中注册这些元素。请使用独立的浏览器运行环境,或延迟导入 UI 直到 DOM 可用。
54
+
55
+ 原生 HTML(将软件包的 `dist/` 目录部署到 `/vendor/mistvault/`):
56
+
57
+ ```html
58
+ <link rel="stylesheet" href="/vendor/mistvault/preact/ui.css">
59
+ <mistvault-panel id="settings" locale="zh-CN" app-name="笔记本"></mistvault-panel>
60
+ <script type="module">
61
+ import '/vendor/mistvault/elements/index.js'
62
+ import { vault } from './vault.js'
63
+ document.querySelector('#settings').controller = vault
64
+ </script>
65
+ ```
66
+
67
+ React(通过 `vault` 传入应用控制器的 JSX 示例):
68
+
69
+ ```jsx
70
+ import { useLayoutEffect, useRef } from 'react'
71
+ import '@tik-choco/mistvault/elements'
72
+ import '@tik-choco/mistvault/elements.css'
73
+
74
+ function Settings({ vault }) {
75
+ const ref = useRef(null)
76
+ useLayoutEffect(() => { ref.current.controller = vault }, [vault])
77
+ return <mistvault-panel ref={ref} locale="zh-CN" app-name="笔记本" />
78
+ }
79
+ ```
80
+
81
+ 请将 `controller`、`extraRooms` 和 `pendingCode` 设为 JavaScript 属性,而不是 HTML 特性。`locale` 和 `appName` 也支持字符串特性 `locale` 和 `app-name`。冒泡事件 `mistvault-pending-handled` 的 `detail` 为 `"imported"` 或 `"cancelled"`,请在监听器中清除 `pendingCode`。`<mistvault-scope-panel>` 接受 `vault` 属性和可选的 `locale`。在 Vue 中可通过 `:controller.prop="vault"` 绑定属性。
82
+
83
+ 可使用共享主题变量 `--mist-fg`、`--mist-bg`、`--mist-muted`、`--mist-border`、`--mist-accent` 和 `--mist-error`;对应的 `--mv-*` 覆盖值优先。
84
+
47
85
  ## 个人代码与房间
48
86
 
49
87
  默认关闭。启用时生成随机的 128 位保管库代码并切换到自动模式。同一来源的应用共享 `tc-vault:settings-v1`,通过存储事件跟随其他标签页的修改。每个应用的元数据保存在 `tc-vault:app:<app>:v1`。导入其他代码会重置所有已存应用的序列、哈希和附件记录,但保留本地应用数据及各应用开关。
@@ -0,0 +1,30 @@
1
+ import { Dom } from './dom.js';
2
+ type Source<V> = {
3
+ getView(): V;
4
+ subscribe(cb: (view: V) => void): () => void;
5
+ };
6
+ declare const HTMLElementBase: {
7
+ new (): HTMLElement;
8
+ prototype: HTMLElement;
9
+ };
10
+ export declare abstract class PanelElement<V, S extends Source<V>> extends HTMLElementBase {
11
+ static observedAttributes: string[];
12
+ private active;
13
+ private currentSource?;
14
+ private view?;
15
+ private unsubscribe?;
16
+ protected dom: Dom;
17
+ protected abstract renderPanel(view: V, source: S): void;
18
+ get locale(): string | undefined;
19
+ set locale(value: string | undefined);
20
+ protected setStringAttribute(name: string, value: string | undefined): void;
21
+ attributeChangedCallback(): void;
22
+ protected get source(): S | undefined;
23
+ protected set source(value: S | undefined);
24
+ protected upgradeProperties(names: string[]): void;
25
+ connectedCallback(): void;
26
+ disconnectedCallback(): void;
27
+ private bind;
28
+ protected render(): void;
29
+ }
30
+ export {};
@@ -0,0 +1,56 @@
1
+ import { Dom } from './dom.js';
2
+ const HTMLElementBase = globalThis.HTMLElement ?? class {
3
+ };
4
+ export class PanelElement extends HTMLElementBase {
5
+ static observedAttributes = ['locale'];
6
+ active = false;
7
+ currentSource;
8
+ view;
9
+ unsubscribe;
10
+ dom = new Dom(this);
11
+ get locale() { return this.getAttribute('locale') ?? undefined; }
12
+ set locale(value) { this.setStringAttribute('locale', value); }
13
+ setStringAttribute(name, value) {
14
+ if (value == null)
15
+ this.removeAttribute(name);
16
+ else if (this.getAttribute(name) !== value)
17
+ this.setAttribute(name, value);
18
+ }
19
+ attributeChangedCallback() { this.render(); }
20
+ get source() { return this.currentSource; }
21
+ set source(value) {
22
+ if (this.currentSource === value)
23
+ return;
24
+ this.currentSource = value;
25
+ this.bind();
26
+ }
27
+ upgradeProperties(names) {
28
+ for (const name of names)
29
+ if (Object.hasOwn(this, name)) {
30
+ const value = Reflect.get(this, name);
31
+ Reflect.deleteProperty(this, name);
32
+ Reflect.set(this, name, value);
33
+ }
34
+ }
35
+ connectedCallback() { this.active = true; this.bind(); }
36
+ disconnectedCallback() { this.active = false; this.unsubscribe?.(); this.unsubscribe = undefined; this.view = undefined; }
37
+ bind() {
38
+ this.unsubscribe?.();
39
+ this.unsubscribe = undefined;
40
+ this.view = undefined;
41
+ const source = this.source;
42
+ if (this.active && source) {
43
+ this.unsubscribe = source.subscribe(view => { this.view = view; this.render(); });
44
+ this.view = source.getView();
45
+ }
46
+ this.render();
47
+ }
48
+ render() {
49
+ if (!this.active)
50
+ return;
51
+ if (this.source && this.view)
52
+ this.renderPanel(this.view, this.source);
53
+ else
54
+ this.dom.finish();
55
+ }
56
+ }
@@ -0,0 +1,21 @@
1
+ import type { VaultMode } from '../settings.js';
2
+ import type { Dom } from './dom.js';
3
+ interface RoomControlsProps {
4
+ locale?: string;
5
+ mode: VaultMode;
6
+ room: string;
7
+ controller: {
8
+ configure(mode: VaultMode, room: string): boolean;
9
+ };
10
+ disableUnchanged?: boolean;
11
+ onInvalid(): void;
12
+ }
13
+ export declare class RoomControls {
14
+ private update;
15
+ private previous?;
16
+ private mode;
17
+ private room;
18
+ constructor(update: () => void);
19
+ render({ node: n }: Dom, props: RoomControlsProps): (false | HTMLButtonElement | HTMLLabelElement)[];
20
+ }
21
+ export {};
@@ -0,0 +1,27 @@
1
+ import { vaultMessage } from '../i18n.js';
2
+ import { validVaultRoom } from '../settings.js';
3
+ export class RoomControls {
4
+ update;
5
+ previous;
6
+ mode = 'off';
7
+ room = '';
8
+ constructor(update) {
9
+ this.update = update;
10
+ }
11
+ render({ node: n }, props) {
12
+ if (this.previous?.mode !== props.mode || this.previous?.room !== props.room || this.previous?.controller !== props.controller) {
13
+ this.mode = props.mode;
14
+ this.room = props.room;
15
+ }
16
+ this.previous = props;
17
+ const t = (key) => vaultMessage(props.locale, key);
18
+ return [n('mode-label', 'label', {}, t('mode'), n('mode', 'select', { value: this.mode,
19
+ onchange: e => { this.mode = e.currentTarget.value; this.update(); } }, n('auto', 'option', { value: 'auto' }, t('auto')), n('custom', 'option', { value: 'custom' }, t('custom')), n('off', 'option', { value: 'off' }, t('off')))),
20
+ this.mode === 'custom' && n('custom-room-label', 'label', {}, t('room'), n('custom-room', 'input', { value: this.room, maxLength: 96,
21
+ attrs: { 'aria-invalid': String(!validVaultRoom(this.room)) }, oninput: e => { this.room = e.currentTarget.value; this.update(); } })),
22
+ n('apply', 'button', { type: 'button', disabled: this.mode === 'custom' && !validVaultRoom(this.room) ||
23
+ !!props.disableUnchanged && this.mode === props.mode && (this.mode !== 'custom' || this.room === props.room),
24
+ onclick: () => { if (!props.controller.configure(this.mode, this.room))
25
+ props.onInvalid(); } }, t('apply'))];
26
+ }
27
+ }
@@ -0,0 +1,10 @@
1
+ import type { ScopeVault, ScopeVaultView } from '../scopeVault.js';
2
+ import { PanelElement } from './PanelElement.js';
3
+ export declare class ScopeVaultPanelElement extends PanelElement<ScopeVaultView, ScopeVault> {
4
+ private notice;
5
+ private rooms;
6
+ get vault(): ScopeVault | undefined;
7
+ set vault(value: ScopeVault | undefined);
8
+ connectedCallback(): void;
9
+ protected renderPanel(view: ScopeVaultView, vault: ScopeVault): void;
10
+ }
@@ -0,0 +1,27 @@
1
+ import { vaultMessage } from '../i18n.js';
2
+ import { PanelElement } from './PanelElement.js';
3
+ import { RoomControls } from './RoomControls.js';
4
+ import { selectInput } from './dom.js';
5
+ export class ScopeVaultPanelElement extends PanelElement {
6
+ notice = '';
7
+ rooms = new RoomControls(() => this.render());
8
+ get vault() { return this.source; }
9
+ set vault(value) { this.source = value; }
10
+ connectedCallback() { this.upgradeProperties(['vault', 'locale']); super.connectedCallback(); }
11
+ renderPanel(view, vault) {
12
+ const t = (key) => vaultMessage(this.locale, key);
13
+ const n = this.dom.node, busy = view.mode === 'off' || view.status === 'saving' || view.status === 'restoring';
14
+ const copyRoom = async () => {
15
+ try {
16
+ await navigator.clipboard.writeText(view.room);
17
+ this.notice = t('copied');
18
+ }
19
+ catch {
20
+ this.notice = t('copyError');
21
+ }
22
+ this.render();
23
+ };
24
+ this.dom.finish(n('panel', 'section', { className: 'mv-panel mv-stack', attrs: { 'aria-label': t('title') } }, n('title', 'h2', {}, t('title')), n('status-card', 'div', { className: 'mv-status-card' }, n('status', 'div', { className: 'mv-status-text', attrs: { role: 'status', 'data-state': view.status } }, n('status-title', 'strong', {}, t(`status_${view.status}`)), !!view.error && n('status-error', 'span', { className: 'mv-error' }, view.error)), n('status-actions', 'div', { className: 'mv-actions' }, n('save', 'button', { type: 'button', disabled: busy, onclick: () => { void vault.saveNow(); } }, t('save')), n('restore', 'button', { type: 'button', disabled: busy, onclick: () => { void vault.restoreNow(); } }, t('restore')))), n('settings', 'div', { className: 'mv-stack' }, this.rooms.render(this.dom, { locale: this.locale, mode: view.mode, room: view.config.room,
25
+ controller: vault, disableUnchanged: !!view.config.by, onInvalid: () => { this.notice = t('invalidRoom'); this.render(); } })), view.mode !== 'off' && n('room', 'div', { className: 'mv-room' }, n('room-row', 'div', { className: 'mv-room-row' }, n('room-label', 'label', {}, t('room'), n('room-input', 'input', { readOnly: true, value: view.room, placeholder: t('roomPending'), onfocus: selectInput })), n('room-copy', 'button', { type: 'button', disabled: !view.room, onclick: () => { void copyRoom(); } }, t('copy'))), n('room-hint', 'p', { className: 'mv-muted mv-hint' }, t('scopeRoomHint'))), !!this.notice && n('notice', 'p', { className: 'mv-notice', attrs: { role: 'status' } }, this.notice)));
26
+ }
27
+ }
@@ -0,0 +1,39 @@
1
+ import type { VaultController, VaultView } from '../controller.js';
2
+ import { PanelElement } from './PanelElement.js';
3
+ export type PendingHandledResult = 'imported' | 'cancelled';
4
+ export declare class VaultPanelElement extends PanelElement<VaultView, VaultController> {
5
+ static observedAttributes: string[];
6
+ private rooms;
7
+ private visible;
8
+ private importing;
9
+ private input;
10
+ private inputError;
11
+ private suppliedCode?;
12
+ private propPending;
13
+ private localPending;
14
+ private linkConsumed;
15
+ private confirmError;
16
+ private notice;
17
+ private additionalRooms?;
18
+ private time;
19
+ private timer?;
20
+ private previous?;
21
+ get controller(): VaultController | undefined;
22
+ set controller(value: VaultController | undefined);
23
+ get appName(): string | undefined;
24
+ set appName(value: string | undefined);
25
+ get pendingCode(): string | null | undefined;
26
+ set pendingCode(value: string | null | undefined);
27
+ get extraRooms(): string[] | undefined;
28
+ set extraRooms(value: string[] | undefined);
29
+ connectedCallback(): void;
30
+ disconnectedCallback(): void;
31
+ private t;
32
+ private copy;
33
+ private resetImport;
34
+ private closeImport;
35
+ private importButton;
36
+ private prepareImport;
37
+ private finishPending;
38
+ protected renderPanel(view: VaultView, controller: VaultController): void;
39
+ }
@@ -0,0 +1,191 @@
1
+ import { consumeVaultLink, parseVaultCode, vaultLink } from '../code.js';
2
+ import { vaultMessage } from '../i18n.js';
3
+ import { PanelElement } from './PanelElement.js';
4
+ import { RoomControls } from './RoomControls.js';
5
+ import { selectInput } from './dom.js';
6
+ export class VaultPanelElement extends PanelElement {
7
+ static observedAttributes = ['locale', 'app-name'];
8
+ rooms = new RoomControls(() => this.render());
9
+ visible = false;
10
+ importing = false;
11
+ input = '';
12
+ inputError = '';
13
+ suppliedCode;
14
+ propPending = null;
15
+ localPending = null;
16
+ linkConsumed = false;
17
+ confirmError = '';
18
+ notice = '';
19
+ additionalRooms;
20
+ time = Date.now();
21
+ timer;
22
+ previous;
23
+ get controller() { return this.source; }
24
+ set controller(value) { this.source = value; }
25
+ get appName() { return this.getAttribute('app-name') ?? undefined; }
26
+ set appName(value) { this.setStringAttribute('app-name', value); }
27
+ get pendingCode() { return this.suppliedCode; }
28
+ set pendingCode(value) {
29
+ if (value === this.suppliedCode)
30
+ return;
31
+ this.suppliedCode = value;
32
+ this.propPending = value || null;
33
+ this.render();
34
+ }
35
+ get extraRooms() { return this.additionalRooms; }
36
+ set extraRooms(value) { this.additionalRooms = value; this.render(); }
37
+ connectedCallback() {
38
+ this.upgradeProperties(['controller', 'locale', 'appName', 'pendingCode', 'extraRooms']);
39
+ super.connectedCallback();
40
+ this.timer = setInterval(() => { this.time = Date.now(); this.render(); }, 60000);
41
+ }
42
+ disconnectedCallback() {
43
+ clearInterval(this.timer);
44
+ this.timer = undefined;
45
+ this.visible = false;
46
+ this.render();
47
+ super.disconnectedCallback();
48
+ }
49
+ t = (key, values) => vaultMessage(this.locale, key, values);
50
+ async copy(value) {
51
+ try {
52
+ await navigator.clipboard.writeText(value);
53
+ this.notice = this.t('copied');
54
+ }
55
+ catch {
56
+ this.notice = this.t('copyError');
57
+ }
58
+ this.render();
59
+ }
60
+ resetImport() { this.importing = false; this.input = ''; this.inputError = ''; }
61
+ closeImport() {
62
+ this.resetImport();
63
+ this.render();
64
+ this.importButton()?.focus();
65
+ }
66
+ importButton() { return this.querySelector('button[aria-expanded]'); }
67
+ prepareImport() {
68
+ const code = parseVaultCode(this.input);
69
+ if (!code)
70
+ this.inputError = this.t('invalidCode');
71
+ else {
72
+ this.inputError = '';
73
+ this.notice = '';
74
+ this.localPending = code;
75
+ }
76
+ this.render();
77
+ }
78
+ finishPending(result) {
79
+ const supplied = this.propPending !== null;
80
+ if (supplied)
81
+ this.propPending = null;
82
+ else
83
+ this.localPending = null;
84
+ this.resetImport();
85
+ this.visible = false;
86
+ this.confirmError = '';
87
+ this.render();
88
+ if (supplied)
89
+ this.dispatchEvent(new CustomEvent('mistvault-pending-handled', { detail: result, bubbles: true }));
90
+ requestAnimationFrame(() => {
91
+ if (!this.isConnected || this.querySelector('.mv-confirm'))
92
+ return;
93
+ const button = this.importButton();
94
+ if (button?.isConnected && !button.closest('details:not([open])'))
95
+ button.focus();
96
+ else
97
+ this.querySelector('h2')?.focus();
98
+ });
99
+ }
100
+ renderPanel(view, controller) {
101
+ if (!this.linkConsumed) {
102
+ this.linkConsumed = true;
103
+ try {
104
+ this.localPending = consumeVaultLink();
105
+ }
106
+ catch {
107
+ this.localPending = null;
108
+ }
109
+ }
110
+ const prev = this.previous, changed = prev?.controller !== controller || prev.mode !== view.mode;
111
+ if (changed || prev.room !== view.room)
112
+ this.visible = false;
113
+ if (changed) {
114
+ this.resetImport();
115
+ this.notice = '';
116
+ }
117
+ if (view.mode === 'off' && prev?.mode !== 'off')
118
+ this.rooms = new RoomControls(() => this.render());
119
+ const pending = this.propPending ?? this.localPending, parsedPending = pending === null ? null : parseVaultCode(pending);
120
+ if (prev?.pending !== pending)
121
+ this.confirmError = '';
122
+ this.previous = { controller, mode: view.mode, room: view.room, pending, importing: this.importing };
123
+ const t = this.t, n = this.dom.node;
124
+ const button = (key, label, onclick, props = {}) => n(key, 'button', { type: 'button', onclick, ...props }, t(label));
125
+ const actions = (key, ...content) => n(key, 'div', { className: 'mv-actions' }, content);
126
+ const stack = (key, ...content) => n(key, 'div', { className: 'mv-stack' }, content);
127
+ const error = (key, message) => !!message && n(key, 'p', { className: 'mv-error', attrs: { role: 'alert' } }, message);
128
+ const confirm = pending !== null && n('confirm', 'div', { className: 'mv-confirm',
129
+ attrs: { role: 'group', tabindex: '-1', 'aria-label': t('pendingTitle') + ' ' + t(parsedPending ? 'confirmation' : 'invalidCode') } }, n('confirm-title', 'h3', {}, t('pendingTitle')), n('confirm-text', 'p', {}, t(parsedPending ? 'confirmation' : 'invalidCode')), error('confirm-error', this.confirmError), actions('confirm-actions', !!parsedPending && button('confirm-ok', 'confirm', () => {
130
+ if (!controller.importCode(parsedPending)) {
131
+ this.confirmError = t('importError');
132
+ this.render();
133
+ return;
134
+ }
135
+ if (view.mode === 'off')
136
+ controller.enable();
137
+ this.finishPending('imported');
138
+ }, { className: 'mv-primary' }), button('confirm-cancel', 'cancel', () => this.finishPending('cancelled'))));
139
+ const importButton = (label) => button('import-button', label, () => {
140
+ if (this.importing)
141
+ this.closeImport();
142
+ else {
143
+ this.importing = true;
144
+ this.render();
145
+ }
146
+ }, { attrs: { 'aria-expanded': String(this.importing) } });
147
+ const importForm = this.importing && n('import', 'div', { className: 'mv-import' }, n('import-label', 'label', {}, t('importLabel'), n('import-input', 'input', { type: 'password', value: this.input, autocomplete: 'off',
148
+ attrs: { 'aria-invalid': String(!!this.inputError) }, oninput: e => {
149
+ this.input = e.currentTarget.value;
150
+ this.inputError = '';
151
+ this.render();
152
+ }, onkeydown: e => {
153
+ if (e.key === 'Enter') {
154
+ e.preventDefault();
155
+ this.prepareImport();
156
+ }
157
+ else if (e.key === 'Escape')
158
+ this.closeImport();
159
+ } })), error('input-error', this.inputError), actions('import-actions', button('import-prepare', 'import', () => this.prepareImport(), { className: 'mv-primary' }), button('import-cancel', 'cancel', () => this.closeImport())));
160
+ const busy = view.status === 'saving' || view.status === 'restoring', enabled = view.appEnabled && view.hasCode;
161
+ const minutes = Math.max(0, Math.floor((Math.max(this.time, Date.now()) - view.savedAt) / 60000));
162
+ const savedTime = minutes < 1 ? t('savedNow') : minutes < 60 ? t('savedAgo', { minutes }) :
163
+ minutes < 1440 ? t('savedHoursAgo', { hours: Math.floor(minutes / 60) }) :
164
+ minutes < 2880 ? t('savedDayAgo') : t('savedDaysAgo', { days: Math.floor(minutes / 1440) });
165
+ const content = view.mode === 'off' ? n('welcome', 'div', { className: 'mv-welcome' }, n('explanation', 'p', { className: 'mv-muted' }, t('explanation')), stack('welcome-buttons', button('enable', 'turnOn', () => controller.enable(), { className: 'mv-primary' }), importButton('useCode')), importForm) : [
166
+ n('status-card', 'div', { className: 'mv-status-card' }, n('status', 'div', { className: 'mv-status-text', attrs: { role: 'status', 'aria-live': 'polite', 'data-state': !view.appEnabled ? 'off' : view.status } }, n('status-title', 'strong', {}, !view.appEnabled && view.status === 'off' ? t('status_appOff') : t(`status_${view.status}`)), view.savedAt > 0 && n('saved-time', 'span', { className: 'mv-muted' }, ' ', savedTime), !!view.error && n('status-error', 'span', { className: 'mv-error' }, ' ', view.error)), actions('status-actions', button('save', 'save', () => { void controller.saveNow(); }, { disabled: !enabled || busy }), button('restore', 'restore', () => { void controller.restoreNow(); }, { disabled: !enabled || busy }))),
167
+ n('switch', 'label', { className: 'mv-switch' }, n('switch-text', 'span', {}, t('app', { app: this.appName || t('appFallback') })), n('switch-input', 'input', { type: 'checkbox', attrs: { role: 'switch' }, checked: view.appEnabled,
168
+ onchange: e => controller.setAppEnabled(e.currentTarget.checked) })),
169
+ n('room', 'div', { className: 'mv-room' }, n('room-row', 'div', { className: 'mv-room-row' }, n('room-label', 'label', {}, t('room'), n('room-input', 'input', { readOnly: true, value: view.room,
170
+ placeholder: t(view.appEnabled ? 'roomPending' : 'roomUnavailable'), onfocus: selectInput })), button('room-copy', 'copy', () => { void this.copy(view.room); }, { disabled: !view.room })), n('room-hint', 'p', { className: 'mv-muted mv-hint' }, t('hint'))),
171
+ n('code-details', 'details', { className: 'mv-disclosure', ontoggle: e => {
172
+ if (!e.currentTarget.open && this.visible) {
173
+ this.visible = false;
174
+ this.render();
175
+ }
176
+ } }, n('code-summary', 'summary', {}, t('code')), n('code-body', 'div', { className: 'mv-disclosure-body' }, n('code-hint', 'p', { className: 'mv-muted' }, t('codeHint')), n('code-input', 'input', { className: 'mv-code', attrs: { 'aria-label': t('code') }, readOnly: true, type: this.visible ? 'text' : 'password',
177
+ value: this.visible ? controller.revealCode() ?? '' : view.hasCode ? '0000000000000000' : '', autocomplete: 'off', onfocus: selectInput }), actions('code-actions', button('reveal', this.visible ? 'hide' : 'reveal', () => { this.visible = !this.visible; this.render(); }, { disabled: !view.hasCode }), button('code-copy', 'copy', () => { const code = controller.revealCode(); if (code)
178
+ void this.copy(code); }, { disabled: !view.hasCode })), stack('code-stack', button('link', 'link', () => { const code = controller.revealCode(); if (code)
179
+ void this.copy(vaultLink(window.location.href, code)); }, { disabled: !view.hasCode }), importButton('importAnother')), importForm)),
180
+ n('advanced-details', 'details', { className: 'mv-disclosure' }, n('advanced-summary', 'summary', {}, t('advanced')), n('advanced-body', 'div', { className: 'mv-disclosure-body' }, this.rooms.render(this.dom, { locale: this.locale, mode: view.mode, room: view.room, controller,
181
+ onInvalid: () => { this.notice = t('invalid'); this.render(); } }))),
182
+ !!view.hasParts && n('parts', 'p', { className: 'mv-parts mv-muted' }, t('parts', view.parts)),
183
+ ];
184
+ const additional = [...new Set(this.extraRooms)].filter(room => room && room !== view.room);
185
+ this.dom.finish(n('panel', 'section', { className: 'mv-panel', attrs: { 'aria-label': t('title') } }, confirm, n('title', 'h2', { attrs: { tabindex: '-1' } }, t('title')), content, additional.length > 0 && stack('extra-rooms', n('extra-title', 'h3', {}, t('extraRooms')), n('extra-list', 'ul', {}, additional.map(room => n('extra:' + room, 'li', {}, room))), button('copy-all', 'copyAll', () => { void this.copy(additional.join('\n')); })), !!this.notice && n('notice', 'p', { className: 'mv-notice', attrs: { role: 'status' } }, this.notice)));
186
+ if (this.importing && !prev?.importing)
187
+ this.querySelector('.mv-import input')?.focus();
188
+ if (pending !== null && prev?.pending !== pending)
189
+ this.querySelector('.mv-confirm')?.focus();
190
+ }
191
+ }
@@ -0,0 +1,14 @@
1
+ export type Child = Node | string | false | null | undefined | Child[];
2
+ type Props<K extends keyof HTMLElementTagNameMap> = Partial<HTMLElementTagNameMap[K]> & {
3
+ attrs?: Record<string, string>;
4
+ };
5
+ export declare class Dom {
6
+ private host;
7
+ private nodes;
8
+ private used;
9
+ constructor(host: HTMLElement);
10
+ node: <K extends keyof HTMLElementTagNameMap>(key: string, tag: K, props: Props<K>, ...content: Child[]) => HTMLElementTagNameMap[K];
11
+ finish(...content: Child[]): void;
12
+ }
13
+ export declare const selectInput: (e: FocusEvent) => void;
14
+ export {};
@@ -0,0 +1,58 @@
1
+ function flatten(values) {
2
+ return values.flatMap(value => Array.isArray(value) ? flatten(value) : value === false || value == null ? [] : [value]);
3
+ }
4
+ function children(parent, values) {
5
+ const next = flatten(values).map((value, i) => {
6
+ if (typeof value !== 'string')
7
+ return value;
8
+ const old = parent.childNodes[i];
9
+ if (old?.nodeType === 3) {
10
+ if (old.nodeValue !== value)
11
+ old.nodeValue = value;
12
+ return old;
13
+ }
14
+ return parent.ownerDocument.createTextNode(value);
15
+ });
16
+ const wanted = new Set(next);
17
+ for (const child of Array.from(parent.childNodes))
18
+ if (!wanted.has(child))
19
+ parent.removeChild(child);
20
+ let cursor = parent.firstChild;
21
+ for (const child of next) {
22
+ if (child !== cursor)
23
+ parent.insertBefore(child, cursor);
24
+ cursor = child.nextSibling;
25
+ }
26
+ }
27
+ export class Dom {
28
+ host;
29
+ nodes = new Map();
30
+ used = new Set();
31
+ constructor(host) {
32
+ this.host = host;
33
+ }
34
+ node = (key, tag, props, ...content) => {
35
+ let node = this.nodes.get(key);
36
+ if (!node) {
37
+ node = this.host.ownerDocument.createElement(tag);
38
+ this.nodes.set(key, node);
39
+ }
40
+ this.used.add(key);
41
+ children(node, content);
42
+ for (const [name, value] of Object.entries(props.attrs ?? {}))
43
+ if (node.getAttribute(name) !== value)
44
+ node.setAttribute(name, value);
45
+ for (const [name, value] of Object.entries(props))
46
+ if (name !== 'attrs' && Reflect.get(node, name) !== value)
47
+ Reflect.set(node, name, value);
48
+ return node;
49
+ };
50
+ finish(...content) {
51
+ children(this.host, content);
52
+ for (const key of this.nodes.keys())
53
+ if (!this.used.has(key))
54
+ this.nodes.delete(key);
55
+ this.used.clear();
56
+ }
57
+ }
58
+ export const selectInput = (e) => e.currentTarget.select();
@@ -0,0 +1,15 @@
1
+ import { VaultPanelElement } from './VaultPanelElement.js';
2
+ import { ScopeVaultPanelElement } from './ScopeVaultPanelElement.js';
3
+ import type { PendingHandledResult } from './VaultPanelElement.js';
4
+ export { VaultPanelElement, ScopeVaultPanelElement };
5
+ export type { PendingHandledResult };
6
+ declare global {
7
+ interface HTMLElementTagNameMap {
8
+ 'mistvault-panel': VaultPanelElement;
9
+ 'mistvault-scope-panel': ScopeVaultPanelElement;
10
+ }
11
+ interface HTMLElementEventMap {
12
+ 'mistvault-pending-handled': CustomEvent<PendingHandledResult>;
13
+ }
14
+ }
15
+ export declare function defineMistvaultElements(): void;
@@ -0,0 +1,12 @@
1
+ import { VaultPanelElement } from './VaultPanelElement.js';
2
+ import { ScopeVaultPanelElement } from './ScopeVaultPanelElement.js';
3
+ export { VaultPanelElement, ScopeVaultPanelElement };
4
+ export function defineMistvaultElements() {
5
+ if (typeof customElements === 'undefined' || typeof HTMLElement === 'undefined')
6
+ return;
7
+ if (!customElements.get('mistvault-panel'))
8
+ customElements.define('mistvault-panel', VaultPanelElement);
9
+ if (!customElements.get('mistvault-scope-panel'))
10
+ customElements.define('mistvault-scope-panel', ScopeVaultPanelElement);
11
+ }
12
+ defineMistvaultElements();
@@ -1,6 +1,10 @@
1
1
  import type { ScopeVault } from '../scopeVault.js';
2
+ import type { ScopeVaultPanelElement } from '../elements/index.js';
3
+ import '../elements/index.js';
2
4
  export interface ScopeVaultPanelProps {
3
5
  vault: ScopeVault;
4
6
  locale?: string;
5
7
  }
6
- export declare function ScopeVaultPanel({ vault, locale }: ScopeVaultPanelProps): import("preact").JSX.Element;
8
+ export declare function ScopeVaultPanel({ vault, locale }: ScopeVaultPanelProps): import("preact").VNode<import("preact").Attributes & {
9
+ ref: import("preact").RefObject<ScopeVaultPanelElement>;
10
+ }>;
@@ -1,20 +1,8 @@
1
- import { jsx as _jsx, jsxs as _jsxs } from "preact/jsx-runtime";
2
- import { useState } from 'preact/hooks';
3
- import { vaultMessage } from '../i18n.js';
4
- import { RoomControls } from './RoomControls.js';
5
- import { useVaultView } from './useVault.js';
1
+ import { h } from 'preact';
2
+ import { useLayoutEffect, useRef } from 'preact/hooks';
3
+ import '../elements/index.js';
6
4
  export function ScopeVaultPanel({ vault, locale }) {
7
- const view = useVaultView(vault), [notice, setNotice] = useState('');
8
- const t = (key) => vaultMessage(locale, key);
9
- const busy = view.mode === 'off' || view.status === 'saving' || view.status === 'restoring';
10
- async function copyRoom() {
11
- try {
12
- await navigator.clipboard.writeText(view.room);
13
- setNotice(t('copied'));
14
- }
15
- catch {
16
- setNotice(t('copyError'));
17
- }
18
- }
19
- return _jsxs("section", { class: "mv-panel mv-stack", "aria-label": t('title'), children: [_jsx("h2", { children: t('title') }), _jsxs("div", { class: "mv-status-card", children: [_jsxs("div", { class: "mv-status-text", role: "status", "data-state": view.status, children: [_jsx("strong", { children: t(`status_${view.status}`) }), view.error && _jsx("span", { class: "mv-error", children: view.error })] }), _jsxs("div", { class: "mv-actions", children: [_jsx("button", { type: "button", disabled: busy, onClick: () => { void vault.saveNow(); }, children: t('save') }), _jsx("button", { type: "button", disabled: busy, onClick: () => { void vault.restoreNow(); }, children: t('restore') })] })] }), _jsx("div", { class: "mv-stack", children: _jsx(RoomControls, { locale: locale, mode: view.mode, room: view.config.room, controller: vault, disableUnchanged: !!view.config.by, onInvalid: () => setNotice(t('invalidRoom')) }) }), view.mode !== 'off' && _jsxs("div", { class: "mv-room", children: [_jsxs("div", { class: "mv-room-row", children: [_jsxs("label", { children: [t('room'), _jsx("input", { readOnly: true, value: view.room, placeholder: t('roomPending'), onFocus: e => e.currentTarget.select() })] }), _jsx("button", { type: "button", disabled: !view.room, onClick: () => { void copyRoom(); }, children: t('copy') })] }), _jsx("p", { class: "mv-muted mv-hint", children: t('scopeRoomHint') })] }), notice && _jsx("p", { class: "mv-notice", role: "status", children: notice })] });
5
+ const ref = useRef(null);
6
+ useLayoutEffect(() => { Object.assign(ref.current, { locale, vault }); });
7
+ return h('mistvault-scope-panel', { ref });
20
8
  }
@@ -1,4 +1,6 @@
1
1
  import type { VaultController } from '../controller.js';
2
+ import type { VaultPanelElement } from '../elements/index.js';
3
+ import '../elements/index.js';
2
4
  export interface VaultPanelProps {
3
5
  controller: VaultController;
4
6
  locale?: string;
@@ -9,4 +11,6 @@ export interface VaultPanelProps {
9
11
  /** Called after a supplied pending code is imported or dismissed. Clear pendingCode in the caller. */
10
12
  onPendingHandled?: (result: 'imported' | 'cancelled') => void;
11
13
  }
12
- export declare function VaultPanel({ controller, locale, appName, pendingCode, onPendingHandled, extraRooms }: VaultPanelProps): import("preact").JSX.Element;
14
+ export declare function VaultPanel({ controller, locale, appName, pendingCode, onPendingHandled, extraRooms }: VaultPanelProps): import("preact").VNode<import("preact").Attributes & {
15
+ ref: import("preact").RefObject<VaultPanelElement>;
16
+ }>;
@@ -1,111 +1,14 @@
1
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "preact/jsx-runtime";
2
- import { useEffect, useLayoutEffect, useRef, useState } from 'preact/hooks';
3
- import { RoomControls } from './RoomControls.js';
4
- import { consumeVaultLink, parseVaultCode, vaultLink } from '../code.js';
5
- import { vaultMessage } from '../i18n.js';
6
- import { useVault } from './useVault.js';
1
+ import { h } from 'preact';
2
+ import { useLayoutEffect, useRef } from 'preact/hooks';
3
+ import '../elements/index.js';
7
4
  export function VaultPanel({ controller, locale, appName, pendingCode, onPendingHandled, extraRooms }) {
8
- const view = useVault(controller);
9
- const t = (key, values) => vaultMessage(locale, key, values);
10
- const additional = [...new Set(extraRooms)].filter(room => room && room !== view.room);
11
- const [visible, setVisible] = useState(false), [input, setInput] = useState('');
12
- const [importing, setImporting] = useState(false), [inputError, setInputError] = useState('');
13
- const [propPending, setPropPending] = useState(pendingCode || null);
14
- const [localPending, setLocalPending] = useState(() => {
15
- try {
16
- return typeof window === 'undefined' ? null : consumeVaultLink();
17
- }
18
- catch {
19
- return null;
20
- }
21
- });
22
- const [confirmError, setConfirmError] = useState('');
23
- const [notice, setNotice] = useState(''), [time, setTime] = useState(Date.now());
24
- const confirmRef = useRef(null), importRef = useRef(null);
25
- const importButtonRef = useRef(null), titleRef = useRef(null);
26
- const pending = propPending ?? localPending;
27
- const parsedPending = pending === null ? null : parseVaultCode(pending);
28
- useLayoutEffect(() => { setPropPending(pendingCode || null); }, [pendingCode]);
5
+ const ref = useRef(null);
29
6
  useLayoutEffect(() => {
30
- setConfirmError('');
31
- if (pending !== null)
32
- confirmRef.current?.focus();
33
- }, [pending]);
34
- useLayoutEffect(() => { if (importing)
35
- importRef.current?.focus(); }, [importing]);
36
- useLayoutEffect(() => { setVisible(false); }, [view.mode, view.room, controller]);
37
- useLayoutEffect(() => { setImporting(false); setInput(''); setInputError(''); setNotice(''); }, [view.mode, controller]);
38
- useEffect(() => { const timer = setInterval(() => setTime(Date.now()), 60000); return () => clearInterval(timer); }, []);
39
- const copy = async (value) => {
40
- try {
41
- await navigator.clipboard.writeText(value);
42
- setNotice(t('copied'));
43
- }
44
- catch {
45
- setNotice(t('copyError'));
46
- }
47
- };
48
- const closeImport = () => {
49
- setImporting(false);
50
- setInput('');
51
- setInputError('');
52
- importButtonRef.current?.focus();
53
- };
54
- const prepareImport = () => {
55
- const code = parseVaultCode(input);
56
- if (!code) {
57
- setInputError(t('invalidCode'));
58
- return;
59
- }
60
- setInputError('');
61
- setNotice('');
62
- setLocalPending(code);
63
- };
64
- const finishPending = (result) => {
65
- if (propPending !== null) {
66
- setPropPending(null);
67
- onPendingHandled?.(result);
68
- }
69
- else
70
- setLocalPending(null);
71
- setInput('');
72
- setInputError('');
73
- setImporting(false);
74
- setVisible(false);
75
- setConfirmError('');
76
- requestAnimationFrame(() => {
77
- if (confirmRef.current)
78
- return;
79
- const button = importButtonRef.current;
80
- if (button?.isConnected && !button.closest('details:not([open])'))
81
- button.focus();
82
- else
83
- titleRef.current?.focus();
84
- });
85
- };
86
- const confirmImport = () => {
87
- if (!parsedPending || !controller.importCode(parsedPending)) {
88
- setConfirmError(t('importError'));
89
- return;
90
- }
91
- if (view.mode === 'off')
92
- controller.enable();
93
- finishPending('imported');
94
- };
95
- const importForm = importing && _jsxs("div", { class: "mv-import", children: [_jsxs("label", { children: [t('importLabel'), _jsx("input", { ref: importRef, type: "password", value: input, autoComplete: "off", "aria-invalid": !!inputError, onInput: e => { setInput(e.currentTarget.value); setInputError(''); }, onKeyDown: e => { if (e.key === 'Enter') {
96
- e.preventDefault();
97
- prepareImport();
98
- }
99
- else if (e.key === 'Escape')
100
- closeImport(); } })] }), inputError && _jsx("p", { class: "mv-error", role: "alert", children: inputError }), _jsxs("div", { class: "mv-actions", children: [_jsx("button", { type: "button", class: "mv-primary", onClick: prepareImport, children: t('import') }), _jsx("button", { type: "button", onClick: closeImport, children: t('cancel') })] })] });
101
- const busy = view.status === 'saving' || view.status === 'restoring';
102
- const enabled = view.appEnabled && view.hasCode;
103
- const minutes = Math.max(0, Math.floor((Math.max(time, Date.now()) - view.savedAt) / 60000));
104
- const savedTime = minutes < 1 ? t('savedNow') : minutes < 60 ? t('savedAgo', { minutes }) :
105
- minutes < 1440 ? t('savedHoursAgo', { hours: Math.floor(minutes / 60) }) :
106
- minutes < 2880 ? t('savedDayAgo') : t('savedDaysAgo', { days: Math.floor(minutes / 1440) });
107
- return _jsxs("section", { class: "mv-panel", "aria-label": t('title'), children: [pending !== null && _jsxs("div", { ref: confirmRef, class: "mv-confirm", role: "group", "aria-label": t('pendingTitle') + ' ' + t(parsedPending ? 'confirmation' : 'invalidCode'), tabIndex: -1, children: [_jsx("h3", { children: t('pendingTitle') }), _jsx("p", { children: parsedPending ? t('confirmation') : t('invalidCode') }), confirmError && _jsx("p", { class: "mv-error", role: "alert", children: confirmError }), _jsxs("div", { class: "mv-actions", children: [parsedPending && _jsx("button", { type: "button", class: "mv-primary", onClick: confirmImport, children: t('confirm') }), _jsx("button", { type: "button", onClick: () => finishPending('cancelled'), children: t('cancel') })] })] }), _jsx("h2", { ref: titleRef, tabIndex: -1, children: t('title') }), view.mode === 'off' ? _jsxs("div", { class: "mv-welcome", children: [_jsx("p", { class: "mv-muted", children: t('explanation') }), _jsxs("div", { class: "mv-stack", children: [_jsx("button", { type: "button", class: "mv-primary", onClick: () => controller.enable(), children: t('turnOn') }), _jsx("button", { ref: importButtonRef, type: "button", "aria-expanded": importing, onClick: () => importing ? closeImport() : setImporting(true), children: t('useCode') })] }), importForm] }) : _jsxs(_Fragment, { children: [_jsxs("div", { class: "mv-status-card", children: [_jsxs("div", { class: "mv-status-text", role: "status", "aria-live": "polite", "data-state": !view.appEnabled ? 'off' : view.status, children: [_jsx("strong", { children: !view.appEnabled && view.status === 'off' ? t('status_appOff') : t(`status_${view.status}`) }), view.savedAt > 0 && _jsxs("span", { class: "mv-muted", children: [' ', savedTime] }), view.error && _jsxs("span", { class: "mv-error", children: [' ', view.error] })] }), _jsxs("div", { class: "mv-actions", children: [_jsx("button", { type: "button", disabled: !enabled || busy, onClick: () => { void controller.saveNow(); }, children: t('save') }), _jsx("button", { type: "button", disabled: !enabled || busy, onClick: () => { void controller.restoreNow(); }, children: t('restore') })] })] }), _jsxs("label", { class: "mv-switch", children: [_jsx("span", { children: t('app', { app: appName || t('appFallback') }) }), _jsx("input", { type: "checkbox", role: "switch", checked: view.appEnabled, onChange: e => controller.setAppEnabled(e.currentTarget.checked) })] }), _jsxs("div", { class: "mv-room", children: [_jsxs("div", { class: "mv-room-row", children: [_jsxs("label", { children: [t('room'), _jsx("input", { readOnly: true, value: view.room, placeholder: t(view.appEnabled ? 'roomPending' : 'roomUnavailable'), onFocus: e => e.currentTarget.select() })] }), _jsx("button", { type: "button", disabled: !view.room, onClick: () => { void copy(view.room); }, children: t('copy') })] }), _jsx("p", { class: "mv-muted mv-hint", children: t('hint') })] }), _jsxs("details", { class: "mv-disclosure", onToggle: e => { if (!e.currentTarget.open)
108
- setVisible(false); }, children: [_jsx("summary", { children: t('code') }), _jsxs("div", { class: "mv-disclosure-body", children: [_jsx("p", { class: "mv-muted", children: t('codeHint') }), _jsx("input", { class: "mv-code", "aria-label": t('code'), readOnly: true, type: visible ? 'text' : 'password', value: visible ? controller.revealCode() ?? '' : view.hasCode ? '0000000000000000' : '', autoComplete: "off", onFocus: e => e.currentTarget.select() }), _jsxs("div", { class: "mv-actions", children: [_jsx("button", { type: "button", disabled: !view.hasCode, onClick: () => setVisible(!visible), children: t(visible ? 'hide' : 'reveal') }), _jsx("button", { type: "button", disabled: !view.hasCode, onClick: () => { const code = controller.revealCode(); if (code)
109
- void copy(code); }, children: t('copy') })] }), _jsxs("div", { class: "mv-stack", children: [_jsx("button", { type: "button", disabled: !view.hasCode, onClick: () => { const code = controller.revealCode(); if (code)
110
- void copy(vaultLink(window.location.href, code)); }, children: t('link') }), _jsx("button", { ref: importButtonRef, type: "button", "aria-expanded": importing, onClick: () => importing ? closeImport() : setImporting(true), children: t('importAnother') })] }), importForm] })] }), _jsxs("details", { class: "mv-disclosure", children: [_jsx("summary", { children: t('advanced') }), _jsx("div", { class: "mv-disclosure-body", children: _jsx(RoomControls, { locale: locale, mode: view.mode, room: view.room, controller: controller, onInvalid: () => setNotice(t('invalid')) }) })] }), view.hasParts && _jsx("p", { class: "mv-parts mv-muted", children: t('parts', view.parts) })] }), additional.length > 0 && _jsxs("div", { class: "mv-stack", children: [_jsx("h3", { children: t('extraRooms') }), _jsx("ul", { children: additional.map(room => _jsx("li", { children: room }, room)) }), _jsx("button", { type: "button", onClick: () => { void copy(additional.join('\n')); }, children: t('copyAll') })] }), notice && _jsx("p", { class: "mv-notice", role: "status", children: notice })] });
7
+ const panel = ref.current;
8
+ const handled = (e) => onPendingHandled?.(e.detail);
9
+ panel.addEventListener('mistvault-pending-handled', handled);
10
+ Object.assign(panel, { locale, appName, pendingCode, extraRooms, controller });
11
+ return () => panel.removeEventListener('mistvault-pending-handled', handled);
12
+ });
13
+ return h('mistvault-panel', { ref });
111
14
  }
@@ -1,6 +1,7 @@
1
+ mistvault-panel, mistvault-scope-panel { display: block; }
1
2
  .mv-panel {
2
- color: var(--mv-fg, inherit);
3
- background: var(--mv-bg, transparent);
3
+ color: var(--mv-fg, var(--mist-fg, inherit));
4
+ background: var(--mv-bg, var(--mist-bg, transparent));
4
5
  font: inherit;
5
6
  line-height: 1.5;
6
7
  max-width: 44rem;
@@ -11,47 +12,47 @@
11
12
  .mv-panel h2 { font-size: 1.3em; line-height: 1.25; margin: 0 0 1rem; }
12
13
  .mv-panel h3 { font-size: 1em; line-height: 1.3; margin: 0; }
13
14
  .mv-panel p { margin: 0; overflow-wrap: anywhere; }
14
- .mv-panel .mv-muted { color: var(--mv-muted, #6d7772); font-size: .9em; }
15
+ .mv-panel .mv-muted { color: var(--mv-muted, var(--mist-muted, #6d7772)); font-size: .9em; }
15
16
  .mv-panel label { display: block; font-weight: 600; }
16
17
  .mv-panel input:not([type=checkbox]), .mv-panel select {
17
18
  display: block;
18
19
  min-width: 0;
19
20
  width: 100%;
20
21
  padding: .65rem .7rem;
21
- border: 1px solid var(--mv-border, rgba(127, 127, 127, .35));
22
+ border: 1px solid var(--mv-border, var(--mist-border, rgba(127, 127, 127, .35)));
22
23
  border-radius: .5rem;
23
24
  color: inherit;
24
- background: var(--mv-bg, transparent);
25
+ background: var(--mv-bg, var(--mist-bg, transparent));
25
26
  font: inherit;
26
27
  font-weight: 400;
27
28
  }
28
- .mv-panel input::placeholder { color: var(--mv-muted, #6d7772); opacity: 1; }
29
+ .mv-panel input::placeholder { color: var(--mv-muted, var(--mist-muted, #6d7772)); opacity: 1; }
29
30
  .mv-panel button {
30
31
  min-height: 2.75rem;
31
32
  padding: .6rem .8rem;
32
- border: 1px solid var(--mv-border, rgba(127, 127, 127, .35));
33
+ border: 1px solid var(--mv-border, var(--mist-border, rgba(127, 127, 127, .35)));
33
34
  border-radius: .5rem;
34
35
  color: inherit;
35
- background: var(--mv-bg, transparent);
36
+ background: var(--mv-bg, var(--mist-bg, transparent));
36
37
  font: inherit;
37
38
  font-weight: 600;
38
39
  line-height: 1.3;
39
40
  cursor: pointer;
40
41
  overflow-wrap: anywhere;
41
42
  }
42
- .mv-panel button:hover:not(:disabled) { border-color: var(--mv-accent, #315fbd); }
43
- .mv-panel button.mv-primary { color: var(--mv-bg, #fff); background: var(--mv-accent, #315fbd); border-color: var(--mv-accent, #315fbd); }
43
+ .mv-panel button:hover:not(:disabled) { border-color: var(--mv-accent, var(--mist-accent, #315fbd)); }
44
+ .mv-panel button.mv-primary { color: var(--mv-bg, var(--mist-bg, #fff)); background: var(--mv-accent, var(--mist-accent, #315fbd)); border-color: var(--mv-accent, var(--mist-accent, #315fbd)); }
44
45
  .mv-panel button:disabled { opacity: .5; cursor: default; }
45
- .mv-panel :focus-visible { outline: 2px solid var(--mv-accent, #315fbd); outline-offset: 3px; }
46
+ .mv-panel :focus-visible { outline: 2px solid var(--mv-accent, var(--mist-accent, #315fbd)); outline-offset: 3px; }
46
47
  .mv-panel .mv-welcome > p { margin-bottom: 1.25rem; }
47
48
  .mv-panel .mv-stack { display: grid; gap: .55rem; }
48
49
  .mv-panel .mv-actions { display: flex; flex-wrap: wrap; gap: .5rem; }
49
50
  .mv-panel .mv-actions button { flex: 1 1 7rem; }
50
51
  .mv-panel .mv-status-card, .mv-panel .mv-confirm {
51
52
  padding: 1rem;
52
- border: 1px solid var(--mv-border, rgba(127, 127, 127, .35));
53
+ border: 1px solid var(--mv-border, var(--mist-border, rgba(127, 127, 127, .35)));
53
54
  border-radius: .75rem;
54
- background: color-mix(in srgb, var(--mv-accent, #315fbd) 7%, transparent);
55
+ background: color-mix(in srgb, var(--mv-accent, var(--mist-accent, #315fbd)) 7%, transparent);
55
56
  }
56
57
  .mv-panel .mv-status-text { display: grid; gap: .15rem; margin-bottom: .85rem; }
57
58
  .mv-panel .mv-status-text strong::before {
@@ -60,12 +61,12 @@
60
61
  height: .55rem;
61
62
  margin-inline-end: .5rem;
62
63
  border-radius: 50%;
63
- background: var(--mv-accent, #315fbd);
64
+ background: var(--mv-accent, var(--mist-accent, #315fbd));
64
65
  content: '';
65
66
  vertical-align: .05em;
66
67
  }
67
- .mv-panel .mv-status-text[data-state=off] strong::before { background: var(--mv-muted, #6d7772); }
68
- .mv-panel .mv-status-text[data-state=error] strong::before { background: var(--mv-error, #b33b3b); }
68
+ .mv-panel .mv-status-text[data-state=off] strong::before { background: var(--mv-muted, var(--mist-muted, #6d7772)); }
69
+ .mv-panel .mv-status-text[data-state=error] strong::before { background: var(--mv-error, var(--mist-error, #b33b3b)); }
69
70
  .mv-panel .mv-switch {
70
71
  display: flex;
71
72
  align-items: center;
@@ -81,9 +82,9 @@
81
82
  width: 2.6rem;
82
83
  height: 1.5rem;
83
84
  margin: 0;
84
- border: 1px solid var(--mv-border, rgba(127, 127, 127, .55));
85
+ border: 1px solid var(--mv-border, var(--mist-border, rgba(127, 127, 127, .55)));
85
86
  border-radius: 1rem;
86
- background: var(--mv-border, #9ca9a1);
87
+ background: var(--mv-border, var(--mist-border, #9ca9a1));
87
88
  cursor: pointer;
88
89
  }
89
90
  .mv-panel .mv-switch input::before {
@@ -92,11 +93,11 @@
92
93
  height: 1.1rem;
93
94
  margin: .13rem;
94
95
  border-radius: 50%;
95
- background: var(--mv-bg, #fff);
96
+ background: var(--mv-bg, var(--mist-bg, #fff));
96
97
  content: '';
97
98
  transition: transform .15s ease;
98
99
  }
99
- .mv-panel .mv-switch input:checked { border-color: var(--mv-accent, #315fbd); background: var(--mv-accent, #315fbd); }
100
+ .mv-panel .mv-switch input:checked { border-color: var(--mv-accent, var(--mist-accent, #315fbd)); background: var(--mv-accent, var(--mist-accent, #315fbd)); }
100
101
  .mv-panel .mv-switch input:checked::before { transform: translateX(1.1rem); }
101
102
  .mv-panel .mv-room { padding-bottom: 1.1rem; }
102
103
  .mv-panel .mv-room-row { display: flex; align-items: end; gap: .5rem; }
@@ -104,25 +105,25 @@
104
105
  .mv-panel .mv-room-row input { margin-top: .4rem; }
105
106
  .mv-panel .mv-room-row button { flex: 0 0 auto; }
106
107
  .mv-panel .mv-hint { margin-top: .4rem; }
107
- .mv-panel .mv-disclosure { min-width: 0; border-top: 1px solid var(--mv-border, rgba(127, 127, 127, .35)); }
108
- .mv-panel .mv-disclosure:last-of-type { border-bottom: 1px solid var(--mv-border, rgba(127, 127, 127, .35)); }
108
+ .mv-panel .mv-disclosure { min-width: 0; border-top: 1px solid var(--mv-border, var(--mist-border, rgba(127, 127, 127, .35))); }
109
+ .mv-panel .mv-disclosure:last-of-type { border-bottom: 1px solid var(--mv-border, var(--mist-border, rgba(127, 127, 127, .35))); }
109
110
  .mv-panel .mv-disclosure summary { display: flex; align-items: center; justify-content: space-between; gap: .75rem; padding: .9rem 0; font-weight: 600; cursor: pointer; list-style: none; }
110
111
  .mv-panel .mv-disclosure summary::-webkit-details-marker { display: none; }
111
- .mv-panel .mv-disclosure summary::after { color: var(--mv-muted, #6d7772); content: '+'; font-size: 1.3em; font-weight: 400; line-height: 1; }
112
+ .mv-panel .mv-disclosure summary::after { color: var(--mv-muted, var(--mist-muted, #6d7772)); content: '+'; font-size: 1.3em; font-weight: 400; line-height: 1; }
112
113
  .mv-panel .mv-disclosure[open] summary::after { content: '−'; }
113
114
  .mv-panel .mv-disclosure-body { display: grid; gap: .65rem; padding: 0 0 1rem; }
114
115
  .mv-panel .mv-disclosure-body label, .mv-panel .mv-import label { display: grid; gap: .4rem; }
115
116
  .mv-panel .mv-disclosure-body > button { justify-self: start; }
116
- .mv-panel .mv-import { display: grid; gap: .55rem; margin-top: .8rem; padding-top: .9rem; border-top: 1px solid var(--mv-border, rgba(127, 127, 127, .35)); }
117
+ .mv-panel .mv-import { display: grid; gap: .55rem; margin-top: .8rem; padding-top: .9rem; border-top: 1px solid var(--mv-border, var(--mist-border, rgba(127, 127, 127, .35))); }
117
118
  .mv-panel .mv-confirm { margin-bottom: 1.25rem; }
118
119
  .mv-panel .mv-confirm p { margin: .55rem 0 .9rem; }
119
120
  .mv-panel .mv-parts, .mv-panel .mv-notice { margin-top: .9rem; }
120
- .mv-panel .mv-error { color: var(--mv-error, #b33b3b); font-size: .9em; }
121
+ .mv-panel .mv-error { color: var(--mv-error, var(--mist-error, #b33b3b)); font-size: .9em; }
121
122
  @media (prefers-color-scheme: dark) {
122
123
  .mv-panel { color-scheme: dark; }
123
- .mv-panel .mv-muted, .mv-panel input::placeholder, .mv-panel .mv-disclosure summary::after { color: var(--mv-muted, #afbdb5); }
124
- .mv-panel .mv-error { color: var(--mv-error, #ff9999); }
125
- .mv-panel .mv-status-text[data-state=error] strong::before { background: var(--mv-error, #ff9999); }
124
+ .mv-panel .mv-muted, .mv-panel input::placeholder, .mv-panel .mv-disclosure summary::after { color: var(--mv-muted, var(--mist-muted, #afbdb5)); }
125
+ .mv-panel .mv-error { color: var(--mv-error, var(--mist-error, #ff9999)); }
126
+ .mv-panel .mv-status-text[data-state=error] strong::before { background: var(--mv-error, var(--mist-error, #ff9999)); }
126
127
  }
127
128
  @media (prefers-reduced-motion: reduce) { .mv-panel .mv-switch input::before { transition: none; } }
128
129
  @media (forced-colors: active) {
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tik-choco/mistvault",
3
- "version": "0.2.0",
4
- "description": "Browser-encrypted distributed vaults with portable transport and optional Preact controls.",
3
+ "version": "0.3.0",
4
+ "description": "Browser-encrypted distributed vaults with portable transport and optional framework-independent Web Components UI.",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
7
7
  "repository": {
@@ -19,6 +19,11 @@
19
19
  "types": "./dist/preact/index.d.ts",
20
20
  "default": "./dist/preact/index.js"
21
21
  },
22
+ "./elements": {
23
+ "types": "./dist/elements/index.d.ts",
24
+ "default": "./dist/elements/index.js"
25
+ },
26
+ "./elements.css": "./dist/preact/ui.css",
22
27
  "./ui.css": "./dist/preact/ui.css"
23
28
  },
24
29
  "files": [
@@ -34,7 +39,7 @@
34
39
  "prepare": "npm run build"
35
40
  },
36
41
  "devDependencies": {
37
- "@tik-choco/mistai": "github:tik-choco-lab/mistai",
42
+ "@tik-choco/mistai": "^0.10.5",
38
43
  "happy-dom": "^21.0.4",
39
44
  "preact": "^10.29.1",
40
45
  "typescript": "~6.0.2",
@@ -1,13 +0,0 @@
1
- import type { VaultMode } from '../settings.js';
2
- interface RoomControlsProps {
3
- locale?: string;
4
- mode: VaultMode;
5
- room: string;
6
- controller: {
7
- configure(mode: VaultMode, room: string): boolean;
8
- };
9
- disableUnchanged?: boolean;
10
- onInvalid(): void;
11
- }
12
- export declare function RoomControls(props: RoomControlsProps): import("preact").JSX.Element;
13
- export {};
@@ -1,12 +0,0 @@
1
- import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "preact/jsx-runtime";
2
- import { useLayoutEffect, useState } from 'preact/hooks';
3
- import { vaultMessage } from '../i18n.js';
4
- import { validVaultRoom } from '../settings.js';
5
- export function RoomControls(props) {
6
- const [mode, setMode] = useState(props.mode), [room, setRoom] = useState(props.room);
7
- useLayoutEffect(() => { setMode(props.mode); setRoom(props.room); }, [props.mode, props.room, props.controller]);
8
- const t = (key) => vaultMessage(props.locale, key);
9
- return _jsxs(_Fragment, { children: [_jsxs("label", { children: [t('mode'), _jsxs("select", { value: mode, onChange: e => setMode(e.currentTarget.value), children: [_jsx("option", { value: "auto", children: t('auto') }), _jsx("option", { value: "custom", children: t('custom') }), _jsx("option", { value: "off", children: t('off') })] })] }), mode === 'custom' && _jsxs("label", { children: [t('room'), _jsx("input", { value: room, maxLength: 96, "aria-invalid": !validVaultRoom(room), onInput: e => setRoom(e.currentTarget.value) })] }), _jsx("button", { type: "button", disabled: mode === 'custom' && !validVaultRoom(room) ||
10
- props.disableUnchanged && mode === props.mode && (mode !== 'custom' || room === props.room), onClick: () => { if (!props.controller.configure(mode, room))
11
- props.onInvalid(); }, children: t('apply') })] });
12
- }