-
Notifications
You must be signed in to change notification settings - Fork 2
/
MarkdownPanel.m
473 lines (407 loc) · 17.6 KB
/
MarkdownPanel.m
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
classdef MarkdownPanel < hgsetget & dynamicprops
%# MarkdownPanel
% Control which displays markdown as HTML within a MATLAB control
%
% ------
% This control utilizes the [Showdown javascript library][1] to convert
% markdown into HTML and then uses MATLAB's internal HTML components to
% display this HTML.
%
% It behaves like any other graphics object within MATLAB in that all
% properties can either be set upon object construction
%
% h = MarkdownPanel('Parent', figure, 'Content', '# Hello World!');
%
% Or after object creation using the returned handle
%
% h = MarkdownPanel();
% h.Parent = gcf;
% set(h, 'Position', [0, 0, 0.5, 0.5])
%
% To set the actual Markdown content, use the `Content` property. You
% can provide *either* a string, or a cell array of strings which will
% automatically create a multi-line entry
%
% set(h, 'Content', '#Hello World')
% set(h, 'Content', {'#Hello World', 'This is a test...'})
%
% You can use the `Options` property to modify options that are
% specific to how Showdown renders the markdown. By default, we use all
% of the default settings except that we enable support for tables.
%
% h.Options.tables = true;
%
% The `Options` property is simply a struct where the fieldnames are
% the option names and the value is the option value. You can modify
% this struct to adjust an option.
%
% % Enable support for tasklists
% h.Options.taskslists = true
%
% A complete list of options can be found in the [Showdown
% documentation][1]
%
% ------
% **Usage**
%
% panel = MarkdownPanel();
%
% **Outputs**
%
% `panel`, Graphics Object, The graphics handle that can be used
% to manipulate the appearance of the control
%
% ------
% **Demo**
%
% A demo application has been bundled with this code to show how to use
% some of the features. To run this demo, simply type the following
% into the MATLAB console.
%
% MarkdownPanel.demo()
%
% ------
% **Attribution**
%
% Copyright (c) <2024> [Jonathan Suever][2].
% All rights reserved
%
% This software is licensed under the [BSD license][3]
%
% [1]: https://github.com/showdownjs/showdown
% [2]: https://github.com/suever
% [3]: https://github.com/suever/MarkdownPanel/blob/master/LICENSE
properties
Content = '' % Markdown content to be displayed
StyleSheets = {} % List of stylesheets to link in
Classes = {} % CSS classes applied to the primary div
Options = struct() % Options to pass to showdown
TemporaryDirectory = tempdir() % Directory in which we store the HTML to render
end
properties (Access = 'protected')
contentFilename = '' % Filename of the temporary HTML file
browser % Handle to the javahandle_withcallbacks
container % Graphics handle to the HTML panel
jbrowser % Java Handle to the underlying java object
listener % Listener for when the jbrowser is deleted
htmlComponent % Java handle to embedded HTML component
end
methods
function self = MarkdownPanel(varargin)
% MarkdownPanel - Constructor for MarkdownPanel object
%
% Can accept any property as parameter/value pair. Creates
% the MarkdownPanel and returns a handle to be used to
% manipulate the appearance/content.
%
% USAGE:
% panel = MarkdownPanel(params)
%
% INPUTS:
% params: Parameter/Value pairs, Properties to set upon
% creation.
%
% OUTPUTS:
% panel: Graphics Object, The graphics handle that can be
% used to manipulate the appearance of the control.
% Use inputParser so we can handle structs AND params
ip = inputParser();
ip.KeepUnmatched = true;
ip.addParamValue('Parent', [], @ishghandle);
ip.parse(varargin{:});
if ~isempty(ip.Results.Parent)
parent = ip.Results.Parent;
else
parent = gcf;
end
% Create the HTML panel in a version-specific way
if verLessThan('matlab', '9.6')
% For pre-HG2 browsers, specify the default to be HTMLPANEL
if verLessThan('matlab', '8.4')
HtmlComponentFactory.setDefaultType('HTMLPANEL');
end
self.jbrowser = javaObjectEDT(com.mathworks.mlwidgets.html.HTMLBrowserPanel);
self.htmlComponent = self.jbrowser.getHtmlComponent();
else
self.jbrowser = javaObjectEDT(com.mathworks.mlwidgets.help.LightweightHelpPanel);
self.htmlComponent = self.jbrowser.getLightweightBrowser();
end
originalWarnings = warning;
warning('off', 'MATLAB:ui:javacomponent:FunctionToBeRemoved');
[self.browser, self.container] = javacomponent(self.jbrowser, [], parent);
warning(originalWarnings);
% By default, make it take up the entire parent
set(self.container, 'Units', 'norm', 'position', [0 0 1 1])
% Now make this look like the container object by creating
% shadow properties that interact with the underlying object
props = fieldnames(get(self.container));
for k = 1:numel(props)
% Ignore if the property is already defined
if ~isempty(self.findprop(props{k})); continue; end
% Add a dynamic property and assign setters/getters that
% will relay properties between the two objects
prop = self.addprop(props{k});
prop.SetMethod = @(s,v)setwrapper(s,prop,v);
prop.GetMethod = @(s,e)getwrapper(s,prop);
end
% If the underlying graphics object is deleted, follow suit
self.listener = addlistener(self.container, ...
'ObjectBeingDestroyed', @(s,e)delete(self));
% Setup the default options
self.Options = struct(...
'tables', true);
% Finally consider all input arguments
set(self, varargin{:})
self.refresh(true);
end
function delete(self)
% delete - Delete the MarkdownPanel and associated objects
%
% USAGE:
% panel.delete()
if ishghandle(self.container)
delete(self.container)
end
% Make sure that we dispose of the html component
self.htmlComponent.dispose();
end
function refresh(self, force)
% refresh - Force a refresh of the displayed markdown
%
% USAGE:
% panel.refresh(force)
%
% INPUTS:
% force: Logical, Indicates whether to completely redraw the
% page (including HTML) (true) or not (false). The
% default is to simply execute javascript on the
% existing page.
if iscell(self.Content)
content = sprintf('%s\\n\\n', self.Content{:});
% Remove trailing newlines
content = regexprep(content, '\n*$', '');
else
content = self.Content;
end
% Replace "true" newlines with "\n"
content = regexprep(content, '\n', '\\n');
% Make sure that we properly escape double quotes so that the
% created javascript is valid
content = regexprep(content, '"', '\\"');
% Javascript to run to update the HTML and make all hyperlinks
% external
jscript = [...
'try {', ...
'var html = conv.makeHtml("', content, '");', ...
'display.innerHTML = html;', ...
'var links = document.querySelectorAll("a");', ...
'for (var k in links) {' ...
'if ( links[k].href && links[k].href.substring(0, 4) === "http" )', ...
' links[k].target = "_blank";', ...
'}', ...
'} catch (err) { ', ...
'error.innerHTML = err.message;', ...
'};'];
% Initial load with entire javascript
if isempty(getappdata(self.container, 'initialized')) || (exist('force', 'var') && force)
% Load showdown from file that way we can catch any import
% issues and display them in the HTML
curdir = fileparts(mfilename('fullpath'));
showdownjs = fullfile(curdir, 'showdown.min.js');
% Attempt to protect the user in case they deleted showdown
if ~exist(showdownjs, 'file')
% Then go download it
url = 'https://cdn.rawgit.com/showdownjs/showdown/1.3.0/dist/showdown.min.js';
urlwrite(url, showdownjs);
end
fid = fopen(showdownjs, 'rb');
showdown = fread(fid, '*char');
fclose(fid);
% Create stylesheet entries
if numel(self.StyleSheets)
format = '<link rel="stylesheet" href="%s">\n';
stylesheets = sprintf(format, self.StyleSheets{:});
else
stylesheets = '';
end
% Create the options that we want to pass to the converter
options = self.Options;
fields = fieldnames(options);
opts = '';
for k = 1:numel(fields)
value = options.(fields{k});
if ischar(value)
value = cat(2, '"', value, '"');
else
value = num2str(value);
end
newopt = ['conv.setOption("', fields{k}, '", ', value, ');'];
opts = cat(2, opts, newopt);
end
html = {...
'<!DOCTYPE html>', ....
'<head>', ...
'<meta http-equiv="X-UA-Compatible" content="IE=edge">', ...
stylesheets, ...
'<script>', ...
'if (window.console) {', ...
'var console = window.console;', ...
'}', ...
'</script>', ...
'</head>', ...
'<body>', ...
'<div class="', sprintf('%s ', self.Classes{:}), '">', ...
'<div id="error" class="error" style="color:#F00"></div>', ...
'<div id="display">Loading...</div>', ...
'</div>', ...
'<script>', ...
'var display = document.getElementById("display");', ...
'var error = document.getElementById("error");', ...
'try {', ...
showdown(:)', ...
'var conv = new showdown.Converter();', ...
opts, ...
'} catch (err) {', ...
'error.innerHTML = err.message;', ...
'display.innerHTML = "";', ...
'}', ...
'</script>', ...
'</body>', ...
'</html>'};
html = sprintf('%s\n', html{:});
% Older versions of MATLAB allow us to specify HTML directly whereas newer versions require us to
% provide an HTML file path to be loaded
if self.useInlineHTML()
self.htmlComponent.setHtmlText(html);
else
if isempty(self.contentFilename)
self.contentFilename = fullfile(self.TemporaryDirectory, sprintf('%s.html', java.util.UUID.randomUUID));
if ~exist(self.TemporaryDirectory, 'dir')
mkdir(self.TemporaryDirectory);
end
end
fid = fopen(self.contentFilename, 'w');
fprintf(fid, '%s', html);
fclose(fid);
self.htmlComponent.load(sprintf('file://%s', self.contentFilename));
end
setappdata(self.container, 'initialized', true);
end
% Convert the markdown to HTML and render it
self.htmlComponent.executeScript(jscript);
end
end
% Set/Get Methods
methods
function set.Content(self, val)
% Look and see if this is a cell array
self.Content = val;
self.refresh();
end
function set.Options(self, val)
% Check to see if they are equal to the old value
if isequal(val, self.Options)
return;
end
self.Options = val;
% Force a complete refresh
self.refresh(true);
end
function set.StyleSheets(self, val)
if ischar(val); val = {val}; end
self.StyleSheets = val;
% Do a hard-refresh of the page
self.refresh(true);
end
function set.TemporaryDirectory(self, val)
w = what(val);
self.TemporaryDirectory = w.path;
end
function set.Classes(self, val)
if ischar(val); val = {val}; end
self.Classes = val;
% Do a hard-refresh of the page
self.refresh(true);
end
end
% These methods automatically translate the properties between the
% underlying object and the current object
methods (Access = 'protected')
function setwrapper(self, prop, value)
% Relays "set" events to the underlying container object
set(self.container, prop.Name, value)
end
function res = getwrapper(self, prop)
% Relays "get" events to the underlying container object
res = get(self.container, prop.Name);
end
function res = useInlineHTML(self)
% HTML to be specified inline
res = ismethod(self.htmlComponent, 'setHtmlText');
end
end
methods (Static)
function panel = demo()
% demo - Demonstrate how to create/use the MarkdownPanel object
%
% This demo creates a simple markdown editor/preview window
% that showcases how to set the content of the markdown
% panel. To do this, it simply shows the help text for the
% MarkdownPanel in both the editor and preview.
%
% It also demonstrates the use of stylesheets (in this case
% Twitter Bootstrap)
%
% USAGE:
% panel = MarkdownPanel.demo()
fig = figure( ...
'Position', [0 0 1200, 700], ...
'Toolbar', 'none', ...
'menubar', 'none', ...
'NumberTitle', 'off', ...
'Name', 'MarkdownPanel Demo');
movegui(fig, 'center');
drawnow;
% Create two side-by-side panels
flow = uiflowcontainer('v0', 'FlowDirection', 'lefttoright');
% Grab the help section and do a little cleanup
h = help(mfilename('fullpath'));
h = regexprep(h, '^\s*', '');
h = regexprep(h, '\n ', '\n');
% Create a java control because the builtin editbox doesn't
% easily return the current value
je = javax.swing.JEditorPane('text', h);
jp = javax.swing.JScrollPane(je);
originalWarnings = warning();
warning('off', 'MATLAB:ui:javacomponent:FunctionToBeRemoved');
[~, hcomp] = javacomponent(jp, [], flow);
set(hcomp, 'Position', [0 0 0.5 1])
warning(originalWarnings);
% Construct the MarkdownPanel object
twitter = 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css';
panel = MarkdownPanel( ...
'Content', h, ...
'Parent', flow, ...
'StyleSheets', twitter, ...
'Classes', 'container');
% Set the option to enable smooth live previews
panel.Options.smoothLivePreview = true;
% Setup a timer to refresh the MarkdownPanel periodically
timerFcn = @(s,e)set(panel, 'Content', char(je.getText()));
htimer = timer( ...
'Period', 1, ...
'BusyMode', 'drop', ...
'TimerFcn', timerFcn, ...
'ExecutionMode', 'fixedRate');
% Destroy the timer when the panel is destroyed
function stopAndDeleteTimer()
stop(htimer);
delete(htimer);
end
L = addlistener(panel, 'ObjectBeingDestroyed', @(s,e)stopAndDeleteTimer());
setappdata(fig, 'Timer', L);
% Start the refresh timer
start(htimer)
end
end
end