Store YAML frontmatter in notes.

This commit is contained in:
2025-07-06 22:29:13 +02:00
parent d28c7bc83e
commit 9113dc1a69
11 changed files with 946 additions and 23 deletions

26
app.py
View File

@@ -1794,6 +1794,9 @@ def create_note():
company_id=g.user.company_id
)
# Sync metadata from frontmatter if present
note.sync_from_frontmatter()
# Set team_id if visibility is Team
if visibility == 'Team' and g.user.team_id:
note.team_id = g.user.team_id
@@ -1867,11 +1870,11 @@ def view_note(slug):
incoming_links = []
for link in note.outgoing_links:
if link.target_note.can_user_view(g.user):
if link.target_note.can_user_view(g.user) and not link.target_note.is_archived:
outgoing_links.append(link)
for link in note.incoming_links:
if link.source_note.can_user_view(g.user):
if link.source_note.can_user_view(g.user) and not link.source_note.is_archived:
incoming_links.append(link)
# Get linkable notes for the modal
@@ -1896,6 +1899,22 @@ def view_note(slug):
can_edit=note.can_user_edit(g.user))
@app.route('/notes/<slug>/mindmap')
@login_required
@company_required
def view_note_mindmap(slug):
"""View a note as a mind map"""
note = Note.query.filter_by(slug=slug, company_id=g.user.company_id).first_or_404()
# Check permissions
if not note.can_user_view(g.user):
abort(403)
return render_template('note_mindmap.html',
title=f"{note.title} - Mind Map",
note=note)
@app.route('/notes/<slug>/edit', methods=['GET', 'POST'])
@login_required
@company_required
@@ -1938,6 +1957,9 @@ def edit_note(slug):
note.folder = folder if folder else None
note.tags = ','.join(tag_list) if tag_list else None
# Sync metadata from frontmatter if present
note.sync_from_frontmatter()
# Update team_id if visibility is Team
if visibility == 'Team' and g.user.team_id:
note.team_id = g.user.team_id

70
frontmatter_utils.py Normal file
View File

@@ -0,0 +1,70 @@
import yaml
import re
from datetime import datetime
def parse_frontmatter(content):
"""
Parse YAML frontmatter from markdown content.
Returns a tuple of (metadata dict, content without frontmatter)
"""
if not content or not content.strip().startswith('---'):
return {}, content
# Match frontmatter pattern
pattern = r'^---\s*\n(.*?)\n---\s*\n(.*)$'
match = re.match(pattern, content, re.DOTALL)
if not match:
return {}, content
try:
# Parse YAML frontmatter
metadata = yaml.safe_load(match.group(1)) or {}
content_body = match.group(2)
return metadata, content_body
except yaml.YAMLError:
# If YAML parsing fails, return original content
return {}, content
def create_frontmatter(metadata):
"""
Create YAML frontmatter from metadata dict.
"""
if not metadata:
return ""
# Filter out None values and empty strings
filtered_metadata = {k: v for k, v in metadata.items() if v is not None and v != ''}
if not filtered_metadata:
return ""
return f"---\n{yaml.dump(filtered_metadata, default_flow_style=False, sort_keys=False)}---\n\n"
def update_frontmatter(content, metadata):
"""
Update or add frontmatter to content.
"""
_, body = parse_frontmatter(content)
frontmatter = create_frontmatter(metadata)
return frontmatter + body
def extract_title_from_content(content):
"""
Extract title from content, checking frontmatter first, then first line.
"""
metadata, body = parse_frontmatter(content)
# Check if title is in frontmatter
if metadata.get('title'):
return metadata['title']
# Otherwise extract from first line of body
lines = body.strip().split('\n')
for line in lines:
line = line.strip()
if line:
# Remove markdown headers if present
return re.sub(r'^#+\s*', '', line)
return 'Untitled Note'

View File

