├── mypy.ini ├── media └── main-feature.gif ├── src ├── ts │ ├── README.md │ ├── helpers.ts │ ├── html-filter │ │ ├── helpers.ts │ │ ├── node.ts │ │ ├── index.ts │ │ ├── styling.ts │ │ └── element.ts │ ├── index.ts │ ├── cross-browser.ts │ └── wrap.ts └── addon │ ├── __init__.py │ ├── manifest.json │ ├── web │ ├── bottom.js │ ├── global_card.css │ ├── resize.js │ ├── editor │ │ ├── editor.js │ │ └── editor.js.map │ └── global_card.js │ ├── semieditor.py │ ├── config.json │ ├── firstrun.py │ ├── reviewer.py │ └── configwindow.py ├── .gitmodules ├── rollup.config.js ├── .github ├── ISSUE_TEMPLATE │ ├── feature_request.md │ └── bug_report.md └── workflows │ ├── checks.yml │ └── create_release.yml ├── release └── new_version.py ├── package.json ├── README.md ├── .gitignore ├── DESCRIPTION.html ├── tsconfig.json ├── FAQ.md └── LICENSE /mypy.ini: -------------------------------------------------------------------------------- 1 | [mypy] 2 | no_strict_optional = True 3 | disallow_untyped_defs = True -------------------------------------------------------------------------------- /media/main-feature.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/BlueGreenMagick/Edit-Field-During-Review-Cloze/HEAD/media/main-feature.gif -------------------------------------------------------------------------------- /src/ts/README.md: -------------------------------------------------------------------------------- 1 | This addon requires `wrapInternal` and `pasteHTML` from Anki editor typescript 2 | Last updated: v2.1.53 3 | -------------------------------------------------------------------------------- /src/addon/__init__.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from . import firstrun 4 | from . import configwindow 5 | from . import reviewer 6 | -------------------------------------------------------------------------------- /.gitmodules: -------------------------------------------------------------------------------- 1 | [submodule "src/addon/ankiaddonconfig"] 2 | path = src/addon/ankiaddonconfig 3 | url = https://github.com/BlueGreenMagick/ankiaddonconfig.git 4 | -------------------------------------------------------------------------------- /src/addon/manifest.json: -------------------------------------------------------------------------------- 1 | { 2 | "package": "edit-field-during-review-cloze", 3 | "name": "Edit Field During Review (Cloze)", 4 | "human_version": "6.23", 5 | "conflicts": [ 6 | "1020366288" 7 | ] 8 | } -------------------------------------------------------------------------------- /src/ts/helpers.ts: -------------------------------------------------------------------------------- 1 | /* Copyright: Ankitects Pty Ltd and contributors 2 | * License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html */ 3 | 4 | export function nodeIsElement(node: Node): node is Element { 5 | return node.nodeType === Node.ELEMENT_NODE; 6 | } -------------------------------------------------------------------------------- /src/ts/html-filter/helpers.ts: -------------------------------------------------------------------------------- 1 | // Copyright: Ankitects Pty Ltd and contributors 2 | // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html 3 | 4 | export function isHTMLElement(elem: Element): elem is HTMLElement { 5 | return elem instanceof HTMLElement; 6 | } 7 | 8 | export function isNightMode(): boolean { 9 | return document.body.classList.contains("nightMode"); 10 | } 11 | -------------------------------------------------------------------------------- /rollup.config.js: -------------------------------------------------------------------------------- 1 | import typescript from '@rollup/plugin-typescript' 2 | 3 | export default [ 4 | { 5 | input: 'src/ts/index.ts', 6 | output: { 7 | sourcemap: true, 8 | format: 'iife', 9 | file: 'src/addon/web/editor/editor.js' 10 | }, 11 | plugins: [ 12 | typescript({ 13 | sourceMap: true, 14 | inlineSources: true 15 | }) 16 | ] 17 | } 18 | ] 19 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | This is a blank template to describe your idea. 11 | Please do not be offended if I don't leave any comments - it doesn't mean I haven't read it or I'm not considering it, but that you were very descriptive so I don't need any further clarifications. 12 | -------------------------------------------------------------------------------- /release/new_version.py: -------------------------------------------------------------------------------- 1 | import re 2 | import sys 3 | import simplejson 4 | from pathlib import Path 5 | 6 | version_string = sys.argv[1] 7 | assert re.match(r"^(\d+).(\d+)$", version_string) 8 | 9 | addon_dir = Path(__file__).resolve().parents[1] / "src" / "addon" 10 | 11 | # Write version in manifest.json 12 | json_path = addon_dir / "manifest.json" 13 | with json_path.open("r") as f: 14 | manifest = simplejson.load(f) 15 | 16 | with json_path.open("w") as f: 17 | manifest["human_version"] = version_string 18 | simplejson.dump(manifest, f, indent=2) 19 | -------------------------------------------------------------------------------- /.github/workflows/checks.yml: -------------------------------------------------------------------------------- 1 | name: checks 2 | 3 | on: 4 | push: 5 | branches: 6 | - "*" 7 | pull_request: 8 | branches: 9 | - "*" 10 | 11 | jobs: 12 | build: 13 | runs-on: ubuntu-latest 14 | steps: 15 | - uses: actions/checkout@v2 16 | with: 17 | submodules: recursive 18 | 19 | - name: Setup Python 20 | uses: actions/setup-python@v2.2.1 21 | with: 22 | python-version: 3.9 23 | 24 | - name: Install npm dependencies 25 | run: npm ci 26 | 27 | - name: Run standard 28 | run: npx standard 29 | 30 | - name: Install Python dependencies 31 | run: python -m pip install aqt mypy pyqt5-stubs PyQt6 PyQt6-WebEngine types-simplejson 32 | 33 | - name: Run mypy 34 | run: python -m mypy --install-types --non-interactive . 35 | -------------------------------------------------------------------------------- /src/ts/index.ts: -------------------------------------------------------------------------------- 1 | /* Copyright: Ankitects Pty Ltd and contributors 2 | * License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html */ 3 | 4 | import { filterHTML } from "./html-filter/index"; 5 | import { wrapInternal } from "./wrap"; 6 | 7 | export function setFormat( 8 | cmd: string, 9 | arg?: any, 10 | nosave: boolean = false 11 | ): void { 12 | // modified - removed saveField call 13 | document.execCommand(cmd, false, arg); 14 | } 15 | 16 | declare global { 17 | interface Window { 18 | EFDRC: any; 19 | } 20 | } 21 | 22 | window.EFDRC.pasteHTML = function ( 23 | html: string, 24 | internal: boolean, 25 | extendedMode: boolean 26 | ): void { 27 | html = filterHTML(html, internal, extendedMode); 28 | 29 | if (html !== "") { 30 | setFormat("inserthtml", html); 31 | } 32 | }; 33 | 34 | window.EFDRC.wrapInternal = wrapInternal; 35 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a bug report 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | The below checklist isn't manditory, but suggested before creating an issue. 10 | - [ ] I've updated this add-on to the latest version 11 | - [ ] I've tried disabling all other add-ons except this one. 12 | 13 | **Describe the bug** 14 | What is the bug, and what behaviour did you expect instead? 15 | 16 | **To Reproduce** 17 | Steps to reproduce the behavior: 18 | 1. Go to '...' 19 | 2. Click on '....' 20 | 3. Scroll down to '....' 21 | 4. See error 22 | 23 | **Screenshots** 24 | If applicable, please add screenshots to help explain your problem. 25 | 26 | **Debug Info** 27 | In the toolbar, go to `Help > About...`. In the About window, click the `Copy Debug Info` button at the bottom beside an 'OK' button. Please paste the contents below. 28 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "edit-field-during-review-cloze", 3 | "version": "1.0.0", 4 | "description": "This addon lets you edit card during review. More information at [Ankiweb](https://ankiweb.net/shared/info/385888438)", 5 | "repository": { 6 | "type": "git", 7 | "url": "git+https://github.com/BlueGreenMagick/Edit-Field-During-Review-Cloze.git" 8 | }, 9 | "author": "bluegreenmagick", 10 | "license": "MIT", 11 | "bugs": { 12 | "url": "https://github.com/BlueGreenMagick/Edit-Field-During-Review-Cloze/issues" 13 | }, 14 | "homepage": "https://github.com/BlueGreenMagick/Edit-Field-During-Review-Cloze#readme", 15 | "scripts": { 16 | "build": "rollup -c" 17 | }, 18 | "standard": { 19 | "ignore": [ 20 | "src/addon/web/editor", 21 | "*.ts" 22 | ] 23 | }, 24 | "devDependencies": { 25 | "standard": "^16.0.3", 26 | "typescript": "^4.2.3", 27 | "@rollup/plugin-typescript": "^8.3.2", 28 | "rollup": "^2.74.1" 29 | } 30 | } -------------------------------------------------------------------------------- /src/addon/web/bottom.js: -------------------------------------------------------------------------------- 1 | /* global autoAnswerTimeout, autoAlertTimeout, autoAgainTimeout */ 2 | 3 | // If focus in on bottom.web, ctrl key press is not catched by global_card.js 4 | // So this code catches ctrl key presses when focus in on bottom.web 5 | 6 | window.addEventListener('keydown', function (event) { 7 | if (['ControlLeft', 'MetaLeft'].includes(event.code)) { 8 | window.pycmd('EFDRC!ctrldown') 9 | } 10 | }) 11 | 12 | window.addEventListener('keyup', function (event) { 13 | if (['ControlLeft', 'MetaLeft'].includes(event.code)) { 14 | window.pycmd('EFDRC!ctrlup') 15 | } 16 | }) 17 | 18 | window.EFDRCResetTimer = function () { 19 | // Reset timer from Speed Focus Mode add-on. 20 | if (typeof autoAnswerTimeout !== 'undefined') { 21 | clearTimeout(autoAnswerTimeout) 22 | } 23 | if (typeof autoAlertTimeout !== 'undefined') { 24 | clearTimeout(autoAlertTimeout) 25 | } 26 | if (typeof autoAgainTimeout !== 'undefined') { 27 | clearTimeout(autoAgainTimeout) 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /src/ts/cross-browser.ts: -------------------------------------------------------------------------------- 1 | // Copyright: Ankitects Pty Ltd and contributors 2 | // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html 3 | 4 | /** 5 | * Gecko has no .getSelection on ShadowRoot, only .activeElement 6 | */ 7 | export function getSelection(element: Node): Selection | null { 8 | const root = element.getRootNode() as Document; 9 | 10 | if (root.getSelection) { 11 | return root.getSelection(); 12 | } 13 | 14 | return document.getSelection(); 15 | } 16 | 17 | /** 18 | * Browser has potential support for multiple ranges per selection built in, 19 | * but in reality only Gecko supports it. 20 | * If there are multiple ranges, the latest range is the _main_ one. 21 | */ 22 | export function getRange(selection: Selection): Range | null { 23 | const rangeCount = selection.rangeCount; 24 | 25 | return rangeCount === 0 ? null : selection.getRangeAt(rangeCount - 1); 26 | } 27 | 28 | /** 29 | * Avoid using selection.isCollapsed: it will always return 30 | * true in shadow root in Gecko 31 | * (this bug seems to also happens in Blink) 32 | */ 33 | export function isSelectionCollapsed(selection: Selection): boolean { 34 | return getRange(selection)!.collapsed; 35 | } 36 | -------------------------------------------------------------------------------- /src/ts/html-filter/node.ts: -------------------------------------------------------------------------------- 1 | // Copyright: Ankitects Pty Ltd and contributors 2 | // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html 3 | 4 | export function removeNode(element: Node): void { 5 | element.parentNode?.removeChild(element); 6 | } 7 | 8 | function iterateElement( 9 | filter: (node: Node) => void, 10 | fragment: DocumentFragment | Element, 11 | ): void { 12 | for (const child of [...fragment.childNodes]) { 13 | filter(child); 14 | } 15 | } 16 | 17 | export const filterNode = 18 | (elementFilter: (element: Element) => void) => 19 | (node: Node): void => { 20 | switch (node.nodeType) { 21 | case Node.COMMENT_NODE: 22 | removeNode(node); 23 | break; 24 | 25 | case Node.DOCUMENT_FRAGMENT_NODE: 26 | iterateElement(filterNode(elementFilter), node as DocumentFragment); 27 | break; 28 | 29 | case Node.ELEMENT_NODE: 30 | iterateElement(filterNode(elementFilter), node as Element); 31 | elementFilter(node as Element); 32 | break; 33 | 34 | default: 35 | // do nothing 36 | } 37 | }; 38 | -------------------------------------------------------------------------------- /src/addon/web/global_card.css: -------------------------------------------------------------------------------- 1 | [data-efdrcfield][contenteditable="true"].EFDRC-outline:focus { 2 | outline: 1px solid #308cc6; 3 | } 4 | /* placeholder style */ 5 | [data-efdrcfield][contenteditable="true"][data-placeholder].EFDRC-ctrl:empty:before { 6 | content: attr(data-placeholder); 7 | color: #888; 8 | font-style: italic; 9 | } 10 | 11 | /* image resizing */ 12 | .ui-wrapper { 13 | outline: 3px solid #66b3da; 14 | overflow: visible !important; 15 | } 16 | .ui-resizable { 17 | position: relative; 18 | } 19 | .ui-resizable-handle { 20 | position: absolute; 21 | font-size: 0.1px; 22 | display: block; 23 | -ms-touch-action: none; 24 | touch-action: none; 25 | } 26 | .ui-resizable-disabled .ui-resizable-handle, 27 | .ui-resizable-autohide .ui-resizable-handle { 28 | display: none; 29 | } 30 | .ui-resizable-s { 31 | cursor: s-resize; 32 | height: 10px; 33 | width: auto; 34 | bottom: -5px; 35 | left: 0; 36 | right: 6px; 37 | } 38 | .ui-resizable-e { 39 | cursor: e-resize; 40 | width: 10px; 41 | height: auto; 42 | right: -5px; 43 | top: 0; 44 | bottom: 6px; 45 | } 46 | .ui-resizable-se { 47 | background: #66b3da; 48 | cursor: se-resize; 49 | width: 11px; 50 | height: 11px; 51 | right: -7px; 52 | bottom: -7px; 53 | } 54 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | For add-on description, please see [AnkiWeb page](https://ankiweb.net/shared/info/385888438) or the [FAQ](./FAQ.md) 2 | # Development 3 | ## Setup 4 | After cloning the project, run the following command 5 | ``` 6 | git submodule update --init --recursive 7 | npm ci 8 | ``` 9 | The first command installs [ankiaddonconfig](https://github.com/BlueGreenMagick/ankiaddonconfig/) as a git submodule, and the second command installs the npm dev dependencies of this project. 10 | 11 | ## Updating typescript code 12 | 13 | After editing code in [./src/ts](./src/ts), run `npm run build` to compile it to [./src/addon/web/editor/editor.js](./src/addon/web/editor/editor.js). 14 | 15 | ## Tests & Formatting 16 | This project uses [mypy](https://github.com/python/mypy) type checking for Python, and [standardjs](https://github.com/standard/standard) for formatting Javascript. 17 | 18 | ``` 19 | python -m mypy . 20 | npx standard --fix 21 | ``` 22 | 23 | You will need to install the following python packages to run mypy: 24 | ``` 25 | python -m pip install aqt PyQt5-stubs mypy types-simplejson 26 | ``` 27 | 28 | This project doesn't use a strict python formatter. Even so, please make it look pretty enough :) 29 | 30 | # Building ankiaddon file 31 | After cloning the repo, go into the repo directory and run the following command to install the git submodule [ankiaddonconfig](https://github.com/BlueGreenMagick/ankiaddonconfig/) 32 | ``` 33 | git submodule update --init --remote src/addon/ankiaddonconfig 34 | ``` 35 | After installing the git submodule, run the following command to create an `efdrc.ankiaddon` file 36 | ``` 37 | cd src/addon ; zip -r ../../efdrc.ankiaddon * ; cd ../../ 38 | ``` -------------------------------------------------------------------------------- /.github/workflows/create_release.yml: -------------------------------------------------------------------------------- 1 | name: Create Release 2 | 3 | on: 4 | workflow_dispatch: 5 | inputs: 6 | version: 7 | description: version string (eg. 6.1) 8 | required: true 9 | 10 | jobs: 11 | create-release: 12 | runs-on: ubuntu-latest 13 | steps: 14 | - uses: actions/checkout@v2 15 | with: 16 | submodules: recursive 17 | 18 | - name: Setup Python 19 | uses: actions/setup-python@v2.2.1 20 | with: 21 | python-version: 3.9 22 | 23 | - name: Install dependencies 24 | run: python -m pip install simplejson 25 | 26 | - name: Run release/new_version.py 27 | run: python ./release/new_version.py ${{ github.event.inputs.version }} 28 | 29 | - name: Commit changes to git 30 | uses: EndBug/add-and-commit@v7.1.1 31 | with: 32 | message: Bump Version to v${{ github.event.inputs.version }} 33 | 34 | - name: Push new version with tag 35 | uses: ad-m/github-push-action@v0.6.0 36 | with: 37 | github_token: ${{ github.token }} 38 | branch: master 39 | tags: ${{ github.event.inputs.version }} 40 | 41 | - name: Create ankiaddon file 42 | run: cd src/addon ; zip -r ../../efdrc_v${{ github.event.inputs.version }}.ankiaddon * ; cd ../../ 43 | 44 | - name: Create github release and upload ankiaddon file 45 | uses: svenstaro/upload-release-action@2.9.0 46 | with: 47 | repo_token: ${{ github.token }} 48 | file: "efdrc_v${{ github.event.inputs.version }}.ankiaddon" 49 | tag: ${{ github.event.inputs.version }} 50 | release_name: EFDRC v${{ github.event.inputs.version }} 51 | -------------------------------------------------------------------------------- /src/ts/wrap.ts: -------------------------------------------------------------------------------- 1 | // Copyright: Ankitects Pty Ltd and contributors 2 | // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html 3 | 4 | import { getRange, getSelection } from "./cross-browser"; 5 | 6 | function wrappedExceptForWhitespace( 7 | text: string, 8 | front: string, 9 | back: string 10 | ): string { 11 | const match = text.match(/^(\s*)([^]*?)(\s*)$/)!; 12 | return match[1] + front + match[2] + back + match[3]; 13 | } 14 | 15 | function moveCursorInside(selection: Selection, postfix: string): void { 16 | const range = getRange(selection)!; 17 | 18 | range.setEnd(range.endContainer, range.endOffset - postfix.length); 19 | range.collapse(false); 20 | 21 | selection.removeAllRanges(); 22 | selection.addRange(range); 23 | } 24 | 25 | export function wrapInternal( 26 | base: Element, 27 | front: string, 28 | back: string, 29 | plainText: boolean 30 | ): void { 31 | const selection = getSelection(base)!; 32 | const range = getRange(selection); 33 | 34 | if (!range) { 35 | return; 36 | } 37 | 38 | const wasCollapsed = range.collapsed; 39 | const content = range.cloneContents(); 40 | const span = document.createElement("span"); 41 | span.appendChild(content); 42 | 43 | if (plainText) { 44 | const new_ = wrappedExceptForWhitespace(span.innerText, front, back); 45 | document.execCommand("inserttext", false, new_); 46 | } else { 47 | const new_ = wrappedExceptForWhitespace(span.innerHTML, front, back); 48 | document.execCommand("inserthtml", false, new_); 49 | } 50 | 51 | if ( 52 | wasCollapsed && 53 | /* ugly solution: treat differently than other wraps */ !front.includes( 54 | " void> = { 18 | [FilterMode.Basic]: filterElementBasic, 19 | [FilterMode.Extended]: filterElementExtended, 20 | [FilterMode.Internal]: filterElementInternal, 21 | }; 22 | 23 | const whitespace = /[\n\t ]+/g; 24 | 25 | function collapseWhitespace(value: string): string { 26 | return value.replace(whitespace, " "); 27 | } 28 | 29 | function trim(value: string): string { 30 | return value.trim(); 31 | } 32 | 33 | const outputHTMLProcessors: Record string> = 34 | { 35 | [FilterMode.Basic]: (outputHTML: string): string => 36 | trim(collapseWhitespace(outputHTML)), 37 | [FilterMode.Extended]: trim, 38 | [FilterMode.Internal]: trim, 39 | }; 40 | 41 | export function filterHTML( 42 | html: string, 43 | internal: boolean, 44 | extended: boolean 45 | ): string { 46 | const template = document.createElement("template"); 47 | template.innerHTML = html; 48 | 49 | const mode = getFilterMode(internal, extended); 50 | const content = template.content; 51 | const filter = filterNode(filters[mode]); 52 | 53 | filter(content); 54 | 55 | return outputHTMLProcessors[mode](template.innerHTML); 56 | } 57 | 58 | function getFilterMode(internal: boolean, extended: boolean): FilterMode { 59 | if (internal) { 60 | return FilterMode.Internal; 61 | } else if (extended) { 62 | return FilterMode.Extended; 63 | } else { 64 | return FilterMode.Basic; 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /DESCRIPTION.html: -------------------------------------------------------------------------------- 1 | This addon lets you edit your card during review. You can add clozes, images, LaTeX expressions, highlight text, and most things you can do in the editor. 2 | To edit a field, click on a field while pressing Ctrl. (Cmd on mac) 3 | 4 | 5 | 6 | After installing, additional work is required to make the fields editable. 7 | Open the addon config and go to the "Fields" tab. You can select the fields of note types you want to edit in the reviewer. 8 | 9 | Doing this edits the note type template so {{Field}} becomes {{edit:Field}}. You can do this manually as well. Whenever you add a new note type, you will need to make them editable with the above method. 10 | 11 | See Commonly asked Questions
for more details. 12 | 13 |

