Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rad73/f086dd1ce5d380ff6320cdca3d1b7c9e to your computer and use it in GitHub Desktop.
Save rad73/f086dd1ce5d380ff6320cdca3d1b7c9e to your computer and use it in GitHub Desktop.

Revisions

  1. @soundyogi soundyogi revised this gist Mar 21, 2018. 1 changed file with 24 additions and 5 deletions.
    29 changes: 24 additions & 5 deletions 2018_chrome_snippet_gui_import_export.js
    Original file line number Diff line number Diff line change
    @@ -1,9 +1,28 @@
    void function() { "use strict"
    /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DO NOT USE YET!!!!!!!!!!!!!!!!!!!!!
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!USE 2016 VERSION BELOW!!!!!!!!!!!!!!!!!!!!!
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! WIP DO NOT USE WIP !!!!!!!!!!!!!!!!!!!!!
    DO NOT USE THIS YET.
    USE THE 2016 VERSION BELOW PLEASE.
    WWWWWWWW WWWWWWWWIIIIIIIIIIPPPPPPPPPPPPPPPPP
    W::::::W W::::::WI::::::::IP::::::::::::::::P
    W::::::W W::::::WI::::::::IP::::::PPPPPP:::::P
    W::::::W W::::::WII::::::IIPP:::::P P:::::P
    W:::::W WWWWW W:::::W I::::I P::::P P:::::P
    W:::::W W:::::W W:::::W I::::I P::::P P:::::P
    W:::::W W:::::::W W:::::W I::::I P::::PPPPPP:::::P
    W:::::W W:::::::::W W:::::W I::::I P:::::::::::::PP
    W:::::W W:::::W:::::W W:::::W I::::I P::::PPPPPPPPP
    W:::::W W:::::W W:::::W W:::::W I::::I P::::P
    W:::::W:::::W W:::::W:::::W I::::I P::::P
    W:::::::::W W:::::::::W I::::I P::::P
    W:::::::W W:::::::W II::::::IIPP::::::PP
    W:::::W W:::::W I::::::::IP::::::::P
    W:::W W:::W I::::::::IP::::::::P
    WWW WWW IIIIIIIIIIPPPPPPPPPP
    * Manage and Import/Export Chrome Snippets (2018)
    * by: http://github.com/soundyogi
    * inspired by: https://github.com/bgrins/devtools-snippets/blob/master/import-export/chrome/devtools_import_export.js
  2. @soundyogi soundyogi revised this gist Mar 21, 2018. 1 changed file with 21 additions and 0 deletions.
    21 changes: 21 additions & 0 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,27 @@
    void function(){
    "use strict"
    /*
    222222222222222 000000000 1111111 66666666
    2:::::::::::::::22 00:::::::::00 1::::::1 6::::::6
    2::::::222222:::::2 00:::::::::::::00 1:::::::1 6::::::6
    2222222 2:::::2 0:::::::000:::::::0111:::::1 6::::::6
    2:::::2 0::::::0 0::::::0 1::::1 6::::::6
    2:::::2 0:::::0 0:::::0 1::::1 6::::::6
    2222::::2 0:::::0 0:::::0 1::::1 6::::::6
    22222::::::22 0:::::0 000 0:::::0 1::::l 6::::::::66666
    22::::::::222 0:::::0 000 0:::::0 1::::l 6::::::::::::::66
    2:::::22222 0:::::0 0:::::0 1::::l 6::::::66666:::::6
    2:::::2 0:::::0 0:::::0 1::::l 6:::::6 6:::::6
    2:::::2 0::::::0 0::::::0 1::::l 6:::::6 6:::::6
    2:::::2 2222220:::::::000:::::::0111::::::1116::::::66666::::::6
    2::::::2222222:::::2 00:::::::::::::00 1::::::::::1 66:::::::::::::66
    2::::::::::::::::::2 00:::::::::00 1::::::::::1 66:::::::::66
    22222222222222222222 000000000 111111111111 666666666
    * Manage and Import / Export snippets from chrome (2016)
    * hacked together by: http://github.com/soundyogi
    * inspired by: https://github.com/bgrins/devtools-snippets/blob/master/import-export/chrome/devtools_import_export.js
  3. @soundyogi soundyogi revised this gist Mar 8, 2018. 1 changed file with 5 additions and 1 deletion.
    6 changes: 5 additions & 1 deletion 2018_chrome_snippet_gui_import_export.js
    Original file line number Diff line number Diff line change
    @@ -1,5 +1,9 @@
    void function() { "use strict"
    /*
    /* !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! DO NOT USE YET!!!!!!!!!!!!!!!!!!!!!
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!USE 2016 VERSION BELOW!!!!!!!!!!!!!!!!!!!!!
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    * Manage and Import/Export Chrome Snippets (2018)
    * by: http://github.com/soundyogi
    * inspired by: https://github.com/bgrins/devtools-snippets/blob/master/import-export/chrome/devtools_import_export.js
  4. @soundyogi soundyogi revised this gist Mar 8, 2018. 1 changed file with 25 additions and 1 deletion.
    26 changes: 25 additions & 1 deletion 2018_chrome_snippet_gui_import_export.js
    Original file line number Diff line number Diff line change
    @@ -160,12 +160,14 @@ function createStore(rootReducer, initialState, storeEnhancer) {
    }

    function baseDispatch(action) {
    if (!action || !action.type) throw Error("cant call dispatch without action. stupid.")
    if (!action || !action.type) throw Error("cant call dispatch without action. stupid.");

    _state = _rootReducer(_state, action)

    for (var subscriberKey in _mapSubscribers)
    _mapSubscribers[subscriberKey] ? _mapSubscribers[subscriberKey]() : null;

    return true;
    }
    }
    }
    @@ -221,6 +223,28 @@ const thunk = store => next => action =>
    : next(action)


    /*
    function combineReducers(reducerObject:Object):function{}
    Combines Reducers by returning a Reducer Reducing Reducers
    */
    function combineReducers(reducerObject){

    function rootReducer(state, action){
    const newState = {}

    Object.keys(reducerObject).reduce( (newState, currentKey) => {
    if(!state) state = {}
    // if(!state[currentKey]) state[currentKey] = undefined;
    newState[currentKey] = reducerObject[currentKey](state[currentKey], action)
    return newState

    }, newState)

    return newState
    }
    return rootReducer
    }

    // Snippets 'Duck'
    //

  5. @soundyogi soundyogi revised this gist Mar 4, 2018. 1 changed file with 527 additions and 92 deletions.
    619 changes: 527 additions & 92 deletions 2018_chrome_snippet_gui_import_export.js
    Original file line number Diff line number Diff line change
    @@ -1,136 +1,571 @@
    void function(){
    "use strict"
    void function() { "use strict"
    /*
    * Manage and Import / Export snippets from chrome (2018)
    * hacked together by: http://github.com/soundyogi
    * Manage and Import/Export Chrome Snippets (2018)
    * by: http://github.com/soundyogi
    * inspired by: https://github.com/bgrins/devtools-snippets/blob/master/import-export/chrome/devtools_import_export.js
    * WORK IN PROGRESS! USE 2016 VERSION! (SCROLL DOWN)
    */

    // - Templates
    // - Test Harness
    // - Diy Redux
    // - Main
    // - Util
    // - CSS

    let_us("execute some init tests", () => {
    if(location.origin !== "chrome-devtools://devtools") throw alert("not in devtools of devtools / please inspect devtools again with: (ctrl+shift+i)")
    ok(location.origin === "chrome-devtools://devtools", 'we are in devtools of devtools, good to go')

    // Templates
    //

    function Layout({getState}){ return `
    <article>
    <header><h1>Chrome Export</h1></header>
    ${sideMenu({getState})}
    <main>
    <h2>Current snippets buffer / state / preview: </h2>
    ${getState().scriptSnippets.forEach((snippet) => {
    return `
    <li>${snippet}</li>
    `})}
    </main>
    ${outMenu({getState})}
    <footer></footer>
    </article>
    `}

    function sideMenu({getState}) { return `
    <aside>
    <nav>
    <h3>--> Input</h3>
    <ul>
    <li>
    <label> load chrome snippets: </label>
    <button id=${uuidv4()} onclick='dispatch(events.snippetsFetchRequested())'> (re)init </button>
    </li>
    <li>
    <label> on name conflicts: </label>
    <select onchange='( x => {console.log(x,event); dispatch(events.snippetsFetchRequested(event))} )()' id='rename'>
    <option value='true'>Rename Import Files</option>
    <option value="false">Overwrite Snippets</option>
    </select>
    </li>
    <li>
    <dropzone>
    <div>Click/Drop .js or .json</div>
    <input id="drop_files" type='file' multiple='true'/>
    </dropzone>
    <label>append files or replace everything?
    <select id='append'>
    <option value='true'>Append</option>
    <option value="false">Replace</option>
    </select>
    </label>
    </li>
    <li>
    import files from external sources:
    <button id="external_bgrins">load some scripts from bgrins/devtools-snippets repo</button>
    <button id="external_bahmutov">load some scripts from bahmutov/code-snippets repo</button>
    </li>
    </ul>
    </nav>
    </aside>
    `};


    function outMenu({getState}){ return `
    <out>
    <nav>
    <h3>Output --></h3>
    <ul>
    <li>
    <button id="export_snippets">export</button>
    <select id='format'>
    <option value="json">Single .json</option>
    <option value="js">Multiple .js</option>
    </select>
    </li>
    <li>
    <button id="save_snippets">Save to Chrome</button>
    </li>
    <li>
    <button id="reset_snippets">DELETE all on Chrome</button>
    </li>
    </ul>
    </nav>
    </out>
    `}


    // Test Harness
    //

    function log(...x) {
    return console.log(...x)
    }

    function test(suiteName, f) {
    log(`Test: ${suiteName}`)
    f({ok})
    }

    function ok(expr, msg) {
    expr ? log(' %c!pass:' + msg, 'color:green') : log(' %c?fail:' + msg, 'color:red')
    }

    // INIT TEST
    test('selftest', function(t) {
    t.ok(true, ' I pass')
    t.ok(false, 'I fail')
    })

    test("are we inspecting devtools?", ()=>{
    if (location.origin !== "chrome-devtools://devtools")
    console.log("not in devtools of devtools / please inspect devtools again with: (ctrl+shift+i)")
    ok(location.origin === "chrome-devtools://devtools", 'we are in devtools of devtools, good to go')
    })

    // DO IT YOURSELF REDUX

    // Naive Redux
    //
    function createStore(rootReducer, initialState, storeEnhancer) {
    const createStore = storeEnhancer
    ? storeEnhancer(_createStore)
    : _createStore
    ;

    function createEventBus()
    {

    // register subscriptions to a topic/channel (string)
    const _topics = {}

    // calls
    function emit(stringTopic, ...payload)
    {
    // call every subscriuber function for channel
    _topics[stringTopic].forEach( subscriberCallback => subscriberCallback(payload))
    }

    // registers new subscriber
    function on(stringTopic, subscriberCallback)
    {
    _topics[stringTopic] = _topics[stringTopic] || [];
    _topics[stringTopic].push(subscriberCallback)
    console.log('Added subscription for channel: '+stringTopic)
    return createStore();

    function _createStore() {
    if (!rootReducer) throw Error('rootReducer is missing')

    const _mapSubscribers = {}
    const _rootReducer = rootReducer
    const _store = {
    dispatch: baseDispatch,
    getState,
    subscribe
    }

    let _state = initialState

    return _store;

    function getState() {
    return _state
    }

    function subscribe(f) {
    _mapSubscribers[uuidv4()] = f
    }

    function baseDispatch(action) {
    if (!action || !action.type) throw Error("cant call dispatch without action. stupid.")

    _state = _rootReducer(_state, action)

    for (var subscriberKey in _mapSubscribers)
    _mapSubscribers[subscriberKey] ? _mapSubscribers[subscriberKey]() : null;
    }
    }
    }

    function applyMiddleware(...middlewares) {
    return createStore => (...args) => {
    const store = createStore(...args)
    let chain = []
    let dispatch

    const middlewareAPI = {
    getState: store.getState,
    dispatch: (...args) => dispatch(...args)
    }
    chain = middlewares.map(middleware => middleware(middlewareAPI))
    dispatch = compose(...chain)(store.dispatch)

    return {
    emit,
    on
    return {
    ...store,
    dispatch
    }
    }
    }

    // redux
    function createStore(reducer){
    const _radio = createEventBus()
    const store = {}

    store.state = {}
    store.getState = function getState(){return store.state}

    store.dispatch = function(actionObject){
    _radio.emit("ACTION", actionObject)
    // Middleware
    //
    const logger = store => next => action => {
    if(!action.type && action instanceof Function) console.log('thunk: '+action.name)
    else { console.info('event: ', action) }
    let result = next(action)
    return result
    }

    const crashReporter = store => next => action => {
    try {
    return next(action)
    } catch (err) {
    console.error('Caught an exception!', err)
    throw err
    }

    _radio.on("ACTION", function processAction(action){
    store.state = _store.reducer(_store.getState(), action)
    _radio.emit("CHANGED")
    })
    }

    const vanillaPromise = store => next => action => {
    if (typeof action.then !== 'function') {
    return next(action)
    }
    return Promise.resolve(action).then(store.dispatch)
    }

    const thunk = store => next => action =>
    typeof action === 'function'
    ? action(store.dispatch, store.getState)
    : next(action)


    // Snippets 'Duck'
    //

    store.subscribe = function addSubscriber(func){
    _radio.on("CHANGED", func)
    // Actions
    //
    const SNIPPETS_FETCH_REQUESTED = 'SNIPPETS_FETCH_REQUESTED'
    const SNIPPETS_FETCHED = 'SNIPPETS_FETCHED'

    const SNIPPET_ADDED = 'SNIPPET_ADDED'
    const SNIPPET_REMOVED = 'SNIPPET_REMOVED'

    // Action Creators / Thunk Creators
    //
    function snippetsFetchRequested(){
    return function snippetsFetchRequestedThunk(dispatch, getState){
    dispatch({type: SNIPPETS_FETCH_REQUESTED})

    InspectorFrontendHost.getPreferences(prefs=>{
    const lastScriptSnippets = prefs.scriptSnippets
    const snippets = deserialize(lastScriptSnippets)
    const lastIdentifier = prefs.scriptSnippets_lastIdentifier

    dispatch(snippetsFetched({snippets, lastIdentifier}))
    })
    }
    }

    function snippetsFetched(payload){
    return {type: SNIPPETS_FETCHED, payload}
    }

    function snippetAdded(){}

    function snippetRemoved(){}

    // TEST
    const RADIO = createEventBus()
    const actionCreators = {
    snippetsFetchRequested,
    snippetsFetched,
    }

    RADIO.on("TEST", function(pl){ console.log(pl) })
    RADIO.emit("TEST", "einstring", 5)

    function import_files(event){
    if(!state.gui_switches.append) state.scriptSnippets = []

    const files = event.target.files
    const stack = Object.keys(files)
    .forEach((key)=>{
    const file = files[key]
    const reader = new FileReader()
    reader.fileName = file.name
    reader.onerror = (()=> {throw Error})
    reader.onabort = (()=> {throw Error})
    reader.onload = file_loaded
    reader.readAsText(file)
    })

    function file_loaded(event){
    const content_string = event.target.result
    const fileName = event.target.fileName
    const fileNameNoExt = /(.+?)(\.[^.]*$|$)/.exec(fileName)[1]
    const ext = /\.[0-9a-z]+$/.exec(fileName)[0]

    function createStore(reducer)
    {
    const subscribers = [];
    const store = {};

    store.state = {};

    store.reducer = reducer;

    store.getState = function getState()
    {
    return store.state;
    };

    store.dispatch = function(actionObject)
    {
    store.state = store.reducer(_store.getState(), action)
    // notify all subs
    subscribers.forEach( sub => sub() )
    };

    store.subscribe = function addSubscriber(func)
    {
    subscribers.push(func)
    if(ext === ".json") return import_json(content_string)
    return add_snippet(fileNameNoExt, content_string)
    }
    }


    function import_json(content_string){
    var json_data = deserialize(content_string)
    json_data.snippets.forEach(snippet => {
    add_snippet(snippet.name, snippet.content)
    })
    }

    function set_pref(name, data_string){
    InspectorFrontendHost.setPreference(name, data_string)
    }


    /* Nanoharness
    */
    function let_us(msg,f){
    console.log("we_will: "+msg)
    try { f() }
    catch (exception) {
    console.warn(exception.stack.replace(/:(\d+):(\d+)/g, "$& (Line $1, Column $2)"))
    function save_snippets(){
    set_pref( "scriptSnippets", serialize(state.scriptSnippets) )
    set_pref( "scriptSnippets_lastIdentifier", state.lastIdentifier)
    prompt('restart chrome now!')
    }


    function reset_snippets(){
    var choice = window.confirm("DELETE ALL SNIPPETS IN DEVTOOLS?")
    if(choice) clear_chrome_snippets()
    init()
    }

    function clear_chrome_snippets(){
    set_pref("scriptSnippets", "[]")
    set_pref("scriptSnippets_lastIdentifier", "0")
    }

    function add_snippet(name, snippet_content_string){
    if(is_duplicate(name, state.scriptSnippets)) {
    if(!state.gui_switches.rename) return state.scriptSnippets[name] = snippet_content_string
    return add_snippet(name+"copy", snippet_content_string)
    }

    const currentIdentifier = serialize(parseInt(state.lastIdentifier)+1)
    const new_snip = {
    content: snippet_content_string,
    id: currentIdentifier,
    name: name
    }

    state.scriptSnippets.push( new_snip )
    state.lastIdentifier = currentIdentifier
    update()
    }

    function external_bgrins(){

    const brings_snippets = [
    'allcolors',
    'cachebuster',
    'cssreload',
    'cssprettifier',
    'hashlink'
    ]

    brings_snippets.forEach((snippet)=>{
    request('https://raw.githubusercontent.com/bgrins/devtools-snippets/master/snippets/'+snippet+'/'+snippet+'.js', function(request){
    const snippet_content_string = request.target.response
    add_snippet(snippet, snippet_content_string)
    })
    })
    }

    function external_bahmutov(){

    const bahmutov_snippets = [
    'timing',
    'profile-method-call',
    'time-method-call'
    ]

    bahmutov_snippets.forEach((snippet)=>{
    request('https://raw.githubusercontent.com/bahmutov/code-snippets/master/'+snippet+'.js', function(request){
    const snippet_content_string = request.target.response
    add_snippet(snippet, snippet_content_string)
    })
    })
    }

    function export_snippets(){
    if(state.gui_switches.format === "json") return download_json()
    return download_js()
    }

    function download_js(){
    state.scriptSnippets.forEach((snippet)=>{
    download(snippet.name+'.js', snippet.content)
    })
    }

    function download_json(){
    console.log("json")
    const fileName = serialize(Date())
    const json_data = serialize({'snippets': state.scriptSnippets}, ['snippets', 'name', 'content'], 2)
    download(fileName+".json", json_data)
    }


    // Reducer
    //
    const snippetsShape = {
    scriptSnippets: [],
    lastIdentifier: 0,
    //ui
    rename: true,
    format: 'json',
    review: false,
    append: true
    }

    function ok(expr, msg){
    log(expr, msg)
    function snippetsReducer(state = snippetsShape, {TYPE, PL}) {

    if(TYPE === SNIPPETS_FETCHED) return {...state, scriptSnippets: PL.snippets}

    return state
    }

    function log(expr, msg){
    expr ? console.log("!pass "+msg) : console.log("?fail "+msg)

    // Main logic
    //

    const app_window = createWindow("menubar=false, width=1024, height=768", "Chrome Snippets Import/Export/Manager")
    const store = createStore(snippetsReducer, undefined, applyMiddleware(logger,thunk,vanillaPromise,crashReporter))

    app_window.dispatch = store.dispatch
    app_window.getState = store.getState
    app_window.events = actionCreators
    app_window.document.head.innerHTML = style();

    store.subscribe(function(){
    // console.log(JSON.stringify(store.getState()))
    render(app_window.document.body, Layout)
    })

    store.dispatch({type: 'first', payload: Date.now()})

    // UTIL
    //

    function render(mountNode, template){
    mountNode.innerHTML = template({getState: store.getState});
    }

    function html_log(){
    const queue = []
    return function log(expr, msg) {
    queue.push( expr ? `!pass ${msg}` : `?fail ${msg}` )
    function compose(...funcs) {
    if (funcs.length === 0) {
    return arg => arg
    }

    if (funcs.length === 1) {
    return funcs[0]
    }

    return funcs.reduce((a, b) => (...args) => a(b(...args)))
    }

    function uuidv4() {
    // RFC4122 version 4 compliant
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random() * 16 | 0
    , v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
    });
    }

    function request(url, success) {
    var xhr = new XMLHttpRequest();
    xhr.open('GET', url);
    xhr.onload = success;
    xhr.send();
    return xhr;
    }

    function serialize(object, ...rest) {
    if (!object) throw Error("serialize needs input")
    return JSON.stringify(object, ...rest)
    }

    function deserialize(string) {
    if (typeof string !== "string") throw Error("deserialize needs a string")
    if (string === "") throw Error("no snippets present")
    return JSON.parse(string)
    }

    function download(name, data) {
    const Blob = new window.Blob([data],{ 'type': 'text/utf-8' })
    const a = app_window.document.createElement('a')
    a.href = URL.createObjectURL(Blob)
    a.download = name
    a.click()
    }

    function is_duplicate(name, snippets_arr) {
    const result = snippets_arr.filter(function(snippet) {
    return snippet.name === name
    })
    if (result.length === 0) return false
    return true
    }

    function createWindow(options, title) {
    const w = window.open("", "", options)
    w.document.title = title
    return w
    }


    // CSS
    //

    function style() { return `
    <style>
    body {
    font-family: 'Open Sans', sans-serif;
    }
    article {
    display: grid;
    grid-template-columns: auto minmax(min-content, 1fr);
    grid-template-rows: auto minmax(min-content, 1fr) auto;
    max-width: 800px;
    margin: 0 auto;
    }
    header {
    grid-column: 1 / span 3;
    grid-row: 1;
    }
    aside {
    grid-column: 1;
    grid-row: 2;
    background-color: #F0F0F2;
    padding: 5px 10px;
    }
    out {
    grid-column: 3;
    grid-row: 2;
    background-color: #F0F0F2;
    padding: 5px 10px;
    }
    main {
    grid-column: 2;
    grid-row: 2;
    align-self: start;
    margin-left: 18px;
    }
    footer {
    grid-column: 1 / span 2;
    grid-row: 3;
    background-color: #474F59;
    margin-top: 20px;
    padding: 5px 10px;
    color: white;
    margin-bottom: 20px;
    }
    #drop_files {
    opacity: 0;
    width: 100%;
    height: 20vh;
    }
    dropzone {
    cursor: pointer;
    border: 1px black dotted;
    font-weight: bold;
    font-size: 1em;
    text-align: center;
    }
    </style>
    `
    }


    }("live long and prosper")i
    }("live long and prosper");
  6. @soundyogi soundyogi revised this gist Mar 3, 2018. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion 2018_chrome_snippet_gui_import_export.js
    Original file line number Diff line number Diff line change
    @@ -4,7 +4,7 @@ void function(){
    * Manage and Import / Export snippets from chrome (2018)
    * hacked together by: http://github.com/soundyogi
    * inspired by: https://github.com/bgrins/devtools-snippets/blob/master/import-export/chrome/devtools_import_export.js
    * ALPHA / SILLY SIDE PROJECT
    * WORK IN PROGRESS! USE 2016 VERSION! (SCROLL DOWN)
    */


  7. @soundyogi soundyogi renamed this gist Mar 3, 2018. 1 changed file with 0 additions and 0 deletions.
  8. @soundyogi soundyogi revised this gist Mar 3, 2018. 1 changed file with 136 additions and 0 deletions.
    136 changes: 136 additions & 0 deletions chrome_snippet_gui_import_export_2018
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,136 @@
    void function(){
    "use strict"
    /*
    * Manage and Import / Export snippets from chrome (2018)
    * hacked together by: http://github.com/soundyogi
    * inspired by: https://github.com/bgrins/devtools-snippets/blob/master/import-export/chrome/devtools_import_export.js
    * ALPHA / SILLY SIDE PROJECT
    */


    let_us("execute some init tests", () => {
    if(location.origin !== "chrome-devtools://devtools") throw alert("not in devtools of devtools / please inspect devtools again with: (ctrl+shift+i)")
    ok(location.origin === "chrome-devtools://devtools", 'we are in devtools of devtools, good to go')
    })

    // DO IT YOURSELF REDUX
    //

    function createEventBus()
    {

    // register subscriptions to a topic/channel (string)
    const _topics = {}

    // calls
    function emit(stringTopic, ...payload)
    {
    // call every subscriuber function for channel
    _topics[stringTopic].forEach( subscriberCallback => subscriberCallback(payload))
    }

    // registers new subscriber
    function on(stringTopic, subscriberCallback)
    {
    _topics[stringTopic] = _topics[stringTopic] || [];
    _topics[stringTopic].push(subscriberCallback)
    console.log('Added subscription for channel: '+stringTopic)
    }

    return {
    emit,
    on
    }
    }

    // redux
    function createStore(reducer){
    const _radio = createEventBus()
    const store = {}

    store.state = {}
    store.getState = function getState(){return store.state}

    store.dispatch = function(actionObject){
    _radio.emit("ACTION", actionObject)
    }

    _radio.on("ACTION", function processAction(action){
    store.state = _store.reducer(_store.getState(), action)
    _radio.emit("CHANGED")
    })

    store.subscribe = function addSubscriber(func){
    _radio.on("CHANGED", func)
    }

    }



    // TEST
    const RADIO = createEventBus()

    RADIO.on("TEST", function(pl){ console.log(pl) })
    RADIO.emit("TEST", "einstring", 5)




    function createStore(reducer)
    {
    const subscribers = [];
    const store = {};

    store.state = {};

    store.reducer = reducer;

    store.getState = function getState()
    {
    return store.state;
    };

    store.dispatch = function(actionObject)
    {
    store.state = store.reducer(_store.getState(), action)
    // notify all subs
    subscribers.forEach( sub => sub() )
    };

    store.subscribe = function addSubscriber(func)
    {
    subscribers.push(func)
    }

    }



    /* Nanoharness
    */
    function let_us(msg,f){
    console.log("we_will: "+msg)
    try { f() }
    catch (exception) {
    console.warn(exception.stack.replace(/:(\d+):(\d+)/g, "$& (Line $1, Column $2)"))
    }
    }

    function ok(expr, msg){
    log(expr, msg)
    }

    function log(expr, msg){
    expr ? console.log("!pass "+msg) : console.log("?fail "+msg)
    }

    function html_log(){
    const queue = []
    return function log(expr, msg) {
    queue.push( expr ? `!pass ${msg}` : `?fail ${msg}` )
    }
    }


    }("live long and prosper")i
  9. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 5 additions and 4 deletions.
    9 changes: 5 additions & 4 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -71,7 +71,7 @@ const markup = `
    <grid>
    <row>
    <column>
    <item> load snippets:
    <item> load chrome snippets:
    <button id="init">(re)init</button>
    </item>
    </column>
    @@ -108,7 +108,7 @@ const markup = `
    <row>
    <column>
    <dropzone>
    <div>Drop files or click</div>
    <div>Click/Drop .js or .json</div>
    <input id="drop_files" type='file' multiple='true'/>
    </dropzone>
    <label>append files or replace everything?
    @@ -118,7 +118,7 @@ const markup = `
    </select>
    </label>
    </column>
    <column>scriptSnippets preview: <ul id="state.scriptSnippets"></ul></column>
    <column>===== snippets preview =====<ul id="state.scriptSnippets"></ul></column>
    <column>import files from external sources:
    <button id="external_bgrins">load some scripts from bgrins/devtools-snippets repo</button>
    <button id="external_bahmutov">load some scripts from bahmutov/code-snippets repo</button>
    @@ -266,6 +266,7 @@ function set_pref(name, data_string){
    function save_snippets(){
    set_pref( "scriptSnippets", serialize(state.scriptSnippets) )
    set_pref( "scriptSnippets_lastIdentifier", state.lastIdentifier)
    prompt('restart chrome now!')
    }


    @@ -449,4 +450,4 @@ function html_log(){
    }


    }("thank you for reading")
    }("goodbye and thanks for all the fish")
  10. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 7 additions and 7 deletions.
    14 changes: 7 additions & 7 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -8,7 +8,7 @@ void function(){
    */


    let_us("execute some init tests", function(){
    let_us("execute some init tests", () => {
    if(location.origin !== "chrome-devtools://devtools") throw Error("not in devtools of devtools / please inspect devtools again (ctrl+shift+i)")
    ok(location.origin === "chrome-devtools://devtools", 'we are in devtools of devtools, good to go')
    })
    @@ -130,10 +130,10 @@ const markup = `

    /* Main logic
    */
    const app_window = create_window("menubar=false, height=700, width=1000", "chrome snippets import/export by: github.com/soundyogi - ALPHA USE AT OWN RISK")
    const app_window = create_window("menubar=false, height=700, width=1000", "chrome snippets import/export - ALPHA USE AT OWN RISK")
    const document = app_window.document

    let_us("bootstrap the whole thing", function(){
    let_us("bootstrap the whole thing", () => {
    init()
    })

    @@ -211,10 +211,10 @@ function render_list(){

    state.scriptSnippets.forEach((snippet)=>{
    const li = document.createElement('li')
    const a = document.createElement('a')
    a.href = snippet.name
    a.innerHTML = snippet.name
    li.appendChild(a)
    //const a = document.createElement('a')
    //a.href = snippet.name
    li.innerHTML = snippet.name
    //li.appendChild(a)
    ul.appendChild(li)
    })
    }
  11. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 1 addition and 9 deletions.
    10 changes: 1 addition & 9 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -248,19 +248,11 @@ function file_loaded(event){
    const ext = /\.[0-9a-z]+$/.exec(fileName)[0]

    if(ext === ".json") return import_json(content_string)
    return import_single(fileNameNoExt, content_string)
    }

    function import_single(name, content){
    add_snippet(name, content)
    return add_snippet(fileNameNoExt, content_string)
    }

    function import_json(content_string){
    var json_data = deserialize(content_string)
    if(!state.gui_switches.append) {
    InspectorFrontendHost.setPreference("scriptSnippets", serialize(json_data.snippets))
    return init()
    }
    json_data.snippets.forEach(snippet => {
    add_snippet(snippet.name, snippet.content)
    })
  12. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 22 additions and 15 deletions.
    37 changes: 22 additions & 15 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -17,6 +17,7 @@ let_us("execute some init tests", function(){
    const state = {
    scriptSnippets: [],
    }
    window.state = state


    const style = `
    @@ -162,7 +163,7 @@ function setupGUI(){
    app_window.document.body.innerHTML = style+markup
    getID("format").on("change", handle_gui_switches)
    getID("rename").on("change", handle_gui_switches)
    //getID("review").on("change", handle_gui_switches)
    getID("append").on("change", handle_gui_switches)

    getID("drop_files").on("change", import_files)

    @@ -184,7 +185,6 @@ function handle_gui_switches(ev){
    opt.format = target.value
    return update()
    }

    if(target.id === 'rename') {
    opt.rename = !target.value
    return update()
    @@ -194,14 +194,15 @@ function handle_gui_switches(ev){
    return update()
    }
    if(target.id === 'append') {
    opt.review = !target.value
    opt.append = !target.value
    return update()
    }
    }


    function update(){
    render_list()
    console.log(state.gui_switches)
    }

    function render_list(){
    @@ -224,7 +225,7 @@ function render_list(){


    function import_files(event){
    if(!state.gui_switches.append) clear_chrome_snippets()
    if(!state.gui_switches.append) state.scriptSnippets = []

    const files = event.target.files
    const stack = Object.keys(files)
    @@ -239,13 +240,6 @@ function import_files(event){
    })
    }

    function import_json(content_string){
    var json_data = deserialize(content_string)
    if(!state.gui_switches.append) return InspectorFrontendHost.setPreference("scriptSnippets", serialize(json_data.snippets))
    json_data.snippets.forEach(snippet => {
    add_snippet(snippet.name, snippet.content)
    })
    }

    function file_loaded(event){
    const content_string = event.target.result
    @@ -254,8 +248,22 @@ function file_loaded(event){
    const ext = /\.[0-9a-z]+$/.exec(fileName)[0]

    if(ext === ".json") return import_json(content_string)
    return import_single(fileNameNoExt, content_string)
    }

    add_snippet(fileNameNoExt, content_string)
    function import_single(name, content){
    add_snippet(name, content)
    }

    function import_json(content_string){
    var json_data = deserialize(content_string)
    if(!state.gui_switches.append) {
    InspectorFrontendHost.setPreference("scriptSnippets", serialize(json_data.snippets))
    return init()
    }
    json_data.snippets.forEach(snippet => {
    add_snippet(snippet.name, snippet.content)
    })
    }

    function set_pref(name, data_string){
    @@ -266,19 +274,18 @@ function set_pref(name, data_string){
    function save_snippets(){
    set_pref( "scriptSnippets", serialize(state.scriptSnippets) )
    set_pref( "scriptSnippets_lastIdentifier", state.lastIdentifier)
    init()
    }


    function reset_snippets(){
    var choice = window.confirm("DELETE ALL SNIPPETS IN DEVTOOLS?")
    if(choice) return clear_chrome_snippets()
    if(choice) clear_chrome_snippets()
    init()
    }

    function clear_chrome_snippets(){
    set_pref("scriptSnippets", "[]")
    set_pref("scriptSnippets_lastIdentifier", "0")
    init()
    }

    function add_snippet(name, snippet_content_string){
  13. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 27 additions and 16 deletions.
    43 changes: 27 additions & 16 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -16,12 +16,6 @@ let_us("execute some init tests", function(){

    const state = {
    scriptSnippets: [],
    lastIdentifier: 0,
    gui_switches: {
    rename: true,
    format: "json",
    review: false
    }
    }


    @@ -116,6 +110,12 @@ const markup = `
    <div>Drop files or click</div>
    <input id="drop_files" type='file' multiple='true'/>
    </dropzone>
    <label>append files or replace everything?
    <select id='append'>
    <option value='true'>Append</option>
    <option value="false">Replace</option>
    </select>
    </label>
    </column>
    <column>scriptSnippets preview: <ul id="state.scriptSnippets"></ul></column>
    <column>import files from external sources:
    @@ -144,7 +144,8 @@ function init(){
    state.gui_switches = {
    rename: true,
    format: "json",
    review: false
    review: false,
    append: true
    }

    InspectorFrontendHost.getPreferences( prefs => {
    @@ -192,6 +193,10 @@ function handle_gui_switches(ev){
    opt.review = !opt.review
    return update()
    }
    if(target.id === 'append') {
    opt.review = !target.value
    return update()
    }
    }


    @@ -219,6 +224,8 @@ function render_list(){


    function import_files(event){
    if(!state.gui_switches.append) clear_chrome_snippets()

    const files = event.target.files
    const stack = Object.keys(files)
    .forEach((key)=>{
    @@ -233,18 +240,20 @@ function import_files(event){
    }

    function import_json(content_string){
    prompt("replace all snippets or append json content")
    var json_data = deserialize(content_string)
    if(!state.gui_switches.append) return InspectorFrontendHost.setPreference("scriptSnippets", serialize(json_data.snippets))
    json_data.snippets.forEach(snippet => {
    add_snippet(snippet.name, snippet.content)
    })
    }

    function file_loaded(event){
    const content_string = event.target.result
    const fileName = event.target.fileName
    const fileNameNoExt = fileName.split(".")[0]
    const fileNameNoExt = /(.+?)(\.[^.]*$|$)/.exec(fileName)[1]
    const ext = /\.[0-9a-z]+$/.exec(fileName)[0]

    console.log(ext)
    // TODO sucks
    if(ext === "json") return import_json(content_string)

    if(ext === ".json") return import_json(content_string)

    add_snippet(fileNameNoExt, content_string)
    }
    @@ -262,12 +271,14 @@ function save_snippets(){


    function reset_snippets(){
    prompt("DELETE ALL SNIPPETS IN DEVTOOLS? (this is not working right now)")
    // TODO: too risky for dev
    return
    var choice = window.confirm("DELETE ALL SNIPPETS IN DEVTOOLS?")
    if(choice) return clear_chrome_snippets()
    }

    function clear_chrome_snippets(){
    set_pref("scriptSnippets", "[]")
    set_pref("scriptSnippets_lastIdentifier", "0")
    init()
    }

    function add_snippet(name, snippet_content_string){
  14. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 34 additions and 6 deletions.
    40 changes: 34 additions & 6 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -118,7 +118,10 @@ const markup = `
    </dropzone>
    </column>
    <column>scriptSnippets preview: <ul id="state.scriptSnippets"></ul></column>
    <column>import files from external sources:<button id="external_snippets">load some scripts from bgrins/devtools-snippets repo</button></column>
    <column>import files from external sources:
    <button id="external_bgrins">load some scripts from bgrins/devtools-snippets repo</button>
    <button id="external_bahmutov">load some scripts from bahmutov/code-snippets repo</button>
    </column>
    </row>
    </grid>
    `
    @@ -166,7 +169,9 @@ function setupGUI(){
    getID("init").on("click", init)
    getID("save_snippets").on("click", save_snippets)
    getID("reset_snippets").on("click", reset_snippets)
    getID("external_snippets").on("click", external_snippets)

    getID("external_bgrins").on("click", external_bgrins)
    getID("external_bahmutov").on("click", external_bahmutov)
    }


    @@ -227,14 +232,21 @@ function import_files(event){
    })
    }

    function import_json(content_string){
    prompt("replace all snippets or append json content")
    }

    function file_loaded(event){
    const content_string = event.target.result
    const fileName = event.target.fileName
    const fileNameNoExt = fileName.split(".")[0]
    const ext = /\.[0-9a-z]+$/.exec(fileName)[0]

    // TODO: this cant be good lol
    var removeExtension = fileName.split(".")[0]
    add_snippet(removeExtension, content_string)
    console.log(ext)
    // TODO sucks
    if(ext === "json") return import_json(content_string)

    add_snippet(fileNameNoExt, content_string)
    }

    function set_pref(name, data_string){
    @@ -276,7 +288,7 @@ function add_snippet(name, snippet_content_string){
    update()
    }

    function external_snippets(){
    function external_bgrins(){

    const brings_snippets = [
    'allcolors',
    @@ -294,6 +306,22 @@ function external_snippets(){
    })
    }

    function external_bahmutov(){

    const bahmutov_snippets = [
    'timing',
    'profile-method-call',
    'time-method-call'
    ]

    bahmutov_snippets.forEach((snippet)=>{
    request('https://raw.githubusercontent.com/bahmutov/code-snippets/master/'+snippet+'.js', function(request){
    const snippet_content_string = request.target.response
    add_snippet(snippet, snippet_content_string)
    })
    })
    }

    function export_snippets(){
    if(state.gui_switches.format === "json") return download_json()
    return download_js()
  15. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 5 additions and 21 deletions.
    26 changes: 5 additions & 21 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -144,7 +144,7 @@ function init(){
    review: false
    }

    get_prefs( prefs => {
    InspectorFrontendHost.getPreferences( prefs => {
    const lastScriptSnippets = prefs.scriptSnippets
    state.scriptSnippets = deserialize(lastScriptSnippets)
    state.lastIdentifier = prefs.scriptSnippets_lastIdentifier
    @@ -242,19 +242,6 @@ function set_pref(name, data_string){
    }


    function get_prefs(cb){
    InspectorFrontendHost.getPreferences(function(prefs){
    cb(prefs)
    })
    }


    function get_snippets(cb){
    get_prefs(function(prefs){
    cb(prefs.scriptSnippets)
    })
    }

    function save_snippets(){
    set_pref( "scriptSnippets", serialize(state.scriptSnippets) )
    set_pref( "scriptSnippets_lastIdentifier", state.lastIdentifier)
    @@ -392,15 +379,12 @@ function create_window(options, title){
    /*
    * UNIT TESTS
    */
    let_us("export a json file", ()=>{

    let_us("write some tests", ()=>{
    // TODO
    // TDD tests are deleted now / remove harness
    })






    /* Nanoharness
    */
    function let_us(msg,f){
    @@ -427,4 +411,4 @@ function html_log(){
    }


    }("thank you for reading this")
    }("thank you for reading")
  16. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -76,7 +76,7 @@ const markup = `
    <grid>
    <row>
    <column>
    <item>
    <item> load snippets:
    <button id="init">(re)init</button>
    </item>
    </column>
  17. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -126,7 +126,7 @@ const markup = `

    /* Main logic
    */
    const app_window = create_window("menubar=false, height=700, width=1000", "chrome snippets import/export")
    const app_window = create_window("menubar=false, height=700, width=1000", "chrome snippets import/export by: github.com/soundyogi - ALPHA USE AT OWN RISK")
    const document = app_window.document

    let_us("bootstrap the whole thing", function(){
  18. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -9,7 +9,7 @@ void function(){


    let_us("execute some init tests", function(){
    if(location.origin !== "chrome-devtools://devtools") throw Error("not in devtools of devtools")
    if(location.origin !== "chrome-devtools://devtools") throw Error("not in devtools of devtools / please inspect devtools again (ctrl+shift+i)")
    ok(location.origin === "chrome-devtools://devtools", 'we are in devtools of devtools, good to go')
    })

  19. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 21 additions and 17 deletions.
    38 changes: 21 additions & 17 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,7 @@ void function(){
    /*
    * Manage and Import / Export snippets from chrome (2016)
    * hacked together by: http://github.com/soundyogi
    * inspired by: aaran etc // TODO
    * inspired by: https://github.com/bgrins/devtools-snippets/blob/master/import-export/chrome/devtools_import_export.js
    * ALPHA / SILLY SIDE PROJECT
    */

    @@ -25,9 +25,6 @@ const state = {
    }


    window.state = state


    const style = `
    <style>
    body{
    @@ -49,10 +46,11 @@ row {
    display: flex;
    -webkit-flex-flow: row;
    width: 90vw;
    margin-bottom: 2vh;
    }
    item {
    background: tomato;
    min-height: 5vh;
    min-height: 13vh;
    color: white;
    font-weight: bold;
    font-size: 1.5em;
    @@ -77,12 +75,12 @@ dropzone {
    const markup = `
    <grid>
    <row>
    <column>
    <item>
    <button id="init">(re)init</button>
    </item>
    <item>
    <input id="import_files" type='file' multiple='true'/>
    </item>
    </column>
    <column>
    <item>
    <label>on name conflicts:
    <select id='rename'>
    @@ -91,29 +89,36 @@ const markup = `
    </select>
    </label>
    </item>
    </column>
    <column>
    <item>
    <button id="export_snippets">export</button>
    <select id='format'>
    <option value="json">Single .json</option>
    <option value="js">Multiple .js</option>
    </select>
    </item>
    </column>
    <column>
    <item>
    <button id="save_snippets">Save to Chrome</button>
    </item>
    </column>
    <column>
    <item>
    <button id="reset_snippets">DELETE all on Chrome</button>
    </item>
    </column>
    </row>
    <row>
    <column>
    <dropzone>
    <div>Drop Files Here</div>
    <input id="drop_files" type='file' multiple='true'/>
    </dropzone>
    </column>
    <column>scriptSnippets preview: <ul id="state.scriptSnippets"></ul></column>
    <column>import files from external sources:<button id="external_snippets">load some scripts from bgrins/devtools-snippets repo</button></column>
    <dropzone>
    <div>Drop files or click</div>
    <input id="drop_files" type='file' multiple='true'/>
    </dropzone>
    </column>
    <column>scriptSnippets preview: <ul id="state.scriptSnippets"></ul></column>
    <column>import files from external sources:<button id="external_snippets">load some scripts from bgrins/devtools-snippets repo</button></column>
    </row>
    </grid>
    `
    @@ -155,7 +160,6 @@ function setupGUI(){
    getID("rename").on("change", handle_gui_switches)
    //getID("review").on("change", handle_gui_switches)

    getID("import_files").on("change", import_files)
    getID("drop_files").on("change", import_files)

    getID("export_snippets").on("click", export_snippets)
    @@ -254,7 +258,7 @@ function get_snippets(cb){
    function save_snippets(){
    set_pref( "scriptSnippets", serialize(state.scriptSnippets) )
    set_pref( "scriptSnippets_lastIdentifier", state.lastIdentifier)
    load_snippets()
    init()
    }


  20. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 4 additions and 1 deletion.
    5 changes: 4 additions & 1 deletion chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,7 @@ void function(){
    /*
    * Manage and Import / Export snippets from chrome (2016)
    * hacked together by: http://github.com/soundyogi
    * inspired by: https://github.com/bgrins/devtools-snippets/blob/master/import-export/chrome/devtools_import_export.js
    * inspired by: aaran etc // TODO
    * ALPHA / SILLY SIDE PROJECT
    */

    @@ -25,6 +25,9 @@ const state = {
    }


    window.state = state


    const style = `
    <style>
    body{
  21. @soundyogi soundyogi revised this gist Jan 26, 2016. No changes.
  22. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 0 additions and 3 deletions.
    3 changes: 0 additions & 3 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -25,9 +25,6 @@ const state = {
    }


    window.state = state


    const style = `
    <style>
    body{
  23. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,7 @@ void function(){
    /*
    * Manage and Import / Export snippets from chrome (2016)
    * hacked together by: http://github.com/soundyogi
    * inspired by: aaran etc // TODO
    * inspired by: https://github.com/bgrins/devtools-snippets/blob/master/import-export/chrome/devtools_import_export.js
    * ALPHA / SILLY SIDE PROJECT
    */

  24. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 30 additions and 21 deletions.
    51 changes: 30 additions & 21 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -52,11 +52,12 @@ row {
    }
    item {
    background: tomato;
    min-height: 20vh;
    min-height: 5vh;
    color: white;
    font-weight: bold;
    font-size: 1.5em;
    text-align: center;
    padding: 20px;
    }
    #drop_files {
    opacity: 0;
    @@ -67,7 +68,7 @@ dropzone {
    cursor: pointer;
    border: 1px black dotted;
    font-weight: bold;
    font-size: 1.5em;
    font-size: 1em;
    text-align: center;
    }
    </style>
    @@ -83,7 +84,7 @@ const markup = `
    <input id="import_files" type='file' multiple='true'/>
    </item>
    <item>
    <label>Rename?
    <label>on name conflicts:
    <select id='rename'>
    <option value='true'>Rename Import Files</option>
    <option value="false">Overwrite Snippets</option>
    @@ -105,11 +106,14 @@ const markup = `
    </item>
    </row>
    <row>
    <column>
    <dropzone>
    <div>Drop Files Here</div>
    <input id="drop_files" type='file' multiple='true'/>
    </dropzone>
    <column><ul id="state.scriptSnippets"></ul></column>
    </column>
    <column>scriptSnippets preview: <ul id="state.scriptSnippets"></ul></column>
    <column>import files from external sources:<button id="external_snippets">load some scripts from bgrins/devtools-snippets repo</button></column>
    </row>
    </grid>
    `
    @@ -158,15 +162,14 @@ function setupGUI(){
    getID("init").on("click", init)
    getID("save_snippets").on("click", save_snippets)
    getID("reset_snippets").on("click", reset_snippets)
    getID("external_snippets").on("click", external_snippets)
    }


    function handle_gui_switches(ev){
    const target = ev.target
    const opt = state.gui_switches

    console.log(target.value)

    if(target.id === 'format') {
    opt.format = target.value
    return update()
    @@ -282,6 +285,24 @@ function add_snippet(name, snippet_content_string){
    update()
    }

    function external_snippets(){

    const brings_snippets = [
    'allcolors',
    'cachebuster',
    'cssreload',
    'cssprettifier',
    'hashlink'
    ]

    brings_snippets.forEach((snippet)=>{
    request('https://raw.githubusercontent.com/bgrins/devtools-snippets/master/snippets/'+snippet+'/'+snippet+'.js', function(request){
    const snippet_content_string = request.target.response
    add_snippet(snippet, snippet_content_string)
    })
    })
    }

    function export_snippets(){
    if(state.gui_switches.format === "json") return download_json()
    return download_js()
    @@ -302,10 +323,6 @@ function download_json(){







    /* util & shorthand
    */
    function request(url, success) {
    @@ -375,17 +392,9 @@ let_us("export a json file", ()=>{

    })

    /*
    let_us("import a snippet from bgrins", ()=> {
    const brings_snippets = [
    'allcolors'
    ]
    brings_snippets.forEach(()=>{
    request('https://raw.githubusercontent.com/bgrins/devtools-snippets/master/snippets/allcolors/allcolors.js', function(request){
    var snippet = request.currentTarget.response || request.target.responseText;
    })
    })
    */





    /* Nanoharness
  25. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -117,7 +117,7 @@ const markup = `

    /* Main logic
    */
    const app_window = create_window("menubar=false, height=700, width=700", "chrome snippets import/export")
    const app_window = create_window("menubar=false, height=700, width=1000", "chrome snippets import/export")
    const document = app_window.document

    let_us("bootstrap the whole thing", function(){
  26. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 4 additions and 3 deletions.
    7 changes: 4 additions & 3 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -224,7 +224,10 @@ function import_files(event){
    function file_loaded(event){
    const content_string = event.target.result
    const fileName = event.target.fileName
    add_snippet(fileName, content_string)

    // TODO: this cant be good lol
    var removeExtension = fileName.split(".")[0]
    add_snippet(removeExtension, content_string)
    }

    function set_pref(name, data_string){
    @@ -377,11 +380,9 @@ let_us("import a snippet from bgrins", ()=> {
    const brings_snippets = [
    'allcolors'
    ]
    brings_snippets.forEach(()=>{
    request('https://raw.githubusercontent.com/bgrins/devtools-snippets/master/snippets/allcolors/allcolors.js', function(request){
    var snippet = request.currentTarget.response || request.target.responseText;
    })
    })
    */
  27. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 0 additions and 26 deletions.
    26 changes: 0 additions & 26 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -347,32 +347,6 @@ function download(name, data){
    a.click()
    }

    function getDownloadFileName(count) {
    var abbrevCount;
    var d = new Date();
    var fileName = 'chrome-snippets-' + count + '-';
    fileName += d.getFullYear();
    var month = d.getMonth() + 1;
    fileName += "-" + ((month < 10) ? "0" + month : month); //$NON-NLS-1$
    // TODO Please note getDay() returns the day of week,
    // see http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.5.16
    var day = d.getDate();
    fileName += "-" + ((day < 10) ? "0" + day : day); //$NON-NLS-1$
    var hours = d.getHours();
    fileName += "T" + ((hours < 10) ? "0" + hours : hours); //$NON-NLS-1$
    var minutes = d.getMinutes();
    fileName += ((minutes < 10) ? "0" + minutes : minutes);
    var seconds = d.getSeconds();
    fileName += ((seconds < 10) ? "0" + seconds : seconds);
    var timeZoneOffset = -d.getTimezoneOffset();
    var offsetMinutes = timeZoneOffset % 60;
    var offsetHours = (timeZoneOffset - offsetMinutes) / 60;
    // TODO FIXME >= 0 ?
    fileName += (offsetHours > 0 ? "+" : "") + ((offsetHours < 10) ? "0" + offsetHours : offsetHours) + ((offsetMinutes < 10) ? "0" + offsetMinutes : offsetMinutes); //$NON-NLS-2$ //$NON-NLS-1$
    fileName += '.json';
    return fileName;
    }


    function is_duplicate(name, snippets_arr){
    const result = snippets_arr.filter(function(snippet){
  28. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 65 additions and 56 deletions.
    121 changes: 65 additions & 56 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -3,7 +3,8 @@ void function(){
    /*
    * Manage and Import / Export snippets from chrome (2016)
    * hacked together by: http://github.com/soundyogi
    * inspired by: aaran etc.
    * inspired by: aaran etc // TODO
    * ALPHA / SILLY SIDE PROJECT
    */


    @@ -57,19 +58,29 @@ item {
    font-size: 1.5em;
    text-align: center;
    }
    #drop_files {
    opacity: 0;
    width: 100%;
    height: 20vh;
    }
    dropzone {
    cursor: pointer;
    border: 1px black dotted;
    font-weight: bold;
    font-size: 1.5em;
    text-align: center;
    }
    </style>
    `

    const markup = `
    <grid>
    <row>
    <item>
    <button id="load_snippets">Load</button>
    <button id="init">(re)init</button>
    </item>
    <item>
    <label>Drop Files Here
    <input id="import_files" type='file' multiple='true'/>
    </label>
    <input id="import_files" type='file' multiple='true'/>
    </item>
    <item>
    <label>Rename?
    @@ -94,7 +105,11 @@ const markup = `
    </item>
    </row>
    <row>
    <column><ul id="state.scriptSnippets"></column>
    <dropzone>
    <div>Drop Files Here</div>
    <input id="drop_files" type='file' multiple='true'/>
    </dropzone>
    <column><ul id="state.scriptSnippets"></ul></column>
    </row>
    </grid>
    `
    @@ -105,10 +120,12 @@ const markup = `
    const app_window = create_window("menubar=false, height=700, width=700", "chrome snippets import/export")
    const document = app_window.document

    init()
    let_us("bootstrap the whole thing", function(){
    init()
    })

    function init(){
    setupGUI()
    load_snippets()

    state.scriptSnippets = []
    state.lastIdentifier = 0
    @@ -117,54 +134,28 @@ function init(){
    format: "json",
    review: false
    }
    }

    function main(prefs){
    const lastScriptSnippets = prefs.scriptSnippets
    state.scriptSnippets = deserialize(lastScriptSnippets)
    state.lastIdentifier = prefs.scriptSnippets_lastIdentifier


    /*
    var loop = setInterval(function(){
    render()
    console.log(state.gui_switches)
    }, 1000)
    window.loop = loop
    */

    render()

    /*
    let_us("import a snippet from bgrins", ()=> {
    const brings_snippets = [
    'allcolors'
    ]
    brings_snippets.forEach(()=>{
    request('https://raw.githubusercontent.com/bgrins/devtools-snippets/master/snippets/allcolors/allcolors.js', function(request){
    var snippet = request.currentTarget.response || request.target.responseText;
    })
    })*/
    get_prefs( prefs => {
    const lastScriptSnippets = prefs.scriptSnippets
    state.scriptSnippets = deserialize(lastScriptSnippets)
    state.lastIdentifier = prefs.scriptSnippets_lastIdentifier

    update()
    })
    }


    function load_snippets(){
    get_prefs(main)
    }

    function setupGUI(){
    app_window.document.body.innerHTML = style+markup
    getID("format").on("change", handle_gui_switches)
    getID("rename").on("change", handle_gui_switches)
    //getID("review").on("change", handle_gui_switches)

    getID("import_files").on("change", import_files)
    getID("drop_files").on("change", import_files)

    getID("export_snippets").on("click", export_snippets)
    getID("load_snippets").on("click", init)
    getID("init").on("click", init)
    getID("save_snippets").on("click", save_snippets)
    getID("reset_snippets").on("click", reset_snippets)
    }
    @@ -193,11 +184,10 @@ function handle_gui_switches(ev){


    function update(){
    render()
    render_list()
    }


    function render(){
    function render_list(){
    const ul = app_window.document.getElementById("state.scriptSnippets")
    ul.innerHTML = ''

    @@ -263,7 +253,7 @@ function save_snippets(){


    function reset_snippets(){
    prompt("DELETE ALL SNIPPETS IN DEVTOOLS?")
    prompt("DELETE ALL SNIPPETS IN DEVTOOLS? (this is not working right now)")
    // TODO: too risky for dev
    return

    @@ -296,13 +286,15 @@ function export_snippets(){

    function download_js(){
    state.scriptSnippets.forEach((snippet)=>{
    download(snippet.name, snippet.content)
    download(snippet.name+'.js', snippet.content)
    })
    }

    function download_json(){
    console.log("json")
    const fileName = serialize(Date())
    const json_data = serialize({'snippets': state.scriptSnippets}, ['snippets', 'name', 'content'], 2)
    download('json', json_data)
    download(fileName+".json", json_data)
    }


    @@ -358,26 +350,26 @@ function download(name, data){
    function getDownloadFileName(count) {
    var abbrevCount;
    var d = new Date();
    var fileName = 'chrome-snippets-' + count + '-'; //$NON-NLS-0$
    var fileName = 'chrome-snippets-' + count + '-';
    fileName += d.getFullYear();
    var month = d.getMonth() + 1;
    fileName += "-" + ((month < 10) ? "0" + month : month); //$NON-NLS-0$ //$NON-NLS-1$
    fileName += "-" + ((month < 10) ? "0" + month : month); //$NON-NLS-1$
    // TODO Please note getDay() returns the day of week,
    // see http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.5.16
    var day = d.getDate();
    fileName += "-" + ((day < 10) ? "0" + day : day); //$NON-NLS-0$ //$NON-NLS-1$
    fileName += "-" + ((day < 10) ? "0" + day : day); //$NON-NLS-1$
    var hours = d.getHours();
    fileName += "T" + ((hours < 10) ? "0" + hours : hours); //$NON-NLS-0$ //$NON-NLS-1$
    fileName += "T" + ((hours < 10) ? "0" + hours : hours); //$NON-NLS-1$
    var minutes = d.getMinutes();
    fileName += ((minutes < 10) ? "0" + minutes : minutes); //$NON-NLS-0$
    fileName += ((minutes < 10) ? "0" + minutes : minutes);
    var seconds = d.getSeconds();
    fileName += ((seconds < 10) ? "0" + seconds : seconds); //$NON-NLS-0$
    fileName += ((seconds < 10) ? "0" + seconds : seconds);
    var timeZoneOffset = -d.getTimezoneOffset();
    var offsetMinutes = timeZoneOffset % 60;
    var offsetHours = (timeZoneOffset - offsetMinutes) / 60;
    // TODO FIXME >= 0 ?
    fileName += (offsetHours > 0 ? "+" : "") + ((offsetHours < 10) ? "0" + offsetHours : offsetHours) + ((offsetMinutes < 10) ? "0" + offsetMinutes : offsetMinutes); //$NON-NLS-0$ //$NON-NLS-2$ //$NON-NLS-1$
    fileName += '.json'; //$NON-NLS-0$
    fileName += (offsetHours > 0 ? "+" : "") + ((offsetHours < 10) ? "0" + offsetHours : offsetHours) + ((offsetMinutes < 10) ? "0" + offsetMinutes : offsetMinutes); //$NON-NLS-2$ //$NON-NLS-1$
    fileName += '.json';
    return fileName;
    }

    @@ -402,6 +394,23 @@ function create_window(options, title){
    /*
    * UNIT TESTS
    */
    let_us("export a json file", ()=>{

    })

    /*
    let_us("import a snippet from bgrins", ()=> {
    const brings_snippets = [
    'allcolors'
    ]
    brings_snippets.forEach(()=>{
    request('https://raw.githubusercontent.com/bgrins/devtools-snippets/master/snippets/allcolors/allcolors.js', function(request){
    var snippet = request.currentTarget.response || request.target.responseText;
    })
    })
    */


    /* Nanoharness
  29. @soundyogi soundyogi revised this gist Jan 26, 2016. 1 changed file with 40 additions and 20 deletions.
    60 changes: 40 additions & 20 deletions chrome_snippet_gui_export_import_2016.js
    Original file line number Diff line number Diff line change
    @@ -104,13 +104,19 @@ const markup = `
    */
    const app_window = create_window("menubar=false, height=700, width=700", "chrome snippets import/export")
    const document = app_window.document
    const init = load_snippets

    init()
    function init(){
    setupGUI()
    load_snippets()

    function load_snippets(){
    app_window.document.body.innerHTML = style+markup
    get_prefs(main)
    state.scriptSnippets = []
    state.lastIdentifier = 0
    state.gui_switches = {
    rename: true,
    format: "json",
    review: false
    }
    }

    function main(prefs){
    @@ -119,22 +125,14 @@ function main(prefs){
    state.lastIdentifier = prefs.scriptSnippets_lastIdentifier


    getID("format").on("change", handle_gui_switches)
    getID("rename").on("change", handle_gui_switches)
    //getID("review").on("change", handle_gui_switches)

    getID("import_files").on("change", import_files)

    getID("export_snippets").on("click", export_snippets)
    getID("load_snippets").on("click", load_snippets)
    getID("save_snippets").on("click", save_snippets)
    getID("reset_snippets").on("click", reset_snippets)

    /*
    var loop = setInterval(function(){
    render()
    console.log(state)
    console.log(state.gui_switches)
    }, 1000)
    window.kill = clearInterval(loop)
    window.loop = loop
    */

    render()

    /*
    @@ -152,6 +150,26 @@ function main(prefs){

    }


    function load_snippets(){
    get_prefs(main)
    }

    function setupGUI(){
    app_window.document.body.innerHTML = style+markup
    getID("format").on("change", handle_gui_switches)
    getID("rename").on("change", handle_gui_switches)
    //getID("review").on("change", handle_gui_switches)

    getID("import_files").on("change", import_files)

    getID("export_snippets").on("click", export_snippets)
    getID("load_snippets").on("click", init)
    getID("save_snippets").on("click", save_snippets)
    getID("reset_snippets").on("click", reset_snippets)
    }


    function handle_gui_switches(ev){
    const target = ev.target
    const opt = state.gui_switches
    @@ -180,14 +198,16 @@ function update(){


    function render(){
    const list = app_window.document.getElementById("state.scriptSnippets")
    list.innerHTML = ''
    const ul = app_window.document.getElementById("state.scriptSnippets")
    ul.innerHTML = ''

    state.scriptSnippets.forEach((snippet)=>{
    const li = document.createElement('li')
    const a = document.createElement('a')
    a.href = snippet.name
    a.innerHTML = snippet.name
    list.appendChild(a)
    li.appendChild(a)
    ul.appendChild(li)
    })
    }

  30. @soundyogi soundyogi renamed this gist Jan 26, 2016. 1 changed file with 0 additions and 0 deletions.