@@ -77,6 +77,7 @@ def run_all_migrations(db_path=None):
migrate_dashboard_system(db_path)
migrate_comment_system(db_path)
migrate_notes_system(db_path)
update_note_link_cascade(db_path)
# Run PostgreSQL-specific migrations if applicable
if FLASK_AVAILABLE:
@@ -1753,6 +1754,72 @@ def migrate_notes_system(db_file=None):
conn.close()
def update_note_link_cascade(db_path):
"""Update note_link table to ensure CASCADE delete is enabled."""
print("Checking note_link cascade delete constraints...")
try:
conn = sqlite3.connect(db_path)
cursor = conn.cursor()
# Check if note_link table exists
cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='note_link'")
if not cursor.fetchone():
print("note_link table does not exist, skipping cascade update")
return
# Check current foreign key constraints
cursor.execute("PRAGMA foreign_key_list(note_link)")
fk_info = cursor.fetchall()
# Check if CASCADE is already set
has_cascade = any('CASCADE' in str(fk) for fk in fk_info)
if not has_cascade:
print("Updating note_link table with CASCADE delete...")
# SQLite doesn't support ALTER TABLE for foreign keys, so recreate the table
cursor.execute("""
CREATE TABLE note_link_temp (
id INTEGER PRIMARY KEY AUTOINCREMENT,
source_note_id INTEGER NOT NULL,
target_note_id INTEGER NOT NULL,
link_type VARCHAR(50) DEFAULT 'related',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
created_by_id INTEGER NOT NULL,
FOREIGN KEY (source_note_id) REFERENCES note(id) ON DELETE CASCADE,
FOREIGN KEY (target_note_id) REFERENCES note(id) ON DELETE CASCADE,
FOREIGN KEY (created_by_id) REFERENCES user(id),
UNIQUE(source_note_id, target_note_id)
)
""")
# Copy data
cursor.execute("INSERT INTO note_link_temp SELECT * FROM note_link")
# Drop old table and rename new one
cursor.execute("DROP TABLE note_link")
cursor.execute("ALTER TABLE note_link_temp RENAME TO note_link")
# Recreate indexes
cursor.execute("CREATE INDEX idx_note_link_source ON note_link(source_note_id)")
cursor.execute("CREATE INDEX idx_note_link_target ON note_link(target_note_id)")
print("note_link table updated with CASCADE delete")
else:
print("note_link table already has CASCADE delete")
conn.commit()
except Exception as e:
print(f"Error updating note_link cascade: {e}")
if conn:
conn.rollback()
finally:
if conn:
conn.close()
def main():
"""Main function with command line interface."""
parser = argparse.ArgumentParser(description='TimeTrack Database Migration Tool')

View File

@@ -0,0 +1,20 @@
-- Migration to add CASCADE delete to note_link foreign keys
-- This ensures that when a note is deleted, all links to/from it are also deleted
-- For PostgreSQL
-- Drop existing foreign key constraints
ALTER TABLE note_link DROP CONSTRAINT IF EXISTS note_link_source_note_id_fkey;
ALTER TABLE note_link DROP CONSTRAINT IF EXISTS note_link_target_note_id_fkey;
-- Add new foreign key constraints with CASCADE
ALTER TABLE note_link
ADD CONSTRAINT note_link_source_note_id_fkey
FOREIGN KEY (source_note_id)
REFERENCES note(id)
ON DELETE CASCADE;
ALTER TABLE note_link
ADD CONSTRAINT note_link_target_note_id_fkey
FOREIGN KEY (target_note_id)
REFERENCES note(id)
ON DELETE CASCADE;

View File

@@ -0,0 +1,25 @@
-- SQLite migration for cascade delete on note_link
-- SQLite doesn't support ALTER TABLE for foreign keys, so we need to recreate the table
-- Create new table with CASCADE delete
CREATE TABLE note_link_new (
id INTEGER PRIMARY KEY,
source_note_id INTEGER NOT NULL,
target_note_id INTEGER NOT NULL,
link_type VARCHAR(50) DEFAULT 'related',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
created_by_id INTEGER NOT NULL,
FOREIGN KEY (source_note_id) REFERENCES note(id) ON DELETE CASCADE,
FOREIGN KEY (target_note_id) REFERENCES note(id) ON DELETE CASCADE,
FOREIGN KEY (created_by_id) REFERENCES user(id),
UNIQUE(source_note_id, target_note_id)
);
-- Copy data from old table
INSERT INTO note_link_new SELECT * FROM note_link;
-- Drop old table
DROP TABLE note_link;
-- Rename new table
ALTER TABLE note_link_new RENAME TO note_link;

View File

