Skip to content

Commit

Permalink
feat: support ace and codemirror editors
Browse files Browse the repository at this point in the history
closes #26 and closes #27
  • Loading branch information
u3u committed Jun 2, 2018
1 parent 9a6a6a5 commit 8fcbc4b
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 27 deletions.
6 changes: 5 additions & 1 deletion bili.config.js
@@ -1,7 +1,11 @@
// https://egoist.moe/bili/#/api

module.exports = {
input: ['src/scripts/background.ts', 'src/scripts/content.ts'],
input: [
'src/scripts/background.ts',
'src/scripts/content.ts',
'src/scripts/prettier.ts',
],
outDir: 'dist/scripts',
format: ['iife', 'iife-min'],
filename: '[name].js',
Expand Down
1 change: 1 addition & 0 deletions public/manifest.json
Expand Up @@ -31,6 +31,7 @@
]
}
],
"web_accessible_resources": ["scripts/*"],
"commands": {
"format-document": {
"suggested_key": {
Expand Down
48 changes: 22 additions & 26 deletions src/scripts/content.ts
@@ -1,31 +1,27 @@
import { isMultiTextbox } from './utils';
const script = document.createElement('script');
script.src = chrome.runtime.getURL('scripts/prettier.min.js');
document.body.appendChild(script);

chrome.runtime.onMessage.addListener(({ action, options }) => {
if (action === 'format') {
const { activeElement } = document;
if (isMultiTextbox(activeElement)) {
if (activeElement.tagName === 'TEXTAREA') {
const textarea = activeElement as HTMLTextAreaElement;
if (textarea.value.length > 0) {
textarea.value = prettier.format(textarea.value, {
parser: 'markdown',
plugins: prettierPlugins,
...options,
});
}
} else {
const element = activeElement as HTMLElement;
if (element.innerText.length > 0) {
element.innerText = prettier.format(element.innerText, {
parser: 'markdown',
plugins: prettierPlugins,
...options,
});
}
}
['keydown', 'keyup', 'change'].forEach(event =>
activeElement.dispatchEvent(new Event(event)),
);
}
window.postMessage({ action: 'getValue', options }, '*');
}
});

window.addEventListener('message', (event) => {
if (event.source !== window) return;
const { action, options, value } = event.data;
if (action === 'prettier') {
window.postMessage(
{
action: 'setValue',
value: prettier.format(value, {
parser: 'markdown',
plugins: prettierPlugins,
...options,
}),
},
'*',
);
}
});
27 changes: 27 additions & 0 deletions src/scripts/prettier.ts
@@ -0,0 +1,27 @@
/* eslint-disable default-case */
import MarkdownEditorFactory from './utils/MarkdownEditorFactory';

window.addEventListener('message', (event) => {
if (event.source !== window) return;
const { action, options, value } = event.data;
const editor = MarkdownEditorFactory.createMarkdownEditor(
document.activeElement,
);
if (editor !== null) {
switch (action) {
case 'getValue':
window.postMessage(
{
action: 'prettier',
value: editor.getValue(),
options,
},
'*',
);
break;
case 'setValue':
editor.setValue(value);
break;
}
}
});

0 comments on commit 8fcbc4b

Please sign in to comment.