Skip to content

Commit

Permalink
feat: add keyboard shortcut in trigger block
Browse files Browse the repository at this point in the history
  • Loading branch information
Kholid060 committed Nov 4, 2021
2 parents 0e9c745 + 67c7d43 commit 4f16674
Show file tree
Hide file tree
Showing 17 changed files with 251 additions and 90 deletions.
31 changes: 31 additions & 0 deletions .github/ISSUE_TEMPLATE/bug_report.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: bug
assignees: ''

---

**Describe the bug**
A clear and concise description of what the bug is.

**To Reproduce**
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error

**Expected behavior**
A clear and concise description of what you expected to happen.

**Screenshots**
If applicable, add screenshots to help explain your problem.

**Desktop (please complete the following information):**
- OS: [e.g. iOS]
- Version [e.g. 22]

**Additional context**
Add any other context about the problem here.
20 changes: 20 additions & 0 deletions .github/ISSUE_TEMPLATE/feature_request.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: enhancement
assignees: ''

---

**Is your feature request related to a problem? Please describe.**
A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]

**Describe the solution you'd like**
A clear and concise description of what you want to happen.

**Describe alternatives you've considered**
A clear and concise description of any alternative solutions or features you've considered.

**Additional context**
Add any other context or screenshots about the feature request here.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@
"@webcomponents/custom-elements": "^1.5.0",
"dayjs": "^1.10.7",
"drawflow": "^0.0.51",
"mousetrap": "^1.6.5",
"nanoid": "3.1.28",
"papaparse": "^5.3.1",
"prismjs": "^1.25.0",
Expand Down
89 changes: 88 additions & 1 deletion src/components/newtab/workflow/edit/EditTrigger.vue
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
:model-value="data.type || 'manual'"
placeholder="Trigger workflow"
class="w-full"
@change="updateData({ type: $event })"
@change="handleSelectChange"
>
<option v-for="trigger in triggers" :key="trigger.id" :value="trigger.id">
{{ trigger.name }}
Expand Down Expand Up @@ -74,9 +74,36 @@
Use regex
</ui-checkbox>
</div>
<div v-else-if="data.type === 'keyboard-shortcut'" class="mt-2">
<div class="flex items-center mb-2">
<ui-input
:model-value="recordKeys.keys"
readonly
class="flex-1 mr-2"
placeholder="Shortcut"
/>
<ui-button v-tooltip="'Record keys'" icon @click="toggleRecordKeys">
<v-remixicon
:name="recordKeys.isRecording ? 'riStopLine' : 'riRecordCircleLine'"
/>
</ui-button>
</div>
<ui-checkbox
:model-value="data.activeInInput"
class="mb-1"
title="Execute shortcut even in an input element"
@change="updateData({ activeInInput: $event })"
>
Active while in input
</ui-checkbox>
<p class="mt-4 leading-tight text-gray-600 dark:text-gray-200">
Note: keyboard shortcut only executed when you're on a webpage
</p>
</div>
</transition-expand>
</template>
<script setup>
import { shallowReactive, onUnmounted } from 'vue';
import dayjs from 'dayjs';
const props = defineProps({
Expand All @@ -92,13 +119,69 @@ const triggers = [
{ id: 'interval', name: 'Interval' },
{ id: 'date', name: 'On specific date' },
{ id: 'visit-web', name: 'When visit a website' },
{ id: 'keyboard-shortcut', name: 'Keyboard shortcut' },
];
const maxDate = dayjs().add(30, 'day').format('YYYY-MM-DD');
const minDate = dayjs().format('YYYY-MM-DD');
const allowedKeys = {
'+': 'plus',
Delete: 'del',
Insert: 'ins',
ArrowDown: 'down',
ArrowLeft: 'left',
ArrowUp: 'up',
ArrowRight: 'right',
Escape: 'escape',
Enter: 'enter',
};
const recordKeys = shallowReactive({
isRecording: false,
keys: props.data.shortcut,
});
function updateData(value) {
emit('update:data', { ...props.data, ...value });
}
function handleKeydownEvent(event) {
event.preventDefault();
event.stopPropagation();
if (event.repeat) return;
const keys = [];
const { ctrlKey, altKey, metaKey, shiftKey, key } = event;
if (ctrlKey || metaKey) keys.push('mod');
if (altKey) keys.push('alt');
if (shiftKey) keys.push('shift');
const isValidKey = !!allowedKeys[key] || /^[a-z0-9,./;'[\]\-=`]$/i.test(key);
if (isValidKey) {
keys.push(allowedKeys[key] || key.toLowerCase());
recordKeys.keys = keys.join('+');
updateData({ shortcut: recordKeys.keys });
}
}
function toggleRecordKeys() {
if (recordKeys.isRecording) {
window.removeEventListener('keydown', handleKeydownEvent);
} else {
window.addEventListener('keydown', handleKeydownEvent);
}
recordKeys.isRecording = !recordKeys.isRecording;
}
function handleSelectChange(type) {
if (recordKeys.isRecording) {
window.removeEventListener('keydown', handleKeydownEvent);
recordKeys.isRecording = false;
}
updateData({ type });
}
function updateIntervalInput(value, { key, min, max }) {
let num = +value;
Expand All @@ -117,4 +200,8 @@ function updateDate(value) {
updateData({ date });
}
onUnmounted(() => {
window.removeEventListener('keydown', handleKeydownEvent);
});
</script>
33 changes: 0 additions & 33 deletions src/components/shared/SharedTaskList.vue

This file was deleted.

58 changes: 58 additions & 0 deletions src/content/shortcut.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import Mousetrap from 'mousetrap';
import browser from 'webextension-polyfill';
import { sendMessage } from '@/utils/message';

Mousetrap.prototype.stopCallback = function () {
return false;
};

function getTriggerBlock(workflow) {
const drawflow = JSON.parse(workflow?.drawflow || '{}');

if (!drawflow?.drawflow?.Home?.data) return null;

const blocks = Object.values(drawflow.drawflow.Home.data);
const trigger = blocks.find(({ name }) => name === 'trigger');

return trigger;
}

(async () => {
try {
const { shortcuts, workflows } = await browser.storage.local.get([
'shortcuts',
'workflows',
]);
const shortcutsArr = Object.entries(shortcuts || {});

if (shortcutsArr.length === 0) return;

const keyboardShortcuts = shortcutsArr.reduce((acc, [id, value]) => {
const workflow = [...workflows].find((item) => item.id === id);

(acc[value] = acc[value] || []).push({
id,
workflow,
activeInInput: getTriggerBlock(workflow)?.data?.activeInInput,
});

return acc;
}, {});

Mousetrap.bind(Object.keys(keyboardShortcuts), ({ target }, command) => {
const isInputElement =
['INPUT', 'SELECT', 'TEXTAREA'].includes(target.tagName) ||
target?.contentEditable === 'true';

keyboardShortcuts[command].forEach((item) => {
if (!item.activeInInput && isInputElement) return;

sendMessage('workflow:execute', item.workflow, 'background');
});

return false;
});
} catch (error) {
console.error(error);
}
})();
2 changes: 2 additions & 0 deletions src/lib/v-remixicon.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import vRemixicon from 'v-remixicon';
import {
riHome5Line,
riGithubFill,
riRecordCircleLine,
riErrorWarningLine,
riCalendarLine,
riFileTextLine,
Expand Down Expand Up @@ -65,6 +66,7 @@ import {
export const icons = {
riHome5Line,
riGithubFill,
riRecordCircleLine,
riErrorWarningLine,
riCalendarLine,
riFileTextLine,
Expand Down
12 changes: 12 additions & 0 deletions src/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,18 @@
"icons": {
"128": "icon-128.png"
},
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": [
"shortcut.bundle.js"
],
"run_at": "document_end",
"all_frames": false
}
],
"permissions": [
"tabs",
"alarms",
Expand Down
21 changes: 14 additions & 7 deletions src/models/workflow.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,17 +38,24 @@ class Workflow extends Model {

static async afterDelete({ id }) {
try {
const { visitWebTriggers } = await browser.storage.local.get(
'visitWebTriggers'
);
const { visitWebTriggers, shortcuts } = await browser.storage.local.get([
'visitWebTriggers',
'shortcuts',
]);
const index = visitWebTriggers.findIndex((item) => item.id === id);

await browser.alarms.clear(id);
if (index !== -1) {
visitWebTriggers.splice(index, 1);
}

if (index === -1) return;
const keyboardShortcuts = shortcuts || {};
delete keyboardShortcuts[id];

visitWebTriggers.splice(index, 1);
await browser.storage.local.set({ visitWebTriggers });
await browser.storage.local.set({
visitWebTriggers,
shortcuts: keyboardShortcuts,
});
await browser.alarms.clear(id);
} catch (error) {
console.error(error);
}
Expand Down
20 changes: 15 additions & 5 deletions src/newtab/pages/workflows/[id].vue
Original file line number Diff line number Diff line change
Expand Up @@ -198,22 +198,28 @@ function updateWorkflow(data) {
async function handleWorkflowTrigger({ data }) {
try {
const workflowAlarm = await browser.alarms.get(workflowId);
const { visitWebTriggers } = await browser.storage.local.get(
'visitWebTriggers'
);
const { visitWebTriggers, shortcuts } = await browser.storage.local.get([
'visitWebTriggers',
'shortcuts',
]);
let visitWebTriggerIndex = visitWebTriggers.findIndex(
(item) => item.id === workflowId
);
const keyboardShortcuts = shortcuts || {};
delete keyboardShortcuts[workflowId];
if (workflowAlarm) await browser.alarms.clear(workflowId);
if (visitWebTriggerIndex !== -1) {
visitWebTriggers.splice(visitWebTriggerIndex, 1);
visitWebTriggerIndex = -1;
await browser.storage.local.set({ visitWebTriggers });
}
await browser.storage.local.set({
visitWebTriggers,
shortcuts: keyboardShortcuts,
});
if (['date', 'interval'].includes(data.type)) {
let alarmInfo;
Expand Down Expand Up @@ -244,6 +250,10 @@ async function handleWorkflowTrigger({ data }) {
}
await browser.storage.local.set({ visitWebTriggers });
} else if (data.type === 'keyboard-shortcut') {
keyboardShortcuts[workflowId] = data.shortcut;
await browser.storage.local.set({ shortcuts: keyboardShortcuts });
}
} catch (error) {
console.error(error);
Expand Down
Loading

0 comments on commit 4f16674

Please sign in to comment.