Commit Graph

37 Commits

Author SHA1 Message Date
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 567ba06b5c Show custom data in stats screen
https://forums.ankiweb.net/t/feature-request-display-custom-data-in-card-info/27187
2023-02-07 12:27:43 +10:00
Damien Elmes ea5153e7a4 Re-enable formatting for .svelte files 2022-11-28 09:17:39 +10:00
Damien Elmes 5e0a761b87
Move away from Bazel (#2202)
(for upgrading users, please see the notes at the bottom)

Bazel brought a lot of nice things to the table, such as rebuilds based on
content changes instead of modification times, caching of build products,
detection of incorrect build rules via a sandbox, and so on. Rewriting the build
in Bazel was also an opportunity to improve on the Makefile-based build we had
prior, which was pretty poor: most dependencies were external or not pinned, and
the build graph was poorly defined and mostly serialized. It was not uncommon
for fresh checkouts to fail due to floating dependencies, or for things to break
when trying to switch to an older commit.

For day-to-day development, I think Bazel served us reasonably well - we could
generally switch between branches while being confident that builds would be
correct and reasonably fast, and not require full rebuilds (except on Windows,
where the lack of a sandbox and the TS rules would cause build breakages when TS
files were renamed/removed).

Bazel achieves that reliability by defining rules for each programming language
that define how source files should be turned into outputs. For the rules to
work with Bazel's sandboxing approach, they often have to reimplement or
partially bypass the standard tools that each programming language provides. The
Rust rules call Rust's compiler directly for example, instead of using Cargo,
and the Python rules extract each PyPi package into a separate folder that gets
added to sys.path.

These separate language rules allow proper declaration of inputs and outputs,
and offer some advantages such as caching of build products and fine-grained
dependency installation. But they also bring some downsides:

- The rules don't always support use-cases/platforms that the standard language
tools do, meaning they need to be patched to be used. I've had to contribute a
number of patches to the Rust, Python and JS rules to unblock various issues.
- The dependencies we use with each language sometimes make assumptions that do
not hold in Bazel, meaning they either need to be pinned or patched, or the
language rules need to be adjusted to accommodate them.

I was hopeful that after the initial setup work, things would be relatively
smooth-sailing. Unfortunately, that has not proved to be the case. Things
frequently broke when dependencies or the language rules were updated, and I
began to get frustrated at the amount of Anki development time I was instead
spending on build system upkeep. It's now about 2 years since switching to
Bazel, and I think it's time to cut losses, and switch to something else that's
a better fit.

The new build system is based on a small build tool called Ninja, and some
custom Rust code in build/. This means that to build Anki, Bazel is no longer
required, but Ninja and Rust need to be installed on your system. Python and
Node toolchains are automatically downloaded like in Bazel.

This new build system should result in faster builds in some cases:

- Because we're using cargo to build now, Rust builds are able to take advantage
of pipelining and incremental debug builds, which we didn't have with Bazel.
It's also easier to override the default linker on Linux/macOS, which can
further improve speeds.
- External Rust crates are now built with opt=1, which improves performance
of debug builds.
- Esbuild is now used to transpile TypeScript, instead of invoking the TypeScript
compiler. This results in faster builds, by deferring typechecking to test/check
time, and by allowing more work to happen in parallel.

As an example of the differences, when testing with the mold linker on Linux,
adding a new message to tags.proto (which triggers a recompile of the bulk of
the Rust and TypeScript code) results in a compile that goes from about 22s on
Bazel to about 7s in the new system. With the standard linker, it's about 9s.

Some other changes of note:

- Our Rust workspace now uses cargo-hakari to ensure all packages agree on
available features, preventing unnecessary rebuilds.
- pylib/anki is now a PEP420 implicit namespace, avoiding the need to merge
source files and generated files into a single folder for running. By telling
VSCode about the extra search path, code completion now works with generated
files without needing to symlink them into the source folder.
- qt/aqt can't use PEP420 as it's difficult to get rid of aqt/__init__.py.
Instead, the generated files are now placed in a separate _aqt package that's
added to the path.
- ts/lib is now exposed as @tslib, so the source code and generated code can be
provided under the same namespace without a merging step.
- MyPy and PyLint are now invoked once for the entire codebase.
- dprint will be used to format TypeScript/json files in the future instead of
the slower prettier (currently turned off to avoid causing conflicts). It can
automatically defer to prettier when formatting Svelte files.
- svelte-check is now used for typechecking our Svelte code, which revealed a
few typing issues that went undetected with the old system.
- The Jest unit tests now work on Windows as well.

If you're upgrading from Bazel, updated usage instructions are in docs/development.md and docs/build.md. A summary of the changes:

- please remove node_modules and .bazel
- install rustup (https://rustup.rs/)
- install rsync if not already installed  (on windows, use pacman - see docs/windows.md)
- install Ninja (unzip from https://github.com/ninja-build/ninja/releases/tag/v1.11.1 and
  place on your path, or from your distro/homebrew if it's 1.10+)
- update .vscode/settings.json from .vscode.dist
2022-11-27 15:24:20 +10:00
Damien Elmes a0e403c3dd Allow passing startup props to setupCardInfo()
Add-ons that use it and don't want the revlog can pass in includeRevlog:false

Issue noticed while addressing https://forums.ankiweb.net/t/card-info-during-review/86/12
in c86da082b4
2022-11-03 11:37:47 +10:00
Matthias Metelka 8142176f84
Introduce new color palette using Sass maps (#2016)
* Remove --medium-border variable

* Implement color palette using Sass maps

I hand-picked the gray tones, the other colors are from the Tailwind CSS v3 palette.

Significant changes:
- light theme is brighter
- dark theme is darker
- borders are softer

I also deleted some platform- and night-mode-specific code.

* Use custom colors for note view switch

* Use same placeholder color for all inputs

* Skew color palette for more dark values

by removing gray[3], which wasn't used anywhere. Slight adjustments were made to the darker tones.

* Adjust frame- window- and border colors

* Give deck browser entries --frame-bg as background color

* Define styling for QComboBox and QLineEdit globally

* Experiment with CSS filter for inline-colors

Inside darker inputs, some colors like dark blue will be hard to read, so we could try to improve text-color contrast with global adjustments depending on the theme.

* Use different map structure for _vars.scss

after @hgiesel's idea: https://github.com/ankitects/anki/pull/2016#discussion_r947087871

* Move custom QLineEdit styles out of searchbar.py

* Merge branch 'main' into color-palette

* Revert QComboBox stylesheet override

* Align gray color palette more with macOS

* Adjust light theme

* Use --slightly-grey-text for options tab color

* Replace gray tones with more neutral values

* Improve categorization of global colors

by renaming almost all of them and sorting them into separate maps.

* Saturate highlight-bg in light theme

* Tweak gray tones

* Adjust box-shadow of EditingArea to make fields look inset

* Add Sass functions to access color palette and semantic variables

in response to https://github.com/ankitects/anki/pull/2016#issuecomment-1220571076

* Showcase use of access functions in several locations

@hgiesel in buttons.scss I access the color palette directly. Is this what you meant by "... keep it local to the component, and possibly make it global at a later time ..."?

* Fix focus box shadow transition and remove default shadow for a cleaner look

I couldn't quite get the inset look the way I wanted, because inset box-shadows do not respect the border radius, therefore causing aliasing.

* Tweak light theme border and shadow colors

* Add functions and colors to base_lib

* Add vars_lib as dependency to base_lib and button_mixins_lib

* Improve uses of default-themed variables

* Use old --frame-bg color and use darker tone for canvas-default

* Return CSS var by default and add palette-of function for raw value

* Showcase use of palette-of function

The #{...} syntax is required only because the use cases are CSS var definitions. In other cases a simple palette-of(keyword, theme) would suffice.

* Light theme: decrease brightness of canvas-default and adjust fg-default

* Use canvas-inset variable for switch knob

* Adjust light theme

* Add back box-shadow to EditingArea

* Light theme: darken background and flatten transition

also set hue and saturation of gray-8 to 0 (like all the other grays).

* Reduce flag colors to single default value

* Tweak card/note accent colors

* Experiment with inset look for fields again

Is this too dark in night mode? It's the same color used for all other text inputs.

* Dark theme: make border-default one shade darker

* Tweak inset shadow color

* Dark theme: make border-faint darker than canvas-default

meaning two shades darker than it currently was.

* Fix PlainTextInput not expanding

* Dark theme: use less saturated flag colors

* Adjust gray tones

* Fix nested variables not getting extracted correctly

* Rename canvas-outset to canvas-elevated

* Light theme: darken canvas-default

* Make canvas-elevated a bit darker

* Rename variables and use them in various components

* Refactor button mixins

* Remove fusion vars from Anki

* Adjust button gradients

* Refactor button mixins

* Fix deck browser table td background color

* Use color function in buttons.scss

* Rework QTabWidget stylesheet

* Fix crash on browser open

* Perfect QTableView header

* Fix bottom toolbar button gradient

* Fix focus outline of bottom toolbar buttons

* Fix custom webview scrollbar

* Fix uses of vars in various webviews

The command @use vars as * lead to repeated inclusion of the CSS vars.

* Enable primary button color with mixin

* Run prettier

* Fix Python code style issues

* Tweak colors

* Lighten scrollbar shades in light theme

* Fix code style issues caused by merge

* Fix harsh border color in editor

caused by leftover --medium-border variables, probably introduced with a merge commit.

* Compile Sass before extracting Python colors/props

This means the Python side doesn't need to worry about the map structure and Sass functions, just copy the output CSS values.

* Desaturate primary button colors by 10%

* Convert accidentally capitalized variable names to lowercase

* Simplify color definitions with qcolor function

* Remove default border-focus variable

* Remove redundant colon

* Apply custom scrollbar CSS only on Windows and Linux

* Make border-subtle color brighter than background in dark theme

* Make border-subtle color a shade brighter in light theme

* Use border-subtle for NoteEditor and EditorToolbar border

* Small patches
2022-09-16 14:11:18 +10:00
RumovZ cff04a288a
Fix card info not updating (#1957)
Update was not triggered if card id didn't change.
2022-07-12 10:34:48 +10:00
Damien Elmes a9769813ba Add back support for custom mountpoint in card stats
The move to separate .html files broke our legacy card stats routine.

Related: d1d71ffdbb
2022-04-15 15:30:05 +10:00
Damien Elmes 6941bccde4 Add support for proto3 optional scalars
Protobuf 3.15 introduced support for marking scalar fields like
uint32 as optional, and all of our tooling appears to support it
now. This allows us to use simple optional/null checks in our Rust/
TypeScript code, without having to resort to an inner message.

I had to apply a minor patch to protobufjs to get this working with
the json-module output; this has also been submitted upstream:
https://github.com/protobufjs/protobuf.js/pull/1693

I've modified CardStatsResponse as an example of the new syntax.

One thing to note: while the Rust and TypeScript bindings use optional/
null fields, as that is the norm in those languages, Google's Python
bindings are not very Pythonic. Referencing an optional field that is
missing will yield the default value, and a separate HasField() call
is required, eg:

```
>>> from anki.stats_pb2 import CardStatsResponse as R
... msg = R.FromString(b"")
... print(msg.first_review)
... print(msg.HasField("first_review"))
0
False
```
2022-02-27 19:42:06 +10:00
Henrik Giesel 5963791d85
Consider using --force-message for ts/protobuf.bzl (#1694)
* Use --force-message in ts/protobuf

* Remove some now unnecessary type assertions in deck-options/lib

* Satisfy formatter
2022-02-27 17:35:07 +10:00
Henrik Giesel 30bbbaf00b
Use eslint for sorting our imports (#1637)
* Make eslint sort our imports

* fix missing deps in eslint rule (dae)

Caught on Linux due to the stricter sandboxing

* Remove exports-last eslint rule (for now?)

* Adjust browserslist settings

- We use ResizeObserver which is not supported in browsers like KaiOS,
  Baidu or Android UC

* Raise minimum iOS version 13.4

- It's the first version that supports ResizeObserver

* Apply new eslint rules to sort imports
2022-02-04 18:36:34 +10:00
Henrik Giesel a8d4774cdb
Add _raw methods for all methods in the backend (#1594)
* Add _bytes methods for all methods in the backend

Expose get_note in qt/aqt/mediasrv.py

* Satisfy formatter

* Rename _bytes function to _raw and have them bytes as input

* Fix backend generation

* Use lib/proto/deckOptions in deck-options

* Add exposed_backend to qt/aqt/mediasrv.py

* Move some more backend methods to exposed_backend_list

* Use protobufjs for congrats and i18n

* Use protobufjs for completeTag

* Use protobufjs services in change-notetype

* Reorder post handlers in alphabetical manner

* Satisfy tests

* Remove unused collection methods

* Rename access_backend to raw_backend_request

* Use _vendor.stringcase instead of creating a new function

* Remove SKIP_UNROLL_OUTPUT

* Directly call _run_command in non _raw methods

* Remove TranslateString, ChangeNotetype and CompleteTag from SKIP_UNROLL_INPUT

* Remove UpdateDeckConfigs from SKIP_UNROLL_INPUT

* Remove ChangeNotetype from SKIP_UNROLL_INPUT

* Remove SKIP_UNROLL_INPUT

* Fix typing issue with translate_string

- Adds typing support for Protobuf maps in genbackend.py

* Do not emit convenience method for protobuf TranslateString
2022-01-21 21:32:39 +10:00
RumovZ 0e06a1c679
Webview margins (#1583)
* Improve side margins in card info screen

* Improve top margin in deck options screen

* Hide revlog time of day on narrow screens

* Remove monospace for now (dae)
2022-01-17 15:04:25 +10:00
Henrik Giesel 478b3a53f1
Remove individual .html files + other refactorings (#1588)
* Move some AddCards specific code to NoteCreator.svelte

* Add new strings for Toggling the Visual / HTML editor

* Set LabelContainer vertical-align to text-top

- Makes them look more centered

* Remove appendInParentheses helper

* Make all ts/*.html files include only module.js and module.css

* Move any JS from .html to index files

* Remove .html files from ts modules

* Remove Python with Starlark implemenation

* Remove reference to non-existing file

* Remove deck-option.html as well

* fix change-notetype screen (dae)
2022-01-16 15:05:35 +10:00
RumovZ 1cee864875
Fix padding and alignment inside revlog table (#1576)
* Use nested tables in revlog

This allows for centered rows, while still preserving internal
alignment.

* Fix hidden columns

* Replace inner tables with flexbox divs

* Replace revlog table with flexbox divs

* Replace flex-gap in revlog

Unsupported on iOS and Qt5.
2022-01-10 12:50:48 +10:00
Damien Elmes 7fcb8cbb62 fix position showing as date in card stats
Fixes #1519
2021-12-02 16:10:29 +10:00
Henrik Giesel ab6a68ec49
Introduce our own Container, Row, and Col components (#1495)
* Refactor out Placeholder from CardInfo.svelte

* Add breakpoint parameter for Container

- Use `Container` component inside `TitledContainer`

* Build Item into Row

- Use Row in DeckOptionsPage instead of just Item

* Reengineer Container/Row/Col CSS

* Inline Badges next to Labels when Lable spans multiple rows

* Adjust margins for mobile

* Implement Col component breakpoints

* Move card-info to use new Container and Row components

* Join StickyHeader and StickyFooter to StickyContainer

* Remove default middle vertical-alignment for Badges again

* Satisfy tests

* Restore inline gutters in change-notetype Mapper

* Add some comment to Col and Container

* Fix breaking behavior in DeckOptionsPage when multi-column

* Add back toolbar left padding to counter-act buttongroup right margins

* Make Label in SwitchRow take more of available space
2021-11-17 13:49:52 +10:00
Damien Elmes d668ac8f7f fix card info layout & test code
Closes #1479

Related: #1470
2021-11-12 16:24:08 +10:00
Damien Elmes fd013f68d2 ensure revlog headers match alignment of columns
+ right-align interval; it looks bad centered
2021-11-02 16:32:09 +10:00
Henrik Giesel 09c29219b4
Several CSS fixes - Editor Cleanup (#1470)
* Refactor editor css, fix editor button highlight

- Avoid using webview.css
- Move more buttons css into button_mixins

* Fix DropdownItem appearance

* Fix the visuals of tags

* Make dropdown font slightly smaller

* Give SelectOption a background color

* Move some css from deck-options-base to CardStateCustomizer

* Avoid using core.scss for CardStats

* Avoid using sass/core in congrats package

* Inline core.scss into webview.scss

* Include fusion-vars for base.scss

* need to keep core.scss around for now (dae)
2021-10-31 08:29:22 +10:00
RumovZ 1c9b5a2e83
Card info cleanup (#1446)
* Cast proto interface to type ...

... instead of using non-null assertions in Revlog.svelte.

* Remove OptionalInt32 and OptionalUInt32
2021-10-23 11:00:43 +10:00
Henrik Giesel 0dff5ea3a3
Use trailingComma: all setting in .prettierrc (#1435) 2021-10-19 09:06:00 +10:00
RumovZ 9b1d53e359 Use `null` for missing stats 2021-10-18 09:36:31 +02:00
RumovZ 0b3b3a5f33 sentCardId -> requestedCardId 2021-10-18 09:12:10 +02:00
RumovZ 8eed005db6 Use `null` for unset cardId 2021-10-18 09:11:00 +02:00
RumovZ dc4f5adc44 Default to `includeRevlog = true` 2021-10-18 09:04:49 +02:00
RumovZ 2a93868922 Center placeholder 2021-10-18 09:01:25 +02:00
RumovZ bbba21126f Improve clarity in card info code a tiny little bit 2021-10-18 09:01:25 +02:00
RumovZ 3c5e149176 Move update logic into CardInfo.svelte
Also use a simpler and faster way to avoid race conditions.
2021-10-18 09:01:24 +02:00
RumovZ 5062024974 Move update logic into CardInfo.svelte 2021-10-18 09:01:24 +02:00
RumovZ 4b5ea6c110 Make CardStats a separate component 2021-10-18 09:01:23 +02:00
RumovZ a47453d5f3 Implement reactively updating Card Info 2021-10-18 09:01:22 +02:00
Damien Elmes bb5053990b pass ts deps into most Svelte packages; remove redundant deps
Henrik, I've left editable/editor alone to avoid causing a conflict;
please add them in your PR instead when you get a chance.
2021-10-18 12:44:31 +10:00
Damien Elmes e8c5802a96 pass sole arg to cardStats as a dictionary
Easier to extend in the future, or (de)serialize in a strongly-typed
language.
2021-10-14 19:28:51 +10:00
Damien Elmes abad6c3844 layout tweaks to card info
- negative margins result in truncated text when the window size
is reduced, so avoid them
- having a 100% table inside a flexbox is not responsive - the table
does not adjust its size as the width is increased or decreased
- in order to look decent on narrow screens (eg phones), we allow
margin collapsing
- in order to look decent on wide screens, we limit the maximum
width to something that is readable
- hide some columns in portrait mode on narrow screens

I tried preserving the centering with margin-left/right: auto, but
could not get it looking right, so have had to move things back to
left alignment.
2021-10-14 19:28:33 +10:00
Damien Elmes 53ce7d2759 support #test in card-info.html
allows us to use scripts/ts-run and ts-watch to test the page
in Chrome by surfing to http://127.0.0.1:40000/_anki/pages/card-info.html#testXXX
2021-10-14 19:23:33 +10:00
RumovZ 3672b0fe73
Switch CardInfoDialog to ts page (#1414)
* Only collect card stats on the backend ...

... instead of rendering an HTML string using askama.

* Add ts page Card Info

* Update test for new `col.card_stats()`

* Remove obsolete CardStats code

* Use new ts page in `CardInfoDialog`

* Align start and end instead of left and right

Curiously, `text-align: start` does not work for `th` tags if assigned
via classes.

* Adopt ts refactorings after rebase

#1405 and #1409

* Clean up `ts/card-info/BUILD.bazel`

* Port card info logic from Rust to TS

* Move repeated field to the top

https://github.com/ankitects/anki/pull/1414#discussion_r725402730

* Convert pseudo classes to interfaces

* CardInfoPage -> CardInfo

* Make revlog in card info optional

* Add legacy support for old card stats

* Check for undefined instead of falsy

* Make Revlog separate component

* drop askama dependency (dae)

* Fix nightmode for legacy card stats
2021-10-14 19:22:47 +10:00