forked from woutdp/live_svelte
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit 9102bcf
Showing
23 changed files
with
755 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}"] | ||
] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() | ||
}) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}))) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |
Oops, something went wrong.