feat: improve history review and note workflows

- Add draft-aware diffs, rendered snapshots and restore confirmation
- Show saved YAML frontmatter in Note Info
- Add Today/Overdue task filters and Ubuntu font families
- Honor timestamp preferences
- Improve vault labels and full-path tooltips

Refs: #234, #244, #257, #262, #265, #268
This commit is contained in:
Yuri Karamian committed 2026-10-04 00:46:43 +02:00
1 parent 505ed2b890
commit 14b2a3e8a2
31 files changed
+1616 -132

No files matched your search

+16 -4
View File
@@ -138,24 +138,36 @@ All releases: [gitlab.com/ArkHost/HelixNotes/-/releases](https://gitlab.com/ArkH
## Features
- Markdown editor with toolbar, slash commands, source mode, code highlighting
- **Tasks view**: aggregate `- [ ]` checklists from across all notes, set priority and due dates, work in a list or a calendar (drag a task to reschedule)
- **Tasks view**: aggregate `- [ ]` checklists from across all notes, set priority and due dates, filter Today or Overdue tasks, work in a list or a calendar (drag a task to reschedule)
- `[[Wiki-links]]` and graph view
- Full-text search (Tantivy), CJK-aware for Chinese, Japanese, and Korean
- Outline panel, daily notes with calendar view, tags with autocomplete, drag-and-drop
- Live KaTeX math editor (`/math`, `/imath`) with modal preview, double-click to edit
- Mermaid diagrams (opt-in render, copy as PNG, save as PNG/SVG)
- Encrypted secret blocks (`/secret`) stored as portable `helix-secret` markdown fences
- Insert date/time (`/date`, `/time`, `/now`), color swatches (`/color`), configurable week start
- Insert date/time (`/date`, `/time`, `/now`) with 12-hour or 24-hour timestamps, color swatches (`/color`), configurable week start
- Manual notebook sorting (drag to reorder above, into, or below)
- External `.md` viewer mode with import-to-vault flow
- PDF preview, Obsidian import, "Show in File Manager"
- AI writing tools (Ollama / OpenAI-compatible / Anthropic / OpenAI)
- **Optional WebDAV sync** to your own server (Nextcloud, ownCloud, a NAS): manual or automatic, with keep-both conflict copies
- Version history with diffs, automatic backups
- Version history with main-area diffs and rendered read-only snapshots, automatic backups
- Multi-window, file associations, focus mode, view mode
- Themes (light, dark, and 14 palettes), accent colors, fonts, 80-200% interface scale
- Themes (light, dark, and 14 palettes), accent colors, fonts including bundled Ubuntu and Ubuntu Mono, 80-200% interface scale
- Local plain-text files, no company cloud
### Version history
Changes compares the selected snapshot with the current editor contents, including unsaved edits. Added and removed lines show what restoring that version would change; long unchanged sections can be expanded.
Snapshot displays the stored note read-only, with View source available for its Markdown body. Metadata is separate and is not restored. Snapshot links are inactive, secrets stay locked, and diagrams render only when requested.
Restore replaces the current note's body and asks for confirmation if it would replace an unsaved draft. Inspecting versions does not replace the live editor contents or reset their undo history.
### Note Info
Open **Note info** from the editor toolbar. Expand **Frontmatter** to inspect the original YAML header, including custom keys, without editing it. This shows the last loaded or saved metadata; unsaved changes are not included, and the display updates after saving.
Full documentation: [helixnotes.com/docs](https://helixnotes.com/docs.html)
## Tech Stack
+2
View File
@@ -69,6 +69,8 @@
"@tiptap/starter-kit": "^3.19.0",
"@types/katex": "^0.16.8",
"@types/markdown-it": "^14.1.2",
"diff": "^9.0.0",
"dompurify": "^3.4.13",
"highlight.js": "^11.11.1",
"katex": "^0.16.28",
"lowlight": "^3.3.0",
+12
View File
@@ -110,6 +110,12 @@ importers:
'@types/markdown-it':
specifier: ^14.1.2
version: 14.1.2
diff:
specifier: ^9.0.0
version: 9.0.0
dompurify:
specifier: ^3.4.13
version: 3.4.13
highlight.js:
specifier: ^11.11.1
version: 11.11.1
@@ -1373,6 +1379,10 @@ packages:
devlop@1.1.0:
resolution: {integrity: sha512-RWmIqhcFf1lRYBvNmr7qTNuyCt/7/ns2jbpp1+PalgE/rDQcBT0fioSMUpJ93irlUhC5hrg4cYqe6U+0ImW0rA==}
diff@9.0.0:
resolution: {integrity: sha512-svtcdpS8CgJyqAjEQIXdb3OjhFVVYjzGAPO8WGCmRbrml64SPw/jJD4GoE98aR7r25A0XcgrK3F02yw9R/vhQw==}
engines: {node: '>=0.3.1'}
dompurify@3.4.13:
resolution: {integrity: sha512-2vmYIoqjze2d+kakP8S/nS5shfsl587kzwEjcGlTdiksUVgFHnFCsLYDVj/JNqJVOQZGSYBTmuycv0PodwmnMQ==}
@@ -2946,6 +2956,8 @@ snapshots:
dependencies:
dequal: 2.0.3
diff@9.0.0: {}
dompurify@3.4.13:
optionalDependencies:
'@types/trusted-types': 2.0.7
+59
View File
@@ -152,6 +152,65 @@
src: url("/fonts/open-sans/OpenSans-BoldItalic.woff2") format("woff2");
}
/* Ubuntu families - unmodified upstream fonts, Ubuntu Font Licence 1.0.
Copyright and licence notices are bundled beside each family's local assets. */
@font-face {
font-family: "Ubuntu";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/ubuntu/Ubuntu-R.ttf") format("truetype");
}
@font-face {
font-family: "Ubuntu";
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/ubuntu/Ubuntu-B.ttf") format("truetype");
}
@font-face {
font-family: "Ubuntu";
font-style: italic;
font-weight: 400;
font-display: swap;
src: url("/fonts/ubuntu/Ubuntu-RI.ttf") format("truetype");
}
@font-face {
font-family: "Ubuntu";
font-style: italic;
font-weight: 700;
font-display: swap;
src: url("/fonts/ubuntu/Ubuntu-BI.ttf") format("truetype");
}
@font-face {
font-family: "Ubuntu Mono";
font-style: normal;
font-weight: 400;
font-display: swap;
src: url("/fonts/ubuntu-mono/UbuntuMono-R.ttf") format("truetype");
}
@font-face {
font-family: "Ubuntu Mono";
font-style: normal;
font-weight: 700;
font-display: swap;
src: url("/fonts/ubuntu-mono/UbuntuMono-B.ttf") format("truetype");
}
@font-face {
font-family: "Ubuntu Mono";
font-style: italic;
font-weight: 400;
font-display: swap;
src: url("/fonts/ubuntu-mono/UbuntuMono-RI.ttf") format("truetype");
}
@font-face {
font-family: "Ubuntu Mono";
font-style: italic;
font-weight: 700;
font-display: swap;
src: url("/fonts/ubuntu-mono/UbuntuMono-BI.ttf") format("truetype");
}
:root {
/* Light theme */
--bg-primary: #ffffff;
+204 -108
View File
@@ -43,6 +43,10 @@
import type { NoteContent, VersionEntry, AiStreamEvent, NoteTitleEntry, TaskItem as TaskRecord, FileEvent, SearchTarget, ToolbarLayout } from '$lib/types';
import { listen } from '@tauri-apps/api/event';
import { debounce } from '$lib/utils/debounce';
import { formatClockTime } from '$lib/utils/time';
import DOMPurify from 'dompurify';
import { splitSnapshot } from '$lib/utils/history-comparison';
import HistoryReview from './HistoryReview.svelte';
import { RevisionSaveQueue, type SaveRevision } from '$lib/utils/revision-save';
import { isCurrentVaultEvent } from '$lib/utils/note-list-updates';
import { beginNoteNavigation, isCurrentNoteNavigation, cancelNoteNavigation } from '$lib/utils/note-navigation';
@@ -469,6 +473,10 @@
let historyPreview = $state<string | null>(null);
let historySelected = $state<VersionEntry | null>(null);
let historyLoading = $state(false);
let historyError = $state<string | null>(null);
let historyPreviewLoading = $state(false);
let historyPreviewError = $state<string | null>(null);
let historyWorking = $state('');
// Info panel
let showInfo = $state(false);
@@ -476,6 +484,9 @@
let charCount = $state(0);
let infoPathCopyState = $state<'idle' | 'copied' | 'error'>('idle');
let infoPathCopyTimer: ReturnType<typeof setTimeout> | null = null;
const infoFrontmatter = $derived(showInfo && !showHistory && $activeNote
? splitSnapshot($activeNote.raw).metadata
: '');
$effect(() => {
$activeNotePath;
@@ -517,7 +528,7 @@
const now = new Date();
const pad = (n: number) => String(n).padStart(2, '0');
const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
const time = `${pad(now.getHours())}:${pad(now.getMinutes())}`;
const time = formatClockTime(now, $appConfig?.time_format);
const text = kind === 'date' ? date : kind === 'time' ? time : `${date} ${time}`;
editor.chain().focus().insertContent(text).run();
}
@@ -3440,10 +3451,11 @@
$effect(() => {
if (trashPreview && !$readOnly) $readOnly = true;
const ro = $readOnly;
const inspecting = showHistory;
untrack(() => {
if (editor) {
if (ro && $editorDirty) forceSave();
editor.setEditable(!ro && !externalOperationBusy);
editor.setEditable(!ro && !inspecting && !externalOperationBusy);
}
});
});
@@ -3513,24 +3525,63 @@
let historyRequest = 0;
function closeHistory() {
historyRequest++;
showHistory = false;
historyVersions = [];
historySelected = null;
historyPreview = null;
historyLoading = false;
historyError = null;
historyPreviewLoading = false;
historyPreviewError = null;
}
async function toggleHistory() {
if (showHistory) {
closeHistory();
return;
}
closeNoteSearch(false);
endToolbarCustomization();
historyWorking = $editorDirty
? ($sourceMode ? restoreTitleH1(source.state.doc.toString()) : editorToMarkdown())
: ($activeNote?.content ?? '');
showHistory = true;
await loadHistory();
}
async function loadHistory() {
const origin = captureOrigin();
const request = ++historyRequest;
showHistory = !showHistory;
historyPreview = null;
const current = () => !editorDisposed && request === historyRequest && showHistory;
historyVersions = [];
historySelected = null;
historyPreview = null;
historyPreviewLoading = false;
historyPreviewError = null;
historyError = null;
historyLoading = false;
if (!showHistory || !origin.noteId || !origin.vault) return;
if (!origin.noteId || !origin.vault) {
historyError = 'Version history is unavailable for this note.';
return;
}
historyLoading = true;
try {
const versions = await getNoteVersions(origin.vault, origin.noteId);
if (!isOriginCurrent(origin) || request !== historyRequest || !showHistory) return;
if (!current()) return;
if (!isOriginCurrent(origin)) {
historyError = 'The editor changed while versions were loading. Retry to reload them.';
return;
}
historyVersions = versions;
historyLoading = false;
if (versions[0]) void previewVersion(versions[0]);
} catch (e) {
console.error('Failed to load versions:', e);
if (isOriginCurrent(origin) && request === historyRequest) historyVersions = [];
if (current()) historyError = `Could not load versions: ${String(e)}`;
} finally {
if (isOriginCurrent(origin) && request === historyRequest) historyLoading = false;
if (current()) historyLoading = false;
}
}
@@ -3538,36 +3589,39 @@
const origin = captureOrigin();
if (!origin.noteId || !origin.vault) return;
const request = ++historyRequest;
const current = () => !editorDisposed && request === historyRequest && showHistory;
historySelected = v;
historyPreview = null;
historyPreviewError = null;
historyPreviewLoading = true;
try {
const content = await getNoteVersionContent(origin.vault, origin.noteId, v.timestamp);
if (isOriginCurrent(origin) && request === historyRequest && showHistory) historyPreview = content;
if (!current()) return;
if (!isOriginCurrent(origin)) {
historyPreviewError = 'The editor changed while this version was loading. Select it again to retry.';
return;
}
historyPreview = content;
} catch (e) {
console.error('Failed to load version:', e);
if (current()) historyPreviewError = `Could not load this version: ${String(e)}`;
} finally {
if (current()) historyPreviewLoading = false;
}
}
async function restoreVersion() {
if (!$activeNote || !$activeNotePath || !historySelected) return;
const origin = captureOrigin();
const selected = historySelected;
const request = historyRequest;
if (!canInsert(origin)) return;
function restoreVersion() {
if (!$activeNote || !$activeNotePath || !historySelected || historyPreview === null || historyPreviewLoading) return;
if (!canInsert(captureOrigin())) return;
if ($editorDirty && !window.confirm('Restore this version and replace your unsaved draft?')) return;
try {
const raw = historyPreview ?? await getNoteVersionContent(origin.vault!, origin.noteId!, selected.timestamp);
if (!isOriginCurrent(origin, true) || !canInsert(origin) || request !== historyRequest || !showHistory) return;
// The raw content includes frontmatter - parse out the body
const fmEnd = raw.indexOf('---', 4);
const body = fmEnd > 0 ? raw.substring(raw.indexOf('\n', fmEnd) + 1) : raw;
const body = splitSnapshot(historyPreview).body;
if ($sourceMode) {
source.replace(stripTitleH1(body));
} else if (editor) {
editor.commands.setContent(markdownToHtml(body));
}
historyPreview = null;
historySelected = null;
showHistory = false;
closeHistory();
} catch (e) {
console.error('Failed to restore version:', e);
}
@@ -3588,22 +3642,14 @@
}
}
const historyDateFormatter = new Intl.DateTimeFormat(undefined, {
year: 'numeric', month: 'short', day: 'numeric',
hour: '2-digit', minute: '2-digit', second: '2-digit', fractionalSecondDigits: 3,
});
function formatVersionDate(iso: string): string {
try {
const d = new Date(iso);
const now = new Date();
const diffMs = now.getTime() - d.getTime();
const diffMins = Math.floor(diffMs / 60000);
if (diffMins < 1) return 'Just now';
if (diffMins < 60) return `${diffMins}m ago`;
const diffHours = Math.floor(diffMins / 60);
if (diffHours < 24) return `${diffHours}h ago`;
const diffDays = Math.floor(diffHours / 24);
if (diffDays < 7) return `${diffDays}d ago`;
return d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: d.getFullYear() !== now.getFullYear() ? 'numeric' : undefined });
} catch {
return iso;
}
const date = new Date(iso);
return Number.isNaN(date.getTime()) ? iso : historyDateFormatter.format(date);
}
function formatVersionSize(bytes: number): string {
@@ -3730,10 +3776,7 @@
saveError = null;
retryingSave = false;
closeAiMenu();
showHistory = false;
historyPreview = null;
historySelected = null;
historyVersions = [];
closeHistory();
secretModal = null;
linkModal = false;
textContextMenu = null;
@@ -3745,8 +3788,6 @@
linkContextMenu = null;
imageToolbar = null;
tableContextMenu = null;
historyRequest++;
historyLoading = false;
savedBlobImages = new Map();
$editorDirty = false;
rememberLoadedNoteScroll();
@@ -4803,8 +4844,8 @@
return out.join('\n');
}
function markdownToHtml(md: string): string {
let src = stripTitleH1(md);
function markdownToHtml(md: string, snapshot = false): string {
let src = snapshot ? md : stripTitleH1(md);
src = secretFencesToHtml(src);
// Pre-process: convert [[Note Title]] wiki-links to HTML anchors
@@ -4876,7 +4917,7 @@
src = src.replace(/<div[^>]*data-pdf-src="([^"]*)"[^>]*data-pdf-name="([^"]*)"[^>]*>[^<]*<\/div>/gi, (_, pdfSrc, name) => {
const vaultRoot = $appConfig?.active_vault ?? '';
const absPath = normalizePath(`${vaultRoot}/${decodeURIComponent(pdfSrc)}`);
const showInline = !isMobile && ($appConfig?.pdf_preview ?? false);
const showInline = !snapshot && !isMobile && ($appConfig?.pdf_preview ?? false);
if (showInline) {
const pdfHeight = $appConfig?.pdf_height ?? 600;
const displaySrc = convertFileSrc(absPath);
@@ -4959,13 +5000,20 @@
html = html.replace(/<ul>(\s*<li data-type="taskItem")/gi, '<ul data-type="taskList">$1');
html = normalizeImageHtml(html);
if (snapshot) {
html = DOMPurify.sanitize(html, {
USE_PROFILES: { html: true },
ADD_URI_SAFE_ATTR: ['src'],
FORBID_TAGS: ['style', 'iframe', 'object', 'embed', 'form', 'input', 'button', 'video', 'audio', 'source', 'svg', 'math', 'link'],
});
}
// Post-process: turn Obsidian callout blockquotes (> [!type] ...) into callout blocks.
if (html.includes('[!')) {
const tmp = document.createElement('div');
tmp.innerHTML = html;
transformCalloutBlockquotes(tmp);
html = tmp.innerHTML;
const template = document.createElement('template');
template.innerHTML = html;
for (const child of Array.from(template.content.children)) transformCalloutBlockquotes(child);
html = template.innerHTML;
}
return html;
@@ -7406,15 +7454,15 @@
</button>
</div>
{/if}
<div class="editor-body-row">
<div class="editor-body" class:source-body={$sourceMode}>
<div class="editor-body-row" class:reviewing-history={showHistory}>
<div class="editor-body" class:source-body={$sourceMode} class:history-hidden={showHistory}>
{#if isMobile}
<SourceEditor controller={source} readonly={$readOnly || !!$viewerNote || externalOperationBusy} visible={$sourceMode} mobile />
<SourceEditor controller={source} readonly={showHistory || $readOnly || !!$viewerNote || externalOperationBusy} visible={$sourceMode} mobile />
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="tiptap-wrapper" class:large-doc={isLargeDoc} style={$sourceMode ? 'display:none' : ''} spellcheck="false" bind:this={editorElement} onclick={(e) => { closeLinkContextMenu(); handleEditorClick(e); }} onkeydown={(e) => { if (e.key === 'Escape') closeLinkContextMenu(); }}></div>
{:else}
{#if $sourceMode}
<SourceEditor controller={source} readonly={$readOnly || !!$viewerNote || externalOperationBusy} numbers={$appConfig?.show_line_numbers ?? false} />
<SourceEditor controller={source} readonly={showHistory || $readOnly || !!$viewerNote || externalOperationBusy} numbers={$appConfig?.show_line_numbers ?? false} />
{:else}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div class="tiptap-wrapper" class:large-doc={isLargeDoc} spellcheck="false" bind:this={editorElement} onclick={(e) => { closeLinkContextMenu(); handleEditorClick(e); }} onkeydown={(e) => { if (e.key === 'Escape') closeLinkContextMenu(); }} oncontextmenu={handleEditorContextMenu}></div>
@@ -7423,6 +7471,12 @@
</div>
{#if showHistory}
<HistoryReview raw={historyPreview} current={historyWorking}
selected={historySelected ? formatVersionDate(historySelected.timestamp) : null}
loading={historyLoading || historyPreviewLoading} error={historyError ?? historyPreviewError}
canRestore={historyPreview !== null && !historyPreviewLoading && canInsert(captureOrigin())}
onRetry={() => { if (historySelected) void previewVersion(historySelected); else void loadHistory(); }}
onRestore={restoreVersion} renderSnapshot={(body) => markdownToHtml(body, true)} />
<div class="history-panel">
<div class="history-header">
<h3>Version History</h3>
@@ -7433,7 +7487,7 @@
<line x1="5" y1="12" x2="19" y2="12" />
</svg>
</button>
<button class="history-close" onclick={() => { showHistory = false; historyPreview = null; historySelected = null; }} aria-label="Close version history">
<button class="history-close" onclick={closeHistory} aria-label="Close version history">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<line x1="18" y1="6" x2="6" y2="18" />
<line x1="6" y1="6" x2="18" y2="18" />
@@ -7442,16 +7496,33 @@
</div>
</div>
{#if historyLoading}
<div class="history-empty">Loading...</div>
<div class="history-empty" role="status">Loading...</div>
{:else if historyError}
<div class="history-empty" role="alert">
<p>{historyError}</p>
<button class="history-retry-btn" onclick={loadHistory}>Retry</button>
</div>
{:else if historyVersions.length === 0}
<div class="history-empty">No versions yet. Versions are created automatically as you edit (at least 5 minutes apart).</div>
{:else}
<div class="history-picker">
<label for="history-version-picker">Version</label>
<select id="history-version-picker" aria-label="Select snapshot version"
value={historySelected?.timestamp ?? ''}
onchange={(event) => { const version = historyVersions.find((v) => v.timestamp === event.currentTarget.value); if (version) void previewVersion(version); }}>
{#each historyVersions as version (version.timestamp)}
<option value={version.timestamp}>{formatVersionDate(version.timestamp)}</option>
{/each}
</select>
</div>
<div class="history-list">
{#each historyVersions as v}
{#each historyVersions as v (v.timestamp)}
<button
class="history-item"
class:active={historySelected?.timestamp === v.timestamp}
aria-pressed={historySelected?.timestamp === v.timestamp}
onclick={() => previewVersion(v)}
title={v.timestamp}
>
<span class="history-date">{formatVersionDate(v.timestamp)}</span>
<span class="history-size">{formatVersionSize(v.size)}</span>
@@ -7459,16 +7530,9 @@
{/each}
</div>
{/if}
{#if historySelected}
<div class="history-actions">
<button class="history-restore-btn" onclick={restoreVersion}>
Restore this version
</button>
</div>
{/if}
</div>
{/if}
{#if showOutline}
{#if showOutline && !showHistory}
<ResizeHandle onResize={handleOutlineResize} />
<div class="outline-panel" style="width: {$outlineWidth}px">
<div class="outline-header">
@@ -7496,7 +7560,7 @@
{/if}
</div>
{/if}
{#if showInfo && $activeNote}
{#if showInfo && $activeNote && !showHistory}
<div class="info-panel">
<div class="info-panel-header">
<span class="info-panel-title">Note Info</span>
@@ -7578,6 +7642,18 @@
{/if}
</div>
{#key $activeNotePath}
<details class="info-section info-frontmatter">
<summary class="info-section-label">Frontmatter</summary>
<p class="info-frontmatter-caption">Last loaded or saved YAML. Unsaved changes are not shown.</p>
{#if infoFrontmatter}
<pre aria-label="Saved frontmatter">{infoFrontmatter}</pre>
{:else}
<p class="info-frontmatter-caption">No frontmatter in this note.</p>
{/if}
</details>
{/key}
{#if onMoveToTrash && $viewMode !== 'trash'}
<div class="info-section info-actions">
<button type="button" class="info-trash-btn" onclick={moveOpenNoteToTrash} disabled={trashingNote}>
@@ -7594,7 +7670,7 @@
</div>
</div>
{#if editorReady && !$sourceMode && !$viewerNote}
{#if editorReady && !$sourceMode && !$viewerNote && !showHistory}
<!-- svelte-ignore a11y_no_static_element_interactions -->
<div
class="editor-formatting-bar"
@@ -9355,6 +9431,8 @@
position: relative;
}
.editor-body.history-hidden { display: none; }
/* Inset the scrollbar off the window's right edge so the window resize handle
(ResizeHandles in +layout) has clean space and doesn't swallow the scrollbar. */
.editor-container:not(.mobile) .editor-body {
@@ -9366,7 +9444,7 @@
}
.history-panel {
width: 240px;
width: 220px;
border-left: 1px solid var(--border-light);
background: var(--bg-secondary);
display: flex;
@@ -9379,6 +9457,7 @@
display: flex;
align-items: center;
justify-content: space-between;
flex-shrink: 0;
padding: 12px 14px;
border-bottom: 1px solid var(--border-light);
}
@@ -9425,14 +9504,27 @@
.history-list {
flex: 1;
min-height: 0;
overflow-y: auto;
padding: 4px 6px;
}
.history-retry-btn {
margin-top: 8px;
padding: 6px 10px;
border: 1px solid var(--border-color);
border-radius: 4px;
background: var(--bg-tertiary);
color: var(--text-primary);
cursor: pointer;
}
.history-item {
display: flex;
align-items: center;
justify-content: space-between;
flex-direction: column;
align-items: flex-start;
gap: 5px;
width: 100%;
padding: 8px 10px;
border: none;
@@ -9466,28 +9558,30 @@
color: var(--text-tertiary);
}
.history-actions {
padding: 8px 10px;
border-top: 1px solid var(--border-light);
}
.history-restore-btn {
.history-picker { display: none; }
.history-picker label { font-size: 12px; color: var(--text-secondary); }
.history-picker select {
width: 100%;
padding: 7px 12px;
border: 1px solid var(--accent);
min-width: 0;
padding: 8px 10px;
border: 1px solid var(--border-color);
border-radius: 6px;
background: var(--accent-light);
color: var(--accent);
background: var(--bg-primary);
color: var(--text-primary);
font-size: 12px;
font-weight: 500;
cursor: pointer;
transition: all 0.15s;
}
.history-item:focus-visible, .history-picker select:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
@media (max-width: 600px) {
.editor-body-row.reviewing-history { flex-direction: column-reverse; }
.history-panel { width: 100%; border-left: none; border-bottom: 1px solid var(--border-light); flex: none; }
.history-header { padding: 8px 12px; }
.history-header-actions > button { min-width: 44px; min-height: 44px; }
.history-list { display: none; }
.history-picker { display: flex; flex-direction: column; gap: 5px; padding: 0 12px 10px; }
.history-picker select { min-height: 44px; }
}
.history-restore-btn:hover {
background: var(--accent);
color: white;
}
.outline-panel {
width: 220px;
@@ -12272,12 +12366,10 @@
position: relative;
}
.editor-container.mobile .editor-body-row:has(.history-panel) > .editor-body,
.editor-container.mobile .editor-body-row:has(.outline-panel) > .editor-body {
display: none;
}
.editor-container.mobile .history-panel,
.editor-container.mobile .outline-panel {
position: static;
flex: 1;
@@ -12287,31 +12379,24 @@
border-left: none;
}
.editor-container.mobile .editor-body-row.reviewing-history { flex-direction: column-reverse; }
.editor-container.mobile .history-panel { width: 100%; flex: none; border-left: none; border-bottom: 1px solid var(--border-light); }
.editor-container.mobile .history-list { display: none; }
.editor-container.mobile .history-picker { display: flex; flex-direction: column; gap: 5px; padding: 0 12px 10px; }
.editor-container.mobile .history-picker select { min-height: 44px; }
.editor-container.mobile .history-item {
padding: 12px 12px;
min-height: 48px;
}
.editor-container.mobile .history-list {
padding-bottom: 80px;
.editor-container.mobile .history-create-btn,
.editor-container.mobile .history-close,
.editor-container.mobile .history-retry-btn {
min-width: 44px;
min-height: 44px;
}
.editor-container.mobile .history-restore-btn {
padding: 14px 16px;
font-size: 15px;
}
.editor-container.mobile .history-actions {
position: fixed;
bottom: 0;
left: 0;
right: 0;
padding: 12px;
padding-bottom: calc(12px + env(safe-area-inset-bottom, 0px));
background: var(--bg-secondary);
border-top: 1px solid var(--border-light);
z-index: 51;
}
.editor-container.mobile .note-search-bar {
padding: 8px 12px;
@@ -12511,6 +12596,17 @@
margin-bottom: 8px;
}
.info-frontmatter { flex-shrink: 0; }
.info-frontmatter > summary { cursor: pointer; margin-bottom: 0; padding: 2px 0; border-radius: 4px; }
.info-frontmatter[open] > summary { margin-bottom: 8px; }
.info-frontmatter > summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.info-frontmatter-caption { margin: 0 0 8px; font-size: 11px; line-height: 1.5; color: var(--text-secondary); }
.info-frontmatter pre { margin: 0; font-family: var(--font-mono, monospace); font-size: 11px; line-height: 1.6; color: var(--text-primary); white-space: pre-wrap; overflow-wrap: anywhere; }
@media (max-width: 600px) {
.info-frontmatter > summary { min-height: 44px; padding: 12px 0; }
}
.editor-container.mobile .info-frontmatter > summary { min-height: 44px; padding: 12px 0; }
.info-row {
display: flex;
align-items: baseline;
+189
View File
@@ -0,0 +1,189 @@
<script lang="ts">
import { tick } from 'svelte';
import SnapshotDocument from './SnapshotDocument.svelte';
import { compareHistory, splitSnapshot, type HistoryComparison, type HistoryRow } from '$lib/utils/history-comparison';
let { raw, current, selected, loading, error, canRestore, onRetry, onRestore, renderSnapshot }: {
raw: string | null;
current: string;
selected: string | null;
loading: boolean;
error: string | null;
canRestore: boolean;
onRetry: () => void;
onRestore: () => void;
renderSnapshot: (body: string) => string;
} = $props();
let view = $state<'changes' | 'snapshot'>('changes');
let source = $state(false);
let comparison = $state<HistoryComparison | null>(null);
let comparing = $state(false);
let comparisonError = $state<string | null>(null);
let request = 0;
const snapshot = $derived(splitSnapshot(raw ?? ''));
const rendered = $derived.by(() => {
if (view !== 'snapshot' || source || raw === null) return { html: '', error: '' };
try {
return { html: renderSnapshot(snapshot.body), error: '' };
} catch (cause) {
return { html: '', error: `Could not render this snapshot: ${String(cause)}` };
}
});
$effect(() => {
const content = raw;
const working = current;
const body = snapshot.body;
const generation = ++request;
comparison = null;
comparisonError = null;
comparing = content !== null;
if (content !== null) {
compareHistory(working, body).then((result) => {
if (generation !== request) return;
comparison = result;
}).catch((cause) => {
if (generation === request) comparisonError = `Could not compare this version: ${String(cause)}`;
}).finally(() => {
if (generation === request) comparing = false;
});
}
return () => { request++; };
});
async function navigateTabs(event: KeyboardEvent) {
if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return;
event.preventDefault();
view = event.key === 'Home' ? 'changes' : event.key === 'End' ? 'snapshot' : view === 'changes' ? 'snapshot' : 'changes';
await tick();
document.getElementById(`history-tab-${view}`)?.focus();
}
</script>
{#snippet lines(rows: HistoryRow[])}
{#each rows as row}
<div class="diff-line {row.kind}">
<span class="line-number" aria-label="Current note line">{row.currentLine ?? ''}</span>
<span class="line-number" aria-label="Snapshot line">{row.snapshotLine ?? ''}</span>
<span class="line-sign" aria-label={row.kind === 'added' ? 'Added by restoring' : row.kind === 'removed' ? 'Removed by restoring' : 'Unchanged'}>{row.kind === 'added' ? '+' : row.kind === 'removed' ? '−' : ' '}</span>
<span class="line-text">{row.text || ' '}{#if !row.newline}<span class="line-ending">No final newline</span>{/if}</span>
</div>
{/each}
{/snippet}
<section class="history-review" aria-label="Version review">
<div class="review-header">
<div class="review-heading">
<strong>{selected ?? 'Version History'}</strong>
<span>Read-only. Your current note stays unchanged.</span>
</div>
<div class="review-tabs" role="tablist" aria-label="Version view" tabindex="-1" onkeydown={navigateTabs}>
<button id="history-tab-changes" role="tab" aria-selected={view === 'changes'} aria-controls="history-changes" tabindex={view === 'changes' ? 0 : -1} onclick={() => view = 'changes'}>Changes</button>
<button id="history-tab-snapshot" role="tab" aria-selected={view === 'snapshot'} aria-controls="history-snapshot" tabindex={view === 'snapshot' ? 0 : -1} onclick={() => view = 'snapshot'}>Snapshot</button>
</div>
</div>
{#if loading}
<p class="review-status" role="status">Loading version…</p>
{:else if error}
<div class="review-status" role="alert"><p>{error}</p><button class="review-button" onclick={onRetry}>Retry</button></div>
{:else if raw === null}
<p class="review-status">Select a version to review.</p>
{:else if view === 'changes'}
<div id="history-changes" class="review-panel" role="tabpanel" aria-labelledby="history-tab-changes" tabindex="0">
<div class="comparison-heading">
<span>Current note → selected version</span>
{#if comparison}<span class="comparison-count"><span class="added-count">+{comparison.added}</span> <span class="removed-count">−{comparison.removed}</span> lines</span>{/if}
</div>
{#if comparing}
<p class="review-status" role="status">Comparing…</p>
{:else if comparisonError}
<p class="review-status" role="alert">{comparisonError}</p>
{:else if comparison && comparison.added === 0 && comparison.removed === 0}
<p class="review-status">No content changes. Metadata is not restored.</p>
{:else if comparison}
<div class="history-diff">
{#key raw}
{#each comparison.chunks as chunk}
{#if chunk.kind === 'unchanged'}
<details class="unchanged-lines"><summary>{chunk.rows.length} unchanged lines</summary>{@render lines(chunk.rows)}</details>
{:else}
{@render lines(chunk.rows)}
{/if}
{/each}
{/key}
</div>
{/if}
</div>
{:else}
<div id="history-snapshot" class="review-panel" role="tabpanel" aria-labelledby="history-tab-snapshot" tabindex="0">
<div class="snapshot-heading"><span>Selected snapshot</span><button class="source-toggle" aria-pressed={source} onclick={() => source = !source}>{source ? 'Rendered view' : 'View source'}</button></div>
{#if snapshot.body === ''}
<p class="review-status">This snapshot is empty.</p>
{:else if source}
<textarea class="snapshot-source" readonly aria-label="Snapshot Markdown, read-only" value={snapshot.body}></textarea>
{:else if rendered.error}
<p class="review-status" role="alert">{rendered.error} View source to inspect the stored body.</p>
{:else}
<SnapshotDocument html={rendered.html} />
{/if}
</div>
{/if}
{#if raw !== null && snapshot.metadata}
<details class="history-metadata"><summary>Metadata (not restored)</summary><pre>{snapshot.metadata}</pre></details>
{/if}
{#if selected}
<div class="review-actions"><span>Restore replaces the current note’s content only.</span><button class="history-restore-btn" disabled={!canRestore} onclick={onRestore}>Restore this version</button></div>
{/if}
</section>
<style>
.history-review { display: flex; flex-direction: column; flex: 1; min-width: 0; min-height: 0; background: var(--bg-primary); }
.review-header { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 12px 16px; border-bottom: 1px solid var(--border-light); flex-shrink: 0; flex-wrap: wrap; }
.review-heading { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
.review-heading strong { font-size: 13px; overflow-wrap: anywhere; }
.review-heading > span { font-size: 12px; color: var(--text-secondary); }
.review-tabs { display: flex; gap: 2px; padding: 2px; border: 1px solid var(--border-color); border-radius: 6px; }
.review-tabs button, .source-toggle, .review-button { padding: 6px 10px; border: none; border-radius: 4px; background: transparent; color: var(--text-secondary); font-size: 12px; cursor: pointer; }
.review-tabs button[aria-selected="true"] { background: var(--accent-light); color: var(--accent); }
.review-tabs button:focus-visible, .source-toggle:focus-visible, .review-button:focus-visible, summary:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
.review-panel { flex: 1; min-height: 0; overflow: auto; outline-offset: -2px; }
.review-panel:focus-visible { outline: 2px solid var(--accent); }
.comparison-heading, .snapshot-heading { display: flex; justify-content: space-between; align-items: center; gap: 12px; padding: 10px 16px; font-size: 12px; color: var(--text-secondary); border-bottom: 1px solid var(--border-light); flex-wrap: wrap; }
.comparison-count { font-family: var(--font-mono, monospace); }
.added-count { color: var(--success); } .removed-count { color: var(--danger, #dc2626); }
.review-status { margin: 0; padding: 20px 16px; color: var(--text-secondary); font-size: 13px; line-height: 1.6; overflow-wrap: anywhere; }
.review-button { margin-top: 8px; border: 1px solid var(--border-color); background: var(--bg-secondary); color: var(--text-primary); }
.history-diff { padding: 8px 0; font-family: var(--font-mono, monospace); font-size: 12px; line-height: 1.6; }
.diff-line { display: grid; grid-template-columns: 3.5em 3.5em 1.6em minmax(0, 1fr); align-items: start; padding: 1px 12px 1px 4px; }
.diff-line.added { background: color-mix(in srgb, var(--success) 12%, var(--bg-primary)); }
.diff-line.removed { background: color-mix(in srgb, var(--danger, #dc2626) 12%, var(--bg-primary)); }
.line-number { padding-right: 8px; text-align: right; color: var(--text-tertiary); user-select: none; font-size: 10px; }
.line-sign { color: var(--text-secondary); user-select: none; }
.added .line-sign { color: var(--success); } .removed .line-sign { color: var(--danger, #dc2626); }
.line-text { white-space: pre-wrap; overflow-wrap: anywhere; }
.line-ending { display: block; color: var(--text-secondary); font-style: italic; font-size: 10px; }
.unchanged-lines > summary { padding: 7px 16px; color: var(--text-secondary); background: var(--bg-secondary); cursor: pointer; font-family: var(--font-sans, inherit); font-size: 12px; }
.snapshot-source { display: block; width: 100%; min-height: 100%; margin: 0; padding: 16px; resize: none; border: none; background: var(--bg-primary); color: var(--text-primary); font-family: var(--font-mono, monospace); font-size: 13px; line-height: 1.6; }
.snapshot-source:focus-visible { outline: 2px solid var(--accent); outline-offset: -2px; }
.history-metadata { flex-shrink: 0; border-top: 1px solid var(--border-light); font-size: 12px; color: var(--text-secondary); max-height: 30%; overflow: auto; }
.history-metadata > summary { cursor: pointer; padding: 8px 16px; }
.history-metadata pre { margin: 0; padding: 0 16px 12px; font-family: var(--font-mono, monospace); font-size: 11px; white-space: pre-wrap; overflow-wrap: anywhere; }
.review-actions { display: flex; align-items: center; justify-content: space-between; gap: 12px; padding: 10px 16px; padding-bottom: calc(10px + env(safe-area-inset-bottom, 0px)); border-top: 1px solid var(--border-light); background: var(--bg-secondary); flex-shrink: 0; flex-wrap: wrap; }
.review-actions > span { font-size: 11px; color: var(--text-secondary); }
.history-restore-btn { padding: 8px 14px; border: 1px solid var(--accent); border-radius: 6px; color: var(--accent); background: var(--accent-light); font-size: 12px; font-weight: 500; cursor: pointer; }
.history-restore-btn:hover:not(:disabled) { background: var(--accent); color: var(--bg-primary); }
.history-restore-btn:disabled { opacity: 0.45; cursor: not-allowed; }
.history-restore-btn:focus-visible { outline: 2px solid var(--accent); outline-offset: 2px; }
@media (max-width: 600px) {
.review-header { padding: 10px 12px; }
.review-tabs { width: 100%; }
.review-tabs button { flex: 1; min-height: 44px; }
.source-toggle, .review-button, .history-restore-btn { min-height: 44px; }
.diff-line { grid-template-columns: 2.8em 2.8em 1.4em minmax(0, 1fr); padding-right: 8px; }
.review-actions { padding: 10px 12px; padding-bottom: calc(10px + env(safe-area-inset-bottom, 0px)); }
.review-actions > span, .history-restore-btn { width: 100%; }
}
</style>
+3 -2
View File
@@ -1466,6 +1466,7 @@
class:qa-drag-below={$viewMode === 'quickaccess' && qaDragOver === noteIndex && qaDragFrom !== null && qaDragHalf === 'bottom'}
class:note-drag-above={canCustomReorder && noteDragOver === noteIndex && noteDragFrom !== null && noteDragHalf === 'top'}
class:note-drag-below={canCustomReorder && noteDragOver === noteIndex && noteDragFrom !== null && noteDragHalf === 'bottom'}
title={$viewMode === 'quickaccess' ? note.path : (getNotebookPath(note) ? `${getNotebookPath(note)}/${note.meta.title}` : note.meta.title)}
onclick={(e) => handleNoteClick(e, note)}
onkeydown={(e) => {
if (e.key === 'F2') {
@@ -1542,7 +1543,7 @@
ondragend={() => { qaDragFrom = null; qaDragOver = null; resetNoteDrag(); }}
>
{#if compact}
<div class="note-compact-row" title={getNotebookPath(note) ? `${getNotebookPath(note)}/${note.meta.title}` : note.meta.title}>
<div class="note-compact-row">
<span class="note-title">
{#if note.meta.pinned}
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="pin-icon">
@@ -1562,7 +1563,7 @@
{#if showDates}<span class="note-date-compact" title={`Created ${formatDate(note.meta.created)}\nModified ${formatDate(note.meta.modified)}`}>{formatRelativeTime($sortMode === 'created' ? note.meta.created : note.meta.modified)}</span>{/if}
</div>
{:else}
<div class="note-title" title={getNotebookPath(note) ? `${getNotebookPath(note)}/${note.meta.title}` : note.meta.title}>
<div class="note-title">
{#if note.meta.pinned}
<svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="pin-icon">
<path d="M12 17v5"/><path d="M9 2h6l-1 7h4l-2 4H8l-2-4h4L9 2z"/>
+1 -1
View File
@@ -253,7 +253,7 @@
<section class="switcher-section" aria-labelledby={`note-switcher-${section.label.replace(' ', '-').toLowerCase()}`}>
<h2 id={`note-switcher-${section.label.replace(' ', '-').toLowerCase()}`}>{section.label}</h2>
{#each section.rows as row (row.path)}
<div class="note-row" class:current-row={row.current}>
<div class="note-row" class:current-row={row.current} title={row.path}>
{#if row.current}<span class="current-marker" aria-hidden="true"></span>{/if}
<button
class="note-primary"
+3 -1
View File
@@ -667,6 +667,8 @@
{ name: 'Open Sans', value: 'opensans', stack: '"Open Sans", -apple-system, sans-serif' },
{ name: 'Literata', value: 'literata', stack: '"Literata", Georgia, serif' },
{ name: 'Mono', value: 'mono', stack: '"JetBrains Mono", "Fira Code", "Cascadia Code", monospace' },
{ name: 'Ubuntu', value: 'ubuntu', stack: '"Ubuntu", -apple-system, sans-serif' },
{ name: 'Ubuntu Mono', value: 'ubuntu-mono', stack: '"Ubuntu Mono", monospace' },
];
const lineHeightPresets = [
@@ -1496,7 +1498,7 @@
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z"/>
</svg>
Switch Vault
Manage Vaults
</button>
</div>
{/if}
+446
View File
@@ -0,0 +1,446 @@
<script lang="ts" module>
let diagramId = 0;
// Mermaid has a shared configuration; serialize snapshot renders and restore it afterward.
let diagramQueue = Promise.resolve();
</script>
<script lang="ts">
import createDOMPurify from 'dompurify';
import katex from 'katex';
import 'katex/dist/katex.min.css';
import { calloutGroup, calloutIcon, calloutLabel } from '$lib/editor/callouts';
import { readSecretTitle } from '$lib/utils/secrets';
let { html, label = 'Snapshot preview' }: { html: string; label?: string } = $props();
let root = $state<HTMLElement>();
let purifier: ReturnType<typeof createDOMPurify>;
const documentTags = [
'a', 'abbr', 'b', 'blockquote', 'br', 'caption', 'code', 'col', 'colgroup',
'dd', 'del', 'details', 'div', 'dl', 'dt', 'em', 'figcaption', 'figure',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'kbd', 'li',
'mark', 'ol', 'p', 'pre', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'small',
'span', 'strong', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'tfoot',
'th', 'thead', 'tr', 'u', 'ul', 'var', 'wbr',
];
const documentAttributes = [
'alt', 'class', 'colspan', 'dir', 'height', 'href', 'lang', 'open', 'reversed',
'rowspan', 'scope', 'span', 'src', 'start', 'style', 'title', 'value', 'width',
'data-type', 'data-checked', 'data-size', 'data-language', 'data-secret-block',
'data-math-inline', 'data-math-block', 'data-callout', 'data-callout-title',
'data-callout-foldable', 'data-callout-folded',
'data-wiki-link', 'data-path', 'data-title', 'data-aliased', 'data-bg-color',
'data-pdf-src', 'data-pdf-name', 'data-page-break',
];
// Custom asset protocols are accepted only here, then checked specifically on images.
const documentUris = /^(?:https?:|mailto:|tel:|asset:|imgproxy:|blob:|data:image\/(?:png|jpeg|gif|webp|avif|bmp);|#)/i;
const formattingProperties = [
'color', 'background-color', 'font-weight', 'font-style', 'font-size',
'text-align', 'text-decoration-line', 'text-decoration-color', 'vertical-align',
];
function message(text: string): HTMLParagraphElement {
const node = document.createElement('p');
node.className = 'snapshot-message';
node.textContent = text;
return node;
}
function imageSourceAllowed(source: string): boolean {
if (/[\u0000-\u0020\u007f]/.test(source)) return false;
if (/^(?:asset|imgproxy):\/\//i.test(source)) return true;
if (/^data:image\/(?:png|jpeg|gif|webp|avif|bmp);base64,[a-z\d+/=]+$/i.test(source)) return true;
try {
const url = new URL(source);
if (url.protocol === 'blob:') return new URL(url.pathname).origin === window.location.origin;
return ['http:', 'https:'].includes(url.protocol)
&& ['asset.localhost', 'imgproxy.localhost'].includes(url.hostname)
&& !url.username && !url.password && !url.port;
} catch {
return false;
}
}
function keepFormatting(element: HTMLElement): void {
const style = element.style;
const values = formattingProperties.map((property) => [property, style.getPropertyValue(property)]);
element.removeAttribute('style');
for (const [property, value] of values) {
// Only presentation properties; no URL-bearing CSS, variables, escapes or overlays.
if (value && !/url\s*\(|var\s*\(|expression\s*\(|[\\@]/i.test(value)) {
element.style.setProperty(property, value);
}
}
}
function prepareDocument(fragment: DocumentFragment): void {
for (const element of fragment.querySelectorAll<HTMLElement>('*')) {
keepFormatting(element);
const language = element.tagName === 'CODE'
? Array.from(element.classList).find((name) => /^language-[\w+-]+$/.test(name))
: undefined;
element.removeAttribute('class');
if (language) element.className = language;
if (element.hasAttribute('data-wiki-link')) {
element.className = 'snapshot-wiki-link';
element.title = `Wiki link to ${element.getAttribute('data-title') || element.textContent || ''} (inactive in snapshot preview)`;
element.setAttribute('aria-disabled', 'true');
}
if (element.hasAttribute('data-page-break')) element.className = 'snapshot-page-break';
// Snapshot links are readable but inert: inspection cannot navigate the live note.
if (element.tagName === 'A') {
const href = element.getAttribute('href');
if (href) element.title = `${element.title ? element.title + ' — ' : ''}${href} (inactive in snapshot preview)`;
element.removeAttribute('href');
element.setAttribute('aria-disabled', 'true');
}
}
for (const attachment of fragment.querySelectorAll<HTMLElement>('[data-pdf-src]')) {
const name = attachment.getAttribute('data-pdf-name') || 'PDF attachment';
const source = attachment.getAttribute('data-pdf-src') || '';
attachment.prepend(message(`${name} — PDF attachment (inline PDF rendering is unavailable in snapshot previews). ${source}`));
}
for (const image of fragment.querySelectorAll<HTMLImageElement>('img')) {
const source = image.getAttribute('src') || '';
if (!imageSourceAllowed(source)) {
image.replaceWith(message(`Image unavailable or blocked${image.alt ? ': ' + image.alt : '.'}`));
continue;
}
image.crossOrigin = 'anonymous';
image.loading = 'lazy';
image.decoding = 'async';
image.addEventListener('error', () => {
image.replaceWith(message(`Image could not be loaded: ${image.alt || source}`));
}, { once: true });
}
for (const item of fragment.querySelectorAll<HTMLElement>('li[data-type="taskItem"]')) {
const body = document.createElement('div');
while (item.firstChild) body.append(item.firstChild);
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.checked = item.getAttribute('data-checked') === 'true';
checkbox.disabled = true;
checkbox.setAttribute('aria-label', checkbox.checked ? 'Completed task' : 'Incomplete task');
item.className = 'snapshot-task';
item.append(checkbox, body);
}
for (const table of fragment.querySelectorAll('table')) {
const scroll = document.createElement('div');
scroll.className = 'snapshot-table';
scroll.tabIndex = 0;
scroll.setAttribute('role', 'region');
scroll.setAttribute('aria-label', 'Snapshot table');
table.replaceWith(scroll);
scroll.append(table);
}
}
function renderSecrets(fragment: DocumentFragment): void {
for (const node of fragment.querySelectorAll<HTMLElement>('[data-secret-block]')) {
const stored = node.getAttribute('data-secret-block') || '';
node.replaceChildren();
node.className = 'snapshot-secret';
const title = document.createElement('strong');
let payload = stored;
let error = '';
try {
payload = decodeURIComponent(stored);
JSON.parse(payload);
} catch {
error = 'The stored secret payload is malformed; it cannot be previewed.';
}
title.textContent = readSecretTitle(payload);
node.append(title, message('Locked encrypted content. Secrets are not unlocked in history previews.'));
if (error) {
const details = document.createElement('details');
const summary = document.createElement('summary');
summary.textContent = 'Stored secret payload';
const code = document.createElement('pre');
code.textContent = payload;
details.append(summary, code);
node.append(message(error), details);
}
// Do not retain ciphertext in the rendered DOM unless needed for a readable error.
node.removeAttribute('data-secret-block');
}
}
function renderCallouts(fragment: DocumentFragment): void {
// Innermost first so nested callout bodies keep their independently rendered headers.
for (const node of Array.from(fragment.querySelectorAll<HTMLElement>('[data-callout]')).reverse()) {
const type = node.getAttribute('data-callout') || 'note';
const title = node.getAttribute('data-callout-title') || calloutLabel(type);
const foldable = node.getAttribute('data-callout-foldable') === 'true';
const wrapper = document.createElement(foldable ? 'details' : 'div');
wrapper.className = 'snapshot-callout';
const group = calloutGroup(type);
wrapper.style.setProperty('--snapshot-callout-color', `var(--callout-${typeof group === 'string' ? group : 'custom'})`);
if (wrapper instanceof HTMLDetailsElement) wrapper.open = node.getAttribute('data-callout-folded') !== 'true';
const header = document.createElement(foldable ? 'summary' : 'div');
header.className = 'snapshot-callout-header';
const icon = document.createElement('span');
icon.setAttribute('aria-hidden', 'true');
icon.append(purifier.sanitize(calloutIcon(type), { USE_PROFILES: { svg: true }, RETURN_DOM_FRAGMENT: true }));
const heading = document.createElement('strong');
heading.textContent = title;
header.append(icon, heading);
if (title !== calloutLabel(type)) {
const kind = document.createElement('small');
kind.textContent = calloutLabel(type);
header.append(kind);
}
const body = document.createElement('div');
body.className = 'snapshot-callout-body';
while (node.firstChild) body.append(node.firstChild);
wrapper.append(header, body);
node.replaceWith(wrapper);
}
}
function renderMath(fragment: DocumentFragment): void {
for (const node of fragment.querySelectorAll<HTMLElement>('[data-math-inline], [data-math-block]')) {
const block = node.hasAttribute('data-math-block');
const stored = node.getAttribute(block ? 'data-math-block' : 'data-math-inline') || '';
let tex = stored;
node.className = block ? 'snapshot-math-block' : 'snapshot-math-inline';
try {
tex = decodeURIComponent(stored);
const rendered = katex.renderToString(tex, { displayMode: block, trust: false, throwOnError: true });
node.replaceChildren(purifier.sanitize(rendered, {
USE_PROFILES: { html: true, mathMl: true, svg: true },
FORBID_TAGS: ['style', 'a', 'img', 'image', 'foreignobject'],
FORBID_ATTR: ['href', 'xlink:href', 'src'],
RETURN_DOM_FRAGMENT: true,
}));
} catch (error) {
const code = document.createElement('code');
code.textContent = tex;
const status = document.createElement('span');
status.className = 'snapshot-message';
status.textContent = ` Math could not be rendered: ${error instanceof Error ? error.message : String(error)}`;
node.replaceChildren(code, status);
}
node.removeAttribute('data-math-inline');
node.removeAttribute('data-math-block');
}
}
function prepareDiagrams(fragment: DocumentFragment, isCurrent: () => boolean): void {
for (const code of fragment.querySelectorAll<HTMLElement>('pre > code.language-mermaid, pre[data-language="mermaid"] > code')) {
const source = code.textContent || '';
const controls = document.createElement('div');
controls.className = 'snapshot-diagram';
const button = document.createElement('button');
button.type = 'button';
button.textContent = '▶ Render diagram';
const status = document.createElement('span');
status.className = 'snapshot-message';
status.setAttribute('role', 'status');
const output = document.createElement('div');
output.className = 'snapshot-diagram-output';
controls.append(button, status, output);
code.parentElement!.after(controls);
button.addEventListener('click', async () => {
button.disabled = true;
status.textContent = 'Rendering diagram…';
let staging: HTMLDivElement | undefined;
let restoreConfig: (() => void) | undefined;
let release!: () => void;
const previousRender = diagramQueue;
diagramQueue = new Promise<void>((resolve) => { release = resolve; });
await previousRender;
try {
const { default: mermaid } = await import('mermaid');
if (!isCurrent() || !controls.isConnected) return;
const previousConfig = mermaid.mermaidAPI.getConfig();
restoreConfig = () => mermaid.initialize(previousConfig);
mermaid.initialize({
startOnLoad: false,
securityLevel: 'strict',
suppressErrorRendering: true,
theme: document.documentElement.classList.contains('dark') ? 'dark' : 'default',
fontFamily: 'inherit',
htmlLabels: false,
flowchart: { htmlLabels: false },
secure: [
...(mermaid.mermaidAPI.defaultConfig.secure || []),
'htmlLabels', 'flowchart', 'themeCSS', 'themeVariables', 'fontFamily', 'altFontFamily', 'dompurifyConfig',
],
});
const parsed = await mermaid.mermaidAPI.getDiagramFromText(source);
// Strict Mermaid still fetches image-shape URLs during layout, before SVG sanitization.
// Inspect its parsed layout data rather than trying to rewrite the fence's source.
if ('getData' in parsed.db && typeof parsed.db.getData === 'function') {
const data: unknown = parsed.db.getData();
if (data && typeof data === 'object' && 'nodes' in data && Array.isArray(data.nodes)
&& data.nodes.some((node: unknown) => node && typeof node === 'object' && 'img' in node && node.img)) {
throw new Error('Embedded Mermaid images are not loaded in snapshot previews.');
}
}
if (!isCurrent() || !controls.isConnected) return;
staging = document.createElement('div');
staging.className = 'snapshot-diagram-staging';
staging.setAttribute('aria-hidden', 'true');
staging.inert = true;
controls.append(staging);
const { svg } = await mermaid.render(`snapshot-diagram-${++diagramId}`, source, staging);
if (!isCurrent() || !controls.isConnected) return;
const clean = purifier.sanitize(svg, {
USE_PROFILES: { svg: true },
FORBID_TAGS: ['style', 'foreignobject', 'image', 'use', 'a'],
FORBID_ATTR: ['style', 'href', 'xlink:href'],
RETURN_DOM_FRAGMENT: true,
});
const blockedContent = purifier.removed.some((entry) => 'element' in entry
&& ['foreignobject', 'image', 'use'].includes(entry.element.nodeName.toLowerCase()));
for (const element of clean.querySelectorAll('*')) {
element.removeAttribute('class');
for (const attribute of Array.from(element.attributes)) {
if (/url\s*\(/i.test(attribute.value) && !/^url\(\s*#[\w:.-]+\s*\)$/i.test(attribute.value)) {
element.removeAttribute(attribute.name);
}
}
}
const diagram = clean.querySelector('svg');
if (!diagram) throw new Error('No safe diagram output was produced.');
diagram.setAttribute('role', 'img');
diagram.setAttribute('aria-label', 'Rendered snapshot diagram; source is shown above');
output.replaceChildren(clean);
status.textContent = blockedContent
? 'Rendered with unsupported embedded content blocked. Original source remains above.'
: 'Rendered. Original source remains above.';
button.textContent = '↻ Render again';
} catch (error) {
if (isCurrent() && controls.isConnected) {
status.textContent = `Diagram could not be rendered: ${error instanceof Error ? error.message : String(error)} Original source remains above.`;
button.textContent = '↻ Retry';
}
} finally {
staging?.remove();
try {
restoreConfig?.();
} finally {
release();
button.disabled = false;
}
}
});
}
}
$effect(() => {
const source = html;
const target = root;
if (!target) return;
let active = true;
try {
purifier ??= createDOMPurify(window);
if (!purifier.isSupported) throw new Error('Safe HTML rendering is unavailable in this browser.');
const fragment = purifier.sanitize(source, {
ALLOWED_TAGS: documentTags,
ALLOWED_ATTR: documentAttributes,
ADD_URI_SAFE_ATTR: documentAttributes.filter((attribute) => attribute.startsWith('data-')),
ALLOWED_NAMESPACES: ['http://www.w3.org/1999/xhtml'],
ALLOW_DATA_ATTR: false,
ALLOW_ARIA_ATTR: false,
ALLOWED_URI_REGEXP: documentUris,
RETURN_DOM_FRAGMENT: true,
});
const blockedMarkup = purifier.removed.some((entry) => 'element' in entry
&& ['script', 'style', 'iframe', 'object', 'embed', 'form', 'input', 'textarea', 'select', 'video', 'audio', 'svg', 'math']
.includes(entry.element.nodeName.toLowerCase()));
prepareDocument(fragment);
renderSecrets(fragment);
renderCallouts(fragment);
renderMath(fragment);
prepareDiagrams(fragment, () => active && target.isConnected);
if (blockedMarkup) {
const details = document.createElement('details');
const summary = document.createElement('summary');
summary.textContent = 'Active or unsupported embedded content was blocked. View supplied HTML as text.';
const code = document.createElement('pre');
code.textContent = source;
details.append(summary, code);
fragment.prepend(details);
}
target.replaceChildren(source.trim() ? fragment : message('This snapshot has no body content.'));
} catch (error) {
const code = document.createElement('pre');
code.textContent = source;
target.replaceChildren(message(`Snapshot could not be rendered: ${error instanceof Error ? error.message : String(error)} Showing supplied HTML as text.`), code);
}
return () => { active = false; };
});
</script>
<section class="snapshot-document" aria-label={label}>
<div class="snapshot-body" bind:this={root}></div>
</section>
<style>
.snapshot-document {
min-width: 0;
max-width: 100%;
padding: 16px;
color: var(--text-primary);
font-family: var(--editor-font-family, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif);
font-size: var(--editor-font-size, 14px);
line-height: var(--editor-line-height, 1.65);
user-select: text;
overflow-wrap: anywhere;
}
.snapshot-body :global(p) { margin: 0 0 0.4em; }
.snapshot-body :global(h1) { font-size: 1.75em; margin: 1.5em 0 0.5em; }
.snapshot-body :global(h2) { font-size: 1.4em; margin: 1.25em 0 0.5em; }
.snapshot-body :global(h3) { font-size: 1.2em; margin: 1em 0 0.5em; }
.snapshot-body :global(h4), .snapshot-body :global(h5), .snapshot-body :global(h6) { margin: 0.9em 0 0.4em; }
.snapshot-body :global(h1), .snapshot-body :global(h2), .snapshot-body :global(h3) { line-height: 1.3; }
.snapshot-body > :global(:first-child) { margin-top: 0; }
.snapshot-body :global(strong) { font-weight: 600; }
.snapshot-body :global(a) { color: var(--text-accent); text-decoration: underline; }
.snapshot-body :global(blockquote) { border-left: 3px solid var(--accent); padding-left: 16px; margin: 1em 0; color: var(--text-secondary); }
.snapshot-body :global(code), .snapshot-body :global(kbd), .snapshot-body :global(pre) { font-family: var(--font-mono, monospace); }
.snapshot-body :global(code) { background: color-mix(in srgb, var(--accent) 8%, var(--bg-tertiary)); padding: 2px 6px; border-radius: 4px; font-size: 0.9em; }
.snapshot-body :global(pre) { overflow-x: auto; max-width: 100%; padding: 16px; margin: 1em 0; border-radius: 8px; background: color-mix(in srgb, var(--accent) 8%, var(--bg-tertiary)); white-space: pre; }
.snapshot-body :global(pre code) { padding: 0; background: none; font-size: 0.93em; line-height: 1.5; }
.snapshot-body :global(img) { max-width: 100%; height: auto; object-fit: contain; }
.snapshot-body :global(img[data-size="small"]) { max-width: 33%; }
.snapshot-body :global(img[data-size="medium"]) { max-width: 65%; }
.snapshot-body :global(ul), .snapshot-body :global(ol) { padding-left: 1.5em; }
.snapshot-body :global(ul[data-type="taskList"]) { padding-left: 0; list-style: none; }
.snapshot-body :global(.snapshot-task) { display: flex; align-items: flex-start; gap: 8px; list-style: none; }
.snapshot-body :global(.snapshot-task > input) { flex: none; margin-top: 0.4em; accent-color: var(--accent); }
.snapshot-body :global(.snapshot-task > div) { flex: 1; min-width: 0; }
.snapshot-body :global(details) { margin: 1em 0; }
.snapshot-body :global(summary) { cursor: pointer; }
.snapshot-body :global(.snapshot-table) { max-width: 100%; overflow-x: auto; margin: 1em 0; }
.snapshot-body :global(table) { border-collapse: collapse; min-width: 100%; }
.snapshot-body :global(th), .snapshot-body :global(td) { border: 1px solid var(--border); padding: 6px 10px; vertical-align: top; }
.snapshot-body :global(th) { background: var(--bg-secondary); font-weight: 600; }
.snapshot-body :global(.snapshot-secret) { margin: 1em 0; padding: 12px; border: 1px solid var(--border); border-radius: 8px; background: color-mix(in srgb, var(--accent) 7%, var(--bg-secondary)); }
.snapshot-body :global(.snapshot-message) { color: var(--text-secondary); font-size: 0.9em; }
.snapshot-body :global(.snapshot-wiki-link) { color: var(--text-accent); text-decoration: underline; text-decoration-style: dotted; }
.snapshot-body :global(.snapshot-page-break) { margin: 1em 0; border-top: 1px dashed var(--border); }
.snapshot-body :global(.snapshot-page-break)::before { content: 'Page break'; color: var(--text-tertiary); font-size: 0.8em; }
.snapshot-body :global(.snapshot-callout) { border: 1px solid rgba(var(--snapshot-callout-color), 0.3); border-left: 3px solid rgb(var(--snapshot-callout-color)); border-radius: 8px; background: rgba(var(--snapshot-callout-color), 0.06); margin: 1em 0; }
.snapshot-body :global(.snapshot-callout-header) { padding: 8px 12px; color: rgb(var(--snapshot-callout-color)); }
.snapshot-body :global(.snapshot-callout-header > span) { display: inline-flex; vertical-align: middle; margin-right: 8px; }
.snapshot-body :global(.snapshot-callout-header > small) { margin-left: 8px; }
.snapshot-body :global(.snapshot-callout-body) { padding: 8px 14px 10px; }
.snapshot-body :global(.snapshot-math-block) { overflow-x: auto; margin: 16px 0; padding: 12px; text-align: center; }
.snapshot-body :global(.snapshot-math-block .katex-display) { margin: 0; }
.snapshot-body :global(.snapshot-diagram) { position: relative; margin: -0.5em 0 1em; }
.snapshot-body :global(.snapshot-diagram button) { border: 1px solid var(--border); border-radius: 6px; padding: 7px 14px; background: var(--bg-tertiary); color: var(--text-primary); font: inherit; font-size: 0.9em; cursor: pointer; }
.snapshot-body :global(.snapshot-diagram button:hover:not(:disabled)) { border-color: var(--accent); }
.snapshot-body :global(.snapshot-diagram button:disabled) { opacity: 0.6; cursor: wait; }
.snapshot-body :global(.snapshot-diagram [role="status"]) { display: block; margin-top: 6px; }
.snapshot-body :global(.snapshot-diagram-output) { overflow-x: auto; max-width: 100%; }
.snapshot-body :global(.snapshot-diagram-output svg) { max-width: 100%; height: auto; color: var(--text-primary); }
/* SVG stylesheets are removed; these local rules keep untrusted diagrams legible. */
.snapshot-body :global(.snapshot-diagram-output svg text), .snapshot-body :global(.snapshot-diagram-output svg tspan) { fill: var(--text-primary); font-family: inherit; }
.snapshot-body :global(.snapshot-diagram-output svg path), .snapshot-body :global(.snapshot-diagram-output svg line), .snapshot-body :global(.snapshot-diagram-output svg polyline) { stroke: var(--text-secondary); fill: none; }
.snapshot-body :global(.snapshot-diagram-output svg rect), .snapshot-body :global(.snapshot-diagram-output svg circle), .snapshot-body :global(.snapshot-diagram-output svg ellipse), .snapshot-body :global(.snapshot-diagram-output svg polygon) { stroke: var(--text-secondary); fill: var(--bg-secondary); }
.snapshot-body :global(.snapshot-diagram-output svg marker path) { fill: var(--text-secondary); }
.snapshot-body :global(.snapshot-diagram-staging) { position: absolute; visibility: hidden; pointer-events: none; width: 100%; }
.snapshot-body :global(summary:focus-visible), .snapshot-body :global(button:focus-visible), .snapshot-body :global(.snapshot-table:focus-visible) { outline: 2px solid var(--accent); outline-offset: 3px; }
</style>
+51 -15
View File
@@ -4,9 +4,11 @@
import { getTasks } from '$lib/api';
import { debounce } from '$lib/utils/debounce';
import { tasksLayout, tasksHideCompleted, tasksOnlyFlagged, tasksSort, appConfig } from '$lib/stores/app';
import { isAndroid } from '$lib/platform';
import { isAndroid, isMobile } from '$lib/platform';
import type { TaskItem, FileEvent } from '$lib/types';
import { isCurrentVaultEvent } from '$lib/utils/note-list-updates';
import { formatLocalDate } from '$lib/utils/time';
import { matchesTaskDueFilter, type TaskDueFilter } from '$lib/utils/task-filter';
let { onOpenTask = (_t: TaskItem) => {}, onToggleTask = async (_t: TaskItem) => {}, onSetTaskPriority = async (_t: TaskItem, _p: string | null) => {}, onSetTaskDue = async (_t: TaskItem, _d: string | null) => {} }: {
onOpenTask?: (t: TaskItem) => void;
@@ -86,6 +88,19 @@
onMount(() => {
void load();
let dayTimer: ReturnType<typeof setTimeout> | undefined;
const refreshDay = () => {
const now = new Date();
today = formatLocalDate(now);
clearTimeout(dayTimer);
const nextDay = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1);
dayTimer = setTimeout(refreshDay, nextDay.getTime() - now.getTime() + 1);
};
const resumeDay = () => {
if (document.visibilityState === 'visible') refreshDay();
};
refreshDay();
document.addEventListener('visibilitychange', resumeDay);
listen<FileEvent>('file-changed', ({ payload }) => handleFileChange(payload)).then((u) => {
if (disposed) u();
else unlisten = u;
@@ -94,11 +109,13 @@
disposed = true;
fullLoad += 1;
unlisten?.();
clearTimeout(dayTimer);
document.removeEventListener('visibilitychange', resumeDay);
};
});
// Local YYYY-MM-DD (en-CA gives ISO-style date)
const today = new Date().toLocaleDateString('en-CA');
let today = $state(formatLocalDate(new Date()));
let dueFilter = $state<TaskDueFilter>('all');
const prioRank: Record<string, number> = { high: 0, med: 1, low: 2 };
function prank(p: string | null) { return p ? (prioRank[p] ?? 3) : 3; }
@@ -109,11 +126,15 @@
return t.text.toLowerCase().includes(q) || t.note_title.toLowerCase().includes(q);
}
const matchingTasks = $derived(tasks.filter((t) =>
(!$tasksHideCompleted || !t.completed)
&& (!$tasksOnlyFlagged || !!t.due || !!t.priority)
&& matchesQuery(t)
&& matchesTaskDueFilter(t.due, dueFilter, today)
));
const filtered = $derived.by(() => {
let list = tasks.slice();
if ($tasksHideCompleted) list = list.filter((t) => !t.completed);
if ($tasksOnlyFlagged) list = list.filter((t) => !!t.due || !!t.priority);
list = list.filter(matchesQuery);
const list = matchingTasks.slice();
list.sort((a, b) => {
if (a.completed !== b.completed) return a.completed ? 1 : -1; // done last
if ($tasksSort === 'priority') {
@@ -168,7 +189,7 @@
const calNow = new Date();
let calMonth = $state(calNow.getMonth());
let calYear = $state(calNow.getFullYear());
let selectedDate = $state(today);
let selectedDate = $state(formatLocalDate(calNow));
const calMonthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
// 0 = Sunday, 1 = Monday (default). Day names + grid offset follow the setting.
@@ -176,12 +197,9 @@
const DOW = ['Su', 'Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa'];
const calDayNames = $derived([...DOW.slice(weekStartsOn), ...DOW.slice(0, weekStartsOn)]);
// Calendar tasks share the list's hide-completed filter (no sort).
const calBase = $derived(tasks.filter((t) => (!$tasksHideCompleted || !t.completed) && (!$tasksOnlyFlagged || !!t.due || !!t.priority) && matchesQuery(t)));
const tasksByDate = $derived.by(() => {
const m = new Map<string, TaskItem[]>();
for (const t of calBase) {
for (const t of matchingTasks) {
if (!t.due) continue;
const arr = m.get(t.due);
if (arr) arr.push(t);
@@ -190,7 +208,7 @@
return m;
});
const undatedTasks = $derived(calBase.filter((t) => !t.due));
const undatedTasks = $derived(matchingTasks.filter((t) => !t.due));
function byPriority(a: TaskItem, b: TaskItem) {
if (a.completed !== b.completed) return a.completed ? 1 : -1;
@@ -247,13 +265,15 @@
}
</script>
<div class="tasks-view">
<div class="tasks-view" class:mobile={isMobile}>
{#if prioMenuFor || dueMenuFor}
<!-- svelte-ignore a11y_consider_explicit_label -->
<button class="prio-backdrop" onclick={() => { prioMenuFor = null; dueMenuFor = null; }} aria-label="Close menu"></button>
{/if}
<div class="tasks-controls">
<input class="tasks-filter" type="text" placeholder="Filter tasks…" bind:value={taskQuery} onkeydown={(e) => { if (e.key === 'Escape') taskQuery = ''; }} aria-label="Filter tasks by text" />
<button class="tasks-ctl" class:active={dueFilter === 'today'} aria-pressed={dueFilter === 'today'} onclick={() => { dueFilter = dueFilter === 'today' ? 'all' : 'today'; if (dueFilter === 'today') calToday(); }} title="Show tasks due today">Today</button>
<button class="tasks-ctl" class:active={dueFilter === 'overdue'} aria-pressed={dueFilter === 'overdue'} onclick={() => { dueFilter = dueFilter === 'overdue' ? 'all' : 'overdue'; }} title="Show tasks due before today">Overdue</button>
<button class="tasks-ctl" class:active={$tasksHideCompleted} onclick={() => ($tasksHideCompleted = !$tasksHideCompleted)} title="Hide completed tasks">Hide done</button>
<button class="tasks-ctl" class:active={$tasksOnlyFlagged} onclick={() => ($tasksOnlyFlagged = !$tasksOnlyFlagged)} title="Only show tasks with a due date or priority">Flagged</button>
{#if !isAndroid}
@@ -388,7 +408,15 @@
</div>
</div>
{:else if filtered.length === 0}
<div class="tasks-empty">No tasks. Add <code>- [ ] something</code> to any note.{#if openCount === 0 && tasks.length}{' '}All done!{/if}</div>
<div class="tasks-empty">
{#if tasks.length === 0}
No tasks. Add <code>- [ ] something</code> to any note.
{:else if $tasksHideCompleted && openCount === 0}
All tasks are complete.
{:else}
No tasks match these filters.
{/if}
</div>
{:else}
<div class="tasks-list">
{#each filtered as t (rowKey(t))}{@render taskRow(t, false)}{/each}
@@ -444,6 +472,14 @@
color: var(--text-primary);
font-size: 12px;
}
.tasks-view.mobile .tasks-filter {
flex-basis: 100%;
min-height: 44px;
}
.tasks-view.mobile .tasks-ctl {
min-width: 44px;
min-height: 44px;
}
.tasks-filter::placeholder { color: var(--text-tertiary); }
.tasks-filter:focus { outline: none; border-color: var(--accent); }
.tasks-list {
+1 -1
View File
@@ -96,7 +96,7 @@
</div>
{/if}
<div class="titlebar-actions">
<button class="switch-vault-btn" onclick={async () => { if (await onBeforeVaultSwitch()) $vaultReady = false; }} title="Switch Vault">
<button class="switch-vault-btn" onclick={async () => { if (await onBeforeVaultSwitch()) $vaultReady = false; }} title="Manage Vaults" aria-label="Manage Vaults">
<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
<path d="M22 19a2 2 0 01-2 2H4a2 2 0 01-2-2V5a2 2 0 012-2h5l2 3h9a2 2 0 012 2z" />
</svg>
+261
View File
@@ -0,0 +1,261 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { compareHistory, splitSnapshot } from './history-comparison.ts';
function rowsOf(comparison) {
return comparison.chunks.flatMap((chunk) => chunk.rows);
}
async function compare(current, snapshot) {
const comparison = await compareHistory(current, snapshot);
const rows = rowsOf(comparison);
const normalize = (body) => body.replace(/\r\n/g, '\n');
const restoreText = (excludedKind) => rows
.filter((row) => row.kind !== excludedKind)
.map((row) => row.text + (row.newline ? '\n' : ''))
.join('');
assert.equal(restoreText('added'), normalize(current), 'all current content is retained');
assert.equal(restoreText('removed'), normalize(snapshot), 'all snapshot content is retained');
assert.equal(comparison.added, rows.filter((row) => row.kind === 'added').length);
assert.equal(comparison.removed, rows.filter((row) => row.kind === 'removed').length);
let currentLine = 1;
let snapshotLine = 1;
for (const row of rows) {
assert.equal(row.currentLine, row.kind === 'added' ? null : currentLine++);
assert.equal(row.snapshotLine, row.kind === 'removed' ? null : snapshotLine++);
assert.equal(typeof row.newline, 'boolean');
assert.equal(row.text.includes('\n'), false);
}
for (let index = 0; index < comparison.chunks.length; index++) {
const chunk = comparison.chunks[index];
assert.ok(chunk.rows.length > 0, 'empty chunks are not displayed');
assert.notEqual(chunk.kind, comparison.chunks[index - 1]?.kind, 'adjacent chunks are merged');
if (chunk.kind === 'unchanged') {
assert.ok(chunk.rows.every((row) => row.kind === 'same'));
}
}
return comparison;
}
function lines(count) {
return Array.from({ length: count }, (_, index) => `line ${index + 1}`);
}
function document(lines) {
return lines.join('\n') + '\n';
}
test('restoring a snapshot adds snapshot-only lines and removes current-only lines', async () => {
const comparison = await compare('keep\nlive\n', 'keep\narchived\nextra\n');
assert.equal(comparison.added, 2);
assert.equal(comparison.removed, 1);
assert.deepEqual(rowsOf(comparison).map((row) => [row.kind, row.text]), [
['same', 'keep'],
['removed', 'live'],
['added', 'archived'],
['added', 'extra'],
]);
});
test('insertion keeps both line-number columns aligned with their own documents', async () => {
const comparison = await compare('first\nlast', 'first\ninserted\nlast');
assert.deepEqual(rowsOf(comparison), [
{ kind: 'same', text: 'first', currentLine: 1, snapshotLine: 1, newline: true },
{ kind: 'added', text: 'inserted', currentLine: null, snapshotLine: 2, newline: true },
{ kind: 'same', text: 'last', currentLine: 2, snapshotLine: 3, newline: false },
]);
});
test('deletion leaves snapshot line numbers unchanged by removed rows', async () => {
const comparison = await compare('first\ndeleted\nlast', 'first\nlast');
assert.deepEqual(rowsOf(comparison), [
{ kind: 'same', text: 'first', currentLine: 1, snapshotLine: 1, newline: true },
{ kind: 'removed', text: 'deleted', currentLine: 2, snapshotLine: null, newline: true },
{ kind: 'same', text: 'last', currentLine: 3, snapshotLine: 2, newline: false },
]);
});
test('replacement presents the current line before its snapshot replacement', async () => {
const comparison = await compare('first\nlive\nlast\n', 'first\narchived\nlast\n');
assert.deepEqual(rowsOf(comparison), [
{ kind: 'same', text: 'first', currentLine: 1, snapshotLine: 1, newline: true },
{ kind: 'removed', text: 'live', currentLine: 2, snapshotLine: null, newline: true },
{ kind: 'added', text: 'archived', currentLine: null, snapshotLine: 2, newline: true },
{ kind: 'same', text: 'last', currentLine: 3, snapshotLine: 3, newline: true },
]);
});
test('empty bodies and blank lines remain distinct without phantom trailing rows', async () => {
const cases = [
['', '', 0, 0],
['', '\n', 1, 0],
['\n', '', 0, 1],
['', '\n\n', 2, 0],
['\n', '\n', 0, 0],
['\n\n', '\n', 0, 1],
['', 'text', 1, 0],
['text', '', 0, 1],
];
for (const [current, snapshot, added, removed] of cases) {
const comparison = await compare(current, snapshot);
assert.equal(comparison.added, added);
assert.equal(comparison.removed, removed);
}
assert.deepEqual((await compare('', '')).chunks, []);
assert.deepEqual(rowsOf(await compare('', '\n')), [
{ kind: 'added', text: '', currentLine: null, snapshotLine: 1, newline: true },
]);
});
test('adding a final newline is visible even when the line text is identical', async () => {
const comparison = await compare('last', 'last\n');
assert.equal(comparison.added, 1);
assert.equal(comparison.removed, 1);
assert.deepEqual(rowsOf(comparison), [
{ kind: 'removed', text: 'last', currentLine: 1, snapshotLine: null, newline: false },
{ kind: 'added', text: 'last', currentLine: null, snapshotLine: 1, newline: true },
]);
});
test('removing a final newline retains the visible missing-newline flag', async () => {
const comparison = await compare('last\n', 'last');
assert.deepEqual(rowsOf(comparison).map((row) => [row.kind, row.text, row.newline]), [
['removed', 'last', true],
['added', 'last', false],
]);
});
test('CRLF-only differences compare equal, including blank lines and the final newline', async () => {
const comparison = await compare('first\r\n\r\nlast\r\n', 'first\n\nlast\n');
assert.equal(comparison.added, 0);
assert.equal(comparison.removed, 0);
assert.deepEqual(rowsOf(comparison).map((row) => [row.text, row.newline]), [
['first', true], ['', true], ['last', true],
]);
const withoutFinalNewline = await compare('last\r\n', 'last');
assert.equal(withoutFinalNewline.added, 1);
assert.equal(withoutFinalNewline.removed, 1);
});
test('whitespace and standalone carriage returns are not ignored', async () => {
const whitespace = await compare('same \n\t\nlast', 'same\n \nlast');
assert.equal(whitespace.added, 2);
assert.equal(whitespace.removed, 2);
const carriageReturn = await compare('first\rlast', 'firstlast');
assert.equal(carriageReturn.added, 1);
assert.equal(carriageReturn.removed, 1);
assert.equal(rowsOf(carriageReturn)[0].text, 'first\rlast');
});
test('snapshot splitting retains raw BOM/CRLF metadata and untouched body bytes', () => {
const metadata = '\uFEFF---\r\ntitle: Snapshot\r\ndescription: "inline --- stays here"\r\n---\r\n';
const body = '# Body\r\n\r\n---\r\ntrailing spaces ';
assert.deepEqual(splitSnapshot(metadata + body), { metadata, body });
});
test('frontmatter closes only at a complete delimiter line, not inline YAML values', () => {
const metadata = '---\ntitle: "before --- after"\nother: ---\n---\n';
const body = 'body\n---\nremaining body\n';
assert.deepEqual(splitSnapshot(metadata + body), { metadata, body });
assert.deepEqual(splitSnapshot('---\n---'), { metadata: '---\n---', body: '' });
assert.deepEqual(splitSnapshot('---\ntitle: archived\n---'), {
metadata: '---\ntitle: archived\n---', body: '',
});
});
test('incomplete, nonleading and non-line delimiters remain entirely in the body', () => {
const bodies = [
'',
'---',
'---\ntitle: "inline --- is not a closing line"\nbody',
'---\ntitle: archived\n--- suffix\nbody',
'---\ntitle: archived\r---\nbody',
'---\ntitle: archived\n---\r',
'intro\n---\ntitle: archived\n---\nbody',
' ---\ntitle: archived\n---\nbody',
'\uFEFFbody\r\n',
];
for (const body of bodies) {
assert.deepEqual(splitSnapshot(body), { body, metadata: '' });
}
});
test('metadata changes do not become body changes when consumers compare split bodies', async () => {
const current = splitSnapshot('---\ntitle: Live\ntags: [live]\n---\nsame body\n');
const snapshot = splitSnapshot('---\ntitle: Archived\ntags: [old]\n---\nsame body\n');
const comparison = await compare(current.body, snapshot.body);
assert.notEqual(current.metadata, snapshot.metadata);
assert.equal(comparison.added, 0);
assert.equal(comparison.removed, 0);
});
test('long edge runs retain all hidden rows with exactly three visible context lines', async () => {
const current = lines(25);
const snapshot = [...current];
snapshot[12] = 'archived line 13';
const comparison = await compare(document(current), document(snapshot));
assert.deepEqual(comparison.chunks.map((chunk) => [chunk.kind, chunk.rows.length]), [
['unchanged', 9], ['lines', 8], ['unchanged', 9],
]);
assert.deepEqual(comparison.chunks[1].rows.map((row) => row.text), [
'line 10', 'line 11', 'line 12', 'line 13', 'archived line 13',
'line 14', 'line 15', 'line 16',
]);
assert.deepEqual(comparison.chunks[0].rows.map((row) => row.currentLine), [1, 2, 3, 4, 5, 6, 7, 8, 9]);
assert.deepEqual(comparison.chunks[2].rows.map((row) => row.snapshotLine), [17, 18, 19, 20, 21, 22, 23, 24, 25]);
});
test('long middle runs preserve three context rows on each side for expansion', async () => {
const current = lines(16);
const snapshot = [...current];
snapshot[0] = 'archived first';
snapshot[15] = 'archived last';
const comparison = await compare(document(current), document(snapshot));
assert.deepEqual(comparison.chunks.map((chunk) => [chunk.kind, chunk.rows.length]), [
['lines', 5], ['unchanged', 8], ['lines', 5],
]);
assert.deepEqual(comparison.chunks[0].rows.filter((row) => row.kind === 'same').map((row) => row.text), [
'line 2', 'line 3', 'line 4',
]);
assert.deepEqual(comparison.chunks[1].rows.map((row) => row.text), current.slice(4, 12));
assert.deepEqual(comparison.chunks[2].rows.filter((row) => row.kind === 'same').map((row) => row.text), [
'line 13', 'line 14', 'line 15',
]);
});
test('overlapping context is not duplicated and the seventh middle line can collapse', async () => {
for (const unchangedCount of [6, 7]) {
const current = ['live first', ...lines(unchangedCount), 'live last'];
const snapshot = ['archived first', ...lines(unchangedCount), 'archived last'];
const comparison = await compare(document(current), document(snapshot));
const hidden = comparison.chunks.filter((chunk) => chunk.kind === 'unchanged');
assert.equal(hidden.length, unchangedCount === 6 ? 0 : 1);
if (hidden.length) assert.deepEqual(hidden[0].rows.map((row) => row.text), ['line 4']);
assert.equal(rowsOf(comparison).filter((row) => row.kind === 'same').length, unchangedCount);
}
});
test('identical notes have zero additions/removals and retain long unchanged content', async () => {
const short = await compare('same\nbody', 'same\nbody');
assert.equal(short.added, 0);
assert.equal(short.removed, 0);
assert.deepEqual(short.chunks.map((chunk) => chunk.kind), ['lines']);
const body = document(lines(3000));
const long = await compare(body, body);
assert.equal(long.added, 0);
assert.equal(long.removed, 0);
assert.deepEqual(long.chunks.map((chunk) => [chunk.kind, chunk.rows.length]), [['unchanged', 3000]]);
});
test('large notes preserve hidden content as well as an appended snapshot line', async () => {
const current = document(lines(3000));
const comparison = await compare(current, current + 'appended\n');
assert.equal(comparison.added, 1);
assert.equal(comparison.removed, 0);
assert.deepEqual(comparison.chunks.map((chunk) => [chunk.kind, chunk.rows.length]), [
['unchanged', 2997], ['lines', 4],
]);
});
+96
View File
@@ -0,0 +1,96 @@
import { diffLines, type Change } from 'diff';
export interface HistoryRow {
kind: 'same' | 'added' | 'removed';
text: string;
currentLine: number | null;
snapshotLine: number | null;
/** Whether this line has a terminating LF; CRLF is normalized for comparison. */
newline: boolean;
}
export interface HistoryChunk {
kind: 'lines' | 'unchanged';
rows: HistoryRow[];
}
export interface HistoryComparison {
added: number;
removed: number;
chunks: HistoryChunk[];
}
/** Separate only a complete leading frontmatter block, keeping both slices verbatim. */
export function splitSnapshot(raw: string): { body: string; metadata: string } {
const opening = /^(?:\uFEFF)?---\r?\n/.exec(raw);
if (!opening) return { body: raw, metadata: '' };
const closingDelimiter = /\n---(?:\r?\n|$)/g;
closingDelimiter.lastIndex = opening[0].length - 1;
const closing = closingDelimiter.exec(raw);
if (!closing) return { body: raw, metadata: '' };
const bodyStart = closing.index + closing[0].length;
return { body: raw.slice(bodyStart), metadata: raw.slice(0, bodyStart) };
}
/** Added/removed rows describe restoring the snapshot over the current editor body. */
export async function compareHistory(
currentBody: string,
snapshotBody: string,
): Promise<HistoryComparison> {
const changes = await new Promise<Change[]>((resolve) => {
diffLines(currentBody, snapshotBody, {
stripTrailingCr: true,
callback: resolve,
});
});
const chunks: HistoryChunk[] = [];
let added = 0;
let removed = 0;
let currentLine = 1;
let snapshotLine = 1;
const contextLines = 3;
for (let changeIndex = 0; changeIndex < changes.length; changeIndex++) {
const change = changes[changeIndex];
const kind: HistoryRow['kind'] = change.added ? 'added' : change.removed ? 'removed' : 'same';
const leadingContext = changeIndex > 0 ? contextLines : 0;
const trailingContext = changeIndex < changes.length - 1 ? contextLines : 0;
const collapse = kind === 'same' && change.count > (
changes.length === 1 ? contextLines * 2 : leadingContext + trailingContext
);
let offset = 0;
let rowIndex = 0;
while (offset < change.value.length) {
const newlineIndex = change.value.indexOf('\n', offset);
const newline = newlineIndex !== -1;
const end = newline ? newlineIndex : change.value.length;
const chunkKind: HistoryChunk['kind'] = collapse
&& rowIndex >= leadingContext
&& rowIndex < change.count - trailingContext
? 'unchanged'
: 'lines';
let chunk = chunks[chunks.length - 1];
if (!chunk || chunk.kind !== chunkKind) {
chunk = { kind: chunkKind, rows: [] };
chunks.push(chunk);
}
chunk.rows.push({
kind,
text: change.value.slice(offset, end),
currentLine: kind === 'added' ? null : currentLine++,
snapshotLine: kind === 'removed' ? null : snapshotLine++,
newline,
});
if (kind === 'added') added++;
if (kind === 'removed') removed++;
offset = newline ? end + 1 : end;
rowIndex++;
}
}
return { added, removed, chunks };
}
+25
View File
@@ -0,0 +1,25 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { matchesTaskDueFilter } from './task-filter.ts';
import { formatLocalDate } from './time.ts';
const today = '2027-01-01';
const dates = [null, '2026-12-31', today, '2027-01-02'];
test('Today includes only tasks due on the current local day', () => {
assert.deepEqual(dates.filter(due => matchesTaskDueFilter(due, 'today', today)), [today]);
});
test('Overdue excludes today, future dates, and undated tasks across a year boundary', () => {
assert.deepEqual(dates.filter(due => matchesTaskDueFilter(due, 'overdue', today)), ['2026-12-31']);
});
test('clearing the date filter restores dated and undated tasks', () => {
assert.equal(matchesTaskDueFilter(null, 'all', today), true);
assert.equal(matchesTaskDueFilter('2027-01-02', 'all', today), true);
});
test('task date keys use the local calendar rather than a locale-specific display string', () => {
assert.equal(formatLocalDate(new Date(2026, 11, 31, 23, 59)), '2026-12-31');
assert.equal(formatLocalDate(new Date(2027, 0, 1, 0, 0)), '2027-01-01');
});
+7
View File
@@ -0,0 +1,7 @@
export type TaskDueFilter = 'all' | 'today' | 'overdue';
export function matchesTaskDueFilter(due: string | null, filter: TaskDueFilter, today: string): boolean {
if (filter === 'all') return true;
if (!due) return false;
return filter === 'today' ? due === today : due < today;
}
+20
View File
@@ -0,0 +1,20 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { formatClockTime } from './time.ts';
const at = (hour, minute) => new Date(2026, 1, 15, hour, minute);
test('12-hour insertion distinguishes midnight, noon, and evening', () => {
assert.equal(formatClockTime(at(0, 7), '12h'), '12:07 AM');
assert.equal(formatClockTime(at(12, 0), '12h'), '12:00 PM');
assert.equal(formatClockTime(at(23, 5), '12h'), '11:05 PM');
});
test('24-hour insertion retains zero-padded clock values', () => {
assert.equal(formatClockTime(at(0, 7), '24h'), '00:07');
assert.equal(formatClockTime(at(23, 5), '24h'), '23:05');
});
test('relative display mode inserts an absolute time rather than an aging label', () => {
assert.equal(formatClockTime(at(17, 28), 'relative'), '17:28');
});
+16
View File
@@ -9,6 +9,22 @@ const fullDateFormatter = new Intl.DateTimeFormat(undefined, {
const monthFormatter = new Intl.DateTimeFormat(undefined, { month: 'long' });
const monthYearFormatter = new Intl.DateTimeFormat(undefined, { month: 'long', year: 'numeric' });
export function formatLocalDate(date: Date): string {
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
return `${date.getFullYear()}-${month}-${day}`;
}
export function formatClockTime(date: Date, timeFormat?: string): string {
const hours = date.getHours();
const minutes = String(date.getMinutes()).padStart(2, '0');
if (timeFormat === '12h') {
return `${hours % 12 || 12}:${minutes} ${hours < 12 ? 'AM' : 'PM'}`;
}
// Relative labels are for display, not text permanently inserted into a note.
return `${String(hours).padStart(2, '0')}:${minutes}`;
}
export function formatRelativeTime(dateStr: string): string {
const date = new Date(dateStr);
if (Number.isNaN(date.getTime())) return date.toString();
+2
View File
@@ -215,6 +215,8 @@
opensans: '"Open Sans", -apple-system, sans-serif',
literata: '"Literata", Georgia, serif',
mono: '"JetBrains Mono", "Fira Code", "Cascadia Code", monospace',
ubuntu: '"Ubuntu", -apple-system, sans-serif',
'ubuntu-mono': '"Ubuntu Mono", monospace',
};
const stack = fontStacks[config.font_family];
if (stack) document.documentElement.style.setProperty('--editor-font-family', stack);
+96
View File
@@ -0,0 +1,96 @@
-------------------------------
UBUNTU FONT LICENCE Version 1.0
-------------------------------
PREAMBLE
This licence allows the licensed fonts to be used, studied, modified and
redistributed freely. The fonts, including any derivative works, can be
bundled, embedded, and redistributed provided the terms of this licence
are met. The fonts and derivatives, however, cannot be released under
any other licence. The requirement for fonts to remain under this
licence does not require any document created using the fonts or their
derivatives to be published under this licence, as long as the primary
purpose of the document is not to be a vehicle for the distribution of
the fonts.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this licence and clearly marked as such. This may
include source files, build scripts and documentation.
"Original Version" refers to the collection of Font Software components
as received under this licence.
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to
a new environment.
"Copyright Holder(s)" refers to all individuals and companies who have a
copyright ownership of the Font Software.
"Substantially Changed" refers to Modified Versions which can be easily
identified as dissimilar to the Font Software by users of the Font
Software comparing the Original Version with the Modified Version.
To "Propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification and with or without charging
a redistribution fee), making available to the public, and in some
countries other activities as well.
PERMISSION & CONDITIONS
This licence does not grant any rights under trademark law and all such
rights are reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of the Font Software, to propagate the Font Software, subject to
the below conditions:
1) Each copy of the Font Software must contain the above copyright
notice and this licence. These can be included either as stand-alone
text files, human-readable headers or in the appropriate machine-
readable metadata fields within text or binary files as long as those
fields can be easily viewed by the user.
2) The font name complies with the following:
(a) The Original Version must retain its name, unmodified.
(b) Modified Versions which are Substantially Changed must be renamed to
avoid use of the name of the Original Version or similar names entirely.
(c) Modified Versions which are not Substantially Changed must be
renamed to both (i) retain the name of the Original Version and (ii) add
additional naming elements to distinguish the Modified Version from the
Original Version. The name of such Modified Versions must be the name of
the Original Version, with "derivative X" where X represents the name of
the new work, appended to that name.
3) The name(s) of the Copyright Holder(s) and any contributor to the
Font Software shall not be used to promote, endorse or advertise any
Modified Version, except (i) as required by this licence, (ii) to
acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with
their explicit written permission.
4) The Font Software, modified or unmodified, in part or in whole, must
be distributed entirely under this licence, and must not be distributed
under any other licence. The requirement for fonts to remain under this
licence does not affect any document created using the Font Software,
except any version of the Font Software extracted from a document
created using the Font Software may only be distributed under this
licence.
TERMINATION
This licence becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
Copyright 2010,2011 Canonical Ltd.
This Font Software is licensed under the Ubuntu Font Licence, Version
1.0. https://launchpad.net/ubuntu-font-licence
+96
View File
@@ -0,0 +1,96 @@
-------------------------------
UBUNTU FONT LICENCE Version 1.0
-------------------------------
PREAMBLE
This licence allows the licensed fonts to be used, studied, modified and
redistributed freely. The fonts, including any derivative works, can be
bundled, embedded, and redistributed provided the terms of this licence
are met. The fonts and derivatives, however, cannot be released under
any other licence. The requirement for fonts to remain under this
licence does not require any document created using the fonts or their
derivatives to be published under this licence, as long as the primary
purpose of the document is not to be a vehicle for the distribution of
the fonts.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this licence and clearly marked as such. This may
include source files, build scripts and documentation.
"Original Version" refers to the collection of Font Software components
as received under this licence.
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to
a new environment.
"Copyright Holder(s)" refers to all individuals and companies who have a
copyright ownership of the Font Software.
"Substantially Changed" refers to Modified Versions which can be easily
identified as dissimilar to the Font Software by users of the Font
Software comparing the Original Version with the Modified Version.
To "Propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification and with or without charging
a redistribution fee), making available to the public, and in some
countries other activities as well.
PERMISSION & CONDITIONS
This licence does not grant any rights under trademark law and all such
rights are reserved.
Permission is hereby granted, free of charge, to any person obtaining a
copy of the Font Software, to propagate the Font Software, subject to
the below conditions:
1) Each copy of the Font Software must contain the above copyright
notice and this licence. These can be included either as stand-alone
text files, human-readable headers or in the appropriate machine-
readable metadata fields within text or binary files as long as those
fields can be easily viewed by the user.
2) The font name complies with the following:
(a) The Original Version must retain its name, unmodified.
(b) Modified Versions which are Substantially Changed must be renamed to
avoid use of the name of the Original Version or similar names entirely.
(c) Modified Versions which are not Substantially Changed must be
renamed to both (i) retain the name of the Original Version and (ii) add
additional naming elements to distinguish the Modified Version from the
Original Version. The name of such Modified Versions must be the name of
the Original Version, with "derivative X" where X represents the name of
the new work, appended to that name.
3) The name(s) of the Copyright Holder(s) and any contributor to the
Font Software shall not be used to promote, endorse or advertise any
Modified Version, except (i) as required by this licence, (ii) to
acknowledge the contribution(s) of the Copyright Holder(s) or (iii) with
their explicit written permission.
4) The Font Software, modified or unmodified, in part or in whole, must
be distributed entirely under this licence, and must not be distributed
under any other licence. The requirement for fonts to remain under this
licence does not affect any document created using the Font Software,
except any version of the Font Software extracted from a document
created using the Font Software may only be distributed under this
licence.
TERMINATION
This licence becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT OF
COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM OTHER
DEALINGS IN THE FONT SOFTWARE.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
+5
View File
@@ -0,0 +1,5 @@
Copyright 2010,2011 Canonical Ltd.
This Font Software is licensed under the Ubuntu Font Licence, Version
1.0. https://launchpad.net/ubuntu-font-licence