Merge remote-tracking branch 'upstream/HEAD' into apkg

This commit is contained in:
RumovZ 2022-03-31 10:28:16 +02:00
commit bd14ccf2a3
29 changed files with 499 additions and 351 deletions

View file

@ -8,7 +8,8 @@ editing-bold-text = Bold text
editing-cards = Cards editing-cards = Cards
editing-center = Center editing-center = Center
editing-change-color = Change color editing-change-color = Change color
editing-cloze-deletion = Cloze deletion editing-cloze-deletion = Cloze deletion (new card)
editing-cloze-deletion-repeat = Cloze deletion (same card)
editing-couldnt-record-audio-have-you-installed = Couldn't record audio. Have you installed 'lame'? editing-couldnt-record-audio-have-you-installed = Couldn't record audio. Have you installed 'lame'?
editing-customize-card-templates = Customize Card Templates editing-customize-card-templates = Customize Card Templates
editing-customize-fields = Customize Fields editing-customize-fields = Customize Fields

View file

@ -46,6 +46,11 @@ message MediaEntries {
string name = 1; string name = 1;
uint32 size = 2; uint32 size = 2;
bytes sha1 = 3; bytes sha1 = 3;
/// Legacy media maps may include gaps in the media list, so the original
/// file index is recorded when importing from a HashMap. This field is not
/// set when exporting.
optional uint32 legacy_zip_filename = 255;
} }
repeated MediaEntry entries = 1; repeated MediaEntry entries = 1;

View file

@ -224,6 +224,7 @@ def show(mw: aqt.AnkiQt) -> QDialog:
"Matthias Metelka", "Matthias Metelka",
"Sergio Quintero", "Sergio Quintero",
"Nicholas Flint", "Nicholas Flint",
"Daniel Vieira Memoria10X",
) )
) )

View file

@ -1387,7 +1387,7 @@ def set_cloze_button(editor: Editor) -> None:
action = "show" if editor.note.note_type()["type"] == MODEL_CLOZE else "hide" action = "show" if editor.note.note_type()["type"] == MODEL_CLOZE else "hide"
editor.web.eval( editor.web.eval(
'require("anki/ui").loaded.then(() =>' 'require("anki/ui").loaded.then(() =>'
f'require("anki/NoteEditor").instances[0].toolbar.templateButtons.{action}("cloze")' f'require("anki/NoteEditor").instances[0].toolbar.toolbar.{action}("cloze")'
"); " "); "
) )

View file

@ -115,12 +115,12 @@ def register_repos():
################ ################
core_i18n_repo = "anki-core-i18n" core_i18n_repo = "anki-core-i18n"
core_i18n_commit = "bd995b3d74f37975554ebd03d3add4ea82bf663f" core_i18n_commit = "7d1954863a721e09d974c609b55fa78f0e178b0f"
core_i18n_zip_csum = "ace985f858958321d5919731981bce2b9356ea3e8fb43b0232a1dc6f55673f3d" core_i18n_zip_csum = "14cce5d0ecd2c00ce839d735ab7fe979439080ad9c510cc6fc2e63c97a9c745c"
qtftl_i18n_repo = "anki-desktop-ftl" qtftl_i18n_repo = "anki-desktop-ftl"
qtftl_i18n_commit = "5045d3604a20b0ae8ce14be2d3597d72c03ccad8" qtftl_i18n_commit = "31baaae83fad4be3d8977d6053ef3032bdb90481"
qtftl_i18n_zip_csum = "45058ea33cb0e5d142cae8d4e926f5eb3dab4d207e7af0baeafda2b92f765806" qtftl_i18n_zip_csum = "96e42e0278affb2586e677b52b466e6ca8bb4f3fd080a561683c48b483202fa2"
i18n_build_content = """ i18n_build_content = """
filegroup( filegroup(

View file

@ -312,6 +312,7 @@ impl MediaEntry {
name: name.into(), name: name.into(),
size: size.try_into().unwrap_or_default(), size: size.try_into().unwrap_or_default(),
sha1: sha1.into(), sha1: sha1.into(),
legacy_zip_filename: None,
} }
} }
} }

View file

