Skip to content

Commit

Permalink
Init
Browse files Browse the repository at this point in the history
  • Loading branch information
woutdp committed Feb 23, 2023
0 parents commit 9102bcf
Show file tree
Hide file tree
Showing 23 changed files with 755 additions and 0 deletions.
4 changes: 4 additions & 0 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
# Used by "mix format"
[
inputs: ["{mix,.formatter}.exs", "{config,lib,test}/**/*.{ex,exs}"]
]
29 changes: 29 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# The directory Mix will write compiled artifacts to.
/_build/

# If you run "mix test --cover", coverage assets end up here.
/cover/

# The directory Mix downloads your dependencies sources to.
/deps/

# Where third-party dependencies like ExDoc output generated docs.
/doc/

# Ignore .fetch files in case you like to edit your project deps locally.
/.fetch

# If the VM crashes, it generates a dump, let's ignore it too.
erl_crash.dump

# Also ignore archive artifacts (built via "mix archive.build").
*.ez

# Ignore package tarball (built via "mix hex.build").
live_svelte-*.tar

# Temporary files, for example, from tests.
/tmp/

# NPM dependencies
node_module/
9 changes: 9 additions & 0 deletions LICENSE.MD
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# MIT License

Copyright (c) 2023 Wout De Puysseleir

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
110 changes: 110 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# LiveSvelte

LiveSvelte renders Svelte directly into your Phoenix LiveView and enables E2E reactivity.

## Features

