├── web
├── static
│ ├── css
│ │ ├── app.css
│ │ ├── prism.css
│ │ └── phoenix.css
│ ├── assets
│ │ ├── favicon.ico
│ │ ├── images
│ │ │ └── phoenix.png
│ │ └── robots.txt
│ ├── js
│ │ ├── app.js
│ │ └── socket.js
│ └── vendor
│ │ └── prism.js
├── views
│ ├── layout_view.ex
│ ├── page_view.ex
│ ├── error_view.ex
│ └── error_helpers.ex
├── controllers
│ └── page_controller.ex
├── router.ex
├── gettext.ex
├── templates
│ ├── page
│ │ └── index.html.eex
│ └── layout
│ │ └── app.html.eex
├── channels
│ └── user_socket.ex
└── web.ex
├── lib
├── blogex
│ ├── repo.ex
│ └── endpoint.ex
├── post_renderer.ex
├── blogex.ex
└── prism_renderer.ex
├── test
├── test_helper.exs
├── views
│ ├── page_view_test.exs
│ ├── layout_view_test.exs
│ └── error_view_test.exs
├── controllers
│ └── page_controller_test.exs
└── support
│ ├── channel_case.ex
│ ├── conn_case.ex
│ └── model_case.ex
├── posts
├── something.md
└── piping.md
├── priv
├── repo
│ └── seeds.exs
└── gettext
│ ├── en
│ └── LC_MESSAGES
│ │ └── errors.po
│ └── errors.pot
├── package.json
├── config
├── test.exs
├── config.exs
├── dev.exs
└── prod.exs
├── .gitignore
├── README.md
├── brunch-config.js
├── mix.exs
└── mix.lock
/web/static/css/app.css:
--------------------------------------------------------------------------------
1 | /* This file is for your main application css. */
--------------------------------------------------------------------------------
/lib/blogex/repo.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.Repo do
2 | use Ecto.Repo, otp_app: :blogex
3 | end
4 |
--------------------------------------------------------------------------------
/web/views/layout_view.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.LayoutView do
2 | use Blogex.Web, :view
3 | end
4 |
--------------------------------------------------------------------------------
/test/test_helper.exs:
--------------------------------------------------------------------------------
1 | ExUnit.start
2 |
3 | Ecto.Adapters.SQL.Sandbox.mode(Blogex.Repo, :manual)
4 |
5 |
--------------------------------------------------------------------------------
/test/views/page_view_test.exs:
--------------------------------------------------------------------------------
1 | defmodule Blogex.PageViewTest do
2 | use Blogex.ConnCase, async: true
3 | end
4 |
--------------------------------------------------------------------------------
/test/views/layout_view_test.exs:
--------------------------------------------------------------------------------
1 | defmodule Blogex.LayoutViewTest do
2 | use Blogex.ConnCase, async: true
3 | end
4 |
--------------------------------------------------------------------------------
/web/static/assets/favicon.ico:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/campezzi/elixir-metaprogramming-example/HEAD/web/static/assets/favicon.ico
--------------------------------------------------------------------------------
/web/static/assets/images/phoenix.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/campezzi/elixir-metaprogramming-example/HEAD/web/static/assets/images/phoenix.png
--------------------------------------------------------------------------------
/posts/something.md:
--------------------------------------------------------------------------------
1 | # Some post title
2 | [This](http://google.com) has support for `Markdown` syntax. _Cool, isn't it?_
3 |
4 | ```elixir
5 | def something do
6 | "Hello, World!"
7 | end
8 | ```
9 |
--------------------------------------------------------------------------------
/web/views/page_view.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.PageView do
2 | use Blogex.Web, :view
3 | alias Blogex.PostRenderer
4 |
5 | def render("post.html", %{post: post}) do
6 | PostRenderer.render("#{post}.md")
7 | end
8 | end
9 |
--------------------------------------------------------------------------------
/web/static/assets/robots.txt:
--------------------------------------------------------------------------------
1 | # See http://www.robotstxt.org/robotstxt.html for documentation on how to use the robots.txt file
2 | #
3 | # To ban all spiders from the entire site uncomment the next two lines:
4 | # User-agent: *
5 | # Disallow: /
6 |
--------------------------------------------------------------------------------
/test/controllers/page_controller_test.exs:
--------------------------------------------------------------------------------
1 | defmodule Blogex.PageControllerTest do
2 | use Blogex.ConnCase
3 |
4 | test "GET /", %{conn: conn} do
5 | conn = get conn, "/"
6 | assert html_response(conn, 200) =~ "Welcome to Phoenix!"
7 | end
8 | end
9 |
--------------------------------------------------------------------------------
/web/controllers/page_controller.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.PageController do
2 | use Blogex.Web, :controller
3 |
4 | def index(conn, _params) do
5 | text(conn, "Nothing to see here!")
6 | end
7 |
8 | def post(conn, %{"post" => post}) do
9 | render(conn, "post.html", post: post)
10 | end
11 | end
12 |
--------------------------------------------------------------------------------
/priv/repo/seeds.exs:
--------------------------------------------------------------------------------
1 | # Script for populating the database. You can run it as:
2 | #
3 | # mix run priv/repo/seeds.exs
4 | #
5 | # Inside the script, you can read and write to any of your
6 | # repositories directly:
7 | #
8 | # Blogex.Repo.insert!(%Blogex.SomeModel{})
9 | #
10 | # We recommend using the bang functions (`insert!`, `update!`
11 | # and so on) as they will fail if something goes wrong.
12 |
--------------------------------------------------------------------------------
/web/views/error_view.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.ErrorView do
2 | use Blogex.Web, :view
3 |
4 | def render("404.html", _assigns) do
5 | "Page not found"
6 | end
7 |
8 | def render("500.html", _assigns) do
9 | "Internal server error"
10 | end
11 |
12 | # In case no render clause matches or no
13 | # template is found, let's render it as 500
14 | def template_not_found(_template, assigns) do
15 | render "500.html", assigns
16 | end
17 | end
18 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "repository": {},
3 | "license": "MIT",
4 | "scripts": {
5 | "deploy": "brunch build --production",
6 | "watch": "brunch watch --stdin"
7 | },
8 | "dependencies": {
9 | "phoenix": "file:deps/phoenix",
10 | "phoenix_html": "file:deps/phoenix_html"
11 | },
12 | "devDependencies": {
13 | "babel-brunch": "~6.0.0",
14 | "brunch": "2.7.4",
15 | "clean-css-brunch": "~2.0.0",
16 | "css-brunch": "~2.0.0",
17 | "javascript-brunch": "~2.0.0",
18 | "uglify-js-brunch": "~2.0.1"
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/config/test.exs:
--------------------------------------------------------------------------------
1 | use Mix.Config
2 |
3 | # We don't run a server during test. If one is required,
4 | # you can enable the server option below.
5 | config :blogex, Blogex.Endpoint,
6 | http: [port: 4001],
7 | server: false
8 |
9 | # Print only warnings and errors during test
10 | config :logger, level: :warn
11 |
12 | # Configure your database
13 | config :blogex, Blogex.Repo,
14 | adapter: Ecto.Adapters.Postgres,
15 | username: "postgres",
16 | password: "postgres",
17 | database: "blogex_test",
18 | hostname: "localhost",
19 | pool: Ecto.Adapters.SQL.Sandbox
20 |
--------------------------------------------------------------------------------
/lib/post_renderer.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.PostRenderer do
2 | require Blogex.PrismRenderer
3 | alias Earmark.Options
4 |
5 | posts_directory = "./posts"
6 |
7 | render_file = fn file ->
8 | "#{posts_directory}/#{file}"
9 | |> File.read!
10 | |> Earmark.to_html(%Options{renderer: Blogex.PrismRenderer})
11 | |> (&{:safe, &1}).()
12 | end
13 |
14 | posts_directory
15 | |> File.ls!
16 | |> Enum.map(&Task.async(fn -> def render(unquote(&1)), do: unquote(render_file.(&1)) end))
17 | |> Enum.map(&Task.await(&1))
18 |
19 | def render(_), do: raise(ArgumentError)
20 | end
21 |
--------------------------------------------------------------------------------
/web/router.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.Router do
2 | use Blogex.Web, :router
3 |
4 | pipeline :browser do
5 | plug :accepts, ["html"]
6 | plug :fetch_session
7 | plug :fetch_flash
8 | plug :protect_from_forgery
9 | plug :put_secure_browser_headers
10 | end
11 |
12 | pipeline :api do
13 | plug :accepts, ["json"]
14 | end
15 |
16 | scope "/", Blogex do
17 | pipe_through :browser # Use the default browser stack
18 |
19 | get "/", PageController, :index
20 | get "/:post", PageController, :post
21 | end
22 |
23 | # Other scopes may use custom stacks.
24 | # scope "/api", Blogex do
25 | # pipe_through :api
26 | # end
27 | end
28 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | # App artifacts
2 | /_build
3 | /db
4 | /deps
5 | /*.ez
6 |
7 | # Generated on crash by the VM
8 | erl_crash.dump
9 |
10 | # Static artifacts
11 | /node_modules
12 |
13 | # Since we are building assets from web/static,
14 | # we ignore priv/static. You may want to comment
15 | # this depending on your deployment strategy.
16 | /priv/static/
17 |
18 | # The config/prod.secret.exs file by default contains sensitive
19 | # data and you should not commit it into version control.
20 | #
21 | # Alternatively, you may comment the line below and commit the
22 | # secrets file as long as you replace its contents by environment
23 | # variables.
24 | /config/prod.secret.exs
25 |
--------------------------------------------------------------------------------
/test/views/error_view_test.exs:
--------------------------------------------------------------------------------
1 | defmodule Blogex.ErrorViewTest do
2 | use Blogex.ConnCase, async: true
3 |
4 | # Bring render/3 and render_to_string/3 for testing custom views
5 | import Phoenix.View
6 |
7 | test "renders 404.html" do
8 | assert render_to_string(Blogex.ErrorView, "404.html", []) ==
9 | "Page not found"
10 | end
11 |
12 | test "render 500.html" do
13 | assert render_to_string(Blogex.ErrorView, "500.html", []) ==
14 | "Internal server error"
15 | end
16 |
17 | test "render any other" do
18 | assert render_to_string(Blogex.ErrorView, "505.html", []) ==
19 | "Internal server error"
20 | end
21 | end
22 |
--------------------------------------------------------------------------------
/web/static/js/app.js:
--------------------------------------------------------------------------------
1 | // Brunch automatically concatenates all files in your
2 | // watched paths. Those paths can be configured at
3 | // config.paths.watched in "brunch-config.js".
4 | //
5 | // However, those files will only be executed if
6 | // explicitly imported. The only exception are files
7 | // in vendor, which are never wrapped in imports and
8 | // therefore are always executed.
9 |
10 | // Import dependencies
11 | //
12 | // If you no longer want to use a dependency, remember
13 | // to also remove its path from "config.paths.watched".
14 | import "phoenix_html"
15 |
16 | // Import local files
17 | //
18 | // Local files can be imported directly using relative
19 | // paths "./socket" or full ones "web/static/js/socket".
20 |
21 | // import socket from "./socket"
22 |
--------------------------------------------------------------------------------
/web/gettext.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.Gettext do
2 | @moduledoc """
3 | A module providing Internationalization with a gettext-based API.
4 |
5 | By using [Gettext](https://hexdocs.pm/gettext),
6 | your module gains a set of macros for translations, for example:
7 |
8 | import Blogex.Gettext
9 |
10 | # Simple translation
11 | gettext "Here is the string to translate"
12 |
13 | # Plural translation
14 | ngettext "Here is the string to translate",
15 | "Here are the strings to translate",
16 | 3
17 |
18 | # Domain-based translation
19 | dgettext "errors", "Here is the error message to translate"
20 |
21 | See the [Gettext Docs](https://hexdocs.pm/gettext) for detailed usage.
22 | """
23 | use Gettext, otp_app: :blogex
24 | end
25 |
--------------------------------------------------------------------------------
/config/config.exs:
--------------------------------------------------------------------------------
1 | # This file is responsible for configuring your application
2 | # and its dependencies with the aid of the Mix.Config module.
3 | #
4 | # This configuration file is loaded before any dependency and
5 | # is restricted to this project.
6 | use Mix.Config
7 |
8 | # General application configuration
9 | config :blogex,
10 | ecto_repos: [Blogex.Repo]
11 |
12 | # Configures the endpoint
13 | config :blogex, Blogex.Endpoint,
14 | url: [host: "localhost"],
15 | secret_key_base: "dFU9Qn4QB73DIlrlHKlJCZ9Zp2CZOAcwCR1vttBQCUY39TqAp0Qaj7K4dwR0AW8r",
16 | render_errors: [view: Blogex.ErrorView, accepts: ~w(html json)],
17 | pubsub: [name: Blogex.PubSub,
18 | adapter: Phoenix.PubSub.PG2]
19 |
20 | # Configures Elixir's Logger
21 | config :logger, :console,
22 | format: "$time $metadata[$level] $message\n",
23 | metadata: [:request_id]
24 |
25 | # Import environment specific config. This must remain at the bottom
26 | # of this file so it overrides the configuration defined above.
27 | import_config "#{Mix.env}.exs"
28 |
--------------------------------------------------------------------------------
/web/templates/page/index.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
<%= gettext "Welcome to %{name}", name: "Phoenix!" %>
3 |
A productive web framework that does not compromise speed and maintainability.
4 |
5 |
6 |
37 |
--------------------------------------------------------------------------------
/lib/blogex.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex do
2 | use Application
3 |
4 | # See http://elixir-lang.org/docs/stable/elixir/Application.html
5 | # for more information on OTP Applications
6 | def start(_type, _args) do
7 | import Supervisor.Spec
8 |
9 | # Define workers and child supervisors to be supervised
10 | children = [
11 | # Start the Ecto repository
12 | # supervisor(Blogex.Repo, []),
13 | # Start the endpoint when the application starts
14 | supervisor(Blogex.Endpoint, []),
15 | # Start your own worker by calling: Blogex.Worker.start_link(arg1, arg2, arg3)
16 | # worker(Blogex.Worker, [arg1, arg2, arg3]),
17 | ]
18 |
19 | # See http://elixir-lang.org/docs/stable/elixir/Supervisor.html
20 | # for other strategies and supported options
21 | opts = [strategy: :one_for_one, name: Blogex.Supervisor]
22 | Supervisor.start_link(children, opts)
23 | end
24 |
25 | # Tell Phoenix to update the endpoint configuration
26 | # whenever the application is updated.
27 | def config_change(changed, _new, removed) do
28 | Blogex.Endpoint.config_change(changed, removed)
29 | :ok
30 | end
31 | end
32 |
--------------------------------------------------------------------------------
/test/support/channel_case.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.ChannelCase do
2 | @moduledoc """
3 | This module defines the test case to be used by
4 | channel tests.
5 |
6 | Such tests rely on `Phoenix.ChannelTest` and also
7 | import other functionality to make it easier
8 | to build and query models.
9 |
10 | Finally, if the test case interacts with the database,
11 | it cannot be async. For this reason, every test runs
12 | inside a transaction which is reset at the beginning
13 | of the test unless the test case is marked as async.
14 | """
15 |
16 | use ExUnit.CaseTemplate
17 |
18 | using do
19 | quote do
20 | # Import conveniences for testing with channels
21 | use Phoenix.ChannelTest
22 |
23 | alias Blogex.Repo
24 | import Ecto
25 | import Ecto.Changeset
26 | import Ecto.Query
27 |
28 |
29 | # The default endpoint for testing
30 | @endpoint Blogex.Endpoint
31 | end
32 | end
33 |
34 | setup tags do
35 | :ok = Ecto.Adapters.SQL.Sandbox.checkout(Blogex.Repo)
36 |
37 | unless tags[:async] do
38 | Ecto.Adapters.SQL.Sandbox.mode(Blogex.Repo, {:shared, self()})
39 | end
40 |
41 | :ok
42 | end
43 | end
44 |
--------------------------------------------------------------------------------
/web/templates/layout/app.html.eex:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 | Hello Blogex!
11 | ">
12 |
13 |
14 |
15 |
16 |
24 |
25 |
<%= get_flash(@conn, :info) %>
26 |
<%= get_flash(@conn, :error) %>
27 |
28 |
29 | <%= render @view_module, @view_template, assigns %>
30 |
31 |
32 |
33 |
34 |
35 |
36 |
--------------------------------------------------------------------------------
/test/support/conn_case.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.ConnCase do
2 | @moduledoc """
3 | This module defines the test case to be used by
4 | tests that require setting up a connection.
5 |
6 | Such tests rely on `Phoenix.ConnTest` and also
7 | import other functionality to make it easier
8 | to build and query models.
9 |
10 | Finally, if the test case interacts with the database,
11 | it cannot be async. For this reason, every test runs
12 | inside a transaction which is reset at the beginning
13 | of the test unless the test case is marked as async.
14 | """
15 |
16 | use ExUnit.CaseTemplate
17 |
18 | using do
19 | quote do
20 | # Import conveniences for testing with connections
21 | use Phoenix.ConnTest
22 |
23 | alias Blogex.Repo
24 | import Ecto
25 | import Ecto.Changeset
26 | import Ecto.Query
27 |
28 | import Blogex.Router.Helpers
29 |
30 | # The default endpoint for testing
31 | @endpoint Blogex.Endpoint
32 | end
33 | end
34 |
35 | setup tags do
36 | :ok = Ecto.Adapters.SQL.Sandbox.checkout(Blogex.Repo)
37 |
38 | unless tags[:async] do
39 | Ecto.Adapters.SQL.Sandbox.mode(Blogex.Repo, {:shared, self()})
40 | end
41 |
42 | {:ok, conn: Phoenix.ConnTest.build_conn()}
43 | end
44 | end
45 |
--------------------------------------------------------------------------------
/web/channels/user_socket.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.UserSocket do
2 | use Phoenix.Socket
3 |
4 | ## Channels
5 | # channel "room:*", Blogex.RoomChannel
6 |
7 | ## Transports
8 | transport :websocket, Phoenix.Transports.WebSocket
9 | # transport :longpoll, Phoenix.Transports.LongPoll
10 |
11 | # Socket params are passed from the client and can
12 | # be used to verify and authenticate a user. After
13 | # verification, you can put default assigns into
14 | # the socket that will be set for all channels, ie
15 | #
16 | # {:ok, assign(socket, :user_id, verified_user_id)}
17 | #
18 | # To deny connection, return `:error`.
19 | #
20 | # See `Phoenix.Token` documentation for examples in
21 | # performing token verification on connect.
22 | def connect(_params, socket) do
23 | {:ok, socket}
24 | end
25 |
26 | # Socket id's are topics that allow you to identify all sockets for a given user:
27 | #
28 | # def id(socket), do: "users_socket:#{socket.assigns.user_id}"
29 | #
30 | # Would allow you to broadcast a "disconnect" event and terminate
31 | # all active sockets and channels for a given user:
32 | #
33 | # Blogex.Endpoint.broadcast("users_socket:#{user.id}", "disconnect", %{})
34 | #
35 | # Returning `nil` makes this socket anonymous.
36 | def id(_socket), do: nil
37 | end
38 |
--------------------------------------------------------------------------------
/lib/blogex/endpoint.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.Endpoint do
2 | use Phoenix.Endpoint, otp_app: :blogex
3 |
4 | socket "/socket", Blogex.UserSocket
5 |
6 | # Serve at "/" the static files from "priv/static" directory.
7 | #
8 | # You should set gzip to true if you are running phoenix.digest
9 | # when deploying your static files in production.
10 | plug Plug.Static,
11 | at: "/", from: :blogex, gzip: false,
12 | only: ~w(css fonts images js favicon.ico robots.txt)
13 |
14 | # Code reloading can be explicitly enabled under the
15 | # :code_reloader configuration of your endpoint.
16 | if code_reloading? do
17 | socket "/phoenix/live_reload/socket", Phoenix.LiveReloader.Socket
18 | plug Phoenix.LiveReloader
19 | plug Phoenix.CodeReloader
20 | end
21 |
22 | plug Plug.RequestId
23 | plug Plug.Logger
24 |
25 | plug Plug.Parsers,
26 | parsers: [:urlencoded, :multipart, :json],
27 | pass: ["*/*"],
28 | json_decoder: Poison
29 |
30 | plug Plug.MethodOverride
31 | plug Plug.Head
32 |
33 | # The session will be stored in the cookie and signed,
34 | # this means its contents can be read but not tampered with.
35 | # Set :encryption_salt if you would also like to encrypt it.
36 | plug Plug.Session,
37 | store: :cookie,
38 | key: "_blogex_key",
39 | signing_salt: "iXaXxD57"
40 |
41 | plug Blogex.Router
42 | end
43 |
--------------------------------------------------------------------------------
/web/views/error_helpers.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.ErrorHelpers do
2 | @moduledoc """
3 | Conveniences for translating and building error messages.
4 | """
5 |
6 | use Phoenix.HTML
7 |
8 | @doc """
9 | Generates tag for inlined form input errors.
10 | """
11 | def error_tag(form, field) do
12 | if error = form.errors[field] do
13 | content_tag :span, translate_error(error), class: "help-block"
14 | end
15 | end
16 |
17 | @doc """
18 | Translates an error message using gettext.
19 | """
20 | def translate_error({msg, opts}) do
21 | # Because error messages were defined within Ecto, we must
22 | # call the Gettext module passing our Gettext backend. We
23 | # also use the "errors" domain as translations are placed
24 | # in the errors.po file.
25 | # Ecto will pass the :count keyword if the error message is
26 | # meant to be pluralized.
27 | # On your own code and templates, depending on whether you
28 | # need the message to be pluralized or not, this could be
29 | # written simply as:
30 | #
31 | # dngettext "errors", "1 file", "%{count} files", count
32 | # dgettext "errors", "is invalid"
33 | #
34 | if count = opts[:count] do
35 | Gettext.dngettext(Blogex.Gettext, "errors", msg, msg, count, opts)
36 | else
37 | Gettext.dgettext(Blogex.Gettext, "errors", msg, opts)
38 | end
39 | end
40 | end
41 |
--------------------------------------------------------------------------------
/config/dev.exs:
--------------------------------------------------------------------------------
1 | use Mix.Config
2 |
3 | # For development, we disable any cache and enable
4 | # debugging and code reloading.
5 | #
6 | # The watchers configuration can be used to run external
7 | # watchers to your application. For example, we use it
8 | # with brunch.io to recompile .js and .css sources.
9 | config :blogex, Blogex.Endpoint,
10 | http: [port: 4000],
11 | debug_errors: true,
12 | code_reloader: true,
13 | check_origin: false,
14 | watchers: [node: ["node_modules/brunch/bin/brunch", "watch", "--stdin",
15 | cd: Path.expand("../", __DIR__)]]
16 |
17 |
18 | # Watch static and templates for browser reloading.
19 | config :blogex, Blogex.Endpoint,
20 | live_reload: [
21 | patterns: [
22 | ~r{priv/static/.*(js|css|png|jpeg|jpg|gif|svg)$},
23 | ~r{priv/gettext/.*(po)$},
24 | ~r{web/views/.*(ex)$},
25 | ~r{web/templates/.*(eex)$}
26 | ]
27 | ]
28 |
29 | # Do not include metadata nor timestamps in development logs
30 | config :logger, :console, format: "[$level] $message\n"
31 |
32 | # Set a higher stacktrace during development. Avoid configuring such
33 | # in production as building large stacktraces may be expensive.
34 | config :phoenix, :stacktrace_depth, 20
35 |
36 | # Configure your database
37 | config :blogex, Blogex.Repo,
38 | adapter: Ecto.Adapters.Postgres,
39 | username: "postgres",
40 | password: "postgres",
41 | database: "blogex_dev",
42 | hostname: "localhost",
43 | pool_size: 10
44 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Blogex
2 |
3 | This is a fun experiment to demonstrate what can be achieved with the Elixir macro system. It's
4 | a rudimentary blogging system - posts are simple Markdown files stored in the `posts` folder.
5 |
6 | Visiting `/some_post_title` will eventually cause the `PageView` module to call
7 | `PostRenderer.render("some_post_title.md")`. Now, here's the fun part - that function has been
8 | defined with a macro in the `PostRenderer` module. At compile time, we go through every file in the
9 | `posts` folder, render it to HTML, and then define a pattern-matched function that simply returns
10 | the result of the render for the given filename. At runtime, calling the `render` function has the
11 | performance cost of returning a constant (AKA blazing fast).
12 |
13 | *New:* posts are now rendered from Markdown into HTML concurrently, courtesy of `Task.async`. Great
14 | performance at runtime _and_ faster compile times? Yes please :)
15 |
16 | This silly example will just raise an error when trying to render a post that doesn't exist in the
17 | `posts` folder, but you get my point. A quick note in case you try playing around with posts: when
18 | you create a new post or modify an existing one, you'll need to stop the Phoenix server and run
19 | `mix do clean, compile` so the macro gets a chance to run again. That could potentially be avoided
20 | with the `@external_resource` module attribute, but I haven't tried using it.
21 |
22 |
23 | ## Running
24 |
25 | To start your Phoenix app:
26 |
27 | * Install dependencies with `mix deps.get`
28 | * Create and migrate your database with `mix ecto.create && mix ecto.migrate`
29 | * Install Node.js dependencies with `npm install`
30 | * Start Phoenix endpoint with `mix phoenix.server`
31 | * Visit [a sample blog post](http://localhost:4000/piping)
32 |
--------------------------------------------------------------------------------
/brunch-config.js:
--------------------------------------------------------------------------------
1 | exports.config = {
2 | // See http://brunch.io/#documentation for docs.
3 | files: {
4 | javascripts: {
5 | joinTo: "js/app.js"
6 |
7 | // To use a separate vendor.js bundle, specify two files path
8 | // http://brunch.io/docs/config#-files-
9 | // joinTo: {
10 | // "js/app.js": /^(web\/static\/js)/,
11 | // "js/vendor.js": /^(web\/static\/vendor)|(deps)/
12 | // }
13 | //
14 | // To change the order of concatenation of files, explicitly mention here
15 | // order: {
16 | // before: [
17 | // "web/static/vendor/js/jquery-2.1.1.js",
18 | // "web/static/vendor/js/bootstrap.min.js"
19 | // ]
20 | // }
21 | },
22 | stylesheets: {
23 | joinTo: "css/app.css",
24 | order: {
25 | after: ["web/static/css/app.css"] // concat app.css last
26 | }
27 | },
28 | templates: {
29 | joinTo: "js/app.js"
30 | }
31 | },
32 |
33 | conventions: {
34 | // This option sets where we should place non-css and non-js assets in.
35 | // By default, we set this to "/web/static/assets". Files in this directory
36 | // will be copied to `paths.public`, which is "priv/static" by default.
37 | assets: /^(web\/static\/assets)/
38 | },
39 |
40 | // Phoenix paths configuration
41 | paths: {
42 | // Dependencies and current project directories to watch
43 | watched: [
44 | "web/static",
45 | "test/static"
46 | ],
47 |
48 | // Where to compile files to
49 | public: "priv/static"
50 | },
51 |
52 | // Configure your plugins
53 | plugins: {
54 | babel: {
55 | // Do not use ES6 compiler in vendor code
56 | ignore: [/web\/static\/vendor/]
57 | }
58 | },
59 |
60 | modules: {
61 | autoRequire: {
62 | "js/app.js": ["web/static/js/app"]
63 | }
64 | },
65 |
66 | npm: {
67 | enabled: true
68 | }
69 | };
70 |
--------------------------------------------------------------------------------
/web/web.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.Web do
2 | @moduledoc """
3 | A module that keeps using definitions for controllers,
4 | views and so on.
5 |
6 | This can be used in your application as:
7 |
8 | use Blogex.Web, :controller
9 | use Blogex.Web, :view
10 |
11 | The definitions below will be executed for every view,
12 | controller, etc, so keep them short and clean, focused
13 | on imports, uses and aliases.
14 |
15 | Do NOT define functions inside the quoted expressions
16 | below.
17 | """
18 |
19 | def model do
20 | quote do
21 | use Ecto.Schema
22 |
23 | import Ecto
24 | import Ecto.Changeset
25 | import Ecto.Query
26 | end
27 | end
28 |
29 | def controller do
30 | quote do
31 | use Phoenix.Controller
32 |
33 | alias Blogex.Repo
34 | import Ecto
35 | import Ecto.Query
36 |
37 | import Blogex.Router.Helpers
38 | import Blogex.Gettext
39 | end
40 | end
41 |
42 | def view do
43 | quote do
44 | use Phoenix.View, root: "web/templates"
45 |
46 | # Import convenience functions from controllers
47 | import Phoenix.Controller, only: [get_csrf_token: 0, get_flash: 2, view_module: 1]
48 |
49 | # Use all HTML functionality (forms, tags, etc)
50 | use Phoenix.HTML
51 |
52 | import Blogex.Router.Helpers
53 | import Blogex.ErrorHelpers
54 | import Blogex.Gettext
55 | end
56 | end
57 |
58 | def router do
59 | quote do
60 | use Phoenix.Router
61 | end
62 | end
63 |
64 | def channel do
65 | quote do
66 | use Phoenix.Channel
67 |
68 | alias Blogex.Repo
69 | import Ecto
70 | import Ecto.Query
71 | import Blogex.Gettext
72 | end
73 | end
74 |
75 | @doc """
76 | When used, dispatch to the appropriate controller/view/etc.
77 | """
78 | defmacro __using__(which) when is_atom(which) do
79 | apply(__MODULE__, which, [])
80 | end
81 | end
82 |
--------------------------------------------------------------------------------
/test/support/model_case.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.ModelCase do
2 | @moduledoc """
3 | This module defines the test case to be used by
4 | model tests.
5 |
6 | You may define functions here to be used as helpers in
7 | your model tests. See `errors_on/2`'s definition as reference.
8 |
9 | Finally, if the test case interacts with the database,
10 | it cannot be async. For this reason, every test runs
11 | inside a transaction which is reset at the beginning
12 | of the test unless the test case is marked as async.
13 | """
14 |
15 | use ExUnit.CaseTemplate
16 |
17 | using do
18 | quote do
19 | alias Blogex.Repo
20 |
21 | import Ecto
22 | import Ecto.Changeset
23 | import Ecto.Query
24 | import Blogex.ModelCase
25 | end
26 | end
27 |
28 | setup tags do
29 | :ok = Ecto.Adapters.SQL.Sandbox.checkout(Blogex.Repo)
30 |
31 | unless tags[:async] do
32 | Ecto.Adapters.SQL.Sandbox.mode(Blogex.Repo, {:shared, self()})
33 | end
34 |
35 | :ok
36 | end
37 |
38 | @doc """
39 | Helper for returning list of errors in a struct when given certain data.
40 |
41 | ## Examples
42 |
43 | Given a User schema that lists `:name` as a required field and validates
44 | `:password` to be safe, it would return:
45 |
46 | iex> errors_on(%User{}, %{password: "password"})
47 | [password: "is unsafe", name: "is blank"]
48 |
49 | You could then write your assertion like:
50 |
51 | assert {:password, "is unsafe"} in errors_on(%User{}, %{password: "password"})
52 |
53 | You can also create the changeset manually and retrieve the errors
54 | field directly:
55 |
56 | iex> changeset = User.changeset(%User{}, password: "password")
57 | iex> {:password, "is unsafe"} in changeset.errors
58 | true
59 | """
60 | def errors_on(struct, data) do
61 | struct.__struct__.changeset(struct, data)
62 | |> Ecto.Changeset.traverse_errors(&Blogex.ErrorHelpers.translate_error/1)
63 | |> Enum.flat_map(fn {key, errors} -> for msg <- errors, do: {key, msg} end)
64 | end
65 | end
66 |
--------------------------------------------------------------------------------
/mix.exs:
--------------------------------------------------------------------------------
1 | defmodule Blogex.Mixfile do
2 | use Mix.Project
3 |
4 | def project do
5 | [
6 | app: :blogex,
7 | version: "0.0.1",
8 | elixir: "~> 1.2",
9 | elixirc_paths: elixirc_paths(Mix.env),
10 | compilers: [:phoenix, :gettext] ++ Mix.compilers,
11 | build_embedded: Mix.env == :prod,
12 | start_permanent: Mix.env == :prod,
13 | aliases: aliases,
14 | deps: deps
15 | ]
16 | end
17 |
18 | # Configuration for the OTP application.
19 | #
20 | # Type `mix help compile.app` for more information.
21 | def application do
22 | [
23 | mod: {Blogex, []},
24 | applications: [
25 | :phoenix,
26 | :phoenix_pubsub,
27 | :phoenix_html,
28 | :cowboy,
29 | :logger,
30 | :gettext,
31 | :phoenix_ecto,
32 | :postgrex,
33 | :earmark,
34 | ]
35 | ]
36 | end
37 |
38 | # Specifies which paths to compile per environment.
39 | defp elixirc_paths(:test), do: ["lib", "web", "test/support"]
40 | defp elixirc_paths(_), do: ["lib", "web"]
41 |
42 | # Specifies your project dependencies.
43 | #
44 | # Type `mix help deps` for examples and options.
45 | defp deps do
46 | [
47 | {:phoenix, "~> 1.2.1"},
48 | {:phoenix_pubsub, "~> 1.0"},
49 | {:phoenix_ecto, "~> 3.0"},
50 | {:postgrex, ">= 0.0.0"},
51 | {:phoenix_html, "~> 2.6"},
52 | {:phoenix_live_reload, "~> 1.0", only: :dev},
53 | {:gettext, "~> 0.11"},
54 | {:cowboy, "~> 1.0"},
55 | {:earmark, "~> 1.0.1"},
56 | ]
57 | end
58 |
59 | # Aliases are shortcuts or tasks specific to the current project.
60 | # For example, to create, migrate and run the seeds file at once:
61 | #
62 | # $ mix ecto.setup
63 | #
64 | # See the documentation for `Mix` for more info on aliases.
65 | defp aliases do
66 | ["ecto.setup": ["ecto.create", "ecto.migrate", "run priv/repo/seeds.exs"],
67 | "ecto.reset": ["ecto.drop", "ecto.setup"],
68 | "test": ["ecto.create --quiet", "ecto.migrate", "test"]]
69 | end
70 | end
71 |
--------------------------------------------------------------------------------
/posts/piping.md:
--------------------------------------------------------------------------------
1 | # Piping into anonymous functions
2 |
3 | Has this ever happened to you?
4 |
5 | ```elixir
6 | "Pipe all the things!"
7 | |> String.upcase
8 | |> String.reverse
9 | |> # ...I can't find a function that does what I need!
10 | ```
11 |
12 | Don't worry, it happens to the best of us. The usual solution is to define a private function that
13 | does what you need to do and carry on. There are times, however, where that doesn't feel right. For
14 | example, say the step missing from the sequence of operations above is putting the resulting
15 | string in the `:result` key of a new `Map`. This function seems way too specific to be useful
16 | elsewhere:
17 |
18 | ```elixir
19 | defp to_result_map(string) do
20 | %{result: string}
21 | end
22 | ```
23 |
24 | Fortunately, steps of a sequence of piped operations are just functions - which means you can pipe
25 | values into _anonymous functions_. While this is obvious from a logical perspective, the syntax
26 | is not entirely intuitive. Here's how you do it:
27 |
28 | ```elixir
29 | "Pipe all the things!"
30 | |> String.upcase
31 | |> String.reverse
32 | |> (fn str -> %{result: str} end).()
33 | ```
34 |
35 | That does the job and it's still pretty readable. If you're feeling brave and don't mind sacrificing
36 | a bit of readability for brevity, you can replace the last line with the shorthand version:
37 |
38 | ```elixir
39 | |> (&%{result: &1}).()
40 | ```
41 |
42 | Another advantage is that anonymous functions are closures, so they have access to other variables
43 | defined in the scope where all the piping is happening. If you were writing private functions, you
44 | would need to pass those in explicitly, which can get tedious and error-prone depending on what you're doing.
45 |
46 | Be mindful of code readability - one of the main advantages of the pipe is that it makes it easy to
47 | see what transformations are being applied to a value, and abusing anonymous functions can quickly
48 | cause that to break down. Also remember about code reuse - if you feel like that transformation
49 | could be useful elsewhere, it's better to extract it into a separate function. Keep that in
50 | mind and you'll get the best of both worlds!
51 |
--------------------------------------------------------------------------------
/config/prod.exs:
--------------------------------------------------------------------------------
1 | use Mix.Config
2 |
3 | # For production, we configure the host to read the PORT
4 | # from the system environment. Therefore, you will need
5 | # to set PORT=80 before running your server.
6 | #
7 | # You should also configure the url host to something
8 | # meaningful, we use this information when generating URLs.
9 | #
10 | # Finally, we also include the path to a manifest
11 | # containing the digested version of static files. This
12 | # manifest is generated by the mix phoenix.digest task
13 | # which you typically run after static files are built.
14 | config :blogex, Blogex.Endpoint,
15 | http: [port: 4000],
16 | url: [host: "example.com", port: 80],
17 | cache_static_manifest: "priv/static/manifest.json",
18 | root: ".",
19 | server: true,
20 | version: Mix.Project.config[:version]
21 |
22 | # Do not print debug messages in production
23 | config :logger, level: :info
24 |
25 | # ## SSL Support
26 | #
27 | # To get SSL working, you will need to add the `https` key
28 | # to the previous section and set your `:url` port to 443:
29 | #
30 | # config :blogex, Blogex.Endpoint,
31 | # ...
32 | # url: [host: "example.com", port: 443],
33 | # https: [port: 443,
34 | # keyfile: System.get_env("SOME_APP_SSL_KEY_PATH"),
35 | # certfile: System.get_env("SOME_APP_SSL_CERT_PATH")]
36 | #
37 | # Where those two env variables return an absolute path to
38 | # the key and cert in disk or a relative path inside priv,
39 | # for example "priv/ssl/server.key".
40 | #
41 | # We also recommend setting `force_ssl`, ensuring no data is
42 | # ever sent via http, always redirecting to https:
43 | #
44 | # config :blogex, Blogex.Endpoint,
45 | # force_ssl: [hsts: true]
46 | #
47 | # Check `Plug.SSL` for all available options in `force_ssl`.
48 |
49 | # ## Using releases
50 | #
51 | # If you are doing OTP releases, you need to instruct Phoenix
52 | # to start the server for all endpoints:
53 | #
54 | # config :phoenix, :serve_endpoints, true
55 | #
56 | # Alternatively, you can configure exactly which server to
57 | # start per endpoint:
58 | #
59 | # config :blogex, Blogex.Endpoint, server: true
60 | #
61 |
62 | # Finally import the config/prod.secret.exs
63 | # which should be versioned separately.
64 | import_config "prod.secret.exs"
65 |
--------------------------------------------------------------------------------
/web/static/js/socket.js:
--------------------------------------------------------------------------------
1 | // NOTE: The contents of this file will only be executed if
2 | // you uncomment its entry in "web/static/js/app.js".
3 |
4 | // To use Phoenix channels, the first step is to import Socket
5 | // and connect at the socket path in "lib/my_app/endpoint.ex":
6 | import {Socket} from "phoenix"
7 |
8 | let socket = new Socket("/socket", {params: {token: window.userToken}})
9 |
10 | // When you connect, you'll often need to authenticate the client.
11 | // For example, imagine you have an authentication plug, `MyAuth`,
12 | // which authenticates the session and assigns a `:current_user`.
13 | // If the current user exists you can assign the user's token in
14 | // the connection for use in the layout.
15 | //
16 | // In your "web/router.ex":
17 | //
18 | // pipeline :browser do
19 | // ...
20 | // plug MyAuth
21 | // plug :put_user_token
22 | // end
23 | //
24 | // defp put_user_token(conn, _) do
25 | // if current_user = conn.assigns[:current_user] do
26 | // token = Phoenix.Token.sign(conn, "user socket", current_user.id)
27 | // assign(conn, :user_token, token)
28 | // else
29 | // conn
30 | // end
31 | // end
32 | //
33 | // Now you need to pass this token to JavaScript. You can do so
34 | // inside a script tag in "web/templates/layout/app.html.eex":
35 | //
36 | //
37 | //
38 | // You will need to verify the user token in the "connect/2" function
39 | // in "web/channels/user_socket.ex":
40 | //
41 | // def connect(%{"token" => token}, socket) do
42 | // # max_age: 1209600 is equivalent to two weeks in seconds
43 | // case Phoenix.Token.verify(socket, "user socket", token, max_age: 1209600) do
44 | // {:ok, user_id} ->
45 | // {:ok, assign(socket, :user, user_id)}
46 | // {:error, reason} ->
47 | // :error
48 | // end
49 | // end
50 | //
51 | // Finally, pass the token on connect as below. Or remove it
52 | // from connect if you don't care about authentication.
53 |
54 | socket.connect()
55 |
56 | // Now that you are connected, you can join channels with a topic:
57 | let channel = socket.channel("topic:subtopic", {})
58 | channel.join()
59 | .receive("ok", resp => { console.log("Joined successfully", resp) })
60 | .receive("error", resp => { console.log("Unable to join", resp) })
61 |
62 | export default socket
63 |
--------------------------------------------------------------------------------
/priv/gettext/en/LC_MESSAGES/errors.po:
--------------------------------------------------------------------------------
1 | ## `msgid`s in this file come from POT (.pot) files.
2 | ##
3 | ## Do not add, change, or remove `msgid`s manually here as
4 | ## they're tied to the ones in the corresponding POT file
5 | ## (with the same domain).
6 | ##
7 | ## Use `mix gettext.extract --merge` or `mix gettext.merge`
8 | ## to merge POT files into PO files.
9 | msgid ""
10 | msgstr ""
11 | "Language: en\n"
12 |
13 | ## From Ecto.Changeset.cast/4
14 | msgid "can't be blank"
15 | msgstr ""
16 |
17 | ## From Ecto.Changeset.unique_constraint/3
18 | msgid "has already been taken"
19 | msgstr ""
20 |
21 | ## From Ecto.Changeset.put_change/3
22 | msgid "is invalid"
23 | msgstr ""
24 |
25 | ## From Ecto.Changeset.validate_format/3
26 | msgid "has invalid format"
27 | msgstr ""
28 |
29 | ## From Ecto.Changeset.validate_subset/3
30 | msgid "has an invalid entry"
31 | msgstr ""
32 |
33 | ## From Ecto.Changeset.validate_exclusion/3
34 | msgid "is reserved"
35 | msgstr ""
36 |
37 | ## From Ecto.Changeset.validate_confirmation/3
38 | msgid "does not match confirmation"
39 | msgstr ""
40 |
41 | ## From Ecto.Changeset.no_assoc_constraint/3
42 | msgid "is still associated to this entry"
43 | msgstr ""
44 |
45 | msgid "are still associated to this entry"
46 | msgstr ""
47 |
48 | ## From Ecto.Changeset.validate_length/3
49 | msgid "should be %{count} character(s)"
50 | msgid_plural "should be %{count} character(s)"
51 | msgstr[0] ""
52 | msgstr[1] ""
53 |
54 | msgid "should have %{count} item(s)"
55 | msgid_plural "should have %{count} item(s)"
56 | msgstr[0] ""
57 | msgstr[1] ""
58 |
59 | msgid "should be at least %{count} character(s)"
60 | msgid_plural "should be at least %{count} character(s)"
61 | msgstr[0] ""
62 | msgstr[1] ""
63 |
64 | msgid "should have at least %{count} item(s)"
65 | msgid_plural "should have at least %{count} item(s)"
66 | msgstr[0] ""
67 | msgstr[1] ""
68 |
69 | msgid "should be at most %{count} character(s)"
70 | msgid_plural "should be at most %{count} character(s)"
71 | msgstr[0] ""
72 | msgstr[1] ""
73 |
74 | msgid "should have at most %{count} item(s)"
75 | msgid_plural "should have at most %{count} item(s)"
76 | msgstr[0] ""
77 | msgstr[1] ""
78 |
79 | ## From Ecto.Changeset.validate_number/3
80 | msgid "must be less than %{number}"
81 | msgstr ""
82 |
83 | msgid "must be greater than %{number}"
84 | msgstr ""
85 |
86 | msgid "must be less than or equal to %{number}"
87 | msgstr ""
88 |
89 | msgid "must be greater than or equal to %{number}"
90 | msgstr ""
91 |
92 | msgid "must be equal to %{number}"
93 | msgstr ""
94 |
--------------------------------------------------------------------------------
/priv/gettext/errors.pot:
--------------------------------------------------------------------------------
1 | ## This file is a PO Template file.
2 | ##
3 | ## `msgid`s here are often extracted from source code.
4 | ## Add new translations manually only if they're dynamic
5 | ## translations that can't be statically extracted.
6 | ##
7 | ## Run `mix gettext.extract` to bring this file up to
8 | ## date. Leave `msgstr`s empty as changing them here as no
9 | ## effect: edit them in PO (`.po`) files instead.
10 |
11 | ## From Ecto.Changeset.cast/4
12 | msgid "can't be blank"
13 | msgstr ""
14 |
15 | ## From Ecto.Changeset.unique_constraint/3
16 | msgid "has already been taken"
17 | msgstr ""
18 |
19 | ## From Ecto.Changeset.put_change/3
20 | msgid "is invalid"
21 | msgstr ""
22 |
23 | ## From Ecto.Changeset.validate_format/3
24 | msgid "has invalid format"
25 | msgstr ""
26 |
27 | ## From Ecto.Changeset.validate_subset/3
28 | msgid "has an invalid entry"
29 | msgstr ""
30 |
31 | ## From Ecto.Changeset.validate_exclusion/3
32 | msgid "is reserved"
33 | msgstr ""
34 |
35 | ## From Ecto.Changeset.validate_confirmation/3
36 | msgid "does not match confirmation"
37 | msgstr ""
38 |
39 | ## From Ecto.Changeset.no_assoc_constraint/3
40 | msgid "is still associated to this entry"
41 | msgstr ""
42 |
43 | msgid "are still associated to this entry"
44 | msgstr ""
45 |
46 | ## From Ecto.Changeset.validate_length/3
47 | msgid "should be %{count} character(s)"
48 | msgid_plural "should be %{count} character(s)"
49 | msgstr[0] ""
50 | msgstr[1] ""
51 |
52 | msgid "should have %{count} item(s)"
53 | msgid_plural "should have %{count} item(s)"
54 | msgstr[0] ""
55 | msgstr[1] ""
56 |
57 | msgid "should be at least %{count} character(s)"
58 | msgid_plural "should be at least %{count} character(s)"
59 | msgstr[0] ""
60 | msgstr[1] ""
61 |
62 | msgid "should have at least %{count} item(s)"
63 | msgid_plural "should have at least %{count} item(s)"
64 | msgstr[0] ""
65 | msgstr[1] ""
66 |
67 | msgid "should be at most %{count} character(s)"
68 | msgid_plural "should be at most %{count} character(s)"
69 | msgstr[0] ""
70 | msgstr[1] ""
71 |
72 | msgid "should have at most %{count} item(s)"
73 | msgid_plural "should have at most %{count} item(s)"
74 | msgstr[0] ""
75 | msgstr[1] ""
76 |
77 | ## From Ecto.Changeset.validate_number/3
78 | msgid "must be less than %{number}"
79 | msgstr ""
80 |
81 | msgid "must be greater than %{number}"
82 | msgstr ""
83 |
84 | msgid "must be less than or equal to %{number}"
85 | msgstr ""
86 |
87 | msgid "must be greater than or equal to %{number}"
88 | msgstr ""
89 |
90 | msgid "must be equal to %{number}"
91 | msgstr ""
92 |
--------------------------------------------------------------------------------
/web/static/css/prism.css:
--------------------------------------------------------------------------------
1 | /* http://prismjs.com/download.html?themes=prism-okaidia&languages=markup+css+clike+javascript+bash+docker+elixir+erlang+gherkin+haskell+json+jsx+sql&plugins=show-language */
2 | /**
3 | * okaidia theme for JavaScript, CSS and HTML
4 | * Loosely based on Monokai textmate theme by http://www.monokai.nl/
5 | * @author ocodia
6 | */
7 |
8 | code[class*="language-"],
9 | pre[class*="language-"] {
10 | color: #f8f8f2;
11 | background: none;
12 | text-shadow: 0 1px rgba(0, 0, 0, 0.3);
13 | font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
14 | text-align: left;
15 | white-space: pre;
16 | word-spacing: normal;
17 | word-break: normal;
18 | word-wrap: normal;
19 | line-height: 1.5;
20 |
21 | -moz-tab-size: 4;
22 | -o-tab-size: 4;
23 | tab-size: 4;
24 |
25 | -webkit-hyphens: none;
26 | -moz-hyphens: none;
27 | -ms-hyphens: none;
28 | hyphens: none;
29 | }
30 |
31 | /* Code blocks */
32 | pre[class*="language-"] {
33 | padding: 1em;
34 | margin: .5em 0;
35 | overflow: auto;
36 | border-radius: 0.3em;
37 | }
38 |
39 | :not(pre) > code[class*="language-"],
40 | pre[class*="language-"] {
41 | background: #272822;
42 | }
43 |
44 | /* Inline code */
45 | :not(pre) > code[class*="language-"] {
46 | padding: .1em;
47 | border-radius: .3em;
48 | white-space: normal;
49 | }
50 |
51 | .token.comment,
52 | .token.prolog,
53 | .token.doctype,
54 | .token.cdata {
55 | color: slategray;
56 | }
57 |
58 | .token.punctuation {
59 | color: #f8f8f2;
60 | }
61 |
62 | .namespace {
63 | opacity: .7;
64 | }
65 |
66 | .token.property,
67 | .token.tag,
68 | .token.constant,
69 | .token.symbol,
70 | .token.deleted {
71 | color: #f92672;
72 | }
73 |
74 | .token.boolean,
75 | .token.number {
76 | color: #ae81ff;
77 | }
78 |
79 | .token.selector,
80 | .token.attr-name,
81 | .token.string,
82 | .token.char,
83 | .token.builtin,
84 | .token.inserted {
85 | color: #a6e22e;
86 | }
87 |
88 | .token.operator,
89 | .token.entity,
90 | .token.url,
91 | .language-css .token.string,
92 | .style .token.string,
93 | .token.variable {
94 | color: #f8f8f2;
95 | }
96 |
97 | .token.atrule,
98 | .token.attr-value,
99 | .token.function {
100 | color: #e6db74;
101 | }
102 |
103 | .token.keyword {
104 | color: #66d9ef;
105 | }
106 |
107 | .token.regex,
108 | .token.important {
109 | color: #fd971f;
110 | }
111 |
112 | .token.important,
113 | .token.bold {
114 | font-weight: bold;
115 | }
116 | .token.italic {
117 | font-style: italic;
118 | }
119 |
120 | .token.entity {
121 | cursor: help;
122 | }
123 |
124 | div.prism-show-language {
125 | position: relative;
126 | }
127 |
128 | div.prism-show-language > div.prism-show-language-label {
129 | color: black;
130 | background-color: #CFCFCF;
131 | display: inline-block;
132 | position: absolute;
133 | bottom: auto;
134 | left: auto;
135 | top: 0;
136 | right: 0;
137 | width: auto;
138 | height: auto;
139 | font-size: 0.9em;
140 | border-radius: 0 0 0 5px;
141 | padding: 0 0.5em;
142 | text-shadow: none;
143 | z-index: 1;
144 | box-shadow: none;
145 | -webkit-transform: none;
146 | -moz-transform: none;
147 | -ms-transform: none;
148 | -o-transform: none;
149 | transform: none;
150 | }
151 |
152 |
--------------------------------------------------------------------------------
/mix.lock:
--------------------------------------------------------------------------------
1 | %{"bbmustache": {:hex, :bbmustache, "1.0.4", "7ba94f971c5afd7b6617918a4bb74705e36cab36eb84b19b6a1b7ee06427aa38", [:rebar], []},
2 | "cf": {:hex, :cf, "0.2.1", "69d0b1349fd4d7d4dc55b7f407d29d7a840bf9a1ef5af529f1ebe0ce153fc2ab", [:rebar3], []},
3 | "connection": {:hex, :connection, "1.0.4", "a1cae72211f0eef17705aaededacac3eb30e6625b04a6117c1b2db6ace7d5976", [:mix], []},
4 | "cowboy": {:hex, :cowboy, "1.0.4", "a324a8df9f2316c833a470d918aaf73ae894278b8aa6226ce7a9bf699388f878", [:rebar, :make], [{:cowlib, "~> 1.0.0", [hex: :cowlib, optional: false]}, {:ranch, "~> 1.0", [hex: :ranch, optional: false]}]},
5 | "cowlib": {:hex, :cowlib, "1.0.2", "9d769a1d062c9c3ac753096f868ca121e2730b9a377de23dec0f7e08b1df84ee", [:make], []},
6 | "db_connection": {:hex, :db_connection, "1.0.0-rc.5", "1d9ab6e01387bdf2de7a16c56866971f7c2f75aea7c69cae2a0346e4b537ae0d", [:mix], [{:connection, "~> 1.0.2", [hex: :connection, optional: false]}, {:poolboy, "~> 1.5", [hex: :poolboy, optional: true]}, {:sbroker, "~> 1.0.0-beta.3", [hex: :sbroker, optional: true]}]},
7 | "decimal": {:hex, :decimal, "1.1.2", "79a769d4657b2d537b51ef3c02d29ab7141d2b486b516c109642d453ee08e00c", [:mix], []},
8 | "earmark": {:hex, :earmark, "1.0.1", "2c2cd903bfdc3de3f189bd9a8d4569a075b88a8981ded9a0d95672f6e2b63141", [:mix], []},
9 | "ecto": {:hex, :ecto, "2.0.4", "03fd3b9aa508b1383eb38c00ac389953ed22af53811aa2e504975a3e814a8d97", [:mix], [{:db_connection, "~> 1.0-rc.2", [hex: :db_connection, optional: true]}, {:decimal, "~> 1.0", [hex: :decimal, optional: false]}, {:mariaex, "~> 0.7.7", [hex: :mariaex, optional: true]}, {:poison, "~> 1.5 or ~> 2.0", [hex: :poison, optional: true]}, {:poolboy, "~> 1.5", [hex: :poolboy, optional: false]}, {:postgrex, "~> 0.11.2", [hex: :postgrex, optional: true]}, {:sbroker, "~> 1.0-beta", [hex: :sbroker, optional: true]}]},
10 | "erlware_commons": {:hex, :erlware_commons, "0.21.0", "a04433071ad7d112edefc75ac77719dd3e6753e697ac09428fc83d7564b80b15", [:rebar3], [{:cf, "0.2.1", [hex: :cf, optional: false]}]},
11 | "exrm": {:hex, :exrm, "1.0.8", "5aa8990cdfe300282828b02cefdc339e235f7916388ce99f9a1f926a9271a45d", [:mix], [{:relx, "~> 3.5", [hex: :relx, optional: false]}]},
12 | "fs": {:hex, :fs, "0.9.2", "ed17036c26c3f70ac49781ed9220a50c36775c6ca2cf8182d123b6566e49ec59", [:rebar], []},
13 | "getopt": {:hex, :getopt, "0.8.2", "b17556db683000ba50370b16c0619df1337e7af7ecbf7d64fbf8d1d6bce3109b", [:rebar], []},
14 | "gettext": {:hex, :gettext, "0.11.0", "80c1dd42d270482418fa158ec5ba073d2980e3718bacad86f3d4ad71d5667679", [:mix], []},
15 | "mime": {:hex, :mime, "1.0.1", "05c393850524767d13a53627df71beeebb016205eb43bfbd92d14d24ec7a1b51", [:mix], []},
16 | "phoenix": {:hex, :phoenix, "1.2.1", "6dc592249ab73c67575769765b66ad164ad25d83defa3492dc6ae269bd2a68ab", [:mix], [{:cowboy, "~> 1.0", [hex: :cowboy, optional: true]}, {:phoenix_pubsub, "~> 1.0", [hex: :phoenix_pubsub, optional: false]}, {:plug, "~> 1.1", [hex: :plug, optional: false]}, {:poison, "~> 1.5 or ~> 2.0", [hex: :poison, optional: false]}]},
17 | "phoenix_ecto": {:hex, :phoenix_ecto, "3.0.1", "42eb486ef732cf209d0a353e791806721f33ff40beab0a86f02070a5649ed00a", [:mix], [{:ecto, "~> 2.0", [hex: :ecto, optional: false]}, {:phoenix_html, "~> 2.6", [hex: :phoenix_html, optional: true]}, {:plug, "~> 1.0", [hex: :plug, optional: false]}]},
18 | "phoenix_html": {:hex, :phoenix_html, "2.6.2", "944a5e581b0d899e4f4c838a69503ebd05300fe35ba228a74439e6253e10e0c0", [:mix], [{:plug, "~> 1.0", [hex: :plug, optional: false]}]},
19 | "phoenix_live_reload": {:hex, :phoenix_live_reload, "1.0.5", "829218c4152ba1e9848e2bf8e161fcde6b4ec679a516259442561d21fde68d0b", [:mix], [{:fs, "~> 0.9.1", [hex: :fs, optional: false]}, {:phoenix, "~> 1.0 or ~> 1.2-rc", [hex: :phoenix, optional: false]}]},
20 | "phoenix_pubsub": {:hex, :phoenix_pubsub, "1.0.0", "c31af4be22afeeebfaf246592778c8c840e5a1ddc7ca87610c41ccfb160c2c57", [:mix], []},
21 | "plug": {:hex, :plug, "1.2.0", "496bef96634a49d7803ab2671482f0c5ce9ce0b7b9bc25bc0ae8e09859dd2004", [:mix], [{:cowboy, "~> 1.0", [hex: :cowboy, optional: true]}, {:mime, "~> 1.0", [hex: :mime, optional: false]}]},
22 | "poison": {:hex, :poison, "2.2.0", "4763b69a8a77bd77d26f477d196428b741261a761257ff1cf92753a0d4d24a63", [:mix], []},
23 | "poolboy": {:hex, :poolboy, "1.5.1", "6b46163901cfd0a1b43d692657ed9d7e599853b3b21b95ae5ae0a777cf9b6ca8", [:rebar], []},
24 | "postgrex": {:hex, :postgrex, "0.11.2", "139755c1359d3c5c6d6e8b1ea72556d39e2746f61c6ddfb442813c91f53487e8", [:mix], [{:connection, "~> 1.0", [hex: :connection, optional: false]}, {:db_connection, "~> 1.0-rc", [hex: :db_connection, optional: false]}, {:decimal, "~> 1.0", [hex: :decimal, optional: false]}]},
25 | "providers": {:hex, :providers, "1.6.0", "db0e2f9043ae60c0155205fcd238d68516331d0e5146155e33d1e79dc452964a", [:rebar3], [{:getopt, "0.8.2", [hex: :getopt, optional: false]}]},
26 | "ranch": {:hex, :ranch, "1.2.1", "a6fb992c10f2187b46ffd17ce398ddf8a54f691b81768f9ef5f461ea7e28c762", [:make], []},
27 | "relx": {:hex, :relx, "3.21.0", "91e1ea9f09b4edfda8461901f4b5c5e0226e43ec161e147eeab29f7761df6eb5", [:rebar3], [{:bbmustache, "1.0.4", [hex: :bbmustache, optional: false]}, {:cf, "0.2.1", [hex: :cf, optional: false]}, {:erlware_commons, "0.21.0", [hex: :erlware_commons, optional: false]}, {:getopt, "0.8.2", [hex: :getopt, optional: false]}, {:providers, "1.6.0", [hex: :providers, optional: false]}]}}
28 |
--------------------------------------------------------------------------------
/lib/prism_renderer.ex:
--------------------------------------------------------------------------------
1 | defmodule Blogex.PrismRenderer do
2 |
3 | defmodule EarmarkError do
4 | defexception [:message]
5 |
6 | def exception(msg), do: %__MODULE__{message: msg}
7 | end
8 |
9 | alias Earmark.Block
10 | import Earmark.Inline, only: [ convert: 2 ]
11 | import Earmark.Helpers, only: [ escape: 2 ]
12 | import Earmark.Helpers.StringHelpers, only: [behead: 2]
13 |
14 | def render(blocks, context, map_func) do
15 | map_func.(blocks, &(render_block(&1, context, map_func)))
16 | |> IO.iodata_to_binary
17 | end
18 |
19 |
20 | #############
21 | # Paragraph #
22 | #############
23 | def render_block(%Block.Para{lines: lines, attrs: attrs}, context, _mf) do
24 | lines = convert(lines, context)
25 | add_attrs("#{lines}
\n", attrs)
26 | end
27 |
28 | ########
29 | # Html #
30 | ########
31 | def render_block(%Block.Html{html: html}, _context, _mf) do
32 | Enum.intersperse(html, ?\n)
33 | end
34 |
35 | def render_block(%Block.HtmlOther{html: html}, _context, _mf) do
36 | Enum.intersperse(html, ?\n)
37 | end
38 |
39 | #########
40 | # Ruler #
41 | #########
42 | def render_block(%Block.Ruler{type: "-", attrs: attrs}, _context, _mf) do
43 | add_attrs(" \n", attrs, [{"class", ["thin"]}])
44 | end
45 |
46 | def render_block(%Block.Ruler{type: "_", attrs: attrs}, _context, _mf) do
47 | add_attrs(" \n", attrs, [{"class", ["medium"]}])
48 | end
49 |
50 | def render_block(%Block.Ruler{type: "*", attrs: attrs}, _context, _mf) do
51 | add_attrs(" \n", attrs, [{"class", ["thick"]}])
52 | end
53 |
54 | ###########
55 | # Heading #
56 | ###########
57 | def render_block(%Block.Heading{level: level, content: content, attrs: attrs}, context, _mf) do
58 | html = "#{convert(content,context)} \n"
59 | add_attrs(html, attrs)
60 | end
61 |
62 | ##############
63 | # Blockquote #
64 | ##############
65 |
66 | def render_block(%Block.BlockQuote{blocks: blocks, attrs: attrs}, context, mf) do
67 | body = render(blocks, context, mf)
68 | html = "#{body} \n"
69 | add_attrs(html, attrs)
70 | end
71 |
72 | #########
73 | # Table #
74 | #########
75 |
76 | def render_block(%Block.Table{header: header, rows: rows, alignments: aligns, attrs: attrs}, context, _mf) do
77 | cols = for _align <- aligns, do: " \n"
78 | html = [ add_attrs("\n", attrs), "\n", cols, " \n" ]
79 |
80 | html = if header do
81 | [ html, "\n",
82 | add_table_rows(context, [header], "th", aligns),
83 | " \n" ]
84 | else
85 | html
86 | end
87 |
88 | html = [ html, add_table_rows(context, rows, "td", aligns), "
\n" ]
89 |
90 | html
91 | end
92 |
93 | ########
94 | # Code #
95 | ########
96 | def render_block(%Block.Code{lines: lines, language: language, attrs: attrs}, _context, _mf) do
97 | class = if language, do: ~s{ class="language-#{language}"}, else: ""
98 | tag = ~s[]
99 | lines = lines |> Enum.map(&(escape(&1, true))) |> Enum.join("\n") # |> String.strip
100 | html = ~s[#{tag}#{lines} \n]
101 | add_attrs(html, attrs)
102 | end
103 |
104 | #########
105 | # Lists #
106 | #########
107 |
108 | def render_block(%Block.List{type: type, blocks: items, attrs: attrs}, context, mf) do
109 | content = render(items, context, mf)
110 | html = "<#{type}>\n#{content}#{type}>\n"
111 | add_attrs(html, attrs)
112 | end
113 |
114 | # format a single paragraph list item, and remove the para tags
115 | def render_block(%Block.ListItem{blocks: blocks, spaced: false, attrs: attrs}, context, mf)
116 | when length(blocks) == 1 do
117 | content = render(blocks, context, mf)
118 | content = Regex.replace(~r{?p>}, content, "")
119 | html = "#{content} \n"
120 | add_attrs(html, attrs)
121 | end
122 |
123 | # format a spaced list item
124 | def render_block(%Block.ListItem{blocks: blocks, attrs: attrs}, context, mf) do
125 | content = render(blocks, context, mf)
126 | html = "#{content} \n"
127 | add_attrs(html, attrs)
128 | end
129 |
130 | ##################
131 | # Footnote Block #
132 | ##################
133 |
134 | def render_block(%Block.FnList{blocks: footnotes}, context, mf) do
135 | items = Enum.map(footnotes, fn(note) ->
136 | blocks = append_footnote_link(note)
137 | %Block.ListItem{attrs: "#fn:#{note.number}", type: :ol, blocks: blocks}
138 | end)
139 | html = render_block(%Block.List{type: :ol, blocks: items}, context, mf)
140 | Enum.join([~s["], "\n")
141 | end
142 |
143 | ####################
144 | # IDDef is ignored #
145 | ####################
146 |
147 | def render_block(%Block.IdDef{}, _context, _mf) do
148 | ""
149 | end
150 |
151 | #####################################
152 | # And here are the inline renderers #
153 | #####################################
154 |
155 | def br, do: " "
156 | def codespan(text), do: ~s[#{text}]
157 | def em(text), do: "#{text} "
158 | def strong(text), do: "#{text} "
159 | def strikethrough(text), do: "#{text}"
160 |
161 | def link(url, text), do: ~s[#{text} ]
162 | def link(url, text, nil), do: ~s[#{text} ]
163 | def link(url, text, title), do: ~s[#{text} ]
164 |
165 | def image(path, alt, nil) do
166 | ~s[ ]
167 | end
168 |
169 | def image(path, alt, title) do
170 | ~s[ ]
171 | end
172 |
173 | def footnote_link(ref, backref, number), do: ~s[]
174 |
175 | # Table rows
176 | def add_table_rows(context, rows, tag, aligns \\ []) do
177 | for row <- rows, do: "\n#{add_tds(context, row, tag, aligns)}\n \n"
178 | end
179 |
180 | def add_tds(context, row, tag, aligns \\ []) do
181 | Enum.reduce(1..length(row), {[], row}, fn(n, {acc, row}) ->
182 | style = cond do
183 | align = Enum.at(aligns, n - 1) ->
184 | " style=\"text-align: #{align}\""
185 | true ->
186 | ""
187 | end
188 | col = Enum.at(row, n - 1)
189 | {["<#{tag}#{style}>#{convert(col, context)}#{tag}>" | acc], row}
190 | end)
191 | |> elem(0)
192 | |> Enum.reverse
193 | end
194 |
195 | ##############################################
196 | # add attributes to the outer tag in a block #
197 | ##############################################
198 |
199 | def add_attrs(text, attrs_as_string, default_attrs \\ [])
200 |
201 | def add_attrs(text, nil, []), do: text
202 |
203 | def add_attrs(text, nil, default), do: add_attrs(text, "", default)
204 |
205 | def add_attrs(text, attrs, default) do
206 | default
207 | |> Enum.into(Map.new)
208 | |> expand(attrs)
209 | |> attrs_to_string
210 | |> add_to(text)
211 | end
212 |
213 | def expand(dict, attrs) do
214 | cond do
215 | Regex.match?(~r{^\s*$}, attrs) -> dict
216 |
217 | match = Regex.run(~r{^\.(\S+)\s*}, attrs) ->
218 | [ leader, class ] = match
219 | Map.update(dict, "class", [ class ], &[ class | &1])
220 | |> expand(behead(attrs, leader))
221 |
222 | match = Regex.run(~r{^\#(\S+)\s*}, attrs) ->
223 | [ leader, id ] = match
224 | Map.update(dict, "id", [ id ], &[ id | &1])
225 | |> expand(behead(attrs, leader))
226 |
227 | match = Regex.run(~r{^(\S+)=\'([^\']*)'\s*}, attrs) -> #'
228 | [ leader, name, value ] = match
229 | Map.update(dict, name, [ value ], &[ value | &1])
230 | |> expand(behead(attrs, leader))
231 |
232 | match = Regex.run(~r{^(\S+)=\"([^\"]*)"\s*}, attrs) -> #"
233 | [ leader, name, value ] = match
234 | Map.update(dict, name, [ value ], &[ value | &1])
235 | |> expand(behead(attrs, leader))
236 |
237 | match = Regex.run(~r{^(\S+)=(\S+)\s*}, attrs) ->
238 | [ leader, name, value ] = match
239 | Map.update(dict, name, [ value ], &[ value | &1])
240 | |> expand(behead(attrs, leader))
241 |
242 | :otherwise ->
243 | raise EarmarkError, "Invalid Markdown attributes: {#{attrs}}"
244 | end
245 | end
246 |
247 | def attrs_to_string(attrs) do
248 | (for { name, value } <- attrs, do: ~s/#{name}="#{Enum.join(value, " ")}"/)
249 | |> Enum.join(" ")
250 | end
251 |
252 | def add_to(attrs, text) do
253 | String.replace(text, ~r{\s?/?>}, " #{attrs}\\0", global: false)
254 | end
255 |
256 | ###############################
257 | # Append Footnote Return Link #
258 | ###############################
259 |
260 | def append_footnote_link(note=%Block.FnDef{}) do
261 | fnlink = ~s[]
262 | [ last_block | blocks ] = Enum.reverse(note.blocks)
263 | last_block = append_footnote_link(last_block, fnlink)
264 | Enum.reverse([last_block | blocks])
265 | |> List.flatten
266 | end
267 |
268 | def append_footnote_link(block=%Block.Para{lines: lines}, fnlink) do
269 | [ last_line | lines ] = Enum.reverse(lines)
270 | last_line = "#{last_line} #{fnlink}"
271 | [put_in(block.lines, Enum.reverse([last_line | lines]))]
272 | end
273 |
274 | def append_footnote_link(block, fnlink) do
275 | [block, %Block.Para{lines: fnlink}]
276 | end
277 |
278 | end
279 |
--------------------------------------------------------------------------------
/web/static/vendor/prism.js:
--------------------------------------------------------------------------------
1 | /* http://prismjs.com/download.html?themes=prism-okaidia&languages=markup+css+clike+javascript+bash+docker+elixir+erlang+gherkin+haskell+json+jsx+sql&plugins=show-language */
2 | var _self="undefined"!=typeof window?window:"undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope?self:{},Prism=function(){var e=/\blang(?:uage)?-(\w+)\b/i,t=0,n=_self.Prism={util:{encode:function(e){return e instanceof a?new a(e.type,n.util.encode(e.content),e.alias):"Array"===n.util.type(e)?e.map(n.util.encode):e.replace(/&/g,"&").replace(/e.length)break e;if(!(v instanceof a)){u.lastIndex=0;var b=u.exec(v),k=1;if(!b&&h&&m!=r.length-1){if(u.lastIndex=y,b=u.exec(e),!b)break;for(var w=b.index+(g?b[1].length:0),_=b.index+b[0].length,A=m,S=y,P=r.length;P>A&&_>S;++A)S+=(r[A].matchedStr||r[A]).length,w>=S&&(++m,y=S);if(r[m]instanceof a||r[A-1].greedy)continue;k=A-m,v=e.slice(y,S),b.index-=y}if(b){g&&(f=b[1].length);var w=b.index+f,b=b[0].slice(f),_=w+b.length,x=v.slice(0,w),O=v.slice(_),j=[m,k];x&&j.push(x);var N=new a(l,c?n.tokenize(b,c):b,d,b,h);j.push(N),O&&j.push(O),Array.prototype.splice.apply(r,j)}}}}}return r},hooks:{all:{},add:function(e,t){var a=n.hooks.all;a[e]=a[e]||[],a[e].push(t)},run:function(e,t){var a=n.hooks.all[e];if(a&&a.length)for(var r,i=0;r=a[i++];)r(t)}}},a=n.Token=function(e,t,n,a,r){this.type=e,this.content=t,this.alias=n,this.matchedStr=a||null,this.greedy=!!r};if(a.stringify=function(e,t,r){if("string"==typeof e)return e;if("Array"===n.util.type(e))return e.map(function(n){return a.stringify(n,t,e)}).join("");var i={type:e.type,content:a.stringify(e.content,t,r),tag:"span",classes:["token",e.type],attributes:{},language:t,parent:r};if("comment"==i.type&&(i.attributes.spellcheck="true"),e.alias){var l="Array"===n.util.type(e.alias)?e.alias:[e.alias];Array.prototype.push.apply(i.classes,l)}n.hooks.run("wrap",i);var o="";for(var s in i.attributes)o+=(o?" ":"")+s+'="'+(i.attributes[s]||"")+'"';return"<"+i.tag+' class="'+i.classes.join(" ")+'"'+(o?" "+o:"")+">"+i.content+""+i.tag+">"},!_self.document)return _self.addEventListener?(_self.addEventListener("message",function(e){var t=JSON.parse(e.data),a=t.language,r=t.code,i=t.immediateClose;_self.postMessage(n.highlight(r,n.languages[a],a)),i&&_self.close()},!1),_self.Prism):_self.Prism;var r=document.currentScript||[].slice.call(document.getElementsByTagName("script")).pop();return r&&(n.filename=r.src,document.addEventListener&&!r.hasAttribute("data-manual")&&("loading"!==document.readyState?window.requestAnimationFrame?window.requestAnimationFrame(n.highlightAll):window.setTimeout(n.highlightAll,16):document.addEventListener("DOMContentLoaded",n.highlightAll))),_self.Prism}();"undefined"!=typeof module&&module.exports&&(module.exports=Prism),"undefined"!=typeof global&&(global.Prism=Prism);
3 | Prism.languages.markup={comment://,prolog:/<\?[\w\W]+?\?>/,doctype://i,cdata://i,tag:{pattern:/<\/?(?!\d)[^\s>\/=$<]+(?:\s+[^\s>\/=]+(?:=(?:("|')(?:\\\1|\\?(?!\1)[\w\W])*\1|[^\s'">=]+))?)*\s*\/?>/i,inside:{tag:{pattern:/^<\/?[^\s>\/]+/i,inside:{punctuation:/^<\/?/,namespace:/^[^\s>\/:]+:/}},"attr-value":{pattern:/=(?:('|")[\w\W]*?(\1)|[^\s>]+)/i,inside:{punctuation:/[=>"']/}},punctuation:/\/?>/,"attr-name":{pattern:/[^\s>\/]+/,inside:{namespace:/^[^\s>\/:]+:/}}}},entity:/?[\da-z]{1,8};/i},Prism.hooks.add("wrap",function(a){"entity"===a.type&&(a.attributes.title=a.content.replace(/&/,"&"))}),Prism.languages.xml=Prism.languages.markup,Prism.languages.html=Prism.languages.markup,Prism.languages.mathml=Prism.languages.markup,Prism.languages.svg=Prism.languages.markup;
4 | Prism.languages.css={comment:/\/\*[\w\W]*?\*\//,atrule:{pattern:/@[\w-]+?.*?(;|(?=\s*\{))/i,inside:{rule:/@[\w-]+/}},url:/url\((?:(["'])(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1|.*?)\)/i,selector:/[^\{\}\s][^\{\};]*?(?=\s*\{)/,string:{pattern:/("|')(\\(?:\r\n|[\w\W])|(?!\1)[^\\\r\n])*\1/,greedy:!0},property:/(\b|\B)[\w-]+(?=\s*:)/i,important:/\B!important\b/i,"function":/[-a-z0-9]+(?=\()/i,punctuation:/[(){};:]/},Prism.languages.css.atrule.inside.rest=Prism.util.clone(Prism.languages.css),Prism.languages.markup&&(Prism.languages.insertBefore("markup","tag",{style:{pattern:/(