Pen Settings

HTML

CSS

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Behavior

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                <playlist-editor></playlist-editor>
<script src="https://code.jquery.com/jquery-2.2.4.js"></script>
<script src="https://unpkg.com/jquerypp@2/dist/global/jquerypp.js"></script>
<script>
window.googleApiLoadedPromise = new Promise(function(resolve) {
  window.googleScriptLoaded = function() {
    gapi.load("client:auth2", function() {
      gapi.client.init({
        apiKey: 'AIzaSyBcnGGOryOnmjUC09T78VCFEqRQRgvPnAc',
        clientId: '764983721035-85cbj35n0kmkmrba10f4jtte8fhpst84.apps.googleusercontent.com',
        discoveryDocs: [ "https://www.googleapis.com/discovery/v1/apis/youtube/v3/rest" ],
        scope: "https://www.googleapis.com/auth/youtube"
      }).then(resolve);
    });
  }
});
</script>
<script async defer src="https://apis.google.com/js/api.js"
    onload="this.onload=function(){}; googleScriptLoaded();"
    onreadystatechange="if (this.readyState === 'complete') this.onload();">
</script>
              
            
!

CSS

              
                @import url('https://fonts.googleapis.com/css?family=Droid+Sans');

body {
  font-family: 'Droid Sans', arial;
  font-size: 16px;
  font-weight: bold;
  background: #f5f5f5;
  color: #333;
}

button, input {
  font-family: 'Droid Sans', arial;
}

input {
  font-size: 14px;
  width: 98%;
  margin-top: 10px;
  padding: 3px;
}

.loading {
  font-size: 14px;
  color: green;
  margin-top: 20px;
}

.source {
  float: left;
  width: 48%;
  padding: 0;
  list-style-type: none;
  border: solid 1px #ddd;
  background-color: #fff;
}

.source li {
  border-bottom: 1px solid #ddd;
  cursor: move;
}

.source li:last-child {
  border-bottom: 0px;
}

.source li:hover {
  box-shadow: -1px 1px 1px rgba(0, 0, 0, .5);
  background-color: #dff0d8;
}

.source li img, .new-playlist li img {
  float: left;
  margin-right: 8px;
  cursor: move;
}

.new-playlist {
  text-align: center;
  float: right;
  width: 48%;
}

.new-playlist ul {
  padding: 0;
  background-color: #fff;
}

.new-playlist li {
  border: dashed 1px #a3a3a3;
  border-width: 1px 1px 0 1px;
}

.new-playlist li:hover {
  background-color: #f5f5f5;
}

.new-playlist li:first-child {
  border-width: 1px 1px 0 1px;
}

.new-playlist li:last-child {
  border-width: 1px;
}

.new-playlist li.btn-li {
  background-color: #f5f5f5;
  border-width: 1px 0 0px 0;
}

.new-playlist button {
  margin: 10px 0;
}

.source li, .new-playlist li {
  font-size: 12px;
  font-weight: normal;
  padding: 6px;
  list-style: none;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
}

.placeholder, .ghost {
  background-color: #ccdcc6;
}

.content {
  color: #888;
  font-size: 12px;
  padding: 18px 0;
  border: 1px dashed #a3a3a3;
}

playlist-editor {
  display:block;
}


              
            
!

JS

              
                import {
  addJQueryEvents,
  Control,
  domData,
  domEvents,
  ObservableArray,
  StacheElement,
  type,
  viewCallbacks
} from "//unpkg.com/can@pre/core.mjs";

addJQueryEvents(jQuery);

const Sortable = Control.extend({
  "{element} dropinit": function() {
    this.droppedOn = false;
  },
  "{element} dropmove": function(el, ev, drop, drag) {
    this.fireEventForDropPosition(ev, drop, drag, "sortableplaceholderat");
  },
  "{element} dropon": function(el, ev, drop, drag) {
    this.droppedOn = true;
    this.fireEventForDropPosition(ev, drop, drag, "sortableinsertat");
  },
  "{element} dropend": function(el, ev, drop, drag) {
    if (!this.droppedOn) {
      drag.revert();
    }
  },
  fireEventForDropPosition(ev, drop, drag, eventName) {
    const dragData = domData.get(drag.element[0], "dragData");
    const sortables = $(this.element).children();

    for (var i = 0; i < sortables.length; i++) {
      //check if cursor is past 1/2 way
      const sortable = $(sortables[i]);
      if (
        ev.pageY < Math.floor(sortable.offset().top + sortable.height() / 2)
      ) {
        // index at which it needs to be inserted before
        domEvents.dispatch(this.element, {
          type: eventName,
          index: i,
          dragData: dragData
        });
        return;
      }
    }
    if (!sortables.length) {
      domEvents.dispatch(this.element, {
        type: eventName,
        index: 0,
        dragData: dragData
      });
    } else {
      domEvents.dispatch(this.element, {
        type: eventName,
        index: i,
        dragData: dragData
      });
    }
  }
});

viewCallbacks.attr("sortable", el => {
  new Sortable(el);
});

