Skip to content

Instantly share code, notes, and snippets.

@jborichevskiy
Last active January 6, 2024 21:45
Show Gist options
  • Save jborichevskiy/101f0e35d3fbbeb905ce0279f16f0b77 to your computer and use it in GitHub Desktop.
Save jborichevskiy/101f0e35d3fbbeb905ce0279f16f0b77 to your computer and use it in GitHub Desktop.
image

There are three components:

  1. import simplemde
  2. add a textarea
  3. add scripts to:
  • initialize simplemde,
  • save changes to localstorage every second
  • check for more recent entry based on time from other tabs
  1. import scripts
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.css"
/>
<script src="https://cdn.jsdelivr.net/simplemde/latest/simplemde.min.js"></script>
  1. textarea & wrapping column for context
<div style="display: flex; flex-direction: column; padding-top: 1.4rem">
  <div
    style="opacity: 0.5;
      margin-left: 4rem;
      max-width: 400px;
      min-width: 400px;
      width: 100%;">
    <textarea style="width: 400px; height: 600px; max-width: 400px"></textarea>
  </div>
</div>
  1. initialize simplemde, and save to / pull from localstorage (thank you gpt)
<script>
  var simplemde = new SimpleMDE({
    autofocus: true,
    spellChecker: false,
    toolbar: false,
    status: false,
  });

  let lastSavedContent = localStorage.getItem('content') || simplemde.value();
  let lastSavedTimestamp = localStorage.getItem('timestamp') || Date.now();

  // Load the latest content from localStorage
  if (lastSavedContent) {
    simplemde.value(lastSavedContent);
  }

  // Check for changes every second
  setInterval(() => {
    const currentContent = simplemde.value();
    const currentTimestamp = Date.now();

    // If the content in localStorage is fresher, use that instead
    if (currentTimestamp < lastSavedTimestamp && currentContent !== lastSavedContent) {
      simplemde.value(lastSavedContent);
    } else if (currentContent !== lastSavedContent) {
      // If the content has changed, save it to localStorage
      localStorage.setItem('content', currentContent);
      localStorage.setItem('timestamp', currentTimestamp.toString());
      lastSavedContent = currentContent;
      lastSavedTimestamp = currentTimestamp;
    }
  }, 1000);

  // Listen for changes to localStorage from other tabs
  window.addEventListener('storage', function(e) {
    if (e.key === 'content') {
      lastSavedContent = e.newValue;
      simplemde.value(lastSavedContent);
    } else if (e.key === 'timestamp') {
      lastSavedTimestamp = e.newValue;
    }
  });
  </script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment