Skip to content

Commit

Permalink
Merge pull request #3 from BoyWithSilverWings/feature/component
Browse files Browse the repository at this point in the history
Feature/component
  • Loading branch information
agneym authored Sep 20, 2019
2 parents fa2d86b + 111cc4d commit 44713df
Show file tree
Hide file tree
Showing 14 changed files with 209 additions and 30 deletions.
25 changes: 25 additions & 0 deletions .github/workflows/checkin.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
name: "Run tests"
on: [pull_request, push]

jobs:
check_pr:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1

- name: "npm ci"
run: npm ci

- name: "npm run build"
run: npm run build

- name: "npm run test"
run: npm run test

- name: "check for uncommitted changes"
# Ensure no changes, but ignore node_modules dir since dev/fresh ci deps installed.
run: |
git diff --exit-code --stat -- . ':!node_modules' \
|| (echo "##[error] found changed files after build. please 'npm run build && npm run format'" \
"and check in all changes" \
&& exit 1)
44 changes: 41 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@

Generates open graph images for your blog with Github Actions.

This github action scans your PR for changes to `md` or `mdx` files, reads frontmatter configuration from them and generates images for your SEO.

In your action file:

```yml
name: "Generate OG Images"
on: pull_request
Expand All @@ -26,18 +30,52 @@ For configuring the parameters, add following fields to the frontmatter:
```md
---
title: "Things you don't know about something 2019"
ogImage:
title: "Things you don't know"
subtitle: "There must be something"
imageUrl: "https://example.com/image-url.jpg"
background-color: "yellow"
font-color: "rgb(0, 0, 0)"
background: "yellow"
fontColor: "rgb(0, 0, 0)"
fontSize: "100%"
---
```

## Frontmatter Props

| Props | Description | Required |
| ---------- | :-------------------------------------: | -------: |
| title | Title of the image | |
| subtitle | Subtitle of the image | |
| imageUrl | The image thumbnail on the top | |
| background | Background color, gradient or image url | |
| fontColor | any css supported color | |
| fontSize | the font size | |

Works only with Pull Requests and `md` and `mdx` files.

## Repository level Props

These are props that you can configure in the action file to customise the working.

| Props | Description | Required |
| ------------ | :--------------------------------------: | -------: |
| path | Path to place the image URL in | true |
| commitMsg | Commit message when image is added | |
| background | Background color, gradient or image url | |
| fontColor | any css supported color | |
| fontSize | the font size | |
| componentUrl | Web Component to be rendered for output. | |

Frontmatter level props on a document always takes precedence over Repository level props.

### I need more customisation on the output.

The generator uses a web component to create the default output and provides a repository level prop to customise this web component.

The component currently being used is on [Github](https://github.com/BoyWithSilverWings/og-image-element) and published on [NPM](https://www.npmjs.com/package/@agney/og-image-element). The default URL is from [Unpkg](https://unpkg.com/) with [https://unpkg.com/@agney/[email protected]](https://unpkg.com/@agney/[email protected]).

You can substitute the same with `componentUrl` input in your workflow file. For more info on creating this web component, visit [source](https://github.com/BoyWithSilverWings/generate-og-image/blob/304fd9aa0b21b01b0fdc8a3d1a63a19ffdc1840d/demo/test-file.jpg)

## Thanks

1. [Zeit OG Image](https://github.com/zeit/og-image)
Expand Down
53 changes: 53 additions & 0 deletions __tests__/generate-html.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import generateHtml from "../src/generate-html";

describe("Generate HTML", () => {
it(`returns a string`, () => {
const result = generateHtml({});
expect(result).toBeTruthy();
});

it(`contains background variable`, () => {
const result = generateHtml({
background: "{{name}}"
});
expect(result.includes("--background")).toBe(true);
});

it(`contains font color variable`, () => {
const result = generateHtml({
fontColor: "{{name}}"
});
expect(result.includes("--fontColor")).toBe(true);
});

it(`contains font size variable`, () => {
const result = generateHtml({
fontSize: "{{name}}"
});
expect(result.includes("--fontSize")).toBe(true);
});

it(`contains passed in title`, () => {
const result = generateHtml({
title: `{{name}}`
});
expect(result.includes("{{name}}")).toBe(true);
expect(result.includes(`slot="title"`)).toBe(true);
});

it(`creates large payload`, () => {
const result = generateHtml({
assetPath: "demo/",
componentUrl: "https://unpkg.com/@agney/[email protected]",
commitMsg: "just some wholesome content. yo all!",
background: "red",
fontColor: "yellow",
fontSize: "90%",
title: "Generating open graph images with Github Actions",
subtitle: "Works with Markdown files",
imageUrl: "https://avatars3.githubusercontent.com/u/8883368?s=40&v=4"
});
console.log(result);
expect(true).toBe(true);
});
});
3 changes: 0 additions & 3 deletions __tests__/main.test.ts

This file was deleted.

16 changes: 14 additions & 2 deletions action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,24 @@ inputs:
commitMsg:
description: "commit message to be shown when adding image"
default: "just some wholesome content. yo all!"
background-color:
background:
description: "background color for image"
default: "#ffffff"
font-color:
fontColor:
description: "font color for image"
default: "#000000"
componentUrl:
description: "URL for web component"
default: "https://unpkg.com/@agney/[email protected]"
fontSize:
description: "Font size for the root"
default: "100%"
width:
description: "Width of the screen"
default: "1200"
height:
description: "Height of the screen"
default: "630"
runs:
using: "docker"
image: "Dockerfile"
Binary file modified demo/test-file.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
7 changes: 5 additions & 2 deletions demo/test-file.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,12 @@
title: Just hack'n
description: Nothing to see here
ogImage:
title: Jack Kings
subtitle: Another subtitle
title: Generating open graph images with Github Actions
subtitle: Works with Markdown files
imageUrl: https://avatars3.githubusercontent.com/u/8883368?s=40&v=4
background: red
fontColor: yellow
fontSize: 90%
---

This is some text about some stuff that happened sometime ago
6 changes: 6 additions & 0 deletions src/commit-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ import octokit from "./github-api";
import { USER_REPO, COMMITTER, GITHUB_HEAD_REF } from "./constants";
import { IRepoProps } from "./types";

/**
* Commit the image with reported filename and commit messsage
* @param content Image to be commited
* @param repoProps properties
* @param filename file to be commited as
*/
async function commitFile(
content: string,
repoProps: Partial<IRepoProps>,
Expand Down
12 changes: 12 additions & 0 deletions src/find-file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,12 +11,20 @@ import {
import octokit from "./github-api";
import { IFrontMatter, IFileProps } from "./types";

/**
* Get name of the file by stripping the extensions
* @param filename
*/
function getFileName(filename: string) {
const { length: len, [len - 1]: last } = filename.split("/");
const name = last.replace(/.mdx?/, "");
return name;
}

/**
* Extract JSON from markdown frontmatter
* @param files List of files in the PR
*/
function getAttributes(files: PullsListFilesResponseItem[]): IFileProps[] {
return files.map(file => {
const filename = file.filename;
Expand All @@ -34,6 +42,10 @@ function getAttributes(files: PullsListFilesResponseItem[]): IFileProps[] {
});
}

/**
* Find files with md and mdx extensions and extract information
* @returns Front matter attributes as JSON
*/
async function findFile() {
const [owner, repo] = USER_REPO;
const githubCtx: any = JSON.parse(GITHUB_CONTEXT as string);
Expand Down
28 changes: 17 additions & 11 deletions src/generate-html.ts
Original file line number Diff line number Diff line change
@@ -1,35 +1,41 @@
import { IProps } from "./types";
import { debug } from "@actions/core";
import { IRepoProps } from "./types";

function generateHtml(prop: Partial<IProps>) {
debug(JSON.stringify(prop));
function createVariables(name: string, value?: string) {
if (value) {
return `--${name}: ${value};`;
}
return "";
}

function generateHtml(prop: Partial<IRepoProps>) {
return `
<!doctype html>
<html lang="en-GB">
<head>
<meta charset="utf-8">
<link href="https://fonts.googleapis.com/css?family=Aleo|Open+Sans&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Nunito:600|Open+Sans&display=swap" rel="stylesheet">
<style>
body {
margin: 0;
font-family: 'Open Sans', sans-serif;
}
og-image-element {
--heading-font: 'Aleo', serif;
--background-color: ${prop.backgroundColor};
--font-color: ${prop.fontColor};
--heading-font: 'Nunito', serif;
${createVariables("fontColor", prop.fontColor)}
${createVariables("background", prop.background)}
${createVariables("fontSize", prop.fontSize)}
}
</style>
<script type="module" rel="preload" src="https://unpkg.com/@agney/[email protected]"></script>
<script type="module" rel="preload" src="${prop.componentUrl}"></script>
</head>
<body>
<og-image-element subtitle=${prop.subtitle || ""}>
<og-image-element subtitle="${prop.subtitle || ""}">
${
prop.imageUrl
? `<img slot="image" src="${prop.imageUrl}" height="100%" />`
: ``
}
<div slot="title">${prop.title}</div>
<div slot="title">${prop.title || ""}</div>
</og-image-element>
</body>
</html>
Expand Down
7 changes: 6 additions & 1 deletion src/generate-image.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,16 @@
import puppeteer from "puppeteer-core";
import { IViewport } from "./types";

