Prepare and generate HTML for a page

@param {Output} output
@param {Page} page
@return {Promise<Page>}
507973
function generatePage(output, page) {
    var book = output.getBook();
    var engine = createTemplateEngine(output);

    return timing.measure(
        'page.generate',
        Promise(page)
        .then(function(resultPage) {
            var file = resultPage.getFile();
            var filePath = file.getPath();
            var parser = file.getParser();
            var context = JSONUtils.encodeOutputWithPage(output, resultPage);

            if (!parser) {
                return Promise.reject(error.FileNotParsableError({
                    filename: filePath
                }));
            }

            // Call hook "page:before"
            return callPageHook('page:before', output, resultPage)

            // Escape code blocks with raw tags
            .then(function(currentPage) {
                return parser.preparePage(currentPage.getContent());
            })

            // Render templating syntax
            .then(function(content) {
                var absoluteFilePath = path.join(book.getContentRoot(), filePath);
                return Templating.render(engine, absoluteFilePath, content, context);
            })

            .then(function(output) {
                var content = output.getContent();

                return parser.parsePage(content)
                .then(function(result) {
                    return output.setContent(result.content);
                });
            })

            // Post processing for templating syntax
            .then(function(output) {
                return Templating.postRender(engine, output);
            })

            // Return new page
            .then(function(content) {
                return resultPage.set('content', content);
            })

            // Call final hook
            .then(function(currentPage) {
                return callPageHook('page', output, currentPage);
            });
        })
    );
}
1099185
function pagedGet ({source, method, skip = 0, aggregatedResponse = null, query = null}) {
  const fullQuery = Object.assign({},
    {
      skip: skip,
      limit: pageLimit,
      order: 'sys.createdAt,sys.id'
    },
    query
  )

  return source[method](fullQuery)
    .then((response) => {
      if (!aggregatedResponse) {
        aggregatedResponse = response
      } else {
        aggregatedResponse.items = aggregatedResponse.items.concat(response.items)
      }
      const page = Math.ceil(skip / pageLimit) + 1
      const pages = Math.ceil(response.total / pageLimit)
      logEmitter.emit('info', `Fetched ${aggregatedResponse.items.length} of ${response.total} items (Page ${page}/${pages})`)
      if (skip + pageLimit <= response.total) {
        return pagedGet({source, method, skip: skip + pageLimit, aggregatedResponse, query})
      }
      return aggregatedResponse
    })
}
991464
function onPage(output, page) {
    var options   = output.getOptions();
    var prefix    = options.get('prefix');

    var file      = page.getFile();

    var book      = output.getBook();
    var plugins   = output.getPlugins();
    var state     = output.getState();
    var resources = state.getResources();

    var engine = createTemplateEngine(output, page.getPath());

    // Output file path
    var filePath = fileToOutput(output, file.getPath());

    // Calcul relative path to the root
    var outputDirName = path.dirname(filePath);
    var basePath = LocationUtils.normalize(path.relative(outputDirName, './'));

    return Modifiers.modifyHTML(page, getModifiers(output, page))
    .then(function(resultPage) {
        // Generate the context
        var context = JSONUtils.encodeOutputWithPage(output, resultPage);
        context.plugins = {
            resources: Plugins.listResources(plugins, resources).toJS()
        };

        context.template = {
            getJSContext: function() {
                return {
                    page: omit(context.page, 'content'),
                    config: context.config,
                    file: context.file,
                    gitbook: context.gitbook,
                    basePath: basePath,
                    book: {
                        language: book.getLanguage()
                    }
                };
            }
        };

        // We should probabbly move it to "template" or a "site" namespace
        context.basePath = basePath;

        // Render the theme
        return Templating.renderFile(engine, prefix + '/page.html', context)

        // Write it to the disk
        .then(function(tplOut) {
            return writeFile(output, filePath, tplOut.getContent());
        });
    });
}
540148
function encodeProgress(output, page) {
    var current = page.getPath();
    var navigation = encodeNavigation(output);
    navigation = Immutable.Map(navigation);

    var n = navigation.size;
    var percent = 0, prevPercent = 0, currentChapter = null;
    var done = true;

    var chapters = navigation
        .map(function(nav, chapterPath) {
            nav.path = chapterPath;
            return nav;
        })
        .valueSeq()
        .sortBy(function(nav) {
            return nav.index;
        })
        .map(function(nav, i) {
            // Calcul percent
            nav.percent = (i * 100) / Math.max((n - 1), 1);

            // Is it done
            nav.done = done;
            if (nav.path == current) {
                currentChapter = nav;
                percent = nav.percent;
                done = false;
            } else if (done) {
                prevPercent = nav.percent;
            }

            return nav;
        })
        .toJS();

    return {
        // Previous percent
        prevPercent: prevPercent,

        // Current percent
        percent: percent,

        // List of chapter with progress
        chapters: chapters,

        // Current chapter
        current: currentChapter
    };
}
505611
function evaluate(page, func) {
    var args = [].slice.call(arguments, 2);
    var fn = "function() { return (" + func.toString() + ").apply(this, " + JSON.stringify(args) + ");}";
    return page.evaluate(fn);
}
849985
function Output(options) {
  options = options || {};
  this.command = options.command || '';
  this.args = options.args || {};
  this.typed = options.typed || '';
  this.canonical = options.canonical || '';
  this.hidden = options.hidden === true ? true : false;

  this.type = undefined;
  this.data = undefined;
  this.completed = false;
  this.error = false;
  this.start = new Date();

  this.promise = new Promise(function(resolve, reject) {
    this._resolve = resolve;
  }.bind(this));
}
287426
function () {
            var $loadStylesheetPromise,
                $loadMetadataPromise,
                $pageOneContentPromise,
                $pageOneTextPromise;

            if ($assetsPromise) {
                return;
            }

            $loadMetadataPromise = scope.get('metadata');
            $loadMetadataPromise.then(function handleMetadataResponse(metadata) {
                config.metadata = metadata;
            });

            // don't load the stylesheet for IE < 9
            if (browser.ielt9) {
                stylesheetEl = util.insertCSS('');
                config.stylesheet = stylesheetEl.styleSheet;
                $loadStylesheetPromise = $.when('').promise({
                    abort: function () {}
                });
            } else {
                $loadStylesheetPromise = scope.get('stylesheet');
                $loadStylesheetPromise.then(function handleStylesheetResponse(cssText) {
                    stylesheetEl = util.insertCSS(cssText);
                    config.stylesheet = stylesheetEl.sheet;
                });
            }


            // load page 1 assets immediately if necessary
            if (config.autoloadFirstPage &&
                (!config.pageStart || config.pageStart === 1)) {
                if (support.svg && config.useSVG) {
                    $pageOneContentPromise = scope.get('page-svg', 1);
                } else if (config.conversionIsComplete) {
                    // unfortunately, page-1.png is not necessarily available
                    // on View API's document.viewable event, so we can only
                    // prefetch page-1.png if conversion is complete
                    $pageOneContentPromise = scope.get('page-img', 1);
                }
                if (config.enableTextSelection) {
                    $pageOneTextPromise = scope.get('page-text', 1);
                }
            }

            // when both metatadata and stylesheet are done or if either fails...
            $assetsPromise = $.when($loadMetadataPromise, $loadStylesheetPromise)
                .fail(function (error) {
                    if ($assetsPromise) {
                        $assetsPromise.abort();
                    }
                    scope.ready();
                    scope.broadcast('asseterror', error);
                    scope.broadcast('fail', error);
                })
                .then(completeInit)
                .promise({
                    abort: function () {
                        $assetsPromise = null;
                        $loadMetadataPromise.abort();
                        $loadStylesheetPromise.abort();
                        if ($pageOneContentPromise) {
                            $pageOneContentPromise.abort();
                        }
                        if ($pageOneTextPromise) {
                            $pageOneTextPromise.abort();
                        }
                    }
                });
        }
