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-center = Center
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-customize-card-templates = Customize Card Templates
editing-customize-fields = Customize Fields

View file

@ -46,6 +46,11 @@ message MediaEntries {
string name = 1;
uint32 size = 2;
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;

View file

@ -224,6 +224,7 @@ def show(mw: aqt.AnkiQt) -> QDialog:
"Matthias Metelka",
"Sergio Quintero",
"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"
editor.web.eval(
'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_commit = "bd995b3d74f37975554ebd03d3add4ea82bf663f"
core_i18n_zip_csum = "ace985f858958321d5919731981bce2b9356ea3e8fb43b0232a1dc6f55673f3d"
core_i18n_commit = "7d1954863a721e09d974c609b55fa78f0e178b0f"
core_i18n_zip_csum = "14cce5d0ecd2c00ce839d735ab7fe979439080ad9c510cc6fc2e63c97a9c745c"
qtftl_i18n_repo = "anki-desktop-ftl"
qtftl_i18n_commit = "5045d3604a20b0ae8ce14be2d3597d72c03ccad8"
qtftl_i18n_zip_csum = "45058ea33cb0e5d142cae8d4e926f5eb3dab4d207e7af0baeafda2b92f765806"
qtftl_i18n_commit = "31baaae83fad4be3d8977d6053ef3032bdb90481"
qtftl_i18n_zip_csum = "96e42e0278affb2586e677b52b466e6ca8bb4f3fd080a561683c48b483202fa2"
i18n_build_content = """
filegroup(

View file

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

View file

@ -102,16 +102,22 @@ fn restore_media(
let media_entries = extract_media_entries(meta, archive)?;
std::fs::create_dir_all(media_folder)?;
for (archive_file_name, entry) in media_entries.iter().enumerate() {
if archive_file_name % 10 == 0 {
progress_fn(ImportProgress::Media(archive_file_name))?;
for (entry_idx, entry) in media_entries.iter().enumerate() {
if entry_idx % 10 == 0 {
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)?;
} else {
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() {
let map: HashMap<&str, String> = serde_json::from_slice(&buf)?;
let mut entries: Vec<(usize, String)> = map
.into_iter()
.map(|(k, v)| (k.parse().unwrap_or_default(), v))
.collect();
entries.sort_unstable();
// any gaps in the file numbers would lead to media being imported under the wrong name
if entries
.iter()
.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![],
map.into_iter()
.map(|(idx_str, name)| {
let idx: u32 = idx_str.parse()?;
Ok(MediaEntry {
name,
size: 0,
sha1: vec![],
legacy_zip_filename: Some(idx),
})
})
.collect())
.collect()
} else {
let entries: MediaEntries = Message::decode(&*buf)?;
Ok(entries.entries)

View file

@ -18,9 +18,31 @@ use crate::{
};
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.due = position as i32;
self.due = last_position.unwrap_or(position) as i32;
self.ctype = CardType::New;
self.queue = CardQueue::New;
self.interval = 0;
@ -30,6 +52,8 @@ impl Card {
self.reps = 0;
self.lapses = 0;
}
last_position.is_none()
}
/// 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()?;
for mut card in cards {
let original = card.clone();
if restore_position && card.original_position.is_some() {
card.schedule_as_new(card.original_position.unwrap(), reset_counts);
} else {
card.schedule_as_new(position, reset_counts);
if card.schedule_as_new(position, reset_counts, restore_position) {
position += 1;
}
if log {
@ -301,6 +322,43 @@ mod test {
}
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 {

View file

@ -35,3 +35,11 @@ alias(
name = "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",
"@npm//@mdi",
"@npm//bootstrap-icons",
"//ts/icons",
"@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">
import { CustomElementArray } from "../editable/decorated";
import contextProperty from "../sveltelib/context-property";
const decoratedElements = new CustomElementArray();
const key = Symbol("decoratedElements");
const [context, setContextProperty] = contextProperty<CustomElementArray>(key);
export { context };
</script>
<script lang="ts">
setContextProperty(decoratedElements);
export { decoratedElements };
</script>
<slot />

View file

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

View file

@ -5,18 +5,24 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
<script lang="ts">
import { get } from "svelte/store";
import ButtonGroup from "../../components/ButtonGroup.svelte";
import IconButton from "../../components/IconButton.svelte";
import Shortcut from "../../components/Shortcut.svelte";
import * as tr from "../../lib/ftl";
import { isApplePlatform } from "../../lib/platform";
import { getPlatformString } from "../../lib/shortcuts";
import { wrapInternal } from "../../lib/wrap";
import { context as noteEditorContext } from "../NoteEditor.svelte";
import type { RichTextInputAPI } from "../rich-text-input";
import { editingInputIsRichText } from "../rich-text-input";
import { ellipseIcon } from "./icons";
import { clozeIcon, incrementClozeIcon } from "./icons";
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;
function getCurrentHighestCloze(increment: boolean): number {
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;
async function onCloze(event: KeyboardEvent | MouseEvent): Promise<void> {
const highestCloze = getCurrentHighestCloze(!event.getModifierState("Alt"));
async function onIncrementCloze(): Promise<void> {
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);
}
$: disabled = !editingInputIsRichText($focusedInput);
const keyCombination = "Control+Alt?+Shift+C";
const incrementKeyCombination = "Control+Shift+C";
const sameKeyCombination = "Control+Alt+Shift+C";
</script>
<IconButton
tooltip="{tr.editingClozeDeletion()} {getPlatformString(keyCombination)}"
{disabled}
on:click={onCloze}
>
{@html ellipseIcon}
</IconButton>
<ButtonGroup>
<IconButton
tooltip="{tr.editingClozeDeletion()} ({getPlatformString(
incrementKeyCombination,
)})"
{disabled}
on:click={onIncrementCloze}
--border-left-radius="5px"
>
{@html incrementClozeIcon}
</IconButton>
<Shortcut
{keyCombination}
event="keyup"
on:action={(event) => onCloze(event.detail.originalEvent)}
/>
<Shortcut
keyCombination={incrementKeyCombination}
{event}
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 StickyContainer from "../../components/StickyContainer.svelte";
import BlockButtons from "./BlockButtons.svelte";
import ClozeButtons from "./ClozeButtons.svelte";
import InlineButtons from "./InlineButtons.svelte";
import NotetypeButtons from "./NotetypeButtons.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">
<TemplateButtons api={templateButtons} />
</Item>
<Item id="cloze">
<ClozeButtons />
</Item>
</DynamicallySlottable>
</ButtonToolbar>
</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 { setFormat } from "../old-editor-adapter";
import { editingInputIsRichText } from "../rich-text-input";
import ClozeButton from "./ClozeButton.svelte";
import { micIcon, paperclipIcon } from "./icons";
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>();
$focusedInput.focusHandler.focus.on(
$focusedInput.editable.focusHandler.focus.on(
async () => setFormat("inserthtml", await mediaPromise),
{ once: true },
);
@ -61,7 +60,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
}
[mediaPromise, resolve] = promiseWithResolver<string>();
$focusedInput.focusHandler.focus.on(
$focusedInput.editable.focusHandler.focus.on(
async () => setFormat("inserthtml", await mediaPromise),
{ once: true },
);
@ -116,10 +115,6 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
/>
</ButtonGroupItem>
<ButtonGroupItem id="cloze">
<ClozeButton />
</ButtonGroupItem>
<ButtonGroupItem>
<LatexButton />
</ButtonGroupItem>

View file

@ -24,7 +24,8 @@ export { default as underlineIcon } from "bootstrap-icons/icons/type-underline.s
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>';
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 paperclipIcon } from "@mdi/svg/svg/paperclip.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";
const { container, api } = context.get();
const { focusHandler, preventResubscription } = api;
const { editable, preventResubscription } = api;
const code = writable("");
@ -41,7 +41,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
let selectAll = false;
function placeHandle(after: boolean): void {
focusHandler.flushCaret();
editable.focusHandler.flushCaret();
if (after) {
(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 { writable } from "svelte/store";
import { singleCallback } from "../../lib/typing";
import { pageTheme } from "../../sveltelib/theme";
import { baseOptions, gutterOptions, htmlanki } from "../code-mirror";
import CodeMirror from "../CodeMirror.svelte";
import { context as decoratedElementsContext } from "../DecoratedElements.svelte";
import { context as editingAreaContext } from "../EditingArea.svelte";
import { context as noteEditorContext } from "../NoteEditor.svelte";
import removeProhibitedTags from "./remove-prohibited";
export let hidden = false;
import { storedToUndecorated, undecoratedToStored } from "./transform";
const configuration = {
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 { editingInputs, content } = editingAreaContext.get();
const decoratedElements = decoratedElementsContext.get();
const code = writable($content);
function focus(): void {
codeMirror.editor.then((editor) => editor.focus());
let codeMirror = {} as CodeMirrorAPI;
async function focus(): Promise<void> {
const editor = await codeMirror.editor;
editor.focus();
}
function moveCaretToEnd(): void {
codeMirror.editor.then((editor) => editor.setCursor(editor.lineCount(), 0));
async function moveCaretToEnd(): Promise<void> {
const editor = await codeMirror.editor;
editor.setCursor(editor.lineCount(), 0);
}
function refocus(): void {
codeMirror.editor.then((editor) => (editor as any).display.input.blur());
async function refocus(): Promise<void> {
const editor = (await codeMirror.editor) as any;
editor.display.input.blur();
focus();
moveCaretToEnd();
}
export let hidden = false;
function toggle(): boolean {
hidden = !hidden;
return hidden;
}
let codeMirror = {} as CodeMirrorAPI;
export const api = {
export const api: PlainTextInputAPI = {
name: "plain-text",
focus,
focusable: !hidden,
@ -81,47 +85,46 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
refocus,
toggle,
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;
}
function refresh(): void {
codeMirror.editor.then((editor) => editor.refresh());
async function refresh(): Promise<void> {
const editor = await codeMirror.editor;
editor.refresh();
}
$: {
hidden;
pushUpdate(!hidden);
tick().then(refresh);
pushUpdate();
}
function storedToUndecorated(html: string): string {
return decoratedElements.toUndecorated(html);
}
function undecoratedToStored(html: string): string {
return decoratedElements.toStored(html);
function onChange({ detail: html }: CustomEvent<string>): void {
code.set(removeProhibitedTags(html));
}
onMount(() => {
$editingInputs.push(api);
$editingInputs = $editingInputs;
const unsubscribeFromEditingArea = content.subscribe((value: string): void => {
code.set(storedToUndecorated(value));
});
const unsubscribeToEditingArea = code.subscribe((value: string): void => {
content.set(removeProhibitedTags(undecoratedToStored(value)));
});
return () => {
unsubscribeFromEditingArea();
unsubscribeToEditingArea();
};
return singleCallback(
content.subscribe((html: string): void =>
/* We call `removeProhibitedTags` here, because content might
* have been changed outside the editor, and we need to parse
* it to get the "neutral" value. Otherwise, there might be
* conflicts with other editing inputs */
code.set(removeProhibitedTags(storedToUndecorated(html))),
),
code.subscribe((html: string): void =>
content.set(undecoratedToStored(html)),
),
);
});
setupLifecycleHooks(api);
@ -133,12 +136,7 @@ License: GNU AGPL, version 3 or later; http://www.gnu.org/licenses/agpl.html
class:hidden
on:focusin={() => ($focusedInput = api)}
>
<CodeMirror
{configuration}
{code}
bind:api={codeMirror}
on:change={({ detail: html }) => code.set(removeProhibitedTags(html))}
/>
<CodeMirror {configuration} {code} bind:api={codeMirror} on:change={onChange} />
</div>
<style lang="scss">

View file

@ -1,16 +1,9 @@
// Copyright: Ankitects Pty Ltd and contributors
// 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 {
return (
"<html><head></head><body>" +
// parsingInstructions.join("") +
html +
"</body>"
);
}
const parser = new DOMParser();
function removeTag(element: HTMLElement, tagName: string): void {
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
-->
<script context="module" lang="ts">
import type { FocusHandlerAPI } from "../../editable/content-editable";
import type { ContentEditableAPI } from "../../editable/ContentEditable.svelte";
import { singleCallback } from "../../lib/typing";
import useContextProperty from "../../sveltelib/context-property";
import useDOMMirror from "../../sveltelib/dom-mirror";
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 CustomStyles from "./CustomStyles.svelte";
export interface RichTextInputAPI extends EditingInputAPI, ContentEditableAPI {
export interface RichTextInputAPI extends EditingInputAPI {
name: "rich-text";
shadowRoot: Promise<ShadowRoot>;
element: Promise<HTMLElement>;
moveCaretToEnd(): void;
toggle(): boolean;
preventResubscription(): () => void;
inputHandler: InputHandlerAPI;
focusHandler: FocusHandlerAPI;
editable: ContentEditableAPI;
}
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 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 noteEditorContext } from "../NoteEditor.svelte";
import getNormalizingNodeStore from "./normalizing-node-store";
import useRichTextResolve from "./rich-text-resolve";
import RichTextStyles from "./RichTextStyles.svelte";
import SetContext from "./SetContext.svelte";
import { fragmentToStored, storedToFragment } from "./transform";
export let hidden: boolean;
const { focusedInput } = noteEditorContext.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 [inputHandler, setupInputHandler] = useInputHandler();
function moveCaretToEnd() {
richTextPromise.then(placeCaretAfterContent);
export function attachShadow(element: Element): void {
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",
shadowRoot: shadowPromise,
element: richTextPromise,
focus() {
richTextPromise.then((richText) => {
richText.focus();
});
},
refocus() {
richTextPromise.then((richText) => {
richText.blur();
richText.focus();
moveCaretToEnd();
});
},
focus,
refocus,
focusable: !hidden,
toggle(): boolean {
hidden = !hidden;
return hidden;
},
toggle,
moveCaretToEnd,
preventResubscription,
inputHandler,
} as RichTextInputAPI;
editable: {} as ContentEditableAPI,
};
const allContexts = getAllContexts();
function attachContentEditable(element: Element, { stylesDidLoad }): void {
stylesDidLoad.then(
() =>
new ContentEditable({
target: element.shadowRoot,
props: {
nodes,
resolve,
mirrors: [mirror],
inputHandlers: [setupInputHandler, setupGlobalInputHandler],
api,
},
context: allContexts,
}),
);
(async () => {
await stylesDidLoad;
new ContentEditable({
target: element.shadowRoot!,
props: {
nodes,
resolve,
mirrors: [mirror],
inputHandlers: [setupInputHandler, setupGlobalInputHandler],
api: api.editable,
},
context: allContexts,
});
})();
}
function pushUpdate(): void {
api.focusable = !hidden;
function pushUpdate(isFocusable: boolean): void {
api.focusable = isFocusable;
$editingInputs = $editingInputs;
}
$: {
hidden;
pushUpdate();
}
$: pushUpdate(!hidden);
onMount(() => {
$editingInputs.push(api);
$editingInputs = $editingInputs;
const unsubscribeFromEditingArea = content.subscribe(writeFromEditingArea);
const unsubscribeToEditingArea = nodes.subscribe(writeToEditingArea);
return () => {
unsubscribeFromEditingArea();
unsubscribeToEditingArea();
};
return singleCallback(
content.subscribe((html: string): void =>
nodes.setUnprocessed(storedToFragment(html)),
),
nodes.subscribe((fragment: DocumentFragment): void =>
content.set(fragmentToStored(fragment)),
),
);
});
</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": "lib" },
{ "path": "domlib" },
{ "path": "sveltelib" }
{ "path": "sveltelib" },
{ "path": "icons" }
],
"compilerOptions": {
"declaration": true,