summaryrefslogtreecommitdiff
path: root/app/helpers/webpack_helper.rb
blob: 552c71e5c51c0612e7508233fcd71a6a76a75af6 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
# frozen_string_literal: true

module WebpackHelper
  def webpack_bundle_tag(bundle)
    javascript_include_tag(*webpack_entrypoint_paths(bundle))
  end

  def webpack_controller_bundle_tags
    chunks = []

    action = case controller.action_name
             when 'create' then 'new'
             when 'update' then 'edit'
             else controller.action_name
             end

    route = [*controller.controller_path.split('/'), action].compact

    until chunks.any? || route.empty?
      entrypoint = "pages.#{route.join('.')}"
      begin
        chunks = webpack_entrypoint_paths(entrypoint, extension: 'js')
      rescue Gitlab::Webpack::Manifest::AssetMissingError
        # no bundle exists for this path
      end
      route.pop
    end

    if chunks.empty?
      chunks = webpack_entrypoint_paths("default", extension: 'js')
    end

    javascript_include_tag(*chunks)
  end

  def webpack_entrypoint_paths(source, extension: nil, exclude_duplicates: true)
    return "" unless source.present?

    paths = Gitlab::Webpack::Manifest.entrypoint_paths(source)
    if extension
      paths.select! { |p| p.ends_with? ".#{extension}" }
    end

    force_host = webpack_public_host
    if force_host
      paths.map! { |p| "#{force_host}#{p}" }
    end

    if exclude_duplicates
      @used_paths ||= []
      new_paths = paths - @used_paths
      @used_paths += new_paths
      new_paths
    else
      paths
    end
  end

  def webpack_public_host
    ActionController::Base.helpers.compute_asset_host
  end

  def webpack_public_path
    relative_path = Rails.application.config.relative_url_root
    webpack_path = Webpacker.instance.config.public_output_path.relative_path_from(Webpacker.instance.config.root_path)

    File.join(webpack_public_host.to_s, relative_path.to_s, webpack_path.to_s, '')
  end
end