527451
function render(content) {
  var deferred = q.defer();

  var blockType = "normal";
  var lines = content.split("\n");
  var blocks = {};
  for (var i=0; i<lines.length; i++) {
    var line = lines[i];

    if (line.substr(0,1) == "@") {
      blockType = line.substr(1).trim();
      if (blockType === "end") blockType = "normal";
      continue;
    }
    if (blocks[blockType])
      blocks[blockType] += line + "\n";
    else
      blocks[blockType] = line + "\n";
  }

  for (var key in blocks) {
    if (blocks.hasOwnProperty(key)) {
      try {
        blocks[key] = metaMarked(blocks[key]);
      } catch(err) {
        return deferred.reject(new Error(err));
      }
    }
    deferred.resolve(blocks);
  }

  return deferred.promise;
}
156929
protected void setOutlinePageInput(VdmContentOutlinePage page,
			IEditorInput input) {
		if (page == null)
			return;

		IVdmElement je = getInputVdmElement();
		if (je != null && je.exists())
			page.setInput(je);
		else
			page.setInput(null);

	}
47860
function onPage(output, page) {
    var file = page.getFile();
    var readme = output.getBook().getReadme().getFile();

    return Modifiers.modifyHTML(page, getModifiers(output, page))
    .then(function(resultPage) {
        // Generate the JSON
        var json = JSONUtils.encodeBookWithPage(output.getBook(), resultPage);

        // Delete some private properties
        delete json.config;

        // Specify JSON output version
        json.version = JSON_VERSION;

        // File path in the output folder
        var filePath = file.getPath() == readme.getPath()? 'README.json' : file.getPath();
        filePath = PathUtils.setExtension(filePath, '.json');

        // Write it to the disk
        return writeFile(
            output,
            filePath,
            JSON.stringify(json, null, 4)
        );
    });
}
255268
async function _html(req, res) {
  const { queueName, queueHost, state } = req.params;
  const {Queues} = req.app.locals;
  const queue = await Queues.get(queueName, queueHost);
  const basePath = req.baseUrl;
  if (!queue) return res.status(404).render('dashboard/templates/queueNotFound', {basePath, queueName, queueHost});

  if (!isValidState(state, queue.IS_BEE)) return res.status(400).json({ message: `Invalid state requested: ${state}` });

  let jobCounts;
  if (queue.IS_BEE) {
    jobCounts = await queue.checkHealth();
    delete jobCounts.newestJob;
  } else {
    jobCounts = await queue.getJobCounts();
  }

  const page = parseInt(req.query.page, 10) || 1;
  const pageSize = parseInt(req.query.pageSize, 10) || 100;

  const startId = (page - 1) * pageSize;
  const endId = startId + pageSize - 1;

  let jobs;
  if (queue.IS_BEE) {
    const page = {};

    if (['failed', 'succeeded'].includes(state)) {
      page.size = pageSize;
    } else {
      page.start = startId;
      page.end = endId;
    }

    jobs = await queue.getJobs(state, page);

    // Filter out Bee jobs that have already been removed by the time the promise resolves
    jobs = jobs.filter((job) => job);
  } else {
    jobs = await queue[`get${_.capitalize(state)}`](startId, endId);
  }

  let pages = _.range(page - 6, page + 7)
    .filter((page) => page >= 1);
  while (pages.length < 12) {
    pages.push(_.last(pages) + 1);
  }
  pages = pages.filter((page) => page <= _.ceil(jobCounts[state] / pageSize));

  return res.render('dashboard/templates/queueJobsByState', {
    basePath,
    queueName,
    queueHost,
    state,
    jobs,
    jobsInStateCount: jobCounts[state],
    disablePagination: queue.IS_BEE && (state === 'succeeded' || state === 'failed'),
    currentPage: page,
    pages,
    pageSize,
    lastPage: _.last(pages)
  });
}
940405
function render(q) {
  if (!q.length) {
    complete();
    return;
  }

  const item = q.shift();

  // render HTML file
  fs.writeFile(`${item.file}.html`, item.html, err => {
    if (err) throw err;

    // if prerendering is enabled
    if (typeof options.prerender === "object" && options.prerender !== null) {
      // wait for response from browser
      puppet.once("message", height => {
        // store height
        item.json.height = height;

        // render JSON file
        fs.writeFile(`${item.file}.json`, JSON.stringify(item.json), err => {
          if (err) throw err;
          process.send(`success::Generated ${item.name}`);

          // render next
          render(q);
        });
      });

      // open html file in browser
      puppet.send({
        url: `http://localhost:${options.prerender.port}/${
          options.prerender.path
        }/${item.slug}.html`
      });

      // if no prerendering is to be done
    } else {
      // render JSON file
      fs.writeFile(`${item.file}.json`, JSON.stringify(item.json), err => {
        if (err) throw err;
        process.send(`success::Generated ${item.name}`);

        // render next
        render(q);
      });
    }
  });
}
688500
function generateCustomOutput(outputConfig) {

			// Accesses context
			var context = prepareBaseTemplateContext();
			_.extend(context, outputConfig.context);

			// Prepares config attributes related to template filepath
			var templatePath = outputConfig.template;
			var extension = path.extname(templatePath);
			var syntax = outputConfig.syntax || '';

			// Renders template with given context
			var template = readTemplate(templatePath, syntax, extension);
			var output = renderTemplate(template, context);

			// Prepares config attributes related to destination filepath
			var dest = outputConfig.dest || o.dest;

			var filepath;
			var destParent;
			var destName;

			if (path.extname(dest) === '') {
				// If user specifies a directory, filename should be same as template
				destParent = dest;
				destName = path.basename(outputConfig.template);
				filepath = path.join(dest, destName);
			}
			else {
				// If user specifies a file, that is our filepath
				destParent = path.dirname(dest);
				filepath = dest;
			}

			// Ensure existence of parent directory and output to file as desired
			mkdirp.sync(destParent);
			fs.writeFileSync(filepath, output);
		}
