-
Notifications
You must be signed in to change notification settings - Fork 13
/
preferencePane.ts
324 lines (308 loc) · 11 KB
/
preferencePane.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
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
import { BasicOptions, BasicTool } from "../basic";
import { UITool } from "../tools/ui";
import { ManagerTool } from "../basic";
/**
* Register preference pane from Zotero 7's `xhtml`, for Zotero 6 & 7.
*/
export class PreferencePaneManager extends ManagerTool {
private alive: boolean = true;
private ui: UITool;
private prefPaneCache: { win?: Window; listeners: { [id: string]: any } };
constructor(base?: BasicTool | BasicOptions) {
super(base);
this.ui = new UITool(this);
this.prefPaneCache = { win: undefined, listeners: {} };
}
/**
* Register a preference pane from an xhtml, for Zotero 6 & 7.
* @remarks
* Don't forget to call `unregisterPrefPane` on exit.
* @remarks
* options:
* ```ts
* export interface PrefPaneOptions {
* pluginID: string;
* src: string;
* id?: string;
* parent?: string;
* label?: string;
* image?: string;
* extraDTD?: string[];
* scripts?: string[];
* defaultXUL?: boolean;
* // Only for Zotero 6
* onload?: (win: Window) => any;
* }
* ```
*
* @param options See {@link https://github.com/windingwind/zotero-plugin-toolkit/blob/main/src/options.ts | source code:options.ts}
* @example
* ```ts
* const prefsManager = new PreferencePaneManager();
* function initPrefs() {
* const prefOptions = {
* pluginID: addonID,
* src: rootURI + "chrome/content/preferences.xhtml",
* label: "Template",
* image: `chrome://${addonRef}/content/icons/favicon.png`,
* extraDTD: [`chrome://${addonRef}/locale/overlay.dtd`],
* defaultXUL: true
* };
* prefsManager.register(prefOptions);
* };
*
* function unInitPrefs() {
* prefsManager.unregisterAll();
* };
* ```
* // bootstrap.js:startup
* initPrefs();
*
* // bootstrap.js:shutdown
* unInitPrefs();
*/
register(options: PrefPaneOptions) {
if (this.isZotero7()) {
this.getGlobal("Zotero").PreferencePanes.register(options);
return;
}
const _initImportedNodesPostInsert = (container: Element) => {
const _observerSymbols = new Map();
const Zotero = this.getGlobal("Zotero");
const window = (container as any).ownerGlobal;
let useChecked = (elem: Element) =>
(elem instanceof window.HTMLInputElement &&
(elem as HTMLInputElement).type == "checkbox") ||
elem.tagName == "checkbox";
let syncFromPref = (elem: Element, preference: string) => {
let value = Zotero.Prefs.get(preference, true);
if (useChecked(elem)) {
(elem as HTMLInputElement).checked = value as boolean;
} else {
(elem as HTMLInputElement).value = value as string;
}
elem.dispatchEvent(new window.Event("syncfrompreference"));
};
// We use a single listener function shared between all elements so we can easily detach it later
let syncToPrefOnModify = (event: Event) => {
const targetNode = event.currentTarget as Element;
if (targetNode?.getAttribute("preference")) {
let value = useChecked(targetNode)
? (targetNode as HTMLInputElement).checked
: (targetNode as HTMLInputElement).value;
Zotero.Prefs.set(
targetNode.getAttribute("preference") || "",
value,
true
);
targetNode.dispatchEvent(new window.Event("synctopreference"));
}
};
let attachToPreference = (elem: Element, preference: string) => {
Zotero.debug(`Attaching <${elem.tagName}> element to ${preference}`);
// @ts-ignore
let symbol = Zotero.Prefs.registerObserver(
preference,
() => syncFromPref(elem, preference),
true
);
_observerSymbols.set(elem, symbol);
};
let detachFromPreference = (elem: Element) => {
if (_observerSymbols.has(elem)) {
Zotero.debug(`Detaching <${elem.tagName}> element from preference`);
// @ts-ignore
Zotero.Prefs.unregisterObserver(this._observerSymbols.get(elem));
_observerSymbols.delete(elem);
}
};
// Activate `preference` attributes
for (let elem of container.querySelectorAll("[preference]")) {
let preference = elem.getAttribute("preference")!;
if (container.querySelector("preferences > preference#" + preference)) {
this.log(
"<preference> is deprecated -- `preference` attribute values should be full preference keys, not <preference> IDs"
);
preference = container
.querySelector("preferences > preference#" + preference)
?.getAttribute("name")!;
}
attachToPreference(elem, preference);
elem.addEventListener(
this.isXULElement(elem) ? "command" : "input",
syncToPrefOnModify
);
// Set timeout before populating the value so the pane can add listeners first
window.setTimeout(() => {
syncFromPref(elem, preference);
});
}
new window.MutationObserver((mutations: MutationRecord[]) => {
for (let mutation of mutations) {
if (mutation.type == "attributes") {
let target = mutation.target as Element;
detachFromPreference(target);
if (target.hasAttribute("preference")) {
attachToPreference(
target,
target.getAttribute("preference") || ""
);
target.addEventListener(
this.isXULElement(target) ? "command" : "input",
syncToPrefOnModify
);
}
} else if (mutation.type == "childList") {
for (let node of mutation.removedNodes) {
detachFromPreference(node as Element);
}
for (let node of mutation.addedNodes) {
if (
node.nodeType == window.Node.ELEMENT_NODE &&
(node as Element).hasAttribute("preference")
) {
attachToPreference(
node as Element,
(node as Element).getAttribute("preference") || ""
);
node.addEventListener(
this.isXULElement(node as Element) ? "command" : "input",
syncToPrefOnModify
);
}
}
}
}
}).observe(container, {
childList: true,
subtree: true,
attributeFilter: ["preference"],
});
// parseXULToFragment() doesn't convert oncommand attributes into actual
// listeners, so we'll do it here
for (let elem of container.querySelectorAll("[oncommand]")) {
(elem as any).oncommand = elem.getAttribute("oncommand");
}
for (let child of container.children) {
child.dispatchEvent(new window.Event("load"));
}
};
const windowListener = {
onOpenWindow: (xulWindow: any) => {
// Avoid multiple tabs when unregister fails
if (!this.alive) {
return;
}
const win: Window = xulWindow
.QueryInterface(Components.interfaces.nsIInterfaceRequestor)
.getInterface(Components.interfaces.nsIDOMWindow);
win.addEventListener(
"load",
async () => {
if (
win.location.href ===
"chrome://zotero/content/preferences/preferences.xul"
) {
this.log("registerPrefPane:detected", options);
const Zotero = this.getGlobal("Zotero");
options.id ||
(options.id = `plugin-${Zotero.Utilities.randomString()}-${new Date().getTime()}`);
const contentOrXHR = await Zotero.File.getContentsAsync(
options.src
);
const content =
typeof contentOrXHR === "string"
? contentOrXHR
: (contentOrXHR as any as XMLHttpRequest).response;
const src = `<prefpane xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="${
options.id
}" insertafter="zotero-prefpane-advanced" label="${
options.label || options.pluginID
}" image="${options.image || ""}">
${content}
</prefpane>`;
const frag = this.ui.parseXHTMLToFragment(
src,
options.extraDTD,
options.defaultXUL
);
this.log(frag);
const prefWindow = win.document.querySelector("prefwindow")!;
prefWindow.appendChild(frag);
const prefPane = win.document.querySelector(`#${options.id}`)!;
// @ts-ignore
prefWindow.addPane(prefPane);
// Enable scroll. Check if the content does overflow the box later.
// @ts-ignore
const contentBox = win.document.getAnonymousNodes(
win.document.querySelector(`#${options.id}`)
)[0] as XUL.Box;
contentBox.style.overflowY = "scroll";
contentBox.style.height = "440px";
// Resize window, otherwise the new prefpane may be placed out of the window
// @ts-ignore
win.sizeToContent();
// Disable scroll if the content does not overflow.
if (contentBox.scrollHeight === contentBox.clientHeight) {
contentBox.style.overflowY = "hidden";
}
this.prefPaneCache.win = win;
this.prefPaneCache.listeners[options.id] = windowListener;
// Binding preferences
_initImportedNodesPostInsert(prefPane);
if (options.scripts?.length) {
options.scripts.forEach((script) =>
Services.scriptloader.loadSubScript(script, win)
);
}
if (options.onload) {
options.onload(win);
}
}
},
false
);
},
};
Services.wm.addListener(windowListener);
}
unregister(id: string) {
const idx = Object.keys(this.prefPaneCache.listeners).indexOf(id);
if (idx < 0) {
return false;
}
const listener = this.prefPaneCache.listeners[id];
Services.wm.removeListener(listener);
listener.onOpenWindow = undefined;
const win = this.prefPaneCache.win;
if (win && !win.closed) {
win.document.querySelector(`#${id}`)?.remove();
}
delete this.prefPaneCache.listeners[id];
return true;
}
/**
* Unregister all preference panes added with this instance
*
* Called on exiting
*/
unregisterAll() {
this.alive = false;
for (const id in this.prefPaneCache.listeners) {
this.unregister(id);
}
}
}
export interface PrefPaneOptions {
pluginID: string;
src: string;
id?: string;
parent?: string;
label?: string;
image?: string;
extraDTD?: string[];
scripts?: string[];
defaultXUL?: boolean;
// Only for Zotero 6
onload?: (win: Window) => any;
}