How to use svelte - 10 common examples

To help you get started, we’ve selected a few svelte examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github soapdog / patchfox / src / ui / utils.js View on Github external
window.location = `/index.html?thread=${encodeURIComponent(hash)}#/thread`
        break
      case "&":
        window.location = `http://localhost:8989/blobs/get/${hash}`
        break
      case "@":
        window.location = `/index.html?feed=${encodeURIComponent(hash)}#/profile`
        break
      case "#":
        window.location = `/index.html?channel=${hash.replace("#","")}#/channel` 
        break
    }
  }
}

const connected = writable(false);

// maybe in the future, migrate routing system to:
// https://github.com/ItalyPaleAle/svelte-spa-router
const route = writable(parseLocation());
const routeParams = derived(route, $route => $route.data)
const routeLocation = derived(route, $route => $route.location)

const navigate = (location, data) => {
  data = data || {}
  route.set({ location, data });
  let dataAsQuery = queryString.stringify(data);
  let url = `/index.html?${dataAsQuery}#${location}`;
  console.log("navigate url", url)
  history.pushState({ location, data }, `Patchfox - ${location}`, `/index.html?${dataAsQuery}#${location}`);
  console.log(`Navigate ${location}`, data);
};
github codediodeio / sveltefire / src / firestore.js View on Github external
once && _teardown();
      },

      // Handle firebase thrown errors
      error => {
        console.error(error);
        next(null, error);
      }
    );

    // Removes firebase listener when store completes
    return () => _teardown();
  };

  // Svelte store
  const store = writable(startWith, start);
  const { subscribe, set } = store;

  return {
    subscribe,
    firestore,
    ref,
    get loading() {
      return _loading;
    },
    get error() {
      return _error;
    }
  };
}
github soapdog / patchfox / src / ui / utils.js View on Github external
case "@":
        window.location = `/index.html?feed=${encodeURIComponent(hash)}#/profile`
        break
      case "#":
        window.location = `/index.html?channel=${hash.replace("#","")}#/channel` 
        break
    }
  }
}

const connected = writable(false);

// maybe in the future, migrate routing system to:
// https://github.com/ItalyPaleAle/svelte-spa-router
const route = writable(parseLocation());
const routeParams = derived(route, $route => $route.data)
const routeLocation = derived(route, $route => $route.location)

const navigate = (location, data) => {
  data = data || {}
  route.set({ location, data });
  let dataAsQuery = queryString.stringify(data);
  let url = `/index.html?${dataAsQuery}#${location}`;
  console.log("navigate url", url)
  history.pushState({ location, data }, `Patchfox - ${location}`, `/index.html?${dataAsQuery}#${location}`);
  console.log(`Navigate ${location}`, data);
};


const routes = {
  "/thread": Thread,
  "/public": Public,
github kenrick95 / Raun / src / stores / I18n.js View on Github external
return this.banana.i18n(...args);
  }
}

let i18n = new I18n('en');

function createTFactory(locale) {
  i18n.init(locale);
  return i18n.t;
}

// NOTE: "MessageStore" is used so that when the messages have been fetched, every subscription of "t" are rerendered.
const MessageStore = writable({});

// eslint-disable-next-line no-unused-vars
export const t = derived([Locale, MessageStore], ([locale, messageStore]) => {
  return createTFactory(locale);
});
github TalesMUD / talesmud / public / app / src / auth.js View on Github external
// src/auth.js

import { onMount, setContext, getContext } from "svelte";
import { writable } from "svelte/store";
import createAuth0Client from "@auth0/auth0-spa-js";

const isLoading = writable(true);
const isAuthenticated = writable(false);
const authToken = writable("");
const userInfo = writable({});
const authError = writable(null);
const AUTH_KEY = {};

// Default Auth0 expiration time is 10 hours or something like that.
// If you want to get fancy you can parse the JWT token and get
// token's actual expiration time.
const refreshRate = 10 * 60 * 60 * 1000;

