@rig-works/dashboard 0.0.0-stage → 0.0.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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Trinitytime
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,237 @@
1
- # Temporary Holding Version
1
+ # dashboard
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 다른 플러그인이 선언한 JSON으로 웹 화면을 그려 주는 Rig 플러그인입니다.
4
+ 플러그인은 HTML을 만들지 않고, shared의 `dashboard:page` 공간에 **화면 JSON**을 쓰면 됩니다. 컨트롤(토글, 입력, 버튼 등)을 조작하면 그 플러그인에 **신호(signal)** 가 전달됩니다. `requires` 선언은 필요 없습니다.
5
+
6
+ ```
7
+ 플러그인 ──shared.set──▶ dashboard:page / dashboard:menu ──▶ 브라우저(/dashboard/<key>)
8
+ 플러그인 ◀──signal.on─── <플러그인 id>:<화면 key>:<컨트롤 id> ◀── 사용자 조작
9
+ ```
10
+
11
+ ## 빠른 시작
12
+
13
+ ```ts
14
+ import type { RigPlugin } from '@rig-works/plugin'
15
+
16
+ const plugin: RigPlugin = async (ctx) => {
17
+ // 1. 화면 등록: /dashboard/hello 로 열린다
18
+ await ctx.shared.set('dashboard:page', 'hello', {
19
+ title: 'Hello',
20
+ items: [
21
+ { type: 'toggle', id: 'enabled', label: '사용', value: false },
22
+ { type: 'button', id: 'run', text: '실행', variant: 'primary' },
23
+ ],
24
+ })
25
+
26
+ // 2. 사이드바 메뉴 등록
27
+ await ctx.shared.set('dashboard:menu', 'hello', { name: 'Hello', page: 'hello' })
28
+
29
+ // 3. 조작 받기: <내 플러그인 id>:<화면 key>:<컨트롤 id>
30
+ ctx.signal.on('myplugin:hello:enabled', (e) => ctx.log.info('enabled =', e.value))
31
+ ctx.signal.on('myplugin:hello:run', () => ctx.log.info('run'))
32
+ }
33
+ export default plugin
34
+ ```
35
+
36
+ > 신호 이름 앞은 화면을 등록한 **플러그인 id**(package.json의 `rig.id`)입니다. 위 예시의 `myplugin`을 자신의 id로 바꿔 쓰세요.
37
+
38
+ ## 화면 정의
39
+
40
+ 타입 `DashboardPage`, `DashboardItem`, `DashboardMenuItem` 등은 패키지에서 내보냅니다. `import type { DashboardPage } from '@rig-works/dashboard'`로 가져와 쓸 수 있습니다.
41
+
42
+ ### 화면 (`dashboard:page`)
43
+
44
+ - 공간: `dashboard:page`
45
+ - key: 화면마다 하나. 영문자, 숫자, `.`, `-`, `_` 1~64자. 이 값이 주소 `/dashboard/<key>`가 되고, 이벤트 신호 이름에도 들어갑니다.
46
+ - value: 아래 형태의 JSON 객체. `items` 배열이 없는 값은 화면으로 인정하지 않습니다.
47
+
48
+ | 필드 | 타입 | 설명 |
49
+ |---|---|---|
50
+ | `title` | string | 화면 제목. 없으면 key를 씁니다 |
51
+ | `description` | string | 제목 아래 설명 |
52
+ | `status` | `{ text, tone? }` | 제목 옆 상태 배지 |
53
+ | `items` | array | 본문 항목 (아래 참고) |
54
+
55
+ `/dashboard/`(key 없이)는 제목 순으로 첫 번째 화면을 보여 줍니다. 없는 key는 404입니다.
56
+
57
+ ### 메뉴 (`dashboard:menu`)
58
+
59
+ - 공간: `dashboard:menu`, key: 항목마다 하나 (key 규칙은 화면과 같음)
60
+ - value: `{ "name": "Hello", "page": "hello", "order": 10 }`
61
+
62
+ | 필드 | 타입 | 설명 |
63
+ |---|---|---|
64
+ | `name` | string | 메뉴에 보이는 이름 |
65
+ | `page` | string | 이동할 화면 key |
66
+ | `order` | number | 정렬 순서. 작을수록 위, 기본 0, 같으면 `name` 순 |
67
+
68
+ 메뉴와 화면은 독립입니다. 메뉴 없이도 주소로 열 수 있고, 없는 화면을 가리키는 메뉴도 그대로 나옵니다. 형태가 틀린 메뉴 값은 건너뜁니다.
69
+
70
+ ### 항목 (`items`)
71
+
72
+ 항목은 `type`으로 구분합니다. 모르는 `type`은 건너뜁니다.
73
+
74
+ **표시 항목**
75
+
76
+ | type | 필드 | 설명 |
77
+ |---|---|---|
78
+ | `heading` | `text`, `level?` (2 \| 3) | 소제목 |
79
+ | `text` | `text`, `muted?` | 문단. `muted`면 흐리게 |
80
+ | `divider` | | 구분선 |
81
+ | `badge` | `text`, `tone?` | 배지. `tone`은 `success` \| `warning` \| `danger` |
82
+ | `section` | `title`, `description?`, `open?`, `items` | 접이식 묶음. `open: false`면 접힌 채로 시작. `items`에 항목을 다시 넣을 수 있습니다 |
83
+
84
+ **컨트롤** (조작할 수 있는 항목)
85
+
86
+ | type | 필드 | 이벤트 `value` |
87
+ |---|---|---|
88
+ | `toggle` | `value?` (boolean) | `true` / `false` |
89
+ | `input` | `inputType?` (`text` \| `number` \| `password`), `value?`, `placeholder?`, `min?`, `max?`, `pattern?`, `required?` | 문자열. `number`는 숫자(비우면 `null`) |
90
+ | `textarea` | `value?`, `rows?`, `required?` | 문자열 |
91
+ | `select` | `options` (문자열 또는 `{ value, label? }` 배열), `value?` | 선택한 `value` 문자열 |
92
+ | `button` | `text?`, `variant?` (`primary` \| `danger`) | 없음 (`null`) |
93
+ | `list` | `items: { label, badge?: { text, tone? } }[]` | 읽기 전용 |
94
+ | `table` | `columns: string[]`, `rows: (string \| number)[][]` | 읽기 전용 |
95
+
96
+ 모든 컨트롤은 `id`, `disabled`, `error`를 공통으로 가집니다.
97
+
98
+ - `id`: 이벤트 이름에 쓰입니다. **없으면 읽기 전용**이라 신호가 나가지 않습니다.
99
+ - `disabled`: `true`면 조작할 수 없습니다.
100
+ - `error`: 있으면 컨트롤 아래에 오류 문구로 보입니다.
101
+
102
+ **행 (row)**
103
+
104
+ 컨트롤은 한 줄(row)에 담겨 그려집니다. 두 가지 방법이 있습니다.
105
+
106
+ ```jsonc
107
+ // 1. 컨트롤에 라벨을 바로 붙이면 컨트롤 하나만 든 row가 됩니다
108
+ { "type": "toggle", "id": "enabled", "label": "사용", "description": "끄면 동작하지 않습니다" }
109
+
110
+ // 2. row로 라벨 하나에 컨트롤 여러 개를 묶습니다
111
+ {
112
+ "type": "row", "label": "Systray", "meta": "v0.0.0 · buwon", "description": "시스템 트레이 메뉴",
113
+ "items": [
114
+ { "type": "toggle", "id": "toggle-systray", "value": true },
115
+ { "type": "button", "id": "remove-systray", "text": "삭제", "variant": "danger", "disabled": true }
116
+ ]
117
+ }
118
+ ```
119
+
120
+ | 필드 | 설명 |
121
+ |---|---|
122
+ | `label` | 왼쪽 라벨. 줄의 첫 입력 컨트롤(toggle, input, textarea, select)과 연결됩니다 |
123
+ | `meta` | 라벨 옆의 부연 |
124
+ | `description` | 라벨 아래 설명 |
125
+
126
+ `textarea`, `list`, `table`이 들어 있는 줄은 컨트롤이 라벨 아래 한 줄을 다 씁니다.
127
+
128
+ ### 전체 예시
129
+
130
+ ```json
131
+ {
132
+ "title": "Plugins",
133
+ "description": "설치된 플러그인을 켜고 끕니다.",
134
+ "status": { "text": "3/4 활성", "tone": "success" },
135
+ "items": [
136
+ {
137
+ "type": "section",
138
+ "title": "설치된 플러그인",
139
+ "items": [
140
+ {
141
+ "type": "row", "label": "Systray", "meta": "v0.0.0",
142
+ "items": [
143
+ { "type": "toggle", "id": "toggle-systray", "value": true },
144
+ { "type": "button", "id": "remove-systray", "text": "삭제", "variant": "danger", "disabled": true }
145
+ ]
146
+ }
147
+ ]
148
+ }
149
+ ]
150
+ }
151
+ ```
152
+
153
+ 이 화면은 dashboard가 기본으로 등록하는 `plugins` 화면(`src/plugins-page.ts`)과 같은 모양입니다.
154
+
155
+ ## 이벤트 연결
156
+
157
+ ### 신호 이름
158
+
159
+ 컨트롤을 조작하면 아래 이름의 신호가 발행됩니다.
160
+
161
+ ```
162
+ <화면을 등록한 플러그인 id>:<화면 key>:<컨트롤 id>
163
+ ```
164
+
165
+ 예: 플러그인 `myplugin`이 key `hello` 화면에 `id: "enabled"` 토글을 넣었다면 `myplugin:hello:enabled`.
166
+ 앞에 플러그인 id가 붙으므로 플러그인끼리 화면 key나 컨트롤 id가 겹쳐도 신호가 섞이지 않습니다.
167
+
168
+ - 컨트롤 `id`는 영문자, 숫자, `.`, `-`, `_` 1~64자여야 합니다. 어긋나면 요청이 400으로 거부됩니다.
169
+ - 화면의 소유자는 shared의 소유권 규칙을 따릅니다. 화면 key를 **처음 쓴 플러그인**이 소유자이고, 그 플러그인의 신호로 전달됩니다.
170
+
171
+ ### 받는 쪽
172
+
173
+ ```ts
174
+ ctx.signal.on('myplugin:hello:enabled', (e) => {
175
+ // e.value: 위 표의 "이벤트 value"
176
+ })
177
+ ```
178
+
179
+ payload는 항상 `{ value }`입니다. 값이 없으면(`button`) `value`는 `null`입니다.
180
+
181
+ ### 언제 발행되는가
182
+
183
+ | 컨트롤 | 발행 시점 |
184
+ |---|---|
185
+ | `toggle`, `select` | 값을 바꾼 즉시 |
186
+ | `input`, `textarea` | 값을 바꾸고 포커스가 빠질 때(`change`) |
187
+ | `button` | 클릭할 때 |
188
+
189
+ - `input`의 `required`, `min`, `max`, `pattern` 검사에 실패하면 신호를 보내지 않고 브라우저의 검증 안내만 보입니다. 서버에서 한 번 더 검증하지는 않으므로 받는 쪽에서도 `value`를 확인하세요.
190
+ - 신호는 전달만 합니다. 브라우저에서 바꾼 값은 그 화면에만 남을 뿐, 저장하지 않습니다.
191
+
192
+ ### 화면을 갱신하는 법
193
+
194
+ 상태는 플러그인이 가집니다. 신호를 받아 처리한 뒤 **같은 key로 화면을 다시 쓰면** 열려 있는 브라우저가 알아서 갱신됩니다.
195
+
196
+ ```ts
197
+ let enabled = false
198
+ const render = () =>
199
+ ctx.shared.set('dashboard:page', 'hello', {
200
+ title: 'Hello',
201
+ status: { text: enabled ? '켜짐' : '꺼짐', tone: enabled ? 'success' : 'warning' },
202
+ items: [{ type: 'toggle', id: 'enabled', label: '사용', value: enabled }],
203
+ })
204
+
205
+ await render()
206
+ ctx.signal.on('myplugin:hello:enabled', (e) => {
207
+ enabled = e.value === true
208
+ render()
209
+ })
210
+ ```
211
+
212
+ 잘못된 입력을 알리려면 같은 방법으로 컨트롤에 `error`를 넣어 다시 씁니다.
213
+
214
+ ```ts
215
+ { type: 'input', id: 'port', label: '포트', value: 99999, error: '1~65535 사이여야 합니다' }
216
+ ```
217
+
218
+ 화면이나 메뉴를 지우려면 `ctx.shared.delete('dashboard:page', key)` 또는 `ctx.shared.set('dashboard:page', key, null)`을 호출합니다. 값을 쓴 플러그인이 비활성화되면 그 플러그인의 화면과 메뉴는 함께 사라집니다.
219
+
220
+ ## 동작
221
+
222
+ - 화면이나 메뉴가 바뀌면 서버가 SSE(`/dashboard/api/events`)로 브라우저에 알립니다. 연속된 변경은 1초 안에 하나로 묶습니다.
223
+ - 브라우저는 알림을 받으면 화면을 다시 받아 **바뀐 컨트롤만** 교체합니다. 입력 중인 컨트롤은 건드리지 않습니다.
224
+ - 항목 구성(개수, 순서)이 바뀌면 본문 전체를 교체합니다. 이때 `section`의 접힘 상태는 초기화됩니다.
225
+ - 보고 있던 화면이 지워지면 페이지를 새로 고칩니다.
226
+ - 모든 값은 외부 입력으로 보고 문자열로 바꿔 그리며 HTML은 이스케이프합니다. 스키마를 검증하지는 않으므로 형태가 틀려도 오류 없이 해당 항목만 건너뜁니다.
227
+
228
+ ## 이 플러그인이 하는 일
229
+
230
+ - `/dashboard/`에서 위 화면들을 서빙하고, 코어가 `/` 요청을 `/dashboard`로 보내도록 shared `http`의 `/`를 등록합니다.
231
+ - 기본 화면 `plugins`를 등록합니다. 지금은 고정된 더미 데이터입니다.
232
+ - 트레이 메뉴에 `Dashboard` 항목(`tray:menu`, 신호 `dashboard:open`)을 넣어, 클릭하면 기본 브라우저로 대시보드를 엽니다.
233
+ - 주소(host, port)는 코어가 shared `http`에 알린 값으로 만듭니다.
234
+
235
+ ## 제한
236
+
237
+ - 사이드바 하위 메뉴, 화면 안의 탭, 컨트롤의 즉시 검증(서버 측)은 지원하지 않습니다.
package/lib/client.js ADDED
@@ -0,0 +1,45 @@
1
+ // 대시보드 클라이언트: 컨트롤 이벤트를 서버로 보내고, 서버가 알리면 화면을 다시 받아 바뀐 부분만 교체한다.
2
+ (() => {
3
+ const { page } = document.body.dataset;
4
+ // base는 다른 호스트 표기(localhost와 127.0.0.1)일 수 있어서, fetch와 EventSource는 현재 출처의 경로만 쓴다 (교차 출처면 CORS로 막힌다).
5
+ const base = new URL(document.body.dataset.base, location.href).pathname;
6
+ const leaves = (root) => [...root.querySelectorAll("[data-k]")];
7
+
8
+ const post = (id, value) =>
9
+ fetch(`${base}api/event`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ page, id, value }) });
10
+
11
+ document.addEventListener("change", (e) => {
12
+ const el = e.target;
13
+ if (!(el instanceof HTMLElement) || !el.dataset.ev) return;
14
+ if (!el.checkValidity()) return void el.reportValidity();
15
+ post(el.dataset.ev, el.type === "checkbox" ? el.checked : el.type === "number" ? (el.value === "" ? null : Number(el.value)) : el.value);
16
+ });
17
+ document.addEventListener("click", (e) => {
18
+ const b = e.target instanceof Element && e.target.closest("button[data-ev]");
19
+ if (b) post(b.dataset.ev);
20
+ });
21
+
22
+ // shortcut: 항목 구성이 바뀌면 main 전체를 바꿔 섹션 접힘 상태가 초기화되고, 같은 HTML이면 교체하지 않아 입력 중인 값은 남는다. 필요해지면 접힘 상태를 보존.
23
+ const sync = (a, b) => {
24
+ const [o, n] = [leaves(a), leaves(b)];
25
+ if (o.map((e) => e.dataset.k).join() !== n.map((e) => e.dataset.k).join()) return void (a.innerHTML = b.innerHTML);
26
+ n.forEach((e, i) => {
27
+ if (!o[i].contains(document.activeElement) && o[i].outerHTML !== e.outerHTML) o[i].replaceWith(e);
28
+ });
29
+ };
30
+
31
+ const reload = async () => {
32
+ const res = await fetch(location.href);
33
+ if (!res.ok) return;
34
+ const doc = new DOMParser().parseFromString(await res.text(), "text/html");
35
+ if (doc.body.dataset.page !== page) return location.reload(); // 현재 화면이 사라졌거나 바뀜
36
+ document.title = doc.title;
37
+ const [nav, newNav] = [document.querySelector(".rig-nav-list"), doc.querySelector(".rig-nav-list")];
38
+ if (nav && newNav && !nav.contains(document.activeElement) && nav.innerHTML !== newNav.innerHTML) nav.innerHTML = newNav.innerHTML;
39
+ sync(document.querySelector("main"), doc.querySelector("main"));
40
+ };
41
+
42
+ const es = new EventSource(`${base}api/events`);
43
+ es.onmessage = reload;
44
+ es.onopen = reload; // 재연결 사이에 놓친 변경을 따라잡는다
45
+ })();
@@ -0,0 +1,124 @@
1
+ import { RigPlugin } from "@rig-works/plugin";
2
+ /** 사이드바 메뉴 항목 하나. */
3
+ interface DashboardMenuItem {
4
+ /** 메뉴에 보이는 이름. */
5
+ name: string;
6
+ /** 이동할 화면의 key (dashboard:page의 key). */
7
+ page: string;
8
+ /** 정렬 순서(작을수록 위, 기본 0). */
9
+ order?: number;
10
+ }
11
+ type DashboardTone = 'success' | 'warning' | 'danger';
12
+ /**
13
+ * 컨트롤이 공통으로 갖는 값. 컨트롤을 조작하면 신호 `<화면을 등록한 플러그인 id>:<화면 key>:<id>`가 { value }와 함께 발행된다 (id가 없으면 읽기 전용).
14
+ */
15
+ interface ControlBase {
16
+ id?: string;
17
+ disabled?: boolean;
18
+ /** 있으면 컨트롤 아래에 오류 문구로 보인다. */
19
+ error?: string;
20
+ }
21
+ interface ToggleItem extends ControlBase {
22
+ type: 'toggle';
23
+ value?: boolean;
24
+ }
25
+ interface InputItem extends ControlBase {
26
+ type: 'input';
27
+ inputType?: 'text' | 'number' | 'password';
28
+ value?: string | number;
29
+ placeholder?: string;
30
+ min?: number;
31
+ max?: number;
32
+ pattern?: string;
33
+ required?: boolean;
34
+ }
35
+ interface TextareaItem extends ControlBase {
36
+ type: 'textarea';
37
+ value?: string;
38
+ rows?: number;
39
+ required?: boolean;
40
+ }
41
+ interface SelectItem extends ControlBase {
42
+ type: 'select';
43
+ options: (string | {
44
+ value: string;
45
+ label?: string;
46
+ })[];
47
+ value?: string;
48
+ }
49
+ interface ButtonItem extends ControlBase {
50
+ type: 'button';
51
+ text?: string;
52
+ variant?: 'primary' | 'danger';
53
+ }
54
+ interface ListItem {
55
+ type: 'list';
56
+ items: {
57
+ label: string;
58
+ badge?: {
59
+ text: string;
60
+ tone?: DashboardTone;
61
+ };
62
+ }[];
63
+ }
64
+ interface TableItem {
65
+ type: 'table';
66
+ columns: string[];
67
+ rows: (string | number)[][];
68
+ }
69
+ /** 한 행(row)에 담을 수 있는 컨트롤. */
70
+ type ControlItem = ToggleItem | InputItem | TextareaItem | SelectItem | ButtonItem | ListItem | TableItem;
71
+ /** 행의 왼쪽에 보이는 라벨, 라벨 옆의 부연, 아래의 설명. */
72
+ interface RowLabels {
73
+ label?: string;
74
+ meta?: string;
75
+ description?: string;
76
+ }
77
+ /** 라벨과 컨트롤 여러 개를 한 줄로 묶는다. */
78
+ interface RowItem extends RowLabels {
79
+ type: 'row';
80
+ items: ControlItem[];
81
+ }
82
+ /** 컨트롤을 row 없이 바로 쓰면 그 컨트롤 하나만 든 row로 그려진다 (RowLabels를 함께 쓸 수 있다). */
83
+ type ControlRowItem = ControlItem & RowLabels;
84
+ interface HeadingItem {
85
+ type: 'heading';
86
+ text: string;
87
+ level?: 2 | 3;
88
+ }
89
+ interface TextItem {
90
+ type: 'text';
91
+ text: string;
92
+ muted?: boolean;
93
+ }
94
+ interface DividerItem {
95
+ type: 'divider';
96
+ }
97
+ interface BadgeItem {
98
+ type: 'badge';
99
+ text: string;
100
+ tone?: DashboardTone;
101
+ }
102
+ /** 제목이 있는 접이식 묶음. */
103
+ interface SectionItem {
104
+ type: 'section';
105
+ title: string;
106
+ description?: string;
107
+ /** false면 접힌 채로 보인다. */
108
+ open?: boolean;
109
+ items: DashboardItem[];
110
+ }
111
+ type DashboardItem = HeadingItem | TextItem | DividerItem | BadgeItem | SectionItem | RowItem | ControlRowItem;
112
+ /** 화면 하나. */
113
+ interface DashboardPage {
114
+ title: string;
115
+ description?: string;
116
+ /** 제목 옆의 상태 배지. */
117
+ status?: {
118
+ text: string;
119
+ tone?: DashboardTone;
120
+ };
121
+ items: DashboardItem[];
122
+ }
123
+ declare const plugin: RigPlugin;
124
+ export { type BadgeItem, type ButtonItem, type ControlItem, type ControlRowItem, type DashboardItem, type DashboardMenuItem, type DashboardPage, type DashboardTone, type DividerItem, type HeadingItem, type InputItem, type ListItem, type RowItem, type RowLabels, type SectionItem, type SelectItem, type TableItem, type TextItem, type TextareaItem, type ToggleItem, plugin as default };