Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions scripts/taskToggleMemory.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,33 @@ import { readFileSync } from 'node:fs';
import test from 'node:test';

const session = readFileSync(new URL('../src/lib/sessions/documentSession.svelte.ts', import.meta.url), 'utf8');
const markdownProcessing: string = readFileSync(new URL('../src/lib/utils/markdown.ts', import.meta.url), 'utf8');
const viewer = readFileSync(new URL('../src/lib/MarkdownViewer.svelte', import.meta.url), 'utf8');

test('preview task toggles transform the active in-memory buffer before saving', () => {
const taskToggle = session.match(/async function toggleTaskCheckbox[\s\S]*?\n\t}\n\n\treturn/);
assert.ok(taskToggle);
assert.doesNotMatch(taskToggle[0], /read_file_content/);
assert.match(taskToggle[0], /const raw = tab\.rawContent;/);
assert.match(taskToggle[0], /getMarkdownBodyWithoutFrontMatter\(raw\)/);
assert.match(taskToggle[0], /body\.slice\(0, offset\)\.split\('\\n'\)\.length/);
assert.match(taskToggle[0], /(?:\[-\+\*\]|\\d\+\[\.\)\])/);
assert.match(taskToggle[0], /tabManager\.updateTabRawContent\(tab\.id, updated\);/);
assert.match(taskToggle[0], /await saveContent\(tab\.id\)/);
});

test('preview task toggles use the renderer source line instead of checkbox order', () => {
const viewerToggle = viewer.match(/async function toggleTaskCheckbox[\s\S]*?\n\t}\n\n/);
assert.ok(viewerToggle);
assert.match(viewerToggle[0], /closest\('li'\)\?\.getAttribute\('data-sourcepos'\)/);
assert.match(viewerToggle[0], /documentSession\.toggleTaskCheckbox\(sourceLine, nowChecked\)/);
assert.doesNotMatch(viewerToggle[0], /allBoxes/);
});

test('preview task processing trusts the Markdown renderer task marker', () => {
const taskProcessing = markdownProcessing.match(/function processTaskItems[\s\S]*?\n}\n\nexport function processMarkdownHtml/);
assert.ok(taskProcessing);
assert.match(taskProcessing[0], /input\.hasAttribute\("data-task-checkbox"\)/);
assert.match(taskProcessing[0], /input\.setAttribute\("disabled", ""\)/);
assert.match(markdownProcessing, /input\.removeAttribute\("disabled"\)/);
});
124 changes: 109 additions & 15 deletions src-tauri/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,25 @@ use std::borrow::Cow;
use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use std::sync::LazyLock;
use std::time::{SystemTime, UNIX_EPOCH};
use tauri::{AppHandle, Emitter, Manager, State};

static INTERNAL_EMBED_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)!\[\[(.*?)\]\]").unwrap());
static WIKILINK_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?s)\[\[#([^\|\]]+)(?:\|([^\]]+))?\]\]").unwrap());
static BLOCK_ID_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"(?m)\s+\^([a-zA-Z0-9_-]+)$").unwrap());
static HIGHLIGHT_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"==([^=\n]+)==").unwrap());
static INLINE_FOOTNOTE_RE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\^\[([^\]]+)\]").unwrap());
static TASK_ITEM_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(
r#"<li data-sourcepos="(?<sourcepos>(?<line>\d+):\d+-\d+:\d+)">(?<input><input type="checkbox" disabled=""(?: checked="")? />)"#,
)
.unwrap()
});
static TASK_SOURCE_RE: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(r"^\s*(?:>\s*)*(?:[-+*]|\d+[.)])\s+\[[ xX]\](?:\s|$)").unwrap()
});

/// Write `bytes` to `target` durably and atomically: write to a sibling temp
/// file, fsync it, then rename over the target. Atomic on both Unix and
/// modern Windows — `std::fs::rename` calls `MoveFileExW` with
Expand Down Expand Up @@ -198,6 +214,63 @@ mod tests {
);
}

#[test]
fn task_list_checkbox_is_emitted_at_the_start_of_its_list_item() {
let html = convert_markdown("- [ ] open task\n- [x] completed task\n");
assert!(
html.contains("<li data-sourcepos=\"1:1-1:15\"><input type=\"checkbox\" data-task-checkbox=\"\" disabled=\"\" /> open task</li>"),
"unexpected task-list HTML: {html}",
);
assert!(
html.contains("<li data-sourcepos=\"2:1-2:20\"><input type=\"checkbox\" data-task-checkbox=\"\" disabled=\"\" checked=\"\" /> completed task</li>"),
"unexpected task-list HTML: {html}",
);
}

#[test]
fn raw_html_checkboxes_are_not_marked_as_tasks() {
let html = convert_markdown("- <input type=\"checkbox\" /> raw control\n");
assert!(
!html.contains("data-task-checkbox"),
"raw HTML control was incorrectly marked as a task: {html}",
);
}

#[test]
fn nested_and_quoted_task_checkboxes_are_marked() {
let html = convert_markdown("- [ ] parent\n - [x] nested\n\n> - [ ] quoted\n");
assert_eq!(
html.matches("data-task-checkbox").count(),
3,
"unexpected task-list HTML: {html}",
);
}

