Skip to content

Commit bf999c5

Browse files
committed
docs: document QuickTools adapter and custom tab saving
Add acode.registerQuickToolsAdapter, the custom tab save event with respondWith, and the appInstallSource, strings, toast, app and root globals.
1 parent 7b21a58 commit bf999c5

5 files changed

Lines changed: 196 additions & 0 deletions

File tree

‎.vitepress/config.mts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -422,6 +422,10 @@ export default defineConfig({
422422
text: "Context Menu",
423423
link: "/docs/interface-apis/context-menu",
424424
},
425+
{
426+
text: "QuickTools Adapter",
427+
link: "/docs/interface-apis/quicktools-adapter",
428+
},
425429
],
426430
},
427431
{

‎docs/editor-components/editor-file.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -363,6 +363,30 @@ try {
363363
}
364364
```
365365

366+
### Saving a Custom Tab <Badge type="tip" text="v1012+" />
367+
368+
A custom tab gets Acode's normal save controls (the save button, `Ctrl` + `S` and the **Save** command) once it has a `save` listener. In the listener, call `event.respondWith()` synchronously with a promise that resolves to `true` after your data is written. `event.saveAs` is `true` for **Save as**.
369+
370+
```js
371+
const fs = acode.require('fs');
372+
const tab = new EditorFile('data.json', { type: 'custom', content: element });
373+
374+
tab.on('save', (event) => {
375+
event.respondWith(
376+
(async () => {
377+
await fs(fileUrl).writeFile(JSON.stringify(myData));
378+
tab.isUnsaved = false;
379+
return true;
380+
})()
381+
);
382+
});
383+
384+
// Mark the tab as changed so it shows the unsaved indicator.
385+
tab.isUnsaved = true;
386+
```
387+
388+
`respondWith()` can be called only once per save. Resolving to anything other than `true` tells Acode the save didn't happen. For plugin editors that also need QuickTools input, see [QuickTools Adapter](../interface-apis/quicktools-adapter).
389+
366390
### Handling File Events
367391

368392
```js

‎docs/global-apis/acode.md‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -336,12 +336,21 @@ Clears a plugin's broken mark so it can be retried on next load.
336336
acode.clearBrokenPluginMark("com.example.plugin");
337337
```
338338

339+
### `registerQuickToolsAdapter(tab: EditorFile, adapter: QuickToolsAdapter): () => void` <Badge type="tip" text="v1012+" />
340+
341+
Routes QuickTools keys, text and commands to a custom editor tab. Returns a function that removes the adapter. See [QuickTools Adapter](../interface-apis/quicktools-adapter.md).
342+
343+
```js
344+
const dispose = acode.registerQuickToolsAdapter(tab, adapter);
345+
```
346+
339347
## Related APIs
340348

341349
- Commands API (preferred for adding/removing commands): [Commands](../utilities/commands.md)
342350
- CodeMirror editor theme API: [Editor Themes](../utilities/editor-themes.md)
343351
- Static CodeMirror highlighter (versionCode `1008+`): [Code Highlight](../utilities/code-highlight.md)
344352
- File and folder icon packs (versionCode `1012+`): [File Icons](../utilities/file-icons.md)
345353
- Language server API: [LSP](../advanced-apis/lsp.md)
354+
- QuickTools input for custom tabs (versionCode `1012+`): [QuickTools Adapter](../interface-apis/quicktools-adapter.md)
346355
- File handler API: [File Handlers](../advanced-apis/file-handlers.md)
347356
- Terminal API: [Terminal](../advanced-apis/terminal.md)

‎docs/global-apis/global-utilities.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,25 @@ These extra global APIs provide essential information about asset directories, s
2626
## ANDROID_SDK_INT
2727
`<number>` The Android SDK version.
2828

29+
## appInstallSource
30+
`<string | null>` Read-only. Package name of the store that installed Acode, for example `"com.android.vending"` for Google Play, or `null` when unknown (such as a sideloaded APK).
31+
32+
## strings
33+
`<Record<string, string>>` Acode's UI text in the user's current language, keyed by the English text. Use it to match Acode's wording, for example `strings["save"]` or `strings.cancel`. A key can be missing in some languages, so always provide a fallback.
34+
35+
```javascript
36+
const label = strings["search in files"] || "Search in files";
37+
```
38+
39+
## toast
40+
`(message: string, duration?: number) => void` Shows a short message at the bottom of the screen. Same as [`acode.require("toast")`](../ui-components/toast.md).
41+
42+
## app
43+
`<HTMLBodyElement>` The app's `<body>` element.
44+
45+
## root
46+
`<HTMLElement>` The `#root` element that holds the header, tabs and editor.
47+
2948

3049
Here is a very simple example on how to use these APIs:
3150
```javascript
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
---
2+
description: Route QuickTools keys, text and commands to a plugin's own editor tab with acode.registerQuickToolsAdapter.
3+
---
4+
5+
# QuickTools Adapter <Badge type="tip" text="v1012+" />
6+
7+
QuickTools is the row of keys above the keyboard (`Ctrl`, `Tab`, arrows, brackets, undo, redo and so on). By default those keys only drive the code editor. A **QuickTools adapter** lets a [custom editor tab](../editor-components/editor-file#creating-a-custom-file-type) handle them instead, so a plugin's own editor (a spreadsheet, a canvas, a hex editor) works with QuickTools like the code editor does.
8+
9+
## Usage
10+
11+
```js
12+
const dispose = acode.registerQuickToolsAdapter(tab, adapter);
13+
```
14+
15+
| Parameter | Type | Description |
16+
| :-------- | :--- | :---------- |
17+
| `tab` | `EditorFile` | The custom tab the adapter belongs to. |
18+
| `adapter` | `QuickToolsAdapter` | The handlers described below. |
19+
20+
It returns a `dispose()` function that removes the adapter. The adapter is also removed automatically when the tab closes.
21+
22+
Each tab can have only one adapter; registering a second one throws an error.
23+
24+
## How It Works
25+
26+
While the tab with an adapter is active:
27+
28+
- **The adapter owns all QuickTools input for the tab.** Actions it doesn't handle are ignored. They never fall through to the code editor.
29+
- **QuickTools is shown while `getState().enabled` is `true`** and hidden otherwise. This replaces the tab's `hideQuickTools` option.
30+
- **Actions run one at a time, in order.** Each `execute()` call waits for the previous one to finish.
31+
- **Pending actions are cancelled** when the user switches tabs, when the adapter reports `enabled: false` or `busy: true`, or when a dialog or other overlay opens. The `signal` passed to `execute()` is aborted, and `cancel()` is called.
32+
- **Paste becomes text.** A paste command or `Ctrl` + `V` is read from the clipboard and delivered as a `text` action.
33+
- **Save and the Command Palette always run normally**, even with an adapter. To make **Save** work for your tab, handle the tab's [`save` event](../editor-components/editor-file#saving-a-custom-tab).
34+
35+
## Adapter
36+
37+
```ts
38+
interface QuickToolsAdapter {
39+
// Required
40+
getState(): { enabled: boolean; busy?: boolean };
41+
subscribe(listener: () => void): () => void;
42+
canHandle(action: QuickToolsAction): boolean;
43+
execute(action: QuickToolsAction, options: { signal: AbortSignal }): void | Promise<void>;
44+
45+
// Optional
46+
focus?(): void | Promise<void>;
47+
captureSelection?(): unknown | Promise<unknown>;
48+
restoreSelection?(snapshot: unknown): void | Promise<void>;
49+
cancel?(): void;
50+
onError?(error: unknown): void;
51+
}
52+
```
53+
54+
| Method | Description |
55+
| :----- | :---------- |
56+
| `getState()` | Current state. `enabled: false` hides QuickTools for the tab; `busy: true` pauses input while your editor is working. |
57+
| `subscribe(listener)` | Call `listener` whenever the state changes. Return a function that unsubscribes. |
58+
| `canHandle(action)` | Return `true` if the adapter can run this action right now. Other actions are dropped. **Undo** and **Redo** are shown disabled while it returns `false` for them. |
59+
| `execute(action, { signal })` | Perform the action. Check `signal.aborted` before any slow step. |
60+
| `focus()` | Give focus back to your editor after a QuickTools key is used. |
61+
| `captureSelection()` | Return a snapshot of the selection or caret before QuickTools takes focus. |
62+
| `restoreSelection(snapshot)` | Put that selection back before the next action runs. |
63+
| `cancel()` | Called when pending actions are cancelled. |
64+
| `onError(error)` | Called if `execute()`, `restoreSelection()` or `focus()` throws. |
65+
66+
## Actions
67+
68+
```ts
69+
type QuickToolsAction =
70+
| { type: "text"; text: string }
71+
| {
72+
type: "key";
73+
key: string; // KeyboardEvent.key, for example "ArrowLeft", "Tab", "Escape", "a"
74+
shiftKey: boolean;
75+
ctrlKey: boolean;
76+
altKey: boolean;
77+
metaKey: boolean;
78+
}
79+
| { type: "command"; command: string }
80+
| { type: "modifier"; key: "shift" | "ctrl" | "alt" | "meta" };
81+
```
82+
83+
| Type | Sent when |
84+
| :--- | :-------- |
85+
| `text` | A character key like `{`, `;` or `"` is tapped, or text is pasted. |
86+
| `key` | A key like **Tab**, **Esc** or an arrow is tapped, or the user types a key while `Ctrl`, `Shift`, `Alt` or `Meta` is active. |
87+
| `command` | A command button is tapped: `undo`, `redo`, `selectall`, `movelinesup`, `movelinesdown`, `copylinesup`, `copylinesdown` or `find` (the search button). |
88+
| `modifier` | Only checked with `canHandle()`. Return `true` to let the user turn on that modifier; Acode then sends the next typed key as a `key` action with the modifier set. |
89+
90+
## Example
91+
92+
A minimal custom tab with a `<textarea>` editor:
93+
94+
```js
95+
const EditorFile = acode.require("EditorFile");
96+
97+
const textarea = document.createElement("textarea");
98+
const tab = new EditorFile("Notes", { type: "custom", content: textarea });
99+
100+
const listeners = new Set();
101+
let state = { enabled: true, busy: false };
102+
103+
function insert(text) {
104+
textarea.setRangeText(text, textarea.selectionStart, textarea.selectionEnd, "end");
105+
}
106+
107+
const dispose = acode.registerQuickToolsAdapter(tab, {
108+
getState: () => state,
109+
subscribe(listener) {
110+
listeners.add(listener);
111+
return () => listeners.delete(listener);
112+
},
113+
canHandle(action) {
114+
if (action.type === "text") return true;
115+
if (action.type === "key") return ["ArrowLeft", "ArrowRight", "Tab"].includes(action.key);
116+
if (action.type === "command") return action.command === "selectall";
117+
return false;
118+
},
119+
execute(action, { signal }) {
120+
if (signal.aborted) return;
121+
const pos = textarea.selectionStart;
122+
if (action.type === "text") insert(action.text);
123+
else if (action.key === "Tab") insert("\t");
124+
else if (action.key === "ArrowLeft") textarea.setSelectionRange(pos - 1, pos - 1);
125+
else if (action.key === "ArrowRight") textarea.setSelectionRange(pos + 1, pos + 1);
126+
else if (action.command === "selectall") textarea.select();
127+
},
128+
focus: () => textarea.focus(),
129+
captureSelection: () => [textarea.selectionStart, textarea.selectionEnd],
130+
restoreSelection: ([start, end]) => textarea.setSelectionRange(start, end),
131+
});
132+
133+
// Hide QuickTools while the tab is read-only, for example.
134+
function setEnabled(enabled) {
135+
state = { ...state, enabled };
136+
for (const listener of listeners) listener();
137+
}
138+
```
139+
140+
Call `dispose()` in your plugin's unmount function if the tab can outlive the plugin.

0 commit comments

Comments
 (0)