wizard-editor.js.es6 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. /*global Mousetrap:true */
  2. import { default as computed, on, observes } from 'ember-addons/ember-computed-decorators';
  3. import { cookAsync } from '../lib/text-lite';
  4. import { getRegister } from 'discourse-common/lib/get-owner';
  5. import { siteDir } from 'discourse/lib/text-direction';
  6. import { determinePostReplaceSelection, clipboardData } from '../lib/utilities-lite';
  7. import toMarkdown from 'discourse/lib/to-markdown';
  8. // Our head can be a static string or a function that returns a string
  9. // based on input (like for numbered lists).
  10. function getHead(head, prev) {
  11. if (typeof head === "string") {
  12. return [head, head.length];
  13. } else {
  14. return getHead(head(prev));
  15. }
  16. }
  17. function getButtonLabel(labelKey, defaultLabel) {
  18. // use the Font Awesome icon if the label matches the default
  19. return I18n.t(labelKey) === defaultLabel ? null : labelKey;
  20. }
  21. const OP = {
  22. NONE: 0,
  23. REMOVED: 1,
  24. ADDED: 2
  25. };
  26. const FOUR_SPACES_INDENT = '4-spaces-indent';
  27. const _createCallbacks = [];
  28. const isInside = (text, regex) => {
  29. const matches = text.match(regex);
  30. return matches && (matches.length % 2);
  31. };
  32. class Toolbar {
  33. constructor(site) {
  34. this.shortcuts = {};
  35. this.groups = [
  36. {group: 'fontStyles', buttons: []},
  37. {group: 'insertions', buttons: []},
  38. {group: 'extras', buttons: []}
  39. ];
  40. this.addButton({
  41. trimLeading: true,
  42. id: 'bold',
  43. group: 'fontStyles',
  44. icon: 'bold',
  45. label: getButtonLabel('wizard_composer.bold_label', 'B'),
  46. shortcut: 'B',
  47. perform: e => e.applySurround('**', '**', 'bold_text')
  48. });
  49. this.addButton({
  50. trimLeading: true,
  51. id: 'italic',
  52. group: 'fontStyles',
  53. icon: 'italic',
  54. label: getButtonLabel('wizard_composer.italic_label', 'I'),
  55. shortcut: 'I',
  56. perform: e => e.applySurround('_', '_', 'italic_text')
  57. });
  58. this.addButton({id: 'link', group: 'insertions', shortcut: 'K', action: 'showLinkModal'});
  59. this.addButton({
  60. id: 'quote',
  61. group: 'insertions',
  62. icon: 'quote-right',
  63. shortcut: 'Shift+9',
  64. perform: e => e.applyList(
  65. '> ',
  66. 'blockquote_text',
  67. { applyEmptyLines: true, multiline: true }
  68. )
  69. });
  70. this.addButton({id: 'code', group: 'insertions', shortcut: 'Shift+C', action: 'formatCode'});
  71. this.addButton({
  72. id: 'bullet',
  73. group: 'extras',
  74. icon: 'list-ul',
  75. shortcut: 'Shift+8',
  76. title: 'wizard_composer.ulist_title',
  77. perform: e => e.applyList('* ', 'list_item')
  78. });
  79. this.addButton({
  80. id: 'list',
  81. group: 'extras',
  82. icon: 'list-ol',
  83. shortcut: 'Shift+7',
  84. title: 'wizard_composer.olist_title',
  85. perform: e => e.applyList(i => !i ? "1. " : `${parseInt(i) + 1}. `, 'list_item')
  86. });
  87. if (Wizard.SiteSettings.support_mixed_text_direction) {
  88. this.addButton({
  89. id: 'toggle-direction',
  90. group: 'extras',
  91. icon: 'exchange',
  92. shortcut: 'Shift+6',
  93. title: 'wizard_composer.toggle_direction',
  94. perform: e => e.toggleDirection(),
  95. });
  96. }
  97. this.groups[this.groups.length-1].lastGroup = true;
  98. }
  99. addButton(button) {
  100. const g = this.groups.findBy('group', button.group);
  101. if (!g) {
  102. throw `Couldn't find toolbar group ${button.group}`;
  103. }
  104. const createdButton = {
  105. id: button.id,
  106. className: button.className || button.id,
  107. label: button.label,
  108. icon: button.label ? null : button.icon || button.id,
  109. action: button.action || 'toolbarButton',
  110. perform: button.perform || function() { },
  111. trimLeading: button.trimLeading,
  112. popupMenu: button.popupMenu || false
  113. };
  114. if (button.sendAction) {
  115. createdButton.sendAction = button.sendAction;
  116. }
  117. const title = I18n.t(button.title || `wizard_composer.${button.id}_title`);
  118. if (button.shortcut) {
  119. const mac = /Mac|iPod|iPhone|iPad/.test(navigator.platform);
  120. const mod = mac ? 'Meta' : 'Ctrl';
  121. var shortcutTitle = `${mod}+${button.shortcut}`;
  122. // Mac users are used to glyphs for shortcut keys
  123. if (mac) {
  124. shortcutTitle = shortcutTitle
  125. .replace('Shift', "\u21E7")
  126. .replace('Meta', "\u2318")
  127. .replace('Alt', "\u2325")
  128. .replace(/\+/g, '');
  129. } else {
  130. shortcutTitle = shortcutTitle
  131. .replace('Shift', I18n.t('shortcut_modifier_key.shift'))
  132. .replace('Ctrl', I18n.t('shortcut_modifier_key.ctrl'))
  133. .replace('Alt', I18n.t('shortcut_modifier_key.alt'));
  134. }
  135. createdButton.title = `${title} (${shortcutTitle})`;
  136. this.shortcuts[`${mod}+${button.shortcut}`.toLowerCase()] = createdButton;
  137. } else {
  138. createdButton.title = title;
  139. }
  140. if (button.unshift) {
  141. g.buttons.unshift(createdButton);
  142. } else {
  143. g.buttons.push(createdButton);
  144. }
  145. }
  146. }
  147. export default Ember.Component.extend({
  148. classNames: ['d-editor'],
  149. ready: false,
  150. insertLinkHidden: true,
  151. linkUrl: '',
  152. linkText: '',
  153. lastSel: null,
  154. _mouseTrap: null,
  155. showPreview: false,
  156. @computed('placeholder')
  157. placeholderTranslated(placeholder) {
  158. if (placeholder) return I18n.t(placeholder);
  159. return null;
  160. },
  161. _readyNow() {
  162. this.set('ready', true);
  163. if (this.get('autofocus')) {
  164. this.$('textarea').focus();
  165. }
  166. },
  167. init() {
  168. this._super();
  169. this.register = getRegister(this);
  170. },
  171. didInsertElement() {
  172. this._super();
  173. Ember.run.scheduleOnce('afterRender', this, this._readyNow);
  174. const mouseTrap = Mousetrap(this.$('.d-editor-input')[0]);
  175. const shortcuts = this.get('toolbar.shortcuts');
  176. // for some reason I am having trouble bubbling this so hack it in
  177. mouseTrap.bind(['ctrl+alt+f'], (event) =>{
  178. this.appEvents.trigger('header:keyboard-trigger', {type: 'search', event});
  179. return true;
  180. });
  181. Object.keys(shortcuts).forEach(sc => {
  182. const button = shortcuts[sc];
  183. mouseTrap.bind(sc, () => {
  184. this.send(button.action, button);
  185. return false;
  186. });
  187. });
  188. // disable clicking on links in the preview
  189. this.$('.d-editor-preview').on('click.preview', e => {
  190. if ($(e.target).is("a")) {
  191. e.preventDefault();
  192. return false;
  193. }
  194. });
  195. if (this.get('composerEvents')) {
  196. this.appEvents.on('composer:insert-block', text => this._addBlock(this._getSelected(), text));
  197. this.appEvents.on('composer:insert-text', (text, options) => this._addText(this._getSelected(), text, options));
  198. this.appEvents.on('composer:replace-text', (oldVal, newVal) => this._replaceText(oldVal, newVal));
  199. }
  200. this._mouseTrap = mouseTrap;
  201. },
  202. @on('willDestroyElement')
  203. _shutDown() {
  204. if (this.get('composerEvents')) {
  205. this.appEvents.off('composer:insert-block');
  206. this.appEvents.off('composer:insert-text');
  207. this.appEvents.off('composer:replace-text');
  208. }
  209. const mouseTrap = this._mouseTrap;
  210. Object.keys(this.get('toolbar.shortcuts')).forEach(sc => mouseTrap.unbind(sc));
  211. mouseTrap.unbind('ctrl+/','command+/');
  212. this.$('.d-editor-preview').off('click.preview');
  213. },
  214. @computed
  215. toolbar() {
  216. const toolbar = new Toolbar(this.site);
  217. _createCallbacks.forEach(cb => cb(toolbar));
  218. this.sendAction('extraButtons', toolbar);
  219. return toolbar;
  220. },
  221. _updatePreview() {
  222. if (this._state !== "inDOM") { return; }
  223. const value = this.get('value');
  224. const markdownOptions = this.get('markdownOptions') || {};
  225. cookAsync(value, markdownOptions).then(cooked => {
  226. if (this.get('isDestroyed')) { return; }
  227. this.set('preview', cooked);
  228. Ember.run.scheduleOnce('afterRender', () => {
  229. if (this._state !== "inDOM") { return; }
  230. const $preview = this.$('.d-editor-preview');
  231. if ($preview.length === 0) return;
  232. this.sendAction('previewUpdated', $preview);
  233. });
  234. });
  235. },
  236. @observes('ready', 'value')
  237. _watchForChanges() {
  238. if (!this.get('ready')) { return; }
  239. // Debouncing in test mode is complicated
  240. if (Ember.testing) {
  241. this._updatePreview();
  242. } else {
  243. Ember.run.debounce(this, this._updatePreview, 30);
  244. }
  245. },
  246. _getSelected(trimLeading, opts) {
  247. if (!this.get('ready')) { return; }
  248. const textarea = this.$('textarea.d-editor-input')[0];
  249. const value = textarea.value;
  250. let start = textarea.selectionStart;
  251. let end = textarea.selectionEnd;
  252. // trim trailing spaces cause **test ** would be invalid
  253. while (end > start && /\s/.test(value.charAt(end-1))) {
  254. end--;
  255. }
  256. if (trimLeading) {
  257. // trim leading spaces cause ** test** would be invalid
  258. while(end > start && /\s/.test(value.charAt(start))) {
  259. start++;
  260. }
  261. }
  262. const selVal = value.substring(start, end);
  263. const pre = value.slice(0, start);
  264. const post = value.slice(end);
  265. if (opts && opts.lineVal) {
  266. const lineVal = value.split("\n")[value.substr(0, textarea.selectionStart).split("\n").length - 1];
  267. return { start, end, value: selVal, pre, post, lineVal };
  268. } else {
  269. return { start, end, value: selVal, pre, post };
  270. }
  271. },
  272. _selectText(from, length) {
  273. Ember.run.scheduleOnce('afterRender', () => {
  274. const $textarea = this.$('textarea.d-editor-input');
  275. const textarea = $textarea[0];
  276. const oldScrollPos = $textarea.scrollTop();
  277. if (!!navigator.platform && /iPad|iPhone|iPod/.test(navigator.platform)) {
  278. $textarea.focus();
  279. }
  280. textarea.selectionStart = from;
  281. textarea.selectionEnd = textarea.selectionStart + length;
  282. $textarea.scrollTop(oldScrollPos);
  283. });
  284. },
  285. // perform the same operation over many lines of text
  286. _getMultilineContents(lines, head, hval, hlen, tail, tlen, opts) {
  287. let operation = OP.NONE;
  288. const applyEmptyLines = opts && opts.applyEmptyLines;
  289. return lines.map(l => {
  290. if (!applyEmptyLines && l.length === 0) {
  291. return l;
  292. }
  293. if (operation !== OP.ADDED &&
  294. (l.slice(0, hlen) === hval && tlen === 0 ||
  295. (tail.length && l.slice(-tlen) === tail))) {
  296. operation = OP.REMOVED;
  297. if (tlen === 0) {
  298. const result = l.slice(hlen);
  299. [hval, hlen] = getHead(head, hval);
  300. return result;
  301. } else if (l.slice(-tlen) === tail) {
  302. const result = l.slice(hlen, -tlen);
  303. [hval, hlen] = getHead(head, hval);
  304. return result;
  305. }
  306. } else if (operation === OP.NONE) {
  307. operation = OP.ADDED;
  308. } else if (operation === OP.REMOVED) {
  309. return l;
  310. }
  311. const result = `${hval}${l}${tail}`;
  312. [hval, hlen] = getHead(head, hval);
  313. return result;
  314. }).join("\n");
  315. },
  316. _applySurround(sel, head, tail, exampleKey, opts) {
  317. const pre = sel.pre;
  318. const post = sel.post;
  319. const tlen = tail.length;
  320. if (sel.start === sel.end) {
  321. if (tlen === 0) { return; }
  322. const [hval, hlen] = getHead(head);
  323. const example = I18n.t(`wizard_composer.${exampleKey}`);
  324. this.set('value', `${pre}${hval}${example}${tail}${post}`);
  325. this._selectText(pre.length + hlen, example.length);
  326. } else if (opts && !opts.multiline) {
  327. const [hval, hlen] = getHead(head);
  328. if (pre.slice(-hlen) === hval && post.slice(0, tail.length) === tail) {
  329. this.set('value', `${pre.slice(0, -hlen)}${sel.value}${post.slice(tail.length)}`);
  330. this._selectText(sel.start - hlen, sel.value.length);
  331. } else {
  332. this.set('value', `${pre}${hval}${sel.value}${tail}${post}`);
  333. this._selectText(sel.start + hlen, sel.value.length);
  334. }
  335. } else {
  336. const lines = sel.value.split("\n");
  337. let [hval, hlen] = getHead(head);
  338. if (lines.length === 1 && pre.slice(-tlen) === tail && post.slice(0, hlen) === hval) {
  339. this.set('value', `${pre.slice(0, -hlen)}${sel.value}${post.slice(tlen)}`);
  340. this._selectText(sel.start - hlen, sel.value.length);
  341. } else {
  342. const contents = this._getMultilineContents(
  343. lines,
  344. head,
  345. hval,
  346. hlen,
  347. tail,
  348. tlen,
  349. opts
  350. );
  351. this.set('value', `${pre}${contents}${post}`);
  352. if (lines.length === 1 && tlen > 0) {
  353. this._selectText(sel.start + hlen, sel.value.length);
  354. } else {
  355. this._selectText(sel.start, contents.length);
  356. }
  357. }
  358. }
  359. },
  360. _applyList(sel, head, exampleKey, opts) {
  361. if (sel.value.indexOf("\n") !== -1) {
  362. this._applySurround(sel, head, '', exampleKey, opts);
  363. } else {
  364. const [hval, hlen] = getHead(head);
  365. if (sel.start === sel.end) {
  366. sel.value = I18n.t(`wizard_composer.${exampleKey}`);
  367. }
  368. const trimmedPre = sel.pre.trim();
  369. const number = (sel.value.indexOf(hval) === 0) ? sel.value.slice(hlen) : `${hval}${sel.value}`;
  370. const preLines = trimmedPre.length ? `${trimmedPre}\n\n` : "";
  371. const trimmedPost = sel.post.trim();
  372. const post = trimmedPost.length ? `\n\n${trimmedPost}` : trimmedPost;
  373. this.set('value', `${preLines}${number}${post}`);
  374. this._selectText(preLines.length, number.length);
  375. }
  376. },
  377. _replaceText(oldVal, newVal) {
  378. const val = this.get('value');
  379. const needleStart = val.indexOf(oldVal);
  380. if (needleStart === -1) {
  381. // Nothing to replace.
  382. return;
  383. }
  384. const textarea = this.$('textarea.d-editor-input')[0];
  385. // Determine post-replace selection.
  386. const newSelection = determinePostReplaceSelection({
  387. selection: { start: textarea.selectionStart, end: textarea.selectionEnd },
  388. needle: { start: needleStart, end: needleStart + oldVal.length },
  389. replacement: { start: needleStart, end: needleStart + newVal.length }
  390. });
  391. // Replace value (side effect: cursor at the end).
  392. this.set('value', val.replace(oldVal, newVal));
  393. // Restore cursor.
  394. this._selectText(newSelection.start, newSelection.end - newSelection.start);
  395. },
  396. _addBlock(sel, text) {
  397. text = (text || '').trim();
  398. if (text.length === 0) {
  399. return;
  400. }
  401. let pre = sel.pre;
  402. let post = sel.value + sel.post;
  403. if (pre.length > 0) {
  404. pre = pre.replace(/\n*$/, "\n\n");
  405. }
  406. if (post.length > 0) {
  407. post = post.replace(/^\n*/, "\n\n");
  408. } else {
  409. post = "\n";
  410. }
  411. const value = pre + text + post;
  412. const $textarea = this.$('textarea.d-editor-input');
  413. this.set('value', value);
  414. $textarea.val(value);
  415. $textarea.prop("selectionStart", (pre+text).length + 2);
  416. $textarea.prop("selectionEnd", (pre+text).length + 2);
  417. Ember.run.scheduleOnce("afterRender", () => $textarea.focus());
  418. },
  419. _addText(sel, text, options) {
  420. const $textarea = this.$('textarea.d-editor-input');
  421. if (options && options.ensureSpace) {
  422. if ((sel.pre + '').length > 0) {
  423. if (!sel.pre.match(/\s$/)) {
  424. text = ' ' + text;
  425. }
  426. }
  427. if ((sel.post + '').length > 0) {
  428. if (!sel.post.match(/^\s/)) {
  429. text = text + ' ';
  430. }
  431. }
  432. }
  433. const insert = `${sel.pre}${text}`;
  434. const value = `${insert}${sel.post}`;
  435. this.set('value', value);
  436. $textarea.val(value);
  437. $textarea.prop("selectionStart", insert.length);
  438. $textarea.prop("selectionEnd", insert.length);
  439. Ember.run.scheduleOnce("afterRender", () => $textarea.focus());
  440. },
  441. _extractTable(text) {
  442. if (text.endsWith("\n")) {
  443. text = text.substring(0, text.length - 1);
  444. }
  445. let rows = text.split("\n");
  446. if (rows.length > 1) {
  447. const columns = rows.map(r => r.split("\t").length);
  448. const isTable = columns.reduce((a, b) => a && columns[0] === b && b > 1) &&
  449. !(columns[0] === 2 && rows[0].split("\t")[0].match(/^•$|^\d+.$/)); // to skip tab delimited lists
  450. if (isTable) {
  451. const splitterRow = [...Array(columns[0])].map(() => "---").join("\t");
  452. rows.splice(1, 0, splitterRow);
  453. return "|" + rows.map(r => r.split("\t").join("|")).join("|\n|") + "|\n";
  454. }
  455. }
  456. return null;
  457. },
  458. _toggleDirection() {
  459. const $textArea = $(".d-editor-input");
  460. let currentDir = $textArea.attr('dir') ? $textArea.attr('dir') : siteDir(),
  461. newDir = currentDir === 'ltr' ? 'rtl' : 'ltr';
  462. $textArea.attr('dir', newDir).focus();
  463. },
  464. paste(e) {
  465. if (!$(".d-editor-input").is(":focus")) {
  466. return;
  467. }
  468. const isComposer = $("#reply-control .d-editor-input").is(":focus");
  469. let { clipboard, canPasteHtml } = clipboardData(e, isComposer);
  470. let plainText = clipboard.getData("text/plain");
  471. let html = clipboard.getData("text/html");
  472. let handled = false;
  473. if (plainText) {
  474. plainText = plainText.trim().replace(/\r/g,"");
  475. const table = this._extractTable(plainText);
  476. if (table) {
  477. this.appEvents.trigger('composer:insert-text', table);
  478. handled = true;
  479. }
  480. }
  481. const { pre, lineVal } = this._getSelected(null, {lineVal: true});
  482. const isInlinePasting = pre.match(/[^\n]$/);
  483. if (canPasteHtml && plainText) {
  484. if (isInlinePasting) {
  485. canPasteHtml = !(lineVal.match(/^```/) || isInside(pre, /`/g) || lineVal.match(/^ /));
  486. } else {
  487. canPasteHtml = !isInside(pre, /(^|\n)```/g);
  488. }
  489. }
  490. if (canPasteHtml && !handled) {
  491. let markdown = toMarkdown(html);
  492. if (!plainText || plainText.length < markdown.length) {
  493. if(isInlinePasting) {
  494. markdown = markdown.replace(/^#+/, "").trim();
  495. markdown = pre.match(/\S$/) ? ` ${markdown}` : markdown;
  496. }
  497. this.appEvents.trigger('composer:insert-text', markdown);
  498. handled = true;
  499. }
  500. }
  501. if (handled) {
  502. e.preventDefault();
  503. }
  504. },
  505. keyPress(e) {
  506. if (e.keyCode === 13) {
  507. const selected = this._getSelected();
  508. this._addText(selected, '\n');
  509. return false;
  510. }
  511. },
  512. actions: {
  513. toolbarButton(button) {
  514. const selected = this._getSelected(button.trimLeading);
  515. const toolbarEvent = {
  516. selected,
  517. selectText: (from, length) => this._selectText(from, length),
  518. applySurround: (head, tail, exampleKey, opts) => this._applySurround(selected, head, tail, exampleKey, opts),
  519. applyList: (head, exampleKey, opts) => this._applyList(selected, head, exampleKey, opts),
  520. addText: text => this._addText(selected, text),
  521. replaceText: text => this._addText({pre: '', post: ''}, text),
  522. getText: () => this.get('value'),
  523. toggleDirection: () => this._toggleDirection(),
  524. };
  525. if (button.sendAction) {
  526. return this.sendAction(button.sendAction, toolbarEvent);
  527. } else {
  528. button.perform(toolbarEvent);
  529. }
  530. },
  531. showLinkModal() {
  532. this._lastSel = this._getSelected();
  533. if (this._lastSel) {
  534. this.set("linkText", this._lastSel.value.trim());
  535. }
  536. this.set('insertLinkHidden', false);
  537. },
  538. formatCode() {
  539. const sel = this._getSelected('', { lineVal: true });
  540. const selValue = sel.value;
  541. const hasNewLine = selValue.indexOf("\n") !== -1;
  542. const isBlankLine = sel.lineVal.trim().length === 0;
  543. const isFourSpacesIndent = this.siteSettings.code_formatting_style === FOUR_SPACES_INDENT;
  544. if (!hasNewLine) {
  545. if (selValue.length === 0 && isBlankLine) {
  546. if (isFourSpacesIndent) {
  547. const example = I18n.t(`wizard_composer.code_text`);
  548. this.set('value', `${sel.pre} ${example}${sel.post}`);
  549. return this._selectText(sel.pre.length + 4, example.length);
  550. } else {
  551. return this._applySurround(sel, "```\n", "\n```", 'paste_code_text');
  552. }
  553. } else {
  554. return this._applySurround(sel, '`', '`', 'code_title');
  555. }
  556. } else {
  557. if (isFourSpacesIndent) {
  558. return this._applySurround(sel, ' ', '', 'code_text');
  559. } else {
  560. const preNewline = (sel.pre[-1] !== "\n" && sel.pre !== "") ? "\n" : "";
  561. const postNewline = sel.post[0] !== "\n" ? "\n" : "";
  562. return this._addText(sel, `${preNewline}\`\`\`\n${sel.value}\n\`\`\`${postNewline}`);
  563. }
  564. }
  565. },
  566. insertLink() {
  567. const origLink = this.get('linkUrl');
  568. const linkUrl = (origLink.indexOf('://') === -1) ? `http://${origLink}` : origLink;
  569. const sel = this._lastSel;
  570. if (Ember.isEmpty(linkUrl)) { return; }
  571. const linkText = this.get('linkText') || '';
  572. if (linkText.length) {
  573. this._addText(sel, `[${linkText}](${linkUrl})`);
  574. } else {
  575. if (sel.value) {
  576. this._addText(sel, `[${sel.value}](${linkUrl})`);
  577. } else {
  578. this._addText(sel, `[${origLink}](${linkUrl})`);
  579. this._selectText(sel.start + 1, origLink.length);
  580. }
  581. }
  582. this.set('linkUrl', '');
  583. this.set('linkText', '');
  584. }
  585. }
  586. });