Commit Graph

37 Commits

Author SHA1 Message Date
Damien Elmes
0cd0ad9b07 Start editing text immediately after adding text node
Closes #2781
2023-10-28 10:25:56 +10:00
Damien Elmes
6a0b96d7ea Fix I/O failing to load if image takes too longer 2023-10-28 07:59:06 +10:00
Damien Elmes
22736238c1 Disable rotation globally
As described on https://github.com/fabricjs/fabric.js/issues/6420#issuecomment-650747872

Fixes rotation marker appearing when selecting, and when ungrouping
2023-10-25 09:23:47 +10:00
Hikaru Y
252addf611
Fix shape selection malfunction after creating shapes in succession (#2773)
* Fix shape selection malfunction after creating shapes in succession

* Disable rotation when duplicating a shape
2023-10-25 09:02:44 +10:00
Abdo
0736cdb29c
Fix scaling of text objects (#2767)
* Fix scaling of text objects

* Do not transform scale factors
2023-10-25 08:47:54 +10:00
Damien Elmes
aab81f9f9a Add tooltips for image occlusions
Closes #2768
2023-10-23 12:03:22 +10:00
Aristotelis
8e828f2955
Allow disabling occlusion mask border (#2764)
* Allow setting occlusion mask border to zero

* Switch to multi-line if statements

cf. 9740393d72

* Enforce if statement braces in dprint

---------

Co-authored-by: Glutanimate <glutanimate@users.noreply.github.com>
2023-10-23 11:43:37 +10:00
Abdo
14940a617b
Fix IO groups breaking upon editing (#2766)
* Fix IO groups breaking upon editing

* Emit change signal after group/ungroup
2023-10-23 09:43:31 +10:00
Damien Elmes
9740393d72 Enforce curly bracket usage for one-statement ifs 2023-10-23 09:19:49 +10:00
Hikaru Y
a53806e24a
Indicate current occlusion type in pop-up menu (#2760)
* Simplify handling of occlusion types in editor code

- Unify updateIONoteInEditMode(), setOcclusionFieldInner() and
setOcclusionField() into updateOcclusionsField()
- Don't use `includeInactive` property of Shape class in editor code
- Drop `isEditMode`

+
Update the occlusions field every time a mask or text is updated, not
only in editing mode but also in adding mode, so that IO cards can be
previewed correctly in the card layout screen

* Indicate current occlusion type in pop-up menu

https://forums.ankiweb.net/t/anki-23-10-beta-5-6/35677/46

* Fix a11y warnings in Toolbar.svelte

* Drop `occludeInactive` parameter from `MaskEditorAPI.getShapes()`
2023-10-23 09:12:56 +10:00
Hikaru Y
f8edbcc686
Fix modified polygon not being saved when editing IO note (#2762) 2023-10-22 10:51:45 +10:00
Aristotelis
56f7d54900
Add APIs for IO mask editing (#2758)
* Add simple mask editor add-on API

* Signal completed mask editor image loading to Python

* Add API methods for querying mask editor state, fix formatting

* Use event forwarding to propagate image loaded event

Should fix mobile support by moving all bridgeCommand calls to `NoteEditor.svelte`

* Add shape classes to mask editor API

---------

Co-authored-by: Glutanimate <glutanimate@users.noreply.github.com>
2023-10-22 10:40:40 +10:00
Abdo
8e1105144a
Commit addition of IO shapes immediately (#2750) 2023-10-20 09:38:03 +10:00
Aristotelis
c828a2eb6f
Add APIs for IO card rendering (#2739)
* Refactor: Add index to shapes package

* Add shape draw callback API to setupImageCloze

* Expose IO drawing API, switch away from image cloze naming

We currently use "image occlusion" in most places, but some references to "image cloze" still remain. For consistency's sake and to make it easier to quickly find IO-related code, this commit replaces all remaining references to "image cloze", only maintaining those required for backwards compatibility with existing note types.

* Add cloze ordinal to shapes

* Do not mutate original shapes during (de)normalization

Mutating shapes would be a recipe for trouble when combined with IO API use by external consumers.

(makeNormal(makeAbsolute(makeNormal())) is not idempotent,
and keeping track of the original state would introduce
additional complexity with no discernible performance benefit
or otherwise.)

* Tweak IO API, allowing modifications to ShapeProperties

* Tweak drawShape parameters

* Switch method order

For consistency with previous implementation

* Run Rust formatters

* Simplify position (de)normalization

---------

Co-authored-by: Glutanimate <glutanimate@users.noreply.github.com>
2023-10-20 09:36:46 +10:00
Hikaru Y
bea4307d78
Another approach to preventing selected shapes from shifting (#2735)
* Revert "Fix selected shapes shifting to canvas origin"

This reverts commit d81b96fed0adb7db2fb9847c52d7cb73f83b4b32.

This introduced a regression where the selection of objects was cleared
when it should not have been. For example, if multiple objects were
selected and the mouse was released while moving them around, the
selection would be cleared.

* Another approach to preventing selected shapes from shifting

Prevent fabric objects from shifting to the wrong position when the
active selection contains multiple objects by calculating their
coordinates relative to the canvas, as in the case of the fabric.Group.
2023-10-15 10:11:23 +10:00
Hikaru Y
7cf19ea213
Fix selected shapes shifting to canvas origin (#2729)
* Fix selected shapes shifting to canvas origin

* Make only newly added shape selected even if it...

... overlaps with another
2023-10-13 09:58:43 +10:00
Aristotelis
a7e5d2a663
Change IO text background color to white (#2726)
Co-authored-by: Glutanimate <glutanimate@users.noreply.github.com>
2023-10-13 08:49:31 +10:00
Abdo
9e147c6335
Add text tool to image occlusion (#2705)
* Add text tool to IO

* Remove unnecessary parentheses

* Fix text objects always grouped

* Remove log

* Fix text objects hidden on back side

* Implement text scaling

* Add inverse text outline

* Warn about IO notes with only text objects

This will result in a different error message than the case where no
objects are added at all though, and the user can bypass the warning.
Maybe this is better to avoid discarding the user's work if they have
spent some time adding text.

* Add isValidType

* Use matches!

* Lock aspect ratio of text objects

* Reword misleading comment

The confusion probably comes from the Fabric docs, which apparently need updating: http://fabricjs.com/docs/fabric.Canvas.html#uniformScaling

* Do not count text objects when calculating current index

* Make text objects respond to size changes

* Fix uniform scaling not working when editing

* Use Arial font

* Escape colons and unify parsing

* Handle scale factor when restricting shape to view

* Use 'cloned'

* Add text background

* Tweak drawShape's params
2023-10-12 13:40:11 +10:00
Hikaru Y
b3f6edc323
Fix polygon tool not working (#2712)
* Fix polygon not converting correctly to cloze

* Fix first polygon disappearing when creating se...

...cond one during editing

Previously, a fabric object was passed directly to a `Shape` such as
`Rectangle` or `Polygon`, so mutating a non-primitive property of the
shape would lead to mutating the original fabric object as well.

* Commit addition of polygon immediately

Unlike the rect or ellipse tools, when the polygon tool was active,
clicking on the canvas did not fire the `object:removed` event and the
`change` event was not dispatched. As a result, an addition of a polygon
was not saved to the DB when switching to another note or closing the
editor in edit mode without performing an action that dispatched the
`change` event.
2023-10-10 13:51:35 +10:00
Aristotelis
4cd12ccd28
Refactor IO image pickers into separate component (#2710)
* Refactor IO image pickers into separate component

* Adjust import path

* Move styles to component and tweak class names

* Remove unused import

---------

Co-authored-by: Glutanimate <glutanimate@users.noreply.github.com>
2023-10-10 13:26:20 +10:00
Abdo
bccc5b0995
Fix wrong mask position after merging groups (#2682) 2023-09-26 13:14:13 +10:00
Damien Elmes
91538518b3 Fix "Add" button showing when editing I/O note; hide toast 2023-09-19 14:19:51 +10:00
Damien Elmes
170ab60a52 Remove the separate chevron in all/one selector 2023-09-17 11:51:48 +10:00
Damien Elmes
d441680984 Remove select image button in I/O
Closes #2620
2023-09-17 11:51:48 +10:00
Hikaru Y
3742fa9f0c
Fix some issues with undo/redo in mask editor (#2649)
Issues:
- The `change` event was not dispatched in MaskEditor.svelte when an
undo/redo was performed. Therefore, if the user then closed the editor
or switched to another note without performing an operation that would
cause the `change` event to be dispatched, the undone or redone changes
were not saved to DB.
- When `IOMode.kind === "edit"` (i.e., Edit Current or Browse), the
beginning of the undo history was a blank canvas, not a canvas with
existing masks. Therefore, if you continued to undo to the beginning of
the history, the masks that existed when you opened the editor would be
lost, and they would not be restored even when you performed a redo.
- In the 'Add' dialog, the undo history was not reset when starting to
create a new IO note after adding an IO note.

Also add a small UI improvement:
The undo/redo buttons are now disabled when there is no action to
undo/redo.
2023-09-10 13:26:41 +10:00
Mani
87e2cf7976
fix: reset image button in io note editor (#2602) 2023-08-16 07:47:46 +10:00
Mani
b9da61f993
follow-up pr for io button in note editor (#2600)
* follow-up pr for io button in note editor

* Expose change event in Svelte instead of relying on timeout (dae)
2023-07-31 14:24:26 +10:00
Mani
135de7f9ed
image occlusion button in note editor (#2485)
* setup mask editor in note editor
- add image on mask button click (only one time)
- show hide add button for io on notetype change
- hide field in io notetype
- icon for toggle
and replace image

* add update io notes

* Tidy up i/o notetype check and fix error

- Make it a method on editor
- Use .get(), because the setting doesn't exist on older notetypes
- Pass the bool value into the ts code, instead of the enum

* reset io page after adding

* remove adjust function & add target for mask editor

* handle browse mode & merged sidetoolbar and toptoolbar to toolbar

* fix: shape, button click in browse, dropdown menu

* add arrow to add button

* store for handling visiblity of maskeditor
- remove update  button in edit mode, implement autoupdate

* update var name

* simplify store
2023-07-27 22:45:49 +10:00
Damien Elmes
f3b6deefe9 Combine all backend methods into a single js/d.ts file, like in Python
Easier to import from, and allows us to declare the output of the build
action without having to iterate over all the proto filenames. Have
confirmed it doesn't break esbuild's tree shaking.
2023-07-03 13:46:38 +10:00
Damien Elmes
62c7cdc543 Add scss formatter 2023-07-03 09:44:38 +10:00
Damien Elmes
45f5709214
Migrate to protobuf-es (#2547)
* Fix .no-reduce-motion missing from graphs spinner, and not being honored

* Begin migration from protobuf.js -> protobuf-es

Motivation:

- Protobuf-es has a nicer API: messages are represented as classes, and
fields which should exist are not marked as nullable.
- As it uses modules, only the proto messages we actually use get included
in our bundle output. Protobuf.js put everything in a namespace, which
prevented tree-shaking, and made it awkward to access inner messages.
- ./run after touching a proto file drops from about 8s to 6s on my machine. The tradeoff
is slower decoding/encoding (#2043), but that was mainly a concern for the
graphs page, and was unblocked by
37151213cd

Approach/notes:

- We generate the new protobuf-es interface in addition to existing
protobuf.js interface, so we can migrate a module at a time, starting
with the graphs module.
- rslib:proto now generates RPC methods for TS in addition to the Python
interface. The input-arg-unrolling behaviour of the Python generation is
not required here, as we declare the input arg as a PlainMessage<T>, which
marks it as requiring all fields to be provided.
- i64 is represented as bigint in protobuf-es. We were using a patch to
protobuf.js to get it to output Javascript numbers instead of long.js
types, but now that our supported browser versions support bigint, it's
probably worth biting the bullet and migrating to bigint use. Our IDs
fit comfortably within MAX_SAFE_INTEGER, but that may not hold for future
fields we add.
- Oneofs are handled differently in protobuf-es, and are going to need
some refactoring.

Other notable changes:

- Added a --mkdir arg to our build runner, so we can create a dir easily
during the build on Windows.
- Simplified the preference handling code, by wrapping the preferences
in an outer store, instead of a separate store for each individual
preference. This means a change to one preference will trigger a redraw
of all components that depend on the preference store, but the redrawing
is cheap after moving the data processing to Rust, and it makes the code
easier to follow.
- Drop async(Reactive).ts in favour of more explicit handling with await
blocks/updating.
- Renamed add_inputs_to_group() -> add_dependency(), and fixed it not adding
dependencies to parent groups. Renamed add() -> add_action() for clarity.

* Remove a couple of unused proto imports

* Migrate card info

* Migrate congrats, image occlusion, and tag editor

+ Fix imports for multi-word proto files.

* Migrate change-notetype

* Migrate deck options

* Bump target to es2020; simplify ts lib list

Have used caniuse.com to confirm Chromium 77, iOS 14.5 and the Chrome
on Android support the full es2017-es2020 features.

* Migrate import-csv

* Migrate i18n and fix missing output types in .js

* Migrate custom scheduling, and remove protobuf.js

To mostly maintain our old API contract, we make use of protobuf-es's
ability to convert to JSON, which follows the same format as protobuf.js
did. It doesn't cover all case: users who were previously changing the
variant of a type will need to update their code, as assigning to a new
variant no longer automatically removes the old one, which will cause an
error when we try to convert back from JSON. But I suspect the large majority
of users are adjusting the current variant rather than creating a new one,
and this saves us having to write proxy wrappers, so it seems like a
reasonable compromise.

One other change I made at the same time was to rename value->kind for
the oneofs in our custom study protos, as 'value' was easily confused
with the 'case/value' output that protobuf-es has.

With protobuf.js codegen removed, touching a proto file and invoking
./run drops from about 8s to 6s.

This closes #2043.

* Allow tree-shaking on protobuf types

* Display backend error messages in our ts alert()

* Make sourcemap generation opt-in for ts-run

Considerably slows down build, and not used most of the time.
2023-06-14 22:47:37 +10:00
Damien Elmes
e63b4b9927 Experiment with disabling prettier whitespace sensitivity
Prettier by default tries to preserve whitespace around inline tags,
which can prevent problems such as a space before the period in
'<a>text</a>.':

https://prettier.io/blog/2018/11/07/1.15.0.html#whitespace-sensitive-formatting

Unfortunately only standard HTML block elements are excluded from this
behaviour, so all of our Svelte components are treated the same way, even
if they are block-based, or used in a way where the extra whitespace
doesn't matter. This makes the code somewhat harder to read.

Changing this option does carry the risk that rogue spaces will creep
into our UI in the future as code is formatted, but as there don't appear
to be any such issues with this initial reformat, I think the improved
readability may justify the relatively small risk.
2023-06-01 11:11:26 +10:00
Damien Elmes
7f6c410ca5
Various changes to I/O handling (#2513)
* Store coordinates as ratios of full size

* Use single definition for cappedCanvasSize()

* Move I/O review code into ts/image-occlusion

A bit simpler when it's all in one place.

* Reduce number precision, and round to whole pixels

>>> n=10000
>>> for i in range(1, int(n)): assert i == round(float("%0.4f" % (i/n))*n)

* Minor typing tweak

So, it turns out that typing is mostly broken in ts/image-occlusion.
We're importing from fabric which is a js file without types, so types
like fabric.Canvas are resolving to any.

I first tried switching to `@types/fabric`, which introduced a slew of
typing errors. Wasted a few hours trying to address them, before deciding
to give up on it, since the types were not complete. Then found fabric
has a 6.0 beta that introduces typing, and spent some time with that, but
ran into some new issues as it still seems to be a work in progress.
I think we're probably best off waiting until it's out and stabilized
before sinking more effort into this.

* Refactor (de)serialization of occlusions

To make the code easier to follow/maintain, cloze deletions are now decoded/
encoded into simple data classes, which can then be converted to Fabric objects
and back. The data objects handle converting from absolute/normal positions, and
producing values suitable for writing to text (eg truncated floats).

Various other changes:

- Polygon points are now stored as 'x,y x2,y2 ...' instead of JSON in cloze
divs, as that makes the handling consistent with reading from cloze deletion
text.
- Fixed the reviewer not showing updated placement when a polygon was moved.
- Disabled rotation controls in the editor, since we don't support rotation during
review.
- Renamed hideInactive to occludeInactive, as it wasn't clear whether the former
meant to hide the occlusions, or keep them (hiding the content). It's stored
as 'oi=1' in the cloze text.

* Increase canvas size limit, and double pixels when required.

* Size canvas based on container size

This results in sharper masks when the intrinsic image size is smaller
than the container, and more legible ones when the container is smaller than
the intrinsic image size.

By using the container instead of the viewport, we account for margins,
and when the pixel ratio is 1x, the canvas size and container size should
match.

* Disable zoom animation on editor load

* Default to rectangle when adding new occlusions

* Allow users to add/update notes directly from mask editing page

* The mask editor needs to work with css pixels, not actual pixels

The canvas and image were being scaled too large, which impacted
performance.
2023-05-31 13:45:12 +10:00
Damien Elmes
7686cb8de8
Fix misaligned image occlusions (#2512)
* Cloze styling is not required in I/O notetype

* Use raw string for IO template

* Rename to notetype.css and use more specific ids

* Move internal i/o styling into runtime

Storing it in the notetype makes it difficult to make changes, and
makes it easier for the user to break.

* Fix misaligned occlusions

At larger screen sizes, the canvas was not increasing above its configured
size, so it ended up being placed top center instead of expanding to fit
the entire container area.

To resolve this, both the image and canvas are forced to the container
size, and the container is constrained to the size of the viewport,
with the same aspect ratio as the image.

Closes #2492
2023-05-23 11:59:50 +10:00
Mani
47a9db8221
fix image height issues in iOS safari (#2480)
* use i18n message when not showing image

* fix height for iOS

* some ui styling

* fix polygon draw in panzoom

* more ui styling and fixes
2023-04-26 16:01:04 +10:00
Damien Elmes
f6486da233
Various tweaks to I/O code (#2478)
* Allow user to select I/O notetype instead of enforcing a specific name

* Display a clearer error when I/O note is missing an image

Opening the card layout screen from "manage notetypes" was showing an
error about the Anki version being too old.

Replacement error is not currently translatable.

* Preserve existing notetype when adding I/O notetype

* Add a 'from clipboard' string

The intention is to use this in the future to allow an image occlusion
to be created from an image on the clipboard.

* Tweak I/O init

- Use union type instead of multiple nullable values
- Pass the notetype id in to initialization

* Fix image insertion in I/O note

- The regex expected double quotes, and we were using single ones
- Image tags don't need to be closed

* Use more consistent naming in image_occlusion.proto

* Tweaks to default I/O notetype

- Show the header on the front side as well (I presume this is what
users expect; if not am happy to revert)
- Don't show comments on card (again, I presume users expect to use
this field to add notes that aren't displayed during review, as they
can use back extra for that)

* Fix sticky footer missing background

Caused by earlier CSS refactoring
2023-04-19 15:30:18 +10:00
Mani
2bf134dc72
Feature image occlusion (#2367)
* 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
2023-03-29 12:33:19 +10:00