#[test]
fn markdown_protocol_preserves_task_markers_for_many_source_lines() {
let markdown = (1..=64)
.map(|line| match line % 3 {
0 => format!("> - [ ] quoted task {line}"),
1 => format!("- [ ] task {line}"),
_ => format!(" - [x] nested task {line}"),
})
.collect::<Vec<_>>()
.join("\n");

let html = convert_markdown(&markdown);
assert_eq!(html.matches("data-task-checkbox").count(), 64, "{html}");
assert!(html.contains("data-sourcepos=\"64:1-64:"), "{html}");
}

#[test]
fn multiline_wikilinks_do_not_shift_task_source_positions() {
let html = convert_markdown("[[#first\nsecond|alias]]\n- [ ] task\n");
assert!(
html.contains("data-task-checkbox"),
"task source position was shifted by a multiline wikilink: {html}",
);
}

#[test]
fn embed_protection_survives_longer_backtick_runs_earlier_in_the_doc() {
// A 4-backtick inline sample desynchronized the old regex pairing and
Expand Down Expand Up @@ -535,9 +608,8 @@ fn create_transfer_window(app: AppHandle, token: String) -> Result<(), String> {

fn process_internal_embeds(content: &str) -> Cow<'_, str> {
let regions = code_region_ranges(content);
let re = Regex::new(r"(?s)!\[\[(.*?)\]\]").unwrap();

re.replace_all(content, |caps: &Captures| {
INTERNAL_EMBED_RE.replace_all(content, |caps: &Captures| {
let full = caps.get(0).unwrap();
if in_code_region(&regions, full.start()) {
return full.as_str().to_string();
Expand Down Expand Up @@ -575,10 +647,9 @@ fn process_wikilinks<'a>(content: &'a str) -> Cow<'a, str> {
let mut processed = Cow::Borrowed(content);

// 1. Process [[#target]] or [[#target|alias]]
let re_links = Regex::new(r"(?s)\[\[#([^\|\]]+)(?:\|([^\]]+))?\]\]").unwrap();
if re_links.is_match(&processed) {
if WIKILINK_RE.is_match(&processed) {
let regions = code_region_ranges(&processed);
let replaced = re_links.replace_all(&processed, |caps: &Captures| {
let replaced = WIKILINK_RE.replace_all(&processed, |caps: &Captures| {
let full = caps.get(0).unwrap();
if in_code_region(&regions, full.start()) {
return full.as_str().to_string();
Expand All @@ -593,10 +664,9 @@ fn process_wikilinks<'a>(content: &'a str) -> Cow<'a, str> {

// 2. Process ^block-id at the end of lines
// For block IDs, they are trailing. We skip code blocks but also need to be careful with inline code at EOL.
let re_ids = Regex::new(r"(?m)\s+\^([a-zA-Z0-9_-]+)$").unwrap();
if re_ids.is_match(&processed) {
if BLOCK_ID_RE.is_match(&processed) {
let regions = code_region_ranges(&processed);
let replaced = re_ids.replace_all(&processed, |caps: &Captures| {
let replaced = BLOCK_ID_RE.replace_all(&processed, |caps: &Captures| {
let full = caps.get(0).unwrap();
if in_code_region(&regions, full.start()) {
return full.as_str().to_string();
Expand All @@ -611,10 +681,9 @@ fn process_wikilinks<'a>(content: &'a str) -> Cow<'a, str> {
}

// 3. Convert ==highlight== to <mark>highlight</mark>
let re_highlight = Regex::new(r"==([^=\n]+)==").unwrap();
if re_highlight.is_match(&processed) {
if HIGHLIGHT_RE.is_match(&processed) {
let regions = code_region_ranges(&processed);
let replaced = re_highlight.replace_all(&processed, |caps: &Captures| {
let replaced = HIGHLIGHT_RE.replace_all(&processed, |caps: &Captures| {
let full = caps.get(0).unwrap();
if in_code_region(&regions, full.start()) {
return full.as_str().to_string();
Expand All @@ -625,12 +694,11 @@ fn process_wikilinks<'a>(content: &'a str) -> Cow<'a, str> {
}

// 4. Convert ^[inline footnote] to a footnote reference
let re_inline_fn = Regex::new(r"\^\[([^\]]+)\]").unwrap();
if re_inline_fn.is_match(&processed) {
if INLINE_FOOTNOTE_RE.is_match(&processed) {
let regions = code_region_ranges(&processed);
let mut footnote_defs = String::new();
let mut fn_count = 0usize;
let replaced = re_inline_fn.replace_all(&processed, |caps: &Captures| {
let replaced = INLINE_FOOTNOTE_RE.replace_all(&processed, |caps: &Captures| {
let full = caps.get(0).unwrap();
if in_code_region(&regions, full.start()) {
return full.as_str().to_string();
Expand Down Expand Up @@ -747,7 +815,33 @@ fn convert_markdown(content: &str) -> String {
options.render.hardbreaks = true;
options.render.sourcepos = true;

markdown_to_html(&processed_links, &options)
let html = markdown_to_html(&processed_links, &options);
annotate_task_checkboxes(html, content)
}

fn annotate_task_checkboxes(html: String, markdown: &str) -> String {
let markdown_lines = markdown.lines().collect::<Vec<_>>();

TASK_ITEM_RE
.replace_all(&html, |captures: &Captures| {
let line = captures["line"].parse::<usize>().unwrap_or_default();
let source_line = markdown_lines.get(line.saturating_sub(1));
if !source_line.is_some_and(|line| TASK_SOURCE_RE.is_match(line)) {
return captures[0].to_string();
}

let input = captures["input"].replacen(
" disabled=\"\"",
" data-task-checkbox=\"\" disabled=\"\"",
1,
);
format!(
"<li data-sourcepos=\"{}\">{}",
&captures["sourcepos"],
input,
)
})
.into_owned()
}

#[tauri::command]
Expand Down
8 changes: 4 additions & 4 deletions src/lib/MarkdownViewer.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -1535,11 +1535,11 @@ import { createDocumentSession, type LoadMarkdownOptions } from './sessions/docu
}

async function toggleTaskCheckbox(checkbox: HTMLInputElement) {
const allBoxes = Array.from(markdownBody?.querySelectorAll('[data-task-checkbox]') || []);
const index = allBoxes.indexOf(checkbox);
if (index === -1) return;
const sourcePosition = checkbox.closest('li')?.getAttribute('data-sourcepos');
const sourceLine = Number(sourcePosition?.match(/^(\d+):/)?.[1]);
if (!Number.isInteger(sourceLine) || sourceLine < 1) return;
const nowChecked = !checkbox.checked;
if (!(await documentSession.toggleTaskCheckbox(index, nowChecked))) return;
if (!(await documentSession.toggleTaskCheckbox(sourceLine, nowChecked))) return;
checkbox.checked = nowChecked;
const li = checkbox.closest('li');
if (li) {
Expand Down
11 changes: 7 additions & 4 deletions src/lib/sessions/documentSession.svelte.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { invoke } from '@tauri-apps/api/core';
import { save } from '@tauri-apps/plugin-dialog';
import { settings } from '../stores/settings.svelte.js';
import { tabManager } from '../stores/tabs.svelte.js';
import { getMarkdownBodyWithoutFrontMatter } from '../utils/frontMatter.js';
import { hasMarkdownLinkExtension } from '../utils/markdownLinks.js';

export type LoadMarkdownOptions = {
Expand Down Expand Up @@ -209,15 +210,17 @@ export function createDocumentSession(options: DocumentSessionOptions) {
}
}

async function toggleTaskCheckbox(index: number, nowChecked: boolean) {
async function toggleTaskCheckbox(sourceLine: number, nowChecked: boolean) {
const tab = tabManager.activeTab;
if (!tab || !tab.path) return false;
const raw = tab.rawContent;
let count = 0;
const updated = raw.replace(/^(\s*[-*+] )\[( |x|X)\]/gm, (match, prefix) => {
if (count++ === index) return `${prefix}[${nowChecked ? 'x' : ' '}]`;
const body = getMarkdownBodyWithoutFrontMatter(raw);
const updatedBody = body.replace(/^(\s*(?:>\s*)*(?:[-+*]|\d+[.)])\s+)\[( |x|X)\]/gm, (match, prefix, _state, offset) => {
const line = body.slice(0, offset).split('\n').length;
if (line === sourceLine) return `${prefix}[${nowChecked ? 'x' : ' '}]`;
return match;
});
const updated = `${raw.slice(0, raw.length - body.length)}${updatedBody}`;
if (updated === raw) return false;
tabManager.updateTabRawContent(tab.id, updated);
await saveContent(tab.id);
Expand Down
35 changes: 4 additions & 31 deletions src/lib/utils/markdown.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,43 +367,16 @@ function stripLeadingWhitespace(nodes: Node[]) {
}
}

function isWhitespaceText(node: Node) {
return node.nodeType === 3 && !node.textContent?.trim();
}

function startsWithNode(element: Element, target: Node) {
const firstContentNode = Array.from(element.childNodes).find(
(node) => !isWhitespaceText(node),
);
return firstContentNode === target;
}

function isTaskCheckbox(input: Element, li: Element) {
const looksRenderedByTaskList =
input.hasAttribute("data-task-checkbox") ||
li.classList.contains("task-list-item");
if (!looksRenderedByTaskList) return false;

const inputParent = input.parentElement;
if (inputParent === li) {
return startsWithNode(li, input);
}

return (
inputParent?.tagName === "P" &&
inputParent.parentElement === li &&
startsWithNode(li, inputParent) &&
startsWithNode(inputParent, input)
);
}

function processTaskItems(root: Element) {
for (const input of Array.from(
root.querySelectorAll('li input[type="checkbox"]'),
)) {
const li = input.closest("li");
if (!li) continue;
if (!isTaskCheckbox(input, li)) continue;
if (!input.hasAttribute("data-task-checkbox")) {
input.setAttribute("disabled", "");
continue;
}

input.setAttribute("data-task-checkbox", "");
input.removeAttribute("disabled");
Expand Down
Loading