- Server-Side Rendered (SSR) Svelte
- End-To-End Reactivity
- Svelte Preprocessing support with [svelte-preprocess](https://github.com/sveltejs/svelte-preprocess)
- Tailwind support

## Docs
<https://hexdocs.pm/live_svelte>

## Installation

Add `live_svelte` to your list of dependencies in `mix.exs`:

```elixir
def deps do
[
{:live_svelte, "~> 0.1.0-rc0"}
]
end
```

Run the following in your terminal
```bash
mix deps.get
mix live_svelte.setup
```

Make sure you have Node installed, you can verify this by running `node --version` in your project directory.

## Usage

### Basic Example

#### Create a Svelte component

```svelte
<script>
export let number = 1
export let pushEvent
function increase() {
pushEvent('set_number', { number: number + 1 }, () => {})
}
function decrease() {
pushEvent('set_number', { number: number - 1 }, () => {})
}
</script>
<p>The number is {number}</p>
<button on:click={increase}>+</button>
<button on:click={decrease}>-</button>
```

#### Create a LiveView

```elixir
# `/lib/app_web/live/live_svelte.ex`
defmodule AppWeb.SvelteLive do
use AppWeb, :live_view

def render(assigns) do
~H"""
<.live_component
module={LiveSvelte.LiveComponent}
id="Example"
name="Example"
props={%{number: @number}}
/>
"""
end

def handle_event("set_number", %{"number" => number}, socket) do
{:noreply, assign(socket, :number, number)}
end

def mount(_params, _session, socket) do
{:ok, assign(socket, :number, 5)}
end
end
```

```elixir
# `/lib/app_web/router.ex`
import Phoenix.LiveView.Router

scope "/", AppWeb do
...
live "/svelte", SvelteLive
...
end
```

###

To use the preprocessor, install the desired preprocessor.

e.g. Typescript
```
cd assets && npm install --save-dev typescript
```

## Credits
- [Ryan Cooke](https://dev.to/debussyman) - [E2E Reactivity using Svelte with Phoenix LiveView](https://dev.to/debussyman/e2e-reactivity-using-svelte-with-phoenix-liveview-38mf)
- [Svonix](https://github.com/nikokozak/svonix)
91 changes: 91 additions & 0 deletions assets/build.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
const esbuild = require('esbuild')
const sveltePlugin = require('esbuild-svelte')
const importGlobPlugin = require('esbuild-plugin-import-glob').default
const sveltePreprocess = require('svelte-preprocess')

const args = process.argv.slice(2)
const watch = args.includes('--watch')
const deploy = args.includes('--deploy')

let optsClient = {
entryPoints: ['js/app.js'],
mainFields: ['svelte', 'browser', 'module', 'main'],
bundle: true,
minify: false,
target: 'es2017',
outdir: '../priv/static/assets',
logLevel: 'info',
plugins: [
importGlobPlugin(),
sveltePlugin({
preprocess: sveltePreprocess(),
compilerOptions: {hydratable: true},
})
]
}

let optsServer = {
entryPoints: ['js/server.js'],
mainFields: ['svelte', 'module', 'main'],
platform: 'node',
format: 'cjs',
bundle: true,
minify: false,
target: "node19.6.1",
outdir: '../priv/static/assets/server',
logLevel: 'info',
plugins: [
importGlobPlugin(),
sveltePlugin({
preprocess: sveltePreprocess(),
compilerOptions: {hydratable: true, generate: 'ssr', format: 'cjs'},
})
]
}

if (watch) {
optsClient = {
...optsClient,
watch,
sourcemap: 'inline'
}

optsServer = {
...optsServer,
watch,
sourcemap: 'inline'
}
}

if (deploy) {
optsClient = {
...optsClient,
minify: true
}

optsServer = {
...optsServer,
minify: true
}
}

const client = esbuild.build(optsClient)
const server = esbuild.build(optsServer)

if (watch) {
client.then(_result => {
process.stdin.on('close', () => {
process.exit(0)
})

process.stdin.resume()
})

server.then(_result => {
process.stdin.on('close', () => {
process.exit(0)
})

process.stdin.resume()
})
}
42 changes: 42 additions & 0 deletions assets/js/app.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
// If you want to use Phoenix channels, run `mix help phx.gen.channel`
// to get started and then uncomment the line below.
// import "./user_socket.js"

// You can include dependencies in two ways.
//
// The simplest option is to put them in assets/vendor and
// import them using relative paths:
//
// import "../vendor/some-package.js"
//
// Alternatively, you can `npm install some-package --prefix assets` and import
// them using a path starting with the package name:
//
// import "some-package"
//

// Include phoenix_html to handle method=PUT/DELETE in forms and buttons.
import "phoenix_html"
// Establish Phoenix Socket and LiveView configuration.
import {Socket} from "phoenix"
import {LiveSocket} from "phoenix_live_view"
import topbar from "../vendor/topbar"
import hooks from './hooks'

let csrfToken = document.querySelector("meta[name='csrf-token']").getAttribute("content")
let liveSocket = new LiveSocket("/live", Socket, {hooks, params: {_csrf_token: csrfToken}})

// Show progress bar on live navigation and form submits
topbar.config({barColors: {0: "#29d"}, shadowColor: "rgba(0, 0, 0, .3)"})
window.addEventListener("phx:page-loading-start", _info => topbar.show(300))
window.addEventListener("phx:page-loading-stop", _info => topbar.hide())

// connect if there are any LiveViews on the page
liveSocket.connect()

// expose liveSocket on window for web console debug logs and latency simulation:
// >> liveSocket.enableDebug()
// >> liveSocket.enableLatencySim(1000) // enabled for duration of browser session
// >> liveSocket.disableLatencySim()
window.liveSocket = liveSocket

62 changes: 62 additions & 0 deletions assets/js/hooks.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
import * as Components from '../svelte/components/**/*'

let { default: modules, filenames } = Components

filenames = filenames
.map(name => name.replace('../svelte/components/', ''))
.map(name => name.replace('.svelte', ''))

components = Object.assign({}, ...modules.map((m, index) => ({[filenames[index]]: m.default})))

function parsedProps(el) {
const props = el.getAttribute('data-props')
return props ? JSON.parse(props) : {}
}

const SvelteComponent = {
mounted() {
const componentName = this.el.getAttribute('data-name')
if (!componentName) {
throw new Error('Component name must be provided')
}

const requiredApp = components[componentName]
if (!requiredApp) {
throw new Error(`Unable to find ${componentName} component. Did you forget to import it into hooks.js?`)
}

const pushEvent = (event, data, callback) => {
this.pushEvent(event, data, callback)
}

const goto = href => {
liveSocket.pushHistoryPatch(href, 'push', this.el)
}

this._instance = new requiredApp({
target: this.el,
props: {...parsedProps(this.el), pushEvent, goto},
hydrate: true
})
},

updated() {
const pushEvent = (event, data, callback) => {
this.pushEvent(event, data, callback)
}

const goto = href => {
liveSocket.pushHistoryPatch(href, 'push', this.el)
}

this._instance.$$set({...parsedProps(this.el), pushEvent, goto})
},

destroyed() {
this._instance?.$destroy()
}
}

export default {
SvelteComponent
}
9 changes: 9 additions & 0 deletions assets/js/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import * as Components from '../svelte/components/**/*'

let { default: modules, filenames } = Components

filenames = filenames
.map(name => name.replace('../svelte/components/', ''))
.map(name => name.replace('.svelte', ''))

module.exports = Object.assign({}, ...modules.map((m, index) => ({[filenames[index]]: m.default})))
18 changes: 18 additions & 0 deletions assets/svelte/components/Example.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<script>
export let number = 1;
export let pushEvent;
function increase() {
pushEvent('set_number', { number: number + 1 })
}
function decrease() {
pushEvent('set_number', { number: number - 1 })
}
</script>

<h1 class="text-red">Component is working</h1>
<p>The number is {number}</p>

<button on:click={increase}>+</button>
<button on:click={decrease}>-</button>
4 changes: 4 additions & 0 deletions assets/svelte/render.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
module.exports.render = (name, props={}) => {
const ssrComponent = require('../../priv/static/assets/server/server.js')[name].default
return ssrComponent.render(props)
}
Loading

0 comments on commit 9102bcf

Please sign in to comment.