@ -102,16 +102,22 @@ fn restore_media(
let media_entries = extract_media_entries(meta, archive)?; let media_entries = extract_media_entries(meta, archive)?;
std::fs::create_dir_all(media_folder)?; std::fs::create_dir_all(media_folder)?;
for (archive_file_name, entry) in media_entries.iter().enumerate() { for (entry_idx, entry) in media_entries.iter().enumerate() {
if archive_file_name % 10 == 0 { if entry_idx % 10 == 0 {
progress_fn(ImportProgress::Media(archive_file_name))?; progress_fn(ImportProgress::Media(entry_idx))?;
} }
if let Ok(mut zip_file) = archive.by_name(&archive_file_name.to_string()) { let zip_filename = entry
.legacy_zip_filename
.map(|n| n as usize)
.unwrap_or(entry_idx)
.to_string();
if let Ok(mut zip_file) = archive.by_name(&zip_filename) {
maybe_restore_media_file(meta, media_folder, entry, &mut zip_file)?; maybe_restore_media_file(meta, media_folder, entry, &mut zip_file)?;
} else { } else {
return Err(AnkiError::invalid_input(&format!( return Err(AnkiError::invalid_input(&format!(
"{archive_file_name} missing from archive" "{zip_filename} missing from archive"
))); )));
} }
} }
@ -191,27 +197,17 @@ fn extract_media_entries(meta: &Meta, archive: &mut ZipArchive<File>) -> Result<
} }
if meta.media_list_is_hashmap() { if meta.media_list_is_hashmap() {
let map: HashMap<&str, String> = serde_json::from_slice(&buf)?; let map: HashMap<&str, String> = serde_json::from_slice(&buf)?;
let mut entries: Vec<(usize, String)> = map map.into_iter()
.into_iter() .map(|(idx_str, name)| {
.map(|(k, v)| (k.parse().unwrap_or_default(), v)) let idx: u32 = idx_str.parse()?;
.collect(); Ok(MediaEntry {
entries.sort_unstable(); name,
// any gaps in the file numbers would lead to media being imported under the wrong name size: 0,
if entries sha1: vec![],
.iter() legacy_zip_filename: Some(idx),
.enumerate() })
.any(|(idx1, (idx2, _))| idx1 != *idx2)
{
return Err(AnkiError::ImportError(ImportError::Corrupt));
}
Ok(entries
.into_iter()
.map(|(_str_idx, name)| MediaEntry {
name,
size: 0,
sha1: vec![],
}) })
.collect()) .collect()
} else { } else {
let entries: MediaEntries = Message::decode(&*buf)?; let entries: MediaEntries = Message::decode(&*buf)?;
Ok(entries.entries) Ok(entries.entries)

View file

@ -18,9 +18,31 @@ use crate::{
}; };
impl Card { impl Card {
fn schedule_as_new(&mut self, position: u32, reset_counts: bool) { pub(crate) fn original_or_current_due(&self) -> i32 {
self.is_filtered()
.then(|| self.original_due)
.unwrap_or(self.due)
}
pub(crate) fn last_position(&self) -> Option<u32> {
if self.ctype == CardType::New {
Some(self.original_or_current_due() as u32)
} else {
self.original_position
}
}
/// True if the provided position has been used.
/// (Always true, if restore_position is false.)
pub(crate) fn schedule_as_new(
&mut self,
position: u32,
reset_counts: bool,
restore_position: bool,
) -> bool {
let last_position = restore_position.then(|| self.last_position()).flatten();
self.remove_from_filtered_deck_before_reschedule(); self.remove_from_filtered_deck_before_reschedule();
self.due = position as i32; self.due = last_position.unwrap_or(position) as i32;
self.ctype = CardType::New; self.ctype = CardType::New;
self.queue = CardQueue::New; self.queue = CardQueue::New;
self.interval = 0; self.interval = 0;
@ -30,6 +52,8 @@ impl Card {
self.reps = 0; self.reps = 0;
self.lapses = 0; self.lapses = 0;
} }
last_position.is_none()
} }
/// If the card is new, change its position, and return true. /// If the card is new, change its position, and return true.
@ -135,10 +159,7 @@ impl Collection {
let cards = col.storage.all_searched_cards_in_search_order()?; let cards = col.storage.all_searched_cards_in_search_order()?;
for mut card in cards { for mut card in cards {
let original = card.clone(); let original = card.clone();
if restore_position && card.original_position.is_some() { if card.schedule_as_new(position, reset_counts, restore_position) {
card.schedule_as_new(card.original_position.unwrap(), reset_counts);
} else {
card.schedule_as_new(position, reset_counts);
position += 1; position += 1;
} }
if log { if log {
@ -301,6 +322,43 @@ mod test {
} }
unreachable!("not random"); unreachable!("not random");
} }
#[test]
fn last_position() {
// new card
let mut card = Card::new(NoteId(0), 0, DeckId(1), 42);
assert_eq!(card.last_position(), Some(42));
// in filtered deck
card.original_deck_id.0 = 1;
card.deck_id.0 = 2;
card.original_due = 42;
card.due = 123456789;
card.queue = CardQueue::Review;
assert_eq!(card.last_position(), Some(42));
// graduated card
let mut card = Card::new(NoteId(0), 0, DeckId(1), 42);
card.queue = CardQueue::Review;
card.ctype = CardType::Review;
card.due = 123456789;
// only recent clients remember the original position
assert_eq!(card.last_position(), None);
card.original_position = Some(42);
assert_eq!(card.last_position(), Some(42));
}
#[test]
fn scheduling_as_new() {
let mut card = Card::new(NoteId(0), 0, DeckId(1), 42);
card.reps = 4;
card.lapses = 2;
// keep counts and position
card.schedule_as_new(1, false, true);
assert_eq!((card.due, card.reps, card.lapses), (42, 4, 2));
// complete reset
card.schedule_as_new(1, true, false);
assert_eq!((card.due, card.reps, card.lapses), (1, 0, 0));
}
} }
impl From<NewCardInsertOrder> for NewCardDueOrder { impl From<NewCardInsertOrder> for NewCardDueOrder {

View file

@ -35,3 +35,11 @@ alias(
name = "node", name = "node",
actual = "@nodejs//:node", actual = "@nodejs//:node",
) )
filegroup(
name = "ts",
srcs = [
"//ts/icons",
],
visibility = ["//ts:__subpackages__"],
)

View file

@ -47,6 +47,7 @@ _esbuild_deps = [
"//sass:button_mixins_lib", "//sass:button_mixins_lib",
"@npm//@mdi", "@npm//@mdi",
"@npm//bootstrap-icons", "@npm//bootstrap-icons",
"//ts/icons",
"@npm//protobufjs", "@npm//protobufjs",
] ]

View file

@ -4,18 +4,10 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
--> -->
<script context="module" lang="ts"> <script context="module" lang="ts">
import { CustomElementArray } from "../editable/decorated"; import { CustomElementArray } from "../editable/decorated";
import contextProperty from "../sveltelib/context-property";
const decoratedElements = new CustomElementArray(); const decoratedElements = new CustomElementArray();
const key = Symbol("decoratedElements"); export { decoratedElements };
const [context, setContextProperty] = contextProperty<CustomElementArray>(key);
export { context };
</script>
<script lang="ts">
setContextProperty(decoratedElements);
</script> </script>
<slot /> <slot />

View file

@ -2,11 +2,10 @@
Copyright: Ankitects Pty Ltd and contributors Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
--> -->
<script lang="ts"> <script lang="ts" context="module">
import { Mathjax } from "../editable/mathjax-element"; import { Mathjax } from "../editable/mathjax-element";
import { context } from "./DecoratedElements.svelte"; import { decoratedElements } from "./DecoratedElements.svelte";
const decoratedElements = context.get();
decoratedElements.push(Mathjax); decoratedElements.push(Mathjax);
import { parsingInstructions } from "./plain-text-input"; import { parsingInstructions } from "./plain-text-input";

View file

@ -12,7 +12,6 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
} from "../../components/ButtonGroupItem.svelte"; } from "../../components/ButtonGroupItem.svelte";
import DynamicallySlottable from "../../components/DynamicallySlottable.svelte"; import DynamicallySlottable from "../../components/DynamicallySlottable.svelte";
import IconButton from "../../components/IconButton.svelte"; import IconButton from "../../components/IconButton.svelte";
import Item from "../../components/Item.svelte";
import Shortcut from "../../components/Shortcut.svelte"; import Shortcut from "../../components/Shortcut.svelte";
import WithDropdown from "../../components/WithDropdown.svelte"; import WithDropdown from "../../components/WithDropdown.svelte";
import { getListItem } from "../../lib/dom"; import { getListItem } from "../../lib/dom";
@ -92,73 +91,69 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
</IconButton> </IconButton>
<ButtonDropdown> <ButtonDropdown>
<Item id="justify"> <ButtonGroup>
<ButtonGroup> <CommandIconButton
<CommandIconButton key="justifyLeft"
key="justifyLeft" tooltip={tr.editingAlignLeft()}
tooltip={tr.editingAlignLeft()} --border-left-radius="5px"
--border-left-radius="5px" --border-right-radius="0px"
--border-right-radius="0px" >{@html justifyLeftIcon}</CommandIconButton
>{@html justifyLeftIcon}</CommandIconButton >
>
<CommandIconButton <CommandIconButton
key="justifyCenter" key="justifyCenter"
tooltip={tr.editingCenter()} tooltip={tr.editingCenter()}
>{@html justifyCenterIcon}</CommandIconButton >{@html justifyCenterIcon}</CommandIconButton
> >
<CommandIconButton <CommandIconButton
key="justifyRight" key="justifyRight"
tooltip={tr.editingAlignRight()} tooltip={tr.editingAlignRight()}
>{@html justifyRightIcon}</CommandIconButton >{@html justifyRightIcon}</CommandIconButton
> >
<CommandIconButton <CommandIconButton
key="justifyFull" key="justifyFull"
tooltip={tr.editingJustify()} tooltip={tr.editingJustify()}
--border-right-radius="5px" --border-right-radius="5px"
>{@html justifyFullIcon}</CommandIconButton >{@html justifyFullIcon}</CommandIconButton
> >
</ButtonGroup> </ButtonGroup>
</Item>
<Item id="indentation"> <ButtonGroup>
<ButtonGroup> <IconButton
<IconButton tooltip="{tr.editingOutdent()} ({getPlatformString(
tooltip="{tr.editingOutdent()} ({getPlatformString( outdentKeyCombination,
outdentKeyCombination, )})"
)})" {disabled}
{disabled} on:click={outdentListItem}
on:click={outdentListItem} --border-left-radius="5px"
--border-left-radius="5px" --border-right-radius="0px"
--border-right-radius="0px" >
> {@html outdentIcon}
{@html outdentIcon} </IconButton>
</IconButton>
<Shortcut <Shortcut
keyCombination={outdentKeyCombination} keyCombination={outdentKeyCombination}
on:action={outdentListItem} on:action={outdentListItem}
/> />
<IconButton <IconButton
tooltip="{tr.editingIndent()} ({getPlatformString( tooltip="{tr.editingIndent()} ({getPlatformString(
indentKeyCombination, indentKeyCombination,
)})" )})"
{disabled} {disabled}
on:click={indentListItem} on:click={indentListItem}
--border-right-radius="5px" --border-right-radius="5px"
> >
{@html indentIcon} {@html indentIcon}
</IconButton> </IconButton>
<Shortcut <Shortcut
keyCombination={indentKeyCombination} keyCombination={indentKeyCombination}
on:action={indentListItem} on:action={indentListItem}
/> />
</ButtonGroup> </ButtonGroup>
</Item>
</ButtonDropdown> </ButtonDropdown>
</WithDropdown> </WithDropdown>
</ButtonGroupItem> </ButtonGroupItem>

