Skip to content

Commit

Permalink
store for handling visiblity of maskeditor
Browse files Browse the repository at this point in the history
- remove update  button in edit mode, implement autoupdate
  • Loading branch information
krmanik committed Jul 22, 2023
1 parent fcf532b commit a87e691
Show file tree
Hide file tree
Showing 10 changed files with 64 additions and 145 deletions.
2 changes: 1 addition & 1 deletion ftl/core/notetypes.ftl
Original file line number Diff line number Diff line change
Expand Up @@ -51,5 +51,5 @@ notetypes-error-generating-cloze = An error occurred when generating an image oc
notetypes-error-getting-imagecloze = An error occurred while fetching an image occlusion note
notetypes-error-loading-image-occlusion = Error loading image occlusion. Is your Anki version up to date?
notetype-error-no-image-to-show = No image to show.
notetypes-no-occlusion-created = No occlusion note created.
notetypes-no-occlusion-created = You must make at least one occlusion.
notetypes-io-select-image = Select Image
19 changes: 10 additions & 9 deletions qt/aqt/addcards.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,6 @@ def __init__(self, mw: AnkiQt) -> None:
self._last_added_note: Optional[Note] = None
gui_hooks.operation_did_execute.append(self.on_operation_did_execute)
restoreGeom(self, "add")
self.col.add_image_occlusion_notetype()
# hide io buttons for note type other than image occlusion
self.show_hide_add_buttons()
gui_hooks.add_cards_did_init(self)
self.show()

Expand Down Expand Up @@ -117,9 +114,9 @@ def setupButtons(self) -> None:
self.addButton.setToolTip(shortcut(tr.adding_add_shortcut_ctrlandenter()))

# add io button
self.ioAddButton = bb.addButton(f"{tr.actions_add()} {downArrow()}", ar)
qconnect(self.ioAddButton.clicked, self.onAddIo)
self.ioAddButton.setShortcut(QKeySequence("Ctrl+Shift+I"))
self.io_add_button = bb.addButton(f"{tr.actions_add()} {downArrow()}", ar)
qconnect(self.io_add_button.clicked, self.onAddIo)
self.io_add_button.setShortcut(QKeySequence("Ctrl+Shift+I"))

# close
self.closeButton = QPushButton(tr.actions_close())
Expand All @@ -142,13 +139,17 @@ def setupButtons(self) -> None:
b.setEnabled(False)
self.historyButton = b

self.col.add_image_occlusion_notetype()
# hide io buttons for note type other than image occlusion
self.show_hide_add_buttons()

def show_hide_add_buttons(self) -> None:
if self.editor.current_notetype_is_image_occlusion():
self.addButton.setVisible(False)
self.ioAddButton.setVisible(True)
self.io_add_button.setVisible(True)
else:
self.addButton.setVisible(True)
self.ioAddButton.setVisible(False)
self.io_add_button.setVisible(False)

def setAndFocusNote(self, note: Note) -> None:
self.editor.set_note(note, focusTo=0)
Expand Down Expand Up @@ -377,7 +378,7 @@ def onAddIo(self) -> None:
qconnect(a.triggered, self.add_io_hide_all_note)
a = m.addAction(tr.notetypes_hide_one_guess_one())
qconnect(a.triggered, self.add_io_hide_one_note)
m.exec(self.ioAddButton.mapToGlobal(QPoint(0, 0)))
m.popup(QCursor.pos())

def add_io_hide_all_note(self) -> None:
self.editor.web.eval("setOcclusionField(true)")
Expand Down
33 changes: 3 additions & 30 deletions qt/aqt/editcurrent.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from anki.errors import NotFoundError
from aqt import gui_hooks
from aqt.qt import *
from aqt.utils import disable_help_button, restoreGeom, saveGeom, tooltip, tr
from aqt.utils import disable_help_button, restoreGeom, saveGeom, tr


