Skip to content

Commit

Permalink
refactor: api
Browse files Browse the repository at this point in the history
  • Loading branch information
windingwind committed Sep 15, 2023
1 parent 11d4909 commit 4c54d01
Show file tree
Hide file tree
Showing 8 changed files with 92 additions and 51 deletions.
22 changes: 15 additions & 7 deletions src/api.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
import {
dispatchEventAction,
dispatchMenuAction,
dispatchShortcutAction,
} from "./modules/events";
dispatchActionByEvent,
dispatchActionByKey,
dispatchActionByShortcut,
} from "./modules/dispatch";
import { ClipboardHelper } from "zotero-plugin-toolkit/dist/helpers/clipboard";
import { getActions, updateAction, deleteAction } from "./utils/actions";

const actionManager = {
dispatchActionByEvent,
dispatchActionByKey,
dispatchActionByShortcut,
getActions,
updateAction,
deleteAction,
};

const utils = {
ClipboardHelper,
};

export default {
dispatchEventAction,
dispatchShortcutAction,
dispatchMenuAction,
actionManager,
utils,
};
6 changes: 3 additions & 3 deletions src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,21 +26,21 @@ async function onStartup() {
helpURL: homepage,
});

await addon.api.dispatchEventAction(ActionEventTypes.programStartup, {});
await addon.api.actionManager.dispatchActionByEvent(ActionEventTypes.programStartup, {});

await onMainWindowLoad(window);
}