View file

@ -5,18 +5,24 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
<script lang="ts"> <script lang="ts">
import { get } from "svelte/store"; import { get } from "svelte/store";
import ButtonGroup from "../../components/ButtonGroup.svelte";
import IconButton from "../../components/IconButton.svelte"; import IconButton from "../../components/IconButton.svelte";
import Shortcut from "../../components/Shortcut.svelte"; import Shortcut from "../../components/Shortcut.svelte";
import * as tr from "../../lib/ftl"; import * as tr from "../../lib/ftl";
import { isApplePlatform } from "../../lib/platform";
import { getPlatformString } from "../../lib/shortcuts"; import { getPlatformString } from "../../lib/shortcuts";
import { wrapInternal } from "../../lib/wrap"; import { wrapInternal } from "../../lib/wrap";
import { context as noteEditorContext } from "../NoteEditor.svelte"; import { context as noteEditorContext } from "../NoteEditor.svelte";
import type { RichTextInputAPI } from "../rich-text-input"; import type { RichTextInputAPI } from "../rich-text-input";
import { editingInputIsRichText } from "../rich-text-input"; import { editingInputIsRichText } from "../rich-text-input";
import { ellipseIcon } from "./icons"; import { clozeIcon, incrementClozeIcon } from "./icons";
const { focusedInput, fields } = noteEditorContext.get(); const { focusedInput, fields } = noteEditorContext.get();
// Workaround for Cmd+Option+Shift+C not working on macOS. The keyup approach works
// on Linux as well, but fails on Windows.
const event = isApplePlatform() ? "keyup" : "keydown";
const clozePattern = /\{\{c(\d+)::/gu; const clozePattern = /\{\{c(\d+)::/gu;
function getCurrentHighestCloze(increment: boolean): number { function getCurrentHighestCloze(increment: boolean): number {
let highest = 0; let highest = 0;
@ -44,27 +50,54 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
$: richTextAPI = $focusedInput as RichTextInputAPI; $: richTextAPI = $focusedInput as RichTextInputAPI;
async function onCloze(event: KeyboardEvent | MouseEvent): Promise<void> { async function onIncrementCloze(): Promise<void> {
const highestCloze = getCurrentHighestCloze(!event.getModifierState("Alt"));
const richText = await richTextAPI.element; const richText = await richTextAPI.element;
const highestCloze = getCurrentHighestCloze(true);
wrapInternal(richText, `{{c${highestCloze}::`, "}}", false);
}
async function onSameCloze(): Promise<void> {
const richText = await richTextAPI.element;
const highestCloze = getCurrentHighestCloze(false);
wrapInternal(richText, `{{c${highestCloze}::`, "}}", false); wrapInternal(richText, `{{c${highestCloze}::`, "}}", false);
} }
$: disabled = !editingInputIsRichText($focusedInput); $: disabled = !editingInputIsRichText($focusedInput);
const keyCombination = "Control+Alt?+Shift+C"; const incrementKeyCombination = "Control+Shift+C";
const sameKeyCombination = "Control+Alt+Shift+C";
</script> </script>
<IconButton <ButtonGroup>
tooltip="{tr.editingClozeDeletion()} {getPlatformString(keyCombination)}" <IconButton
{disabled} tooltip="{tr.editingClozeDeletion()} ({getPlatformString(
on:click={onCloze} incrementKeyCombination,
> )})"
{@html ellipseIcon} {disabled}
</IconButton> on:click={onIncrementCloze}
--border-left-radius="5px"
>
{@html incrementClozeIcon}
</IconButton>
<Shortcut <Shortcut
{keyCombination} keyCombination={incrementKeyCombination}
event="keyup" {event}
on:action={(event) => onCloze(event.detail.originalEvent)} on:action={onIncrementCloze}
/> />
<IconButton
tooltip="{tr.editingClozeDeletionRepeat()} ({getPlatformString(
sameKeyCombination,
)})"
{disabled}
on:click={onSameCloze}
--border-right-radius="5px"
>
{@html clozeIcon}
</IconButton>
<Shortcut keyCombination={sameKeyCombination} {event} on:action={onSameCloze} />
</ButtonGroup>