@@ -1368,7 +1368,12 @@ class Note(db.Model):
"""Get a plain text preview of the note content"""
# Strip markdown formatting for preview
import re
text = self.content
from frontmatter_utils import parse_frontmatter
# Extract body content without frontmatter
_, body = parse_frontmatter(self.content)
text = body
# Remove headers
text = re.sub(r'^#+\s+', '', text, flags=re.MULTILINE)
# Remove emphasis
@@ -1390,30 +1395,84 @@ class Note(db.Model):
"""Render markdown content to HTML"""
try:
import markdown
from frontmatter_utils import parse_frontmatter
# Extract body content without frontmatter
_, body = parse_frontmatter(self.content)
# Use extensions for better markdown support
html = markdown.markdown(self.content, extensions=['extra', 'codehilite', 'toc'])
html = markdown.markdown(body, extensions=['extra', 'codehilite', 'toc'])
return html
except ImportError:
# Fallback if markdown not installed
return f'<pre>{self.content}</pre>'
def get_frontmatter(self):
"""Get frontmatter metadata from content"""
from frontmatter_utils import parse_frontmatter
metadata, _ = parse_frontmatter(self.content)
return metadata
def update_frontmatter(self):
"""Update content with current metadata as frontmatter"""
from frontmatter_utils import update_frontmatter
metadata = {
'title': self.title,
'visibility': self.visibility.value.lower(),
'folder': self.folder,
'tags': self.get_tags_list() if self.tags else None,
'project': self.project.code if self.project else None,
'task_id': self.task_id,
'pinned': self.is_pinned if self.is_pinned else None,
'created': self.created_at.isoformat() if self.created_at else None,
'updated': self.updated_at.isoformat() if self.updated_at else None,
'author': self.created_by.username if self.created_by else None
}
# Remove None values
metadata = {k: v for k, v in metadata.items() if v is not None}
self.content = update_frontmatter(self.content, metadata)
def sync_from_frontmatter(self):
"""Update model fields from frontmatter in content"""
from frontmatter_utils import parse_frontmatter
metadata, _ = parse_frontmatter(self.content)
if metadata:
# Update fields from frontmatter
if 'title' in metadata:
self.title = metadata['title']
if 'visibility' in metadata:
try:
self.visibility = NoteVisibility[metadata['visibility'].upper()]
except KeyError:
pass
if 'folder' in metadata:
self.folder = metadata['folder']
if 'tags' in metadata:
if isinstance(metadata['tags'], list):
self.set_tags_list(metadata['tags'])
elif isinstance(metadata['tags'], str):
self.tags = metadata['tags']
if 'pinned' in metadata:
self.is_pinned = bool(metadata['pinned'])
class NoteLink(db.Model):
"""Links between notes for creating relationships"""
id = db.Column(db.Integer, primary_key=True)
# Source and target notes
source_note_id = db.Column(db.Integer, db.ForeignKey('note.id'), nullable=False)
target_note_id = db.Column(db.Integer, db.ForeignKey('note.id'), nullable=False)
# Source and target notes with cascade deletion
source_note_id = db.Column(db.Integer, db.ForeignKey('note.id', ondelete='CASCADE'), nullable=False)
target_note_id = db.Column(db.Integer, db.ForeignKey('note.id', ondelete='CASCADE'), nullable=False)
# Link metadata
link_type = db.Column(db.String(50), default='related') # related, parent, child, etc.
created_at = db.Column(db.DateTime, default=datetime.now)
created_by_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)
# Relationships
source_note = db.relationship('Note', foreign_keys=[source_note_id], backref='outgoing_links')
target_note = db.relationship('Note', foreign_keys=[target_note_id], backref='incoming_links')
# Relationships with cascade deletion
source_note = db.relationship('Note', foreign_keys=[source_note_id],
backref=db.backref('outgoing_links', cascade='all, delete-orphan'))
target_note = db.relationship('Note', foreign_keys=[target_note_id],
backref=db.backref('incoming_links', cascade='all, delete-orphan'))
created_by = db.relationship('User', foreign_keys=[created_by_id])
# Unique constraint to prevent duplicate links

View File

@@ -15,3 +15,4 @@ xlsxwriter==3.1.2
Flask-Mail==0.9.1
psycopg2-binary==2.9.9
markdown==3.4.4
PyYAML==6.0.1

View File

