Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Complete the view, liveview, esbuild and tailwind integration #392

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 5 additions & 3 deletions .formatter.exs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
[
inputs: ["*.exs", "{config,lib,priv,rel,test}/**/*.{ex,exs}"],
line_length: 180,
plugins: [Styler]
import_deps: [:ecto, :ecto_sql, :phoenix],
subdirectories: ["priv/*/migrations"],
plugins: [Phoenix.LiveView.HTMLFormatter],
inputs: ["*.{heex,ex,exs}", "{config,lib,test}/**/*.{heex,ex,exs}", "priv/*/seeds.exs"],
line_length: 180
]
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
/db
/deps
/*.ez
/cover

# Temporary files
/tmp
/cover

# Generated on crash by the VM
erl_crash.dump
Expand Down
3 changes: 3 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,9 @@ ENV MIX_ENV="prod"
COPY mix.exs mix.lock ./
RUN mix deps.get --only $MIX_ENV

# Setup assets dependencies (Esbuild, Tailwind, etc…) so the are cached
RUN mix assets.setup

# Copy compile-time config files before we compile dependencies
# to ensure any relevant config change will trigger the dependencies
# to be re-compiled.
Expand Down
46 changes: 3 additions & 43 deletions assets/css/app.css
Original file line number Diff line number Diff line change
@@ -1,43 +1,3 @@
.home {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
padding: 40px;
text-align: center;
font-family:
system-ui,
-apple-system,
'Segoe UI',
Roboto,
'Helvetica Neue',
Arial,
'Noto Sans',
'Liberation Sans',
sans-serif,
'Apple Color Emoji',
'Segoe UI Emoji',
'Segoe UI Symbol',
'Noto Color Emoji';
line-height: 1.4;
}

.home a {
display: block;
margin: 0 0 20px;
}

.home p {
margin: 0 0 20px;
}

.home p:last-child {
margin-bottom: 0;
}

.flash-messages {
position: fixed;
top: 0;
right: 0;
padding: 10px;
}
@import 'tailwindcss/base';
@import 'tailwindcss/components';
@import 'tailwindcss/utilities';
36 changes: 10 additions & 26 deletions assets/js/app.js
Original file line number Diff line number Diff line change
@@ -1,38 +1,22 @@
import 'simple-css-reset/reset.css';
import '../css/app.css';
// 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';

const FLASH_TTL = 8000;
const Hooks = {};

Hooks.Flash = {
mounted() {
this.timer = setTimeout(() => this._hide(), FLASH_TTL);

this.el.addEventListener('mouseover', () => {
clearTimeout(this.timer);
this.timer = setTimeout(() => this._hide(), FLASH_TTL);
});
},

destroyed() {
clearTimeout(this.timer);
},

_hide() {
liveSocket.execJS(this.el, this.el.getAttribute('phx-click'));
}
};

const csrfToken = document
.querySelector("meta[name='csrf-token']")
.getAttribute('content');

const liveSocket = new LiveSocket('/live', Socket, {
hooks: Hooks,
params: {_csrf_token: csrfToken} // eslint-disable-line camelcase
});

// 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;
30 changes: 4 additions & 26 deletions assets/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 0 additions & 6 deletions assets/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,6 @@
"node": "^20.5.0",
"npm": "^9.8.0"
},
"dependencies": {
"phoenix": "^1.7.7",
"phoenix_html": "^3.3.1",
"phoenix_live_view": "^0.20.5",
"simple-css-reset": "^3.0.0"
},
"devDependencies": {
"@babel/eslint-parser": "^7.23.10",
"eslint": "^8.56.0",
Expand Down
99 changes: 99 additions & 0 deletions assets/tailwind.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
/* eslint-env node */

// See the Tailwind configuration guide for advanced usage
// https://tailwindcss.com/docs/configuration

const plugin = require('tailwindcss/plugin');
// const fs = require('fs');
// const path = require('path');

module.exports = {
content: ['./js/**/*.js', '../lib/*_web.ex', '../lib/*_web/**/*.*ex'],
theme: {
extend: {
colors: {
brand: '#FD4F00'
}
}
},
plugins: [
require('@tailwindcss/forms'),
// Allows prefixing tailwind classes with LiveView classes to add rules
// only when LiveView classes are applied, for example:
//
// <div class="phx-click-loading:animate-ping">
//
plugin(({addVariant}) =>
addVariant('phx-no-feedback', ['.phx-no-feedback&', '.phx-no-feedback &'])
),
plugin(({addVariant}) =>
addVariant('phx-click-loading', [
'.phx-click-loading&',
'.phx-click-loading &'
])
),
plugin(({addVariant}) =>
addVariant('phx-submit-loading', [
'.phx-submit-loading&',
'.phx-submit-loading &'
])
),
plugin(({addVariant}) =>
addVariant('phx-change-loading', [
'.phx-change-loading&',
'.phx-change-loading &'
])
),
plugin(({addVariant}) =>
addVariant('phx-change-loading', [
'.phx-change-loading&',
'.phx-change-loading &'
])
)

// Embeds Heroicons (https://heroicons.com) into your app.css bundle
// See your `CoreComponents.icon/1` for more information.
// plugin(({matchComponents, theme}) => {
// const iconsDir = path.join(__dirname, './vendor/heroicons/optimized');
// const values = {};
// const icons = [
// ['', '/24/outline'],
// ['-solid', '/24/solid'],
// ['-mini', '/20/solid']
// ];

// /* eslint max-nested-callbacks: ["error", 3] */
// icons.forEach(([suffix, dir]) => {
// fs.readdirSync(path.join(iconsDir, dir)).map((file) => {
// const name = path.basename(file, '.svg') + suffix;

// values[name] = {name, fullPath: path.join(iconsDir, dir, file)};
// });
// });

// matchComponents(
// {
// hero: ({name, fullPath}) => {
// const content = fs
// .readFileSync(fullPath)
// .toString()
// .replace(/\r?\n|\r/g, '');

// return {
// [`--hero-${name}`]: `url('data:image/svg+xml;utf8,${content}')`,
// '-webkit-mask': `var(--hero-${name})`,
// mask: `var(--hero-${name})`,
// 'mask-repeat': 'no-repeat',
// 'background-color': 'currentColor',
// 'vertical-align': 'middle',
// display: 'inline-block',
// width: theme('spacing.5'),
// height: theme('spacing.5')
// };
// }
// },
// {values}
// );
// })
]
};
20 changes: 17 additions & 3 deletions config/config.exs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,10 @@ config :phoenix, :json_library, Jason