View file

@ -56,6 +56,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import Item from "../../components/Item.svelte"; import Item from "../../components/Item.svelte";
import StickyContainer from "../../components/StickyContainer.svelte"; import StickyContainer from "../../components/StickyContainer.svelte";
import BlockButtons from "./BlockButtons.svelte"; import BlockButtons from "./BlockButtons.svelte";
import ClozeButtons from "./ClozeButtons.svelte";
import InlineButtons from "./InlineButtons.svelte"; import InlineButtons from "./InlineButtons.svelte";
import NotetypeButtons from "./NotetypeButtons.svelte"; import NotetypeButtons from "./NotetypeButtons.svelte";
import TemplateButtons from "./TemplateButtons.svelte"; import TemplateButtons from "./TemplateButtons.svelte";
@ -105,6 +106,10 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
<Item id="template"> <Item id="template">
<TemplateButtons api={templateButtons} /> <TemplateButtons api={templateButtons} />
</Item> </Item>
<Item id="cloze">
<ClozeButtons />
</Item>
</DynamicallySlottable> </DynamicallySlottable>
</ButtonToolbar> </ButtonToolbar>
</StickyContainer> </StickyContainer>

View file

@ -20,7 +20,6 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { context } from "../NoteEditor.svelte"; import { context } from "../NoteEditor.svelte";
import { setFormat } from "../old-editor-adapter"; import { setFormat } from "../old-editor-adapter";
import { editingInputIsRichText } from "../rich-text-input"; import { editingInputIsRichText } from "../rich-text-input";
import ClozeButton from "./ClozeButton.svelte";
import { micIcon, paperclipIcon } from "./icons"; import { micIcon, paperclipIcon } from "./icons";
import LatexButton from "./LatexButton.svelte"; import LatexButton from "./LatexButton.svelte";
@ -41,7 +40,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
} }
[mediaPromise, resolve] = promiseWithResolver<string>(); [mediaPromise, resolve] = promiseWithResolver<string>();
$focusedInput.focusHandler.focus.on( $focusedInput.editable.focusHandler.focus.on(
async () => setFormat("inserthtml", await mediaPromise), async () => setFormat("inserthtml", await mediaPromise),
{ once: true }, { once: true },
); );
@ -61,7 +60,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
} }
[mediaPromise, resolve] = promiseWithResolver<string>(); [mediaPromise, resolve] = promiseWithResolver<string>();
$focusedInput.focusHandler.focus.on( $focusedInput.editable.focusHandler.focus.on(
async () => setFormat("inserthtml", await mediaPromise), async () => setFormat("inserthtml", await mediaPromise),
{ once: true }, { once: true },
); );
@ -116,10 +115,6 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
/> />
</ButtonGroupItem> </ButtonGroupItem>
<ButtonGroupItem id="cloze">
<ClozeButton />
</ButtonGroupItem>
<ButtonGroupItem> <ButtonGroupItem>
<LatexButton /> <LatexButton />
</ButtonGroupItem> </ButtonGroupItem>