class EditCurrent(QDialog):
Expand All @@ -30,38 +30,11 @@ def __init__(self, mw: aqt.AnkiQt) -> None:
self.editor.card = self.mw.reviewer.card
self.editor.set_note(self.mw.reviewer.card.note(), focusTo=0)
restoreGeom(self, "editcurrent")
self.setupButtons()
gui_hooks.operation_did_execute.append(self.on_operation_did_execute)
self.show()

def setupButtons(self) -> None:
if self.editor.current_notetype_is_image_occlusion():
bb = self.form.buttonBox
ar = QDialogButtonBox.ButtonRole.ActionRole
# add io hide all button
self.ioAddButton = bb.addButton(tr.actions_update_note(), ar)
qconnect(self.ioAddButton.clicked, self.onAddIo)
self.ioAddButton.setShortcut(QKeySequence("Ctrl+Shift+I"))

self.form.buttonBox.button(QDialogButtonBox.StandardButton.Close).setShortcut(
QKeySequence("Ctrl+Return")
)

def onAddIo(self) -> None:
m = QMenu(self)
a = m.addAction(tr.notetypes_hide_all_guess_one())
qconnect(a.triggered, self.update_io_hide_all_note)
a = m.addAction(tr.notetypes_hide_one_guess_one())
qconnect(a.triggered, self.update_io_hide_one_note)
m.exec(self.ioAddButton.mapToGlobal(QPoint(0, 0)))

def update_io_hide_all_note(self) -> None:
self.editor.web.eval("setOcclusionField(true)")
tooltip(tr.importing_updated(), period=500)

def update_io_hide_one_note(self) -> None:
self.editor.web.eval("setOcclusionField(false)")
tooltip(tr.importing_updated(), period=500)
gui_hooks.operation_did_execute.append(self.on_operation_did_execute)
self.show()

