1
0
mirror of https://github.com/AvengeMedia/DankMaterialShell.git synced 2026-01-26 14:32:52 -05:00

Chroma core - syntax & markdown previews

This commit is contained in:
purian23
2026-01-19 20:19:15 -05:00
parent f2be6cfeb1
commit d1ecb5af70
5 changed files with 584 additions and 156 deletions

View File

@@ -1,3 +1,4 @@
pragma ComponentBehavior: Bound
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
@@ -6,8 +7,6 @@ import qs.Common
import qs.Services
import qs.Widgets
pragma ComponentBehavior: Bound
Column {
id: root
@@ -22,55 +21,181 @@ Column {
property int currentMatchIndex: -1
property int matchCount: 0
signal saveRequested()
signal openRequested()
signal newRequested()
signal escapePressed()
signal contentChanged()
signal settingsRequested()
// Plugin-provided markdown/syntax highlighting (via builtInPluginSettings)
property bool pluginInstalled: SettingsData.getBuiltInPluginSetting("dankNotepadMarkdown", "enabled", false)
property bool pluginMarkdownEnabled: SettingsData.getBuiltInPluginSetting("dankNotepadMarkdown", "markdownPreview", false)
property bool pluginSyntaxEnabled: SettingsData.getBuiltInPluginSetting("dankNotepadMarkdown", "syntaxHighlighting", false)
property string pluginHighlightedHtml: SettingsData.getBuiltInPluginSetting("dankNotepadMarkdown", "highlightedHtml", "")
property string pluginFileExtension: SettingsData.getBuiltInPluginSetting("dankNotepadMarkdown", "currentFileExtension", "")
// Local toggle for markdown preview (can be toggled from UI)
property bool markdownPreviewActive: pluginMarkdownEnabled
// Toggle markdown preview
function toggleMarkdownPreview() {
if (!markdownPreviewActive) {
// Entering preview mode
syncContentToPlugin();
markdownPreviewActive = true;
} else {
// Exiting preview mode
markdownPreviewActive = false;
}
}
// Local toggle for syntax highlighting preview (read-only view with colors)
property bool syntaxPreviewActive: false
// Store original text when entering syntax preview mode
property string syntaxPreviewOriginalText: ""
// Function to refresh plugin settings (called from Connections inside TextArea)
function refreshPluginSettings() {
pluginInstalled = SettingsData.getBuiltInPluginSetting("dankNotepadMarkdown", "enabled", false);
pluginMarkdownEnabled = SettingsData.getBuiltInPluginSetting("dankNotepadMarkdown", "markdownPreview", false);
pluginSyntaxEnabled = SettingsData.getBuiltInPluginSetting("dankNotepadMarkdown", "syntaxHighlighting", false);
pluginHighlightedHtml = SettingsData.getBuiltInPluginSetting("dankNotepadMarkdown", "highlightedHtml", "");
pluginFileExtension = SettingsData.getBuiltInPluginSetting("dankNotepadMarkdown", "currentFileExtension", "");
console.warn("NotepadTextEditor: Plugin settings refreshed. MdEnabled:", pluginMarkdownEnabled, "HtmlLength:", pluginHighlightedHtml.length);
}
// Toggle syntax preview mode
function toggleSyntaxPreview() {
if (!syntaxPreviewActive) {
// Entering preview mode
syncContentToPlugin();
syntaxPreviewActive = true;
} else {
// Exiting preview mode
syntaxPreviewActive = false;
}
}
// File extension detection for current tab
readonly property string currentFilePath: currentTab?.filePath || ""
readonly property string currentFileExtension: {
if (!currentFilePath)
return "";
var parts = currentFilePath.split('.');
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : "";
}
onCurrentTabChanged: handleCurrentTabChanged()
Component.onCompleted: handleCurrentTabChanged()
function handleCurrentTabChanged() {
if (!currentTab)
return;
// Reset preview state ONLY when tab actually changes
markdownPreviewActive = false;
syntaxPreviewActive = false;
syntaxPreviewOriginalText = "";
textArea.readOnly = false;
syncContentToPlugin();
}
function syncContentToPlugin() {
if (!currentTab)
return;
// Notify plugin of content update
// console.warn("NotepadTextEditor: Pushing content to plugin. Length:", textArea.text.length, "Path:", currentFilePath);
SettingsData.setBuiltInPluginSetting("dankNotepadMarkdown", "currentFilePath", currentFilePath);
SettingsData.setBuiltInPluginSetting("dankNotepadMarkdown", "currentFileExtension", currentFileExtension);
SettingsData.setBuiltInPluginSetting("dankNotepadMarkdown", "sourceContent", textArea.text);
SettingsData.setBuiltInPluginSetting("dankNotepadMarkdown", "currentTabChanged", Date.now());
}
// Debounce content updates to plugin to keep preview ready
Timer {
id: syncTimer
interval: 500
repeat: false
onTriggered: syncContentToPlugin()
}
Connections {
target: textArea
function onTextChanged() {
if (!markdownPreviewActive && !syntaxPreviewActive) {
syncTimer.restart();
}
}
}
readonly property string fileExtension: {
if (!currentFilePath)
return "";
var parts = currentFilePath.split('.');
return parts.length > 1 ? parts[parts.length - 1].toLowerCase() : "";
}
readonly property bool isMarkdownFile: fileExtension === "md" || fileExtension === "markdown" || fileExtension === "mdown"
readonly property bool isCodeFile: fileExtension !== "" && fileExtension !== "txt" && !isMarkdownFile
signal saveRequested
signal openRequested
signal newRequested
signal escapePressed
signal contentChanged
signal settingsRequested
function hasUnsavedChanges() {
if (!currentTab || !contentLoaded) {
return false
return false;
}
if (currentTab.isTemporary) {
return textArea.text.length > 0
return textArea.text.length > 0;
}
return textArea.text !== lastSavedContent
// If in preview mode, compare original text
if (markdownPreviewActive || syntaxPreviewActive) {
return syntaxPreviewOriginalText !== lastSavedContent;
}
return textArea.text !== lastSavedContent;
}
function loadCurrentTabContent() {
if (!currentTab) return
if (!currentTab)
return;
contentLoaded = false;
// Reset preview states on load
markdownPreviewActive = false;
syntaxPreviewActive = false;
syntaxPreviewOriginalText = "";
contentLoaded = false
NotepadStorageService.loadTabContent(
NotepadStorageService.currentTabIndex,
(content) => {
lastSavedContent = content
textArea.text = content
contentLoaded = true
}
)
NotepadStorageService.loadTabContent(NotepadStorageService.currentTabIndex, content => {
lastSavedContent = content;
textArea.text = content;
contentLoaded = true;
textArea.readOnly = false;
});
}
function saveCurrentTabContent() {
if (!currentTab || !contentLoaded) return
if (!currentTab || !contentLoaded)
return;
NotepadStorageService.saveTabContent(
NotepadStorageService.currentTabIndex,
textArea.text
)
lastSavedContent = textArea.text
// If in preview mode, save the original text, NOT the HTML
var contentToSave = (markdownPreviewActive || syntaxPreviewActive) ? syntaxPreviewOriginalText : textArea.text;
NotepadStorageService.saveTabContent(NotepadStorageService.currentTabIndex, contentToSave);
lastSavedContent = contentToSave;
}
function autoSaveToSession() {
if (!currentTab || !contentLoaded) return
saveCurrentTabContent()
if (!currentTab || !contentLoaded)
return;
saveCurrentTabContent();
}
function setTextDocumentLineHeight() {
return
return;
}
property string lastTextForLineModel: ""
@@ -78,100 +203,102 @@ Column {
function updateLineModel() {
if (!SettingsData.notepadShowLineNumbers) {
lineModel = []
lastTextForLineModel = ""
return
lineModel = [];
lastTextForLineModel = "";
return;
}
// In preview mode, line numbers might not match visual lines correctly due to wrapping/HTML
// But for now let's use the current text (plain or HTML)
if (textArea.text !== lastTextForLineModel || lineModel.length === 0) {
lastTextForLineModel = textArea.text
lineModel = textArea.text.split('\n')
lastTextForLineModel = textArea.text;
lineModel = textArea.text.split('\n');
}
}
function performSearch() {
let matches = []
currentMatchIndex = -1
let matches = [];
currentMatchIndex = -1;
if (!searchQuery || searchQuery.length === 0) {
searchMatches = []
matchCount = 0
textArea.select(0, 0)
return
searchMatches = [];
matchCount = 0;
textArea.select(0, 0);
return;
}
const text = textArea.text
const query = searchQuery.toLowerCase()
let index = 0
const text = textArea.text;
const query = searchQuery.toLowerCase();
let index = 0;
while (index < text.length) {
const foundIndex = text.toLowerCase().indexOf(query, index)
if (foundIndex === -1) break
const foundIndex = text.toLowerCase().indexOf(query, index);
if (foundIndex === -1)
break;
matches.push({
start: foundIndex,
end: foundIndex + searchQuery.length
})
index = foundIndex + 1
});
index = foundIndex + 1;
}
searchMatches = matches
matchCount = matches.length
searchMatches = matches;
matchCount = matches.length;
if (matchCount > 0) {
currentMatchIndex = 0
highlightCurrentMatch()
currentMatchIndex = 0;
highlightCurrentMatch();
} else {
textArea.select(0, 0)
textArea.select(0, 0);
}
}
function highlightCurrentMatch() {
if (currentMatchIndex >= 0 && currentMatchIndex < searchMatches.length) {
const match = searchMatches[currentMatchIndex]
const match = searchMatches[currentMatchIndex];
textArea.cursorPosition = match.start
textArea.moveCursorSelection(match.end, TextEdit.SelectCharacters)
textArea.cursorPosition = match.start;
textArea.moveCursorSelection(match.end, TextEdit.SelectCharacters);
const flickable = textArea.parent
const flickable = textArea.parent;
if (flickable && flickable.contentY !== undefined) {
const lineHeight = textArea.font.pixelSize * 1.5
const approxLine = textArea.text.substring(0, match.start).split('\n').length
const targetY = approxLine * lineHeight - flickable.height / 2
flickable.contentY = Math.max(0, Math.min(targetY, flickable.contentHeight - flickable.height))
const lineHeight = textArea.font.pixelSize * 1.5;
const approxLine = textArea.text.substring(0, match.start).split('\n').length;
const targetY = approxLine * lineHeight - flickable.height / 2;
flickable.contentY = Math.max(0, Math.min(targetY, flickable.contentHeight - flickable.height));
}
}
}
function findNext() {
if (matchCount === 0 || searchMatches.length === 0) return
currentMatchIndex = (currentMatchIndex + 1) % matchCount
highlightCurrentMatch()
if (matchCount === 0 || searchMatches.length === 0)
return;
currentMatchIndex = (currentMatchIndex + 1) % matchCount;
highlightCurrentMatch();
}
function findPrevious() {
if (matchCount === 0 || searchMatches.length === 0) return
currentMatchIndex = currentMatchIndex <= 0 ? matchCount - 1 : currentMatchIndex - 1
highlightCurrentMatch()
if (matchCount === 0 || searchMatches.length === 0)
return;
currentMatchIndex = currentMatchIndex <= 0 ? matchCount - 1 : currentMatchIndex - 1;
highlightCurrentMatch();
}
function showSearch() {
searchVisible = true
searchVisible = true;
Qt.callLater(() => {
searchField.forceActiveFocus()
})
searchField.forceActiveFocus();
});
}
function hideSearch() {
searchVisible = false
searchQuery = ""
searchMatches = []
matchCount = 0
currentMatchIndex = -1
textArea.select(0, 0)
textArea.forceActiveFocus()
searchVisible = false;
searchQuery = "";
searchMatches = [];
matchCount = 0;
currentMatchIndex = -1;
textArea.select(0, 0);
textArea.forceActiveFocus();
}
spacing: Theme.spacingM
@@ -221,43 +348,43 @@ Column {
clip: true
Component.onCompleted: {
text = root.searchQuery
text = root.searchQuery;
}
Connections {
target: root
function onSearchQueryChanged() {
if (searchField.text !== root.searchQuery) {
searchField.text = root.searchQuery
searchField.text = root.searchQuery;
}
}
}
onTextChanged: {
if (root.searchQuery !== text) {
root.searchQuery = text
root.performSearch()
root.searchQuery = text;
root.performSearch();
}
}
Keys.onEscapePressed: event => {
root.hideSearch()
event.accepted = true
root.hideSearch();
event.accepted = true;
}
Keys.onReturnPressed: event => {
if (event.modifiers & Qt.ShiftModifier) {
root.findPrevious()
root.findPrevious();
} else {
root.findNext()
root.findNext();
}
event.accepted = true
event.accepted = true;
}
Keys.onEnterPressed: event => {
if (event.modifiers & Qt.ShiftModifier) {
root.findPrevious()
root.findPrevious();
} else {
root.findNext()
root.findNext();
}
event.accepted = true
event.accepted = true;
}
}
@@ -325,6 +452,7 @@ Column {
DankFlickable {
id: flickable
visible: !root.markdownPreviewActive && !root.syntaxPreviewActive
anchors.fill: parent
anchors.margins: 1
clip: true
@@ -397,6 +525,7 @@ Column {
focus: true
activeFocusOnTab: true
textFormat: TextEdit.PlainText
// readOnly: root.syntaxPreviewActive || root.markdownPreviewActive // Handled by visibility now
inputMethodHints: Qt.ImhNoPredictiveText | Qt.ImhNoAutoUppercase
persistentSelection: true
tabStopDistance: 40
@@ -416,31 +545,45 @@ Column {
SequentialAnimation on opacity {
running: textArea.activeFocus
loops: Animation.Infinite
PropertyAnimation { from: 1.0; to: 0.0; duration: 650; easing.type: Easing.InOutQuad }
PropertyAnimation { from: 0.0; to: 1.0; duration: 650; easing.type: Easing.InOutQuad }
PropertyAnimation {
from: 1.0
to: 0.0
duration: 650
easing.type: Easing.InOutQuad
}
PropertyAnimation {
from: 0.0
to: 1.0
duration: 650
easing.type: Easing.InOutQuad
}
}
}
Component.onCompleted: {
loadCurrentTabContent()
setTextDocumentLineHeight()
root.updateLineModel()
loadCurrentTabContent();
setTextDocumentLineHeight();
root.updateLineModel();
Qt.callLater(() => {
textArea.forceActiveFocus()
})
textArea.forceActiveFocus();
});
}
Connections {
target: NotepadStorageService
function onCurrentTabIndexChanged() {
loadCurrentTabContent()
// Exit syntax preview mode when switching tabs
if (root.syntaxPreviewActive) {
root.syntaxPreviewActive = false;
}
loadCurrentTabContent();
Qt.callLater(() => {
textArea.forceActiveFocus()
})
textArea.forceActiveFocus();
});
}
function onTabsChanged() {
if (NotepadStorageService.tabs.length > 0 && !contentLoaded) {
loadCurrentTabContent()
loadCurrentTabContent();
}
}
}
@@ -448,46 +591,49 @@ Column {
Connections {
target: SettingsData
function onNotepadShowLineNumbersChanged() {
root.updateLineModel()
root.updateLineModel();
}
function onBuiltInPluginSettingsChanged() {
root.refreshPluginSettings();
}
}
onTextChanged: {
if (contentLoaded && text !== lastSavedContent) {
autoSaveTimer.restart()
autoSaveTimer.restart();
}
root.contentChanged()
root.updateLineModel()
root.contentChanged();
root.updateLineModel();
}
Keys.onEscapePressed: (event) => {
root.escapePressed()
event.accepted = true
Keys.onEscapePressed: event => {
root.escapePressed();
event.accepted = true;
}
Keys.onPressed: (event) => {
Keys.onPressed: event => {
if (event.modifiers & Qt.ControlModifier) {
switch (event.key) {
case Qt.Key_S:
event.accepted = true
root.saveRequested()
break
event.accepted = true;
root.saveRequested();
break;
case Qt.Key_O:
event.accepted = true
root.openRequested()
break
event.accepted = true;
root.openRequested();
break;
case Qt.Key_N:
event.accepted = true
root.newRequested()
break
event.accepted = true;
root.newRequested();
break;
case Qt.Key_A:
event.accepted = true
selectAll()
break
event.accepted = true;
selectAll();
break;
case Qt.Key_F:
event.accepted = true
root.showSearch()
break
event.accepted = true;
root.showSearch();
break;
}
}
}
@@ -495,6 +641,11 @@ Column {
background: Rectangle {
color: "transparent"
}
// Make links clickable in markdown preview mode
onLinkActivated: link => {
Qt.openUrlExternally(link);
}
}
StyledText {
@@ -511,6 +662,47 @@ Column {
z: textArea.z + 1
}
}
// Dedicated Flickable for Preview Mode
DankFlickable {
id: previewFlickable
visible: root.markdownPreviewActive || root.syntaxPreviewActive
anchors.fill: parent
anchors.margins: 1
clip: true
contentWidth: width - 11
TextArea.flickable: TextArea {
id: previewAreaReal
text: root.pluginHighlightedHtml
textFormat: TextEdit.RichText
readOnly: true
// Copy styling from main textArea
placeholderText: ""
font.family: SettingsData.notepadUseMonospace ? SettingsData.monoFontFamily : (SettingsData.notepadFontFamily || SettingsData.fontFamily)
font.pixelSize: SettingsData.notepadFontSize * SettingsData.fontScale
font.letterSpacing: 0
color: Theme.surfaceText
selectedTextColor: Theme.background
selectionColor: Theme.primary
selectByMouse: true
selectByKeyboard: true
wrapMode: TextArea.Wrap
focus: true
activeFocusOnTab: true
leftPadding: Theme.spacingM
topPadding: Theme.spacingM
rightPadding: Theme.spacingM
bottomPadding: Theme.spacingM
// Make links clickable
onLinkActivated: link => {
Qt.openUrlExternally(link);
}
}
}
}
Column {
@@ -575,6 +767,44 @@ Column {
color: Theme.surfaceTextMedium
}
}
// Markdown preview toggle (only visible when plugin installed and viewing .md file)
Row {
spacing: Theme.spacingS
visible: root.pluginInstalled && root.isMarkdownFile
DankActionButton {
iconName: root.markdownPreviewActive ? "visibility" : "visibility_off"
iconSize: Theme.iconSize - 2
iconColor: root.markdownPreviewActive ? Theme.primary : Theme.surfaceTextMedium
onClicked: root.toggleMarkdownPreview()
}
StyledText {
anchors.verticalCenter: parent.verticalCenter
text: I18n.tr("Preview")
font.pixelSize: Theme.fontSizeSmall
color: root.markdownPreviewActive ? Theme.primary : Theme.surfaceTextMedium
}
}
// Syntax highlighting toggle (only visible when plugin installed and viewing code file)
Row {
spacing: Theme.spacingS
visible: root.pluginInstalled && root.pluginSyntaxEnabled && root.isCodeFile
DankActionButton {
iconName: root.syntaxPreviewActive ? "code" : "code_off"
iconSize: Theme.iconSize - 2
iconColor: root.syntaxPreviewActive ? Theme.primary : Theme.surfaceTextMedium
onClicked: root.toggleSyntaxPreview()
}
StyledText {
anchors.verticalCenter: parent.verticalCenter
text: root.syntaxPreviewActive ? I18n.tr("Edit") : I18n.tr("Highlight")
font.pixelSize: Theme.fontSizeSmall
color: root.syntaxPreviewActive ? Theme.primary : Theme.surfaceTextMedium
}
}
}
DankActionButton {
@@ -608,29 +838,29 @@ Column {
StyledText {
text: {
if (autoSaveTimer.running) {
return I18n.tr("Auto-saving...")
return I18n.tr("Auto-saving...");
}
if (hasUnsavedChanges()) {
if (currentTab && currentTab.isTemporary) {
return I18n.tr("Unsaved note...")
return I18n.tr("Unsaved note...");
} else {
return I18n.tr("Unsaved changes")
return I18n.tr("Unsaved changes");
}
} else {
return I18n.tr("Saved")
return I18n.tr("Saved");
}
}
font.pixelSize: Theme.fontSizeSmall
color: {
if (autoSaveTimer.running) {
return Theme.primary
return Theme.primary;
}
if (hasUnsavedChanges()) {
return Theme.warning
return Theme.warning;
} else {
return Theme.success
return Theme.success;
}
}
opacity: textArea.text.length > 0 ? 1.0 : 0.0
@@ -643,7 +873,7 @@ Column {
interval: 2000
repeat: false
onTriggered: {
autoSaveToSession()
autoSaveToSession();
}
}
}