2bf134dc72
* add note types with occlusions and image fields * generate image occlusion cloze div data - generate div element with data-* atrributes for canvas shape generate for reviewer * getting image data & deck id and adding notes the implementation added into backend - added service index in backend.proto for image occlusion request - created image_occlusion.proto with required message and service - implementation in backend for getting image and adding notes, also during editing return imagecloze note and update notes - add notes to selected deck, if no notetype then add image occlusion notetypes - reuse notetype from stock notetypes when not exist * script for generating shapes using canvas api in reviewer - the flash issues fixed by loading image and using image size to draw canvas, also when image get resized, calculate scale using natural width and canvas width to draw shape at right position - limit size of canvas for safari * init image occlusion page in ts and build page with - fabricjs for editing shapes - panzoom for drag and zoom - pickr for color picker - build page using web.rs * implement top toolbar for canvas shapes - undo & redo tools - zoom in, zoom out and zoom fit - group & ungroup - copy & paste - set transparency of shapes - align tools * implement side toolbar for drawing shapes add top toolbar and the side toolbar contains following tools - cursor for selecting shapes - zoom for drag and zoom shapes in mask editor - rectangle for creating it - ellipse for creating it - polygon for creating it using points - shape fill color - question mask color (currently only single color can be added for all shapes) * add maskeditor page for editing mask - add side toolbar and sidebar include toptoolbar - load maskeditor in two mode - for adding note using path to image - for editing note using note id * implement note editor page for adding notes - the note editor page have simple button (B/I/U) and option to toggle html view - option to select deck for adding notes into that deck - option to generate to hide all, guess one & hide one, guess one notes * add image occlusion page add side toolbar, top toolbar, mask editor and note editor - option to switch between mask editor and note editor * implement generates notes and save notes implemention to show toast components for messages * removed pickr & implemented color picker component - remove pickr - implemented using html5 canvas - range input for changing color - another range input for opacity changes - hex and rgba value support * rename methods name & rust unwrap safety - change plural names to singular - create respone message in proto and return response with imagecloze note or error if not found with note id - remove image_occlusion from post handler list - rename service name in mediasrv.py - rename methods name for image occlusion in backend and image_occlusion - update frontend also for update functions' names - handle error in frontend mask-editor.ts, when error getting notes then toast message shown to frontend * extract to function & add comments & remove global - extract function in mask-editor.ts to reduce duplicate - remove unused global from css - add comments to store.ts explaining usage - changes id to noteId in lib.ts - add comments for limitSize, becuase of duplicate implementation * remove image_occlusion notetype - remove from stock notetype, stdmodels - add implementation for notetype to image occlusion - add i18n for errors * update smooth scroll, always show cursor tools - change questionmask to qmask - make selectable for shape true in all tools to simplify edits and draw shapes - update image occlusion in reviewer ts to load image properly * add and get notetype else return errors * fix: not showing occlusion * Use a oneof for ImageClozeNoteResponse Makes it clearer that only one of them can be returned * Don't crash if image filename not provided The second unwrap should be ok, as the input is utf8 * Refactor get_image_cloze_note - fixes crash when note doesn't exist - Ok(None) case was not covered - decouples business logic from native error->proto error conversion - no need for original copy - field[x] is more idiomatic than field.get(x).unwrap() - don't need mutable access to fields * Fix crash if image file unreadable + Use our read_file helper for better error context * Add metadata() helper * Fix crash if file metadata can't be read * remove color picker, qmask and shape color - remove strings from ftl - remove color picker component - remove from cloze generation - remove icons for two buttons - use constant color for shapes * update color in reviewer and ftl strings * fix shape position in canvas & add border to shape - rename mask to inactive shape and active shape color - border witdth and border color - change decimal point deserializing string and toFixed(2) - add thin border in mask editor, may be image background was transparent * fix shape position in canvas after modified - do not draw fixed ratio shapes by turn of uniformScaling - fix rectangle width,height - fix ellipse rx,ry,width,height - fix polygon postion and points - draw outside of canvas also * fix border width and color in reviewer canvas - rename variable * refactor cloze div generate and remove angle * fix origin when drawn outside of canvas from right * fix shape at boundry & not include rx,ry rectangle - move shapes at boundry when pointer is outside of canvas - include rx, ry for ellipse only - include points for polygon only * fix lint errors & update image size in editor canvas based on height and width * remove unsupported layerX & layerX for touchscreen - fix shapes at edges * implemented undo redo with canvas state - implemented undo redo using fabric canvas events - polygon is special case and implemented only added and modified event - rectangle and ellipse have object:added, object:modified and object:removed case - change id to undo and redo * remove background image from canvas and used css to put image tag below canvas editor - set image width and height after adding image * fix for polygon points, add br in cloze strings, & toogle masks button - fix shapes at edges - toggle masks button to show/hide masks - hide clozes string, it contains <br> - set height for div container (used 'relative' in css) * refactor top toolbar, add space and border radius - rename cursor tools - add left and right border * fix undo after undo happen, use transparent color in draw mode
266 lines
7.4 KiB
TypeScript
266 lines
7.4 KiB
TypeScript
// Copyright: Ankitects Pty Ltd and contributors
|
|
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
|
|
|
|
/* eslint
|
|
@typescript-eslint/no-explicit-any: "off",
|
|
*/
|
|
|
|
import "css-browser-selector/css_browser_selector.min";
|
|
|
|
export { default as $, default as jQuery } from "jquery/dist/jquery";
|
|
|
|
import { mutateNextCardStates } from "./answering";
|
|
import { setupImageCloze } from "./image_occlusion";
|
|
|
|
globalThis.anki = globalThis.anki || {};
|
|
globalThis.anki.mutateNextCardStates = mutateNextCardStates;
|
|
globalThis.anki.setupImageCloze = setupImageCloze;
|
|
|
|
import { bridgeCommand } from "@tslib/bridgecommand";
|
|
|
|
import { maybePreloadExternalCss } from "./css";
|
|
import { allImagesLoaded, maybePreloadImages, preloadAnswerImages } from "./images";
|
|
|
|
declare const MathJax: any;
|
|
|
|
type Callback = () => void | Promise<void>;
|
|
|
|
export const onUpdateHook: Array<Callback> = [];
|
|
export const onShownHook: Array<Callback> = [];
|
|
|
|
export const ankiPlatform = "desktop";
|
|
let typeans: HTMLInputElement | undefined;
|
|
|
|
export function getTypedAnswer(): string | null {
|
|
return typeans?.value ?? null;
|
|
}
|
|
|
|
function _runHook(
|
|
hooks: Array<Callback>,
|
|
): Promise<PromiseSettledResult<void | Promise<void>>[]> {
|
|
const promises: (Promise<void> | void)[] = [];
|
|
|
|
for (const hook of hooks) {
|
|
try {
|
|
const result = hook();
|
|
promises.push(result);
|
|
} catch (error) {
|
|
console.log("Hook failed: ", error);
|
|
}
|
|
}
|
|
|
|
return Promise.allSettled(promises);
|
|
}
|
|
|
|
let _updatingQueue: Promise<void> = Promise.resolve();
|
|
|
|
export function _queueAction(action: Callback): void {
|
|
_updatingQueue = _updatingQueue.then(action);
|
|
}
|
|
|
|
// Setting innerHTML does not evaluate the contents of script tags, so we need
|
|
// to add them again in order to trigger the download/evaluation. Promise resolves
|
|
// when download/evaluation has completed.
|
|
function replaceScript(oldScript: HTMLScriptElement): Promise<void> {
|
|
return new Promise((resolve) => {
|
|
const newScript = document.createElement("script");
|
|
let mustWaitForNetwork = true;
|
|
if (oldScript.src) {
|
|
newScript.addEventListener("load", () => resolve());
|
|
newScript.addEventListener("error", () => resolve());
|
|
} else {
|
|
mustWaitForNetwork = false;
|
|
}
|
|
|
|
for (const attribute of oldScript.attributes) {
|
|
newScript.setAttribute(attribute.name, attribute.value);
|
|
}
|
|
|
|
newScript.appendChild(document.createTextNode(oldScript.innerHTML));
|
|
oldScript.replaceWith(newScript);
|
|
|
|
if (!mustWaitForNetwork) {
|
|
resolve();
|
|
}
|
|
});
|
|
}
|
|
|
|
async function setInnerHTML(element: Element, html: string): Promise<void> {
|
|
for (const oldVideo of element.getElementsByTagName("video")) {
|
|
oldVideo.pause();
|
|
|
|
while (oldVideo.firstChild) {
|
|
oldVideo.removeChild(oldVideo.firstChild);
|
|
}
|
|
|
|
oldVideo.load();
|
|
}
|
|
|
|
element.innerHTML = html;
|
|
|
|
for (const oldScript of element.getElementsByTagName("script")) {
|
|
await replaceScript(oldScript);
|
|
}
|
|
}
|
|
|
|
const renderError = (type: string) => (error: unknown): string => {
|
|
const errorMessage = String(error).substring(0, 2000);
|
|
let errorStack: string;
|
|
if (error instanceof Error) {
|
|
errorStack = String(error.stack).substring(0, 2000);
|
|
} else {
|
|
errorStack = "";
|
|
}
|
|
return `<div>Invalid ${type} on card: ${errorMessage}\n${errorStack}</div>`.replace(
|
|
/\n/g,
|
|
"<br>",
|
|
);
|
|
};
|
|
|
|
export async function _updateQA(
|
|
html: string,
|
|
_unusused: unknown,
|
|
onupdate: Callback,
|
|
onshown: Callback,
|
|
): Promise<void> {
|
|
onUpdateHook.length = 0;
|
|
onUpdateHook.push(onupdate);
|
|
|
|
onShownHook.length = 0;
|
|
onShownHook.push(onshown);
|
|
|
|
const qa = document.getElementById("qa")!;
|
|
|
|
// prevent flash of unstyled content when external css used
|
|
await maybePreloadExternalCss(html);
|
|
|
|
// prevent flickering & layout shift on image load
|
|
await maybePreloadImages(html);
|
|
|
|
qa.style.opacity = "0";
|
|
|
|
try {
|
|
await setInnerHTML(qa, html);
|
|
} catch (error) {
|
|
await setInnerHTML(qa, renderError("html")(error));
|
|
}
|
|
|
|
await _runHook(onUpdateHook);
|
|
|
|
// dynamic toolbar background
|
|
bridgeCommand("updateToolbar");
|
|
|
|
// wait for mathjax to ready
|
|
await MathJax.startup.promise
|
|
.then(() => {
|
|
// clear MathJax buffers from previous typesets
|
|
MathJax.typesetClear();
|
|
|
|
return MathJax.typesetPromise([qa]);
|
|
})
|
|
.catch(renderError("MathJax"));
|
|
|
|
qa.style.opacity = "1";
|
|
|
|
await _runHook(onShownHook);
|
|
}
|
|
|
|
export function _showQuestion(q: string, a: string, bodyclass: string): void {
|
|
_queueAction(() =>
|
|
_updateQA(
|
|
q,
|
|
null,
|
|
function() {
|
|
// return to top of window
|
|
window.scrollTo(0, 0);
|
|
|
|
document.body.className = bodyclass;
|
|
},
|
|
function() {
|
|
// focus typing area if visible
|
|
typeans = document.getElementById("typeans") as HTMLInputElement;
|
|
if (typeans) {
|
|
typeans.focus();
|
|
}
|
|
// preload images
|
|
allImagesLoaded().then(() => preloadAnswerImages(q, a));
|
|
},
|
|
)
|
|
);
|
|
}
|
|
|
|
function scrollToAnswer(): void {
|
|
document.getElementById("answer")?.scrollIntoView();
|
|
}
|
|
|
|
export function _showAnswer(a: string, bodyclass: string): void {
|
|
_queueAction(() =>
|
|
_updateQA(
|
|
a,
|
|
null,
|
|
function() {
|
|
if (bodyclass) {
|
|
// when previewing
|
|
document.body.className = bodyclass;
|
|
}
|
|
|
|
// avoid scrolling to the answer until images load
|
|
allImagesLoaded().then(scrollToAnswer);
|
|
},
|
|
function() {
|
|
/* noop */
|
|
},
|
|
)
|
|
);
|
|
}
|
|
|
|
export function _drawFlag(flag: 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7): void {
|
|
const elem = document.getElementById("_flag")!;
|
|
elem.toggleAttribute("hidden", flag === 0);
|
|
elem.style.color = `var(--flag-${flag})`;
|
|
}
|
|
|
|
export function _drawMark(mark: boolean): void {
|
|
document.getElementById("_mark")!.toggleAttribute("hidden", !mark);
|
|
}
|
|
|
|
export function _typeAnsPress(): void {
|
|
const code = (window.event as KeyboardEvent).code;
|
|
if (["Enter", "NumpadEnter"].includes(code)) {
|
|
bridgeCommand("ans");
|
|
}
|
|
}
|
|
|
|
export function _emulateMobile(enabled: boolean): void {
|
|
document.documentElement.classList.toggle("mobile", enabled);
|
|
}
|
|
|
|
// Block Qt's default drag & drop behavior by default
|
|
export function _blockDefaultDragDropBehavior(): void {
|
|
function handler(evt: DragEvent) {
|
|
evt.preventDefault();
|
|
}
|
|
document.ondragenter = handler;
|
|
document.ondragover = handler;
|
|
document.ondrop = handler;
|
|
}
|
|
|
|
// work around WebEngine/IME bug in Qt6
|
|
// https://github.com/ankitects/anki/issues/1952
|
|
const dummyButton = document.createElement("button");
|
|
dummyButton.style.position = "absolute";
|
|
dummyButton.style.left = "-9999px";
|
|
document.addEventListener("focusout", (event) => {
|
|
// Prevent type box from losing focus when switching IMEs
|
|
if (!document.hasFocus()) {
|
|
return;
|
|
}
|
|
|
|
const target = event.target;
|
|
if (target instanceof HTMLInputElement || target instanceof HTMLTextAreaElement) {
|
|
document.body.appendChild(dummyButton);
|
|
dummyButton.focus();
|
|
document.body.removeChild(dummyButton);
|
|
}
|
|
});
|