@@ -89,6 +89,10 @@
<div class="form-group editor-group">
<div class="editor-toolbar">
<button type="button" class="toolbar-btn" onclick="toggleFrontmatter()" title="Toggle Frontmatter" style="background: #e3f2fd;">
<span style="font-family: monospace;">---</span>
</button>
<span class="toolbar-separator"></span>
<button type="button" class="toolbar-btn toolbar-bold" onclick="insertMarkdown('**', '**')" title="Bold">
<b>B</b>
</button>
@@ -635,6 +639,25 @@
// Global Ace Editor instance
let aceEditor;
// Toggle frontmatter visibility
function toggleFrontmatter() {
if (!aceEditor) return;
const content = aceEditor.getValue();
if (content.trim().startsWith('---')) {
// Frontmatter exists, just move cursor to it
aceEditor.moveCursorTo(0, 0);
aceEditor.focus();
} else {
// Add frontmatter
const newContent = updateContentFrontmatter(content);
aceEditor.setValue(newContent, -1);
aceEditor.moveCursorTo(0, 0);
aceEditor.focus();
}
}
// Markdown toolbar functions for Ace Editor
function insertMarkdown(before, after) {
if (!aceEditor) return;
@@ -666,14 +689,39 @@ function insertMarkdown(before, after) {
syncContentAndUpdatePreview();
}
// Extract title from first line of content
// Extract title from content (frontmatter or first line)
function extractTitleFromContent(content) {
// Check for frontmatter first
if (content.trim().startsWith('---')) {
const frontmatterMatch = content.match(/^---\s*\n([\s\S]*?)\n---/);
if (frontmatterMatch) {
const frontmatterContent = frontmatterMatch[1];
const titleMatch = frontmatterContent.match(/title:\s*(.+)/);
if (titleMatch) {
// Remove quotes if present
return titleMatch[1].replace(/^["']|["']$/g, '').trim();
}
}
}
// Otherwise extract from first line
const lines = content.split('\n');
let firstLine = '';
// Find the first non-empty line
for (let line of lines) {
const trimmed = line.trim();
// Skip frontmatter if present
let skipUntil = 0;
if (lines[0].trim() === '---') {
for (let i = 1; i < lines.length; i++) {
if (lines[i].trim() === '---') {
skipUntil = i + 1;
break;
}
}
}
// Find the first non-empty line after frontmatter
for (let i = skipUntil; i < lines.length; i++) {
const trimmed = lines[i].trim();
if (trimmed) {
// Remove markdown headers if present
firstLine = trimmed.replace(/^#+\s*/, '');
@@ -685,14 +733,101 @@ function extractTitleFromContent(content) {
return firstLine || 'Untitled Note';
}
// Update or create frontmatter in content
function updateContentFrontmatter(content) {
const settings = {
visibility: document.getElementById('visibility').value.toLowerCase(),
folder: document.getElementById('folder').value || undefined,
tags: document.getElementById('tags').value ?
document.getElementById('tags').value.split(',').map(t => t.trim()).filter(t => t) : undefined,
project: document.getElementById('project_id').selectedOptions[0]?.text.split(' - ')[0] || undefined,
task_id: parseInt(document.getElementById('task_id').value) || undefined,
pinned: false
};
// Remove undefined values
Object.keys(settings).forEach(key => settings[key] === undefined && delete settings[key]);
// Parse existing frontmatter
let body = content;
let existingFrontmatter = {};
if (content.trim().startsWith('---')) {
const match = content.match(/^---\s*\n([\s\S]*?)\n---\s*\n([\s\S]*)$/);
if (match) {
try {
// Simple YAML parsing for our use case
const yamlContent = match[1];
yamlContent.split('\n').forEach(line => {
const colonIndex = line.indexOf(':');
if (colonIndex > 0) {
const key = line.substring(0, colonIndex).trim();
const value = line.substring(colonIndex + 1).trim();
existingFrontmatter[key] = value.replace(/^["']|["']$/g, '');
}
});
body = match[2];
} catch (e) {
console.error('Error parsing frontmatter:', e);
}
}
}
// Merge settings with existing frontmatter
const frontmatter = { ...existingFrontmatter, ...settings };
// Add title from content or form field
const titleField = document.getElementById('title').value;
if (titleField && titleField !== 'Untitled Note') {
frontmatter.title = titleField;
} else {
frontmatter.title = extractTitleFromContent(body);
}
// Build new frontmatter
let yamlContent = '---\n';
Object.entries(frontmatter).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') {
if (Array.isArray(value)) {
yamlContent += `${key}:\n`;
value.forEach(item => {
yamlContent += ` - ${item}\n`;
});
} else if (typeof value === 'string' && (value.includes(':') || value.includes('"'))) {
yamlContent += `${key}: "${value}"\n`;
} else {
yamlContent += `${key}: ${value}\n`;
}
}
});
yamlContent += '---\n\n';
return yamlContent + body;
}
// Sync Ace Editor content with hidden textarea and update preview
function syncContentAndUpdatePreview() {
let frontmatterUpdateTimer;
function syncContentAndUpdatePreview(updateFrontmatter = true) {
if (!aceEditor) return;
const content = aceEditor.getValue();
let content = aceEditor.getValue();
// Only update frontmatter when settings change, not on every keystroke
if (updateFrontmatter) {
clearTimeout(frontmatterUpdateTimer);
frontmatterUpdateTimer = setTimeout(() => {
const newContent = updateContentFrontmatter(aceEditor.getValue());
if (aceEditor.getValue() !== newContent) {
const currentPosition = aceEditor.getCursorPosition();
aceEditor.setValue(newContent, -1);
aceEditor.moveCursorToPosition(currentPosition);
}
}, 2000); // Wait 2 seconds after typing stops
}
document.getElementById('content').value = content;
// Update title from first line
// Update title from content
const title = extractTitleFromContent(content);
document.getElementById('title').value = title;
@@ -703,9 +838,61 @@ function syncContentAndUpdatePreview() {
headerTitle.textContent = title ? (isEdit ? `Edit: ${title}` : title) : (isEdit ? 'Edit Note' : 'Create Note');
}
// Sync settings from frontmatter
syncSettingsFromFrontmatter(content);
updatePreview();
}
// Sync settings UI from frontmatter
function syncSettingsFromFrontmatter(content) {
if (!content.trim().startsWith('---')) return;
const match = content.match(/^---\s*\n([\s\S]*?)\n---/);
if (!match) return;
const yamlContent = match[1];
const frontmatter = {};
// Simple YAML parsing
yamlContent.split('\n').forEach(line => {
const colonIndex = line.indexOf(':');
if (colonIndex > 0) {
const key = line.substring(0, colonIndex).trim();
let value = line.substring(colonIndex + 1).trim();
// Handle arrays (tags)
if (key === 'tags' && !value) {
// Multi-line array, skip for now
return;
}
value = value.replace(/^["']|["']$/g, '');
frontmatter[key] = value;
}
});
// Update UI elements
if (frontmatter.visibility) {
const visibilitySelect = document.getElementById('visibility');
const capitalizedVisibility = frontmatter.visibility.charAt(0).toUpperCase() + frontmatter.visibility.slice(1);
for (let option of visibilitySelect.options) {
if (option.value === capitalizedVisibility) {
visibilitySelect.value = capitalizedVisibility;
break;
}
}
}
if (frontmatter.folder !== undefined) {
document.getElementById('folder').value = frontmatter.folder;
}
if (frontmatter.tags !== undefined) {
document.getElementById('tags').value = frontmatter.tags;
}
}
// Live preview update
let previewTimer;
function updatePreview() {
@@ -747,7 +934,7 @@ function initializeAceEditor() {
// Set theme (use github theme for light mode)
aceEditor.setTheme("ace/theme/github");
// Set markdown mode
// Set markdown mode (which includes YAML frontmatter highlighting)
aceEditor.session.setMode("ace/mode/markdown");
// Configure editor options
@@ -770,15 +957,43 @@ function initializeAceEditor() {
const initialContent = document.getElementById('content').value;
aceEditor.setValue(initialContent, -1); // -1 moves cursor to start
// If editing and has content, extract title
// If editing and has content, sync from frontmatter
if (initialContent) {
const title = extractTitleFromContent(initialContent);
// If editing existing note without frontmatter, add it
if (!initialContent.trim().startsWith('---')) {
const newContent = updateContentFrontmatter(initialContent);
aceEditor.setValue(newContent, -1);
}
syncSettingsFromFrontmatter(aceEditor.getValue());
const title = extractTitleFromContent(aceEditor.getValue());
document.getElementById('title').value = title;
}
// Listen for changes in Ace Editor
aceEditor.on('change', function() {
syncContentAndUpdatePreview();
syncContentAndUpdatePreview(false); // Don't update frontmatter on every keystroke
});
// If this is a new note, add initial frontmatter
if (!initialContent || initialContent.trim() === '') {
const newContent = updateContentFrontmatter('# New Note\n\nStart writing here...');
aceEditor.setValue(newContent, -1);
syncContentAndUpdatePreview(false);
}
// Listen for changes in settings to update frontmatter
['visibility', 'folder', 'tags', 'project_id', 'task_id'].forEach(id => {
const element = document.getElementById(id);
if (element) {
element.addEventListener('change', function() {
// Force immediate frontmatter update when settings change
const content = updateContentFrontmatter(aceEditor.getValue());
const currentPosition = aceEditor.getCursorPosition();
aceEditor.setValue(content, -1);
aceEditor.moveCursorToPosition(currentPosition);
syncContentAndUpdatePreview(false);
});
}
});
// Handle form submission - ensure content is synced

401
templates/note_mindmap.html Normal file
View File

@@ -0,0 +1,401 @@
{% extends "layout.html" %}
{% block content %}
<div class="timetrack-container note-mindmap-container">
<div class="mindmap-header">
<h2>{{ note.title }} - Mind Map View</h2>
<div class="mindmap-actions">
<button type="button" class="btn btn-sm btn-secondary" onclick="resetZoom()">
Reset Zoom
</button>
<button type="button" class="btn btn-sm btn-secondary" onclick="toggleFullscreen()">
Fullscreen
</button>
<a href="{{ url_for('view_note', slug=note.slug) }}" class="btn btn-sm btn-info">
Back to Note
</a>
</div>
</div>
<div id="mindmap-container" class="mindmap-container">
<svg id="mindmap-svg"></svg>
</div>
</div>
<style>
.note-mindmap-container {
max-width: none !important;
width: 100% !important;
padding: 1rem !important;
margin: 0 !important;
height: calc(100vh - 100px);
display: flex;
flex-direction: column;
}
.mindmap-header {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 1rem;
}
.mindmap-actions {
display: flex;
gap: 0.5rem;
}
.mindmap-container {
flex: 1;
background: white;
border: 1px solid #dee2e6;
border-radius: 8px;
overflow: hidden;
position: relative;
}
#mindmap-svg {
width: 100%;
height: 100%;
cursor: grab;
}
#mindmap-svg.grabbing {
cursor: grabbing;
}
.node {
cursor: pointer;
}
.node circle {
fill: #fff;
stroke: steelblue;
stroke-width: 3px;
}
.node rect {
fill: #f9f9f9;
stroke: steelblue;
stroke-width: 2px;
rx: 5px;
}
.node text {
font: 12px sans-serif;
pointer-events: none;
}
.link {
fill: none;
stroke: #ccc;
stroke-width: 2px;
}
.node.collapsed circle {
fill: steelblue;
}
.node.root rect {
fill: #4CAF50;
stroke: #45a049;
}
.node.root text {
fill: white;
font-weight: bold;
}
.node.level1 rect {
fill: #e3f2fd;
stroke: #2196F3;
}
.node.level2 rect {
fill: #f3e5f5;
stroke: #9C27B0;
}
.node.level3 rect {
fill: #fff3e0;
stroke: #FF9800;
}
/* Fullscreen styles */
.mindmap-container.fullscreen {
position: fixed;
top: 0;
left: 0;
width: 100vw;
height: 100vh;
z-index: 9999;
margin: 0;
border-radius: 0;
}
</style>
<script src="https://d3js.org/d3.v7.min.js"></script>
<script>
// Parse markdown content to extract structure
const markdownContent = {{ note.content | tojson }};
function parseMarkdownToTree(markdown) {
const lines = markdown.split('\n');
const root = {
name: '{{ note.title }}',
children: [],
level: 0
};
const stack = [root];
let currentList = null;
lines.forEach(line => {
// Check for headers
const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
if (headerMatch) {
const level = headerMatch[1].length;
const text = headerMatch[2];
// Pop stack until we find parent level
while (stack.length > level) {
stack.pop();
}
const node = {
name: text,
children: [],
level: level
};
const parent = stack[stack.length - 1];
if (!parent.children) parent.children = [];
parent.children.push(node);
stack.push(node);
currentList = null;
}
// Check for list items
const listMatch = line.match(/^(\s*)[*\-+]\s+(.+)$/);
if (listMatch) {
const indent = listMatch[1].length;
const text = listMatch[2];
const node = {
name: text,
children: [],
level: stack[stack.length - 1].level + 1,
isList: true
};
const parent = stack[stack.length - 1];
if (!parent.children) parent.children = [];
parent.children.push(node);
}
// Check for numbered lists
const numberedListMatch = line.match(/^(\s*)\d+\.\s+(.+)$/);
if (numberedListMatch) {
const text = numberedListMatch[2];
const node = {
name: text,
children: [],
level: stack[stack.length - 1].level + 1,
isList: true
};
const parent = stack[stack.length - 1];
if (!parent.children) parent.children = [];
parent.children.push(node);
}
});
return root;
}
// D3 Mind Map Implementation
const treeData = parseMarkdownToTree(markdownContent);
const margin = {top: 20, right: 120, bottom: 20, left: 120};
const width = document.getElementById('mindmap-container').clientWidth;
const height = document.getElementById('mindmap-container').clientHeight;
const svg = d3.select("#mindmap-svg")
.attr("viewBox", [-width / 2, -height / 2, width, height]);
const g = svg.append("g");
// Add zoom behavior
const zoom = d3.zoom()
.scaleExtent([0.1, 3])
.on("zoom", (event) => {
g.attr("transform", event.transform);
});
svg.call(zoom);
// Create tree layout
const tree = d3.tree()
.size([height - margin.top - margin.bottom, width - margin.left - margin.right]);
// Create hierarchy
const root = d3.hierarchy(treeData);
root.x0 = 0;
root.y0 = 0;
// Collapse after the second level
root.descendants().forEach((d, i) => {
d.id = i;
if (d.depth && d.depth > 1) {
d._children = d.children;
d.children = null;
}
});
update(root);
function update(source) {
const duration = 750;
// Compute tree layout
const treeData = tree(root);
const nodes = treeData.descendants();
const links = treeData.links();
// Normalize for fixed-depth
nodes.forEach(d => {
d.y = d.depth * 180;
});
// Update nodes
const node = g.selectAll("g.node")
.data(nodes, d => d.id);
const nodeEnter = node.enter().append("g")
.attr("class", d => `node level${Math.min(d.depth, 3)}`)
.attr("transform", d => `translate(${source.y0},${source.x0})`)
.on("click", click);
// Add rectangles for nodes
nodeEnter.append("rect")
.attr("width", 1e-6)
.attr("height", 1e-6)
.attr("x", -1)
.attr("y", -1)
.attr("class", d => d.depth === 0 ? "root" : "");
// Add text
nodeEnter.append("text")
.attr("dy", ".35em")
.attr("text-anchor", "middle")
.text(d => d.data.name)
.style("fill-opacity", 1e-6);
// Transition nodes to their new position
const nodeUpdate = nodeEnter.merge(node);
nodeUpdate.transition()
.duration(duration)
.attr("transform", d => `translate(${d.y},${d.x})`);
nodeUpdate.select("rect")
.attr("width", d => {
const textLength = d.data.name.length * 8 + 20;
return Math.max(textLength, 100);
})
.attr("height", 30)
.attr("x", d => {
const textLength = d.data.name.length * 8 + 20;
return -Math.max(textLength, 100) / 2;
})
.attr("y", -15)
.attr("class", d => d._children ? "collapsed" : "");
nodeUpdate.select("text")
.style("fill-opacity", 1);
// Remove exiting nodes
const nodeExit = node.exit().transition()
.duration(duration)
.attr("transform", d => `translate(${source.y},${source.x})`)
.remove();
nodeExit.select("rect")
.attr("width", 1e-6)
.attr("height", 1e-6);
nodeExit.select("text")
.style("fill-opacity", 1e-6);
// Update links
const link = g.selectAll("path.link")
.data(links, d => d.target.id);
const linkEnter = link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", d => {
const o = {x: source.x0, y: source.y0};
return diagonal({source: o, target: o});
});
const linkUpdate = linkEnter.merge(link);
linkUpdate.transition()
.duration(duration)
.attr("d", diagonal);
const linkExit = link.exit().transition()
.duration(duration)
.attr("d", d => {
const o = {x: source.x, y: source.y};
return diagonal({source: o, target: o});
})
.remove();
// Store old positions
nodes.forEach(d => {
d.x0 = d.x;
d.y0 = d.y;
});
}
function diagonal(d) {
return `M ${d.source.y} ${d.source.x}
C ${(d.source.y + d.target.y) / 2} ${d.source.x},
${(d.source.y + d.target.y) / 2} ${d.target.x},
${d.target.y} ${d.target.x}`;
}
function click(event, d) {
if (d.children) {
d._children = d.children;
d.children = null;
} else {
d.children = d._children;
d._children = null;
}
update(d);
}
function resetZoom() {
svg.transition()
.duration(750)
.call(zoom.transform, d3.zoomIdentity);
}
function toggleFullscreen() {
const container = document.getElementById('mindmap-container');
container.classList.toggle('fullscreen');
// Recalculate dimensions
const newWidth = container.clientWidth;
const newHeight = container.clientHeight;
svg.attr("viewBox", [-newWidth / 2, -newHeight / 2, newWidth, newHeight]);
}
// Center the tree initially
svg.call(zoom.transform, d3.zoomIdentity.translate(width / 2, height / 2).scale(0.8));
</script>
{% endblock %}

View File

@@ -15,10 +15,24 @@
{% if note.updated_at > note.created_at %}
<span class="date">· Updated {{ note.updated_at|format_date }}</span>
{% endif %}
{% if note.is_pinned %}
<span class="pin-badge">📌 Pinned</span>
{% endif %}
</div>
</div>
<div class="note-actions">
<a href="{{ url_for('view_note_mindmap', slug=note.slug) }}" class="btn btn-info">
<svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16" style="vertical-align: -2px; margin-right: 4px;">
<circle cx="8" cy="8" r="2"/>
<circle cx="3" cy="3" r="1.5"/>
<circle cx="13" cy="3" r="1.5"/>
<circle cx="3" cy="13" r="1.5"/>
<circle cx="13" cy="13" r="1.5"/>
<path d="M6.5 6.5L4 4M9.5 6.5L12 4M6.5 9.5L4 12M9.5 9.5L12 12" stroke="currentColor" fill="none"/>
</svg>
Mind Map
</a>
{% if note.can_user_edit(g.user) %}
<a href="{{ url_for('edit_note', slug=note.slug) }}" class="btn btn-primary">Edit</a>
<form method="POST" action="{{ url_for('delete_note', slug=note.slug) }}" style="display: inline;"
@@ -57,7 +71,7 @@
<div class="association-item">
<span class="association-label">Tags:</span>
<span class="association-value">
{% for tag in note.tags %}
{% for tag in note.get_tags_list() %}
<a href="{{ url_for('notes_list', tag=tag) }}" class="tag-badge">{{ tag }}</a>
{% endfor %}
</span>
@@ -429,6 +443,15 @@
font-style: italic;
}
.pin-badge {
background: #fff3cd;
color: #856404;
padding: 0.2rem 0.5rem;
border-radius: 4px;
font-size: 0.85rem;
font-weight: 500;
}
/* Modal styles */
.modal-content {
max-width: 500px;

View File

@@ -248,6 +248,16 @@
<path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
</svg>
</a>
<a href="{{ url_for('view_note_mindmap', slug=note.slug) }}" class="btn-action" title="Mind Map">
<svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
<circle cx="8" cy="8" r="2"/>
<circle cx="3" cy="3" r="1.5"/>
<circle cx="13" cy="3" r="1.5"/>
<circle cx="3" cy="13" r="1.5"/>
<circle cx="13" cy="13" r="1.5"/>
<path d="M6.5 6.5L4 4M9.5 6.5L12 4M6.5 9.5L4 12M9.5 9.5L12 12" stroke="currentColor" fill="none"/>
</svg>
</a>
{% if note.can_user_edit(g.user) %}
<a href="{{ url_for('edit_note', slug=note.slug) }}" class="btn-action" title="Edit">
<svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
@@ -328,6 +338,16 @@
<path d="M11.742 10.344a6.5 6.5 0 1 0-1.397 1.398h-.001c.03.04.062.078.098.115l3.85 3.85a1 1 0 0 0 1.415-1.414l-3.85-3.85a1.007 1.007 0 0 0-.115-.1zM12 6.5a5.5 5.5 0 1 1-11 0 5.5 5.5 0 0 1 11 0z"/>
</svg>
</a>
<a href="{{ url_for('view_note_mindmap', slug=note.slug) }}" class="btn-action" title="Mind Map">
<svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
<circle cx="8" cy="8" r="2"/>
<circle cx="3" cy="3" r="1.5"/>
<circle cx="13" cy="3" r="1.5"/>
<circle cx="3" cy="13" r="1.5"/>
<circle cx="13" cy="13" r="1.5"/>
<path d="M6.5 6.5L4 4M9.5 6.5L12 4M6.5 9.5L4 12M9.5 9.5L12 12" stroke="currentColor" fill="none"/>
</svg>
</a>
{% if note.can_user_edit(g.user) %}
<a href="{{ url_for('edit_note', slug=note.slug) }}" class="btn-action" title="Edit">
<svg width="16" height="16" fill="currentColor" viewBox="0 0 16 16">
@@ -1006,7 +1026,7 @@
}
.column-actions {
width: 120px;
width: 160px;
}
.note-actions {