File size: 7,741 Bytes
26ab438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1378e63
26ab438
 
 
 
1378e63
 
 
26ab438
1378e63
 
26ab438
 
 
 
 
1378e63
26ab438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1378e63
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26ab438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1378e63
 
26ab438
1378e63
 
 
 
 
26ab438
 
1378e63
 
 
 
 
 
 
 
 
 
 
4f397cc
1378e63
 
 
 
4f397cc
1378e63
 
 
 
 
 
be3ad36
 
 
 
1378e63
defcdae
 
26ab438
 
defcdae
 
26ab438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1378e63
26ab438
1378e63
26ab438
1378e63
26ab438
 
1378e63
 
26ab438
 
1378e63
 
26ab438
 
1378e63
26ab438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1378e63
26ab438
1378e63
26ab438
 
 
 
 
 
 
 
 
 
 
 
 
1378e63
26ab438
 
 
 
1378e63
26ab438
1378e63
26ab438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1378e63
26ab438
 
1378e63
 
 
 
 
 
 
 
 
26ab438
1378e63
 
 
 
26ab438
1378e63
26ab438
1378e63
 
26ab438
1378e63
26ab438
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { utils } from "./utils.js";

function getCurrentLineString(element) {
  const selection = window.getSelection();
  const range = selection.getRangeAt(0);
  const node = range.startContainer;
  const offset = range.startOffset;

  // If the selection is inside a text node
  if (node.nodeType === Node.TEXT_NODE) {
    const text = node.textContent;
    const lineStart = text.lastIndexOf('\n', offset) + 1;
    const lineEnd = text.indexOf('\n', offset);
    const line = lineEnd === -1 ? text.slice(lineStart) : text.slice(lineStart, lineEnd);
    return line;
  }

  // If the selection is inside an element node
  const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
  let currentNode, currentLine = '';

  while (currentNode = walker.nextNode()) {
    const text = currentNode.textContent;
    const lines = text.split('\n');

    for (let i = 0; i < lines.length; i++) {
      if (range.intersectsNode(currentNode)) {
        currentLine = lines[i];
        break;
      }
    }

    if (currentLine !== '') {
      break;
    }
  }

  return currentLine;
}






function createLastButton(cmd, name = cmd, onclick = console.log,style={}) {
  const button = document.createElement('button');

  button.className = 'toastui-editor-toolbar-icons last';
  button.style.backgroundImage = 'none';
  button.style.margin = style.margin || '0';
  button.style.fontSize = style.fontSize || 'x-large';
  button.innerHTML = `${name}`;
  button.addEventListener('click', () => {
    onclick();
    editor.exec(cmd || '');
  });

  return button;
}

let editorContainer = document.querySelector('#notebin_editor');
window.tuieditor = window.editor = new toastui.Editor({
  el: document.querySelector('#notebin_editor'),
  previewStyle: 'tab',
  height: window.innerHeight * 0.8 + 'px',
  initialValue: '\n\n\n\n\n\n',
  customHTMLSanitizer: html => html,
  toolbarItems: [
    [{
      el: createLastButton('undo', '⤺'),
      command: 'undo',
      tooltip: 'Undo'
    },
    {
      el: createLastButton('redo', '⤻'),
      command: 'redo',
      tooltip: 'Redo'
    },
    {
      el: createLastButton('', 'wrap', () => {
        const element = document.querySelector('.ProseMirror');
        if (element.style.overflowX === 'auto' && element.style.whiteSpace === 'nowrap') {
          element.style.overflowX = '';
          element.style.whiteSpace = '';
        } else {
          element.style.overflowX = 'auto';
          element.style.whiteSpace = 'nowrap';
        }

      },
      {
        fontSize: 'medium'
      }
    ),
      
      command: 'wrap',
      tooltip: 'wrap'
    }
    ],
    ['heading'],
    //[ 'bold', 'italic', 'strike'],
    //   ['hr', 'quote'],
    //   ['ul', 'ol', 'task', 'indent', 'outdent'],
    //    ['table', 'image', 'link'],
    ['image'],
    ['code', 'codeblock'],

  ],
});