1118648
function formatOutput(output) {
    var indent = '  ';
    var pad = '  ';
    var results = [];
    results.push('AppDir:' + output.appDir);
    output.suites.forEach(function(suite) {
      results.push(pad + 'Suite: ' + suite.description + ' -- ' + suite.status);
      pad+=indent;
      suite.specs.forEach(function(spec) {
        results.push(pad + spec.status + ' - ' + spec.description);
        if (spec.failedExpectations) {
          pad+=indent;
          spec.failedExpectations.forEach(function (fe) {
            results.push(pad + 'message: ' + fe.message);
          });
          pad=pad.substr(2);
        }
      });
      pad = pad.substr(2);
      results.push('');
    });
    results.push('');
    return results.join('\n');
  }
798045
function outputOutput(output, cb) {
    cb = u.maybe(cb);

    if (!output) return cb(new Error('no output specified'));

    debug('output %s', output.name);
    var files = output.files = [];

    var omit = output.omitRoutes;
    if (omit && !u.isArray(omit)) { omit = [omit]; }

    // TODO: re-use similar filter in server/serve-statics and server/serve-scripts
    var filterRe = new RegExp( '^(/admin/|/server/' +
                (opts.editor ? '' : '|/pub/') +
                       (omit ? '|' + u.map(omit, u.escapeRegExp).join('|') : '') +
                               ')');

    // pass1: collect files to generate (not /server or /admin or /pub)
    u.each(generator.pages, function(page) {
      if (filterRe.test(page._href)) return;
      if (output.match && !output.match(page)) return;
      var file = { page: page, path: page._href };
      if (page['http-header']) { file['http-header'] = page['http-header']; }
      files.push(file);
    });

    // pass2:
    fixOutputPaths(output, files);

    // pass3: generate using (possibly modified) file paths for relPaths
    // E.g. /adobe may live in the file /adobe/index.html so the relPath is '..'
    u.each(files, function(file) {
      var renderOpts =
        output.relPaths   ? { relPath:u.relPath(file.path) } :
        output.staticRoot ? { relPath:output.staticRoot } :
        opts.relPaths     ? { relPath:u.relPath(file.path) } :
        opts.staticRoot   ? { relPath:opts.staticRoot } :
        {};
      if (output.fqImages) { renderOpts.fqImages = output.fqImages; }
      file.text = generator.renderDoc(file.page, renderOpts);
      delete file.page;
    });

    output.src.put(files, cb);
  }
949594
def render_page(page, page_args):
    
    print(page_args)
    template_name = page.template if page.template else page.name
    template = "signage/pages/{}.html".format(template_name)
    if page.function:
        context_method = getattr(pages, page.function)
    else:
        context_method = getattr(pages, page.name)
    sign, request = page_args
    context = context_method(page, sign, request)
    return render_to_string(template, context)
1111373
function renderPage(state) {
    // Get presenter object
    piccolo.require(state.resolved.name, function (error, Resource) {
      if (error) return piccolo.emit('error', error);

      var presenter = new Resource(state.query.href, document);
          presenter[state.resolved.method].apply(presenter, state.resolved.args);
    });
  }