async function generateImage(html: string) {
async function generateImage(viewport: IViewport, html: string) {
const browser = await puppeteer.launch({
executablePath: "/usr/bin/google-chrome-unstable",
args: ["--no-sandbox"]
});
const page = await browser.newPage();
page.setViewport({
width: +viewport.width,
height: +viewport.height
});
await page.setContent(html);
const image = await page.screenshot({ encoding: "base64" });
await browser.close();
Expand Down
11 changes: 8 additions & 3 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
#!/usr/bin/env node
import { warning, debug } from "@actions/core";
import { warning } from "@actions/core";

import { GITHUB_TOKEN, GITHUB_EVENT_NAME } from "./constants";
import generateImage from "./generate-image";
Expand All @@ -22,7 +22,6 @@ async function run() {

const repoProps = await getRepoProps();
const fileProperties = await findFile();
debug(JSON.stringify(fileProperties));

if (!fileProperties.length) {
warning("No compatible files found");
Expand All @@ -34,7 +33,13 @@ async function run() {
...property.attributes
});

const image = await generateImage(html);
const image = await generateImage(
{
width: repoProps.width,
height: repoProps.height
},
html
);

commitFile(image, repoProps, property.filename);
});
Expand Down
16 changes: 12 additions & 4 deletions src/repo-props.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,21 @@ import { getInput } from "@actions/core";
async function getRepoProps() {
const assetPath = getInput(`path`);
const commitMsg = getInput(`commitMsg`);
const backgroundColor = getInput(`background-color`);
const fontColor = getInput(`font-color`);
const background = getInput(`background`);
const fontColor = getInput(`fontColor`);
const componentUrl = getInput("componentUrl");
const fontSize = getInput("fontSize");
const width = getInput("width");
const height = getInput("height");
return {
assetPath,
componentUrl,
commitMsg,
backgroundColor,
fontColor
background,
fontColor,
fontSize,
width,
height
};
}

Expand Down
11 changes: 10 additions & 1 deletion src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,9 @@ export interface IProps {
subtitle: string;
filename: string;
imageUrl: string;
backgroundColor: string;
background: string;
fontColor: string;
fontSize: string;
}

export interface IFrontMatter {
Expand All @@ -19,4 +20,12 @@ export interface IFrontMatter {
export interface IRepoProps extends IProps {
assetPath: string;
commitMsg: string;
componentUrl: string;
width: string | number;
height: string | number;
}

export interface IViewport {
width: string | number;
height: string | number;
}

0 comments on commit 44713df

Please sign in to comment.