@lengmoxxl/sdk 0.1.13 → 0.1.50

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.md CHANGED
@@ -53,6 +53,30 @@ SDK 连接本机或 SSH 机器上的旺财后台进程,提供终端、文件
53
53
  `allow-same-origin`;收到来源为该 frame、`event.data === host.preview.message` 的消息后
54
54
  `postMessage(html, '*')`。预览会执行其中脚本。
55
55
 
56
+ ## 快捷键
57
+
58
+ `@lengmoxxl/sdk/keys` 做前端的键:写序列、对按键,插件只声明“哪个序列做什么”,窗口级键位把 trie 交进来复用同一套匹配。
59
+
60
+ ```ts
61
+ import { bindKeys } from '@lengmoxxl/sdk/keys';
62
+
63
+ bindKeys(panel, [
64
+ { keys: 'j', run: () => move(1) },
65
+ { keys: 'gg', run: () => move(-Infinity) },
66
+ { keys: '<C-l>', run: open },
67
+ ]);
68
+ ```
69
+
70
+ - 序列按 Neovim 记法写:`gg`、`<C-l>`、`<Enter>`、`<Down>`;字母区分大小写,字母上的 Shift 就是大写(`<S-x>` 与 `X` 同一个键),只有具名键(如 `<S-Tab>`)才把 Shift 当修饰键。
71
+ - 绑定只在焦点位于 `element` 内时生效;按下没有对应动作的键不拦截,页面照常收到。
72
+ - 一个既能结束又能继续的前缀(`g` 与 `gg`)等 800ms(`timeout` 可改)再执行,等的时候再按一下就接着匹配,按别的键则结束等待并把这一按从头匹配(该按的绑定照常执行);点击页面也作废。
73
+ - 元素里有输入框时,默认只有写了 `insert: true` 的绑定在框内生效(框里的字母归框);整页就是编辑器时用 `{ fields: 'all' }`。
74
+ - `ignore(event)` 直接放行某些按键。
75
+ - 返回值是解绑函数,React 里 `useEffect(() => bindKeys(...))` 直接返回即可;序列的中间状态按元素保存,重新绑定不会打断按了一半的 `gg`。
76
+
77
+ 窗口级键位(`init.ts` 的 `keys`、插件的 `keys` 导出、leader、which-key 提示)与插件页用的是同一套匹配:内核用
78
+ `bindTries` 交上自己按页面挑好的 trie 和画提示、离框的回调,绑定本身仍由主进程执行。
79
+
56
80
  ## 插件配置
57
81
 
58
82
  `host.config` 是浅合并,避免把自定义字段命名为 `theme`,配色键见