setTimeout(() => {

  // tuieditor.focus();
  tuieditor.moveCursorToStart(true);

  window.tuieditor.mdEditor.el.addEventListener('focus', (event) => {
    // Log the event and the pasted data
    console.log('focus event triggered:', event);
    syncNote();
  });


  window.tuieditor.mdEditor.el.addEventListener('keydown', function (event) {
    if (event.key === 'Enter' && event.ctrlKey) {
      // Your code here
      let currentLineString = getCurrentLineString(editorContainer);
      console.log('Ctrl + Enter was pressed:', currentLineString);
      let prompt = ' ';
      let selectText = window.getSelection().toString();
      utils.displayMarkdown(`${prompt} **${selectText.length >= 1 ? selectText : currentLineString}** ...`);
      utils.AIComplete(`${prompt} **${selectText.length >= 1 ? selectText : currentLineString}** `);
    }
  });

  document.body.addEventListener('keydown', event => {
    if (event.key === 'Enter' && event.ctrlKey) {
      // Your code here
      tuieditor.mdEditor.focus();

      console.log('body Ctrl + Enter was pressed:');
    }
  });

  let url_div = document.querySelector('#url_div');
  url_div.innerText = window.location.href;
  url_div.addEventListener('pointerdown', () => {
    const text = url_div.textContent;
    navigator.clipboard.writeText(text);
    utils.showToast('copyed url to clipboard');
  })


}, 1000);



//   editor.insertToolbarItem({ groupIndex: 0, itemIndex: 0 }, {
//     name: 'myItem',
//     tooltip: 'Custom Button',
//     command: 'bold',
//     text: '@',
//     className: 'toastui-editor-toolbar-icons first',
//     style: { backgroundImage: 'none' }
//   });


let editorModel = {
  value: null,
  lastChangeTime: 0,
  noteid: ''
}


// Create a new custom event
const editorchange = new CustomEvent('editorchange', {
  detail: {
    // Include any data you want to pass with the event
    message: 'Editor content has changed'
  },
  bubbles: true,
  cancelable: true
});

document.addEventListener('editorchange', () => {
  console.log('editorchange');
  editorModel.lastChangeTime = Date.now();
  syncNote();

})

let setChangeTimeoutid = 0;
document.addEventListener('keydown', () => {
  console.log('keydown');
  clearTimeout(setChangeTimeoutid);
  setChangeTimeoutid = setTimeout(() => {
    document.body.dispatchEvent(editorchange)

  }, 5000);

})

document.body.addEventListener('paste', (event) => {
  // Log the event and the pasted data
  console.log('Paste event triggered:', event);
  console.log('Pasted data:', event.clipboardData.getData('text'));
  document.body.dispatchEvent(editorchange)

});

document.body.addEventListener('pointerdown', (event) => {
  // Log the event and the pasted data
  console.log('pointerdown event triggered:', event);
  syncNote();
});





function getUrlParameter(name) {
  name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
  var regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
  var results = regex.exec(location.search);
  return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}

function setUrlParameter(paramName, paramValue) {
  const url = new URL(window.location.href);
  url.searchParams.set(paramName, paramValue);
  history.pushState({}, "", url);
}

let noteid = getUrlParameter('noteid');
console.log(noteid);



async function initEditorModel() {
  editorModel.noteid = getUrlParameter('noteid') || Date.now();
  setUrlParameter('noteid', editorModel.noteid);
  console.log('initEditorModel', editorModel);
  getNote();

}


initEditorModel();


setInterval(async () => {
  // saveNote();
}, 3000)


async function getNote() {
  let res = await fetch(`/kv/get?key=${editorModel.noteid}`);
  res = await res.json();
  console.log('getNote:', res);
  if (res) {
    res = res.value;
    editorModel.value = res.text;
    editorModel.lastChangeTime = res.lastChangeTime || 0;
    tuieditor.setMarkdown(res.text)
  }
}

async function saveNote() {
  let form = new FormData();
  form.append('key', noteid);
  form.append('value', JSON.stringify({
    text: tuieditor.getMarkdown(),
    lastChangeTime: editorModel.lastChangeTime
  }))

  await fetch('/kv/set',
    {
      method: 'post',
      body: form
    }
  )
  console.log('note saved')

}


async function syncNote() {
  try {
    let res = await fetch(`/kv/get?key=${editorModel.noteid}`);
    res = await res.json();
    console.log('getNote in syncNote:', res);
    if (res) {
      res = res.value;
      if (res.lastChangeTime > editorModel.lastChangeTime) {
        console.log(res.lastChangeTime, editorModel.lastChangeTime);
        editorModel.value = res.text;
        editorModel.lastChangeTime = res.lastChangeTime || 0;
        tuieditor.setMarkdown(res.text);

      }
      else {
        saveNote();
      }
    }

  } catch (error) {
    console.log('syncNote eroor:', error);
    saveNote();
  }

}