Credits & License

14 | 15 | This addon was created by Bluegreenmagick, and is licensed under the GNU AGPL v3. 16 | 17 | This addon is based on the Edit Field During Review addon by Nickolay (kelciour). 18 | The following people has contributed code to this addon: Arthur Milchior, Aristotelis P. (Glutanimate), and hikaru-y. 19 | It also contains code from Anki by Damien Elmes and other developers, which is licensed under the GNU AGPL v3. 20 | 21 |

Additional Links

22 | 23 | Ankiweb -  24 | Github -  25 | Report an issue -  26 | License -------------------------------------------------------------------------------- /src/addon/semieditor.py: -------------------------------------------------------------------------------- 1 | from typing import Any, Callable, Optional 2 | 3 | from anki.hooks import wrap 4 | from aqt import mw 5 | from aqt.editor import Editor, EditorWebView 6 | from aqt.progress import ProgressManager, ProgressDialog 7 | from aqt.qt import QCursor, Qt 8 | 9 | # necessary in order to use methods defined in Editor and EditorWebView 10 | # without setting up the UI 11 | 12 | 13 | myprogress = False 14 | 15 | 16 | class SemiEditor(Editor): 17 | def __init__(self) -> None: 18 | self.mw = mw 19 | self.parentWindow = "EFDRCsemiedit" # type: ignore 20 | 21 | # For compatibility with other addons (GH#125) 22 | self.currentField = None 23 | self.last_field_index = None 24 | self.card = None 25 | 26 | 27 | class SemiEditorWebView(EditorWebView): 28 | def __init__(self) -> None: 29 | self.mw = mw 30 | self.editor = SemiEditor() 31 | 32 | 33 | def mystart(*args: Any, **kwargs: Any) -> Optional[ProgressDialog]: 34 | global myprogress 35 | _old = kwargs.pop("_old") 36 | if "parent" in kwargs: 37 | parent = kwargs["parent"] 38 | elif len(args) > 4: 39 | parent = args[4] # Position of 'parent' parameter. 40 | else: 41 | parent = None 42 | 43 | if parent == "EFDRCsemiedit": 44 | # Don't show progress window when pasting images while in review. 45 | myprogress = True 46 | mw.app.setOverrideCursor(QCursor(Qt.CursorShape.WaitCursor)) 47 | return None 48 | else: 49 | myprogress = False 50 | return _old(*args, **kwargs) 51 | 52 | 53 | def myfinish(self: ProgressManager, _old: Callable) -> None: 54 | global myprogress 55 | if myprogress: 56 | myprogress = False 57 | self.app.restoreOverrideCursor() 58 | return 59 | else: 60 | return _old(self) 61 | 62 | 63 | ProgressManager.start = wrap(ProgressManager.start, mystart, "around") # type: ignore 64 | ProgressManager.finish = wrap(ProgressManager.finish, myfinish, "around") # type: ignore 65 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es2019", 4 | "module": "es6", 5 | "lib": [ 6 | "es2017", 7 | "es2018.intl", 8 | "es2018.promise", 9 | "es2019.array", 10 | "es2019.object", 11 | "es2019.string", 12 | "es2020.promise", 13 | "dom", 14 | "dom.iterable" 15 | ], 16 | "baseUrl": ".", 17 | "paths": {}, 18 | "types": [], 19 | "importsNotUsedAsValues": "error", 20 | /* Strict Type-Checking Options */ 21 | "strict": true /* Enable all strict type-checking options. */, 22 | "noImplicitAny": false /* Raise error on expressions and declarations with an implied 'any' type. */, 23 | "strictNullChecks": true /* Enable strict null checks. */, 24 | "strictFunctionTypes": true /* Enable strict checking of function types. */, 25 | "strictBindCallApply": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */, 26 | "strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */, 27 | "noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */, 28 | "alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */, 29 | /* Module Resolution Options */ 30 | "moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */, 31 | "allowSyntheticDefaultImports": true /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */, 32 | "esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */, 33 | "jsx": "react", 34 | "noEmitHelpers": true, 35 | "importHelpers": true 36 | }, 37 | "include": [ 38 | "./src/ts/*.ts" 39 | ] 40 | } -------------------------------------------------------------------------------- /src/ts/html-filter/styling.ts: -------------------------------------------------------------------------------- 1 | // Copyright: Ankitects Pty Ltd and contributors 2 | // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html 3 | 4 | interface AllowPropertiesBlockValues { 5 | [property: string]: string[]; 6 | } 7 | 8 | type BlockProperties = string[]; 9 | 10 | type StylingPredicate = (property: string, value: string) => boolean; 11 | 12 | const stylingNightMode: AllowPropertiesBlockValues = { 13 | "font-weight": [], 14 | "font-style": [], 15 | "text-decoration-line": [], 16 | }; 17 | 18 | const stylingLightMode: AllowPropertiesBlockValues = { 19 | color: [], 20 | "background-color": ["transparent"], 21 | ...stylingNightMode, 22 | }; 23 | 24 | const stylingInternal: BlockProperties = [ 25 | "background-color", 26 | "font-size", 27 | "font-family", 28 | "width", 29 | "height", 30 | "max-width", 31 | "max-height", 32 | ]; 33 | 34 | const allowPropertiesBlockValues = 35 | (allowBlock: AllowPropertiesBlockValues): StylingPredicate => 36 | (property: string, value: string): boolean => 37 | Object.prototype.hasOwnProperty.call(allowBlock, property) && 38 | !allowBlock[property].includes(value); 39 | 40 | const blockProperties = 41 | (block: BlockProperties): StylingPredicate => 42 | (property: string): boolean => 43 | !block.includes(property); 44 | 45 | const filterStyling = 46 | (predicate: (property: string, value: string) => boolean) => 47 | (element: HTMLElement): void => { 48 | for (const property of [...element.style]) { 49 | const value = element.style.getPropertyValue(property); 50 | 51 | if (!predicate(property, value)) { 52 | element.style.removeProperty(property); 53 | } 54 | } 55 | }; 56 | 57 | export const filterStylingNightMode = filterStyling( 58 | allowPropertiesBlockValues(stylingNightMode), 59 | ); 60 | export const filterStylingLightMode = filterStyling( 61 | allowPropertiesBlockValues(stylingLightMode), 62 | ); 63 | export const filterStylingInternal = filterStyling(blockProperties(stylingInternal)); 64 | -------------------------------------------------------------------------------- /src/addon/config.json: -------------------------------------------------------------------------------- 1 | { 2 | "ctrl_click": true, 3 | "outline": true, 4 | "process_paste": true, 5 | "remove_span": false, 6 | "tag": "div", 7 | "resize_image_default_state": true, 8 | "resize_image_preserve_ratio": 2, 9 | "disable_autoplay_after_edit": false, 10 | "shortcuts" : { 11 | "cloze": "Ctrl + Shift + C", 12 | "cloze-alt": "Ctrl + Shift + Alt + C", 13 | "image-resize": "Alt + S" 14 | }, 15 | "special_formatting": { 16 | "fontcolor": { 17 | "enabled": true, 18 | "command": "foreColor", 19 | "shortcut": "F7", 20 | "arg": { 21 | "type": "color", 22 | "value": "#00f" 23 | } 24 | }, 25 | "formatblock": { 26 | "enabled": false, 27 | "command": "formatBlock", 28 | "shortcut": "Ctrl + .", 29 | "arg": { 30 | "type": "text", 31 | "value": "pre" 32 | } 33 | }, 34 | "highlight": { 35 | "enabled": false, 36 | "command": "hiliteColor", 37 | "shortcut": "Ctrl + Shift + B", 38 | "arg": { 39 | "type": "color", 40 | "value": "#00f" 41 | } 42 | }, 43 | "hyperlink": { 44 | "enabled": false, 45 | "command": "createLink", 46 | "shortcut": "Ctrl + Shift + H", 47 | "arg": null 48 | }, 49 | "indent": { 50 | "enabled": false, 51 | "command": "indent", 52 | "shortcut": "Ctrl + Shift + ]", 53 | "arg": null 54 | }, 55 | "justifyCenter": { 56 | "enabled": false, 57 | "command": "justifyCenter", 58 | "shortcut": "Ctrl + Shift + Alt + S", 59 | "arg": null 60 | }, 61 | "justifyFull": { 62 | "enabled": false, 63 | "command": "justifyFull", 64 | "shortcut": "Ctrl + Shift + Alt + B", 65 | "arg": null 66 | }, 67 | "justifyLeft": { 68 | "enabled": false, 69 | "command": "justifyLeft", 70 | "shortcut": "Ctrl + Shift + Alt + L", 71 | "arg": null 72 | }, 73 | "justifyRight": { 74 | "enabled": false, 75 | "command": "justifyRight", 76 | "shortcut": "Ctrl + Shift + Alt + R", 77 | "arg": null 78 | }, 79 | "orderedlist": { 80 | "enabled": false, 81 | "command": "insertOrderedList", 82 | "shortcut": "Ctrl + ]", 83 | "arg": null 84 | }, 85 | "outdent": { 86 | "enabled": false, 87 | "command": "outdent", 88 | "shortcut": "Ctrl + Shift + [", 89 | "arg": null 90 | }, 91 | "removeformat": { 92 | "enabled": true, 93 | "command": "removeFormat", 94 | "shortcut": "Ctrl + R", 95 | "arg": null 96 | }, 97 | "strikethrough": { 98 | "enabled": false, 99 | "command": "strikeThrough", 100 | "shortcut": "Ctrl + Shift + Alt + 5", 101 | "arg": null 102 | }, 103 | "subscript": { 104 | "enabled": false, 105 | "command": "subscript", 106 | "shortcut": "Ctrl + =", 107 | "arg": null 108 | }, 109 | "superscript": { 110 | "enabled": false, 111 | "command": "superscript", 112 | "shortcut": "Ctrl + Shift + =", 113 | "arg": null 114 | }, 115 | "unhyperlink": { 116 | "enabled": false, 117 | "command": "createLink", 118 | "shortcut": "Ctrl + Shift + Alt + H", 119 | "arg": null 120 | }, 121 | "unorderedlist": { 122 | "enabled": false, 123 | "command": "insertUnorderedList", 124 | "shortcut": "Ctrl + [", 125 | "arg": null 126 | } 127 | }, 128 | "version": { 129 | "major": -1, 130 | "minor": -1 131 | } 132 | } -------------------------------------------------------------------------------- /src/ts/html-filter/element.ts: -------------------------------------------------------------------------------- 1 | // Copyright: Ankitects Pty Ltd and contributors 2 | // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html 3 | 4 | import { isHTMLElement, isNightMode } from "./helpers"; 5 | import { removeNode as removeElement } from "./node"; 6 | import { 7 | filterStylingInternal, 8 | filterStylingLightMode, 9 | filterStylingNightMode, 10 | } from "./styling"; 11 | 12 | interface TagsAllowed { 13 | [tagName: string]: FilterMethod; 14 | } 15 | 16 | type FilterMethod = (element: Element) => void; 17 | 18 | function filterAttributes( 19 | attributePredicate: (attributeName: string) => boolean, 20 | element: Element, 21 | ): void { 22 | for (const attr of [...element.attributes]) { 23 | const attrName = attr.name.toUpperCase(); 24 | 25 | if (!attributePredicate(attrName)) { 26 | element.removeAttributeNode(attr); 27 | } 28 | } 29 | } 30 | 31 | function allowNone(element: Element): void { 32 | filterAttributes(() => false, element); 33 | } 34 | 35 | const allow = 36 | (attrs: string[]): FilterMethod => 37 | (element: Element): void => 38 | filterAttributes( 39 | (attributeName: string) => attrs.includes(attributeName), 40 | element, 41 | ); 42 | 43 | function unwrapElement(element: Element): void { 44 | element.replaceWith(...element.childNodes); 45 | } 46 | 47 | function filterSpan(element: Element): void { 48 | const filterAttrs = allow(["STYLE"]); 49 | filterAttrs(element); 50 | 51 | const filterStyle = isNightMode() ? filterStylingNightMode : filterStylingLightMode; 52 | filterStyle(element as HTMLSpanElement); 53 | } 54 | 55 | const tagsAllowedBasic: TagsAllowed = { 56 | BR: allowNone, 57 | IMG: allow(["SRC", "ALT"]), 58 | DIV: allowNone, 59 | P: allowNone, 60 | SUB: allowNone, 61 | SUP: allowNone, 62 | TITLE: removeElement, 63 | }; 64 | 65 | const tagsAllowedExtended: TagsAllowed = { 66 | ...tagsAllowedBasic, 67 | A: allow(["HREF"]), 68 | B: allowNone, 69 | BLOCKQUOTE: allowNone, 70 | CODE: allowNone, 71 | DD: allowNone, 72 | DL: allowNone, 73 | DT: allowNone, 74 | EM: allowNone, 75 | FONT: allow(["COLOR"]), 76 | H1: allowNone, 77 | H2: allowNone, 78 | H3: allowNone, 79 | I: allowNone, 80 | LI: allowNone, 81 | OL: allowNone, 82 | PRE: allowNone, 83 | RP: allowNone, 84 | RT: allowNone, 85 | RUBY: allowNone, 86 | SPAN: filterSpan, 87 | STRONG: allowNone, 88 | TABLE: allowNone, 89 | TD: allow(["COLSPAN", "ROWSPAN"]), 90 | TH: allow(["COLSPAN", "ROWSPAN"]), 91 | TR: allow(["ROWSPAN"]), 92 | U: allowNone, 93 | UL: allowNone, 94 | }; 95 | 96 | const filterElementTagsAllowed = 97 | (tagsAllowed: TagsAllowed) => 98 | (element: Element): void => { 99 | const tagName = element.tagName; 100 | 101 | if (Object.prototype.hasOwnProperty.call(tagsAllowed, tagName)) { 102 | tagsAllowed[tagName](element); 103 | } else if (element.innerHTML) { 104 | unwrapElement(element); 105 | } else { 106 | removeElement(element); 107 | } 108 | }; 109 | 110 | export const filterElementBasic = filterElementTagsAllowed(tagsAllowedBasic); 111 | export const filterElementExtended = filterElementTagsAllowed(tagsAllowedExtended); 112 | 113 | export function filterElementInternal(element: Element): void { 114 | if (isHTMLElement(element)) { 115 | filterStylingInternal(element); 116 | } 117 | } 118 | -------------------------------------------------------------------------------- /FAQ.md: -------------------------------------------------------------------------------- 1 | ## I can't edit the cards while reviewing! 2 | 3 | Please check if you enabled editing your field in the note type. Go to the addon config, select the `Fields` tab. Choose your note type from the dropdown and see if the fields are editable. 4 | 5 | Alternatively, you can control each fields editability by editing the notetype card template. Add or remove `edit:` from the field name. For example, `{{edit:Front}}`, `{{edit:cloze:Text}}`. 6 | 7 | ## What do I put in as keyboard shortcut? 8 | 9 | Each shortcut can have `"Ctrl"`, `"Shift"`, `"Alt"`, and one other key. They are combined using `+`. 10 | 11 | Examples: `"K"`, `"Ctrl+C"`, `"Alt+Shift+,"`, `"Ctrl+Alt+F1` 12 | 13 | If you are using Macs, use press `Cmd` key for `"Ctrl"`, and `Opt` key for `"Alt"`. 14 | 15 | ## Can I have multiple formatting shortcuts? 16 | 17 | It is possible to have multiple formatting shortcut entries. You can do this to have multiple `fontcolor`, `formatblock`, or `highlight` shortcuts with different colors, or if you want multiple keyboard shortcuts. 18 | 19 | You will need to go to the Advanced config editor. In `special_formatting`, copy paste the entry you want to duplicate, which looks like below. 20 | 21 | ```json 22 | "fontcolor": { 23 | "arg": { 24 | "type": "color", 25 | "value": "#00f" 26 | }, 27 | "command": "foreColor", 28 | "enabled": true, 29 | "shortcut": "F7" 30 | }, 31 | ``` 32 | 33 | Edit the entry name (`fontcolor`) to any unique name, then exit. If you exit the addon config and reopen it, your new entry should be there in the list of formatting shortcuts. 34 | 35 | Before editing in the Advanced config editor, you should save the existing config in another place, so if you modify the config incorrectly, you will be able to restore your previous config. 36 | 37 | When deleting the newly added entry from advanced config editor, you'll see an error after saving. You can ignore the error and click "Quit Config". 38 | 39 | ## How do I apply styles to editable field html? 40 | 41 | You can use the css selector `div[data-efdrcfield]` (or `span[data-efdrcfield]` depending on your config) 42 | 43 | ## How do I align fields next to each other? (Instead of field going to a new line) 44 | 45 | For now, please put the following line into note type template styling: 46 | 47 | ```css 48 | div[data-efdrcfield] { 49 | display: inline-block; 50 | } 51 | ``` 52 | 53 | ## How to add a custom shortcut action 54 | 55 | You can customize the note type to add a custom shortcut action during edit. You will need to know JavaScript. 56 | 57 | Add the following code to your note type. The handler will only be triggered when you press the shortcut while editing. 58 | Any edits to elem.innerHTML is saved to note field when 'blur' event is triggered on elem. 59 | 60 | ```javascript 61 | EFDRC.registerShortcut("Ctrl+Shift+Alt+R", (event, elem) => { 62 | // event: KeyEvent, elem: contenteditable field element that is being edited 63 | // Write code to do whatever you want. 64 | } 65 | ``` 66 | 67 | ## How to edit conditionally hidden field? 68 | 69 | When you use conitional replacement in Anki notetype template to hide fields when empty, 70 | you need to modify your note type to be able to edit it during review. 71 | 72 | If you want to hide `{{Field}}` if it is empty, write the below code in your notetype: 73 | 74 | ```html 75 |
76 | {{Field}} 77 |
78 | ``` 79 | 80 | Then add the following code into the Styling of the note type: 81 | 82 | ```css 83 | .hidden { 84 | display: none; 85 | } 86 | 87 | [data-efdrc-ctrl] .hidden, 88 | [data-efdrc-editing] .hidden { 89 | display: block; 90 | } 91 | ``` 92 | 93 | This works because the add-on adds `data-efdrc-ctrl` attribute to card container div while ctrl is pressed, 94 | and `data-efdrc-editing` while you are editing a field. 95 | -------------------------------------------------------------------------------- /src/addon/firstrun.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | from aqt import mw 4 | from aqt.utils import showText 5 | 6 | from .ankiaddonconfig import ConfigManager 7 | 8 | 9 | conf = ConfigManager() 10 | 11 | 12 | class Version: 13 | def __init__(self) -> None: 14 | self.load() 15 | 16 | def load(self) -> None: 17 | self.major = conf["version.major"] 18 | self.minor = conf["version.minor"] 19 | # v6.x has string version 20 | if isinstance(self.major, str): 21 | self.major = int(self.major) 22 | if isinstance(self.minor, str): 23 | self.major = int(self.minor) 24 | 25 | def __eq__(self, other: str) -> bool: # type: ignore 26 | ver = [int(i) for i in other.split(".")] 27 | return self.major == ver[0] and self.minor == ver[1] 28 | 29 | def __gt__(self, other: str) -> bool: 30 | ver = [int(i) for i in other.split(".")] 31 | return self.major > ver[0] or (self.major == ver[0] and self.minor > ver[1]) 32 | 33 | def __lt__(self, other: str) -> bool: 34 | ver = [int(i) for i in other.split(".")] 35 | return self.major < ver[0] or (self.major == ver[0] and self.minor < ver[1]) 36 | 37 | def __ge__(self, other: str) -> bool: 38 | return self == other or self > other 39 | 40 | def __le__(self, other: str) -> bool: 41 | return self == other or self < other 42 | 43 | 44 | version = Version() 45 | 46 | 47 | # Initial installation have config version of -1.-1 48 | # Versions before 6.0 will have config version of 0.0 49 | # However if the user hasn't edited their config, it will show up as -1.-1 50 | 51 | 52 | def distinguish_initial_install() -> None: 53 | if not version == "-1.-1": 54 | return 55 | if conf.get("undo", None): 56 | conf["version.major"] = 0 57 | conf["version.minor"] = 0 58 | conf.save() 59 | version.load() 60 | 61 | 62 | distinguish_initial_install() 63 | 64 | 65 | # Make config compatible when upgrading from older version 66 | 67 | 68 | def change_resize_image_preserve_ratio() -> None: 69 | resize_conf = conf["resize_image_preserve_ratio"] 70 | if not isinstance(resize_conf, bool): 71 | return 72 | 73 | if resize_conf: 74 | conf["resize_image_preserve_ratio"] = 1 75 | else: 76 | conf["resize_image_preserve_ratio"] = 0 77 | conf.save() 78 | 79 | 80 | change_resize_image_preserve_ratio() 81 | 82 | 83 | def change_special_formatting() -> None: 84 | if not "z_special_formatting" in conf: 85 | return 86 | for key in conf["z_special_formatting"]: 87 | opts = conf["z_special_formatting"][key] 88 | if isinstance(opts, list): 89 | enabled = opts[0] 90 | arg = opts[1] 91 | else: 92 | enabled = opts 93 | arg = None 94 | conf[f"special_formatting.{key}.enabled"] = enabled 95 | if arg is not None: 96 | conf[f"special_formatting.{key}.arg"] = { 97 | "type": "color" if key in ["fontcolor", "highlight"] else "text", 98 | "value": arg, 99 | } 100 | 101 | del conf["z_special_formatting"] 102 | conf.save() 103 | 104 | 105 | change_special_formatting() 106 | 107 | 108 | def remove_undo() -> None: 109 | if not "undo" in conf: 110 | return 111 | del conf["undo"] 112 | conf.save() 113 | 114 | 115 | remove_undo() 116 | 117 | 118 | def initial_tutorial() -> None: 119 | tutorial = "
".join( 120 | [ 121 | "

Edit Field During Review (Cloze)", 122 | "How to Use

" 123 | "

Initial Setup

" 124 | "1. Open the add-on config and go to the Fields tab.", 125 | "2. For each note type, check the fields you want editable.", 126 | "3. Remember to do this whenever you add or modify a note type!", 127 | "4. And it's done! Now you can Ctrl + Click on the field content to edit it.", 128 | ] 129 | ) 130 | showText(tutorial, type="html", title="Add-on Tutorial") 131 | 132 | 133 | if version == "-1.-1": 134 | initial_tutorial() 135 | 136 | # Save current version 137 | version_string = os.environ.get("EFDRC_VERSION") 138 | if not version_string: 139 | addon_dir = mw.addonManager.addonFromModule(__name__) 140 | meta = mw.addonManager.addonMeta(addon_dir) 141 | version_string = meta["human_version"] 142 | 143 | conf["version.major"] = int(version_string.split(".")[0]) 144 | conf["version.minor"] = int(version_string.split(".")[1]) 145 | conf.save() 146 | -------------------------------------------------------------------------------- /src/addon/web/resize.js: -------------------------------------------------------------------------------- 1 | /* global $, EFDRC */ 2 | 3 | (function () { 4 | EFDRC.priorImgs = [] 5 | 6 | const savePriorImg = function (img) { 7 | const id = EFDRC.priorImgs.length 8 | EFDRC.priorImgs.push(img.cloneNode()) 9 | img.setAttribute('data-EFDRCImgId', id) 10 | } 11 | 12 | const restorePriorImg = function (img) { 13 | /* 14 | only save changes to width and height 15 | resizable img is guranteed to have the data-EFDRCImgId attribute. 16 | if img was added during review, resizable isn't applied to it. 17 | */ 18 | const width = img.style.width 19 | const height = img.style.height 20 | 21 | // apply stored style 22 | const id = img.getAttribute('data-EFDRCImgId') 23 | const priorImg = EFDRC.priorImgs[id] 24 | priorImg.style.width = width 25 | priorImg.style.height = height 26 | 27 | img.parentNode.replaceChild(priorImg, img) 28 | } 29 | 30 | const ratioShouldBePreserved = function (event) { 31 | if (EFDRC.CONF.resize_image_preserve_ratio === 1 && event.originalEvent.target.classList.contains('ui-resizable-se')) { 32 | return true 33 | } else if (EFDRC.CONF.resize_image_preserve_ratio === 2) { 34 | return true 35 | } else { 36 | return false 37 | } 38 | } 39 | 40 | const maybeRemoveHeight = function (img, $img, ui) { 41 | if (!img.naturalHeight) { return } 42 | const originalRatio = img.naturalWidth / img.naturalHeight 43 | const currentRatio = $img.width() / $img.height() 44 | if (Math.abs(originalRatio - currentRatio) < 0.01 || EFDRC.CONF.resize_image_preserve_ratio === 2) { 45 | $img.css('height', '') 46 | if (ui) { 47 | ui.element.css('height', $img.height()) 48 | } 49 | } 50 | } 51 | 52 | const onDblClick = function () { 53 | const img = this 54 | const $img = $(img) 55 | $img.css('width', '') 56 | $img.css('height', '') 57 | const $parents = $img.parents('div[class^=ui-]') 58 | $parents.css('width', '') 59 | $parents.css('height', '') 60 | } 61 | 62 | EFDRC.resizeImage = async function (idx, img) { 63 | while (!img.complete) { 64 | // wait for image to load 65 | await new Promise(resolve => setTimeout(resolve, 20)) 66 | } 67 | 68 | savePriorImg(img) 69 | 70 | const $img = $(img) 71 | if ($img.resizable('instance') === undefined) { // just in case? 72 | const aspRatio = (EFDRC.CONF.resize_image_preserve_ratio === 2) 73 | const computedStyle = window.getComputedStyle(img) 74 | 75 | $img.resizable({ 76 | start: function (event, ui) { 77 | if (ratioShouldBePreserved(event)) { 78 | // preserve ratio when using corner point to resize 79 | $img.resizable('option', 'aspectRatio', true).data('ui-resizable')._aspectRatio = true 80 | } 81 | }, 82 | stop: function (event, ui) { 83 | $img.resizable('option', 'aspectRatio', false).data('ui-resizable')._aspectRatio = false 84 | maybeRemoveHeight(img, $img, ui) // this might not be working 85 | }, 86 | resize: function (event, ui) { 87 | if (ratioShouldBePreserved(event)) { 88 | maybeRemoveHeight(img, $img, ui) 89 | } 90 | }, 91 | classes: { 92 | // remove unneeded classes 93 | 'ui-resizable-se': '' 94 | }, 95 | minHeight: 15, 96 | minWidth: 15, 97 | aspectRatio: aspRatio 98 | }) 99 | 100 | // passing maxWidth to resizable doesn't work because 101 | // it only takes in pixel values 102 | const ui = $img.resizable('instance') 103 | ui.element.css('max-width', computedStyle.maxWidth) 104 | ui.element.css('max-height', computedStyle.maxHeight) 105 | $img.css('max-width', '100%') 106 | $img.css('max-height', '100%') 107 | if (parseFloat(computedStyle.minWidth)) { // not 0 108 | ui.element.css('min-width', computedStyle.minWidth) 109 | } 110 | if (parseFloat(computedStyle.minHeight)) { 111 | ui.element.css('min-height', computedStyle.minHeight) 112 | } 113 | 114 | $img.dblclick(onDblClick) 115 | const $divUi = $img.parents('div[class=ui-wrapper]') 116 | $divUi.attr('contentEditable', 'false') 117 | $divUi.css('display', 'inline-block') 118 | } 119 | } 120 | 121 | EFDRC.cleanResize = function (field) { 122 | const resizables = field.querySelectorAll('.ui-resizable') 123 | for (let x = 0; x < resizables.length; x++) { 124 | $(resizables[x]).resizable('destroy') 125 | } 126 | const imgs = field.querySelectorAll('[data-EFDRCImgId]') 127 | for (const img of imgs) { 128 | maybeRemoveHeight(img, $(img)) 129 | restorePriorImg(img) 130 | } 131 | EFDRC.priorImgs = [] 132 | } 133 | 134 | EFDRC.maybeResizeOrClean = function (focus) { 135 | if (focus) { 136 | // Called from __init__.py on field focus. Else undefined. 137 | EFDRC.resizeImageMode = EFDRC.CONF.resize_image_default_state 138 | } 139 | if (EFDRC.resizeImageMode) { 140 | $(document.activeElement).find('img').each(EFDRC.resizeImage) 141 | } else { 142 | EFDRC.cleanResize(document.activeElement) 143 | } 144 | } 145 | })() 146 | -------------------------------------------------------------------------------- /src/addon/reviewer.py: -------------------------------------------------------------------------------- 1 | import base64 2 | import json 3 | from typing import Any, Optional, Tuple, Union 4 | 5 | import anki 6 | from anki.template import TemplateRenderContext 7 | from anki.notes import Note 8 | from anki.cards import Card 9 | from anki.collection import OpChanges 10 | import aqt 11 | from aqt import mw, gui_hooks 12 | from aqt.editor import Editor 13 | from aqt.qt import QClipboard 14 | from aqt.reviewer import Reviewer, ReviewerBottomBar 15 | from aqt.browser.previewer import MultiCardPreviewer 16 | from aqt.utils import showText, tooltip 17 | from aqt.operations.note import update_note 18 | 19 | from .semieditor import SemiEditorWebView 20 | from .ankiaddonconfig import ConfigManager 21 | 22 | ERROR_MSG = "ERROR - Edit Field During Review Cloze\n{}" 23 | 24 | editorwv = SemiEditorWebView() 25 | 26 | 27 | class FldNotFoundError(Exception): 28 | def __init__(self, fld: str): 29 | self.fld = fld 30 | 31 | def __str__(self) -> str: 32 | return f"Field {self.fld} not found in note. Please check your note type." 33 | 34 | 35 | conf = ConfigManager() 36 | 37 | 38 | def myRevHtml() -> str: 39 | conf.load() # update config when reviewer is launched 40 | 41 | # config should not have any single quote values 42 | js = "EFDRC.registerConfig('{}');".format(conf.to_json()) 43 | js += "EFDRC.setupReviewer()" 44 | return f"" 45 | 46 | 47 | def edit_filter(txt: str, field: str, filt: str, ctx: TemplateRenderContext) -> str: 48 | if not filt == "edit": 49 | return txt 50 | # Encode field to escape special characters. 51 | class_name = "" 52 | if conf["outline"]: 53 | class_name += "EFDRC-outline " 54 | if conf["ctrl_click"]: 55 | class_name += "EFDRC-ctrl " 56 | field = base64.b64encode(field.encode("utf-8")).decode("ascii") 57 | txt = """<%s data-EFDRCfield="%s" class="%s">%s""" % ( 58 | conf["tag"], 59 | field, 60 | class_name, 61 | txt, 62 | conf["tag"], 63 | ) 64 | return txt 65 | 66 | 67 | def serve_card(txt: str, card: Card, kind: str) -> str: 68 | return txt + "" 69 | 70 | 71 | def save_field_and_reload( 72 | note: Note, 73 | fld: str, 74 | val: str, 75 | context: Union[Reviewer, MultiCardPreviewer] 76 | ) -> None: 77 | if fld == "Tags": 78 | # aqt.editor.Editor.saveTags 79 | tags = mw.col.tags.split(val) 80 | if note.tags == tags: 81 | return 82 | note.tags = tags 83 | elif fld not in note: 84 | raise FldNotFoundError(fld) 85 | else: 86 | # aqt.editor.Editor.onBridgeCmd 87 | txt = Editor.mungeHTML(editorwv.editor, val) 88 | if note[fld] == txt: 89 | return 90 | note[fld] = txt 91 | # 2.1.45+ 92 | 93 | def on_success(changes: OpChanges) -> None: 94 | reload_review_context(context) 95 | 96 | def on_failure(exc: Exception) -> None: 97 | reload_review_context(context) 98 | raise exc 99 | 100 | update_note( 101 | parent=mw, note=note 102 | ).success(on_success).failure(on_failure).run_in_background() 103 | 104 | 105 | def get_value(note: Note, fld: str) -> str: 106 | if fld == "Tags": 107 | try: 108 | string_tags = note.string_tags() 109 | except: 110 | string_tags = note.stringTags() # type:ignore 111 | return string_tags.strip(" ") 112 | if fld in note: 113 | return note[fld] 114 | raise FldNotFoundError(fld) 115 | 116 | def autoplay_false() -> bool: 117 | return False 118 | 119 | def reload_reviewer(reviewer: Reviewer) -> None: 120 | cid = reviewer.card.id 121 | try: 122 | timer_started = reviewer.card.timer_started 123 | timer_started_snake_case = True 124 | except: 125 | timer_started = reviewer.card.timerStarted # type: ignore 126 | timer_started_snake_case = False 127 | reviewer.card = mw.col.getCard(cid) # type: ignore 128 | if timer_started_snake_case: 129 | reviewer.card.timer_started = timer_started 130 | else: 131 | reviewer.card.timerStarted = timer_started # type: ignore 132 | 133 | original_autoplay = reviewer.card.autoplay 134 | will_disable_autoplay = conf.get("disable_autoplay_after_edit", False) 135 | if will_disable_autoplay: 136 | reviewer.card.autoplay = autoplay_false # type: ignore 137 | 138 | try: 139 | if reviewer.state == "question": 140 | reviewer._showQuestion() 141 | elif reviewer.state == "answer": 142 | reviewer._showAnswer() 143 | finally: 144 | if will_disable_autoplay: 145 | reviewer.card.autoplay = original_autoplay # type: ignore 146 | 147 | def reload_previewer(previewer: MultiCardPreviewer) -> None: 148 | # previewer may skip rendering if modified note's mtime has not changed 149 | previewer._last_state = None 150 | previewer.render_card() 151 | 152 | def reload_review_context(context: Union[Reviewer, MultiCardPreviewer]) -> None: 153 | if isinstance(context, Reviewer): 154 | reload_reviewer(context) 155 | else: 156 | reload_previewer(context) 157 | 158 | def handle_pycmd_message( 159 | handled: Tuple[bool, Any], message: str, context: Any 160 | ) -> Tuple[bool, Any]: 161 | if isinstance(context, Reviewer): 162 | card = context.card 163 | web: "aqt.webview.AnkiWebView" = context.web 164 | reviewer = context 165 | previewer = None 166 | elif isinstance(context, MultiCardPreviewer): 167 | if context._web is None: 168 | return handled 169 | card = context.card() 170 | web = context._web 171 | reviewer = None 172 | previewer = context 173 | else: 174 | return handled 175 | 176 | if message.startswith("EFDRC#"): 177 | errmsg = "Something unexpected occured. The edit may not have been saved." 178 | nidstr, fld, new_val = message.replace("EFDRC#", "").split("#", 2) 179 | nid = int(nidstr) 180 | note = card.note() 181 | if note.id != nid: 182 | # nid may be note id of previous reviewed card 183 | tooltip(ERROR_MSG.format(errmsg)) 184 | return (True, None) 185 | fld = base64.b64decode(fld, validate=True).decode("utf-8") 186 | try: 187 | save_field_and_reload(note, fld, new_val, context) 188 | return (True, None) 189 | except FldNotFoundError as e: 190 | tooltip(ERROR_MSG.format(str(e))) 191 | return (True, None) 192 | 193 | # Replace reviewer field html if it is different from real field value. 194 | # For example, clozes, mathjax, audio. 195 | elif message.startswith("EFDRC!focuson#"): 196 | fld = message.replace("EFDRC!focuson#", "") 197 | decoded_fld = base64.b64decode(fld, validate=True).decode("utf-8") 198 | note = card.note() 199 | try: 200 | val = get_value(note, decoded_fld) 201 | except FldNotFoundError as e: 202 | tooltip(ERROR_MSG.format(str(e))) 203 | return (True, None) 204 | encoded_val = base64.b64encode(val.encode("utf-8")).decode("ascii") 205 | web.eval(f"EFDRC.showRawField('{encoded_val}', '{note.id}', '{fld}')") 206 | 207 | # Reset timer from Speed Focus Mode add-on. 208 | if reviewer is not None: 209 | reviewer.bottom.web.eval("window.EFDRCResetTimer()") 210 | return (True, None) 211 | 212 | elif message == "EFDRC!reload": 213 | reload_review_context(context) 214 | return (True, None) 215 | # Catch ctrl key presses from bottom.web. 216 | elif message == "EFDRC!ctrldown": 217 | web.eval("EFDRC.ctrldown()") 218 | return (True, None) 219 | elif message == "EFDRC!ctrlup": 220 | web.eval("EFDRC.ctrlup()") 221 | return (True, None) 222 | 223 | elif message == "EFDRC!paste": 224 | # From aqt.editor.Editor._onPaste, doPaste. 225 | mime = mw.app.clipboard().mimeData(mode=QClipboard.Mode.Clipboard) 226 | html, internal = editorwv._processMime(mime) 227 | print(internal) 228 | html = editorwv.editor._pastePreFilter(html, internal) 229 | print(html) 230 | web.eval( 231 | "EFDRC.pasteHTML(%s, %s);" % (json.dumps(html), json.dumps(internal)) 232 | ) 233 | return (True, None) 234 | 235 | elif message.startswith("EFDRC!debug#"): 236 | fld = message.replace("EFDRC!debug#", "") 237 | showText(fld) 238 | return (True, None) 239 | return handled 240 | 241 | 242 | def url_from_fname(file_name: str) -> str: 243 | addon_package = mw.addonManager.addonFromModule(__name__) 244 | return f"/_addons/{addon_package}/web/{file_name}" 245 | 246 | 247 | def on_webview(web_content: aqt.webview.WebContent, context: Optional[Any]) -> None: 248 | if isinstance(context, Reviewer) or isinstance(context, MultiCardPreviewer): 249 | web_content.body += myRevHtml() 250 | web_content.body += f'' 251 | js_contents = ["global_card.js", "resize.js"] 252 | for file_name in js_contents: 253 | web_content.js.append(url_from_fname(file_name)) 254 | jquery_ui = "js/vendor/jquery-ui.min.js" 255 | if jquery_ui not in web_content.js: 256 | web_content.js.append(jquery_ui) 257 | web_content.css.append(url_from_fname("global_card.css")) 258 | 259 | elif isinstance(context, ReviewerBottomBar): 260 | web_content.js.append(url_from_fname("bottom.js")) 261 | 262 | 263 | mw.addonManager.setWebExports(__name__, r"web/.*") 264 | gui_hooks.webview_will_set_content.append(on_webview) 265 | gui_hooks.webview_did_receive_js_message.append(handle_pycmd_message) 266 | gui_hooks.card_will_show.append(serve_card) 267 | anki.hooks.field_filter.append(edit_filter) 268 | -------------------------------------------------------------------------------- /src/addon/web/editor/editor.js: -------------------------------------------------------------------------------- 1 | (function (exports) { 2 | 'use strict'; 3 | 4 | // Copyright: Ankitects Pty Ltd and contributors 5 | // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html 6 | function isHTMLElement(elem) { 7 | return elem instanceof HTMLElement; 8 | } 9 | function isNightMode() { 10 | return document.body.classList.contains("nightMode"); 11 | } 12 | 13 | // Copyright: Ankitects Pty Ltd and contributors 14 | // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html 15 | function removeNode(element) { 16 | var _a; 17 | (_a = element.parentNode) === null || _a === void 0 ? void 0 : _a.removeChild(element); 18 | } 19 | function iterateElement(filter, fragment) { 20 | for (const child of [...fragment.childNodes]) { 21 | filter(child); 22 | } 23 | } 24 | const filterNode = (elementFilter) => (node) => { 25 | switch (node.nodeType) { 26 | case Node.COMMENT_NODE: 27 | removeNode(node); 28 | break; 29 | case Node.DOCUMENT_FRAGMENT_NODE: 30 | iterateElement(filterNode(elementFilter), node); 31 | break; 32 | case Node.ELEMENT_NODE: 33 | iterateElement(filterNode(elementFilter), node); 34 | elementFilter(node); 35 | break; 36 | // do nothing 37 | } 38 | }; 39 | 40 | // Copyright: Ankitects Pty Ltd and contributors 41 | // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html 42 | const stylingNightMode = { 43 | "font-weight": [], 44 | "font-style": [], 45 | "text-decoration-line": [], 46 | }; 47 | const stylingLightMode = { 48 | color: [], 49 | "background-color": ["transparent"], 50 | ...stylingNightMode, 51 | }; 52 | const stylingInternal = [ 53 | "background-color", 54 | "font-size", 55 | "font-family", 56 | "width", 57 | "height", 58 | "max-width", 59 | "max-height", 60 | ]; 61 | const allowPropertiesBlockValues = (allowBlock) => (property, value) => Object.prototype.hasOwnProperty.call(allowBlock, property) && 62 | !allowBlock[property].includes(value); 63 | const blockProperties = (block) => (property) => !block.includes(property); 64 | const filterStyling = (predicate) => (element) => { 65 | for (const property of [...element.style]) { 66 | const value = element.style.getPropertyValue(property); 67 | if (!predicate(property, value)) { 68 | element.style.removeProperty(property); 69 | } 70 | } 71 | }; 72 | const filterStylingNightMode = filterStyling(allowPropertiesBlockValues(stylingNightMode)); 73 | const filterStylingLightMode = filterStyling(allowPropertiesBlockValues(stylingLightMode)); 74 | const filterStylingInternal = filterStyling(blockProperties(stylingInternal)); 75 | 76 | // Copyright: Ankitects Pty Ltd and contributors 77 | function filterAttributes(attributePredicate, element) { 78 | for (const attr of [...element.attributes]) { 79 | const attrName = attr.name.toUpperCase(); 80 | if (!attributePredicate(attrName)) { 81 | element.removeAttributeNode(attr); 82 | } 83 | } 84 | } 85 | function allowNone(element) { 86 | filterAttributes(() => false, element); 87 | } 88 | const allow = (attrs) => (element) => filterAttributes((attributeName) => attrs.includes(attributeName), element); 89 | function unwrapElement(element) { 90 | element.replaceWith(...element.childNodes); 91 | } 92 | function filterSpan(element) { 93 | const filterAttrs = allow(["STYLE"]); 94 | filterAttrs(element); 95 | const filterStyle = isNightMode() ? filterStylingNightMode : filterStylingLightMode; 96 | filterStyle(element); 97 | } 98 | const tagsAllowedBasic = { 99 | BR: allowNone, 100 | IMG: allow(["SRC", "ALT"]), 101 | DIV: allowNone, 102 | P: allowNone, 103 | SUB: allowNone, 104 | SUP: allowNone, 105 | TITLE: removeNode, 106 | }; 107 | const tagsAllowedExtended = { 108 | ...tagsAllowedBasic, 109 | A: allow(["HREF"]), 110 | B: allowNone, 111 | BLOCKQUOTE: allowNone, 112 | CODE: allowNone, 113 | DD: allowNone, 114 | DL: allowNone, 115 | DT: allowNone, 116 | EM: allowNone, 117 | FONT: allow(["COLOR"]), 118 | H1: allowNone, 119 | H2: allowNone, 120 | H3: allowNone, 121 | I: allowNone, 122 | LI: allowNone, 123 | OL: allowNone, 124 | PRE: allowNone, 125 | RP: allowNone, 126 | RT: allowNone, 127 | RUBY: allowNone, 128 | SPAN: filterSpan, 129 | STRONG: allowNone, 130 | TABLE: allowNone, 131 | TD: allow(["COLSPAN", "ROWSPAN"]), 132 | TH: allow(["COLSPAN", "ROWSPAN"]), 133 | TR: allow(["ROWSPAN"]), 134 | U: allowNone, 135 | UL: allowNone, 136 | }; 137 | const filterElementTagsAllowed = (tagsAllowed) => (element) => { 138 | const tagName = element.tagName; 139 | if (Object.prototype.hasOwnProperty.call(tagsAllowed, tagName)) { 140 | tagsAllowed[tagName](element); 141 | } 142 | else if (element.innerHTML) { 143 | unwrapElement(element); 144 | } 145 | else { 146 | removeNode(element); 147 | } 148 | }; 149 | const filterElementBasic = filterElementTagsAllowed(tagsAllowedBasic); 150 | const filterElementExtended = filterElementTagsAllowed(tagsAllowedExtended); 151 | function filterElementInternal(element) { 152 | if (isHTMLElement(element)) { 153 | filterStylingInternal(element); 154 | } 155 | } 156 | 157 | // Copyright: Ankitects Pty Ltd and contributors 158 | var FilterMode; 159 | (function (FilterMode) { 160 | FilterMode[FilterMode["Basic"] = 0] = "Basic"; 161 | FilterMode[FilterMode["Extended"] = 1] = "Extended"; 162 | FilterMode[FilterMode["Internal"] = 2] = "Internal"; 163 | })(FilterMode || (FilterMode = {})); 164 | const filters = { 165 | [FilterMode.Basic]: filterElementBasic, 166 | [FilterMode.Extended]: filterElementExtended, 167 | [FilterMode.Internal]: filterElementInternal, 168 | }; 169 | const whitespace = /[\n\t ]+/g; 170 | function collapseWhitespace(value) { 171 | return value.replace(whitespace, " "); 172 | } 173 | function trim(value) { 174 | return value.trim(); 175 | } 176 | const outputHTMLProcessors = { 177 | [FilterMode.Basic]: (outputHTML) => trim(collapseWhitespace(outputHTML)), 178 | [FilterMode.Extended]: trim, 179 | [FilterMode.Internal]: trim, 180 | }; 181 | function filterHTML(html, internal, extended) { 182 | const template = document.createElement("template"); 183 | template.innerHTML = html; 184 | const mode = getFilterMode(internal, extended); 185 | const content = template.content; 186 | const filter = filterNode(filters[mode]); 187 | filter(content); 188 | return outputHTMLProcessors[mode](template.innerHTML); 189 | } 190 | function getFilterMode(internal, extended) { 191 | if (internal) { 192 | return FilterMode.Internal; 193 | } 194 | else if (extended) { 195 | return FilterMode.Extended; 196 | } 197 | else { 198 | return FilterMode.Basic; 199 | } 200 | } 201 | 202 | // Copyright: Ankitects Pty Ltd and contributors 203 | // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html 204 | /** 205 | * Gecko has no .getSelection on ShadowRoot, only .activeElement 206 | */ 207 | function getSelection(element) { 208 | const root = element.getRootNode(); 209 | if (root.getSelection) { 210 | return root.getSelection(); 211 | } 212 | return document.getSelection(); 213 | } 214 | /** 215 | * Browser has potential support for multiple ranges per selection built in, 216 | * but in reality only Gecko supports it. 217 | * If there are multiple ranges, the latest range is the _main_ one. 218 | */ 219 | function getRange(selection) { 220 | const rangeCount = selection.rangeCount; 221 | return rangeCount === 0 ? null : selection.getRangeAt(rangeCount - 1); 222 | } 223 | 224 | // Copyright: Ankitects Pty Ltd and contributors 225 | function wrappedExceptForWhitespace(text, front, back) { 226 | const match = text.match(/^(\s*)([^]*?)(\s*)$/); 227 | return match[1] + front + match[2] + back + match[3]; 228 | } 229 | function moveCursorInside(selection, postfix) { 230 | const range = getRange(selection); 231 | range.setEnd(range.endContainer, range.endOffset - postfix.length); 232 | range.collapse(false); 233 | selection.removeAllRanges(); 234 | selection.addRange(range); 235 | } 236 | function wrapInternal(base, front, back, plainText) { 237 | const selection = getSelection(base); 238 | const range = getRange(selection); 239 | if (!range) { 240 | return; 241 | } 242 | const wasCollapsed = range.collapsed; 243 | const content = range.cloneContents(); 244 | const span = document.createElement("span"); 245 | span.appendChild(content); 246 | if (plainText) { 247 | const new_ = wrappedExceptForWhitespace(span.innerText, front, back); 248 | document.execCommand("inserttext", false, new_); 249 | } 250 | else { 251 | const new_ = wrappedExceptForWhitespace(span.innerHTML, front, back); 252 | document.execCommand("inserthtml", false, new_); 253 | } 254 | if (wasCollapsed && 255 | /* ugly solution: treat differently than other wraps */ !front.includes(" { 84 | if (isCtrlKey(ev.code)) EFDRC.ctrlup() 85 | ev.stopPropagation() 86 | } 87 | EFDRC.handleKeyPress = (ev, target) => { 88 | ev.stopPropagation() 89 | } 90 | 91 | EFDRC.handleFocus = function (event, target) { 92 | if (typeof window.showTooltip === 'function' && typeof window.showTooltip2 === 'undefined') { 93 | // Disable Popup Dictionary addon tooltip on double mouse click. 94 | // Using hotkey should still work however. 95 | window.showTooltip2 = window.showTooltip 96 | window.showTooltip = function (event, tooltip, element) { 97 | EFDRC.tooltip = { 98 | ev: event, 99 | tt: tooltip, 100 | el: element 101 | } 102 | } 103 | window.showTooltip.hide = function () { } 104 | window.invokeTooltipAtSelectedElm2 = window.invokeTooltipAtSelectedElm 105 | window.invokeTooltipAtSelectedElm = function () { 106 | window.invokeTooltipAtSelectedElm2() 107 | window.showTooltip2(EFDRC.tooltip.ev, EFDRC.tooltip.tt, EFDRC.tooltip.el) 108 | } 109 | } 110 | 111 | const qEl = document.getElementById('qa') 112 | if (qEl !== null) { 113 | qEl.setAttribute('data-efdrc-editing', 'true') 114 | } 115 | 116 | const fld = target.getAttribute('data-EFDRCfield') 117 | window.pycmd('EFDRC!focuson#' + fld) 118 | } 119 | 120 | EFDRC.handleBlur = function (event, target) { 121 | if (typeof showTooltip2 === 'function') { 122 | // Restore Popup Dictionary 123 | window.showTooltip = window.showTooltip2 124 | delete window.showTooltip2 125 | window.invokeTooltipAtSelectedElm = window.invokeTooltipAtSelectedElm2 126 | delete window.invokeTooltipAtSelectedElm2 127 | } 128 | 129 | const qEl = document.getElementById('qa') 130 | if (qEl !== null) { 131 | qEl.removeAttribute('data-efdrc-editing') 132 | } 133 | 134 | const el = target 135 | if (EFDRC.CONF.remove_span) { 136 | removeSpan(el) 137 | } 138 | el.setAttribute('contenteditable', 'false') 139 | if (el.hasAttribute('data-EFDRCnid')) { 140 | EFDRC.cleanResize(el) 141 | window.pycmd('EFDRC#' + el.getAttribute('data-EFDRCnid') + '#' + el.getAttribute('data-EFDRCfield') + '#' + el.innerHTML) 142 | } 143 | window.pycmd('EFDRC!reload') 144 | } 145 | 146 | /* Shortcuts */ 147 | const specialCharCodes = { 148 | '-': 'minus', 149 | '=': 'equal', 150 | '[': 'bracketleft', 151 | ']': 'bracketright', 152 | ';': 'semicolon', 153 | "'": 'quote', 154 | '`': 'backquote', 155 | '\\': 'backslash', 156 | ',': 'comma', 157 | '.': 'period', 158 | '/': 'slash' 159 | } 160 | 161 | const registerShortcut = function (shortcut, handler) { 162 | const shortcutKeys = shortcut.toLowerCase().split(/[+]/).map(key => key.trim()) 163 | const modKeys = ['ctrl', 'shift', 'alt'] 164 | const scutInfo = {} 165 | modKeys.forEach(modKey => { scutInfo[modKey] = shortcutKeys.includes(modKey) }) 166 | let mainKey = shortcutKeys[shortcutKeys.length - 1] 167 | if (mainKey.length === 1) { 168 | if (/\d/.test(mainKey)) { 169 | mainKey = 'digit' + mainKey 170 | } else if (/[a-zA-Z]/.test(mainKey)) { 171 | mainKey = 'key' + mainKey 172 | } else { 173 | const code = specialCharCodes[mainKey] 174 | if (code) { 175 | mainKey = code 176 | } 177 | } 178 | } 179 | scutInfo.key = mainKey 180 | scutInfo.handler = handler 181 | EFDRC.shortcuts.push(scutInfo) 182 | } 183 | // Expose registerShortcut to notetype JS 184 | EFDRC.registerShortcut = registerShortcut 185 | 186 | const matchShortcut = function (event, scutInfo) { 187 | if (scutInfo.key !== event.code.toLowerCase()) return false 188 | if (scutInfo.ctrl !== (event.ctrlKey || event.metaKey)) return false 189 | if (scutInfo.shift !== event.shiftKey) return false 190 | if (scutInfo.alt !== event.altKey) return false 191 | return true 192 | } 193 | 194 | const registerFormattingShortcut = function () { 195 | for (const key in EFDRC.CONF.special_formatting) { 196 | const format = EFDRC.CONF.special_formatting[key] 197 | if (!format.enabled) { 198 | continue 199 | } 200 | const shortcut = format.shortcut 201 | registerShortcut(shortcut, () => { 202 | if (format.arg) { 203 | document.execCommand(format.command, false, format.arg.value) 204 | } else { 205 | document.execCommand(format.command, false) 206 | } 207 | }) // spread args list 208 | } 209 | } 210 | 211 | const isCtrlKey = function (keycode) { 212 | return ['ControlLeft', 'MetaLeft', 'ControlRight', 'MetaRight'].includes(keycode) 213 | } 214 | 215 | window.addEventListener('keydown', function (ev) { 216 | if (isCtrlKey(ev.code)) { 217 | EFDRC.ctrldown() 218 | } 219 | }) 220 | 221 | window.addEventListener('keyup', function (ev) { 222 | if (isCtrlKey(ev.code)) { 223 | EFDRC.ctrlup() 224 | } 225 | }) 226 | 227 | /* Called from reviewer.py */ 228 | EFDRC.registerConfig = function (confStr) { 229 | EFDRC.CONF = JSON.parse(confStr) 230 | EFDRC.CONF.span = (EFDRC.CONF.tag === 'span') 231 | EFDRC.resizeImageMode = EFDRC.CONF.resize_image_default_state 232 | } 233 | 234 | EFDRC.setupReviewer = function () { 235 | // image resizer 236 | registerShortcut(EFDRC.CONF.shortcuts['image-resize'], (event) => { 237 | EFDRC.resizeImageMode = !EFDRC.resizeImageMode 238 | EFDRC.maybeResizeOrClean() 239 | }) 240 | registerShortcut(EFDRC.CONF.shortcuts.cloze, (event, el) => { 241 | wrapCloze(event, el, false) 242 | }) 243 | registerShortcut(EFDRC.CONF.shortcuts['cloze-alt'], (event, el) => { 244 | wrapCloze(event, el, true) 245 | }) 246 | registerShortcut('Backspace', (event, el) => { 247 | if (EFDRC.CONF.span) return 248 | if (EFDRC.CONF.remove_span) setTimeout(() => removeSpan(el), 0) 249 | return -1 250 | }) 251 | registerShortcut('Delete', (event, el) => { 252 | if (EFDRC.CONF.remove_span) setTimeout(() => removeSpan(el), 0) 253 | return -1 254 | }) 255 | registerShortcut('Escape', (event, el) => { 256 | el.blur() 257 | }) 258 | registerFormattingShortcut() 259 | } 260 | 261 | const handlers = [ 262 | ['onpaste', 'handlePaste'], 263 | ['onfocus', 'handleFocus'], 264 | ['onblur', 'handleBlur'], 265 | ['onkeydown', 'handleKeydown'], 266 | ['onkeyup', 'handleKeyUp'], 267 | ['onkeypress', 'handleKeyPress'] 268 | ] 269 | 270 | EFDRC.serveCard = function () { // fld: string 271 | const els = document.querySelectorAll('[data-EFDRCfield]') 272 | for (const el of els) { 273 | if (EFDRC.CONF.ctrl_click) { 274 | const fldName = b64DecodeUnicode(el.getAttribute('data-EFDRCfield')) 275 | el.setAttribute('data-placeholder', fldName) 276 | } else { 277 | el.setAttribute('contenteditable', 'true') 278 | } 279 | for (const handlerInfo of handlers) { 280 | el.setAttribute(handlerInfo[0], `EFDRC.${handlerInfo[1]}(event, this)`) 281 | } 282 | } 283 | } 284 | 285 | EFDRC.ctrldown = function () { 286 | if (EFDRC.CONF.ctrl_click) { 287 | // Set 'data-EFDRC-ctrl' attribute on '#q' element 288 | // which is reset when card or side changes. 289 | // It can be used for styling in note type templates 290 | const qEl = document.getElementById('qa') 291 | if (qEl !== null) { 292 | qEl.setAttribute('data-efdrc-ctrl', 'true') 293 | } 294 | 295 | const els = document.querySelectorAll('[data-EFDRCfield]') 296 | for (const el of els) { 297 | el.setAttribute('contenteditable', 'true') 298 | } 299 | } else { 300 | ctrlLinkEnable() // Ctrl + Click on a link to click a link 301 | } 302 | } 303 | 304 | EFDRC.ctrlup = function () { 305 | if (EFDRC.CONF.ctrl_click) { 306 | const qEl = document.getElementById('qa') 307 | if (qEl !== null) { 308 | qEl.removeAttribute('data-efdrc-ctrl') 309 | } 310 | 311 | const els = document.querySelectorAll('[data-EFDRCfield]') 312 | for (const el of els) { 313 | if (el !== document.activeElement) { 314 | el.setAttribute('contenteditable', 'false') 315 | } 316 | } 317 | } else { 318 | ctrlLinkDisable() 319 | } 320 | } 321 | 322 | EFDRC.showRawField = function (encoded, nid, fld) { 323 | const val = b64DecodeUnicode(encoded) 324 | const elems = document.querySelectorAll(`[data-EFDRCfield='${fld}']`) 325 | for (let e = 0; e < elems.length; e++) { 326 | const elem = elems[e] 327 | if (elem.innerHTML !== val) { 328 | elem.innerHTML = val 329 | } 330 | elem.setAttribute('data-EFDRCnid', nid) 331 | } 332 | EFDRC.maybeResizeOrClean(true) 333 | } 334 | })() 335 | -------------------------------------------------------------------------------- /src/addon/configwindow.py: -------------------------------------------------------------------------------- 1 | import re 2 | from enum import Enum 3 | from typing import List, TypedDict, Set, TYPE_CHECKING 4 | 5 | from anki.models import NoteType 6 | from aqt import mw 7 | from aqt.qt import * 8 | 9 | from .ankiaddonconfig import ConfigManager, ConfigWindow 10 | 11 | conf = ConfigManager() 12 | 13 | 14 | def general_tab(conf_window: ConfigWindow) -> None: 15 | tab = conf_window.add_tab("General") 16 | tab.checkbox( 17 | "ctrl_click", 18 | "Ctrl + Click to edit field (Cmd on mac)", 19 | tooltip="If not checked, there is no need to press Ctrl", 20 | ) 21 | tab.checkbox("outline", "Show a blue outline around the field when editing") 22 | tab.checkbox("process_paste", "Process pasted content for images and HTML") 23 | tab.checkbox("disable_autoplay_after_edit", "Disable Autoplay after edit") 24 | tag_options = ["div", "span"] 25 | tab.dropdown( 26 | "tag", 27 | tag_options, 28 | tag_options, 29 | "HTML tag to use for editable field:", 30 | tooltip="div is recommended", 31 | ) 32 | tab.text_input( 33 | "shortcuts.cloze-alt", 34 | "Shortcut for same number cloze:", 35 | tooltip="Default is Ctrl+Shift+Alt+C", 36 | ) 37 | 38 | tab.space(20) 39 | tab.text("Image Resizing", bold=True) 40 | tab.checkbox( 41 | "resize_image_default_state", 42 | "Use image resizing", 43 | tooltip="Even when unchecked, you can toggle the 'image resize mode' with below shortcut", 44 | ) 45 | option_labels = [ 46 | "Don't preserve ratio", 47 | "Preserve ratio when using corner", 48 | "Always preserve ratio", 49 | ] 50 | option_values = [0, 1, 2] 51 | tab.dropdown( 52 | "resize_image_preserve_ratio", 53 | option_labels, 54 | option_values, 55 | "Image resizing mode:", 56 | ) 57 | tab.text_input( 58 | "shortcuts.image-resize", 59 | "Shortcut for image resize mode:", 60 | tooltip="Pressing this shortcut toggles the image resize mode", 61 | ) 62 | tab.stretch() 63 | 64 | 65 | def formatting_tab(conf_window: ConfigWindow) -> None: 66 | conf = conf_window.conf 67 | tab = conf_window.add_tab("Formatting") 68 | tab.setContentsMargins(25, 25, 25, 25) 69 | scroll_layout = tab.scroll_layout(horizontal=False) 70 | for formatting in conf["special_formatting"]: 71 | hlayout = scroll_layout.hlayout() 72 | item_key = f"special_formatting.{formatting}" 73 | hlayout.checkbox(f"{item_key}.enabled") 74 | hlayout.text(formatting).setFixedWidth(120) 75 | hlayout.text_input(f"{item_key}.shortcut").setFixedWidth(160) 76 | if conf[f"{item_key}.arg"] is not None: 77 | if conf[f"{item_key}.arg.type"] == "color": 78 | hlayout.color_input(f"{item_key}.arg.value") 79 | else: 80 | hlayout.text_input(f"{item_key}.arg.value").setFixedWidth(60) 81 | hlayout.stretch() 82 | tab.stretch() 83 | 84 | 85 | class TemplateField(TypedDict): 86 | name: str 87 | edit: bool 88 | 89 | 90 | class Editability(Enum): 91 | NONE = 0 92 | PARTIAL = 1 93 | ALL = 2 94 | 95 | @classmethod 96 | def from_check_state(cls, check_state: Qt.CheckState) -> "Editability": 97 | if check_state == Qt.CheckState.Unchecked: 98 | return cls.NONE 99 | if check_state == Qt.CheckState.Checked: 100 | return cls.ALL 101 | return cls.PARTIAL 102 | 103 | @classmethod 104 | def to_check_state(cls, val: "Editability") -> Qt.CheckState: 105 | if val == cls.NONE: 106 | return Qt.CheckState.Unchecked 107 | if val == cls.ALL: 108 | return Qt.CheckState.Checked 109 | return Qt.CheckState.PartiallyChecked 110 | 111 | 112 | class FieldIsEditable(TypedDict): 113 | name: str 114 | orig_edit: Editability 115 | edit: Editability 116 | 117 | 118 | class NoteTypeFields(TypedDict): 119 | name: str 120 | fields: List[FieldIsEditable] 121 | 122 | 123 | def modify_field_editability( 124 | note_type: "NoteType", field: FieldIsEditable 125 | ) -> "NoteType": 126 | for template in note_type["tmpls"]: 127 | for side in ["qfmt", "afmt"]: 128 | if field["edit"] == Editability.ALL: 129 | template[side] = re.sub( 130 | "{{((?:(?!edit:)[^#/:}]+:)*%s)}}" % re.escape(field["name"]), 131 | r"{{edit:\1}}", 132 | template[side], 133 | ) 134 | elif field["edit"] == Editability.NONE: 135 | template[side] = re.sub( 136 | "{{((?:[^#/:}]+:)*)edit:((?:[^#/:}]+:)*%s)}}" % re.escape(field["name"]), 137 | r"{{\1\2}}", 138 | template[side], 139 | ) 140 | return note_type 141 | 142 | 143 | def parse_fields(template: str) -> List[TemplateField]: 144 | matches = re.findall("{{[^#/}]+?}}", template) # type: ignore 145 | fields = [] 146 | for m in matches: 147 | # strip off mustache 148 | m = re.sub(r"[{}]", "", m) 149 | # strip off modifiers 150 | splitted = m.split(":") 151 | modifiers = splitted[:-1] 152 | field_name = splitted[-1] 153 | has_edit = "edit" in modifiers 154 | field_info = TemplateField(name=field_name, edit=has_edit) 155 | fields.append(field_info) 156 | return fields 157 | 158 | 159 | def get_fields_in_every_notetype(fields_in_note_type: List[NoteTypeFields]) -> None: 160 | for i in fields_in_note_type: 161 | fields_in_note_type.pop() 162 | 163 | models = mw.col.models 164 | note_types = models.all() 165 | for note_type in note_types: 166 | templates = note_type["tmpls"] 167 | editable_field_names: Set[str] = set() 168 | uneditable_field_names: Set[str] = set() 169 | 170 | for template in templates: 171 | for side in ["qfmt", "afmt"]: 172 | for tmpl_field in parse_fields(template[side]): # type: ignore 173 | name = tmpl_field["name"] 174 | if tmpl_field["edit"]: 175 | editable_field_names.update([name]) 176 | else: 177 | uneditable_field_names.update([name]) 178 | 179 | field_names = [fld["name"] for fld in note_type["flds"]] 180 | fields_list = [] 181 | for fldname in field_names: 182 | try: 183 | # if (False, False), skip since the field isn't used in any of the templates. 184 | editable = { 185 | (True, True): Editability.PARTIAL, 186 | (True, False): Editability.ALL, 187 | (False, True): Editability.NONE, 188 | }[(fldname in editable_field_names, fldname in uneditable_field_names)] 189 | 190 | field = FieldIsEditable(name=fldname, edit=editable, orig_edit=editable) 191 | fields_list.append(field) 192 | except: 193 | pass 194 | nt = NoteTypeFields(name=note_type["name"], fields=fields_list) 195 | fields_in_note_type.append(nt) 196 | 197 | 198 | def fields_tab(conf_window: ConfigWindow) -> None: 199 | tab = conf_window.add_tab("Fields") 200 | dropdown = QComboBox() 201 | tab.addWidget(dropdown) 202 | tab.space(10) 203 | tab.text("Check the boxes to make the fields editable while reviewing") 204 | qlist = QListWidget() 205 | qlist.setStyleSheet("QListWidget{border: 1px solid; padding: 6px;}") 206 | tab.addWidget(qlist) 207 | 208 | fields_in_note_type: List[NoteTypeFields] = [] 209 | 210 | def update_label_status(idx: int) -> None: 211 | notetype = fields_in_note_type[idx] 212 | editable = {Editability.NONE: 0, Editability.PARTIAL: 0, Editability.ALL: 0} 213 | for field in notetype["fields"]: 214 | editable[field["edit"]] += 1 215 | if editable[Editability.ALL] + editable[Editability.PARTIAL] == 0: 216 | status = "❌" 217 | elif editable[Editability.NONE] + editable[Editability.PARTIAL] == 0: 218 | status = "✅" 219 | else: 220 | status = "🔶" 221 | old_label = dropdown.itemText(idx) 222 | new_label = old_label[:-1] + status 223 | dropdown.setItemText(idx, new_label) 224 | 225 | def on_check(item: QListWidgetItem) -> None: 226 | nt_idx = dropdown.currentIndex() 227 | fields = fields_in_note_type[nt_idx]["fields"] 228 | field = fields[qlist.row(item)] 229 | field["edit"] = Editability.from_check_state(item.checkState()) 230 | update_label_status(nt_idx) 231 | 232 | def on_double_click(item: QListWidgetItem) -> None: 233 | curr_check = item.checkState() 234 | if curr_check == Qt.CheckState.Checked: 235 | item.setCheckState(Qt.CheckState.Unchecked) 236 | else: # Partially checked or unchecked 237 | item.setCheckState(Qt.CheckState.Checked) 238 | 239 | def switch_template(idx: int) -> None: 240 | if idx == -1: 241 | return 242 | qlist.clear() 243 | fields = fields_in_note_type[idx]["fields"] 244 | for field in fields: 245 | item = QListWidgetItem(field["name"], qlist, QListWidgetItem.ItemType.Type) 246 | qlist.addItem(item) 247 | item.setCheckState(Editability.to_check_state(field["edit"])) 248 | 249 | def on_save() -> None: 250 | for note_type_fields in fields_in_note_type: 251 | modified = False 252 | try: # 2.1.45 253 | note_type = mw.col.models.by_name(note_type_fields["name"]) 254 | except: # 2.1.41-44 255 | note_type = mw.col.models.byName( # type: ignore 256 | note_type_fields["name"] 257 | ) 258 | for field in note_type_fields["fields"]: 259 | if field["edit"] != field["orig_edit"]: 260 | modified = True 261 | note_type = modify_field_editability(note_type, field) 262 | if modified: 263 | mw.col.models.save(note_type) 264 | 265 | qlist.itemChanged.connect(on_check) 266 | qlist.itemDoubleClicked.connect(on_double_click) 267 | dropdown.currentIndexChanged.connect(switch_template) 268 | conf_window.execute_on_save(on_save) 269 | 270 | get_fields_in_every_notetype(fields_in_note_type) 271 | for idx, nt in enumerate(fields_in_note_type): 272 | dropdown.addItem(nt["name"] + " ") 273 | update_label_status(idx) 274 | dropdown.setCurrentIndex(0) # Triggers currentIndexChanged 275 | 276 | def make_every_field_editable() -> None: 277 | for idx, note_type_fields in enumerate(fields_in_note_type): 278 | for field in note_type_fields["fields"]: 279 | field["edit"] = Editability.ALL 280 | update_label_status(idx) 281 | switch_template(dropdown.currentIndex()) 282 | 283 | tab.space(10) 284 | button_layout = tab.hlayout() 285 | button_layout.stretch() 286 | button = QPushButton("Make every field in every note type editable ✅") 287 | button.clicked.connect(make_every_field_editable) 288 | button_layout.addWidget(button) 289 | button_layout.stretch() 290 | tab.space(5) 291 | 292 | 293 | def about_tab(conf_window: ConfigWindow) -> None: 294 | conf = conf_window.conf 295 | tab = conf_window.add_tab("About") 296 | tab.text("Edit Field During Review (Cloze)", bold=True, size=20) 297 | tab.text("© 2019-2021 Yoonchae Lee (Bluegreenmagick)") 298 | tab.text(f"Version {conf['version.major']}.{conf['version.minor']}") 299 | tab.text( 300 | "Found a bug?" 301 | " " 302 | "Report issues here" 303 | ".", 304 | html=True, 305 | ) 306 | tab.space(15) 307 | tab.text("License", bold=True) 308 | tab.text( 309 | "Edit Field During Review (Cloze) is a Free and Open Source Software (FOSS)" 310 | " distributed under the GNU AGPL v3 license." 311 | " It may also contain code that are licensed under a different license." 312 | " Please see the LICENSE file for more information.", 313 | multiline=True, 314 | ) 315 | tab.stretch() 316 | 317 | 318 | def with_window(conf_window: ConfigWindow) -> None: 319 | conf_window.set_footer("Changes will take effect when you start a review session") 320 | 321 | 322 | conf.use_custom_window() 323 | conf.on_window_open(with_window) 324 | conf.add_config_tab(general_tab) 325 | conf.add_config_tab(formatting_tab) 326 | conf.add_config_tab(fields_tab) 327 | conf.add_config_tab(about_tab) 328 | -------------------------------------------------------------------------------- /src/addon/web/editor/editor.js.map: -------------------------------------------------------------------------------- 1 | {"version":3,"file":"editor.js","sources":["../../../ts/html-filter/helpers.ts","../../../ts/html-filter/node.ts","../../../ts/html-filter/styling.ts","../../../ts/html-filter/element.ts","../../../ts/html-filter/index.ts","../../../ts/cross-browser.ts","../../../ts/wrap.ts","../../../ts/index.ts"],"sourcesContent":["// Copyright: Ankitects Pty Ltd and contributors\n// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html\n\nexport function isHTMLElement(elem: Element): elem is HTMLElement {\n return elem instanceof HTMLElement;\n}\n\nexport function isNightMode(): boolean {\n return document.body.classList.contains(\"nightMode\");\n}\n","// Copyright: Ankitects Pty Ltd and contributors\n// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html\n\nexport function removeNode(element: Node): void {\n element.parentNode?.removeChild(element);\n}\n\nfunction iterateElement(\n filter: (node: Node) => void,\n fragment: DocumentFragment | Element,\n): void {\n for (const child of [...fragment.childNodes]) {\n filter(child);\n }\n}\n\nexport const filterNode =\n (elementFilter: (element: Element) => void) =>\n (node: Node): void => {\n switch (node.nodeType) {\n case Node.COMMENT_NODE:\n removeNode(node);\n break;\n\n case Node.DOCUMENT_FRAGMENT_NODE:\n iterateElement(filterNode(elementFilter), node as DocumentFragment);\n break;\n\n case Node.ELEMENT_NODE:\n iterateElement(filterNode(elementFilter), node as Element);\n elementFilter(node as Element);\n break;\n\n default:\n // do nothing\n }\n };\n","// Copyright: Ankitects Pty Ltd and contributors\n// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html\n\ninterface AllowPropertiesBlockValues {\n [property: string]: string[];\n}\n\ntype BlockProperties = string[];\n\ntype StylingPredicate = (property: string, value: string) => boolean;\n\nconst stylingNightMode: AllowPropertiesBlockValues = {\n \"font-weight\": [],\n \"font-style\": [],\n \"text-decoration-line\": [],\n};\n\nconst stylingLightMode: AllowPropertiesBlockValues = {\n color: [],\n \"background-color\": [\"transparent\"],\n ...stylingNightMode,\n};\n\nconst stylingInternal: BlockProperties = [\n \"background-color\",\n \"font-size\",\n \"font-family\",\n \"width\",\n \"height\",\n \"max-width\",\n \"max-height\",\n];\n\nconst allowPropertiesBlockValues =\n (allowBlock: AllowPropertiesBlockValues): StylingPredicate =>\n (property: string, value: string): boolean =>\n Object.prototype.hasOwnProperty.call(allowBlock, property) &&\n !allowBlock[property].includes(value);\n\nconst blockProperties =\n (block: BlockProperties): StylingPredicate =>\n (property: string): boolean =>\n !block.includes(property);\n\nconst filterStyling =\n (predicate: (property: string, value: string) => boolean) =>\n (element: HTMLElement): void => {\n for (const property of [...element.style]) {\n const value = element.style.getPropertyValue(property);\n\n if (!predicate(property, value)) {\n element.style.removeProperty(property);\n }\n }\n };\n\nexport const filterStylingNightMode = filterStyling(\n allowPropertiesBlockValues(stylingNightMode),\n);\nexport const filterStylingLightMode = filterStyling(\n allowPropertiesBlockValues(stylingLightMode),\n);\nexport const filterStylingInternal = filterStyling(blockProperties(stylingInternal));\n","// Copyright: Ankitects Pty Ltd and contributors\n// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html\n\nimport { isHTMLElement, isNightMode } from \"./helpers\";\nimport { removeNode as removeElement } from \"./node\";\nimport {\n filterStylingInternal,\n filterStylingLightMode,\n filterStylingNightMode,\n} from \"./styling\";\n\ninterface TagsAllowed {\n [tagName: string]: FilterMethod;\n}\n\ntype FilterMethod = (element: Element) => void;\n\nfunction filterAttributes(\n attributePredicate: (attributeName: string) => boolean,\n element: Element,\n): void {\n for (const attr of [...element.attributes]) {\n const attrName = attr.name.toUpperCase();\n\n if (!attributePredicate(attrName)) {\n element.removeAttributeNode(attr);\n }\n }\n}\n\nfunction allowNone(element: Element): void {\n filterAttributes(() => false, element);\n}\n\nconst allow =\n (attrs: string[]): FilterMethod =>\n (element: Element): void =>\n filterAttributes(\n (attributeName: string) => attrs.includes(attributeName),\n element,\n );\n\nfunction unwrapElement(element: Element): void {\n element.replaceWith(...element.childNodes);\n}\n\nfunction filterSpan(element: Element): void {\n const filterAttrs = allow([\"STYLE\"]);\n filterAttrs(element);\n\n const filterStyle = isNightMode() ? filterStylingNightMode : filterStylingLightMode;\n filterStyle(element as HTMLSpanElement);\n}\n\nconst tagsAllowedBasic: TagsAllowed = {\n BR: allowNone,\n IMG: allow([\"SRC\", \"ALT\"]),\n DIV: allowNone,\n P: allowNone,\n SUB: allowNone,\n SUP: allowNone,\n TITLE: removeElement,\n};\n\nconst tagsAllowedExtended: TagsAllowed = {\n ...tagsAllowedBasic,\n A: allow([\"HREF\"]),\n B: allowNone,\n BLOCKQUOTE: allowNone,\n CODE: allowNone,\n DD: allowNone,\n DL: allowNone,\n DT: allowNone,\n EM: allowNone,\n FONT: allow([\"COLOR\"]),\n H1: allowNone,\n H2: allowNone,\n H3: allowNone,\n I: allowNone,\n LI: allowNone,\n OL: allowNone,\n PRE: allowNone,\n RP: allowNone,\n RT: allowNone,\n RUBY: allowNone,\n SPAN: filterSpan,\n STRONG: allowNone,\n TABLE: allowNone,\n TD: allow([\"COLSPAN\", \"ROWSPAN\"]),\n TH: allow([\"COLSPAN\", \"ROWSPAN\"]),\n TR: allow([\"ROWSPAN\"]),\n U: allowNone,\n UL: allowNone,\n};\n\nconst filterElementTagsAllowed =\n (tagsAllowed: TagsAllowed) =>\n (element: Element): void => {\n const tagName = element.tagName;\n\n if (Object.prototype.hasOwnProperty.call(tagsAllowed, tagName)) {\n tagsAllowed[tagName](element);\n } else if (element.innerHTML) {\n unwrapElement(element);\n } else {\n removeElement(element);\n }\n };\n\nexport const filterElementBasic = filterElementTagsAllowed(tagsAllowedBasic);\nexport const filterElementExtended = filterElementTagsAllowed(tagsAllowedExtended);\n\nexport function filterElementInternal(element: Element): void {\n if (isHTMLElement(element)) {\n filterStylingInternal(element);\n }\n}\n","// Copyright: Ankitects Pty Ltd and contributors\n// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html\n\nimport {\n filterElementBasic,\n filterElementExtended,\n filterElementInternal,\n} from \"./element\";\nimport { filterNode } from \"./node\";\n\nenum FilterMode {\n Basic,\n Extended,\n Internal,\n}\n\nconst filters: Record void> = {\n [FilterMode.Basic]: filterElementBasic,\n [FilterMode.Extended]: filterElementExtended,\n [FilterMode.Internal]: filterElementInternal,\n};\n\nconst whitespace = /[\\n\\t ]+/g;\n\nfunction collapseWhitespace(value: string): string {\n return value.replace(whitespace, \" \");\n}\n\nfunction trim(value: string): string {\n return value.trim();\n}\n\nconst outputHTMLProcessors: Record string> =\n {\n [FilterMode.Basic]: (outputHTML: string): string =>\n trim(collapseWhitespace(outputHTML)),\n [FilterMode.Extended]: trim,\n [FilterMode.Internal]: trim,\n };\n\nexport function filterHTML(\n html: string,\n internal: boolean,\n extended: boolean\n): string {\n const template = document.createElement(\"template\");\n template.innerHTML = html;\n\n const mode = getFilterMode(internal, extended);\n const content = template.content;\n const filter = filterNode(filters[mode]);\n\n filter(content);\n\n return outputHTMLProcessors[mode](template.innerHTML);\n}\n\nfunction getFilterMode(internal: boolean, extended: boolean): FilterMode {\n if (internal) {\n return FilterMode.Internal;\n } else if (extended) {\n return FilterMode.Extended;\n } else {\n return FilterMode.Basic;\n }\n}\n","// Copyright: Ankitects Pty Ltd and contributors\n// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html\n\n/**\n * Gecko has no .getSelection on ShadowRoot, only .activeElement\n */\nexport function getSelection(element: Node): Selection | null {\n const root = element.getRootNode() as Document;\n\n if (root.getSelection) {\n return root.getSelection();\n }\n\n return document.getSelection();\n}\n\n/**\n * Browser has potential support for multiple ranges per selection built in,\n * but in reality only Gecko supports it.\n * If there are multiple ranges, the latest range is the _main_ one.\n */\nexport function getRange(selection: Selection): Range | null {\n const rangeCount = selection.rangeCount;\n\n return rangeCount === 0 ? null : selection.getRangeAt(rangeCount - 1);\n}\n\n/**\n * Avoid using selection.isCollapsed: it will always return\n * true in shadow root in Gecko\n * (this bug seems to also happens in Blink)\n */\nexport function isSelectionCollapsed(selection: Selection): boolean {\n return getRange(selection)!.collapsed;\n}\n","// Copyright: Ankitects Pty Ltd and contributors\n// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html\n\nimport { getRange, getSelection } from \"./cross-browser\";\n\nfunction wrappedExceptForWhitespace(\n text: string,\n front: string,\n back: string\n): string {\n const match = text.match(/^(\\s*)([^]*?)(\\s*)$/)!;\n return match[1] + front + match[2] + back + match[3];\n}\n\nfunction moveCursorInside(selection: Selection, postfix: string): void {\n const range = getRange(selection)!;\n\n range.setEnd(range.endContainer, range.endOffset - postfix.length);\n range.collapse(false);\n\n selection.removeAllRanges();\n selection.addRange(range);\n}\n\nexport function wrapInternal(\n base: Element,\n front: string,\n back: string,\n plainText: boolean\n): void {\n const selection = getSelection(base)!;\n const range = getRange(selection);\n\n if (!range) {\n return;\n }\n\n const wasCollapsed = range.collapsed;\n const content = range.cloneContents();\n const span = document.createElement(\"span\");\n span.appendChild(content);\n\n if (plainText) {\n const new_ = wrappedExceptForWhitespace(span.innerText, front, back);\n document.execCommand(\"inserttext\", false, new_);\n } else {\n const new_ = wrappedExceptForWhitespace(span.innerHTML, front, back);\n document.execCommand(\"inserthtml\", false, new_);\n }\n\n if (\n wasCollapsed &&\n /* ugly solution: treat differently than other wraps */ !front.includes(\n \" 10 | (c) 2019-2021 Yoonchae Lee 11 | (c) 2020 Arthur Milchior 12 | and other contributors 13 | 14 | 15 | GNU AFFERO GENERAL PUBLIC LICENSE 16 | Version 3, 19 November 2007 17 | 18 | Copyright (C) 2007 Free Software Foundation, Inc. 19 | Everyone is permitted to copy and distribute verbatim copies 20 | of this license document, but changing it is not allowed. 21 | 22 | Preamble 23 | 24 | The GNU Affero General Public License is a free, copyleft license for 25 | software and other kinds of works, specifically designed to ensure 26 | cooperation with the community in the case of network server software. 27 | 28 | The licenses for most software and other practical works are designed 29 | to take away your freedom to share and change the works. By contrast, 30 | our General Public Licenses are intended to guarantee your freedom to 31 | share and change all versions of a program--to make sure it remains free 32 | software for all its users. 33 | 34 | When we speak of free software, we are referring to freedom, not 35 | price. Our General Public Licenses are designed to make sure that you 36 | have the freedom to distribute copies of free software (and charge for 37 | them if you wish), that you receive source code or can get it if you 38 | want it, that you can change the software or use pieces of it in new 39 | free programs, and that you know you can do these things. 40 | 41 | Developers that use our General Public Licenses protect your rights 42 | with two steps: (1) assert copyright on the software, and (2) offer 43 | you this License which gives you legal permission to copy, distribute 44 | and/or modify the software. 45 | 46 | A secondary benefit of defending all users' freedom is that 47 | improvements made in alternate versions of the program, if they 48 | receive widespread use, become available for other developers to 49 | incorporate. Many developers of free software are heartened and 50 | encouraged by the resulting cooperation. However, in the case of 51 | software used on network servers, this result may fail to come about. 52 | The GNU General Public License permits making a modified version and 53 | letting the public access it on a server without ever releasing its 54 | source code to the public. 55 | 56 | The GNU Affero General Public License is designed specifically to 57 | ensure that, in such cases, the modified source code becomes available 58 | to the community. It requires the operator of a network server to 59 | provide the source code of the modified version running there to the 60 | users of that server. Therefore, public use of a modified version, on 61 | a publicly accessible server, gives the public access to the source 62 | code of the modified version. 63 | 64 | An older license, called the Affero General Public License and 65 | published by Affero, was designed to accomplish similar goals. This is 66 | a different license, not a version of the Affero GPL, but Affero has 67 | released a new version of the Affero GPL which permits relicensing under 68 | this license. 69 | 70 | The precise terms and conditions for copying, distribution and 71 | modification follow. 72 | 73 | TERMS AND CONDITIONS 74 | 75 | 0. Definitions. 76 | 77 | "This License" refers to version 3 of the GNU Affero General Public License. 78 | 79 | "Copyright" also means copyright-like laws that apply to other kinds of 80 | works, such as semiconductor masks. 81 | 82 | "The Program" refers to any copyrightable work licensed under this 83 | License. Each licensee is addressed as "you". "Licensees" and 84 | "recipients" may be individuals or organizations. 85 | 86 | To "modify" a work means to copy from or adapt all or part of the work 87 | in a fashion requiring copyright permission, other than the making of an 88 | exact copy. The resulting work is called a "modified version" of the 89 | earlier work or a work "based on" the earlier work. 90 | 91 | A "covered work" means either the unmodified Program or a work based 92 | on the Program. 93 | 94 | To "propagate" a work means to do anything with it that, without 95 | permission, would make you directly or secondarily liable for 96 | infringement under applicable copyright law, except executing it on a 97 | computer or modifying a private copy. Propagation includes copying, 98 | distribution (with or without modification), making available to the 99 | public, and in some countries other activities as well. 100 | 101 | To "convey" a work means any kind of propagation that enables other 102 | parties to make or receive copies. Mere interaction with a user through 103 | a computer network, with no transfer of a copy, is not conveying. 104 | 105 | An interactive user interface displays "Appropriate Legal Notices" 106 | to the extent that it includes a convenient and prominently visible 107 | feature that (1) displays an appropriate copyright notice, and (2) 108 | tells the user that there is no warranty for the work (except to the 109 | extent that warranties are provided), that licensees may convey the 110 | work under this License, and how to view a copy of this License. If 111 | the interface presents a list of user commands or options, such as a 112 | menu, a prominent item in the list meets this criterion. 113 | 114 | 1. Source Code. 115 | 116 | The "source code" for a work means the preferred form of the work 117 | for making modifications to it. "Object code" means any non-source 118 | form of a work. 119 | 120 | A "Standard Interface" means an interface that either is an official 121 | standard defined by a recognized standards body, or, in the case of 122 | interfaces specified for a particular programming language, one that 123 | is widely used among developers working in that language. 124 | 125 | The "System Libraries" of an executable work include anything, other 126 | than the work as a whole, that (a) is included in the normal form of 127 | packaging a Major Component, but which is not part of that Major 128 | Component, and (b) serves only to enable use of the work with that 129 | Major Component, or to implement a Standard Interface for which an 130 | implementation is available to the public in source code form. A 131 | "Major Component", in this context, means a major essential component 132 | (kernel, window system, and so on) of the specific operating system 133 | (if any) on which the executable work runs, or a compiler used to 134 | produce the work, or an object code interpreter used to run it. 135 | 136 | The "Corresponding Source" for a work in object code form means all 137 | the source code needed to generate, install, and (for an executable 138 | work) run the object code and to modify the work, including scripts to 139 | control those activities. However, it does not include the work's 140 | System Libraries, or general-purpose tools or generally available free 141 | programs which are used unmodified in performing those activities but 142 | which are not part of the work. For example, Corresponding Source 143 | includes interface definition files associated with source files for 144 | the work, and the source code for shared libraries and dynamically 145 | linked subprograms that the work is specifically designed to require, 146 | such as by intimate data communication or control flow between those 147 | subprograms and other parts of the work. 148 | 149 | The Corresponding Source need not include anything that users 150 | can regenerate automatically from other parts of the Corresponding 151 | Source. 152 | 153 | The Corresponding Source for a work in source code form is that 154 | same work. 155 | 156 | 2. Basic Permissions. 157 | 158 | All rights granted under this License are granted for the term of 159 | copyright on the Program, and are irrevocable provided the stated 160 | conditions are met. This License explicitly affirms your unlimited 161 | permission to run the unmodified Program. The output from running a 162 | covered work is covered by this License only if the output, given its 163 | content, constitutes a covered work. This License acknowledges your 164 | rights of fair use or other equivalent, as provided by copyright law. 165 | 166 | You may make, run and propagate covered works that you do not 167 | convey, without conditions so long as your license otherwise remains 168 | in force. You may convey covered works to others for the sole purpose 169 | of having them make modifications exclusively for you, or provide you 170 | with facilities for running those works, provided that you comply with 171 | the terms of this License in conveying all material for which you do 172 | not control copyright. Those thus making or running the covered works 173 | for you must do so exclusively on your behalf, under your direction 174 | and control, on terms that prohibit them from making any copies of 175 | your copyrighted material outside their relationship with you. 176 | 177 | Conveying under any other circumstances is permitted solely under 178 | the conditions stated below. Sublicensing is not allowed; section 10 179 | makes it unnecessary. 180 | 181 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 182 | 183 | No covered work shall be deemed part of an effective technological 184 | measure under any applicable law fulfilling obligations under article 185 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 186 | similar laws prohibiting or restricting circumvention of such 187 | measures. 188 | 189 | When you convey a covered work, you waive any legal power to forbid 190 | circumvention of technological measures to the extent such circumvention 191 | is effected by exercising rights under this License with respect to 192 | the covered work, and you disclaim any intention to limit operation or 193 | modification of the work as a means of enforcing, against the work's 194 | users, your or third parties' legal rights to forbid circumvention of 195 | technological measures. 196 | 197 | 4. Conveying Verbatim Copies. 198 | 199 | You may convey verbatim copies of the Program's source code as you 200 | receive it, in any medium, provided that you conspicuously and 201 | appropriately publish on each copy an appropriate copyright notice; 202 | keep intact all notices stating that this License and any 203 | non-permissive terms added in accord with section 7 apply to the code; 204 | keep intact all notices of the absence of any warranty; and give all 205 | recipients a copy of this License along with the Program. 206 | 207 | You may charge any price or no price for each copy that you convey, 208 | and you may offer support or warranty protection for a fee. 209 | 210 | 5. Conveying Modified Source Versions. 211 | 212 | You may convey a work based on the Program, or the modifications to 213 | produce it from the Program, in the form of source code under the 214 | terms of section 4, provided that you also meet all of these conditions: 215 | 216 | a) The work must carry prominent notices stating that you modified 217 | it, and giving a relevant date. 218 | 219 | b) The work must carry prominent notices stating that it is 220 | released under this License and any conditions added under section 221 | 7. This requirement modifies the requirement in section 4 to 222 | "keep intact all notices". 223 | 224 | c) You must license the entire work, as a whole, under this 225 | License to anyone who comes into possession of a copy. This 226 | License will therefore apply, along with any applicable section 7 227 | additional terms, to the whole of the work, and all its parts, 228 | regardless of how they are packaged. This License gives no 229 | permission to license the work in any other way, but it does not 230 | invalidate such permission if you have separately received it. 231 | 232 | d) If the work has interactive user interfaces, each must display 233 | Appropriate Legal Notices; however, if the Program has interactive 234 | interfaces that do not display Appropriate Legal Notices, your 235 | work need not make them do so. 236 | 237 | A compilation of a covered work with other separate and independent 238 | works, which are not by their nature extensions of the covered work, 239 | and which are not combined with it such as to form a larger program, 240 | in or on a volume of a storage or distribution medium, is called an 241 | "aggregate" if the compilation and its resulting copyright are not 242 | used to limit the access or legal rights of the compilation's users 243 | beyond what the individual works permit. Inclusion of a covered work 244 | in an aggregate does not cause this License to apply to the other 245 | parts of the aggregate. 246 | 247 | 6. Conveying Non-Source Forms. 248 | 249 | You may convey a covered work in object code form under the terms 250 | of sections 4 and 5, provided that you also convey the 251 | machine-readable Corresponding Source under the terms of this License, 252 | in one of these ways: 253 | 254 | a) Convey the object code in, or embodied in, a physical product 255 | (including a physical distribution medium), accompanied by the 256 | Corresponding Source fixed on a durable physical medium 257 | customarily used for software interchange. 258 | 259 | b) Convey the object code in, or embodied in, a physical product 260 | (including a physical distribution medium), accompanied by a 261 | written offer, valid for at least three years and valid for as 262 | long as you offer spare parts or customer support for that product 263 | model, to give anyone who possesses the object code either (1) a 264 | copy of the Corresponding Source for all the software in the 265 | product that is covered by this License, on a durable physical 266 | medium customarily used for software interchange, for a price no 267 | more than your reasonable cost of physically performing this 268 | conveying of source, or (2) access to copy the 269 | Corresponding Source from a network server at no charge. 270 | 271 | c) Convey individual copies of the object code with a copy of the 272 | written offer to provide the Corresponding Source. This 273 | alternative is allowed only occasionally and noncommercially, and 274 | only if you received the object code with such an offer, in accord 275 | with subsection 6b. 276 | 277 | d) Convey the object code by offering access from a designated 278 | place (gratis or for a charge), and offer equivalent access to the 279 | Corresponding Source in the same way through the same place at no 280 | further charge. You need not require recipients to copy the 281 | Corresponding Source along with the object code. If the place to 282 | copy the object code is a network server, the Corresponding Source 283 | may be on a different server (operated by you or a third party) 284 | that supports equivalent copying facilities, provided you maintain 285 | clear directions next to the object code saying where to find the 286 | Corresponding Source. Regardless of what server hosts the 287 | Corresponding Source, you remain obligated to ensure that it is 288 | available for as long as needed to satisfy these requirements. 289 | 290 | e) Convey the object code using peer-to-peer transmission, provided 291 | you inform other peers where the object code and Corresponding 292 | Source of the work are being offered to the general public at no 293 | charge under subsection 6d. 294 | 295 | A separable portion of the object code, whose source code is excluded 296 | from the Corresponding Source as a System Library, need not be 297 | included in conveying the object code work. 298 | 299 | A "User Product" is either (1) a "consumer product", which means any 300 | tangible personal property which is normally used for personal, family, 301 | or household purposes, or (2) anything designed or sold for incorporation 302 | into a dwelling. In determining whether a product is a consumer product, 303 | doubtful cases shall be resolved in favor of coverage. For a particular 304 | product received by a particular user, "normally used" refers to a 305 | typical or common use of that class of product, regardless of the status 306 | of the particular user or of the way in which the particular user 307 | actually uses, or expects or is expected to use, the product. A product 308 | is a consumer product regardless of whether the product has substantial 309 | commercial, industrial or non-consumer uses, unless such uses represent 310 | the only significant mode of use of the product. 311 | 312 | "Installation Information" for a User Product means any methods, 313 | procedures, authorization keys, or other information required to install 314 | and execute modified versions of a covered work in that User Product from 315 | a modified version of its Corresponding Source. The information must 316 | suffice to ensure that the continued functioning of the modified object 317 | code is in no case prevented or interfered with solely because 318 | modification has been made. 319 | 320 | If you convey an object code work under this section in, or with, or 321 | specifically for use in, a User Product, and the conveying occurs as 322 | part of a transaction in which the right of possession and use of the 323 | User Product is transferred to the recipient in perpetuity or for a 324 | fixed term (regardless of how the transaction is characterized), the 325 | Corresponding Source conveyed under this section must be accompanied 326 | by the Installation Information. But this requirement does not apply 327 | if neither you nor any third party retains the ability to install 328 | modified object code on the User Product (for example, the work has 329 | been installed in ROM). 330 | 331 | The requirement to provide Installation Information does not include a 332 | requirement to continue to provide support service, warranty, or updates 333 | for a work that has been modified or installed by the recipient, or for 334 | the User Product in which it has been modified or installed. Access to a 335 | network may be denied when the modification itself materially and 336 | adversely affects the operation of the network or violates the rules and 337 | protocols for communication across the network. 338 | 339 | Corresponding Source conveyed, and Installation Information provided, 340 | in accord with this section must be in a format that is publicly 341 | documented (and with an implementation available to the public in 342 | source code form), and must require no special password or key for 343 | unpacking, reading or copying. 344 | 345 | 7. Additional Terms. 346 | 347 | "Additional permissions" are terms that supplement the terms of this 348 | License by making exceptions from one or more of its conditions. 349 | Additional permissions that are applicable to the entire Program shall 350 | be treated as though they were included in this License, to the extent 351 | that they are valid under applicable law. If additional permissions 352 | apply only to part of the Program, that part may be used separately 353 | under those permissions, but the entire Program remains governed by 354 | this License without regard to the additional permissions. 355 | 356 | When you convey a copy of a covered work, you may at your option 357 | remove any additional permissions from that copy, or from any part of 358 | it. (Additional permissions may be written to require their own 359 | removal in certain cases when you modify the work.) You may place 360 | additional permissions on material, added by you to a covered work, 361 | for which you have or can give appropriate copyright permission. 362 | 363 | Notwithstanding any other provision of this License, for material you 364 | add to a covered work, you may (if authorized by the copyright holders of 365 | that material) supplement the terms of this License with terms: 366 | 367 | a) Disclaiming warranty or limiting liability differently from the 368 | terms of sections 15 and 16 of this License; or 369 | 370 | b) Requiring preservation of specified reasonable legal notices or 371 | author attributions in that material or in the Appropriate Legal 372 | Notices displayed by works containing it; or 373 | 374 | c) Prohibiting misrepresentation of the origin of that material, or 375 | requiring that modified versions of such material be marked in 376 | reasonable ways as different from the original version; or 377 | 378 | d) Limiting the use for publicity purposes of names of licensors or 379 | authors of the material; or 380 | 381 | e) Declining to grant rights under trademark law for use of some 382 | trade names, trademarks, or service marks; or 383 | 384 | f) Requiring indemnification of licensors and authors of that 385 | material by anyone who conveys the material (or modified versions of 386 | it) with contractual assumptions of liability to the recipient, for 387 | any liability that these contractual assumptions directly impose on 388 | those licensors and authors. 389 | 390 | All other non-permissive additional terms are considered "further 391 | restrictions" within the meaning of section 10. If the Program as you 392 | received it, or any part of it, contains a notice stating that it is 393 | governed by this License along with a term that is a further 394 | restriction, you may remove that term. If a license document contains 395 | a further restriction but permits relicensing or conveying under this 396 | License, you may add to a covered work material governed by the terms 397 | of that license document, provided that the further restriction does 398 | not survive such relicensing or conveying. 399 | 400 | If you add terms to a covered work in accord with this section, you 401 | must place, in the relevant source files, a statement of the 402 | additional terms that apply to those files, or a notice indicating 403 | where to find the applicable terms. 404 | 405 | Additional terms, permissive or non-permissive, may be stated in the 406 | form of a separately written license, or stated as exceptions; 407 | the above requirements apply either way. 408 | 409 | 8. Termination. 410 | 411 | You may not propagate or modify a covered work except as expressly 412 | provided under this License. Any attempt otherwise to propagate or 413 | modify it is void, and will automatically terminate your rights under 414 | this License (including any patent licenses granted under the third 415 | paragraph of section 11). 416 | 417 | However, if you cease all violation of this License, then your 418 | license from a particular copyright holder is reinstated (a) 419 | provisionally, unless and until the copyright holder explicitly and 420 | finally terminates your license, and (b) permanently, if the copyright 421 | holder fails to notify you of the violation by some reasonable means 422 | prior to 60 days after the cessation. 423 | 424 | Moreover, your license from a particular copyright holder is 425 | reinstated permanently if the copyright holder notifies you of the 426 | violation by some reasonable means, this is the first time you have 427 | received notice of violation of this License (for any work) from that 428 | copyright holder, and you cure the violation prior to 30 days after 429 | your receipt of the notice. 430 | 431 | Termination of your rights under this section does not terminate the 432 | licenses of parties who have received copies or rights from you under 433 | this License. If your rights have been terminated and not permanently 434 | reinstated, you do not qualify to receive new licenses for the same 435 | material under section 10. 436 | 437 | 9. Acceptance Not Required for Having Copies. 438 | 439 | You are not required to accept this License in order to receive or 440 | run a copy of the Program. Ancillary propagation of a covered work 441 | occurring solely as a consequence of using peer-to-peer transmission 442 | to receive a copy likewise does not require acceptance. However, 443 | nothing other than this License grants you permission to propagate or 444 | modify any covered work. These actions infringe copyright if you do 445 | not accept this License. Therefore, by modifying or propagating a 446 | covered work, you indicate your acceptance of this License to do so. 447 | 448 | 10. Automatic Licensing of Downstream Recipients. 449 | 450 | Each time you convey a covered work, the recipient automatically 451 | receives a license from the original licensors, to run, modify and 452 | propagate that work, subject to this License. You are not responsible 453 | for enforcing compliance by third parties with this License. 454 | 455 | An "entity transaction" is a transaction transferring control of an 456 | organization, or substantially all assets of one, or subdividing an 457 | organization, or merging organizations. If propagation of a covered 458 | work results from an entity transaction, each party to that 459 | transaction who receives a copy of the work also receives whatever 460 | licenses to the work the party's predecessor in interest had or could 461 | give under the previous paragraph, plus a right to possession of the 462 | Corresponding Source of the work from the predecessor in interest, if 463 | the predecessor has it or can get it with reasonable efforts. 464 | 465 | You may not impose any further restrictions on the exercise of the 466 | rights granted or affirmed under this License. For example, you may 467 | not impose a license fee, royalty, or other charge for exercise of 468 | rights granted under this License, and you may not initiate litigation 469 | (including a cross-claim or counterclaim in a lawsuit) alleging that 470 | any patent claim is infringed by making, using, selling, offering for 471 | sale, or importing the Program or any portion of it. 472 | 473 | 11. Patents. 474 | 475 | A "contributor" is a copyright holder who authorizes use under this 476 | License of the Program or a work on which the Program is based. The 477 | work thus licensed is called the contributor's "contributor version". 478 | 479 | A contributor's "essential patent claims" are all patent claims 480 | owned or controlled by the contributor, whether already acquired or 481 | hereafter acquired, that would be infringed by some manner, permitted 482 | by this License, of making, using, or selling its contributor version, 483 | but do not include claims that would be infringed only as a 484 | consequence of further modification of the contributor version. For 485 | purposes of this definition, "control" includes the right to grant 486 | patent sublicenses in a manner consistent with the requirements of 487 | this License. 488 | 489 | Each contributor grants you a non-exclusive, worldwide, royalty-free 490 | patent license under the contributor's essential patent claims, to 491 | make, use, sell, offer for sale, import and otherwise run, modify and 492 | propagate the contents of its contributor version. 493 | 494 | In the following three paragraphs, a "patent license" is any express 495 | agreement or commitment, however denominated, not to enforce a patent 496 | (such as an express permission to practice a patent or covenant not to 497 | sue for patent infringement). To "grant" such a patent license to a 498 | party means to make such an agreement or commitment not to enforce a 499 | patent against the party. 500 | 501 | If you convey a covered work, knowingly relying on a patent license, 502 | and the Corresponding Source of the work is not available for anyone 503 | to copy, free of charge and under the terms of this License, through a 504 | publicly available network server or other readily accessible means, 505 | then you must either (1) cause the Corresponding Source to be so 506 | available, or (2) arrange to deprive yourself of the benefit of the 507 | patent license for this particular work, or (3) arrange, in a manner 508 | consistent with the requirements of this License, to extend the patent 509 | license to downstream recipients. "Knowingly relying" means you have 510 | actual knowledge that, but for the patent license, your conveying the 511 | covered work in a country, or your recipient's use of the covered work 512 | in a country, would infringe one or more identifiable patents in that 513 | country that you have reason to believe are valid. 514 | 515 | If, pursuant to or in connection with a single transaction or 516 | arrangement, you convey, or propagate by procuring conveyance of, a 517 | covered work, and grant a patent license to some of the parties 518 | receiving the covered work authorizing them to use, propagate, modify 519 | or convey a specific copy of the covered work, then the patent license 520 | you grant is automatically extended to all recipients of the covered 521 | work and works based on it. 522 | 523 | A patent license is "discriminatory" if it does not include within 524 | the scope of its coverage, prohibits the exercise of, or is 525 | conditioned on the non-exercise of one or more of the rights that are 526 | specifically granted under this License. You may not convey a covered 527 | work if you are a party to an arrangement with a third party that is 528 | in the business of distributing software, under which you make payment 529 | to the third party based on the extent of your activity of conveying 530 | the work, and under which the third party grants, to any of the 531 | parties who would receive the covered work from you, a discriminatory 532 | patent license (a) in connection with copies of the covered work 533 | conveyed by you (or copies made from those copies), or (b) primarily 534 | for and in connection with specific products or compilations that 535 | contain the covered work, unless you entered into that arrangement, 536 | or that patent license was granted, prior to 28 March 2007. 537 | 538 | Nothing in this License shall be construed as excluding or limiting 539 | any implied license or other defenses to infringement that may 540 | otherwise be available to you under applicable patent law. 541 | 542 | 12. No Surrender of Others' Freedom. 543 | 544 | If conditions are imposed on you (whether by court order, agreement or 545 | otherwise) that contradict the conditions of this License, they do not 546 | excuse you from the conditions of this License. If you cannot convey a 547 | covered work so as to satisfy simultaneously your obligations under this 548 | License and any other pertinent obligations, then as a consequence you may 549 | not convey it at all. For example, if you agree to terms that obligate you 550 | to collect a royalty for further conveying from those to whom you convey 551 | the Program, the only way you could satisfy both those terms and this 552 | License would be to refrain entirely from conveying the Program. 553 | 554 | 13. Remote Network Interaction; Use with the GNU General Public License. 555 | 556 | Notwithstanding any other provision of this License, if you modify the 557 | Program, your modified version must prominently offer all users 558 | interacting with it remotely through a computer network (if your version 559 | supports such interaction) an opportunity to receive the Corresponding 560 | Source of your version by providing access to the Corresponding Source 561 | from a network server at no charge, through some standard or customary 562 | means of facilitating copying of software. This Corresponding Source 563 | shall include the Corresponding Source for any work covered by version 3 564 | of the GNU General Public License that is incorporated pursuant to the 565 | following paragraph. 566 | 567 | Notwithstanding any other provision of this License, you have 568 | permission to link or combine any covered work with a work licensed 569 | under version 3 of the GNU General Public License into a single 570 | combined work, and to convey the resulting work. The terms of this 571 | License will continue to apply to the part which is the covered work, 572 | but the work with which it is combined will remain governed by version 573 | 3 of the GNU General Public License. 574 | 575 | 14. Revised Versions of this License. 576 | 577 | The Free Software Foundation may publish revised and/or new versions of 578 | the GNU Affero General Public License from time to time. Such new versions 579 | will be similar in spirit to the present version, but may differ in detail to 580 | address new problems or concerns. 581 | 582 | Each version is given a distinguishing version number. If the 583 | Program specifies that a certain numbered version of the GNU Affero General 584 | Public License "or any later version" applies to it, you have the 585 | option of following the terms and conditions either of that numbered 586 | version or of any later version published by the Free Software 587 | Foundation. If the Program does not specify a version number of the 588 | GNU Affero General Public License, you may choose any version ever published 589 | by the Free Software Foundation. 590 | 591 | If the Program specifies that a proxy can decide which future 592 | versions of the GNU Affero General Public License can be used, that proxy's 593 | public statement of acceptance of a version permanently authorizes you 594 | to choose that version for the Program. 595 | 596 | Later license versions may give you additional or different 597 | permissions. However, no additional obligations are imposed on any 598 | author or copyright holder as a result of your choosing to follow a 599 | later version. 600 | 601 | 15. Disclaimer of Warranty. 602 | 603 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 604 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 605 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 606 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 607 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 608 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 609 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 610 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 611 | 612 | 16. Limitation of Liability. 613 | 614 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 615 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 616 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 617 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 618 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 619 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 620 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 621 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 622 | SUCH DAMAGES. 623 | 624 | 17. Interpretation of Sections 15 and 16. 625 | 626 | If the disclaimer of warranty and limitation of liability provided 627 | above cannot be given local legal effect according to their terms, 628 | reviewing courts shall apply local law that most closely approximates 629 | an absolute waiver of all civil liability in connection with the 630 | Program, unless a warranty or assumption of liability accompanies a 631 | copy of the Program in return for a fee. 632 | 633 | END OF TERMS AND CONDITIONS 634 | 635 | How to Apply These Terms to Your New Programs 636 | 637 | If you develop a new program, and you want it to be of the greatest 638 | possible use to the public, the best way to achieve this is to make it 639 | free software which everyone can redistribute and change under these terms. 640 | 641 | To do so, attach the following notices to the program. It is safest 642 | to attach them to the start of each source file to most effectively 643 | state the exclusion of warranty; and each file should have at least 644 | the "copyright" line and a pointer to where the full notice is found. 645 | 646 | 647 | Copyright (C) 648 | 649 | This program is free software: you can redistribute it and/or modify 650 | it under the terms of the GNU Affero General Public License as published by 651 | the Free Software Foundation, either version 3 of the License, or 652 | (at your option) any later version. 653 | 654 | This program is distributed in the hope that it will be useful, 655 | but WITHOUT ANY WARRANTY; without even the implied warranty of 656 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 657 | GNU Affero General Public License for more details. 658 | 659 | You should have received a copy of the GNU Affero General Public License 660 | along with this program. If not, see . 661 | 662 | Also add information on how to contact you by electronic and paper mail. 663 | 664 | If your software can interact with users remotely through a computer 665 | network, you should also make sure that it provides a way for users to 666 | get its source. For example, if your program is a web application, its 667 | interface could display a "Source" link that leads users to an archive 668 | of the code. There are many ways you could offer source, and different 669 | solutions will be better for different programs; see section 13 for the 670 | specific requirements. 671 | 672 | You should also get your employer (if you work as a programmer) or school, 673 | if any, to sign a "copyright disclaimer" for the program, if necessary. 674 | For more information on this, and how to apply and follow the GNU AGPL, see 675 | . 676 | 677 | --------------------------------------------------------------------------------