Skip to content

Commit

Permalink
initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
haikyuu committed Apr 12, 2023
0 parents commit a55af5d
Show file tree
Hide file tree
Showing 13 changed files with 2,637 additions and 0 deletions.
31 changes: 31 additions & 0 deletions .github/workflows/release.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
name: Create Release
on:
push:
tags:
- "*"
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v3

- name: Set up Node.js
uses: actions/setup-node@v3
with:
node-version: 18.x
cache: yarn

- name: Install dependencies
run: yarn install --immutable

- name: Compile assets
run: yarn build

- name: Create block tarballs
run: node ./release.ts

- name: Release
uses: softprops/action-gh-release@v1
with:
files: dist/*.tar.gz
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
node_modules
.DS_Store
dist-ssr
*.local
.yalc.lock
.yalc
dist
7 changes: 7 additions & 0 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
Copyright 2022 GitHub and contributors

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
45 changes: 45 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
# GitHub Blocks Template

Use this repository as a starter template for building your own Blocks.
## Quickstart

> 🛑 Currently, you must be flagged into the [GitHub Blocks Technical Preview](https://blocks.githubnext.com) in order to develop blocks. There is no "offline" development mode at this time.
Fork this repo using the [`Use this template`](https://github.com/githubnext/blocks-template/generate) button above:

!["Use this template" button](https://user-images.githubusercontent.com/8978670/144893319-5d45ab5c-12c0-42b4-99f8-97f658deb03b.png)

Then, clone _your_ repo (not [this one!](https://github.com/githubnext/blocks-template)) and get ready for action:

```bash
yarn # install dependencies
yarn start # start the dev server
# Or use npm, pnpm, you know the drill
```

When you visit [localhost:4000](https://localhost:4000) in your browser, you'll be
redirected to the Blocks app, but your locally-developed blocks will appear in the block picker:

<img alt="Block picker" src="https://user-images.githubusercontent.com/56439/181648955-101b6567-3f9b-44b3-af99-7ef3ca6161b9.png" width="418" />

(if you're using Safari (or another browser that doesn't permit calling `http` URLs from an `https` page), run `yarn start-https` and visit [https://localhost:4000](https://localhost:4000) instead.)

This template includes one example File Block and one Folder Block. The dev server supports hot reloading, so make some changes, and see what they do!

## Under the hood

Currently, Blocks are [React](https://reactjs.org/) components. They have a well-defined contract with their surroundings, and receive a [fixed set of props](https://github.com/githubnext/blocks/blob/main/docs/Developing%20blocks/4%20API%20reference%20and%20types.md) when they are instantiated. They are developed in [TypeScript](https://www.typescriptlang.org/), and bundled with [Vite](https://vitejs.dev/).

## More Info

Visit [githubnext/blocks](https://blocks.githubnext.com/githubnext/blocks) for a full tutorial, documentation, and examples.

You should also join us in our discord! There's a [#blocks channel](https://discord.com/channels/735557230698692749/1039950186136469535) where you can connect with us and other folks who are building Blocks:

> 👋 https://discord.gg/githubnext
## License

MIT

✌️ ❤️
_GitHub Next_
20 changes: 20 additions & 0 deletions blocks.config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
[
{
"type": "file",
"id": "scrim-file-block",
"title": "Scrimba File Block",
"description": "Record interactive code-casts inside Github",
"entry": "blocks/scrimba-block.tsx",
"matches": ["*"],
"example_path": "https://github.com/imba/imba/README.md"
},
{
"type": "folder",
"id": "scrim-folder-block",
"title": "Scrimba Folder Block",
"description": "Record interactive code-casts inside Github",
"entry": "blocks/scrimba-block.tsx",
"matches": ["*"],
"example_path": "https://github.com/imba/imba"
}
]
3 changes: 3 additions & 0 deletions blocks/example-file-block/index.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
pre {
background: papayawhip;
}
43 changes: 43 additions & 0 deletions blocks/example-file-block/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { FileBlockProps, getLanguageFromFilename } from "@githubnext/blocks";
import { Button, Box } from "@primer/react";
import "./index.css";

export default function ExampleFileBlock(props: FileBlockProps) {
const { context, content, metadata, onUpdateMetadata } = props;
const language = Boolean(context.path)
? getLanguageFromFilename(context.path)
: "N/A";

return (
<Box p={4}>
<Box
borderColor="border.default"
borderWidth={1}
borderStyle="solid"
borderRadius={6}
overflow="hidden"
>
<Box
bg="canvas.subtle"
p={3}
borderBottomWidth={1}
borderBottomStyle="solid"
borderColor="border.default"
>
File: {context.path} {language}
</Box>
<Box p={4}>
<p>Metadata example: this button has been clicked:</p>
<Button
onClick={() =>
onUpdateMetadata({ number: (metadata.number || 0) + 1 })
}
>
{metadata.number || 0} times
</Button>
<pre className="mt-3 p-3">{content}</pre>
</Box>
</Box>
</Box>
);
}
162 changes: 162 additions & 0 deletions blocks/scrimba-block.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,162 @@
import { tw } from "twind";
import { FolderBlockProps } from "@githubnext/blocks";
import { useCallback, useEffect, useRef, useState } from "react";
import "./style.css";
import { Button, Text, Link } from "@primer/react";

const SCRIMBA_BASE_URL = import.meta.env.DEV
? "https://dev.scrimba.com:3000"
: "https://scrimba.com";
const SCRIMBA_URL = `${SCRIMBA_BASE_URL}/new/htmlblocks`;

export default function (props: FolderBlockProps) {
const { tree, context, onRequestGitHubData, files } = props;
const [scrimMounted, setScrimMounted] = useState(false);
const [scrimRecorded, setScrimRecorded] = useState("");

const frame = useRef(null);

const getFilesRecursive = useCallback(
async (folderPath: string) => {
const apiUrl = `/repos/${context.owner}/${context.repo}/contents/${folderPath}`;
const folderContents = await onRequestGitHubData(apiUrl, {
ref: context.sha,
});

const filePromises = folderContents.map(async (item) => {
if (item.type === "file") {
const fileResponse = await fetch(item.download_url);
return { path: item.path, content: await fileResponse.text() };
} else if (item.type === "dir") {
const subFolderFiles = await getFilesRecursive(item.path);
return subFolderFiles;
}
});

let files = await Promise.all(filePromises)
.then((files) => files.flat())
.catch((error) => {
console.error(
`Failed to get contents of files in ${folderPath}`,
error
);
return [];
});

return files;
},
[context.repo, context.owner, context.sha]
);

const getFiles = useCallback(
async (all?: boolean) => {
if (!tree && !all) {
return [{ ...context, type: "blob", content: props.content }];
}
return getFilesRecursive(context.path);
},
[context.repo, context.owner, context.sha, files, tree, props.content]
);

const sendData = useCallback(
(files, other?: boolean) => {
if (frame.current) {
let payload = {
files,
title: `Walkthrough of ${context.path.split("/").slice(-1)[0]} in ${
context.owner
}/${context.repo}`,
};
if (other) payload = files;
frame.current.contentWindow.postMessage(payload, "*");
}
},
[frame, context.owner, context.repo, context.path]
);

const listenToRecorded = useCallback(() => {
window.addEventListener("message", (e) => {
if (e.origin !== SCRIMBA_BASE_URL) return;
if (e.data.event == "recorded") {
setScrimRecorded(e.data.id);
}
});
}, []);

const reload = useCallback(async () => {
let files;
if (!tree) {
const parts = context.path.split("/");
const path = parts[parts.length - 1];
files = [{ path, content: props.content, type: "blob" }];
} else {
files = await getFiles();
}
sendData(files);
setScrimMounted(true);
listenToRecorded();
}, [props.content, context.path]);

const init = useCallback(async () => {
let files = await getFiles();
window.addEventListener("message", (e) => {
if (e.origin !== SCRIMBA_BASE_URL) return;

if (e.data.mounted) {
setScrimMounted(true);
if (!tree) {
const parts = context.path.split("/");
const path = parts[parts.length - 1];
files = [{ path, content: props.content, type: "blob" }];
}
sendData(files);
}
});
}, [getFiles, props.content, context.path, frame]);

const loadFiles = useCallback(async () => {
if (!frame.current) return;
const files = await getFiles(true);
sendData(files);
}, [getFiles, frame, context.folder]);

useEffect(() => {
if (frame.current) {
init();
listenToRecorded();
}
}, [frame]);
const publish = useCallback(() => {
sendData({ action: "publish" }, true);
}, [sendData]);

return (
<div className={tw(`w-full h-full`)} id="example-block-code-block">
<div className={tw(`flex w-full h-full overflow-x-hidden flex-col`)}>
<div className={tw(`flex ai-center jc-between flex-row`)}>
{scrimMounted ? null : (
<Button onClick={reload}>Not working? Reload</Button>
)}
<Button onClick={loadFiles}>Load all files</Button>
</div>
{scrimRecorded ? (
<Text>
<Button onClick={publish} className={tw("inline-block")}>
Publish the scrim{" "}
</Button>
to make it available for everyone at{" "}
<Link
href={`${SCRIMBA_BASE_URL}/scrim/${scrimRecorded}`}
>{`${SCRIMBA_BASE_URL}/scrim/${scrimRecorded}`}</Link>
</Text>
) : null}
<iframe
allow="microphone;"
ref={frame}
src={SCRIMBA_URL}
className={tw`my-2 h-full w-full`}
/>
</div>
</div>
);
}
Empty file added blocks/style.css
Empty file.
16 changes: 16 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
{
"name": "custom-block-template",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"start": "blocks start",
"start-https": "blocks start --https=true",
"build": "blocks build"
},
"dependencies": {
"@githubnext/blocks": "^2.3.5",
"@primer/react": "^35.24.0",
"react": "^18.1.0",
"react-dom": "^18.1.0"
}
}
16 changes: 16 additions & 0 deletions release.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
#!/usr/bin/env node

const path = require("path");
const fs = require("fs");
const { exec } = require("child_process");

// Loop over each directory inside of the dist directory and generate a tar ball for each of them
const distDir = path.resolve(__dirname, "./dist");
const distBlocks = fs.readdirSync(distDir);

distBlocks.forEach((distBlock) => {
const tarBall = `${distBlock}.tar.gz`;
const tarBallPath = path.resolve(__dirname, "./dist", tarBall);
const tarBallCmd = `tar -czf ${tarBallPath} -C ${distDir} ${distBlock}`;
exec(tarBallCmd);
});
4 changes: 4 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
{
"extends": "./node_modules/@githubnext/blocks/tsconfig.json",
"include": ["./blocks"]
}
Loading

0 comments on commit a55af5d

Please sign in to comment.