class PlaylistEditor extends StacheElement {
  static view = `
    {{# if(this.googleApiLoadedPromise.isPending) }}
        <div>Loading Google API…</div>
    {{ else }}
      {{# if(this.signedIn) }}
        Welcome {{ this.givenName }}! <button on:click="this.googleAuth.signOut()">Sign Out</button>
      {{ else }}
        <button on:click="this.googleAuth.signIn()">Sign In</button>
      {{/ if }}

      <div>
        <input value:bind="this.searchQuery" placeholder="Search for videos">
      </div>

      {{# if(this.searchResultsPromise.isPending) }}
        <div class="loading">Loading videos…</div>
      {{/ if }}

      {{# if(this.searchResultsPromise.isResolved) }}
        <ul class="source">
          {{# for(searchResult of this.searchResultsPromise.value) }}
            <li 
              on:draginit="this.videoDrag(scope.arguments[1])"
              {{ domData("dragData", searchResult) }}
            >
              <a draggable="false" href="https://www.youtube.com/watch?v={{ searchResult.id.videoId }}" target='_blank'>
                <img draggable="false" src="{{ searchResult.snippet.thumbnails.default.url }}" width="50px">
              </a>
              {{ searchResult.snippet.title }}
            </li>
          {{/ for }}
        </ul>

        {{# if(this.searchResultsPromise.value.length) }}
          <div class="new-playlist">
            <ul
              sortable
              on:sortableplaceholderat="this.addDropPlaceholder(scope.event.index, scope.event.dragData)"
              on:sortableinsertat="this.addVideo(scope.event.index, scope.event.dragData)"
              on:dropout="this.clearDropPlaceholder()"
            >
              {{# for(videoWithDropPlaceholder of this.videosWithDropPlaceholder) }}
                <li class="{{# if(videoWithDropPlaceholder.isPlaceholder) }}placeholder{{/ if }}">
                  <a href="https://www.youtube.com/watch?v={{ videoWithDropPlaceholder.video.id.videoId }}" target='_blank'>
                    <img src="{{ videoWithDropPlaceholder.video.snippet.thumbnails.default.url }}" width="50px">
                  </a>
                  {{ videoWithDropPlaceholder.video.snippet.title }}
                </li>
              {{else}}
                <div class="content">Drag video here</div>
              {{/ for }}
            </ul>
            {{# if(this.playlistVideos.length) }}
              <button 
                on:click="this.createPlaylist()"
                disabled:from="this.createPlaylistPromise.isPending()"
              >
                Create Playlist
              </button>
            {{/ if }}
          </div>
        {{/ if }}

      {{/ if }}
    {{/ if }}
  `;

  static props = {
    signedIn: Boolean,

    googleApiLoadedPromise: {
      get default() {
        return googleApiLoadedPromise;
      }
    },

    googleAuth: {
      async(resolve) {
        this.googleApiLoadedPromise.then(() => {
          resolve(gapi.auth2.getAuthInstance());
        });
      }
    },

    searchQuery: "",

    dropPlaceholderData: type.Any,

    playlistVideos: {
      get default() {
        return new ObservableArray();
      }
    },

    createPlaylistPromise: type.Any,

    get givenName() {
      return (
        this.googleAuth &&
        this.googleAuth.currentUser
          .get()
          .getBasicProfile()
          .getGivenName()
      );
    },

    get searchResultsPromise() {
      if (this.searchQuery.length > 2) {
        return gapi.client.youtube.search
          .list({
            q: this.searchQuery,
            part: "snippet",
            type: "video"
          })
          .then(response => {
            console.info("Search results:", response.result.items);
            return response.result.items;
          });
      }
    },

    get videosWithDropPlaceholder() {
      const copy = this.playlistVideos.map(video => {
        return {
          video: video,
          isPlaceholder: false
        };
      });
      if (this.dropPlaceholderData) {
        copy.splice(this.dropPlaceholderData.index, 0, {
          video: this.dropPlaceholderData.video,
          isPlaceholder: true
        });
      }
      return copy;
    }
  };

  connected() {
    this.listenTo("googleAuth", ({ value: googleAuth }) => {
      this.signedIn = googleAuth.isSignedIn.get();
      googleAuth.isSignedIn.listen(isSignedIn => {
        this.signedIn = isSignedIn;
      });
    });

    this.listenTo("createPlaylistPromise", ({ value: promise }) => {
      if (promise) {
        promise.then(() => {
          this.playlistVideos = [];
          this.createPlaylistPromise = null;
        });
      }
    });
  }

  videoDrag(drag) {
    drag.ghost().addClass("ghost");
  }

  getDragData(drag) {
    return domData.get(drag.element[0], "dragData");
  }

  addDropPlaceholder(index, video) {
    this.dropPlaceholderData = {
      index: index,
      video: video
    };
  }

  clearDropPlaceholder() {
    this.dropPlaceholderData = null;
  }

  addVideo(index, video) {
    this.dropPlaceholderData = null;
    if (index >= this.playlistVideos.length) {
      this.playlistVideos.push(video);
    } else {
      this.playlistVideos.splice(index, 0, video);
    }
  }

  createPlaylist() {
    const playlistName = prompt("What would you like to name your playlist?");
    if (!playlistName) {
      return;
    }

    let playlistId;
    let lastPromise = gapi.client.youtube.playlists
      .insert({
        part: "snippet,status",
        resource: {
          snippet: {
            title: playlistName,
            description:
              "A private playlist created with the YouTube API and CanJS"
          },
          status: {
            privacyStatus: "private"
          }
        }
      })
      .then(response => {
        playlistId = response.result.id;
      });

    const playlistVideos = this.playlistVideos.slice();
    playlistVideos.forEach(video => {
      lastPromise = lastPromise.then(() => {
        return gapi.client.youtube.playlistItems
          .insert({
            part: "snippet",
            resource: {
              snippet: {
                playlistId: playlistId,
                resourceId: video.id
              }
            }
          });
      });
    });

    this.createPlaylistPromise = lastPromise;
  }
}

customElements.define("playlist-editor", PlaylistEditor);

              
            
!
999px

Console