def on_operation_did_execute(
self, changes: OpChanges, handler: Optional[object]
Expand Down
20 changes: 4 additions & 16 deletions qt/aqt/editor.py
Original file line number Diff line number Diff line change
Expand Up @@ -477,11 +477,6 @@ def onBridgeCmd(self, cmd: str) -> Any:
elif cmd in self._links:
return self._links[cmd](self)

elif cmd.startswith("toggleMaskEditor"):
(_, show_str) = cmd.split(":", 1)
show = show_str == "true"
self.onToggleMaskEditor(show)

else:
print("uncaught cmd", cmd)

Expand Down Expand Up @@ -556,7 +551,7 @@ def oncallback(arg: Any) -> None:
setCloseHTMLTags({json.dumps(self.mw.col.get_config("closeHTMLTags", True))});
triggerChanges();
setIsImageOcclusion({json.dumps(self.current_notetype_is_image_occlusion())});
setIsBrowseMode({json.dumps(self.editorMode == EditorMode.BROWSER)})
setIsEditMode({json.dumps(self.editorMode != EditorMode.ADD_CARDS)});
"""

if self.addMode:
Expand Down Expand Up @@ -1207,10 +1202,10 @@ def onAddImageForOcclusion(self) -> None:
def accept(file: str) -> None:
try:
html = self._addMedia(file)
options = {"kind": "add", "imagePath": file, "notetypeId": 0}
mode = {"kind": "add", "imagePath": file, "notetypeId": 0}
# pass both html and options
options = {"html": html, "mode": options}
self.web.eval(f"setupMaskEditor({options})")
options = {"html": html, "mode": mode}
self.web.eval(f"setupMaskEditor({json.dumps(options)})")
except Exception as e:
showWarning(str(e))
return
Expand All @@ -1225,12 +1220,6 @@ def accept(file: str) -> None:

self.parentWindow.activateWindow()

def onToggleMaskEditor(self, show) -> None:
if show:
self.web.eval("toggleMaskEditor(true)")
else:
self.web.eval("toggleMaskEditor(false)")

# Links from HTML
######################################################################

Expand Down Expand Up @@ -1261,7 +1250,6 @@ def _init_links(self) -> None:
toggleShrinkImages=Editor.toggleShrinkImages,
toggleCloseHTMLTags=Editor.toggleCloseHTMLTags,
addImageForOcclusion=Editor.onAddImageForOcclusion,
toggleMaskEditor=Editor.onToggleMaskEditor,
)


Expand Down
4 changes: 1 addition & 3 deletions ts/editor/EditorField.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -86,11 +86,9 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
setupLifecycleHooks(api);
onDestroy(() => api?.destroy());
$: hideField = field.hidden || false;
</script>

<div class="field-container {hideField ? 'hide' : ''}" on:mouseenter on:mouseleave>
<div class="field-container" class:hide={field.hidden} on:mouseenter on:mouseleave>
<slot name="field-label" />

<Collapsible collapse={collapsed} let:collapsed={hidden}>
Expand Down
82 changes: 23 additions & 59 deletions ts/editor/NoteEditor.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -237,20 +237,15 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
return noteId;
}
$: isImageOcclusion = false;
let isImageOcclusion = false;
function setIsImageOcclusion(val: boolean) {
isImageOcclusion = val;
if (isImageOcclusion) {
toggleMaskEditor(true);
} else {
toggleMaskEditor(false);
}
$showMaskEditor = val;
}
$: isBrowseMode = false;
function setIsBrowseMode(val: boolean) {
isBrowseMode = val;
let isEditMode = false;
function setIsEditMode(val: boolean) {
isEditMode = val;
}
let cols: ("dupe" | "")[] = [];
Expand Down Expand Up @@ -303,7 +298,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
}
function saveNow(): void {
updateNoteInBrowseMode();
updateIONoteInEditMode();
closeMathjaxEditor?.();
$commitTagEdits();
saveFieldNow();
Expand Down Expand Up @@ -392,57 +387,29 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { wrapInternal } from "@tslib/wrap";
import LabelButton from "components/LabelButton.svelte";
import Shortcut from "components/Shortcut.svelte";
import { setupImageOcclusion } from "image-occlusion";
import ImageOcclusionPage from "image-occlusion/ImageOcclusionPage.svelte";
import type { IOMode } from "image-occlusion/lib";
import { exportShapesToClozeDeletions } from "image-occlusion/shapes/to-cloze";
import { isShowMaskEditor } from "image-occlusion/store";
import { mathjaxConfig } from "../editable/mathjax-element";
import CollapseLabel from "./CollapseLabel.svelte";
import * as oldEditorAdapter from "./old-editor-adapter";
$: isShowMaskEditor = false;
$: isIOImageLoaded = false;
function toggleMaskEditor(show: boolean) {
isShowMaskEditor = show;
const element = document.getElementById("io-mask-editor") as HTMLElement;
const ioMaskBtn = document.getElementById("io-mask-btn") as HTMLElement;
if (isShowMaskEditor) {
ioMaskBtn?.classList.add("active-io-btn");
} else {
ioMaskBtn?.classList.remove("active-io-btn");
}
if (element) {
element.style.display = show ? "block" : "none";
}
}
let isIOImageLoaded = false;
const showMaskEditor = isShowMaskEditor;
let imageOcclusionMode: IOMode;
async function setupMaskEditor(options: { html: string; mode: IOMode }) {
imageOcclusionMode = options.mode;
if (options.mode.kind === "add") {
fieldStores[1].set(options.html);
}
// remove old page for new image occlusion
const page = document.querySelector(".image-occlusion") as HTMLElement;
if (page) {
page.remove();
}
const ioMaskEditor = document.getElementById("io-mask-editor") as HTMLElement;
const ioSelectImageDiv = document.getElementById(
"io-select-image-div",
) as HTMLElement;
if (ioSelectImageDiv) {
ioSelectImageDiv.remove();
}
await setupImageOcclusion(options.mode, ioMaskEditor);
toggleMaskEditor(true);
isIOImageLoaded = true;
}
// update cloze deletions and set occlusion fields, it call in saveNow to update cloze deletions
function updateNoteInBrowseMode() {
if (isBrowseMode) {
function updateIONoteInEditMode() {
if (isEditMode) {
const clozeNote = get(fieldStores[0]);
if (clozeNote.includes("oi=1")) {
setOcclusionField(true);
Expand Down Expand Up @@ -515,8 +482,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
setCloseHTMLTags,
triggerChanges,
setIsImageOcclusion,
setIsBrowseMode,
toggleMaskEditor,
setIsEditMode,
setupMaskEditor,
setOcclusionField,
...oldEditorAdapter,
Expand Down Expand Up @@ -572,11 +538,14 @@ the AddCards dialog) should be implemented in the user of this component.
</Absolute>
{/if}

<!-- for init maskeditor -->
<div id="io-mask-editor" style="display: none;" />
{#if imageOcclusionMode && isImageOcclusion}
<div style="display: {$showMaskEditor ? 'block' : 'none'}">
<ImageOcclusionPage mode={imageOcclusionMode} />
</div>
{/if}

{#if isShowMaskEditor && isImageOcclusion && !isIOImageLoaded}
<div id="io-select-image-div" style="padding-top: 60px; text-align: center">
{#if $showMaskEditor && isImageOcclusion && !isIOImageLoaded}
<div id="io-select-image-div" style="padding-top: 60px; text-align: center;">
<LabelButton
--border-left-radius="5px"
--border-right-radius="5px"
Expand All @@ -588,7 +557,7 @@ the AddCards dialog) should be implemented in the user of this component.
</div>
{/if}

{#if !isShowMaskEditor}
{#if !$showMaskEditor}
<Fields>
{#each fieldsData as field, index}
{@const content = fieldStores[index]}
Expand Down Expand Up @@ -749,11 +718,6 @@ the AddCards dialog) should be implemented in the user of this component.
margin-top: 2px !important;
}
:global(.active-io-btn) {
background: var(--button-primary-bg) !important;
color: white !important;
}
:global(.io-select-image-btn) {
margin: auto;
padding: 0px 8px 0px 8px !important;
Expand Down
35 changes: 13 additions & 22 deletions ts/editor/editor-toolbar/ImageOcclusionButton.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,17 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import ButtonGroup from "components/ButtonGroup.svelte";
import DynamicallySlottable from "components/DynamicallySlottable.svelte";
import IconButton from "components/IconButton.svelte";
import { maskEditorButtonPressed } from "image-occlusion/store";
import { get } from "svelte/store";
import { isShowMaskEditor } from "image-occlusion/store";
import ButtonGroupItem, {
createProps,
setSlotHostContext,
updatePropsList,
} from "../../components/ButtonGroupItem.svelte";
import { bridgeCommand } from "../../lib/bridgecommand";
import { mdiRefresh, mdiViewDashboard } from "./icons";
import { mdiViewDashboard } from "./icons";
export let api = {};
const showMaskEditor = isShowMaskEditor;
</script>

<ButtonGroup>
Expand All @@ -31,29 +30,21 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
<ButtonGroupItem>
<IconButton
id="io-mask-btn"
class={$showMaskEditor ? "active-io-btn" : ""}
on:click={() => {
if (get(maskEditorButtonPressed)) {
bridgeCommand(`toggleMaskEditor:${false}`);
} else {
bridgeCommand(`toggleMaskEditor:${true}`);
}
maskEditorButtonPressed.set(!get(maskEditorButtonPressed));
$showMaskEditor = !$showMaskEditor;
isShowMaskEditor.set($showMaskEditor);
}}
>
{@html mdiViewDashboard}
</IconButton>
</ButtonGroupItem>

{#if get(maskEditorButtonPressed)}
<ButtonGroupItem>
<IconButton
on:click={() => {
bridgeCommand("addImageForOcclusion");
}}
>
{@html mdiRefresh}
</IconButton>
</ButtonGroupItem>
{/if}
</DynamicallySlottable>
</ButtonGroup>

<style>
:global(.active-io-btn) {
background: var(--button-primary-bg) !important;
color: white !important;
}
</style>
Loading

0 comments on commit a87e691

Please sign in to comment.