wizard-editor.js.es6 20 KB

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