package/dist/keys.d.ts ADDED
@@ -0,0 +1,77 @@
1
+ /** One press: the modifiers held and the key they were held for, named as `event.key` names it. */
2
+ interface Stroke {
3
+ ctrl: boolean;
4
+ alt: boolean;
5
+ shift: boolean;
6
+ meta: boolean;
7
+ key: string;
8
+ }
9
+ interface KeyBinding {
10
+ keys: string;
11
+ run(): void;
12
+ insert?: boolean;
13
+ }
14
+ /**
15
+ * One press, written either as `<C-Space>` or as `C-Space`, and read as nothing when it names no key. Shift is carried
16
+ * by the character's case for a letter, as Neovim's is, and stays a modifier only for a named key, whose name cannot
17
+ * show it.
18
+ */
19
+ export declare function readStroke(text: string): Stroke | undefined;
20
+ /** Whether the press was made in something the selector names — including inside a shadow tree, since a press there is
21
+ * retargeted to its host and only the path it took says where it came from. */
22
+ export declare const pressIn: (event: Event, selector: string) => boolean;
23
+ /** Whether the press was made in a field. */
24
+ export declare const isEditable: (event: Event) => boolean;
25
+ /** A node of the sequences bound: what a prefix leads to, how a hint names that press, and the binding that ends there,
26
+ * if one does. */
27
+ export interface TrieNode<T> {
28
+ children: Map<string, TrieNode<T>>;
29
+ label: string;
30
+ binding?: T;
31
+ }
32
+ export type Tries<B extends KeyBinding> = {
33
+ outside: TrieNode<B>;
34
+ field: TrieNode<B>;
35
+ };
36
+ /**
37
+ * The two tries a set of bindings is matched in: every binding outside a field, and only those that say `insert` inside
38
+ * one — or all of them there when the page is an editor, which is what `fields: 'all'` says.
39
+ */
40
+ export declare function triesOf<B extends KeyBinding>(bindings: B[], options?: {
41
+ leader?: Stroke;
42
+ fields?: 'all';
43
+ }): Tries<B>;
44
+ /** The options both entry points take. */
45
+ interface KeyOptions {
46
+ /** Presses the engine leaves to whatever is behind it, such as the ones another pane of the same panel reads for itself. */
47
+ ignore?(event: KeyboardEvent): boolean;
48
+ /** How long a prefix waits for the press that would continue it; left out, the engine's own default applies. */
49
+ timeout?: number;
50
+ }
51
+ /** What `bindKeys` takes beyond `KeyOptions`: how its tries are built. */
52
+ interface PageOptions extends KeyOptions {
53
+ /** `all`, or left out for the tries `triesOf` builds. */
54
+ fields?: 'all';
55
+ }
56
+ /** What `bindTries` takes beyond `KeyOptions`: what it tells the caller, and the presses it takes first. */
57
+ interface BindOptions<B extends KeyBinding> extends KeyOptions {
58
+ /** The prefix as it now stands: the node it reached and how its presses are written, told again each time a press makes
59
+ * it longer — then nothing, once the wait is over, however it ended. */
60
+ prefix?(node: TrieNode<B> | undefined, labels: string[]): void;
61
+ /** A press taken before matching, where a caller leaves a field or takes a press the field would otherwise get, such as
62
+ * the Escape that should end a waiting prefix; it is told whether a prefix is waiting, and true takes the press and ends
63
+ * the matching there. */
64
+ before?(event: KeyboardEvent, waiting: boolean): boolean;
65
+ }
66
+ /**
67
+ * Binds keys whose tries the caller picks per press, for a keymap whose keys depend on where the press was made. A press
68
+ * that continues nothing ends the wait and is matched again from the start, as Vim does; one that matches nothing at all
69
+ * is left to whatever is behind it.
70
+ */
71
+ export declare function bindTries<B extends KeyBinding>(element: HTMLElement, triesFor: (event: KeyboardEvent) => Tries<B>, options: BindOptions<B>): () => void;
72
+ /**
73
+ * Binds a page's own keys, given as the bindings it declares: they answer while the focus is inside `element`, and their
74
+ * tries are the two `triesOf` makes of them.
75
+ */
76
+ export declare function bindKeys<B extends KeyBinding>(element: HTMLElement, bindings: B[], options?: PageOptions): () => void;
77
+ export {};
package/dist/keys.js ADDED
@@ -0,0 +1,197 @@
1
+ // keys.ts
2
+ var NAMES = {
3
+ cr: "Enter",
4
+ enter: "Enter",
5
+ esc: "Escape",
6
+ escape: "Escape",
7
+ tab: "Tab",
8
+ space: " ",
9
+ bs: "Backspace",
10
+ backspace: "Backspace",
11
+ del: "Delete",
12
+ delete: "Delete",
13
+ up: "ArrowUp",
14
+ down: "ArrowDown",
15
+ left: "ArrowLeft",
16
+ right: "ArrowRight",
17
+ home: "Home",
18
+ end: "End",
19
+ pageup: "PageUp",
20
+ pagedown: "PageDown",
21
+ insert: "Insert"
22
+ };
23
+ for (let at = 1; at <= 12; at += 1) NAMES[`f${at}`] = `F${at}`;
24
+ var strokeKey = (stroke) => `${Number(stroke.ctrl)}${Number(stroke.alt)}${Number(stroke.shift)}${Number(stroke.meta)}:${stroke.key}`;
25
+ function readStroke(text) {
26
+ const written = text.startsWith("<") && text.endsWith(">") ? text.slice(1, -1) : text;
27
+ const stroke = { ctrl: false, alt: false, shift: false, meta: false, key: "" };
28
+ let rest = written;
29
+ while (rest.length > 2 && rest[1] === "-") {
30
+ const modifier = rest[0].toLowerCase();
31
+ if (modifier === "c") stroke.ctrl = true;
32
+ else if (modifier === "a" || modifier === "m") stroke.alt = true;
33
+ else if (modifier === "d") stroke.meta = true;
34
+ else if (modifier === "s") stroke.shift = true;
35
+ else break;
36
+ rest = rest.slice(2);
37
+ }
38
+ if (rest.length === 1) return { ...stroke, shift: false, key: stroke.shift && rest.toLowerCase() !== rest.toUpperCase() ? rest.toUpperCase() : rest };
39
+ const named = NAMES[rest.toLowerCase()];
40
+ return named ? { ...stroke, key: named } : void 0;
41
+ }
42
+ function parseKeys(text, leader) {
43
+ const presses = [];
44
+ for (let at = 0; at < text.length; ) {
45
+ if (/\s/.test(text[at])) {
46
+ at += 1;
47
+ continue;
48
+ }
49
+ let token;
50
+ if (text[at] === "<") {
51
+ const end = text.indexOf(">", at);
52
+ if (end < 0) return void 0;
53
+ token = text.slice(at + 1, end);
54
+ at = end + 1;
55
+ } else {
56
+ token = text[at];
57
+ at += 1;
58
+ }
59
+ if (token.toLowerCase() === "leader") {
60
+ if (!leader) return void 0;
61
+ presses.push(leader);
62
+ continue;
63
+ }
64
+ const stroke = readStroke(token);
65
+ if (!stroke) return void 0;
66
+ presses.push(stroke);
67
+ }
68
+ return presses.length ? presses : void 0;
69
+ }
70
+ var baseChar = (code) => code.startsWith("Key") ? code.slice(3).toLowerCase() : code.startsWith("Digit") ? code.slice(5) : void 0;
71
+ function strokesOf(event) {
72
+ const { ctrlKey: ctrl, altKey: alt, metaKey: meta } = event;
73
+ if (event.key.length === 1) {
74
+ const stroke = { ctrl, alt, shift: false, meta, key: event.key };
75
+ const base = alt ? baseChar(event.code) : void 0;
76
+ return base && base !== event.key ? [stroke, { ...stroke, key: base }] : [stroke];
77
+ }
78
+ if (event.key === "Dead" || event.key === "Unidentified" || event.key === "Process") return [];
79
+ return [{ ctrl, alt, shift: event.shiftKey, meta, key: event.key }];
80
+ }
81
+ var pressIn = (event, selector) => event.composedPath().some((node) => node instanceof Element && node.matches(selector));
82
+ var isEditable = (event) => pressIn(event, 'input, textarea, [contenteditable=""], [contenteditable="true"]');
83
+ function labelOf(stroke) {
84
+ const modifiers = `${stroke.ctrl ? "C-" : ""}${stroke.alt ? "A-" : ""}${stroke.shift ? "S-" : ""}${stroke.meta ? "D-" : ""}`;
85
+ const key = stroke.key.length === 1 ? stroke.key : stroke.key.toUpperCase();
86
+ return `${modifiers}${stroke.key === " " ? "SPC" : key}`;
87
+ }
88
+ function buildTrie(bindings, leader) {
89
+ const root = { children: /* @__PURE__ */ new Map(), label: "" };
90
+ for (const binding of bindings) {
91
+ const presses = parseKeys(binding.keys, leader);
92
+ if (!presses) {
93
+ console.error(`Keymap ${binding.keys}: cannot be read`);
94
+ continue;
95
+ }
96
+ let node = root;
97
+ for (const stroke of presses) {
98
+ const key = strokeKey(stroke);
99
+ const label = labelOf(stroke);
100
+ let child = node.children.get(key);
101
+ if (child) child.label = label;
102
+ else node.children.set(key, child = { children: /* @__PURE__ */ new Map(), label });
103
+ node = child;
104
+ }
105
+ node.binding = binding;
106
+ }
107
+ return root;
108
+ }
109
+ function nodeAt(trie, path) {
110
+ let node = trie;
111
+ for (const stroke of path) {
112
+ node = node.children.get(strokeKey(stroke));
113
+ if (!node) return void 0;
114
+ }
115
+ return node;
116
+ }
117
+ function triesOf(bindings, options = {}) {
118
+ const outside = buildTrie(bindings, options.leader);
119
+ return { outside, field: options.fields === "all" ? outside : buildTrie(bindings.filter((binding) => binding.insert), options.leader) };
120
+ }
121
+ var PREFIX_WAIT = 800;
122
+ var prefixes = /* @__PURE__ */ new WeakMap();
123
+ function bindTries(element, triesFor, options) {
124
+ const stopTimer = () => clearTimeout(prefixes.get(element)?.timer);
125
+ const endPrefix = () => {
126
+ stopTimer();
127
+ if (prefixes.delete(element)) options.prefix?.(void 0, []);
128
+ };
129
+ const runAfterWait = (binding) => {
130
+ endPrefix();
131
+ binding?.run();
132
+ };
133
+ const takeEvent = (event) => {
134
+ event.preventDefault();
135
+ event.stopPropagation();
136
+ };
137
+ const onKeyDown = (event) => {
138
+ if (event.isComposing || event.repeat) return;
139
+ const started = prefixes.get(element);
140
+ if (options.before?.(event, started !== void 0)) {
141
+ takeEvent(event);
142
+ endPrefix();
143
+ return;
144
+ }
145
+ if (options.ignore?.(event)) return;
146
+ const { outside, field } = triesFor(event);
147
+ const trie = isEditable(event) ? field : outside;
148
+ const takePress = (next, path) => {
149
+ takeEvent(event);
150
+ if (next.binding && !next.children.size) {
151
+ runAfterWait(next.binding);
152
+ return;
153
+ }
154
+ stopTimer();
155
+ const timer = window.setTimeout(() => runAfterWait(next.binding), options.timeout ?? PREFIX_WAIT);
156
+ prefixes.set(element, { path, timer });
157
+ options.prefix?.(next, path.map(labelOf));
158
+ };
159
+ const strokes = strokesOf(event);
160
+ const tryStrokes = (base) => {
161
+ for (const stroke of strokes) {
162
+ const path = [...base, stroke];
163
+ const next = nodeAt(trie, path);
164
+ if (next) {
165
+ takePress(next, path);
166
+ return true;
167
+ }
168
+ }
169
+ return false;
170
+ };
171
+ if (started) {
172
+ if (tryStrokes(started.path)) return;
173
+ endPrefix();
174
+ }
175
+ tryStrokes([]);
176
+ };
177
+ const onPointerDown = () => endPrefix();
178
+ element.addEventListener("keydown", onKeyDown, true);
179
+ element.addEventListener("pointerdown", onPointerDown, true);
180
+ return () => {
181
+ element.removeEventListener("keydown", onKeyDown, true);
182
+ element.removeEventListener("pointerdown", onPointerDown, true);
183
+ };
184
+ }
185
+ function bindKeys(element, bindings, options = {}) {
186
+ const { fields, ...shared } = options;
187
+ let own;
188
+ return bindTries(element, () => own ??= triesOf(bindings, { fields }), shared);
189
+ }
190
+ export {
191
+ bindKeys,
192
+ bindTries,
193
+ isEditable,
194
+ pressIn,
195
+ readStroke,
196
+ triesOf
197
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@lengmoxxl/sdk",
3
- "version": "0.1.13",
3
+ "version": "0.1.50",
4
4
  "description": "Client SDK for WangCai: connect to a local or remote machine and drive its pty, files and git",
5
5
  "license": "MIT",
6
6
  "repository": {
@@ -33,6 +33,10 @@
33
33
  "types": "./dist/bridge.d.ts",
34
34
  "default": "./dist/bridge.cjs"
35
35
  },
36
+ "./keys": {
37
+ "types": "./dist/keys.d.ts",
38
+ "default": "./dist/keys.js"
39
+ },
36
40
  "./channel": {
37
41
  "types": "./dist/channel.d.ts"
38
42
  },
@@ -43,7 +47,7 @@
43
47
  "registry": "https://registry.npmjs.org/"
44
48
  },
45
49
  "scripts": {
46
- "build": "esbuild index.ts --outfile=dist/index.cjs --bundle --platform=node --target=node22 --packages=external && esbuild bridge.ts --outfile=dist/bridge.cjs --bundle --platform=node --target=node22 --packages=external && tsc",
50
+ "build": "esbuild index.ts --outfile=dist/index.cjs --bundle --platform=node --target=node22 --packages=external && esbuild bridge.ts --outfile=dist/bridge.cjs --bundle --platform=node --target=node22 --packages=external && esbuild keys.ts --outfile=dist/keys.js --format=esm --bundle --platform=browser --target=chrome140 && tsc",
47
51
  "prepack": "npm run build",
48
52
  "typecheck": "tsc --noEmit"
49
53
  },