extension.rb 7.96 KB
Newer Older
Chris Snijder's avatar
Chris Snijder committed
1
2
3
4
5
6
7
8
9
10
11
12
# Require core library
require 'middleman-core'

# Extension namespace
class RecursiveNav < ::Middleman::Extension
  # option :my_option, 'default', 'An example option'

  def initialize(app, options_hash={}, &block)
    # Call super to build options from the options_hash
    super
  end

Chris Snijder's avatar
Chris Snijder committed
13
   helpers do
Chris Snijder's avatar
Chris Snijder committed
14
15
16
17
18
19
20
21
22
23
24
    # Return a list of links with translated versions of this page
    #
    #
    def translation_links
      links = {}
      locales.select{|l| l != locale}.each do |loc|
        # Blog seems to treat localisation way differently, so we have a different
        # solutions for blog posts than for other pages.
        if current_page.path.start_with? "blog"
          # Check if same file exists in other language
          if File.exists? current_page.source_file.sub("/#{locale}/", "/#{loc}/")
25
            links[loc] = url_for('/' + current_page.path.sub("/#{locale}/", "/#{loc}/"))
Chris Snijder's avatar
Chris Snijder committed
26
27
28
          end
        else
          path = current_page.target.sub("pages/", "").sub(/([\.\/])#{locale}([\.\/])/, "\\1#{loc}\\2")
29
30
31
          url = extensions[:i18n].localized_path("/#{path}", loc)
          if url
            links[loc] = url_for(url)
Chris Snijder's avatar
Chris Snijder committed
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
          end
        end
      end
      links
    end

    class NavNode
      attr_reader :type
      attr_accessor :children
      attr_reader :data
      attr_reader :weight
      attr_reader :title
      attr_reader :path
      attr_reader :page_id
      attr_reader :url

      def initialize(path, page_id)
        @type = :node
        @children = nil
        @data = Middleman::Util::EnhancedHash.new
        if meta = _meta_file(path)
          @data = meta
        end
55
56
        @weight = meta.nav.weight rescue 99999
        @title = meta.nav.title rescue meta.title rescue File.basename(path).capitalize
Chris Snijder's avatar
Chris Snijder committed
57
58
59
60
61
62
63
64
65
66
67
68
69
        @path = path
        @page_id = page_id
        @url = nil
      end

      def is_index?
        return @page_id == 'index' || @page_id.end_with?('/index')
      end

      private
      def _meta_file(path)
        meta_file = File.join path, "_meta.y{ml,aml}"
        if (files = Dir.glob(meta_file)).length > 0
Chris Snijder's avatar
Chris Snijder committed
70
          # puts "== File(s) \"#{files.join(", ")}\" exist(s)."
Chris Snijder's avatar
Chris Snijder committed
71
        else
Chris Snijder's avatar
Chris Snijder committed
72
          # puts "== File \"#{meta_file}\" does not exist."
Chris Snijder's avatar
Chris Snijder committed
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
          return nil
        end
        files.each do |f|
          begin
            return Middleman::Util::EnhancedHash.new(YAML.load_file f)
          rescue IOError => e
            puts "== Can't read \"#{f}\", reason: #{e}"
          end
        end
        return nil
      end
    end

    class NavNodeResource < NavNode
      attr_reader :type
      attr_accessor :children
      attr_reader :data
      attr_reader :weight
      attr_reader :title
      attr_reader :path
      attr_reader :page_id
      attr_reader :url
      attr_reader :locale
      attr_reader :nav
      attr_reader :nav_title
      attr_reader :resource
      attr_reader :page_id
      def initialize(resource)
        @type = resource.metadata[:resource_type]
        @children = nil
        @data = Middleman::Util::EnhancedHash.new
        if meta = _meta_file(File.dirname(resource.source_file))
          @data = meta
        end
        @data.deep_merge!(resource.data)
108
        @weight = @data.nav.weight rescue 99999
Chris Snijder's avatar
Chris Snijder committed
109
110
111
112
113
114
115
        @title = @data.title
        @path = File.dirname(
          resource.source_file.sub(/^#{__dir__}\/source\//, '')
        )
        @page_id = resource.page_id
        @url = resource.url
        @locale = resource.options[:locale]
116
117
118
119
120
121
122
123
124
125
        @nav = resource.data.nav rescue Middleman::Util::EnhancedHash.new
        begin
            @nav_title = @data.nav.title
        rescue
            @nav_title = @data&.title
        rescue
            @nav_title = resource.title
        rescue
            @nav_title = "No title set"
        end
Chris Snijder's avatar
Chris Snijder committed
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
        @resource = resource
      end
    end

    def _recurse_nav(resources, start, max_levels)
      nodes = []
      # Get all page_id's of index files
      indexes = resources.select {|r| r.page_id.end_with? "index"}
      indexes.map! {|r| File.dirname(r.page_id)}
      # Intersect arrays to find paths with no index
      no_index_res = resources.reject {|r| indexes.include? File.dirname(r.page_id) }
      no_index_res.map! {|r| [File.dirname(r.source_file), r.page_id]}

      # Recursively find directories without indexes
      no_index_deep = []
      no_index_res.uniq.each do |path, page_id|
        page_id = File.dirname(page_id)
        page_id_split = page_id.split('/')
        # Check from deepest to shallowest level
        (page_id_split.length-1).downto(0) do |i|
          sub_id = page_id_split[0..i].join("/")
          sub_path = path.split('/')
          sub_path = sub_path[0..sub_path.length-i].join('/')
          if not indexes.include? sub_id
            no_index_deep << [sub_path, sub_id]
          end
        end
      end

      no_index_deep.uniq.each do |path, page_id|
        # Directory only nodes, i.e. no [title.html] nor directory/index.html
        nodes << NavNode.new(path, "#{page_id}/index")
      end

      # Normal resources that represent pages
      resources.each do |r|
        nodes << NavNodeResource.new(r)
      end

      # All resources and empty paths converted to NavNodes and NavNodeResource
      # NavNodes are orphaned so we need to recreate parent child structure from
      # paths
      node_index = nodes.map { |n| [n.page_id, {:node => n}] }.to_h
      # Limit node levels to max_levels
      node_index.select! {|page_id, data|
        if data[:node].is_index?
          # Indexes are physically saved *under* the dir, so one more level is
          # allowed here.
          page_id.count('/') <= max_levels
        else
          page_id.count('/') <= max_levels - 1
        end
      }
      node_index.each do |page_id, data|
        parent = File.dirname(page_id)
        if data[:node].is_index?
          # Index pages belong one level higher..
          parent = File.dirname(parent)
        end
        data[:parent] = parent == "." ? "index" : parent
      end

      def _recurse_children(node_index, parent)
        # Select items with passed parent as a parent
        level_nodes = node_index.select {|page_id, data| data[:parent] == parent}
        nodes = []
        # Add all nodes to the curren level.
        nodes = level_nodes.map do |page_id, data|
          # And also recurse over their children by their path
          node = data[:node]
          new_parent = File.dirname(page_id)
          unless new_parent == parent
            children = _recurse_children(node_index, new_parent)
            if children.length > 0
              node.children = children
            end
          end
          node
        end
        nodes.sort_by! {|n| n.weight}
      end

      tree = _recurse_children node_index, start

Chris Snijder's avatar
Chris Snijder committed
210
211
212
213
214
215
216
217
218
      #def traverse_tree(tree, level)
      #  for node in tree
      #    puts "#{'##' * level} #{node.page_id}"
      #    if node.children
      #      traverse_tree node.children, level+1
      #    end
      #  end
      #end
      #traverse_tree(tree, 1)
Chris Snijder's avatar
Chris Snijder committed
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
      tree
    end

    ##
    # Return part of the sitemap that can be used as navigation
    # @param locale str Locale you want for your navigation by default whatever
    #   is mounted at root
    # @param node str From where in the navigation tree you want to start
    # @returns array sitemap.resources subset
    def generate_nav locale, max_levels=10, start="index"
      # We need only links to HTML pages
      res = sitemap.resources.find_all {|r| r.ext == ".html"}
      # Select only resources tagged with a resource type of :page
      res.select! {|r| r.metadata[:resource_type]&.include? :page}
      # Filter out what is in the currently selected locale
      res.select! {|r| r.options[:locale] == locale}
      # Only get resources that are within the `start` path,
      # e.g. if `start`=="products" only return everything *under* products.
      if start != "index"
        res.select! do |r|
          r.page_id.start_with?(start) &&
          r.page_id.sub!(/^#{start}/, '').length > 0
        end
      end
      _recurse_nav res, start, max_levels
    end
  end
end