generated from tiddly-gittly/TiddlyWiki-TS-Plugin-Template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
widget.ts
268 lines (253 loc) · 10.6 KB
/
widget.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
/* eslint-disable @typescript-eslint/unbound-method */
/* eslint-disable @typescript-eslint/strict-boolean-expressions */
import { Modal } from '$:/core/modules/utils/dom/modal.js';
import { widget as Widget } from '$:/core/modules/widgets/widget.js';
import { autocomplete, OnStateChangeProps } from '@algolia/autocomplete-js';
import type { AutocompleteNavigator } from '@algolia/autocomplete-shared/dist/esm/core/AutocompleteNavigator';
import { IChangedTiddlers, ITiddlerFields } from 'tiddlywiki';
import '@algolia/autocomplete-theme-classic';
import { AutocompleteState } from '@algolia/autocomplete-core';
import { observe, unobserve } from '@seznam/visibility-observer';
import { IContext } from './utils/context';
import { fixPanelPosition } from './utils/fixPanelPosition';
import { getActiveElement } from './utils/getFocused';
import { getSubPlugins } from './utils/getSubPlugins';
import { handleDarkMode } from './utils/handleDarkMode';
import { uniqSourcesBy } from './utils/uniqSourcesBy';
class CommandPaletteWidget extends Widget {
id = 'default';
refresh(_changedTiddlers: IChangedTiddlers) {
return false;
}
/** We restore focus of element when we are close */
// eslint-disable-next-line unicorn/no-null
previouslyFocusedElement: HTMLElement | null = null;
autoCompleteInstance: ReturnType<typeof autocomplete<ITiddlerFields>> | undefined;
/** Can't get state from its instance, so use this as a way to get state */
autoCompleteState?: OnStateChangeProps<ITiddlerFields>;
historyMode = false;
render(parent: Element, nextSibling: Element) {
this.parentDomNode = parent;
this.computeAttributes();
this.execute();
this.id = this.getAttribute('id', 'default');
// params are get from `$:/plugins/linonetwo/commandpalette/DefaultCommandPalette` using transclusion from `$:/temp/commandpalette/default/opened`
const initialPrefix = this.getAttribute('prefix', '');
this.historyMode = this.getAttribute('historyMode', 'no') === 'yes';
const titlePriorityText = this.wiki.getTiddlerText('$:/plugins/linonetwo/commandpalette/configs/TitlePriorityText', 'no') === 'yes';
const containerElement = $tw.utils.domMaker('nav', {
class: 'tw-commandpalette-container',
});
parent.insertBefore(containerElement, nextSibling);
this.domNodes.push(containerElement);
handleDarkMode();
const removeDuplicates = uniqSourcesBy<ITiddlerFields>(({ item }) => item.title);
this.previouslyFocusedElement = getActiveElement();
const updateState = (nextState: OnStateChangeProps<ITiddlerFields>) => {
this.autoCompleteState = nextState;
};
this.autoCompleteInstance = autocomplete<ITiddlerFields>({
id: this.id,
container: containerElement,
placeholder: 'Search for tiddlers',
initialState: {
query: initialPrefix,
},
defaultActiveItemId: 0,
onStateChange(nextState) {
updateState(nextState);
},
autoFocus: true,
openOnFocus: true,
ignoreCompositionEvents: true,
navigator: {
navigate: this.onEnter.bind(this) satisfies AutocompleteNavigator<ITiddlerFields>['navigate'],
navigateNewTab: this.onCtrlEnter.bind(this) satisfies AutocompleteNavigator<ITiddlerFields>['navigateNewTab'],
},
plugins: getSubPlugins(),
reshape({ sourcesBySourceId }) {
const {
'title': titleSource,
'title-pinyin': titlePinyinSource,
'story-history': storyHistorySource,
'text': textSource,
...rest
} = sourcesBySourceId;
// this will also affect `priority` field. The order here is more important than `priority` field.
return [
...removeDuplicates(...[...(titlePriorityText ? [titleSource, textSource] : [textSource, titleSource]), titlePinyinSource, storyHistorySource].filter(Boolean)),
...Object.values(rest),
];
},
});
this.autoCompleteInstance.setContext({ widget: this } satisfies IContext);
this.onCommandPaletteInputDOMInit(containerElement);
this.onCommandPaletteDetachedDOMInit(containerElement);
}
onVisibilityChange(
visibilityEntry: IntersectionObserverEntry & {
target: HTMLElement;
},
) {
if (!visibilityEntry.isIntersecting) {
this.destroy();
unobserve(visibilityEntry.target, this.onVisibilityChange.bind(this));
}
}
onEnter({ itemUrl, state }: {
item: ITiddlerFields;
itemUrl: string;
state: AutocompleteState<ITiddlerFields>;
}): void {
if (state.context.newQuery !== undefined) {
this.autoCompleteInstance?.setQuery?.((state.context as IContext).newQuery!);
this.autoCompleteInstance?.setContext({ newQuery: undefined } satisfies IContext);
// use query to re-search, and will set activeItemId to defaultActiveItemId
void this.autoCompleteInstance?.refresh?.();
}
if (!state.context.noNavigate) {
$tw.wiki.setText('$:/layout', 'text', undefined, '', { suppressTimestamp: true });
this.dispatchEvent({
type: 'tm-navigate',
navigateTo: itemUrl,
navigateFromNode: this,
});
}
if (!state.context.noClose) {
this.setCloseState();
}
this.clearContext();
}
onCtrlEnter({ itemUrl, state }: {
item: ITiddlerFields;
itemUrl: string;
state: AutocompleteState<ITiddlerFields>;
}) {
$tw.utils.copyToClipboard(itemUrl);
if (!state.context.noClose) {
this.setCloseState();
}
this.clearContext();
}
clearContext() {
// don't clear filter, otherwise can't get it in next step (under-filter)
this.autoCompleteInstance?.setContext({ noNavigate: undefined, newQuery: undefined, noClose: undefined /* , filter: undefined */ } satisfies IContext);
}
/**
* Handle full screen search mode on mobile
* @url https://www.algolia.com/doc/ui-libraries/autocomplete/core-concepts/detached-mode/
* @returns
*/
onCommandPaletteDetachedDOMInit(containerElement: HTMLElement) {
const buttonElement = containerElement.querySelector<HTMLButtonElement>('button.aa-DetachedSearchButton');
if (buttonElement === null) {
return;
}
buttonElement.click();
buttonElement.style.display = 'none';
const detachedElement = (this.document as unknown as Document).querySelector<HTMLDivElement>('body.aa-Detached > div.aa-DetachedOverlay');
if (detachedElement === null) {
return;
}
observe(detachedElement, this.onVisibilityChange.bind(this));
}
/** Copy from Modal, to use its logic */
srcDocument = this.document;
modalCount = 0;
/**
* Do things after command palette UI is initialized.
*/
onCommandPaletteInputDOMInit(containerElement: HTMLElement) {
const inputElement = containerElement.querySelector<HTMLInputElement>('input');
if (inputElement === null) {
return;
}
observe(containerElement, this.onVisibilityChange.bind(this));
this.registerHistoryKeyboardHandlers(inputElement);
// autoFocus param is not working, focus manually.
inputElement.focus();
// no API to listen esc, listen manually
inputElement.addEventListener('keydown', (event) => {
if (event.key === 'Escape') {
if (inputElement.value === '') {
this.setCloseState();
} else {
event.stopPropagation();
event.preventDefault();
inputElement.value = '';
}
}
// pressing enter is useless (it auto searches), and will cause dropdown to close, so ignore it.
if (event.key === 'Enter') {
this.autoCompleteInstance?.setIsOpen(true);
event.stopPropagation();
event.preventDefault();
}
});
this.modalCount++;
// call with this
Modal.prototype.adjustPageClass.call(this);
/* eslint-disable @typescript-eslint/unbound-method */
fixPanelPosition();
inputElement.addEventListener('focus', fixPanelPosition);
inputElement.addEventListener('blur', fixPanelPosition);
window.addEventListener('resize', fixPanelPosition);
/* eslint-enable @typescript-eslint/unbound-method */
}
historySwitchActiveItemId?: number;
registerHistoryKeyboardHandlers(inputElement: HTMLInputElement) {
if (!this.historyMode) return;
inputElement.addEventListener('keydown', (event) => {
if (this.autoCompleteInstance === undefined) return;
// when use ctrl+tab to switch between history, when release tab (while still holding ctrl), do nothing after palette open.
if (event.key === 'Tab' && event.ctrlKey) {
this.historySwitchActiveItemId = (this.historySwitchActiveItemId ?? this.autoCompleteState?.state?.activeItemId ?? 0) + (event.shiftKey ? -1 : 1);
const collectionLength = this.autoCompleteState?.state?.collections?.[0]?.items?.length ?? 0;
if (this.historySwitchActiveItemId === -1) {
this.historySwitchActiveItemId = Math.max(collectionLength - 1, 0);
} else if (this.historySwitchActiveItemId >= collectionLength) {
this.historySwitchActiveItemId = 0;
}
this.autoCompleteInstance.setActiveItemId(this.historySwitchActiveItemId);
this.autoCompleteInstance.setIsOpen(true);
event.stopPropagation();
event.preventDefault();
}
});
inputElement.addEventListener('keyup', (event) => {
if (this.autoCompleteInstance === undefined) return;
if (event.key === 'Tab' && event.ctrlKey) {
event.stopPropagation();
event.preventDefault();
return;
}
// when release ctrl, and we are in history mode (no query), open the tiddler.
if (event.key === 'Control' && this.autoCompleteState?.state?.query === '') {
event.stopPropagation();
event.preventDefault();
const item = this.autoCompleteState?.state?.collections.find(({ source }) => source.sourceId === 'story-history')?.items[this.autoCompleteState?.state?.activeItemId ?? 0];
if (!item) return;
this.autoCompleteInstance.navigator.navigate({ item, itemUrl: item.title, state: this.autoCompleteState?.state });
}
});
}
setCloseState() {
$tw.wiki.deleteTiddler(`$:/temp/commandpalette/${this.id}/opened`);
this.autoCompleteInstance?.setIsOpen(false);
this.modalCount = 0;
Modal.prototype.adjustPageClass.call(this);
}
destroy() {
this.setCloseState();
this.autoCompleteInstance?.destroy();
this.autoCompleteInstance = undefined;
/* eslint-disable @typescript-eslint/unbound-method */
window.removeEventListener('resize', fixPanelPosition);
/* eslint-enable @typescript-eslint/unbound-method */
this.previouslyFocusedElement?.focus?.();
}
}
declare let exports: {
['command-palette']: typeof CommandPaletteWidget;
};
exports['command-palette'] = CommandPaletteWidget;