-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsquibview.js
More file actions
4465 lines (3869 loc) · 156 KB
/
squibview.js
File metadata and controls
4465 lines (3869 loc) · 156 KB
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
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* SquibView a live md/html/etc Editor/renderer with copy support
supports markdown, html, and split view
supports copying of formatted html and markdown
supports copying of images as data urls
supports copying of svg as png
supports copying of tables as formatted tables
supports copying of code blocks as formatted tables
supports copying of math blocks as formatted math
by deftio (c) 2024
*/
// Import required libraries
import TinyEmitter from 'tiny-emitter';
import DiffMatchPatch from 'diff-match-patch';
import './squibview.css'; // Import the main CSS file
import { VERSION, REPO_URL } from './version.js'; // Import version info
import EventEmitter3 from 'eventemitter3';
import MarkdownIt from 'markdown-it'; // Import markdown-it
import Papa from 'papaparse';
import HtmlToMarkdown from './HtmlToMarkdown.js';
import { RevisionHistory } from './RevisionHistory.js';
// Import highlight.js for syntax highlighting
// Use dynamic lookup to maintain compatibility with different build targets
function getHljs() {
try {
if (typeof window !== 'undefined' && window.hljs) {
return window.hljs;
}
if (typeof global !== 'undefined' && global.hljs) {
return global.hljs;
}
} catch (e) {
// Ignore errors
}
return null;
}
// Fix for development mode
/*
try {
if (!TinyEmitter || !DiffMatchPatch) {
// If direct imports failed, try the shim
const shim = await import('./import-shim.js');
if (!TinyEmitter && shim.TinyEmitter) TinyEmitter = shim.TinyEmitter;
if (!DiffMatchPatch && shim.DiffMatchPatch) DiffMatchPatch = shim.DiffMatchPatch;
}
} catch (e) {
console.warn('Import shim not available, continuing with direct imports', e);
}
*/
/**
* SquibView is a lightweight editor that live-renders different content types
*/
class SquibView {
static defaultOptions = {
initialContent: '',
inputContentType: 'md', // 'md', 'html', 'reveal', 'csv' or 'tsv'
showControls: true,
titleShow: false,
titleContent: '',
initialView: 'split',
baseClass: 'squibview',
onReplaceSelectedText: null,
preserveImageTags: true, // Changed default to true
showLineNumbers: false, // Enable/disable line numbers
lineNumberStart: 1, // Starting line number
lineNumberMinDigits: 2, // Minimum digits (e.g., 01, 02)
autoload_deps: null, // Default off, can be { all: true } or fine-grained control
streamingMode: false, // Enable streaming-friendly error handling
incompleteBlockPlaceholder: '⏳ Rendering...', // Placeholder for incomplete blocks
renderErrorPlaceholder: '❌ Render error', // Placeholder for render errors
errorHandling: null // Fine-grained error control
};
// Default CDN URLs for autoloading dependencies
static DEFAULT_CDN_URLS = {
mermaid: {
script: 'https://unpkg.com/mermaid@10.6.1/dist/mermaid.min.js'
},
hljs: {
script: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js',
css: 'https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/styles/github.min.css'
},
mathjax: {
script: 'https://cdn.jsdelivr.net/npm/mathjax@3.2.2/es5/tex-svg.js'
},
leaflet: {
script: 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.js',
css: 'https://unpkg.com/leaflet@1.9.4/dist/leaflet.css'
},
three: {
script: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js'
},
stlLoader: {
script: 'https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/STLLoader.js'
},
orbitControls: {
script: 'https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/controls/OrbitControls.js'
}
};
static version = {
version: VERSION,
url: REPO_URL
};
/**
* Creates a new SquibView instance.
*
* @param {HTMLElement|string} element - The DOM element or selector where the editor will be mounted
* @param {Object} options - Configuration options for the editor
* @param {string} [options.initialContent=''] - Initial content to load
* @param {string} [options.inputContentType='md'] - Type of the initial content ('md', 'html', 'reveal', 'csv', 'tsv')
* @param {boolean} [options.showControls=true] - Whether to show the control buttons
* @param {boolean} [options.titleShow=false] - Whether to show the title section
* @param {string} [options.titleContent=''] - Content for the title section
* @param {string} [options.initialView='split'] - Initial view mode ('src', 'html', 'split')
* @param {string} [options.baseClass='squibview'] - Base CSS class for styling
* @param {Object|null} [options.autoload_deps=null] - Configuration for autoloading dependencies. null = disabled (default), { all: true } = enable all, or fine-grained control per library
* @throws {Error} Throws if the container element is not found
*/
constructor(element, options = {}) {
this.options = { ...SquibView.defaultOptions, ...options };
this.container = typeof element === 'string' ? document.querySelector(element) : element;
if (!this.container) {
throw new Error('Container element not found');
}
// Initialize autoload configuration
this._initializeAutoload();
// Initialize event emitter for plugin communication and selection events
this.events = new TinyEmitter();
// Initialize revision manager
this.revisionManager = new RevisionHistory();
// Track last selection data
this.lastSelectionData = null;
// Store text selection handlers
this._onTextReplacementHandler = null;
// Initialize renderer registry
this.renderers = {};
// Initialize HTML to Markdown converter
this._initializeHtmlToMarkdown();
// Initialize libraries and register default renderers
this.initializeLibraries();
this.registerDefaultRenderers();
// Create DOM structure
this.createStructure();
this.initializeEventHandlers();
this.initializeResizeObserver();
// Initialize line numbers if enabled
if (this.options.showLineNumbers) {
this.initializeLineNumbers();
}
// Set initial content
if (this.options.initialContent) {
this.revisionManager.initialize(this.options.initialContent, this.options.inputContentType);
this.setContent(this.options.initialContent, this.options.inputContentType, false);
} else {
this.revisionManager.initialize('', this.options.inputContentType);
}
// Set initial view
this.setView(this.options.initialView);
// Update UI elements based on current content type
this.updateTypeButtons();
// Set up text replacement handler if provided in options
if (this.options.onReplaceSelectedText) {
this.onReplaceSelectedText = this.options.onReplaceSelectedText;
}
}
/**
* Initialize autoload configuration
* @private
*/
_initializeAutoload() {
const autoloadConfig = this.options.autoload_deps;
// If autoload is disabled (null or false), do nothing
if (!autoloadConfig) {
this.autoloadConfig = null;
return;
}
// Parse the configuration
this.autoloadConfig = {
enabled: true,
cdnUrls: { ...SquibView.DEFAULT_CDN_URLS, ...(autoloadConfig.cdnUrls || {}) },
libraries: {}
};
// Helper to parse library config
const parseLibConfig = (libName, config) => {
// If 'all' is set, apply to all libraries
if (config.all === true) {
return { strategy: 'ondemand' };
} else if (config.all === 'auto') {
return { strategy: 'auto' };
} else if (config.all === false) {
return { strategy: 'none' };
}
// Check specific library config
const libConfig = config[libName];
if (libConfig === false || libConfig === 'none') {
return { strategy: 'none' };
} else if (libConfig === true || libConfig === 'ondemand') {
return { strategy: 'ondemand' };
} else if (libConfig === 'auto') {
return { strategy: 'auto' };
} else if (typeof libConfig === 'function') {
return { strategy: 'custom', handler: libConfig };
} else if (typeof libConfig === 'object') {
return libConfig;
}
// Default based on 'all' setting or ondemand
return config.all ? { strategy: 'ondemand' } : { strategy: 'none' };
};
// Configure each library
['mermaid', 'hljs', 'mathjax', 'leaflet', 'three'].forEach(lib => {
this.autoloadConfig.libraries[lib] = parseLibConfig(lib, autoloadConfig);
});
// Track loaded libraries
this.loadedLibraries = new Set();
this.loadingPromises = {};
// Load 'auto' libraries immediately after init
setTimeout(() => this._loadAutoLibraries(), 0);
}
/**
* Load libraries configured with 'auto' strategy
* @private
*/
async _loadAutoLibraries() {
if (!this.autoloadConfig || !this.autoloadConfig.enabled) return;
for (const [libName, config] of Object.entries(this.autoloadConfig.libraries)) {
if (config.strategy === 'auto') {
await this._autoloadLibrary(libName);
}
}
}
/**
* Load a script dynamically
* @private
*/
_loadScript(src) {
return new Promise((resolve, reject) => {
if (document.querySelector(`script[src="${src}"]`)) {
resolve();
return;
}
const script = document.createElement('script');
script.src = src;
script.onload = resolve;
script.onerror = () => reject(new Error(`Failed to load script: ${src}`));
document.head.appendChild(script);
});
}
/**
* Load a CSS file dynamically
* @private
*/
_loadCSS(href) {
return new Promise((resolve, reject) => {
if (document.querySelector(`link[href="${href}"]`)) {
resolve();
return;
}
const link = document.createElement('link');
link.rel = 'stylesheet';
link.href = href;
link.onload = resolve;
link.onerror = () => reject(new Error(`Failed to load CSS: ${href}`));
document.head.appendChild(link);
});
}
/**
* Autoload a specific library
* @private
*/
async _autoloadLibrary(libName) {
if (!this.autoloadConfig || !this.autoloadConfig.enabled) return false;
const config = this.autoloadConfig.libraries[libName];
if (!config || config.strategy === 'none') return false;
// Check if already loaded
if (this.loadedLibraries.has(libName)) return true;
// Check if library is already available
if (this._isLibraryLoaded(libName)) {
this.loadedLibraries.add(libName);
return true;
}
// Handle custom loading strategy
if (config.strategy === 'custom' && config.handler) {
const result = await config.handler();
if (result) this.loadedLibraries.add(libName);
return result;
}
// Check if already loading
if (this.loadingPromises[libName]) {
return this.loadingPromises[libName];
}
// Start loading
const cdnConfig = this.autoloadConfig.cdnUrls[libName];
if (!cdnConfig) return false;
this.loadingPromises[libName] = this._loadLibraryAssets(libName, cdnConfig);
try {
const result = await this.loadingPromises[libName];
if (result) {
this.loadedLibraries.add(libName);
// Re-initialize if needed
if (libName === 'mermaid') {
this.initializeLibraries();
}
}
return result;
} finally {
delete this.loadingPromises[libName];
}
}
/**
* Load library assets (script and optional CSS)
* @private
*/
async _loadLibraryAssets(libName, cdnConfig) {
try {
const promises = [];
if (cdnConfig.script) {
promises.push(this._loadScript(cdnConfig.script));
}
if (cdnConfig.css) {
promises.push(this._loadCSS(cdnConfig.css));
}
await Promise.all(promises);
// Wait for library to be available
await this._waitForLibrary(libName);
// Special handling for Three.js - load additional dependencies after THREE is available
if (libName === 'three' && window.THREE) {
// STLLoader and OrbitControls need THREE to be globally available
if (this.autoloadConfig.cdnUrls.stlLoader) {
await this._loadScript(this.autoloadConfig.cdnUrls.stlLoader.script);
}
if (this.autoloadConfig.cdnUrls.orbitControls) {
await this._loadScript(this.autoloadConfig.cdnUrls.orbitControls.script);
}
}
return this._isLibraryLoaded(libName);
} catch (err) {
if (this.autoloadConfig.debug) {
console.error(`Failed to load ${libName}:`, err);
}
return false;
}
}
/**
* Wait for a library to become available
* @private
*/
_waitForLibrary(libName, maxAttempts = 20) {
return new Promise((resolve) => {
let attempts = 0;
const check = () => {
if (this._isLibraryLoaded(libName) || attempts >= maxAttempts) {
resolve();
} else {
attempts++;
setTimeout(check, 100);
}
};
check();
});
}
/**
* Check if a library is loaded
* @private
*/
_isLibraryLoaded(libName) {
switch (libName) {
case 'mermaid':
return typeof window !== 'undefined' && typeof window.mermaid !== 'undefined';
case 'hljs':
return typeof window !== 'undefined' && typeof window.hljs !== 'undefined';
case 'mathjax':
return typeof window !== 'undefined' && typeof window.MathJax !== 'undefined';
case 'leaflet':
return typeof window !== 'undefined' && typeof window.L !== 'undefined';
case 'three':
return typeof window !== 'undefined' && typeof window.THREE !== 'undefined';
default:
return false;
}
}
/**
* Check content and autoload required libraries
* @private
*/
async _checkAndAutoloadLibraries(content) {
if (!this.autoloadConfig || !this.autoloadConfig.enabled) return;
const promises = [];
// Check for mermaid diagrams
if (content.includes('```mermaid')) {
const config = this.autoloadConfig.libraries.mermaid;
if (config && config.strategy === 'ondemand') {
promises.push(this._autoloadLibrary('mermaid'));
}
}
// Check for code blocks (for syntax highlighting)
if (/```\w+/.test(content)) {
const config = this.autoloadConfig.libraries.hljs;
if (config && config.strategy === 'ondemand') {
promises.push(this._autoloadLibrary('hljs'));
}
}
// Check for math content
if (content.includes('$$') || content.includes('```math')) {
const config = this.autoloadConfig.libraries.mathjax;
if (config && config.strategy === 'ondemand') {
promises.push(this._autoloadLibrary('mathjax'));
}
}
// Check for GeoJSON/TopoJSON
if (content.includes('```geojson') || content.includes('```topojson')) {
const config = this.autoloadConfig.libraries.leaflet;
if (config && config.strategy === 'ondemand') {
promises.push(this._autoloadLibrary('leaflet'));
}
}
// Check for STL 3D models
if (content.includes('```stl')) {
const config = this.autoloadConfig.libraries.three;
if (config && config.strategy === 'ondemand') {
promises.push(this._autoloadLibrary('three'));
}
}
// Wait for all libraries to load
if (promises.length > 0) {
await Promise.all(promises);
}
}
/**
* Initialize the HTML to Markdown converter
*
* @private
*/
async _initializeHtmlToMarkdown() {
try {
// Try to load synchronously first for better performance
if (typeof HtmlToMarkdown !== 'undefined') {
// If HtmlToMarkdown is already available globally (e.g., in UMD build)
this._htmlToMarkdownConverter = new HtmlToMarkdown({
cacheSize: 20 // Cache up to 20 recent conversions for better performance
});
} else {
// Fall back to dynamic import if needed
const module = await import('./HtmlToMarkdown.js');
const HtmlToMarkdownClass = module.default;
this._htmlToMarkdownConverter = new HtmlToMarkdownClass({
cacheSize: 20
});
}
} catch (err) {
console.error('Failed to load HtmlToMarkdown module:', err);
// Provide a minimal fallback implementation
this._htmlToMarkdownConverter = {
convert: (html) => {
const div = document.createElement('div');
div.innerHTML = html;
return div.textContent;
}
};
}
}
/**
* Initializes the required libraries for rendering content.
* Sets up Mermaid for diagrams and markdown-it for Markdown processing.
*
* @private
*/
initializeLibraries() {
// Initialize Mermaid for diagram rendering if available
if (typeof window !== 'undefined' && window.mermaid) {
const self = this;
window.mermaid.initialize({
startOnLoad: false,
securityLevel: 'loose',
theme: 'default',
errorCallback: function (error) {
// Only log errors if not in streaming mode or if explicitly configured
if (!self._shouldSuppressErrors('mermaid')) {
console.warn("Mermaid error:", error);
}
return "<div class='mermaid-error'></div>";
}
});
// Don't auto-init in streaming mode - we'll handle it manually
if (!this.options.streamingMode) {
window.mermaid.init(undefined, ".mermaid");
}
}
// Initialize markdown-it with options and syntax highlighting
this.md = new MarkdownIt({
html: true,
linkify: true,
typographer: true,
breaks: false, // Set to true to preserve single line breaks
highlight: (str, lang) => {
const hljs = getHljs();
if (lang && hljs && hljs.getLanguage && hljs.getLanguage(lang)) {
try {
return hljs.highlight(str, { language: lang }).value;
} catch (e) {
// Fallback to no highlighting on error
}
}
return '';
}
});
// Configure custom fence rendering for markdown-it
const defaultFence = this.md.renderer.rules.fence ||
((tokens, idx, options, env, self) => self.renderToken(tokens, idx, options));
this.md.renderer.rules.fence = (tokens, idx, options, env, self) => {
const token = tokens[idx];
const info = token.info.trim().toLowerCase(); // Normalize to lowercase
const content = token.content; // Raw content from the fenced block
// Handle Mermaid diagrams
if (info === 'mermaid') {
const escapedContent = this.md.utils.escapeHtml(content);
return `<div class="mermaid" data-source-type="mermaid">${escapedContent}</div>`;
}
// Handle SVG directly
if (info === 'svg') {
const escapeForAttribute = (str) => {
return str.replace(/&/g, '&')
.replace(/"/g, '"')
.replace(/'/g, ''')
.replace(/</g, '<')
.replace(/>/g, '>');
};
const escapedSource = escapeForAttribute(content);
return `<div class="svg-container" data-source-type="svg" data-original-source="${escapedSource}">${content}</div>`;
}
// Handle GeoJSON maps
if (info === 'geojson') {
const escapedContent = this.md.utils.escapeHtml(content);
const escapedSource = this.md.utils.escapeHtml(content);
return `<div class="geojson-container" data-source-type="geojson" data-original-source="${escapedSource}">${escapedContent}</div>`;
}
// Handle TopoJSON maps
if (info === 'topojson') {
const escapedContent = this.md.utils.escapeHtml(content);
const escapedSource = this.md.utils.escapeHtml(content);
return `<div class="topojson-container" data-source-type="topojson" data-original-source="${escapedSource}">${escapedContent}</div>`;
}
// Handle STL 3D models
if (info === 'stl') {
const escapedContent = this.md.utils.escapeHtml(content);
const escapedSource = this.md.utils.escapeHtml(content);
return `<div class="stl-container" data-source-type="stl" data-original-source="${escapedSource}">${escapedContent}</div>`;
}
// Handle mathematical expressions
if (info === 'math') {
const mathId = 'math-' + Math.random().toString(36).substring(2, 15);
// Pass raw 'content' to MathJax, wrapped in $$ ... $$ on a single line
const singleLineContent = content.replace(/\r?\n/g, ' ').replace(/\s+/g, ' ').trim();
return `<div id="${mathId}" class="math-display" data-source-type="math">$${'$'}${singleLineContent}$${'$'}</div>`;
}
// Default fence renderer (for code blocks)
const langName = token.info.trim().split(/\s+/)[0] || '';
const escapedLangName = this.md.utils.escapeHtml(langName);
const tableLangs = ['csv', 'tsv', 'psv'];
if (tableLangs.includes(langName)) {
try {
if (typeof Papa === 'undefined' || typeof Papa.parse !== 'function') {
return `<pre class="squibview-error" data-source-type="${escapedLangName}">Error: PapaParse library not loaded.</pre>`;
}
let parseConfig = { skipEmptyLines: true };
if (langName !== 'tsv') parseConfig.delimiter = langName === 'csv' ? ',' : '|';
const parsedData = Papa.parse(content, parseConfig);
if (parsedData.errors && parsedData.errors.length > 0) {
let errorMessages = parsedData.errors.map(err => `${err.type}: ${err.message} (Row: ${err.row})`).join('\n');
return `<pre class="squibview-error" data-source-type="${escapedLangName}">Error parsing ${langName} data:\n${this.md.utils.escapeHtml(errorMessages)}</pre>`;
}
return `<div data-source-type="${escapedLangName}">${this._dataToHtmlTable(parsedData.data)}</div>`;
} catch (e) {
return `<pre class="squibview-error" data-source-type="${escapedLangName}">Could not render ${this.md.utils.escapeHtml(langName)} table.</pre>`;
}
}
let codeHtml;
const hljs = getHljs();
if (hljs && hljs.getLanguage && hljs.getLanguage(langName)) {
try {
const highlightedContent = hljs.highlight(content, { language: langName, ignoreIllegals: true }).value;
codeHtml = `<pre><code class="hljs language-${escapedLangName}" data-source-type="code" data-lang="${escapedLangName}">${highlightedContent}</code></pre>`;
} catch (e) {
// Fallback to non-highlighted if error occurs
}
}
if (!codeHtml) {
const escapedContent = this.md.utils.escapeHtml(content);
codeHtml = `<pre><code class="hljs language-${escapedLangName}" data-source-type="code" data-lang="${escapedLangName}">${escapedContent}</code></pre>`;
}
return `<div data-source-type="${escapedLangName || 'code'}">${codeHtml}</div>`;
};
}
/**
* Converts parsed data (array of arrays) to an HTML table string.
*
* @param {Array<Array<string>>} rows - The data rows, where the first row is the header.
* @returns {string} An HTML table string.
* @private
*/
_dataToHtmlTable(rows) {
if (!rows || rows.length === 0) {
return '<p class="squibview-info">No data to display.</p>';
}
let html = '<table class="squibview-data-table">';
// Header
const headerCells = rows[0];
html += '<thead><tr>';
headerCells.forEach(cell => {
html += `<th>${this.md.utils.escapeHtml(String(cell))}</th>`;
});
html += '</tr></thead>';
// Body
html += '<tbody>';
for (let i = 1; i < rows.length; i++) {
html += '<tr>';
const bodyCells = rows[i];
// Ensure all rows have the same number of cells as the header
// by either truncating or padding with empty cells
for (let j = 0; j < headerCells.length; j++) {
const cellContent = bodyCells[j] !== undefined ? String(bodyCells[j]) : '';
html += `<td>${this.md.utils.escapeHtml(cellContent)}</td>`;
}
html += '</tr>';
}
html += '</tbody></table>';
return html;
}
/**
* Registers a content type renderer with specified configuration
*
* @param {string} type - The content type identifier ('md', 'html', etc.)
* @param {Object} config - Renderer configuration
* @param {Function} config.render - Function to render the content type
* @param {Function} [config.sourceToOutput] - Function to transform source to output
* @param {Function} [config.outputToSource] - Function to transform output back to source
* @param {Object} [config.operations] - Map of operations that can be performed on this content type
* @param {Array} [config.buttons] - Buttons to display when this content type is active
*/
registerRenderer(type, config) {
this.renderers[type] = config;
// Trigger event for plugins to react
this.events.emit('renderer:registered', type, config);
// Update buttons if this is the current content type
if (this.inputContentType === type) {
this.updateTypeButtons();
}
}
/**
* Registers the default renderers for standard content types
*
* @private
*/
registerDefaultRenderers() {
// Markdown renderer
this.registerRenderer('md', {
render: (source) => this.renderMarkdown(source),
sourceToOutput: (source) => this.md.render(source),
outputToSource: (output, options = {}) => this.htmlToMarkdown(output, options),
operations: {
increaseHeadings: (src) => this.markdownAdjustHeadings(src, 1),
decreaseHeadings: (src) => this.markdownAdjustHeadings(src, -1),
removeHR: (src) => src.replace(/---/g, ''),
fixLinefeeds: (src) => this.fixLinefeedsInMarkdown(src),
toggleLinefeedView: () => { this.toggleLinefeedView(); return this.getContent(); }
},
buttons: [
{ label: 'H-', action: 'decreaseHeadings', title: 'Decrease heading levels' },
{ label: 'H+', action: 'increaseHeadings', title: 'Increase heading levels' },
{ label: 'Remove HR', action: 'removeHR', title: 'Remove horizontal rules' },
{ label: 'Smart Linefeeds', action: 'fixLinefeeds', title: 'Convert all single line breaks to hard line breaks (two spaces + newline) in the source.' }
]
});
// HTML renderer
this.registerRenderer('html', {
render: (source) => this.renderHTML(source),
sourceToOutput: (source) => source,
outputToSource: (output) => output,
operations: {},
buttons: []
});
// RevealJS renderer
this.registerRenderer('reveal', {
render: (source) => this.renderHTML(this.makeRevealJSFullPage(source)),
sourceToOutput: (source) => this.makeRevealJSFullPage(source),
outputToSource: (output) => output,
operations: {},
buttons: []
});
// CSV renderer
this.registerRenderer('csv', {
render: (source) => {
const markdownTable = this.csvOrTsvToMarkdownTable(source, ',');
this.renderMarkdown(markdownTable);
},
sourceToOutput: (source) => this.csvOrTsvToMarkdownTable(source, ','),
outputToSource: (output) => this.tableToCSV(output),
operations: {},
buttons: []
});
// TSV renderer
this.registerRenderer('tsv', {
render: (source) => {
const markdownTable = this.csvOrTsvToMarkdownTable(source, '\t');
this.renderMarkdown(markdownTable);
},
sourceToOutput: (source) => this.csvOrTsvToMarkdownTable(source, '\t'),
outputToSource: (output) => this.tableToCSV(output, '\t'),
operations: {},
buttons: []
});
// Semicolon separated values renderer
this.registerRenderer('semisv', {
render: (source) => {
const markdownTable = this.csvOrTsvToMarkdownTable(source, ';');
this.renderMarkdown(markdownTable);
},
sourceToOutput: (source) => this.csvOrTsvToMarkdownTable(source, ';'),
outputToSource: (output) => this.tableToCSV(output, ';'),
operations: {},
buttons: []
});
// Space separated values renderer
this.registerRenderer('ssv', {
render: (source) => {
const markdownTable = this.csvOrTsvToMarkdownTable(source, ' ');
this.renderMarkdown(markdownTable);
},
sourceToOutput: (source) => this.csvOrTsvToMarkdownTable(source, ' '),
outputToSource: (output) => this.tableToCSV(output, ' '),
operations: {},
buttons: []
});
}
/**
* Creates the DOM structure for the editor.
* Sets up the title bar, controls, and editor areas.
*
* @private
*/
createStructure() {
this.container.classList.add(this.options.baseClass);
this.container.innerHTML = `
<div class="${this.options.baseClass}-title" ${!this.options.titleShow ? 'style="display:none"' : ''}>
${this.options.titleContent}
</div>
<div class="${this.options.baseClass}-controls" ${!this.options.showControls ? 'style="display:none"' : ''}>
<button data-view='src'>Source</button>
<button data-view="html">Rendered</button>
<button data-view="split">Split</button>
<button class="copy-src-button">Copy Source</button>
<button class="copy-html-button">Copy Rendered</button>
<button class="revision-undo" title="Undo">↩</button>
<button class="revision-redo" title="Redo">↪</button>
<span class="${this.options.baseClass}-type-buttons"></span>
</div>
<div class="${this.options.baseClass}-editor">
${this.options.showLineNumbers ?
`<div class="${this.options.baseClass}-source-panel">
<div class="${this.options.baseClass}-line-gutter"></div>
<textarea class="${this.options.baseClass}-input"></textarea>
</div>` :
`<textarea class="${this.options.baseClass}-input"></textarea>`
}
<div class="${this.options.baseClass}-output"></div>
</div>
`;
this.title = this.container.querySelector(`.${this.options.baseClass}-title`);
this.controls = this.container.querySelector(`.${this.options.baseClass}-controls`);
this.editor = this.container.querySelector(`.${this.options.baseClass}-editor`);
this.input = this.container.querySelector(`.${this.options.baseClass}-input`);
this.output = this.container.querySelector(`.${this.options.baseClass}-output`);
this.typeButtonsContainer = this.container.querySelector(`.${this.options.baseClass}-type-buttons`);
this.universalButtonsContainer = this.container.querySelector(`.${this.options.baseClass}-universal-buttons`);
// Line numbers elements
if (this.options.showLineNumbers) {
this.sourcePanel = this.container.querySelector(`.${this.options.baseClass}-source-panel`);
this.lineGutter = this.container.querySelector(`.${this.options.baseClass}-line-gutter`);
}
}
/**
* Updates the type-specific buttons based on the current content type
*
* @private
*/
updateTypeButtons() {
// Clear current buttons
this.typeButtonsContainer.innerHTML = '';
// Get buttons for current content type
const renderer = this.renderers[this.inputContentType];
if (renderer && renderer.buttons && renderer.buttons.length > 0) {
renderer.buttons.forEach(button => {
const btn = document.createElement('button');
btn.textContent = button.label;
if (button.title) {
btn.title = button.title;
}
btn.addEventListener('click', () => {
if (renderer.operations && renderer.operations[button.action]) {
const newContent = renderer.operations[button.action](this.getContent());
this.setContent(newContent, this.inputContentType);
}
});
this.typeButtonsContainer.appendChild(btn);
});
}
}
/**
* Sets up event listeners for user interactions.
* Handles view changes, copy functionality, and input changes.
*
* @private
*/
initializeEventHandlers() {
// View buttons
this.controls.querySelectorAll('button[data-view]').forEach(button => {
button.addEventListener('click', () => this.setView(button.dataset.view));
});
// Copy buttons
this.controls.querySelector('.copy-src-button').addEventListener('click', () => this.copySource());
this.controls.querySelector('.copy-html-button').addEventListener('click', () => this.copyHTML());
// Undo/redo buttons
this.controls.querySelector('.revision-undo').addEventListener('click', () => this.revisionUndo());
this.controls.querySelector('.revision-redo').addEventListener('click', () => this.revisionRedo());
// Input source change event
this.input.addEventListener('input', () => {
this.setContent();
});
// Text selection event in source panel
this.input.addEventListener('mouseup', () => {
const selection = document.getSelection();
if (selection && selection.toString().trim() !== '') {
const selectionData = {
panel: 'source',
text: selection.toString(),
range: {
start: this.input.selectionStart,
end: this.input.selectionEnd
}
};
this.lastSelectionData = selectionData;
this.events.emit('text:selected', selectionData);
}
});
// Listen for changes in rendered content to support bidirectional editing
// Use a debounce pattern to prevent processing every keystroke
let editDebounceTimer = null;
// Create a map to store special content blocks
this.specialContentBlocks = new Map();
this.output.addEventListener('input', () => {
if (this.currentView === 'html' || this.currentView === 'split') {
const editableContent = this.output.querySelector('[contenteditable="true"]');
if (editableContent) {
// Clear any existing timer
if (editDebounceTimer) {
clearTimeout(editDebounceTimer);
}
// Set a new timer to process the edit after a short delay (300ms)
editDebounceTimer = setTimeout(() => {
const renderedContent = editableContent.innerHTML;
const renderer = this.renderers[this.inputContentType];
if (renderer && renderer.outputToSource) {
// Get the original source markdown
const originalSource = this.input.value;
// Process the HTML back to markdown, passing original source for context
let newSource = renderer.outputToSource(renderedContent, {
originalSource: originalSource
});
// Update source without triggering render cycle
this.input.value = newSource;
// Only save revision after editing stops for a moment
this.revisionManager.addRevision(newSource, this.inputContentType);
// Emit content change event
this.events.emit('content:change', newSource, this.inputContentType);
}
// Clear the timer reference
editDebounceTimer = null;
}, 300);
}
}
});
// Text selection event in rendered panel
this.output.addEventListener('mouseup', () => {
const selection = document.getSelection();
if (selection && selection.toString().trim() !== '') {
const range = selection.getRangeAt(0);
const selectionData = {
panel: 'rendered',
text: selection.toString(),