function createAuth(config) {
  let auth0 = null;
  let intervalId = undefined;

  // You can use Svelte's hooks in plain JS files. How nice!
  onMount(async () => {
github ctx-core / ctx-core / packages / theme / store.ts View on Github external
import { writable, derived } from 'svelte/store'
// @ts-ignore
import { subscribe__debug } from '@ctx-core/store'
import { _class } from '@ctx-core/html'
import { not } from '@ctx-core/function'
export const __theme__invert = writable(null)
export function invert__theme() {
  __theme__invert.update(not)
}
export const __class__theme__invert =
  derived(__theme__invert,
    theme__invert => _class({ theme__invert }))
github SAP / luigi / core / src / App.html View on Github external
GenericHelpers,
    StateHelpers,
    RoutingHelpers,
    IframeHelpers,
    AuthHelpers
  } from './utilities/helpers';
  import { LuigiI18N, LuigiConfig, LuigiElements } from './core-api';
  import { Navigation } from './navigation/services/navigation';
  import { Routing } from './services/routing';
  import { Iframe } from './services/iframe';
  import { SplitViewSvc } from './services/split-view';
  import { ViewGroupPreloading } from './services/preloading';
  import { MessagesListeners } from './services/messages-listeners';
  import { thirdPartyCookiesStatus } from './utilities/third-party-cookies-check.js';

  const dispatch = createEventDispatcher();

  export let store;
  export let getTranslation;

  let showLoadingIndicator = false;

  let mfSplitView = {
    displayed: false
  };
  let splitViewValues;

  /// MFs
  let modalIframe;
  let modalIframeData;
  let modal;
  let splitViewIframe;
github kenrick95 / Raun / src / stores / RcStreamGroup.js View on Github external
import { readable } from 'svelte/store';
import { RcStream } from './RcStream';
import { OresQueue } from './Ores';
import { filterEvents } from './AppConfig';

/**
 * @var {Array<Array<RcEvent>>} eventGroups
 *
 * New events at the front
 */
let eventGroups = [];


export const RcStreamGroups = readable(eventGroups, async (set) => {
  RcStream.subscribe((events) => {
    if (!events || events.length < 1) {
      return;
    }
    const filteredEvents = filterEvents(events);


    const newEventIds = [];
    for (const newEvent of filteredEvents) {
      newEventIds.push({ revid: newEvent.revision.new, dbName: newEvent.wiki });
    }
    OresQueue.update((eventIds) => [...eventIds, ...newEventIds]);
    
    for (const newEvent of filteredEvents) {
      // TODO: These operations are expensive; O(N) on every new event received; see if we can improve
github ctx-core / ctx-core / packages / store / lib.ts View on Github external
export function derived__async(stores, fn, initial_value = null) {
	const single = !Array.isArray(stores)
	if (single) stores = [stores]
	const auto = fn.length < 2
	let value = {}
	return readable(initial_value, set=>{
		let inited = false
		const values = []
		let pending = 0
		// @ts-ignore
		async function sync():Promise<void> {
			if (pending) return
			const result = await fn(single ? values[0] : values, set)
			if (auto && (value !== (value = result))) set(result)
		}
		const unsubscribers = stores.map((store, i)=>
			subscribe(
				store,
				value=>{
					values[i] = value
					pending &= ~(1 << i)
					if (inited) sync()
github timhall / svelte-apollo / src / query.ts View on Github external
initial_value = { data: initial_value } as any;
    } catch (err) {
      // Ignore preload errors
    }
  }

  // Create query and observe,
  // but don't subscribe directly to avoid firing duplicate value if initialized
  const observable_query = client.watchQuery<TData>(options);
  const { subscribe: subscribe_to_query } = observe<Value>(
    observable_query,
    initial_value
  );

  // Wrap the query subscription with a readable to prevent duplicate values
  const { subscribe } = readable(
    (initial_value as unknown) as Deferred<Value>,
    set => {
      subscribed = true;

      const skip_duplicate = initial_value !== undefined;
      let initialized = false;
      let skipped = false;

      const unsubscribe = subscribe_to_query(value => {
        if (skip_duplicate && initialized && !skipped) {
          skipped = true;
        } else {
          if (!initialized) initialized = true;
          set(value);
        }
      });