config :elixir_boilerplate, ElixirBoilerplateWeb.Endpoint,
pubsub_server: ElixirBoilerplate.PubSub,
render_errors: [view: ElixirBoilerplateWeb.Errors, accepts: ~w(html json)]
render_errors: [
formats: [html: ElixirBoilerplateWeb.Controllers.ErrorHTML, json: ElixirBoilerplateWeb.Controllers.ErrorJSON],
layout: false
]

config :elixir_boilerplate, ElixirBoilerplate.Repo,
migration_primary_key: [type: :binary_id, default: {:fragment, "gen_random_uuid()"}],
Expand All @@ -30,13 +33,24 @@ config :absinthe_security, AbsintheSecurity.Phase.MaxDepthCheck, max_depth_count
config :absinthe_security, AbsintheSecurity.Phase.MaxDirectivesCheck, max_directive_count: 100

config :esbuild,
version: "0.16.4",
version: "0.17.11",
default: [
args: ~w(js/app.js --bundle --target=es2016 --outdir=../priv/static/assets),
args: ~w(js/app.js --bundle --target=es2017 --outdir=../priv/static/assets --external:/fonts/* --external:/images/*),
cd: Path.expand("../assets", __DIR__),
env: %{"NODE_PATH" => Path.expand("../deps", __DIR__)}
]

config :tailwind,
version: "3.2.7",
default: [
args: ~w(
--config=tailwind.config.js
--input=css/app.css
--output=../priv/static/assets/app.css
),
cd: Path.expand("../assets", __DIR__)
]

config :sentry,
included_environments: [:all],
root_source_code_path: File.cwd!(),
Expand Down
12 changes: 8 additions & 4 deletions config/dev.exs
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ config :elixir_boilerplate, ElixirBoilerplateWeb.Endpoint,
debug_errors: true,
check_origin: false,
watchers: [
esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]}
esbuild: {Esbuild, :install_and_run, [:default, ~w(--sourcemap=inline --watch)]},
tailwind: {Tailwind, :install_and_run, [:default, ~w(--watch)]}
],
live_reload: [
patterns: [
~r{priv/gettext/.*$},
~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
~r{lib/elixir_boilerplate_web/.*(ee?x)$}
~r"priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$",
~r"priv/gettext/.*(po)$",
~r"lib/elixir_boilerplate_web/../.*(ex|heex)$"
]
]

Expand All @@ -21,3 +22,6 @@ config :logger, :console, format: "[$level] $message\n"

config :phoenix, :stacktrace_depth, 20
config :phoenix, :plug_init_mode, :runtime

# Enable dev routes for dashboard and mailbox
config :elixir_boilerplate, dev_routes: true
3 changes: 3 additions & 0 deletions config/prod.exs
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,6 @@ config :logger, :console,
format: "$time $metadata[$level] $message\n",
level: :info,
metadata: ~w(request_id graphql_operation_name)a

# Runtime production configuration, including reading
# of environment variables, is done on config/runtime.exs.
5 changes: 4 additions & 1 deletion config/runtime.exs
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@ if get_env("PHX_SERVER", :boolean) == true do
config :elixir_boilerplate, ElixirBoilerplateWeb.Endpoint, server: true
end

config :elixir_boilerplate, ElixirBoilerplateWeb.Session,
session_key: get_env!("SESSION_KEY"),
session_signing_salt: get_env!("SESSION_SIGNING_SALT")

config :elixir_boilerplate, ElixirBoilerplateWeb.Endpoint,
http: [port: get_env!("PORT", :integer)],
secret_key_base: get_env!("SECRET_KEY_BASE"),
session_key: get_env!("SESSION_KEY"),
session_signing_salt: get_env!("SESSION_SIGNING_SALT"),
live_view: [signing_salt: get_env!("SESSION_SIGNING_SALT")],
url: get_endpoint_url_config(canonical_uri),
static_url: get_endpoint_url_config(static_uri)
Expand Down
8 changes: 8 additions & 0 deletions lib/elixir_boilerplate_web/api/version/controller.ex
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
defmodule ElixirBoilerplateWeb.Api.Version.Controller do
use ElixirBoilerplateWeb.Controller

@spec index(Plug.Conn.t(), map) :: Plug.Conn.t()
def index(conn, _) do
json(conn, %{version: Application.get_env(:elixir_boilerplate, :version)})
end
end
Loading