async function onMainWindowLoad(win: Window): Promise<void> {
initShortcuts(win);
initMenu();
await addon.api.dispatchEventAction(ActionEventTypes.mainWindowLoad, {
await addon.api.actionManager.dispatchActionByEvent(ActionEventTypes.mainWindowLoad, {
window: win,
});
}

async function onMainWindowUnload(win: Window): Promise<void> {
await addon.api.dispatchEventAction(ActionEventTypes.mainWindowUnload, {
await addon.api.actionManager.dispatchActionByEvent(ActionEventTypes.mainWindowUnload, {
window: win,
});
}
Expand Down
8 changes: 4 additions & 4 deletions src/modules/events.ts → src/modules/dispatch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import {
} from "../utils/actions";
import { KeyModifier } from "../utils/shorcut";

export { dispatchEventAction, dispatchShortcutAction, dispatchMenuAction };
export { dispatchActionByEvent, dispatchActionByShortcut, dispatchActionByKey };

async function dispatchEventAction(
async function dispatchActionByEvent(
eventType: ActionEventTypes,
data: ActionDataData,
) {
Expand All @@ -23,7 +23,7 @@ function getActionsByEvent(event: ActionEventTypes) {
);
}

async function dispatchShortcutAction(
async function dispatchActionByShortcut(
shortcut: KeyModifier,
data: ActionDataData,
) {
Expand All @@ -42,7 +42,7 @@ function getActionsByShortcuts(shortcut: KeyModifier) {
);
}

async function dispatchMenuAction(key: string, data: ActionDataData) {
async function dispatchActionByKey(key: string, data: ActionDataData) {
const action = addon.data.actions.map.get(key);
if (!action) {
return;
Expand Down
2 changes: 1 addition & 1 deletion src/modules/menu.ts
Original file line number Diff line number Diff line change
Expand Up @@ -82,7 +82,7 @@ function getActionsByMenu() {
async function triggerMenuCommand(key: string) {
const items = Zotero.getActiveZoteroPane().getSelectedItems();
for (const item of items) {
await addon.api.dispatchMenuAction(key, {
await addon.api.actionManager.dispatchActionByKey(key, {
itemID: item.id,
});
}
Expand Down
14 changes: 7 additions & 7 deletions src/modules/notify.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ async function onNotify(
Zotero.Items.get(ids as number[]),
);
for (const item of parentItems) {
await addon.api.dispatchEventAction(ActionEventTypes.openFile, {
await addon.api.actionManager.dispatchActionByEvent(ActionEventTypes.openFile, {
itemID: item.id,
});
}
Expand All @@ -56,23 +56,23 @@ async function onNotify(
);
for (const item of items) {
if (item.isRegularItem()) {
await addon.api.dispatchEventAction(ActionEventTypes.createItem, {
await addon.api.actionManager.dispatchActionByEvent(ActionEventTypes.createItem, {
itemID: item.id,
});
} else if (item.isAnnotation()) {
await addon.api.dispatchEventAction(ActionEventTypes.createAnnotation, {
await addon.api.actionManager.dispatchActionByEvent(ActionEventTypes.createAnnotation, {
itemID: item.id,
});
const parentItem = Zotero.Items.getTopLevel([item])[0];
await addon.api.dispatchEventAction(ActionEventTypes.appendAnnotation, {
await addon.api.actionManager.dispatchActionByEvent(ActionEventTypes.appendAnnotation, {
itemID: parentItem.id,
});
} else if (item.isNote()) {
await addon.api.dispatchEventAction(ActionEventTypes.createNote, {
await addon.api.actionManager.dispatchActionByEvent(ActionEventTypes.createNote, {
itemID: item.id,
});
const parentItem = Zotero.Items.getTopLevel([item])[0];
await addon.api.dispatchEventAction(ActionEventTypes.appendNote, {
await addon.api.actionManager.dispatchActionByEvent(ActionEventTypes.appendNote, {
itemID: parentItem.id,
});
}
Expand All @@ -91,7 +91,7 @@ async function onNotify(
Zotero.Items.get(itemIDs as number[]),
);
for (const item of parentItems) {
await addon.api.dispatchEventAction(ActionEventTypes.closeTab, {
await addon.api.actionManager.dispatchActionByEvent(ActionEventTypes.closeTab, {
itemID: item.id,
});
}
Expand Down
49 changes: 25 additions & 24 deletions src/modules/preferenceWindow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import {
ActionOperationTypes,
ActionData,
emptyAction,
updateCachedActionKeys,
} from "../utils/actions";
import { closeWindow, isWindowAlive } from "../utils/window";
import { KeyModifier } from "../utils/shorcut";
Expand All @@ -29,9 +28,8 @@ export async function initPrefPane(_window: Window) {
async function initUI() {
const renderLock = Zotero.Promise.defer();
if (!isWindowAlive(addon.data.prefs.window)) return;
updateCachedActionKeys();
addon.data.prefs.tableHelper = new ztoolkit.VirtualizedTable(
addon.data.prefs.window!,
addon.data.prefs.window!
)
.setContainerId(`${config.addonRef}-table-container`)
.setProp({
Expand Down Expand Up @@ -96,7 +94,7 @@ async function initUI() {
// Returning false to prevent default event.
.setProp("onKeyDown", (event: KeyboardEvent) => {
if (event.key == "Delete" || (Zotero.isMac && event.key == "Backspace")) {
addon.data.actions.map.delete(addon.data.actions.selectedKey!);
addon.api.actionManager.deleteAction(addon.data.actions.selectedKey!);
updateUI();
return false;
}
Expand Down Expand Up @@ -132,17 +130,18 @@ function initEvents() {
doc
.querySelector(`#${config.addonRef}-rule-add`)
?.addEventListener("command", (e) => {
const newKey = `${Date.now()}`;
addon.data.actions.map.set(newKey, Object.assign({}, emptyAction));
const key = addon.api.actionManager.updateAction(
Object.assign({}, emptyAction)
);
updateUI();
editAction(newKey);
editAction(key);
});

doc
.querySelector(`#${config.addonRef}-rule-remove`)
?.addEventListener("command", (e) => {
const currentKey = addon.data.actions.selectedKey;
addon.data.actions.map.delete(currentKey!);
addon.api.actionManager.deleteAction(currentKey!);
updateUI();
});

Expand All @@ -154,12 +153,10 @@ function initEvents() {
}

function updateUI() {
updateCachedActionKeys();
setTimeout(() => addon.data.prefs.tableHelper?.treeInstance.invalidate());
}

function getRowData(index: number) {
if (addon.data.actions.cachedKeys.length == 0) updateCachedActionKeys();
const keys = addon.data.actions.cachedKeys;
let action: ActionData = emptyAction;
if (keys.length > index) {
Expand All @@ -169,7 +166,7 @@ function getRowData(index: number) {
return {
event: getString(`prefs-rule-event-${ActionEventTypes[action.event]}`),
operation: getString(
`prefs-rule-operation-${ActionOperationTypes[action.operation]}`,
`prefs-rule-operation-${ActionOperationTypes[action.operation]}`
),
data: action.data,
shortcut: action.shortcut,
Expand Down Expand Up @@ -308,7 +305,7 @@ async function editAction(currentKey?: string) {
const content = await openEditorWindow(dialogData.data);
(
dialog.window.document.querySelector(
"#data-input",
"#data-input"
) as HTMLTextAreaElement
).value = content;
dialogData.data = content;
Expand Down Expand Up @@ -342,7 +339,7 @@ async function editAction(currentKey?: string) {
const key = ev.target as HTMLElement;
const win = dialog.window;
key.textContent = `[${getString(
"prefs-rule-edit-shortcut-placeholder",
"prefs-rule-edit-shortcut-placeholder"
)}]`;
dialogData.shortcut = "";
const keyDownListener = (e: KeyboardEvent) => {
Expand Down Expand Up @@ -428,16 +425,20 @@ async function editAction(currentKey?: string) {
switch (dialogData._lastButtonId) {
case "save":
{
addon.data.actions.map.set(currentKey, {
event: Number(dialogData.event),
operation: Number(dialogData.operation),
data: addon.data.prefs.editorInstance?.getValue() || dialogData.data,
// Replace things inside []
shortcut: dialogData.shortcut.replace(/\[(.*?)\]/g, ""),
enabled: dialogData.enabled,
menu: dialogData.menu,
name: dialogData.name,
});
addon.api.actionManager.updateAction(
{
event: Number(dialogData.event),
operation: Number(dialogData.operation),
data:
addon.data.prefs.editorInstance?.getValue() || dialogData.data,
// Replace things inside []
shortcut: dialogData.shortcut.replace(/\[(.*?)\]/g, ""),
enabled: dialogData.enabled,
menu: dialogData.menu,
name: dialogData.name,
},
currentKey
);
updateUI();
}
break;
Expand All @@ -453,7 +454,7 @@ async function openEditorWindow(content: string) {
const editorWin = addon.data.prefs.window?.openDialog(
"chrome://scaffold/content/monaco/monaco.html",
"monaco",
"chrome,centerscreen,dialog=no,resizable,scrollbars=yes,width=800,height=600",
"chrome,centerscreen,dialog=no,resizable,scrollbars=yes,width=800,height=600"
) as
| (Window & {
loadMonaco: (options: Record<string, any>) => Promise<{ editor: any }>;
Expand Down
4 changes: 2 additions & 2 deletions src/modules/shortcuts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,13 +33,13 @@ async function triggerShortcut(e: KeyboardEvent) {
}
const items = Zotero.getActiveZoteroPane().getSelectedItems();
if (items.length === 0) {
await addon.api.dispatchShortcutAction(shortcut, {
await addon.api.actionManager.dispatchActionByShortcut(shortcut, {
itemID: -1,
});
return;
}
for (const item of items) {
await addon.api.dispatchShortcutAction(shortcut, {
await addon.api.actionManager.dispatchActionByShortcut(shortcut, {
itemID: item.id,
});
}
Expand Down
38 changes: 35 additions & 3 deletions src/utils/actions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ export {
initActions,
updateCachedActionKeys,
applyAction,
getActions,
updateAction,
deleteAction,
};

enum ActionEventTypes {
Expand Down Expand Up @@ -95,7 +98,7 @@ function initActions() {
addon.data.actions.map = new ztoolkit.LargePref(
`${config.prefsPrefix}.rules`,
`${config.prefsPrefix}.rules.`,
"parser",
"parser"
).asMapLike() as ActionMap;
if (!getPref("rulesInit")) {
for (const key of defaultActions.keys()) {
Expand All @@ -105,6 +108,7 @@ function initActions() {
}
setPref("rulesInit", true);
}
updateCachedActionKeys();
}

function updateCachedActionKeys() {
Expand Down Expand Up @@ -136,7 +140,7 @@ async function applyAction(rule: ActionData, data: ActionDataData) {
item?.removeTag(tag);
}
message = `Remove tag ${tags.join(",")} from item ${item?.getField(
"title",
"title"
)}`;
break;
}
Expand All @@ -149,7 +153,7 @@ async function applyAction(rule: ActionData, data: ActionDataData) {
}
}
message = `Toggle tag ${tags.join(",")} to item ${item?.getField(
"title",
"title"
)}`;
break;
}
Expand Down Expand Up @@ -199,3 +203,31 @@ async function applyAction(rule: ActionData, data: ActionDataData) {
message && updateHint(message);
return true;
}

function getActions(): Record<string, ActionData>;
function getActions(key: string): ActionData | undefined;
function getActions(
key?: string
): Record<string, ActionData> | ActionData | undefined {
if (!key) {
const map = addon.data.actions.map;
const actions: Record<string, ActionData> = {};
for (const [key, value] of map) {
actions[key] = Object.assign({}, value);
}
return actions;
}
return addon.data.actions.map.get(key) || undefined;
}

function updateAction(action: ActionData, key?: string) {
key = key || `${Date.now()}`;
addon.data.actions.map.set(key, action);
updateCachedActionKeys();
return key;
}

function deleteAction(key: string) {
addon.data.actions.map.delete(key);
updateCachedActionKeys();
}

0 comments on commit 4c54d01

Please sign in to comment.