philomena/lib/philomena_web/controllers/page/history_controller.ex

40 lines
1.1 KiB
Elixir
Raw Permalink Normal View History

2019-12-06 18:59:17 +01:00
defmodule PhilomenaWeb.Page.HistoryController do
use PhilomenaWeb, :controller
alias Philomena.StaticPages.StaticPage
alias Philomena.StaticPages.Version
alias Philomena.Repo
import Ecto.Query
2019-12-06 19:09:29 +01:00
plug :load_resource, model: StaticPage, id_name: "page_id", id_field: "slug", persisted: true
2019-12-06 18:59:17 +01:00
def index(conn, _params) do
page = conn.assigns.static_page
2019-12-06 19:06:54 +01:00
{versions, _last_body} =
2019-12-06 18:59:17 +01:00
Version
|> where(static_page_id: ^page.id)
|> preload(:user)
|> order_by(desc: :created_at)
|> Repo.all()
|> generate_differences(page.body)
2020-01-11 05:20:19 +01:00
render(conn, "index.html",
title: "Revision History for Page `#{page.title}'",
layout_class: "layout--wide",
versions: versions
)
2019-12-06 18:59:17 +01:00
end
defp generate_differences(pages, current_body) do
Enum.map_reduce(pages, current_body, fn page, previous_body ->
2019-12-15 18:33:37 +01:00
difference = List.myers_difference(split(page.body), split(previous_body))
2019-12-06 18:59:17 +01:00
2019-12-06 19:06:54 +01:00
{%{page | difference: difference}, page.body}
2019-12-06 18:59:17 +01:00
end)
end
defp split(nil), do: ""
defp split(body), do: String.split(body, "\n")
2019-12-15 18:33:37 +01:00
end