-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.ts
368 lines (310 loc) · 9.97 KB
/
main.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
import { App, MarkdownView, Notice, Plugin, PluginSettingTab, Setting, WorkspaceLeaf } from 'obsidian';
import { EditorView, Decoration, DecorationSet, ViewPlugin, ViewUpdate } from '@codemirror/view';
import { Range } from '@codemirror/state';
interface DialoguePluginSettings {
fadeIntensity: number;
fadeEnabled: boolean;
modifyDialogueColor: boolean;
dialogueColor: string;
dialogueStarters: string;
dialogueEnders: string;
}
const DEFAULT_SETTINGS: DialoguePluginSettings = {
fadeIntensity: 100,
fadeEnabled: true,
modifyDialogueColor: false,
dialogueColor: '#FFFFFF',
dialogueStarters: '“‘"\'«',
dialogueEnders: '”’"\'»'
}
class ColorUtility {
static updateFadeColor(settings: DialoguePluginSettings) {
if (!settings.fadeEnabled) {
document.body.style.setProperty('--adjusted-color', 'inherit');
return;
}
const fadeIntensity = settings.fadeIntensity
const baseColor = getComputedStyle(document.body).getPropertyValue('--text-normal').trim();
const fadeColor = getComputedStyle(document.body).getPropertyValue('--dialogue-excluded-text-color').trim();
const baseRGB = this.hexToRgb(baseColor);
const fadeRGB = this.hexToRgb(fadeColor);
const blendRGB = {
r: Math.round(this.lerp(baseRGB.r, fadeRGB.r, fadeIntensity / 100)),
g: Math.round(this.lerp(baseRGB.g, fadeRGB.g, fadeIntensity / 100)),
b: Math.round(this.lerp(baseRGB.b, fadeRGB.b, fadeIntensity / 100))
};
const blendedColor = `rgb(${blendRGB.r}, ${blendRGB.g}, ${blendRGB.b})`;
document.body.style.setProperty('--adjusted-color', blendedColor);
if (settings.modifyDialogueColor) {
document.body.style.setProperty('--dialogue-text-color', settings.dialogueColor);
} else {
document.body.style.setProperty('--dialogue-text-color', baseColor);
}
}
static hexToRgb(hex: string) {
const r = parseInt(hex.slice(1, 3), 16);
const g = parseInt(hex.slice(3, 5), 16);
const b = parseInt(hex.slice(5, 7), 16);
return { r, g, b };
}
static lerp(start: number, end: number, t: number) {
return start + (end - start) * t;
}
}
export default class DialoguePlugin extends Plugin {
settings: DialoguePluginSettings;
lastActiveMarkdownLeaf: WorkspaceLeaf | null = null;
toggleChanged: boolean;
async onload() {
await this.loadSettings();
this.addSettingTab(new DialoguePluginSettingsTab(this.app, this));
this.registerMarkdownPostProcessor((element, context) => {
if (this.settings.fadeEnabled) {
this.highlightDialog(element);
}
});
this.registerEditorExtension(this.dialogHighlighterExtension());
this.addCommand({
id: 'toggle-dialogue-mode',
name: 'Toggle dialogue mode',
callback: () => {
this.toggleChanged = true;
this.toggleFadeOut();
const markdownView = this.app.workspace.getActiveViewOfType(MarkdownView);
markdownView?.previewMode.rerender(true);
},
});
}
toggleFadeOut() {
this.settings.fadeEnabled = !this.settings.fadeEnabled;
this.saveSettings();
new Notice(`Dialogue fade out ${this.settings.fadeEnabled ? 'enabled' : 'disabled'}`);
ColorUtility.updateFadeColor(this.settings);
}
highlightDialog(element: HTMLElement) {
ColorUtility.updateFadeColor(this.settings);
const textNodes = this.getTextNodes(element);
textNodes.forEach(node => {
const text = node.nodeValue || "";
const result = DialogueUtility.detectDialogue(text, this);
if (result.parts.map(p => p.text).join('') !== text) {
const wrapper = document.createDocumentFragment();
result.parts.forEach(part => {
const span = document.createElement('span');
span.className = part.isDialogue ? 'dialogue-text' : 'non-dialogue-text';
span.appendChild(document.createTextNode(part.text));
wrapper.appendChild(span);
});
if (node.parentNode) {
node.parentNode.replaceChild(wrapper, node);
}
}
});
}
createWrapper(content: (string | HTMLElement)[]): HTMLElement {
const wrapper = document.createElement('span');
content.forEach(item => {
if (typeof item === 'string') {
wrapper.appendChild(document.createTextNode(item));
} else {
wrapper.appendChild(item);
}
});
return wrapper;
}
getTextNodes(element: HTMLElement): Text[] {
const textNodes: Text[] = [];
const nodesToVisit: Node[] = [element];
while (nodesToVisit.length > 0) {
const currentNode = nodesToVisit.shift();
if (currentNode) {
if (currentNode.nodeType === Node.TEXT_NODE) {
textNodes.push(currentNode as Text);
} else {
nodesToVisit.unshift(...Array.from(currentNode.childNodes));
}
}
}
return textNodes;
}
dialogHighlighterExtension() {
return ViewPlugin.define(view => new DialogueEditorExtension(view, this), {
decorations: v => v.decorations
});
}
async loadSettings() {
this.settings = Object.assign({}, DEFAULT_SETTINGS, await this.loadData());
}
async saveSettings() {
await this.saveData(this.settings);
}
}
class DialogueEditorExtension {
decorations: DecorationSet;
plugin: DialoguePlugin;
constructor(view: EditorView, plugin: DialoguePlugin) {
this.plugin = plugin;
this.decorations = this.buildDecorations(view);
}
update(update: ViewUpdate) {
if (update.docChanged || update.viewportChanged || this.plugin.toggleChanged) {
this.decorations = this.buildDecorations(update.view);
ColorUtility.updateFadeColor(this.plugin.settings);
this.plugin.toggleChanged = false;
}
}
buildDecorations(view: EditorView): DecorationSet {
if (!this.plugin.settings.fadeEnabled) {
return Decoration.none;
}
const builder: Range<Decoration>[] = [];
for (const { from, to } of view.visibleRanges) {
for (let pos = from; pos <= to;) {
const line = view.state.doc.lineAt(pos);
const text = line.text;
const result = DialogueUtility.detectDialogue(text, this.plugin);
let bufferStart = line.from;
result.parts.forEach(part => {
const end = bufferStart + part.text.length;
builder.push(Decoration.mark({ class: part.isDialogue ? 'dialogue-text' : 'non-dialogue-text' }).range(bufferStart, end));
bufferStart = end;
});
pos = line.to + 1;
}
}
return Decoration.set(builder, true);
}
}
class DialoguePluginSettingsTab extends PluginSettingTab {
plugin: DialoguePlugin;
constructor(app: App, plugin: DialoguePlugin) {
super(app, plugin);
this.plugin = plugin;
}
display(): void {
const { containerEl } = this;
containerEl.empty();
new Setting(containerEl)
.setName('Enable fade effect')
.setDesc('Enable or disable the fade effect on excluded text.')
.addToggle(toggle => {
toggle
.setValue(this.plugin.settings.fadeEnabled)
.onChange(async value => {
this.plugin.settings.fadeEnabled = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName('Fade intensity')
.setDesc('The intensity of the fade effect on excluded text.')
.addSlider(slider => {
slider
.setLimits(0, 100, 1)
.setDynamicTooltip()
.setValue(this.plugin.settings.fadeIntensity)
.onChange(async value => {
this.plugin.settings.fadeIntensity = value;
await this.plugin.saveSettings();
ColorUtility.updateFadeColor(this.plugin.settings);
});
});
new Setting(containerEl)
.setName('Modify dialogue text color')
.setDesc('Enable or disable the modification of the dialogue text color.')
.addToggle(toggle => {
toggle
.setValue(this.plugin.settings.modifyDialogueColor)
.onChange(async value => {
this.plugin.settings.modifyDialogueColor = value;
await this.plugin.saveSettings();
this.display();
ColorUtility.updateFadeColor(this.plugin.settings);
});
});
new Setting(containerEl)
.setName('Dialogue text color')
.setDesc('The color of the dialogue text.')
.addColorPicker(color => {
color
.setValue(this.plugin.settings.dialogueColor)
.setDisabled(!this.plugin.settings.modifyDialogueColor)
.onChange(async value => {
this.plugin.settings.dialogueColor = value;
await this.plugin.saveSettings();
ColorUtility.updateFadeColor(this.plugin.settings);
});
});
new Setting(containerEl)
.setName('Dialogue starters')
.setDesc('Characters that indicate the start of a dialogue.')
.addText(text => {
text
.setValue(this.plugin.settings.dialogueStarters)
.onChange(async value => {
this.plugin.settings.dialogueStarters = value;
await this.plugin.saveSettings();
});
});
new Setting(containerEl)
.setName('Dialogue enders')
.setDesc('Characters that indicate the end of a dialogue.')
.addText(text => {
text
.setValue(this.plugin.settings.dialogueEnders)
.onChange(async value => {
this.plugin.settings.dialogueEnders = value;
await this.plugin.saveSettings();
});
});
}
}
interface DialoguePart {
text: string;
isDialogue: boolean;
}
interface DetectionResult {
parts: DialoguePart[];
inDialog: boolean;
}
class DialogueUtility {
static detectDialogue(text: string, plugin: DialoguePlugin): DetectionResult {
const openQuotes = plugin.settings.dialogueStarters.split('');
const closeQuotes = plugin.settings.dialogueEnders.split('');
if (openQuotes.length == 0) {
openQuotes.push('"', '“', '‘', '«');
}
if (closeQuotes.length == 0) {
closeQuotes.push('"', '”', '’', '»');
}
const parts: DialoguePart[] = [];
let buffer = '';
let inDialog = false;
for (let i = 0; i < text.length; i++) {
const char = text[i];
if (inDialog) {
buffer += char;
if (closeQuotes.includes(char) && (i === text.length - 1 || text[i + 1] === ' ' || text[i + 1] === '.' || text[i + 1] === ',')) {
inDialog = false;
parts.push({ text: buffer, isDialogue: true });
buffer = '';
}
} else {
if (openQuotes.includes(char)) {
inDialog = true;
if (buffer) {
parts.push({ text: buffer, isDialogue: false });
buffer = '';
}
buffer += char;
} else {
buffer += char;
}
}
}
if (buffer) {
parts.push({ text: buffer, isDialogue: inDialog });
}
return { parts, inDialog: false };
}
}