View file

@ -24,7 +24,8 @@ export { default as underlineIcon } from "bootstrap-icons/icons/type-underline.s
export const arrowIcon = export const arrowIcon =
'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="transparent" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2 5l6 6 6-6"/></svg>'; '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill="transparent" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2 5l6 6 6-6"/></svg>';
export { default as ellipseIcon } from "@mdi/svg/svg/contain.svg"; export { default as incrementClozeIcon } from "../../icons/contain-plus.svg";
export { default as clozeIcon } from "@mdi/svg/svg/contain.svg";
export { default as functionIcon } from "@mdi/svg/svg/function-variant.svg"; export { default as functionIcon } from "@mdi/svg/svg/function-variant.svg";
export { default as paperclipIcon } from "@mdi/svg/svg/paperclip.svg"; export { default as paperclipIcon } from "@mdi/svg/svg/paperclip.svg";
export { default as micIcon } from "bootstrap-icons/icons/mic.svg"; export { default as micIcon } from "bootstrap-icons/icons/mic.svg";

View file

@ -17,7 +17,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import MathjaxMenu from "./MathjaxMenu.svelte"; import MathjaxMenu from "./MathjaxMenu.svelte";
const { container, api } = context.get(); const { container, api } = context.get();
const { focusHandler, preventResubscription } = api; const { editable, preventResubscription } = api;
const code = writable(""); const code = writable("");
@ -41,7 +41,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
let selectAll = false; let selectAll = false;
function placeHandle(after: boolean): void { function placeHandle(after: boolean): void {
focusHandler.flushCaret(); editable.focusHandler.flushCaret();
if (after) { if (after) {
(mathjaxElement as any).placeCaretAfter(); (mathjaxElement as any).placeCaretAfter();

View file

@ -30,15 +30,14 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { onMount, tick } from "svelte"; import { onMount, tick } from "svelte";
import { writable } from "svelte/store"; import { writable } from "svelte/store";
import { singleCallback } from "../../lib/typing";
import { pageTheme } from "../../sveltelib/theme"; import { pageTheme } from "../../sveltelib/theme";
import { baseOptions, gutterOptions, htmlanki } from "../code-mirror"; import { baseOptions, gutterOptions, htmlanki } from "../code-mirror";
import CodeMirror from "../CodeMirror.svelte"; import CodeMirror from "../CodeMirror.svelte";
import { context as decoratedElementsContext } from "../DecoratedElements.svelte";
import { context as editingAreaContext } from "../EditingArea.svelte"; import { context as editingAreaContext } from "../EditingArea.svelte";
import { context as noteEditorContext } from "../NoteEditor.svelte"; import { context as noteEditorContext } from "../NoteEditor.svelte";
import removeProhibitedTags from "./remove-prohibited"; import removeProhibitedTags from "./remove-prohibited";
import { storedToUndecorated, undecoratedToStored } from "./transform";
export let hidden = false;
const configuration = { const configuration = {
mode: htmlanki, mode: htmlanki,
@ -49,31 +48,36 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
const { focusedInput } = noteEditorContext.get(); const { focusedInput } = noteEditorContext.get();
const { editingInputs, content } = editingAreaContext.get(); const { editingInputs, content } = editingAreaContext.get();
const decoratedElements = decoratedElementsContext.get();
const code = writable($content); const code = writable($content);
function focus(): void { let codeMirror = {} as CodeMirrorAPI;
codeMirror.editor.then((editor) => editor.focus());
async function focus(): Promise<void> {
const editor = await codeMirror.editor;
editor.focus();
} }
function moveCaretToEnd(): void { async function moveCaretToEnd(): Promise<void> {
codeMirror.editor.then((editor) => editor.setCursor(editor.lineCount(), 0)); const editor = await codeMirror.editor;
editor.setCursor(editor.lineCount(), 0);
} }
function refocus(): void { async function refocus(): Promise<void> {
codeMirror.editor.then((editor) => (editor as any).display.input.blur()); const editor = (await codeMirror.editor) as any;
editor.display.input.blur();
focus(); focus();
moveCaretToEnd(); moveCaretToEnd();
} }
export let hidden = false;
function toggle(): boolean { function toggle(): boolean {
hidden = !hidden; hidden = !hidden;
return hidden; return hidden;
} }
let codeMirror = {} as CodeMirrorAPI; export const api: PlainTextInputAPI = {
export const api = {
name: "plain-text", name: "plain-text",
focus, focus,
focusable: !hidden, focusable: !hidden,
@ -81,47 +85,46 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
refocus, refocus,
toggle, toggle,
codeMirror, codeMirror,
} as PlainTextInputAPI; };
function pushUpdate(): void { /**
api.focusable = !hidden; * Communicate to editing area that input is not focusable
*/
function pushUpdate(isFocusable: boolean): void {
api.focusable = isFocusable;
$editingInputs = $editingInputs; $editingInputs = $editingInputs;
} }
function refresh(): void { async function refresh(): Promise<void> {
codeMirror.editor.then((editor) => editor.refresh()); const editor = await codeMirror.editor;
editor.refresh();
} }
$: { $: {
hidden; pushUpdate(!hidden);
tick().then(refresh); tick().then(refresh);
pushUpdate();
} }
function storedToUndecorated(html: string): string { function onChange({ detail: html }: CustomEvent<string>): void {
return decoratedElements.toUndecorated(html); code.set(removeProhibitedTags(html));
}
function undecoratedToStored(html: string): string {
return decoratedElements.toStored(html);
} }
onMount(() => { onMount(() => {
$editingInputs.push(api); $editingInputs.push(api);
$editingInputs = $editingInputs; $editingInputs = $editingInputs;
const unsubscribeFromEditingArea = content.subscribe((value: string): void => { return singleCallback(
code.set(storedToUndecorated(value)); content.subscribe((html: string): void =>
}); /* We call `removeProhibitedTags` here, because content might
* have been changed outside the editor, and we need to parse
const unsubscribeToEditingArea = code.subscribe((value: string): void => { * it to get the "neutral" value. Otherwise, there might be
content.set(removeProhibitedTags(undecoratedToStored(value))); * conflicts with other editing inputs */
}); code.set(removeProhibitedTags(storedToUndecorated(html))),
),
return () => { code.subscribe((html: string): void =>
unsubscribeFromEditingArea(); content.set(undecoratedToStored(html)),
unsubscribeToEditingArea(); ),
}; );
}); });
setupLifecycleHooks(api); setupLifecycleHooks(api);
@ -133,12 +136,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
class:hidden class:hidden
on:focusin={() => ($focusedInput = api)} on:focusin={() => ($focusedInput = api)}
> >
<CodeMirror <CodeMirror {configuration} {code} bind:api={codeMirror} on:change={onChange} />
{configuration}
{code}
bind:api={codeMirror}
on:change={({ detail: html }) => code.set(removeProhibitedTags(html))}
/>
</div> </div>
<style lang="scss"> <style lang="scss">

View file

@ -1,16 +1,9 @@
// Copyright: Ankitects Pty Ltd and contributors // Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html // License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
const parser = new DOMParser(); import { createDummyDoc } from "../../lib/parsing";
function createDummyDoc(html: string): string { const parser = new DOMParser();
return (
"<html><head></head><body>" +
// parsingInstructions.join("") +
html +
"</body>"
);
}
function removeTag(element: HTMLElement, tagName: string): void { function removeTag(element: HTMLElement, tagName: string): void {
for (const elem of element.getElementsByTagName(tagName)) { for (const elem of element.getElementsByTagName(tagName)) {

View file

@ -0,0 +1,12 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { decoratedElements } from "../DecoratedElements.svelte";
export function storedToUndecorated(html: string): string {
return decoratedElements.toUndecorated(html);
}
export function undecoratedToStored(html: string): string {
return decoratedElements.toStored(html);
}

View file

@ -3,8 +3,8 @@ Copyright: Ankitects Pty Ltd and contributors
License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
--> -->
<script context="module" lang="ts"> <script context="module" lang="ts">
import type { FocusHandlerAPI } from "../../editable/content-editable";
import type { ContentEditableAPI } from "../../editable/ContentEditable.svelte"; import type { ContentEditableAPI } from "../../editable/ContentEditable.svelte";
import { singleCallback } from "../../lib/typing";
import useContextProperty from "../../sveltelib/context-property"; import useContextProperty from "../../sveltelib/context-property";
import useDOMMirror from "../../sveltelib/dom-mirror"; import useDOMMirror from "../../sveltelib/dom-mirror";
import type { InputHandlerAPI } from "../../sveltelib/input-handler"; import type { InputHandlerAPI } from "../../sveltelib/input-handler";
@ -13,15 +13,14 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type { EditingInputAPI } from "../EditingArea.svelte"; import type { EditingInputAPI } from "../EditingArea.svelte";
import type CustomStyles from "./CustomStyles.svelte"; import type CustomStyles from "./CustomStyles.svelte";
export interface RichTextInputAPI extends EditingInputAPI, ContentEditableAPI { export interface RichTextInputAPI extends EditingInputAPI {
name: "rich-text"; name: "rich-text";
shadowRoot: Promise<ShadowRoot>;
element: Promise<HTMLElement>; element: Promise<HTMLElement>;
moveCaretToEnd(): void; moveCaretToEnd(): void;
toggle(): boolean; toggle(): boolean;
preventResubscription(): () => void; preventResubscription(): () => void;
inputHandler: InputHandlerAPI; inputHandler: InputHandlerAPI;
focusHandler: FocusHandlerAPI; editable: ContentEditableAPI;
} }
export function editingInputIsRichText( export function editingInputIsRichText(
@ -49,198 +48,102 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { placeCaretAfterContent } from "../../domlib/place-caret"; import { placeCaretAfterContent } from "../../domlib/place-caret";
import ContentEditable from "../../editable/ContentEditable.svelte"; import ContentEditable from "../../editable/ContentEditable.svelte";
import type { DecoratedElement } from "../../editable/decorated";
import { bridgeCommand } from "../../lib/bridgecommand";
import {
fragmentToString,
nodeContainsInlineContent,
nodeIsElement,
} from "../../lib/dom";
import { on } from "../../lib/events";
import { promiseWithResolver } from "../../lib/promise";
import { nodeStore } from "../../sveltelib/node-store";
import { context as decoratedElementsContext } from "../DecoratedElements.svelte";
import { context as editingAreaContext } from "../EditingArea.svelte"; import { context as editingAreaContext } from "../EditingArea.svelte";
import { context as noteEditorContext } from "../NoteEditor.svelte"; import { context as noteEditorContext } from "../NoteEditor.svelte";
import getNormalizingNodeStore from "./normalizing-node-store";
import useRichTextResolve from "./rich-text-resolve";
import RichTextStyles from "./RichTextStyles.svelte"; import RichTextStyles from "./RichTextStyles.svelte";
import SetContext from "./SetContext.svelte"; import SetContext from "./SetContext.svelte";
import { fragmentToStored, storedToFragment } from "./transform";
export let hidden: boolean; export let hidden: boolean;
const { focusedInput } = noteEditorContext.get(); const { focusedInput } = noteEditorContext.get();
const { content, editingInputs } = editingAreaContext.get(); const { content, editingInputs } = editingAreaContext.get();
const decoratedElements = decoratedElementsContext.get();
function normalizeFragment(fragment: DocumentFragment): void {
fragment.normalize();
for (const decorated of decoratedElements) {
for (const element of fragment.querySelectorAll(
decorated.tagName,
) as NodeListOf<DecoratedElement>) {
element.undecorate();
}
}
}
const nodes = nodeStore<DocumentFragment>(undefined, normalizeFragment);
function adjustInputHTML(html: string): string {
for (const component of decoratedElements) {
html = component.toUndecorated(html);
}
return html;
}
function adjustInputFragment(fragment: DocumentFragment): void {
if (nodeContainsInlineContent(fragment)) {
fragment.appendChild(document.createElement("br"));
}
}
function writeFromEditingArea(html: string): void {
/* We need .createContextualFragment so that customElements are initialized */
const fragment = document
.createRange()
.createContextualFragment(adjustInputHTML(html));
adjustInputFragment(fragment);
nodes.setUnprocessed(fragment);
}
function adjustOutputFragment(fragment: DocumentFragment): void {
if (
fragment.hasChildNodes() &&
nodeIsElement(fragment.lastChild!) &&
nodeContainsInlineContent(fragment) &&
fragment.lastChild!.tagName === "BR"
) {
fragment.lastChild!.remove();
}
}
function adjustOutputHTML(html: string): string {
for (const component of decoratedElements) {
html = component.toStored(html);
}
return html;
}
function writeToEditingArea(fragment: DocumentFragment): void {
const clone = document.importNode(fragment, true);
adjustOutputFragment(clone);
const output = adjustOutputHTML(fragmentToString(clone));
content.set(output);
}
const [shadowPromise, shadowResolve] = promiseWithResolver<ShadowRoot>();
function attachShadow(element: Element): void {
shadowResolve(element.attachShadow({ mode: "open" }));
}
const [richTextPromise, richTextResolve] = promiseWithResolver<HTMLElement>();
function resolve(richTextInput: HTMLElement): { destroy: () => void } {
function onPaste(event: Event): void {
event.preventDefault();
bridgeCommand("paste");
}
function onCutOrCopy(): void {
bridgeCommand("cutOrCopy");
}
const removePaste = on(richTextInput, "paste", onPaste);
const removeCopy = on(richTextInput, "copy", onCutOrCopy);
const removeCut = on(richTextInput, "cut", onCutOrCopy);
richTextResolve(richTextInput);
return {
destroy() {
removePaste();
removeCopy();
removeCut();
},
};
}
const nodes = getNormalizingNodeStore();
const [richTextPromise, resolve] = useRichTextResolve();
const { mirror, preventResubscription } = useDOMMirror(); const { mirror, preventResubscription } = useDOMMirror();
const [inputHandler, setupInputHandler] = useInputHandler(); const [inputHandler, setupInputHandler] = useInputHandler();
function moveCaretToEnd() { export function attachShadow(element: Element): void {
richTextPromise.then(placeCaretAfterContent); element.attachShadow({ mode: "open" });
} }
export const api = { async function moveCaretToEnd(): Promise<void> {
const richText = await richTextPromise;
placeCaretAfterContent(richText);
}
async function focus(): Promise<void> {
const richText = await richTextPromise;
richText.focus();
}
async function refocus(): Promise<void> {
const richText = await richTextPromise;
richText.blur();
richText.focus();
moveCaretToEnd();
}
function toggle(): boolean {
hidden = !hidden;
return hidden;
}
export const api: RichTextInputAPI = {
name: "rich-text", name: "rich-text",
shadowRoot: shadowPromise,
element: richTextPromise, element: richTextPromise,
focus() { focus,
richTextPromise.then((richText) => { refocus,
richText.focus();
});
},
refocus() {
richTextPromise.then((richText) => {
richText.blur();
richText.focus();
moveCaretToEnd();
});
},
focusable: !hidden, focusable: !hidden,
toggle(): boolean { toggle,
hidden = !hidden;
return hidden;
},
moveCaretToEnd, moveCaretToEnd,
preventResubscription, preventResubscription,
inputHandler, inputHandler,
} as RichTextInputAPI; editable: {} as ContentEditableAPI,
};
const allContexts = getAllContexts(); const allContexts = getAllContexts();
function attachContentEditable(element: Element, { stylesDidLoad }): void { function attachContentEditable(element: Element, { stylesDidLoad }): void {
stylesDidLoad.then( (async () => {
() => await stylesDidLoad;
new ContentEditable({
target: element.shadowRoot, new ContentEditable({
props: { target: element.shadowRoot!,
nodes, props: {
resolve, nodes,
mirrors: [mirror], resolve,
inputHandlers: [setupInputHandler, setupGlobalInputHandler], mirrors: [mirror],
api, inputHandlers: [setupInputHandler, setupGlobalInputHandler],
}, api: api.editable,
context: allContexts, },
}), context: allContexts,
); });
})();
} }
function pushUpdate(): void { function pushUpdate(isFocusable: boolean): void {
api.focusable = !hidden; api.focusable = isFocusable;
$editingInputs = $editingInputs; $editingInputs = $editingInputs;
} }
$: { $: pushUpdate(!hidden);
hidden;
pushUpdate();
}
onMount(() => { onMount(() => {
$editingInputs.push(api); $editingInputs.push(api);
$editingInputs = $editingInputs; $editingInputs = $editingInputs;
const unsubscribeFromEditingArea = content.subscribe(writeFromEditingArea); return singleCallback(
const unsubscribeToEditingArea = nodes.subscribe(writeToEditingArea); content.subscribe((html: string): void =>
nodes.setUnprocessed(storedToFragment(html)),
return () => { ),
unsubscribeFromEditingArea(); nodes.subscribe((fragment: DocumentFragment): void =>
unsubscribeToEditingArea(); content.set(fragmentToStored(fragment)),
}; ),
);
}); });
</script> </script>

View file

@ -0,0 +1,25 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import type { DecoratedElement } from "../../editable/decorated";
import type { NodeStore } from "../../sveltelib/node-store";
import { nodeStore } from "../../sveltelib/node-store";
import { decoratedElements } from "../DecoratedElements.svelte";
function normalizeFragment(fragment: DocumentFragment): void {
fragment.normalize();
for (const decorated of decoratedElements) {
for (const element of fragment.querySelectorAll(
decorated.tagName,
) as NodeListOf<DecoratedElement>) {
element.undecorate();
}
}
}
function getStore(): NodeStore<DocumentFragment> {
return nodeStore<DocumentFragment>(undefined, normalizeFragment);
}
export default getStore;

View file

@ -0,0 +1,43 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import { bridgeCommand } from "../../lib/bridgecommand";
import { on } from "../../lib/events";
import { promiseWithResolver } from "../../lib/promise";
function bridgeCopyPasteCommands(input: HTMLElement): { destroy(): void } {
function onPaste(event: Event): void {
event.preventDefault();
bridgeCommand("paste");
}
function onCutOrCopy(): void {
bridgeCommand("cutOrCopy");
}
const removePaste = on(input, "paste", onPaste);
const removeCopy = on(input, "copy", onCutOrCopy);
const removeCut = on(input, "cut", onCutOrCopy);
return {
destroy() {
removePaste();
removeCopy();
removeCut();
},
};
}
function useRichTextResolve(): [Promise<HTMLElement>, (input: HTMLElement) => void] {
const [promise, resolve] = promiseWithResolver<HTMLElement>();
function richTextResolve(input: HTMLElement): { destroy(): void } {
const destroy = bridgeCopyPasteCommands(input);
resolve(input);
return destroy;
}
return [promise, richTextResolve];
}
export default useRichTextResolve;

View file

@ -0,0 +1,60 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
import {
fragmentToString,
nodeContainsInlineContent,
nodeIsElement,
} from "../../lib/dom";
import { createDummyDoc } from "../../lib/parsing";
import { decoratedElements } from "../DecoratedElements.svelte";
function adjustInputHTML(html: string): string {
for (const component of decoratedElements) {
html = component.toUndecorated(html);
}
return html;
}
function adjustInputFragment(fragment: DocumentFragment): void {
if (nodeContainsInlineContent(fragment)) {
fragment.appendChild(document.createElement("br"));
}
}
export function storedToFragment(html: string): DocumentFragment {
/* We need .createContextualFragment so that customElements are initialized */
const fragment = document
.createRange()
.createContextualFragment(createDummyDoc(adjustInputHTML(html)));
adjustInputFragment(fragment);
return fragment;
}
function adjustOutputFragment(fragment: DocumentFragment): void {
if (
fragment.hasChildNodes() &&
nodeIsElement(fragment.lastChild!) &&
nodeContainsInlineContent(fragment) &&
fragment.lastChild!.tagName === "BR"
) {
fragment.lastChild!.remove();
}
}
function adjustOutputHTML(html: string): string {
for (const component of decoratedElements) {
html = component.toStored(html);
}
return html;
}
export function fragmentToStored(fragment: DocumentFragment): string {
const clone = document.importNode(fragment, true);
adjustOutputFragment(clone);
return adjustOutputHTML(fragmentToString(clone));
}

9
ts/icons/BUILD.bazel Normal file
View file

@ -0,0 +1,9 @@
load("@build_bazel_rules_nodejs//:index.bzl", "js_library")
js_library(
name = "icons",
srcs = glob([
"*.svg",
]),
visibility = ["//visibility:public"],
)

View file

@ -0,0 +1 @@
<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd"><svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" id="mdi-contain" width="24" height="24" viewBox="0 0 24 24"><path d="M1 2h6v2h-4v14h4v2h-6zm5 14v-2h2v2zm4 0v-2h2v2zm4 0v-2h2v.54c-.625.583-.891.887-1.191 1.46zM21 2v11.082c-.68-.11-1.32-.11-2 0v-9.082h-4v-2zm0 13v3h3v2h-3v3h-2v-3h-3v-2h3v-3h2Z" /></svg>

After

Width:  |  Height:  |  Size: 488 B

12
ts/lib/parsing.ts Normal file
View file

@ -0,0 +1,12 @@
// Copyright: Ankitects Pty Ltd and contributors
// License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
/**
* Parsing with or without this dummy structure changes the output
* for both `DOMParser.parseAsString` and range.createContextualFragment`.
* Parsing without means that comments or meaningless html elements are dropped,
* which we want to avoid.
*/
export function createDummyDoc(html: string): string {
return `<html><head></head><body>${html}</body></html>`;
}

View file

@ -12,7 +12,8 @@
{ "path": "reviewer" }, { "path": "reviewer" },
{ "path": "lib" }, { "path": "lib" },
{ "path": "domlib" }, { "path": "domlib" },
{ "path": "sveltelib" } { "path": "sveltelib" },
{ "path": "icons" }
], ],
"compilerOptions": { "compilerOptions": {
"declaration": true, "declaration": true,