file_path stringlengths 3 280 | file_language stringclasses 66 values | content stringlengths 1 1.04M | repo_name stringlengths 5 92 | repo_stars int64 0 154k | repo_description stringlengths 0 402 | repo_primary_language stringclasses 108 values | developer_username stringlengths 1 25 | developer_name stringlengths 0 30 | developer_company stringlengths 0 82 |
|---|---|---|---|---|---|---|---|---|---|
src/03-even-or-odd/test.ts | TypeScript | import evenOrOdd from '.'
describe('03-even-or-odd', () => {
it('should return even or odd', () => {
expect(evenOrOdd(2)).toBe('Even')
expect(evenOrOdd(0)).toBe('Even')
expect(evenOrOdd(3)).toBe('Odd')
expect(evenOrOdd(5)).toBe('Odd')
})
})
| willianjusten/kata-playground-ts | 22 | A simple playground to create and test your Katas in Typescript. | JavaScript | willianjusten | Willian Justen | |
src/04-summation/index.ts | TypeScript | export default function summation(num: number) {
return (num * (num + 1)) / 2
}
| willianjusten/kata-playground-ts | 22 | A simple playground to create and test your Katas in Typescript. | JavaScript | willianjusten | Willian Justen | |
src/04-summation/test.ts | TypeScript | import summation from '.'
describe('04-summation', () => {
it('should sum the numbers', () => {
expect(summation(2)).toBe(3)
expect(summation(8)).toBe(36)
})
})
| willianjusten/kata-playground-ts | 22 | A simple playground to create and test your Katas in Typescript. | JavaScript | willianjusten | Willian Justen | |
api/_lib/chromium.ts | TypeScript | import core from 'puppeteer-core';
import { getOptions } from './options';
import { FileType } from './types';
let _page: core.Page | null;
async function getPage(isDev: boolean) {
if (_page) {
return _page;
}
const options = await getOptions(isDev);
const browser = await core.launch(options);
_page = await browser.newPage();
return _page;
}
export async function getScreenshot(html: string, type: FileType, isDev: boolean) {
const page = await getPage(isDev);
await page.setViewport({ width: 2048, height: 1170 });
await page.setContent(html);
const file = await page.screenshot({ type });
return file;
}
| willianjusten/og-image-blog | 1 | TypeScript | willianjusten | Willian Justen | ||
api/_lib/options.ts | TypeScript | import chrome from 'chrome-aws-lambda';
const exePath = process.platform === 'win32'
? 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'
: process.platform === 'linux'
? '/usr/bin/google-chrome'
: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome';
interface Options {
args: string[];
executablePath: string;
headless: boolean;
}
export async function getOptions(isDev: boolean) {
let options: Options;
if (isDev) {
options = {
args: [],
executablePath: exePath,
headless: true
};
} else {
options = {
args: chrome.args,
executablePath: await chrome.executablePath,
headless: chrome.headless,
};
}
return options;
}
| willianjusten/og-image-blog | 1 | TypeScript | willianjusten | Willian Justen | ||
api/_lib/parser.ts | TypeScript | import { IncomingMessage } from "http";
import { parse } from "url";
import { ParsedRequest } from "./types";
export function parseRequest(req: IncomingMessage) {
console.log("HTTP " + req.url);
const { pathname } = parse(req.url || "/", true);
const arr = (pathname || "/").slice(1).split(".");
let extension = "";
let text = "";
if (arr.length === 0) {
text = "";
} else if (arr.length === 1) {
text = arr[0];
} else {
extension = arr.pop() as string;
text = arr.join(".");
}
const parsedRequest: ParsedRequest = {
fileType: extension === "jpeg" ? extension : "png",
text: decodeURIComponent(text),
};
return parsedRequest;
}
| willianjusten/og-image-blog | 1 | TypeScript | willianjusten | Willian Justen | ||
api/_lib/sanitizer.ts | TypeScript | const entityMap: { [key: string]: string } = {
"&": "&",
"<": "<",
">": ">",
'"': """,
"'": "'",
"/": "/",
".png": "",
};
export function sanitizeHtml(html: string) {
return String(html).replace(/[&<>"'\/]/g, (key) => entityMap[key]);
}
| willianjusten/og-image-blog | 1 | TypeScript | willianjusten | Willian Justen | ||
api/_lib/template.ts | TypeScript | import { sanitizeHtml } from "./sanitizer";
import { ParsedRequest } from "./types";
import slugify from "slugify";
function getCss() {
return `
* {
margin: 0;
padding: 0;
border-box: box-sizing;
}
body {
background: rgb(3, 5, 24);
height: 100vh;
display: flex;
}
.heading {
font-family: 'Source Sans Pro', sans-serif;
color: rgba(243,244,246);
font-size: 7vw;
font-weight: 700;
line-height: 1;
}
.container {
display: flex;
flex-direction: column;
justify-content: space-between;
padding: 10rem 6rem;
}
.avatar {
width: 200px;
height: 200px;
border-radius: 50%;
border: 5px solid rgba(243,244,246);
margin-right: 50px;
}
.name {
font-family: 'Open Sans', sans-serif;
color: rgba(243,244,246);
font-size: 1.8vw;
font-weight: 600;
}
.link {
font-family: 'Open Sans', sans-serif;
color: rgb(136, 153, 166);
font-size: 1.8vw;
font-weight: 600;
margin: 0.8rem 0;
}
.twitter {
font-family: 'Open Sans', sans-serif;
color: #f231a5;
font-size: 1.8vw;
font-weight: 600;
}
.box-info {
display: flex;
align-items: center;
}
`;
}
export function getHtml(parsedReq: ParsedRequest) {
const { text } = parsedReq;
return `<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Generated Image</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Source+Sans+Pro:wght@700&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@600&display=swap" rel="stylesheet">
<style>
${getCss()}
</style>
<body>
<div class="container">
<h1 class="heading">${sanitizeHtml(text)}</h1>
<div class="box-info">
<img
src="https://github.com/willianjusten.png"
alt="Willian Justen"
class="avatar"
/>
<div class="info">
<p class="name">Willian Justen</p>
<p class="link">willianjusten.com.br/${slugify(text, {
lower: true,
})}</p>
<p class="twitter">
twitter.com/Willian_justen
</p>
</div>
</div>
</div>
</body>
</html>`;
}
| willianjusten/og-image-blog | 1 | TypeScript | willianjusten | Willian Justen | ||
api/_lib/types.ts | TypeScript | export type FileType = "png" | "jpeg";
export type Theme = "light" | "dark";
export interface ParsedRequest {
fileType: FileType;
text: string;
}
| willianjusten/og-image-blog | 1 | TypeScript | willianjusten | Willian Justen | ||
api/index.ts | TypeScript | import { IncomingMessage, ServerResponse } from 'http';
import { parseRequest } from './_lib/parser';
import { getScreenshot } from './_lib/chromium';
import { getHtml } from './_lib/template';
const isDev = !process.env.AWS_REGION;
const isHtmlDebug = process.env.OG_HTML_DEBUG === '1';
export default async function handler(req: IncomingMessage, res: ServerResponse) {
try {
const parsedReq = parseRequest(req);
const html = getHtml(parsedReq);
if (isHtmlDebug) {
res.setHeader('Content-Type', 'text/html');
res.end(html);
return;
}
const { fileType } = parsedReq;
const file = await getScreenshot(html, fileType, isDev);
res.statusCode = 200;
res.setHeader('Content-Type', `image/${fileType}`);
res.setHeader('Cache-Control', `public, immutable, no-transform, s-maxage=31536000, max-age=31536000`);
res.end(file);
} catch (e) {
res.statusCode = 500;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>Internal Error</h1><p>Sorry, there was a problem</p>');
console.error(e);
}
}
| willianjusten/og-image-blog | 1 | TypeScript | willianjusten | Willian Justen | ||
public/index.html | HTML | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<meta name="twitter:card" content="summary_large_image"/>
<meta name="twitter:site" content="@vercel"/>
<meta property="og:site_name" content="Open Graph Image as a Service"/>
<meta property="og:type" content="website"/>
<meta property="og:title" content="Open Graph Image as a Service"/>
<meta property="og:locale" content="en"/>
<meta property="og:url" content="https://og-image.vercel.app"/>
<link rel="canonical" href="https://og-image.vercel.app"/>
<meta name="description" content="A service to generate dynamic Open Graph images on-the-fly for the purpose of sharing a website to social media. Proudly hosted on Vercel."/>
<meta property="og:description" content="A service to generate dynamic Open Graph images on-the-fly for the purpose of sharing a website to social media. Proudly hosted on Vercel."/>
<meta property="og:image" content="https://og-image.vercel.app/Open%20Graph%20Image%20as%20a%20Service.png?theme=light&md=1&fontSize=95px&images=https%3A%2F%2Fassets.vercel.com%2Fimage%2Fupload%2Ffront%2Fassets%2Fdesign%2Fzeit-black-triangle.svg"/>
<title>Open Graph Image as a Service</title>
<meta name="viewport" content="width=device-width, maximum-scale=1.0" />
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div class="wrapper">
<a href="https://github.com/vercel/og-image" class="github-corner" aria-label="View source on GitHub">
<svg width="80" height="80" viewBox="0 0 250 250" class="svg">
<path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path>
<path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path>
<path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body">
</path>
</svg>
</a>
<h1>Open Graph Image as a Service</h1>
<div id="app">
<em>Loading...</em>
</div>
<div class="center">
<h2>What is this?</h2>
<p>This is a service that generates dynamic <a href="http://ogp.me">Open Graph</a> images that you can embed in your <code><meta></code> tags.</p>
<p>For each keystroke, headless chromium is used to render an HTML page and take a screenshot of the result which gets cached.</p>
<p>Find out how this works and deploy your own image generator by visiting <a href="https://github.com/vercel/og-image">GitHub</a>.</p>
<footer>Proudly hosted on <a href="https://vercel.com">▲Vercel</a></footer>
</div>
</div>
</div>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/dot-dom@0.3.0/dotdom.min.js"></script>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/copee@1.0.6/dist/copee.umd.js"></script>
<script type="module" src="dist/web/index.js"></script>
</body>
</html>
| willianjusten/og-image-blog | 1 | TypeScript | willianjusten | Willian Justen | ||
public/style.css | CSS | body {
font-family: "SF Pro Text", "SF Pro Icons", "Helvetica Neue", "Helvetica",
"Arial", sans-serif;
margin: 20px;
overflow-x: hidden;
padding: 0;
box-sizing: border-box;
}
a {
cursor: pointer;
color: #0076FF;
text-decoration: none;
transition: all 0.2s ease;
border-bottom: 1px solid white;
}
a:hover {
border-bottom: 1px solid #0076FF;
}
footer {
opacity: 0.5;
font-size: 0.8em;
}
.center, h1 {
text-align: center;
}
.container {
display: flex;
justify-content: center;
width: 100%;
}
.split {
display: flex;
justify-content: center;
width: 100%;
}
.pull-left {
min-width: 50%;
display: flex;
justify-content: flex-end;
}
.pull-right {
min-width: 50%;
}
button {
appearance: none;
align-items: center;
color: #fff;
background: #000;
display: inline-flex;
width: 100px;
height: 40px;
padding: 0 25px;
outline: none;
border: 1px solid #000;
font-size: 12px;
justify-content: center;
text-transform: uppercase;
cursor: pointer;
text-align: center;
user-select: none;
font-weight: 100;
position: relative;
overflow: hidden;
transition: border 0.2s,background 0.2s,color 0.2s ease-out;
border-radius: 5px;
white-space: nowrap;
text-decoration: none;
line-height: 0;
height: 24px;
width: calc(100% + 2px);
padding: 0 10px;
font-size: 12px;
background: #fff;
border: 1px solid #eaeaea;
color: #666;
}
button:hover {
color: #000;
border-color: #000;
background: #fff;
}
.input-outer-wrapper {
align-items: center;
border-radius: 5px;
border: 1px solid #e1e1e1;
display: inline-flex;
height: 37px;
position: relative;
transition: border 0.2s ease,color 0.2s ease;
vertical-align: middle;
width: 100%;
}
.input-outer-wrapper:hover {
box-shadow: 0 2px 6px rgba(0,0,0,0.1);
border-color: #ddd;
}
.input-inner-wrapper {
display: block;
margin: 4px 10px;
position: relative;
width: 100%;
}
.input-inner-wrapper input {
background-color: transparent;
border-radius: 0;
border: none;
box-shadow: none;
box-sizing: border-box;
display: block;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "Roboto", "Oxygen", "Ubuntu", "Cantarell", "Fira Sans", "Droid Sans", "Helvetica Neue", sans-serif;
font-size: 14px;
line-height: 27px;
outline: 0;
width: 100%;
}
.select-wrapper {
appearance: none;
color: #000;
background: #fff;
display: inline-flex;
height: 40px;
outline: none;
border: 1px solid #eaeaea;
font-size: 12px;
text-transform: uppercase;
user-select: none;
font-weight: 100;
position: relative;
overflow: hidden;
transition: border 0.2s,background 0.2s,color 0.2s ease-out, box-shadow 0.2s ease;
border-radius: 5px;
white-space: nowrap;
line-height: 0;
width: auto;
min-width: 100%;
}
.select-wrapper:hover {
box-shadow: 0 2px 6px rgba(0,0,0,0.1);
border-color: #ddd;
}
.select-wrapper.small {
height: 24px;
min-width: 100px;
width: 100px;
}
.select-arrow {
border-left: 1px solid #eaeaea;
background: #fff;
width: 40px;
height: 100%;
position: absolute;
right: 0;
pointer-events: none;
display: flex;
align-items: center;
justify-content: center;
}
.select-arrow.small {
width: 22px;
}
.svg {
fill: #151513;
color: #fff;
position: absolute;
top: 0;
border: 0;
right: 0;
}
select {
height: 100%;
border: none;
box-shadow: none;
background: transparent;
background-image: none;
color: #000;
line-height: 40px;
font-size: 14px;
margin-right: -20px;
width: calc(100% + 20px);
padding: 0 0 0 16px;
text-transform: none;
}
.field-flex {
display: flex;
margin-top: 10px;
}
.field-value {
margin: 10px 80px;
}
.field-label {
display: inline-block;
width: 100px;
margin-right: 20px;
text-align: right;
}
.field-value {
width: 200px;
display: inline-block;
}
label {
display: flex;
align-items: center;
}
.toast-area {
position: fixed;
bottom: 10px;
right: 20px;
max-width: 420px;
z-index: 2000;
transition: transform 0.4s ease;
}
.toast-outer {
width: 420px;
height: 72px;
position: absolute;
bottom: 0;
right: 0;
transition: all 0.4s ease;
transform: translate3d(0,130%,0px) scale(1);
animation: show-jsx-1861505484 0.4s ease forwards;
opacity: 1;
}
.toast-inner {
width: 420px;
background: black;
color: white;
border: 0;
border-radius: 5px;
height: 60px;
align-items: center;
justify-content: space-between;
box-shadow: 0 4px 9px rgba(0,0,0,0.12);
font-size: 14px;
display: flex;
}
.toast-message {
text-overflow: ellipsis;
white-space: nowrap;
width: 100%;
overflow: hidden;
margin-top: -1px;
margin-left: 20px;
}
img {
max-width: 100%;
transition: all 0.3s ease-in 0s;
}
.image-wrapper {
display: block;
cursor: pointer;
text-decoration: none;
background: #fff;
box-shadow: 0px 1px 5px 0px rgba(0,0,0,0.12);
border-radius: 5px;
margin-bottom: 50px;
transition: all 0.2s ease;
max-width: 100%;
}
.image-wrapper:hover {
box-shadow: 0 1px 16px rgba(0,0,0,0.1);
border-color: #ddd;
}
@media (max-width: 1000px) {
.field {
margin: 20px 10px;
}
.pull-left {
margin-left: 1.5em;
}
}
@media (max-width: 900px) {
.split {
flex-wrap: wrap;
}
.field-label {
width: 60px;
font-size: 13px;
}
}
.github-corner:hover .octo-arm {
animation: octocat-wave 560ms ease-in-out;
}
@keyframes octocat-wave {
0%,100% { transform:rotate(0) }
20%,60% { transform:rotate(-25deg) }
40%,80% { transform:rotate(10deg) }
}
@media (max-width: 500px) {
.github-corner:hover .octo-arm {
animation: none;
}
.github-corner .octo-arm {
animation: octocat-wave 560ms ease-in-out;
}
.container {
margin: 19%;
}
.svg {
right: -33%;
}
}
@media (max-width: 360px) {
.container {
margin: 29.5%;
}
.svg {
right: -52%;
}
}
| willianjusten/og-image-blog | 1 | TypeScript | willianjusten | Willian Justen | ||
web/index.ts | TypeScript | import { ParsedRequest } from "../api/_lib/types";
const { H, R, copee } = window as any;
let timeout = -1;
interface ImagePreviewProps {
src: string;
onclick: () => void;
onload: () => void;
onerror: () => void;
loading: boolean;
}
const ImagePreview = ({
src,
onclick,
onload,
onerror,
loading,
}: ImagePreviewProps) => {
const style = {
filter: loading ? "blur(5px)" : "",
opacity: loading ? 0.1 : 1,
};
const title = "Click to copy image URL to clipboard";
return H(
"a",
{ className: "image-wrapper", href: src, onclick },
H("img", { src, onload, onerror, style, title })
);
};
interface TextInputProps {
value: string;
oninput: (val: string) => void;
}
const TextInput = ({ value, oninput }: TextInputProps) => {
return H(
"div",
{ className: "input-outer-wrapper" },
H(
"div",
{ className: "input-inner-wrapper" },
H("input", {
type: "text",
value,
oninput: (e: any) => oninput(e.target.value),
})
)
);
};
interface FieldProps {
label: string;
input: any;
}
const Field = ({ label, input }: FieldProps) => {
return H(
"div",
{ className: "field" },
H(
"label",
H("div", { className: "field-label" }, label),
H("div", { className: "field-value" }, input)
)
);
};
interface ToastProps {
show: boolean;
message: string;
}
const Toast = ({ show, message }: ToastProps) => {
const style = { transform: show ? "translate3d(0,-0px,-0px) scale(1)" : "" };
return H(
"div",
{ className: "toast-area" },
H(
"div",
{ className: "toast-outer", style },
H(
"div",
{ className: "toast-inner" },
H("div", { className: "toast-message" }, message)
)
)
);
};
interface AppState extends ParsedRequest {
loading: boolean;
showToast: boolean;
messageToast: string;
selectedImageIndex: number;
widths: string[];
heights: string[];
overrideUrl: URL | null;
}
type SetState = (state: Partial<AppState>) => void;
const App = (_: any, state: AppState, setState: SetState) => {
const setLoadingState = (newState: Partial<AppState>) => {
window.clearTimeout(timeout);
if (state.overrideUrl && state.overrideUrl !== newState.overrideUrl) {
newState.overrideUrl = state.overrideUrl;
}
if (newState.overrideUrl) {
timeout = window.setTimeout(() => setState({ overrideUrl: null }), 200);
}
setState({ ...newState, loading: true });
};
const {
fileType = "png",
text = "Migrei meu blog do Gatsby para o NextJS",
showToast = false,
messageToast = "",
loading = true,
overrideUrl = null,
} = state;
const url = new URL(window.location.origin);
url.pathname = `${encodeURIComponent(text)}.${fileType}`;
return H(
"div",
{ className: "split" },
H(
"div",
{ className: "pull-left" },
H(
"div",
H(Field, {
label: "Text Input",
input: H(TextInput, {
value: text,
oninput: (val: string) => {
console.log("oninput " + val);
setLoadingState({ text: val, overrideUrl: url });
},
}),
})
)
),
H(
"div",
{ className: "pull-right" },
H(ImagePreview, {
src: overrideUrl ? overrideUrl.href : url.href,
loading: loading,
onload: () => setState({ loading: false }),
onerror: () => {
setState({
showToast: true,
messageToast: "Oops, an error occurred",
});
setTimeout(() => setState({ showToast: false }), 2000);
},
onclick: (e: Event) => {
e.preventDefault();
const success = copee.toClipboard(url.href);
if (success) {
setState({
showToast: true,
messageToast: "Copied image URL to clipboard",
});
setTimeout(() => setState({ showToast: false }), 3000);
} else {
window.open(url.href, "_blank");
}
return false;
},
})
),
H(Toast, {
message: messageToast,
show: showToast,
})
);
};
R(H(App), document.getElementById("app"));
| willianjusten/og-image-blog | 1 | TypeScript | willianjusten | Willian Justen | ||
configs/babel.js | JavaScript | const {
MIN_IE_VERSION,
MIN_NODE_VERSION,
IGNORE_PATHS
} = require("../constants");
const { context, tool } = process.beemo;
const { args } = context;
const env = process.env.NODE_ENV;
const plugins = [
"@babel/plugin-proposal-export-default-from",
"@babel/plugin-proposal-class-properties",
"@babel/plugin-syntax-dynamic-import",
["babel-plugin-transform-dev", { evaluate: false }]
];
const presetEnvOptions = {
loose: true,
modules: args.esm ? false : "commonjs",
shippedProposals: true,
targets: args.node ? { node: MIN_NODE_VERSION } : { ie: MIN_IE_VERSION },
useBuiltIns: false
};
if (env === "test") {
presetEnvOptions.modules = "commonjs";
presetEnvOptions.targets = { node: "current" };
plugins.push([
"@babel/plugin-transform-runtime",
{
helpers: true,
regenerator: true,
useESModules: !!context.args.esm
}
]);
}
const presets = [
["@babel/preset-env", presetEnvOptions],
"@babel/preset-react"
];
if (args.minify) {
presets.push([
"minify",
{
removeUndefined: false,
evaluate: false,
builtIns: false,
}
]);
}
if (tool.config.drivers.includes("typescript")) {
presets.push("@babel/preset-typescript");
plugins.push("babel-plugin-typescript-to-proptypes");
}
module.exports = {
ignore: [...IGNORE_PATHS, "__tests__", "__mocks__"],
plugins,
presets
};
| williaster/build-config | 1 | Version-controlled build config for easy re-use and sharing 📝 | JavaScript | williaster | Chris Williams | airbnb |
configs/eslint.js | JavaScript | /* eslint sort-keys: off */
const path = require("path");
const { EXTS, EXT_PATTERN, IGNORE_PATHS } = require("../constants");
const { tool } = process.beemo;
const extendsConfig = ["airbnb", "prettier"];
if (tool.config.drivers.includes("typescript")) {
extendsConfig.push(path.join(__dirname, "./eslint/typescript.js"));
}
// This file could be broken into multiple files per-driver
module.exports = {
root: true,
parser: "babel-eslint",
extends: extendsConfig,
plugins: ["promise", "compat", "babel", "prettier"],
ignore: [
...IGNORE_PATHS,
"babel.config.js",
"jest.config.js",
"prettier.config.js",
"tsconfig.json",
"*.min.js",
"*.map"
],
env: {
browser: true
},
globals: {
__DEV__: true
},
settings: {
polyfills: ["promises"],
"import/extensions": EXTS,
"import/resolver": {
node: {
extensions: EXTS
}
}
},
parserOptions: {
sourceType: "module",
ecmaVersion: 2018,
ecmaFeatures: {
jsx: true
}
},
rules: {
"class-methods-use-this": "off",
"multiline-comment-style": "off",
"no-else-return": ["error", { allowElseIf: true }],
"no-invalid-this": "off", // Handled by babel/no-invalid-this
"object-curly-spacing": "off", // Handled by babel/object-curly-spacing
"padded-blocks": [
"error",
{
// Never apply to blocks
classes: "never",
switches: "never"
}
],
"babel/new-cap": "error",
"babel/no-invalid-this": "error",
"babel/object-curly-spacing": ["error", "always"],
"babel/semi": "error",
"compat/compat": "error", // browser compatibility
"lines-between-class-members": [
"error",
"always",
{ exceptAfterSingleLine: true }
],
"prettier/prettier": "error",
"promise/always-return": "error",
"promise/avoid-new": "off",
"promise/catch-or-return": "error",
"promise/no-callback-in-promise": "error",
"promise/no-native": "off",
"promise/no-nesting": "off",
"promise/no-new-statics": "error",
"promise/no-promise-in-callback": "error",
"promise/no-return-in-finally": "error",
"promise/no-return-wrap": ["error", { allowReject: true }],
"promise/param-names": "error",
"promise/valid-params": "error",
"react/sort-prop-types": "off", // Handled by sort-keys
"react/jsx-sort-default-props": "off", // Handled by sort-keys
// New and not in Airbnb
"react/no-unsafe": "error",
// Want to support but disabled in Airbnb
complexity: ["error", 11], // eslint-disable-line no-magic-numbers
"newline-before-return": "error",
"no-constant-condition": "error",
"no-div-regex": "error",
"no-eq-null": "error",
"no-implicit-coercion": "error",
"no-magic-numbers": [
"error",
{
ignore: [-1, 0, 1, 2, 3],
ignoreArrayIndexes: true,
enforceConst: true
}
],
"no-native-reassign": "error",
"no-negated-condition": "error",
"no-useless-call": "error",
"sort-keys": [
"error",
"asc",
{
caseSensitive: false,
natural: true
}
],
"import/default": "error",
"import/no-anonymous-default-export": [
"error",
{
allowArray: true,
allowLiteral: true,
allowObject: true
}
],
"react/forbid-foreign-prop-types": "error",
"react/jsx-handler-names": [
"error",
{
eventHandlerPrefix: "handle",
eventHandlerPropPrefix: "on"
}
],
"react/jsx-key": "error",
"react/jsx-no-literals": "off",
"react/no-did-mount-set-state": "error",
"react/no-direct-mutation-state": "error",
// Doesnt work with Prettier
"function-paren-newline": "off",
"react/jsx-one-expression-per-line": "off"
},
overrides: [
{
plugins: ["jest"],
env: {
jest: true,
node: true
},
files: [
`{spec,test,tests}/**/*.${EXT_PATTERN}`,
`packages/*/{spec,test,tests}/**/*.${EXT_PATTERN}`
],
rules: {
"no-magic-numbers": "off",
"sort-keys": "off",
"import/no-extraneous-dependencies": "off",
"jest/consistent-test-it": "error",
"jest/lowercase-name": "off",
"jest/no-disabled-tests": "error",
"jest/no-identical-title": "error",
"jest/no-jasmine-globals": "error",
"jest/no-jest-import": "error",
"jest/no-test-prefixes": "error",
"jest/no-large-snapshots": "error",
"jest/prefer-to-be-null": "error",
"jest/prefer-to-be-undefined": "error",
"jest/prefer-to-have-length": "error",
"jest/valid-describe": "error",
"jest/valid-expect": "error",
"react/jsx-filename-extension": "off"
}
}
]
};
| williaster/build-config | 1 | Version-controlled build config for easy re-use and sharing 📝 | JavaScript | williaster | Chris Williams | airbnb |
configs/eslint/typescript.js | JavaScript | const extensions = [".ts", ".tsx", ".js", ".jsx", ".json"];
module.exports = {
settings: {
"import/extensions": extensions,
"import/resolver": {
node: {
extensions
}
},
"import/parsers": {
"typescript-eslint-parser": [".ts", ".tsx"]
}
},
overrides: [
{
parser: "typescript-eslint-parser",
plugins: ["typescript"],
files: ["*.{ts,tsx}"],
rules: {
"no-restricted-globals": "off",
"no-undef": "off",
"no-unused-vars": "warn", // Temp (false positives: https://github.com/nzakas/eslint-plugin-typescript/issues/90)
// IMPORT
"import/extensions": [
"error",
"never",
{
json: "always"
}
],
"import/named": "off",
"import/no-cycle": "off",
"import/no-named-as-default": "off",
// REACT
"react/destructuring-assignment": "off",
"react/jsx-filename-extension": [
"error",
{ extensions: [".tsx", ".jsx"] }
],
"react/no-unused-prop-types": "off",
"react/prefer-stateless-function": "off",
"react/prop-types": "off",
// TYPESCRIPT
"typescript/adjacent-overload-signatures": "error",
"typescript/class-name-casing": "error",
"typescript/member-delimiter-style": "error",
"typescript/member-ordering": "off", // Prefer react/sort-comp
"typescript/no-angle-bracket-type-assertion": "error",
"typescript/no-empty-interface": "error",
"typescript/no-array-constructor": "error",
"typescript/no-triple-slash-reference": "error",
"typescript/no-parameter-properties": "error",
"typescript/no-unused-vars": "warn",
"typescript/no-use-before-define": "error",
"typescript/prefer-namespace-keyword": "error",
"typescript/type-annotation-spacing": "error"
}
}
]
};
| williaster/build-config | 1 | Version-controlled build config for easy re-use and sharing 📝 | JavaScript | williaster | Chris Williams | airbnb |
configs/jest.js | JavaScript | const fs = require("fs");
const path = require("path");
const { EXTS, EXT_PATTERN, IGNORE_PATHS } = require("../constants");
const { context, tool } = process.beemo;
const { react, testDir = "test" } = tool.config.settings;
const { args } = context;
const setupFiles = [];
const setupFilePath = path.join(
process.cwd(),
args.setup || `./${testDir}/setup.js`
);
if (fs.existsSync(setupFilePath)) {
setupFiles.push(setupFilePath);
}
if (args.react || react) {
setupFiles.push(path.join(__dirname, "./jest/enzyme.js"));
}
const roots = [];
if (tool.package.workspaces) {
tool.package.workspaces.forEach(wsPath => {
// eslint-disable-next-line no-magic-numbers
const wsRelPath = wsPath.endsWith("/*") ? wsPath.slice(0, -2) : wsPath;
// eg <rootDir>/packages
roots.push(path.join("<rootDir>", wsRelPath));
});
} else {
roots.push("<rootDir>");
}
module.exports = {
coverageDirectory: "./coverage",
coveragePathIgnorePatterns: [...IGNORE_PATHS],
coverageReporters: ["lcov"],
globals: {
__DEV__: true
},
moduleFileExtensions: EXTS.map(ext => ext.slice(1)), // no period
roots,
setupFiles,
snapshotSerializers: ["enzyme-to-json/serializer"],
testMatch: [`**/?(*.)+(spec|test).${EXT_PATTERN}`],
testURL: "http://localhost/",
transform: {
"^.+\\.(t|j)sx?$": "babel-jest"
},
verbose: true
};
| williaster/build-config | 1 | Version-controlled build config for easy re-use and sharing 📝 | JavaScript | williaster | Chris Williams | airbnb |
configs/jest/enzyme.js | JavaScript | const Enzyme = require("enzyme");
const Adapter = require("enzyme-adapter-react-16");
Enzyme.configure({
adapter: new Adapter()
});
| williaster/build-config | 1 | Version-controlled build config for easy re-use and sharing 📝 | JavaScript | williaster | Chris Williams | airbnb |
configs/prettier.js | JavaScript | const { IGNORE_PATHS } = require("../constants");
module.exports = {
arrowParens: "avoid",
bracketSpacing: true,
ignore: [...IGNORE_PATHS, "lerna.json", "package.json", "package-lock.json"],
jsxBracketSameLine: false,
printWidth: 100,
proseWrap: "always",
semi: true,
singleQuote: true,
tabWidth: 2,
trailingComma: "all",
useTabs: false
};
| williaster/build-config | 1 | Version-controlled build config for easy re-use and sharing 📝 | JavaScript | williaster | Chris Williams | airbnb |
configs/typescript.js | JavaScript | // Package: Run in root
// Workspaces: Run in each package (copied into each)
const path = require("path");
const { context, tool } = process.beemo;
const toolConfig = tool.config.settings || {};
const testDir = toolConfig.testDir || context.args.testDir || "test";
let include = ["./src/**/*", "./types/**/*"];
const typeRoots = ["./node_modules/@types"];
// When --noEmit is passed, we want to run the type checker and include test files.
// Otherwise, we do not want to emit declarations for test files.
if (context.args.noEmit) {
include.push(`./${testDir}/**/*`);
}
// When --workspaces is passed, the tsconfig.json is copied into each
// workspace package instead of being referenced from the root. Because
// of this, we need to calculate relative paths from within each workspace
// package, so that we may resolve root node_modules and types correctly.
if (context.args.workspaces) {
context.workspaces.forEach(wsPath => {
const wsRelativeRoot = path.relative(wsPath, context.workspaceRoot);
typeRoots.push(path.join(wsRelativeRoot, "node_modules/@types"));
include.push(path.join(wsRelativeRoot, "types/**/*"));
});
// However, when running through Jest at the root, we need to find all packages.
// Be sure not to break non-workspace enabled projects.
} else if (tool.package.workspaces) {
include = [];
tool.package.workspaces.forEach(wsPath => {
const wsRelPath = wsPath.endsWith("/*") ? wsPath.slice(0, -2) : wsPath;
include.push(path.join(wsRelPath, `./**/*`));
});
}
module.exports = {
compilerOptions: {
allowSyntheticDefaultImports: true,
declaration: true, // generates corresponding '.d.ts' file.
declarationDir: "./lib",
esModuleInterop: true, // Emit __importStar and __importDefault helpers for runtime babel ecosystem compatibility and enable --allowSyntheticDefaultImports for typesystem compatibility
forceConsistentCasingInFileNames: true,
jsx: "react",
lib: ["dom", "esnext"],
module: "commonjs",
moduleResolution: "node",
noEmitOnError: true,
noImplicitReturns: true,
noImplicitThis: true,
noImplicitAny: true,
noUnusedLocals: true,
outDir: "./lib",
pretty: true,
removeComments: false,
strict: true,
target: "esnext",
typeRoots
},
include,
exclude: ["node_modules"]
};
| williaster/build-config | 1 | Version-controlled build config for easy re-use and sharing 📝 | JavaScript | williaster | Chris Williams | airbnb |
constants.js | JavaScript | exports.EXTS = [".js", ".jsx", ".ts", ".tsx", ".json"];
exports.EXT_PATTERN = "{js,jsx,ts,tsx}";
exports.DIR_PATTERN = "{lib,build,bin,src,test,tests}";
exports.MIN_IE_VERSION = 10;
exports.MIN_NODE_VERSION = "6.5";
exports.IGNORE_PATHS = [
"node_modules/",
"public/",
"esm/",
"lib/",
"tmp/",
"dist/"
];
| williaster/build-config | 1 | Version-controlled build config for easy re-use and sharing 📝 | JavaScript | williaster | Chris Williams | airbnb |
next-env.d.ts | TypeScript | /// <reference types="next" />
/// <reference types="next/types/global" />
/// <reference types="next/image-types/global" />
// NOTE: This file should not be edited
// see https://nextjs.org/docs/basic-features/typescript for more information.
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
next.config.js | JavaScript | /** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
swcMinify: true,
typescript: {
// Dangerously allow production builds to successfully complete even if
// your project has type errors.
ignoreBuildErrors: true,
},
basePath: process.env.NODE_ENV === 'production' ? '/r3f-spaceship' : '',
};
module.exports = nextConfig;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/01_3d-concepts.tsx | TypeScript (TSX) | import type { NextPage } from 'next';
import Head from 'next/head';
import styles from '../styles/r3f.module.css';
import React, { useState } from 'react';
import Demo from './demos/01';
const basePath = process.env.NODE_ENV === 'production' ? '/r3f-spaceship' : '';
const ThreeDConcepts: NextPage = () => {
const [showDemo, setShowDemo] = useState(false);
const [showAxes, setShowAxes] = useState(false);
const [showCamera, setShowCamera] = useState(false);
const [showAmbient, setShowAmbient] = useState(false);
const [showPoint, setShowPoint] = useState(false);
const [showMeshNormal, setShowMeshNormal] = useState(false);
const [showBoxes, setShowBoxes] = useState(false);
const [showMaterials, setShowMaterials] = useState(false);
return (
<div className={styles.container}>
<Head>
<title>3D basics</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h3>A 3D Scene 🕶</h3>
Show demo{' '}
<input
type="checkbox"
checked={showDemo}
onChange={() => setShowDemo(!showDemo)}
/>
{!showDemo && (
<div className={styles.flex}>
<img
src={`${basePath}/cartesian.png`}
alt=""
width={150}
height={130}
/>
<img
src={`${basePath}/camera.jpeg`}
alt=""
width={240}
height={220}
/>
<img src={`${basePath}/mesh.png`} alt="" width={210} height={180} />
<img
src={`${basePath}/materials.png`}
alt=""
width={350}
height={110}
/>
<img
src={`${basePath}/lights.jpeg`}
alt=""
width={300}
height={220}
/>
</div>
)}
<ul>
<li>
Cartesian 3D space{' '}
{showDemo && (
<input
type="checkbox"
checked={showAxes}
onChange={() => setShowAxes(!showAxes)}
/>
)}
</li>
<li>
Perspective Camera (position, near/far){' '}
{showDemo && (
<input
type="checkbox"
checked={showCamera}
onChange={() => setShowCamera(!showCamera)}
/>
)}
</li>
<li>
Mesh{' '}
{showDemo && (
<input
type="checkbox"
checked={showBoxes}
onChange={() => setShowBoxes(!showBoxes)}
/>
)}
<ul>
<li>Geometry (points and edges)</li>
<li>
Materials (color, shiny/rough, texture){' '}
{showDemo && (
<input
type="checkbox"
checked={showMaterials}
onChange={() => setShowMaterials(!showMaterials)}
/>
)}
<ul>
<li>
Mesh normal{' '}
{showDemo && (
<input
type="checkbox"
checked={showMeshNormal}
onChange={() => setShowMeshNormal(!showMeshNormal)}
/>
)}
</li>
</ul>
</li>
</ul>
</li>
<li>
Lights
<ul>
<li>
Ambient (global illumination)
{showDemo && (
<input
type="checkbox"
checked={showAmbient}
onChange={() => setShowAmbient(!showAmbient)}
/>
)}
</li>
<li>Directional (single direction, parallel rays)</li>
<li>
Point (single point, all directions){' '}
{showDemo && (
<input
type="checkbox"
checked={showPoint}
onChange={() => setShowPoint(!showPoint)}
/>
)}
</li>
<li>Spotlight (single point, single directional cone)</li>
</ul>
</li>
</ul>
{showDemo && (
<Demo
showAmbient={showAmbient}
showBoxes={showBoxes}
showPoint={showPoint}
showMaterials={showMaterials}
showMeshNormal={showMeshNormal}
showCamera={showCamera}
showAxes={showAxes}
/>
)}
</main>
</div>
);
};
export default ThreeDConcepts;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/02_r3f.tsx | TypeScript (TSX) | import React, { useState } from 'react';
import type { NextPage } from 'next';
import Head from 'next/head';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { githubGist as syntaxStyle } from 'react-syntax-highlighter/dist/cjs/styles/hljs';
import styles from '../styles/r3f.module.css';
import Demo from './demos/02';
import Demo2 from './demos/02-b';
import DemoSource from '!!raw-loader!./demos/02';
import DemoThreeSource from '!!raw-loader!./demos/02-three';
import DemoSource2 from '!!raw-loader!./demos/02-b';
const ThreeDConcepts: NextPage = () => {
const [showDemo, setShowDemo] = useState(false);
const [showDemo2, setShowDemo2] = useState(false);
return (
<div className={styles.container}>
<Head>
<title>@react-three/fiber</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h3>@react-three/fiber</h3>
<ul>
{!showDemo && !showDemo2 && (
<>
<li>
3D browser experiences are made with{' '}
<a
href="https://en.wikipedia.org/wiki/WebGL"
target="_blank"
rel="noreferrer"
>
WebGL
</a>
<ul>
<li>
Web standard allowing GPU-accelerated usage of physics/image
processing as part of canvas
</li>
<li>
JS control code + shader code written in Open GL Shading
language
</li>
<li>Very low level</li>
</ul>
</li>
<li>
<a target="_blank" href="https://threejs.org/" rel="noreferrer">
Three.js
</a>{' '}
is a high-level API for WebGL
</li>
</>
)}
<li>
<a
target="_blank"
href="https://github.com/pmndrs/react-three-fiber"
rel="noreferrer"
>
@react-three/fiber
</a>{' '}
is a declarative renderer for Three.js
<ul>
<li>
Demo{' '}
<input
type="checkbox"
checked={showDemo}
onChange={() => {
setShowDemo(!showDemo);
setShowDemo2(false);
}}
/>
</li>
<li>
Demo with controls{' '}
<input
type="checkbox"
checked={showDemo2}
onChange={() => {
setShowDemo(false);
setShowDemo2(!showDemo2);
}}
/>
</li>
</ul>
</li>
</ul>
{(showDemo || showDemo2) && (
<div className={styles.demo}>
<div className={styles.code}>
<SyntaxHighlighter
language="typescript"
style={syntaxStyle}
customStyle={{ fontSize: '1.2em' }}
>
{showDemo ? DemoSource : DemoSource2}
</SyntaxHighlighter>
<br />
<br />
{showDemo && (
<SyntaxHighlighter
language="typescript"
style={syntaxStyle}
customStyle={{ fontSize: '1.2em' }}
>
{DemoThreeSource}
</SyntaxHighlighter>
)}
</div>
<div className={styles.scene}>
{showDemo ? <Demo /> : <Demo2 />}
</div>
</div>
)}
</main>
</div>
);
};
export default ThreeDConcepts;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/03_stars.tsx | TypeScript (TSX) | import React, { useState } from 'react';
import type { NextPage } from 'next';
import Head from 'next/head';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { githubGist as syntaxStyle } from 'react-syntax-highlighter/dist/cjs/styles/hljs';
import styles from '../styles/r3f.module.css';
import Stars from './demos/03-stars';
import AnimatedStars from './demos/03-animated-stars';
import AnimatedStarsSource from '!!raw-loader!./demos/03-animated-stars';
import StarsOnlySource from '!!raw-loader!./demos/03-stars-only';
import AnimatedStarsOnlySource from '!!raw-loader!./demos/03-animated-stars-only';
const sceneLookup = {
stars: [Stars, StarsOnlySource],
animated: [AnimatedStars, AnimatedStarsOnlySource],
full: [AnimatedStars, AnimatedStarsSource],
} as const;
const ThreeDConcepts: NextPage = () => {
const [scene, setScene] = useState<keyof typeof sceneLookup>('stars');
const [Scene, Source] = sceneLookup[scene] ?? [];
return (
<div className={styles.container}>
<Head>
<title>@react-three/fiber</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h3>Adding stars to our scene 💫</h3>
<form onChange={(e) => setScene(e.target.value)}>
<label>
<input type="radio" value="stars" checked={scene === 'stars'} />{' '}
Stars
</label>
<label>
<input
type="radio"
value="animated"
checked={scene === 'animated'}
/>{' '}
Animated stars
</label>
<label>
<input type="radio" value="full" checked={scene === 'full'} />
Stars (full source)
</label>
</form>
{Scene && Source && (
<div className={styles.demo}>
<div className={styles.code}>
<SyntaxHighlighter
language="typescript"
style={syntaxStyle}
customStyle={{ fontSize: '1.2em' }}
>
{Source}
</SyntaxHighlighter>
</div>
<div className={styles.scene}>
<Scene />
</div>
</div>
)}
</main>
</div>
);
};
export default ThreeDConcepts;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/04_smoke.tsx | TypeScript (TSX) | import React, { useState } from 'react';
import type { NextPage } from 'next';
import Head from 'next/head';
import SyntaxHighlighter from 'react-syntax-highlighter';
import { githubGist as syntaxStyle } from 'react-syntax-highlighter/dist/cjs/styles/hljs';
import styles from '../styles/r3f.module.css';
import Smoke from './demos/04-smoke';
import SmokeWithEffects from './demos/04-smoke-with-effects';
import SmokeWithEffectsSource from '!!raw-loader!./demos/04-smoke-with-effects';
import SmokeOnlySource from '!!raw-loader!./demos/04-smoke-only';
import EffectsOnlySource from '!!raw-loader!./demos/04-effects-only';
const sceneLookup = {
smoke: [Smoke, SmokeOnlySource],
effects: [SmokeWithEffects, EffectsOnlySource],
full: [SmokeWithEffects, SmokeWithEffectsSource],
} as const;
const ThreeDConcepts: NextPage = () => {
const [scene, setScene] = useState<keyof typeof sceneLookup>('smoke');
const [Scene, Source] = sceneLookup[scene] ?? [];
return (
<div className={styles.container}>
<Head>
<title>@react-three/fiber</title>
<link rel="icon" href="/favicon.ico" />
</Head>
<main className={styles.main}>
<h3>Adding smoke to our rocket 💨</h3>
<form onChange={(e) => setScene(e.target.value)}>
<label>
<input type="radio" value="smoke" checked={scene === 'smoke'} />{' '}
Smoke
</label>
<label>
<input type="radio" value="effects" checked={scene === 'effects'} />{' '}
Smoke with post-processing effects
</label>
<label>
<input type="radio" value="full" checked={scene === 'full'} />
Final (full source)
</label>
</form>
{Scene && Source && (
<div className={styles.demo}>
<div className={styles.code}>
<SyntaxHighlighter
language="typescript"
style={syntaxStyle}
customStyle={{ fontSize: '1.2em' }}
>
{Source}
</SyntaxHighlighter>
</div>
<div className={styles.scene}>
<Scene />
</div>
</div>
)}
</main>
</div>
);
};
export default ThreeDConcepts;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/__app.tsx | TypeScript (TSX) | import type { AppProps } from 'next/app';
function MyApp({ Component, pageProps }: AppProps) {
console.log({ Component });
return <Component {...pageProps} />;
}
export default MyApp;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/_app.tsx | TypeScript (TSX) | import '../styles/globals.css';
import dynamic from 'next/dynamic';
const NoSSRApp = dynamic(() => import('./__app'), { ssr: false });
export default NoSSRApp;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/api/hello.ts | TypeScript | // Next.js API route support: https://nextjs.org/docs/api-routes/introduction
import type { NextApiRequest, NextApiResponse } from 'next'
type Data = {
name: string
}
export default function handler(
req: NextApiRequest,
res: NextApiResponse<Data>
) {
res.status(200).json({ name: 'John Doe' })
}
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/01.tsx | TypeScript (TSX) | import React, { useRef, useState } from 'react';
import { Canvas, useFrame } from '@react-three/fiber';
import { OrbitControls, useHelper } from '@react-three/drei';
import * as THREE from 'three';
const Demo = (props: React.Props<typeof Scene>) => (
<Canvas shadows style={{ background: '#0a5c5b', height: 600 }}>
<Scene {...props} />
</Canvas>
);
const Scene = ({
showAmbient = true,
showAxes = true,
showPoint = true,
showBoxes = true,
showCamera = true,
showMaterials = true,
showMeshNormal = true,
}) => {
const pointRef = useRef<THREE.PointLight>();
useHelper(showPoint && pointRef, THREE.PointLightHelper, 0.5);
useFrame(({ clock }) => {
if (pointRef.current) {
pointRef.current.position.x = Math.sin(clock.elapsedTime) * Math.PI;
pointRef.current.position.y = Math.cos(clock.elapsedTime) * Math.PI;
}
});
return (
<>
<OrbitControls />
{showAxes && <axesHelper />}
{showCamera && <Camera />}
{showAmbient && <ambientLight intensity={0.2} />}
{showPoint && (
<pointLight
ref={pointRef}
castShadow
intensity={0.5}
position={[2, 2, 2]}
shadow-mapSize-height={1024}
shadow-mapSize-width={1024}
shadow-camera-far={50}
shadow-camera-left={-10}
shadow-camera-right={10}
shadow-camera-top={10}
shadow-camera-bottom={-10}
/>
)}
{showBoxes && (
<>
<Box
castShadow
wireframe={!showMaterials}
position={[-1.2, 0, 1]}
rotation={-0.01}
/>
<Box
wireframe={!showMaterials}
normals={showMeshNormal}
castShadow={false}
position={[1.2, 0, 1]}
/>
<Box
wireframe
castShadow={false}
scale={1.05}
position={[1.2, 0, 1]}
/>
<Plane wireframe={!showMaterials} rotation={[0, Math.PI, 0]} />
</>
)}
</>
);
};
const Box = ({
rotation = 0.01,
wireframe,
normals,
...props
}: Partial<JSX.IntrinsicElements['mesh']> & {
rotation?: number;
normals?: number;
wireframe?: boolean;
}) => {
// This reference gives us direct access to the THREE.Mesh object
const ref = useRef<THREE.mesh>();
// Hold state for hovered and clicked events
const [hovered, hover] = useState(false);
const [clicked, click] = useState(false);
// Subscribe this component to the render-loop, rotate the mesh every frame
useFrame(() => {
if (ref.current) ref.current.rotation.x += rotation;
});
// Return the view, these are regular Threejs elements expressed in JSX
return (
<mesh
{...props}
ref={ref}
scale={(props.scale ?? 1) * (clicked ? 1.5 : 1)}
onClick={() => click(!clicked)}
onPointerOver={() => hover(true)}
onPointerOut={() => hover(false)}
>
<boxGeometry args={[1, 1, 1]} />
{normals ? (
<meshNormalMaterial
wireframe={wireframe}
color={wireframe ? '#000' : hovered ? 'hotpink' : 'orange'}
/>
) : (
<meshStandardMaterial
wireframe={wireframe}
color={wireframe ? '#000' : hovered ? 'hotpink' : 'orange'}
/>
)}
</mesh>
);
};
const Plane = ({
wireframe,
...props
}: Partial<JSX.IntrinsicElements['mesh']> & { wireframe?: boolean }) => (
<mesh {...props} receiveShadow position={[0, 0, -0.01]}>
<planeGeometry args={[10, 10, 10, 10]} />
<meshStandardMaterial
wireframe={wireframe}
color="#3ae8ce"
side={THREE.DoubleSide}
metalness={0.5}
roughness={0.15}
/>
</mesh>
);
const Camera = () => {
const camera = React.useRef<THREE.PerspectiveCamera>();
useHelper(camera, THREE.CameraHelper);
return (
<perspectiveCamera
makeDefault={false}
position={[0, 0, 5]}
near={1}
far={5.2}
ref={camera}
>
<meshBasicMaterial />
</perspectiveCamera>
);
};
export default Demo;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/02-b.tsx | TypeScript (TSX) | import React from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import { Leva, useControls } from 'leva';
const Demo = () => (
<>
<Canvas>
<Scene />
</Canvas>
<Leva />
</>
);
const Scene = () => {
const { background } = useControls({
background: '#b483b4',
});
return (
<>
<color attach="background" args={[background]} />
<OrbitControls />
<ambientLight intensity={0.5} />
<pointLight
color="#0ff"
position={[-3, 3, 0]} // x,y,z
/>
<Rocket />
</>
);
};
const Rocket = () => {
const { wireframe } = useControls({
wireframe: false,
});
return (
<mesh>
<coneGeometry
args={[0.75, 2, 30]} // [radius, height, numSegments]
/>
<meshStandardMaterial wireframe={wireframe} color="#ff8474" />
</mesh>
);
};
export default Demo;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/02-three.tsx | TypeScript (TSX) | import * as THREE from 'three';
export default function ThreeJSEquivalent() {
// const scene = new THREE.Scene(); // <Canvas>
// scene.background = '#b483b4';
// const ambientLight = new THREE.AmbientLight(); // <ambientLight />
// ambientLight.intensity = 0.5;
// const pointLight = new THREE.AmbientLight(); // <pointLight />
// pointLight.color = '#0ff';
// pointLight.position = [3, 10, 0];
// const mesh = new THREE.Mesh(); // <mesh />
// const material = new THREE.MeshStandardMaterial(); // <meshStandardMaterial />
// material.color = '#ff8474';
// const geometry = new THREE.ConeGeometry(0.75, 2, 30); // <coneGeometry />
// mesh.material = material;
// mesh.geometry = geometry;
// scene.add(ambientLight);
// scene.add(pointLight);
// scene.add(mesh);
return null;
}
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/02.tsx | TypeScript (TSX) | import React from 'react';
import { Canvas } from '@react-three/fiber';
const Demo = () => (
<Canvas>
<color attach="background" args={['#b483b4']} />
<ambientLight intensity={0.5} />
<pointLight
color="#0ff"
position={[3, 10, 0]} // x,y,z
/>
<Rocket />
</Canvas>
);
const Rocket = () => (
<mesh>
<coneGeometry
args={[0.75, 2, 30]} // [radius, height, numSegments]
/>
<meshStandardMaterial color="#ff8474" />
</mesh>
);
export default Demo;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/03-animated-stars-only.tsx | TypeScript (TSX) | import React, { useMemo, useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { useControls } from 'leva';
const Stars = ({ speed = 1 }) => {
// tuning variables
const { starCount, starColor, starSpread, wrapDistance } = useControls({
starColor: '#db2438',
starCount: { value: 500, min: 0, max: 1000, step: 1 },
starSpread: { value: 30, min: 1, max: 100, step: 1 },
wrapDistance: { value: 70, min: 20, max: 100, step: 1 },
});
const meshRef = useRef<THREE.InstancedMesh>();
const object3d = useMemo(() => new THREE.Object3D(), []);
// randomly place stars
const stars = useMemo(() => {
const result = [];
for (let i = 0; i < starCount; i++) {
result.push({
// add speedFactor
speedFactor: THREE.MathUtils.randFloat(0.2, 1),
x: THREE.MathUtils.randFloat(-starSpread, starSpread),
y: THREE.MathUtils.randFloat(-starSpread, starSpread),
z: THREE.MathUtils.randFloat(-starSpread, starSpread),
random: THREE.MathUtils.randFloat(20, 100),
});
}
return result;
}, [starCount, starSpread]);
// update stars each frame
useFrame((state) => {
const { elapsedTime } = state.clock;
stars.forEach((star, i) => {
const { x, y, z, random, speedFactor } = star;
const nextY = y - elapsedTime * speed * speedFactor;
// start particle from the top once it's out of view
const nextYWrapped =
(nextY % wrapDistance) + (speed === 0 ? 0 : wrapDistance / 2);
const scale = Math.cos(random);
// Update the dummy object
object3d.position.set(x, nextYWrapped, z);
object3d.scale.set(scale, scale, scale);
object3d.rotation.set(0, Math.PI * elapsedTime * (random / 50), 0);
object3d.updateMatrix();
// And apply the matrix to the instanced item
meshRef.current.setMatrixAt(i, object3d.matrix);
});
meshRef.current.instanceMatrix.needsUpdate = true;
});
return (
<instancedMesh
ref={meshRef}
args={[null, null, starCount]} // [geometry, material, count]
>
<planeGeometry
args={[0.25, 10]} // [width, height]
/>
{/** shiny material */}
<meshPhongMaterial
color={starColor}
side={THREE.DoubleSide} // solid on both sides
depthWrite={false}
/>
</instancedMesh>
);
};
export default Stars;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/03-animated-stars.tsx | TypeScript (TSX) | import React from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import { Leva, useControls } from 'leva';
import AnimatedStars from './03-animated-stars-only';
const Demo = () => (
<>
<Canvas>
<Scene />
</Canvas>
<Leva />
</>
);
const Scene = () => {
const { background, speed } = useControls({
background: '#850085',
speed: { value: 0, min: 0, max: 200 },
});
return (
<>
<color attach="background" args={[background]} />
<OrbitControls />
<ambientLight intensity={0.5} />
<Rocket />
<AnimatedStars speed={speed} />
</>
);
};
const Rocket = () => (
<mesh>
<coneGeometry
args={[0.75, 2, 30]} // [radius, height, numSegments]
/>
<meshStandardMaterial color="#ff8474" />
</mesh>
);
export default Demo;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/03-stars-only.tsx | TypeScript (TSX) | import React, { useMemo, useRef } from 'react';
import { useFrame } from '@react-three/fiber';
import * as THREE from 'three';
import { useControls } from 'leva';
const Stars = () => {
// tuning variables
const { starCount, starColor, starSpread } = useControls({
starColor: '#dec068',
starCount: { value: 100, min: 0, max: 1000, step: 1 },
starSpread: { value: 20, min: 1, max: 100, step: 1 },
});
const meshRef = useRef<THREE.InstancedMesh>();
const object3d = useMemo(() => new THREE.Object3D(), []);
// randomly place stars
const stars = useMemo(() => {
const result = [];
for (let i = 0; i < starCount; i++) {
result.push({
x: THREE.MathUtils.randFloat(-starSpread, starSpread),
y: THREE.MathUtils.randFloat(-starSpread, starSpread),
z: THREE.MathUtils.randFloat(-starSpread, starSpread),
random: THREE.MathUtils.randFloat(20, 100),
});
}
return result;
}, [starCount, starSpread]);
// update stars each frame
useFrame(() => {
stars.forEach((star, i) => {
const { x, y, z, random } = star;
const scale = Math.cos(random);
// Update the dummy object
object3d.position.set(x, y, z);
object3d.scale.set(scale, scale, scale);
object3d.updateMatrix();
// And apply the matrix to the instanced item
meshRef.current.setMatrixAt(i, object3d.matrix);
});
meshRef.current.instanceMatrix.needsUpdate = true;
});
return (
<instancedMesh
ref={meshRef}
args={[null, null, starCount]} // [geometry, material, count]
>
<planeGeometry
args={[0.25, 10]} // [width, height]
/>
{/** shiny material */}
<meshPhongMaterial
color={starColor}
side={THREE.DoubleSide} // solid on both sides
depthWrite={false}
/>
</instancedMesh>
);
};
export default Stars;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/03-stars.tsx | TypeScript (TSX) | import React from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import { Leva, useControls } from 'leva';
import Stars from './03-stars-only';
const Demo = () => (
<>
<Canvas>
<Scene />
</Canvas>
<Leva />
</>
);
const Scene = () => {
const { background } = useControls({
background: '#312331',
});
return (
<>
<color attach="background" args={[background]} />
<OrbitControls />
<ambientLight intensity={0.5} />
<Rocket />
<Stars />
</>
);
};
const Rocket = () => (
<mesh>
<coneGeometry
args={[0.75, 2, 30]} // [radius, height, numSegments]
/>
<meshStandardMaterial color="#ff8474" />
</mesh>
);
export default Demo;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/04-effects-only.tsx | TypeScript (TSX) | import React from 'react';
import { useControls } from 'leva';
import { EffectComposer, Bloom } from '@react-three/postprocessing';
export default function Effects() {
const { intensity, threshold, opacity } = useControls({
intensity: { value: 0.5, min: 0.1, max: 5, step: 0.01 },
threshold: { value: 0.67, min: 0, max: 1, step: 0.01 },
opacity: { value: 0.35, min: 0, max: 1, step: 0.05 },
});
return (
<EffectComposer>
<Bloom
luminanceThreshold={threshold}
intensity={intensity}
luminanceSmoothing={0}
opacity={opacity}
/>
</EffectComposer>
);
}
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/04-smoke-only.tsx | TypeScript (TSX) | import React, { useMemo, useRef } from 'react';
import * as THREE from 'three';
import { useFrame } from '@react-three/fiber';
import { useControls } from 'leva';
const RocketSmoke = ({ speed = 100, particleSize = 0.1 }) => {
// tuning variables
const {
smokeDensity: count,
smokeSpread: cloudSpread,
smokeLength: tailSize,
smokeColor: color,
smokeOpacity: opacity,
smokeSize: smokeMaxSize,
smokeGrowthRate: growthRate,
} = useControls({
smokeDensity: { value: 485, min: 0, max: 1000, step: 1 },
smokeSpread: { value: 3, min: 0, max: 10, step: 0.5 },
smokeLength: { value: 15, min: 10, max: 100, step: 1 },
smokeColor: '#4ce5df',
smokeOpacity: { value: 0.25, min: 0, max: 1, step: 0.05 },
smokeSize: { value: 5, min: 1, max: 100, step: 1 },
smokeGrowthRate: { value: 0.5, min: 0.1, max: 1.5, step: 0.05 },
});
const meshRef = useRef<THREE.InstancedMesh>();
const object3d = useMemo(() => new THREE.Object3D(), []);
const initialY = 0;
// create smoke particles
const particles = useMemo(() => {
const result = [];
for (let i = 0; i < count; i++) {
result.push({
speedVariation: THREE.MathUtils.randFloat(0.01, 0.51),
// y-position
y: THREE.MathUtils.randFloat(initialY, initialY + tailSize),
// how quickly x/z diffuse
growX: THREE.MathUtils.randFloatSpread(cloudSpread),
growZ: THREE.MathUtils.randFloatSpread(cloudSpread),
});
}
return result;
}, [count, cloudSpread, tailSize]);
// update particles per frame
useFrame((state) => {
const { elapsedTime } = state.clock;
particles.forEach((particle, i) => {
const { speedVariation, y, growX, growZ } = particle;
//
const offset = elapsedTime * Math.max(1, speed) * speedVariation;
const nextY = Math.min(0, (y - offset) % tailSize); // wrap particles
const fractionY = nextY / tailSize; // 0-1 of how much y moves
const nextX =
growX * fractionY + // increase along y
Math.sin(growX * elapsedTime) * cloudSpread * fractionY; // variation
const nextZ =
growZ * fractionY + // increase along y
Math.sin(growZ * elapsedTime) * cloudSpread * fractionY; // variation
const scale = Math.min(
0.5 * Math.pow(2, Math.abs(nextY * growthRate)), // grow as y changes
smokeMaxSize
);
// Update the dummy object
object3d.position.set(nextX, nextY, nextZ);
object3d.scale.set(scale, scale, scale);
object3d.updateMatrix();
// And apply the matrix to the instanced item
meshRef.current.setMatrixAt(i, object3d.matrix);
});
meshRef.current.instanceMatrix.needsUpdate = true;
});
return (
<instancedMesh
ref={meshRef}
args={[null, null, count]} // geometry, material
position={[0, -1, 0]} // offset from rocket
>
<sphereGeometry
args={[particleSize, 10, 10]} // [size, widthSegmentCount, heightSegCount]
/>
<meshBasicMaterial
color={color}
transparent
opacity={opacity}
depthWrite={false}
/>
</instancedMesh>
);
};
export default RocketSmoke;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/04-smoke-with-effects.tsx | TypeScript (TSX) | import React from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import { Leva, useControls } from 'leva';
import AnimatedStars from './03-animated-stars-only';
import RocketSmoke from './04-smoke-only';
import Effects from './04-effects-only';
const Demo = ({ showControls = true }) => (
<>
<Canvas camera={{ position: [1, -10, 15] }}>
<Scene />
<Effects />
</Canvas>
<Leva hidden={!showControls} />
</>
);
const Scene = () => {
const { background, speed } = useControls({
background: '#01020d',
speed: { value: 50, min: 0, max: 200 },
});
return (
<>
<color attach="background" args={[background]} />
<OrbitControls />
<ambientLight intensity={0.5} />
<Rocket />
<RocketSmoke speed={speed} />
<AnimatedStars speed={speed} />
</>
);
};
const Rocket = () => (
<mesh>
<coneGeometry
args={[0.75, 2, 30]} // [radius, height, numSegments]
/>
<meshStandardMaterial color="#ff8474" />
</mesh>
);
export default Demo;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/demos/04-smoke.tsx | TypeScript (TSX) | import React from 'react';
import { Canvas } from '@react-three/fiber';
import { OrbitControls } from '@react-three/drei';
import { Leva, useControls } from 'leva';
import AnimatedStars from './03-animated-stars-only';
import RocketSmoke from './04-smoke-only';
const Demo = ({ showControls = true }) => (
<>
<Canvas camera={{ position: [0, 0, -15] }}>
<Scene />
</Canvas>
<Leva hidden={!showControls} />
</>
);
const Scene = () => {
const { background, speed } = useControls({
background: '#311212',
speed: { value: 0, min: 0, max: 200 },
});
return (
<>
<color attach="background" args={[background]} />
<OrbitControls />
<ambientLight intensity={0.5} />
<Rocket />
<RocketSmoke speed={speed} />
<AnimatedStars speed={speed} />
</>
);
};
const Rocket = () => (
<mesh>
<coneGeometry
args={[0.75, 2, 30]} // [radius, height, numSegments]
/>
<meshStandardMaterial color="#ff8474" />
</mesh>
);
export default Demo;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
pages/index.tsx | TypeScript (TSX) | import type { NextPage } from 'next';
import Head from 'next/head';
import styles from '../styles/Home.module.css';
import Demo from './demos/04-smoke-with-effects';
const basePath = process.env.NODE_ENV === 'production' ? '/r3f-spaceship' : '';
const Home: NextPage = () => {
return (
<div className={styles.container}>
<Head>
<title>Build a 3D spaceship 🚀</title>
<link rel="icon" href={`${basePath}/favicon.ico`} />
</Head>
<main className={styles.main}>
<div className={styles.hero}>
<Demo showControls={false} />
</div>
<h1 className={styles.title}>Build a 3D spaceship 🚀</h1>
<p className={styles.description}>
Follow the links below for a step-by-step guide to create the this
</p>
<div className={styles.row}>
<a href={`${basePath}/01_3d-concepts`} className={styles.card}>
<h2>01. 🤓 →</h2>
<p>Basic 3D programming concepts.</p>
</a>
<a href={`${basePath}/02_r3f`} className={styles.card}>
<h2>02. 🚀 →</h2>
<p>3D in React with @react-three/fiber</p>
</a>
<a href={`${basePath}/03_stars`} className={styles.card}>
<h2>03. 💫 →</h2>
<p>Animate stars in our scene</p>
</a>
<a href={`${basePath}/04_smoke`} className={styles.card}>
<h2>04. 💨 →</h2>
<p>Add particle smoke to our rocket</p>
</a>
<div className={styles.card}>
<h2>Resources</h2>
<ul>
<li>
<a target="_blank" rel="noreferrer" href="https://threejs.org/">
three.js
</a>
</li>
<li>
<a
target="_blank"
rel="noreferrer"
href="https://github.com/pmndrs/react-three-fiber"
>
@react-three/fiber
</a>
</li>
<li>
<a
target="_blank"
rel="noreferrer"
href="https://threejs-journey.com/"
>
threejs-journey ($100)
</a>
</li>
<li>
<a
target="_blank"
rel="noreferrer"
href="https://twitter.com/0xca0a"
>
0xca0a (r3f creator)
</a>
</li>
</ul>
</div>
</div>
</main>
</div>
);
};
export default Home;
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
styles/Home.module.css | CSS | .container {
padding: 0;
}
.main {
min-height: 100vh;
flex: 1;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
}
.main a {
text-decoration: none;
}
.title {
color: #de6363;
margin: 0;
line-height: 1.15;
font-size: 4rem;
}
.main a:not(.card) {
color: #de6363;
}
.main a:hover,
.main a:focus,
.main a:active {
text-decoration: underline;
}
.main a:hover,
.main a:focus,
.main a:active {
text-decoration: underline;
}
.title,
.description {
text-align: start;
}
.description {
margin: 2rem 0;
line-height: 1.5;
font-size: 1.5rem;
}
.hero {
width: 100%;
height: 50vh;
margin-bottom: 2rem;
}
.code {
background: #fafafa;
border-radius: 5px;
padding: 0.75rem;
font-size: 1.1rem;
font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
Bitstream Vera Sans Mono, Courier New, monospace;
}
.row {
padding: 0 2rem;
display: flex;
flex-wrap: wrap;
}
.card {
margin-right: 1rem;
margin-bottom: 1rem;
padding: 1.5rem;
text-align: left;
color: inherit;
text-decoration: none;
border: 1px solid #eaeaea;
border-radius: 10px;
transition: color 0.25s ease, border-color 0.15s ease;
width: 220px;
height: 180px;
}
.card:last-child {
margin-left: 2rem;
width: auto;
}
.card:not(:last-child):hover,
.card:not(:last-child):focus,
.card:not(:last-child):active {
color: #de6363;
border-color: #de6363;
}
.card h2 {
margin: 0 0 1rem 0;
font-size: 1.5rem;
}
.column h2 {
margin: 0;
font-size: 1.5rem;
}
.card p {
margin: 0;
font-size: 1.25rem;
line-height: 1.5;
}
@media (max-width: 1000px) {
.row {
width: 100%;
flex-direction: column;
}
.card {
width: 100%;
height: auto;
}
}
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
styles/globals.css | CSS | html,
body {
padding: 0;
margin: 0;
font-family: -apple-system, BlinkMacSystemFont, Segoe UI, Roboto, Oxygen,
Ubuntu, Cantarell, Fira Sans, Droid Sans, Helvetica Neue, sans-serif;
height: 100%;
}
a {
color: inherit;
text-decoration: none;
}
* {
box-sizing: border-box;
}
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
styles/r3f.module.css | CSS | .main {
padding: 2rem;
}
.main ul {
margin-left: 4px;
}
.main ul ul {
margin-bottom: 8px;
}
.main a {
color: #0070f3;
}
.main a:hover,
.main a:focus,
.main a:active {
text-decoration: underline;
}
.demo {
width: 100%;
min-height: calc(100vh - 200px);
display: flex;
flex-wrap: nowrap;
align-items: flex-start;
column-gap: 16px;
margin-top: 1rem;
}
.code {
width: 50%;
overflow: auto;
max-height: calc(100vh - 200px);
border: 1px solid #ccc;
}
.code pre {
margin: 0;
}
.scene {
width: 50%;
flex-grow: 1;
}
.scene canvas {
min-height: calc(100vh - 200px);
}
.scene__full_width {
width: 100%;
flex-grow: 1;
}
.scene__full_width canvas {
min-height: calc(100vh - 200px);
}
.flex {
display: flex;
flex-direction: row;
flex-wrap: wrap;
column-gap: 16px;
row-gap: 16px;
align-items: center;
justify-content: center;
}
| williaster/r3f-spaceship | 0 | example repo for r3f | TypeScript | williaster | Chris Williams | airbnb |
T6A04A.h | C/C++ Header | /*
* Arduino driver for the T6A04A Dot Matrix LCD controller,
* as used by the TI-83+ calculator.
*
* LCD Pinout use by TI-83+ to Toshiba T6A04A - 17 pin interface
* via: https://gist.github.com/parzivail/12ea33cef02794381a06265ff4ef129e
*
* 1 VCC [Fat wire 1] +5
* 2 GND [Fat wire 2] GND
* 3 RST
* 4 NC
* 5 NC
* 6 STB
* 7 DI
* 8 CE
* 9 D7
* 10 D6
* 11 D5
* 12 D4
* 13 D3
* 14 D2
* 15 D1
* 16 D0
* 17 RW
*
* TODO:
* - drawFastVLine
*/
#ifndef T6A04A_H
#define T6A04A_H
#include <Arduino.h>
#include <Adafruit_GFX.h>
typedef unsigned char u8;
typedef u8 pin;
const u8 Y_COUNT = 64;
// the LCD used by TI-83+ has only 96 pixels horizontally,
// although the driver technically supports up to 128 pixels.
const u8 X_COUNT = 96;
const u8 ROW_COUNT = Y_COUNT;
// can't compute COLUMN_COUNT because this depends on the display word size
// which is configurable between 6 and 8 bits.
const u8 STANDBY_ENABLE = LOW;
const u8 STANDBY_DISABLE = HIGH;
const u8 RW_WRITE = LOW;
const u8 RW_READ = HIGH;
typedef enum WriteMode {
WRITE_INSTRUCTION = 1,
WRITE_DATA = 2,
} WriteMode;
typedef enum ReadMode {
READ_STATUS = 1,
READ_DATA = 2,
} ReadMode;
typedef enum CounterOrientation {
// counter moves left and right.
COLUMN_WISE = 1,
// counter moves up and down.
ROW_WISE = 2,
} CounterOrientation;
typedef enum CounterDirection {
// counter moves to the left or down.
INCREMENT = 1,
// counter moves to the right or up.
DECREMENT = 2,
} CounterDirection;
typedef struct CounterConfig {
CounterOrientation orientation;
CounterDirection direction;
} CounterConfig;
typedef enum WordLength {
WORD_LENGTH_8 = 8,
WORD_LENGTH_6 = 6,
} WordLength;
// used to hold OUTPUT, INPUT
typedef u8 IOMode;
class Status {
private:
u8 inner;
public:
Status(u8 v) : inner(v) {}
bool is_busy() const
{
return (this->inner & 0b10000000) != 0;
}
WordLength word_length() const
{
if ((this->inner & 0b01000000) != 0) {
return WordLength::WORD_LENGTH_8;
} else {
return WordLength::WORD_LENGTH_6;
};
}
bool is_enabled() const
{
return (this->inner & 0b00100000) != 0;
}
CounterOrientation counter_orientation() const
{
if ((this->inner & 0b00000010) != 0) {
return CounterOrientation::ROW_WISE;
} else {
return CounterOrientation::COLUMN_WISE;
};
}
CounterDirection counter_direction() const
{
if ((this->inner & 0b00000001) != 0) {
return CounterDirection::INCREMENT;
} else {
return CounterDirection::DECREMENT;
};
}
CounterConfig counter_config() const
{
return CounterConfig {
this->counter_orientation(),
this->counter_direction(),
};
}
};
class T6A04A : public Adafruit_GFX
{
private:
pin rst; // pin 3
pin stb; // pin 6
pin di; // pin 7
pin ce; // ...
pin d7;
pin d6;
pin d5;
pin d4;
pin d3;
pin d2;
pin d1;
pin d0;
pin rw; // pin 17
CounterConfig counter_config;
WordLength word_length;
IOMode io_mode;
void bus_write(WriteMode m, u8 v)
{
bool di = 0;
if (m == WriteMode::WRITE_INSTRUCTION) {
di = LOW;
} else if (m == WriteMode::WRITE_DATA) {
di = HIGH;
} else {
Serial.println("error: unexpected write mode");
abort();
}
digitalWrite(this->ce, LOW);
digitalWrite(this->di, di);
this->set_bus_mode(OUTPUT);
digitalWrite(this->d0, HIGH && (v & B00000001));
digitalWrite(this->d1, HIGH && (v & B00000010));
digitalWrite(this->d2, HIGH && (v & B00000100));
digitalWrite(this->d3, HIGH && (v & B00001000));
digitalWrite(this->d4, HIGH && (v & B00010000));
digitalWrite(this->d5, HIGH && (v & B00100000));
digitalWrite(this->d6, HIGH && (v & B01000000));
digitalWrite(this->d7, HIGH && (v & B10000000));
digitalWrite(this->ce, HIGH);
// "As mentioned, a 10 microsecond delay is required after sending the command"
// via: https://wikiti.brandonw.net/index.php?title=83Plus:Ports:10
delayMicroseconds(10);
digitalWrite(this->ce, LOW);
}
void write_instruction(u8 v)
{
this->bus_write(WriteMode::WRITE_INSTRUCTION, v);
}
void write_data(u8 v)
{
this->bus_write(WriteMode::WRITE_DATA, v);
}
void set_bus_mode(IOMode m)
{
if (m != this->io_mode) {
if (OUTPUT == m) {
digitalWrite(this->rw, RW_WRITE);
} else if (INPUT == m) {
digitalWrite(this->rw, RW_READ);
} else {
Serial.println("error: unexpected IO mode");
abort();
}
pinMode(this->d0, m);
pinMode(this->d1, m);
pinMode(this->d2, m);
pinMode(this->d3, m);
pinMode(this->d4, m);
pinMode(this->d5, m);
pinMode(this->d6, m);
pinMode(this->d7, m);
this->io_mode = m;
}
}
u8 bus_read(ReadMode m)
{
digitalWrite(this->ce, LOW);
if (ReadMode::READ_STATUS == m) {
digitalWrite(this->di, LOW);
} else if (ReadMode::READ_DATA == m) {
digitalWrite(this->di, HIGH);
} else {
Serial.println("error: unexpected read mode");
abort();
}
this->set_bus_mode(INPUT);
digitalWrite(this->ce, HIGH);
// "As mentioned, a 10 microsecond delay is required after sending the command"
// via: https://wikiti.brandonw.net/index.php?title=83Plus:Ports:10
delayMicroseconds(10);
const u8 d0 = digitalRead(this->d0);
const u8 d1 = digitalRead(this->d1);
const u8 d2 = digitalRead(this->d2);
const u8 d3 = digitalRead(this->d3);
const u8 d4 = digitalRead(this->d4);
const u8 d5 = digitalRead(this->d5);
const u8 d6 = digitalRead(this->d6);
const u8 d7 = digitalRead(this->d7);
digitalWrite(this->ce, LOW);
return (
(d7 << 7) |
(d6 << 6) |
(d5 << 5) |
(d4 << 4) |
(d3 << 3) |
(d2 << 2) |
(d1 << 1) |
d0
);
}
// turn the given index on/off within the given word.
static inline u8 paint_pixel(u8 word, u8 index, bool color) {
if (color) {
return word | (0b10000000 >> index);
} else {
return word & ~(0b10000000 >> index);
}
}
public:
T6A04A(
pin rst,
pin stb,
pin di,
pin ce,
pin d7,
pin d6,
pin d5,
pin d4,
pin d3,
pin d2,
pin d1,
pin d0,
pin rw)
: rst(rst),
stb(stb),
di(di),
ce(ce),
d7(d7),
d6(d6),
d5(d5),
d4(d4),
d3(d3),
d2(d2),
d1(d1),
d0(d0),
rw(rw),
counter_config(CounterConfig { CounterOrientation::ROW_WISE, CounterDirection::INCREMENT }),
word_length(WordLength::WORD_LENGTH_8),
io_mode(OUTPUT),
Adafruit_GFX(96, 64)
{
pinMode(this->ce, OUTPUT);
pinMode(this->di, OUTPUT);
pinMode(this->rw, OUTPUT);
pinMode(this->rst, OUTPUT);
pinMode(this->d0, OUTPUT);
pinMode(this->d1, OUTPUT);
pinMode(this->d2, OUTPUT);
pinMode(this->d3, OUTPUT);
pinMode(this->d4, OUTPUT);
pinMode(this->d5, OUTPUT);
pinMode(this->d6, OUTPUT);
pinMode(this->d7, OUTPUT);
// the LCD is reset when RST is pulsed low.
digitalWrite(this->rst, HIGH);
digitalWrite(this->stb, STANDBY_DISABLE);
}
void init() {
this->reset();
this->set_word_length(WordLength::WORD_LENGTH_8);
this->enable_display();
this->set_contrast(48);
this->set_counter_orientation(CounterOrientation::ROW_WISE);
this->set_counter_direction(CounterDirection::INCREMENT);
this->set_column(0);
this->set_row(0);
this->set_z(0);
}
// > When /RST = L, the reset function is executed and the following settings are mode.
// > (3) Display..............................OFF
// > (4) Word length..........................8 bits/word
// > (5) Counter mode.........................Y-counter (row-counter)/up mode
// > (6) Y-(page) address.....................Page = 0 (column 0)
// > (7) X-address............................XAD = 0 (row 0)
// > (8) Z-address............................ZAD = 0
// > (9) Op-amp1 (OPA1) ......................min
// > (10) Op-amp2 (OPA2) ......................min
void reset() {
digitalWrite(this->rst, LOW);
// "As mentioned, a 10 microsecond delay is required after sending the command"
// via: https://wikiti.brandonw.net/index.php?title=83Plus:Ports:10
delayMicroseconds(10);
digitalWrite(this->rst, HIGH);
}
// set the word length used when write/reading data to the display.
// this seems to be useful to update either 8 or 6 bit regions quickly,
// e.g. when a character is 8 or 6 pixels wide.
//
// this doesn't affect the total number of required pins,
// only the display word size.
//
// command: 86E
//
// cost: one bus operation
void set_word_length(WordLength wl)
{
this->word_length = wl;
if (wl == WordLength::WORD_LENGTH_8) {
this->write_instruction(0b00000001);
} else if (wl == WordLength::WORD_LENGTH_6) {
this->write_instruction(0b00000000);
} else {
Serial.println("error: unexpected word length");
abort();
}
}
// > When /STB = L, the T6A04A is in standby state.
// > The internal oscillator is stopped, power consumption is
// > reduced, and the power supply level for the LCD (VLC1 to VLC5) becomes VDD.
void enable_standby() {
digitalWrite(this->stb, STANDBY_ENABLE);
}
// > When /STB = L, the T6A04A is in standby state.
// > The internal oscillator is stopped, power consumption is
// > reduced, and the power supply level for the LCD (VLC1 to VLC5) becomes VDD.
void disable_standby() {
digitalWrite(this->stb, STANDBY_DISABLE);
}
// > This command sets the contrast for the LCD.
// > The LCD contrast can be set in 64 steps.
//
// command: SCE
//
// cost: one bus operation
void set_contrast(u8 contrast)
{
this->write_instruction(0b11000000 | (contrast & 0b00111111));
}
// > This command turns display ON/OFF. It does not affect the data in the display RAM.
//
// command: DPE (ON)
//
// cost: one bus operation
void enable_display()
{
this->write_instruction(0b00000011);
}
// > This command turns display ON/OFF. It does not affect the data in the display RAM.
//
// command: DPE (OFF)
//
// cost: one bus operation
void disable_display()
{
this->write_instruction(0b00000010);
}
void set_counter_config(CounterOrientation o, CounterDirection d)
{
if (this->counter_config.direction == d && this->counter_config.orientation == o) {
return;
}
this->counter_config = CounterConfig { o, d };
u8 command = 0b00000100;
if (o == CounterOrientation::ROW_WISE) {
command |= 0b00000010;
} else if (o == CounterOrientation::COLUMN_WISE) {
// pass: bit is unset
} else {
Serial.println("error: unexpected counter orientation");
abort();
}
if (d == CounterDirection::INCREMENT) {
command |= 0b00000001;
} else if (d == CounterDirection::DECREMENT) {
// pass: bit is unset
} else {
Serial.println("error: unexpected counter direction");
abort();
}
this->write_instruction(command);
}
void set_counter_orientation(CounterOrientation o)
{
this->set_counter_config(o, this->counter_config.direction);
}
void set_counter_direction(CounterDirection d)
{
this->set_counter_config(this->counter_config.orientation, d);
}
// set the column coordinate for subsequent call to `write_byte`.
// column zero is the left-most column.
// note that the unit here is in 8 (or 6)-bit bytes, not pixels.
//
// changing the word-width via `set_word_length` will affect the unit.
//
// the internal counter dictates how the column is incremented after a write.
// see `set_counter_direction` for more information.
//
// command: SYE
//
// cost: one bus operation
void set_column(u8 column)
{
this->write_instruction(0b00100000 | (column & 0b00011111));
}
// set the row coordinate for subsequent calls to `write_byte`.
// row zero is the top-most row.
// unit: pixels.
//
// the internal counter dictates how the row is incremented after a write.
// see `set_counter_direction` for more information.
//
// command: SXE
//
// cost: one bus operation
void set_row(u8 row)
{
this->write_instruction(0b10000000 | (row & 0b00111111));
}
// > This command sets the top row of the LCD screen, irrespective of the current [Y]-address.
// > For instance, when the Z-address is 32, the top row of the LCD screen is address 32
// > of the display RAM, and the bottom row of the LCD screen is address 31 of the display RAM.
//
// wb: I believe you use can use this to implement scrolling.
//
// command: SZE
//
// cost: one bus operation
void set_z(u8 z)
{
this->write_instruction(0b01000000 | (z & 0b00111111));
}
// write a word of data to the LCD, left-to-right.
// MSB is the leftmost pixel, LSB is the rightmost pixel.
//
// changing the word-width via `set_word_length` will affect the unit.
//
// the internal counter dictates how the address is incremented after a write.
// see `set_counter_direction` for more information.
//
// cost: one bus operation
void write_word(u8 v)
{
this->write_data(v);
}
// naive clear of the LCD by writing zeros to all pixels.
//
// this may change the counter config and word length.
//
// cost: 796 bus operations
void clear()
{
this->fillScreen(0);
}
// command: STRD
//
// cost: one bus operation
Status read_status()
{
return Status(this->bus_read(ReadMode::READ_STATUS));
}
// read a word of data from the current address.
// write a word of data to the LCD, left-to-right.
// MSB is the leftmost pixel, LSB is the rightmost pixel.
//
// changing the word-width via `set_word_length` will affect the unit.
//
// the internal counter dictates how the address is incremented after a read.
// see `set_counter_direction` for more information.
//
// after changing the address, ensure you read a dummy value first:
//
// > However, when a data read is executed, the correct data does not appear on the first
// > data reading. Therefore, ensure that the T6A04A performs a dummy data read before
// > reading the actual data.
//
// once the dummy value is read, its ok to read multiple times.
//
// command: DARD
//
// cost: one bus operation
u8 read_word()
{
return this->bus_read(ReadMode::READ_DATA);
}
// read the word at the given coordinates.
//
// use only if you expect the coordinates to differ from the current adddress,
// because this routine updates coordinates and handles the dummy read.
// this is less efficient than sequential reads that rely on the counter.
//
// cost: four bus operations
u8 read_word_at(u8 row, u8 column)
{
this->set_row(row);
this->set_column(column);
this->read_word(); // dummy
return this->read_word();
}
// write word at the given coordinates.
//
// use only if you expect the coordinates to differ from the current adddress,
// because this routine updates coordinates.
// this is less efficient than sequential writes that rely on the counter.
//
// cost: three bus operations
void write_word_at(u8 row, u8 column, u8 word)
{
this->set_row(row);
this->set_column(column);
this->write_word(word);
}
// naive update of a single pixel at a given (x, y) location.
//
// note this assumes 8-bit word size.
//
// note that this isn't really very fast: it must read the current word and the write it back.
// if you have RAM to spare, then you should probably maintain a local screen buffer instead.
// (but this takes 1024 bytes to represent the entire 64x128 display)
//
// it takes about 4s to update the entire screen using this routine repeatedly,
// which is about .6ms/pixel.
//
// so, for example, if you're targetting 16ms/frame, thats about 26 pixels.
//
// cost: seven bus operations
void write_pixel(u8 x, u8 y, bool on)
{
if (x >= X_COUNT || y >= Y_COUNT) {
return;
}
u8 row = y;
u8 column = x / 8;
u8 bit = x % 8;
u8 existing = this->read_word_at(row, column);
u8 next = this->paint_pixel(existing, bit, on);
if (next != existing) {
this->write_word_at(row, column, next);
}
}
virtual void drawPixel(int16_t x, int16_t y, uint16_t color) override
{
if (x < 0 || x >= X_COUNT || y < 0 || y >= Y_COUNT) {
return;
}
this->write_pixel(x, y, color != 0);
}
// optimized implementation of horizontal line drawing,
// taking advantage of the auto-incrementing counter and
// sequential 8-bit read/writes.
virtual void drawFastHLine(int16_t x, int16_t y, int16_t w, uint16_t color) override
{
if (w == 0) {
// zero width line: no pixels.
return;
}
if (w < 0) {
// enforce w to be positive.
x = x + w;
w = -w;
}
if (y < 0 || y >= Y_COUNT) {
// this is off the screen, low or high
return;
}
u8 start_x = x;
u8 end_x = x + w;
if (end_x < 0 || start_x >= X_COUNT) {
// all pixels off the side of the screen
return;
}
if (start_x < 0) {
// clamp line within the screen
start_x = 0;
}
if (end_x > X_COUNT) {
// clamp line within the screen
end_x = X_COUNT;
}
const u8 row = y;
this->set_word_length(WordLength::WORD_LENGTH_8);
this->set_counter_config(CounterOrientation::ROW_WISE, CounterDirection::INCREMENT);
const u8 start_column = start_x / WordLength::WORD_LENGTH_8;
const u8 end_column = end_x / WordLength::WORD_LENGTH_8;
bool start_aligned = 0 == (start_x % WordLength::WORD_LENGTH_8);
bool end_aligned = 0 == (end_x % WordLength::WORD_LENGTH_8);
// there are two special cases:
// 1. only one word is partially overwritten, this takes one read and one write.
// 2. the line is word-aligned, we can blindly overwrite those words directly.
//
// in the general case, we need to read in the existing data,
// update it, and write it back out.
if (start_column == end_column) {
// case 1:
// all pixels in the same word
// 00xxxxxx00
u8 left_pixel = start_x % WordLength::WORD_LENGTH_8;
u8 right_pixel = end_x % WordLength::WORD_LENGTH_8;
u8 word = this->read_word_at(row, start_column);
for (u8 i = left_pixel; i < right_pixel; i++) {
word = this->paint_pixel(word, i, 0 != color);
}
this->write_word_at(row, start_column, word);
} else if (start_aligned && end_aligned) {
// case 2:
// line with aligned edges
// 00000000 xxxxxxxx ... xxxxxxxx 00000000
this->set_row(row);
this->set_column(start_column);
while (x + 8 <= end_x) {
// we can blindly overwrite the word
// because all bits will be set.
if (0 != color) {
this->write_word(0b11111111);
} else {
this->write_word(0b00000000);
}
x += 8;
}
} else {
// general case:
// multi-word line with at least one unaligned edge
// 00000xxx xxxxxxxx xxx00000
// 00000000 xxxxxxxx xxx00000
// 00000xxx xxxxxxxx 00000000
// statically allocate enough space for an entire row (12 bytes),
// even if we only use a few bytes,
// since this is trivially fast (stack allocation).
u8 words[X_COUNT / WordLength::WORD_LENGTH_8];
// read the start and end words.
// we don't care about the middle words,
// because we blindly overwrite them.
{
this->set_row(row);
this->set_column(start_column);
this->read_word(); // dummy
words[start_column] = this->read_word();
if (start_column + 1 != end_column) {
// if the start and end columns are adjacent,
// its faster to just read the next word directly.
// otherwise, seek to end column.
this->set_column(end_column);
this->read_word(); // dummy
}
words[end_column] = this->read_word();
}
// update the row contents
// to be written back out in one pass.
{
// unaligned left side
// 00000xxx ........
if (0 != start_x % WordLength::WORD_LENGTH_8) {
u8 start_pixel = start_x % WordLength::WORD_LENGTH_8;
u8 start_word = words[start_column];
for (u8 i = start_pixel; i < WordLength::WORD_LENGTH_8; i++) {
start_word = this->paint_pixel(start_word, i, 0 != color);
x += 1;
}
words[start_column] = start_word;
}
// x is now aligned to the start of a word.
// aligned middle
// ........ xxxxxxxx ........
while (x + 8 <= end_x) {
// we can blindly overwrite the word
// because all bits will be set.
if (0 != color) {
words[x / WordLength::WORD_LENGTH_8] = 0b11111111;
} else {
words[x / WordLength::WORD_LENGTH_8] = 0b00000000;
}
x += 8;
}
// unaligned right side
// ........ xxx00000
if (0 != end_x % WordLength::WORD_LENGTH_8) {
u8 end_pixel = end_x % WordLength::WORD_LENGTH_8;
u8 end_word = words[end_column];
for (u8 i = 0; i < end_pixel; i++) {
end_word = this->paint_pixel(end_word, i, 0 != color);
x += 1;
}
words[end_column] = end_word;
}
}
// write the affected row data (up to 12 bytes) in one pass
// relying on the counter to increment the address.
{
this->set_row(row);
this->set_column(start_column);
for (u8 i = start_column; i < end_column + 1; i++) {
this->write_word(words[i]);
}
}
}
}
virtual void fillRect(int16_t x, int16_t y, int16_t w, int16_t h, uint16_t color) override
{
if (w == 0 || h == 0) {
return;
}
if (w < 0) {
// enforce w to be positive.
x = x + w;
w = -w;
}
if (h < 0) {
// enforce h to be positive.
y = y + h;
h = -h;
}
if (x >= X_COUNT) {
return;
}
if (y >= Y_COUNT) {
return;
}
u8 start_x = x;
u8 end_x = x + w;
u8 start_y = y;
u8 end_y = y + h;
if (end_x < 0) {
return;
}
if (end_y < 0) {
return;
}
if (start_x < 0) {
// clamp line within the screen
start_x = 0;
}
if (end_x > X_COUNT) {
// clamp line within the screen
end_x = X_COUNT;
}
if (start_y < 0) {
// clamp line within the screen
start_y = 0;
}
if (end_y > Y_COUNT) {
// clamp line within the screen
end_y = Y_COUNT;
}
for (u8 row = start_y; row < end_y; row++) {
this->drawFastHLine(start_x, row, end_x - start_x, color);
}
}
virtual void fillScreen(uint16_t color) override
{
this->set_counter_config(CounterOrientation::COLUMN_WISE, CounterDirection::INCREMENT);
this->set_word_length(WordLength::WORD_LENGTH_8);
const u8 word = 0 == color ? 0b00000000 : 0b11111111;
// columns are longer than rows,
// so clear column-wise for fewer total calls to set_row/column
for (int x = 0; x < (X_COUNT / WordLength::WORD_LENGTH_8); x++) {
this->set_column(x);
this->set_row(0);
for (int y = 0; y < Y_COUNT; y++) {
this->write_word(word);
}
}
}
};
#endif // T6A04A_H | williballenthin/arduino-T6A04A | 0 | Arduino display driver for the T6A04A monochrome LCD driver used in TI-83 graphing calculators | C++ | williballenthin | Willi Ballenthin | HexRaysSA |
opt.cpp | C++ | #include "T6A04A.h"
#include "opt.h"
class Benchmark {
protected:
// implement these!
virtual void step(T6A04A *lcd, bool color) = 0;
virtual char* name() = 0;
public:
void run(T6A04A *lcd)
{
lcd->init();
lcd->clear();
Serial.print("measuring: ");
Serial.print(this->name());
Serial.print(": ");
const u32 count = 100;
u32 ts0 = millis();
bool color = true;
for (u32 i = 0; i < count; i++) {
this->step(lcd, color);
color = !color;
}
u32 ts1 = millis();
Serial.print(float(ts1 - ts0) / float(count));
Serial.print("ms");
Serial.println("");
return;
}
};
// Arduino Uno R3: 0.08ms/op
class SetColumnBenchmark : public Benchmark {
virtual char* name() override {
return "set column";
}
virtual void step(T6A04A *lcd, bool color) override {
lcd->set_column(0);
}
};
// Arduino Uno R3: 0.08ms/op
class SetRowBenchmark : public Benchmark {
virtual char* name() override {
return "set row";
}
virtual void step(T6A04A *lcd, bool color) override {
lcd->set_row(0);
}
};
// Arduino Uno R3: 0.08ms/write
class WriteWordBenchmark : public Benchmark {
virtual char* name() override {
return "write word";
}
virtual void step(T6A04A *lcd, bool color) override {
lcd->write_word(0x00);
}
};
// Arduino Uno R3: 0.22ms/write
class WriteWordAtBenchmark : public Benchmark {
virtual char* name() override {
return "write word at";
}
virtual void step(T6A04A *lcd, bool color) override {
lcd->write_word_at(0, 0, 0x00);
}
};
// Arduino Uno R3: 0.08ms/read
class ReadWordBenchmark : public Benchmark {
virtual char* name() override {
return "read word";
}
virtual void step(T6A04A *lcd, bool color) override {
lcd->read_word();
}
};
// Arduino Uno R3: 0.37ms/read
class ReadWordAtBenchmark : public Benchmark {
virtual char* name() override {
return "read word at";
}
virtual void step(T6A04A *lcd, bool color) override {
lcd->read_word_at(0, 0);
}
};
// Arduino Uno R3: 0.62ms/write
class WritePixelBenchmark : public Benchmark {
virtual char* name() override {
return "write pixel";
}
virtual void step(T6A04A *lcd, bool color) override {
lcd->write_pixel(0, 0, color);
}
};
//
// naive horizontal line (96px) via write_pixel
// Arduino Uno R3: 60ms/line
//
class NaiveHLineBenchmark : public Benchmark {
virtual char* name() override {
return "naive hline";
}
virtual void step(T6A04A *lcd, bool color) override {
for (u8 x = 0; x < 96; x++) {
lcd->write_pixel(x, 0, color);
}
}
};
//
// optimized horizontal line (96px) via drawFastHLine
// Arduino Uno R3: 1.2ms/line (23x speedup over naive)
//
class FastHLineBenchmark : public Benchmark {
virtual char* name() override {
return "fast hline";
}
virtual void step(T6A04A *lcd, bool color) override {
lcd->drawFastHLine(0, 0, 96, color);
}
};
// naive vertical line (64px) via write_pixel
// Arduino Uno R3: 40ms/line
class NaiveVLineBenchmark : public Benchmark {
virtual char* name() override {
return "naive vline";
}
virtual void step(T6A04A *lcd, bool color) override {
for (u8 y = 0; y < 64; y++) {
lcd->write_pixel(0, y, color);
}
}
};
// naive 8x8 px rect at (0, 0) via write_pixel
// Arduino Uno R3: 40ms/rect
class NaiveAlignedRectBenchmark : public Benchmark {
virtual char* name() override {
return "naive aligned rect";
}
virtual void step(T6A04A *lcd, bool color) override {
for (u8 x = 0; x < 8; x++) {
for (u8 y = 0; y < 8; y++) {
lcd->write_pixel(x, y, color);
}
}
}
};
// optimized 8x8 px rect at (0, 0)
// Arduino Uno R3: 2.6ms/rect
class FastAlignedRectBenchmark : public Benchmark {
virtual char* name() override {
return "fast aligned rect";
}
virtual void step(T6A04A *lcd, bool color) override {
lcd->fillRect(0, 0, 8, 8, color);
}
};
// naive 8x8 px rect at (4, 4) via write_pixel
// Arduino Uno R3: 40ms/rect (15x speedup)
class NaiveUnalignedRectBenchmark : public Benchmark {
virtual char* name() override {
return "naive unaligned rect";
}
virtual void step(T6A04A *lcd, bool color) override {
for (u8 x = 0; x < 8; x++) {
for (u8 y = 0; y < 8; y++) {
lcd->write_pixel(x + 4, y + 4, color);
}
}
}
};
// fast 8x8 px rect at (4, 4)
// Arduino Uno R3: 7ms/rect (5x speedup)
class FastUnalignedRectBenchmark : public Benchmark {
virtual char* name() override {
return "fast unaligned rect";
}
virtual void step(T6A04A *lcd, bool color) override {
lcd->fillRect(2, 2, 8, 8, color);
}
};
// Arduino Uno R3: 61ms
class FillScreenBenchmark : public Benchmark {
virtual char* name() override {
return "fill screen";
}
virtual void step(T6A04A *lcd, bool color) override {
lcd->fillScreen(color);
}
};
static Benchmark *benchmarks[] = {
new SetColumnBenchmark(),
new SetRowBenchmark(),
new WriteWordBenchmark(),
new WriteWordAtBenchmark(),
new ReadWordBenchmark(),
new ReadWordAtBenchmark(),
new WritePixelBenchmark(),
new NaiveHLineBenchmark(),
new FastHLineBenchmark(),
new NaiveVLineBenchmark(),
new NaiveAlignedRectBenchmark(),
new FastAlignedRectBenchmark(),
new NaiveUnalignedRectBenchmark(),
new FastUnalignedRectBenchmark(),
new FillScreenBenchmark(),
};
void run_benchmarks(T6A04A *lcd)
{
for (u8 i = 0; i < sizeof(benchmarks) / sizeof(Benchmark*); i++) {
benchmarks[i]->run(lcd);
}
} | williballenthin/arduino-T6A04A | 0 | Arduino display driver for the T6A04A monochrome LCD driver used in TI-83 graphing calculators | C++ | williballenthin | Willi Ballenthin | HexRaysSA |
opt.h | C/C++ Header | #ifndef OPT_H
#define OPT_H
#include "T6A04A.h"
void run_benchmarks(T6A04A *lcd);
#endif // OPT_H | williballenthin/arduino-T6A04A | 0 | Arduino display driver for the T6A04A monochrome LCD driver used in TI-83 graphing calculators | C++ | williballenthin | Willi Ballenthin | HexRaysSA |
test.cpp | C++ | #include "test.h"
//
// demonstrate a few features of the T6A04A driver.
// use a serial connection to verify the output.
//
bool test_T6A04A(T6A04A *lcd)
{
lcd->init();
//
// demonstrate status read
//
Status s = lcd->read_status();
if (s.counter_orientation() != CounterOrientation::ROW_WISE) {
Serial.println("FAIL: unexpected counter orientation");
return false;
}
if (s.counter_direction() != CounterDirection::INCREMENT) {
Serial.println("FAIL: unexpected counter direction");
return false;
}
if (s.word_length() != WordLength::WORD_LENGTH_8) {
Serial.println("FAIL: unexpected word length");
return false;
}
if (!s.is_enabled()) {
Serial.println("FAIL: unexpected status");
return false;
}
if (s.is_busy()) {
Serial.println("FAIL: unexpected busy");
return false;
}
//
// demonstrate writing to lcd memory
//
lcd->set_row(1);
lcd->set_column(1);
lcd->write_word(0b10101010);
lcd->write_word(0b11111111);
//
// demonstrate reading from lcd memory
//
lcd->set_row(1);
lcd->set_column(1);
// must read a dummy value after changing an address
u8 dummy = lcd->read_word();
if (0b10101010 != lcd->read_word()) {
Serial.println("FAIL: unexpected value at (1, 1)");
return false;
}
if (0b11111111 != lcd->read_word()) {
Serial.println("FAIL: unexpected value at (2, 1)");
return false;
}
//
// demonstrate using Adafruit_GFX functionality
// (but note there aren't any assertions here).
//
lcd->drawLine(0, 0, X_COUNT, Y_COUNT, true);
lcd->drawLine(X_COUNT, 0, 0, Y_COUNT, true);
lcd->setCursor(1, 1);
lcd->setTextColor(1);
lcd->setTextSize(1);
lcd->setTextWrap(true);
lcd->println("Hello, world!");
//
// pass
//
lcd->clear();
Serial.println("PASS");
return true;
} | williballenthin/arduino-T6A04A | 0 | Arduino display driver for the T6A04A monochrome LCD driver used in TI-83 graphing calculators | C++ | williballenthin | Willi Ballenthin | HexRaysSA |
test.h | C/C++ Header | #include "T6A04A.h"
bool test_T6A04A(T6A04A *lcd);
| williballenthin/arduino-T6A04A | 0 | Arduino display driver for the T6A04A monochrome LCD driver used in TI-83 graphing calculators | C++ | williballenthin | Willi Ballenthin | HexRaysSA |
buildtools.ps1 | PowerShell | function Build-Library {
[CmdletBinding()]
param (
[ValidateNotNullOrEmpty()]
[string[]]$Libraries = @()
)
$platforms = @("x86-windows-static", "x64-windows-static");
$versions = @("v140", "v141", "v142");
$arguments = "";
foreach ($library in $Libraries) {
foreach ($platform in $platforms) {
foreach ($version in $versions) {
$arguments += " ${library}:${platform}-${version}";
}
}
}
$cmd = "docker run --network 'Default Switch' -v libs:c:\vcpkg\vcpkg-master\installed buildtools install ${arguments}";
Write-Verbose -Message $cmd;
Invoke-Expression $cmd;
}
| williballenthin/siglib | 12 | function identification signatures | Python | williballenthin | Willi Ballenthin | HexRaysSA |
create_sig.py | Python | """
create a .sig file from .pat files stored in tarballs
optionally excludes tarball paths and includes pat file names
example runs:
$ python3 create_sig.py -d -e libraries test -i libc msvc --tarballs-root data/ -- outdir/
-d - output debugging messages
-e - exclude paths containing string `libraries` or `test`
-ip - include pat files containing `libc` and `msvc`
--tarballs-root - root path storing tarballs containing .pat files
--
data/ - root path of tarballs
outdir/ - path to output files
$ python3 create_sig.py --patfiles data/VS6/vc98/lib/libc*.pat -- outdir/
--patfiles - paths to .pat files
--
outdir/ - path to output files
"""
import os
import shutil
import sys
import logging
import tarfile
import argparse
import subprocess
logger = logging.getLogger(__name__)
# the patched sigmake doesn't complain about number of leaves
PATH_SIGMAKE = os.path.abspath("../sigmake_patched.exe")
PATH_ZIPSIG = os.path.abspath("../zipsig.exe")
SIGNAME_DEFAULT = "(sigfile)"
def collect_tarball_paths(path, exclude=None):
"""
return all tarballs recursively collected starting from path
exclude specifies a list of strings used to filter out paths
"""
tarball_paths = []
for root, dirs, files in os.walk(path):
for file in files:
if not file.endswith(".tar.gz"):
continue
tarball_path = os.path.join(root, file)
if exclude:
skip = False
for exc in exclude:
if exc in tarball_path:
skip = True
break
if skip:
logger.debug(f" [-] skipping {tarball_path}")
continue
tarball_paths.append(tarball_path)
return tarball_paths
def extract_pat_files(outdir, tarball_path, exclude=None, include=None, write_files=True):
"""
extract all .pat files from a tarball to output directory
"""
tar = tarfile.open(tarball_path, "r:gz")
for m in tar.getmembers():
if not m.name.endswith(".pat"):
continue
if exclude:
skip = False
for exc in exclude:
if exc in m.name:
skip = True
break
if skip:
logger.debug(f" [-] skipping {m.name}")
continue
if include:
for inc in include:
if inc in m.name:
if write_files:
write_tar_member(outdir, tar, m)
else:
logger.debug(f" [+] {m.name}")
else:
if write_files:
write_tar_member(outdir, tar, m)
else:
logger.debug(f" [+] {m.name}")
return 0
def write_tar_member(outdir, tar, m):
"""
write file from tarball to output directory
"""
outpath = os.path.join(outdir, flatten_path(m.name))
logger.debug(" writing %s", outpath)
with open(outpath, "wb") as f:
f.write(tar.extractfile(m).read())
def flatten_path(name):
# tarballs may store directory structure, e.g. VS6.tar.gz/VS6.tar/VS6/vc98/lib/libc.lib.pat
name = name.replace("/", "-")
return name
def create_sig_file_from_pats(outdir, outsigfile, patfiles, signame, reject_functions, ignore_functions):
"""
convenience functionality around IDA's sigmake
"""
outsigfile = os.path.join(outdir, outsigfile)
reject_functions = [f"-lr{rf}" for rf in reject_functions] if reject_functions else []
ignore_functions = [f"-li{igf}" for igf in ignore_functions] if ignore_functions else []
# use multiple -v for more verbosity, two appears to be max
args = (
[PATH_SIGMAKE, "-v", "-v"] + [f'-n"{signame}"'] + reject_functions + ignore_functions + patfiles + [outsigfile]
)
logfile = open(os.path.join(outdir, "run1.log"), "wb")
r = run(args, stdout=logfile, stderr=logfile)
logfile.close()
exc_file = os.path.splitext(outsigfile)[0] + ".exc"
if not os.path.exists(exc_file):
raise ValueError(f"sigmake failed, check {logfile.name} - did not create exclusion file {exc_file}")
process_exc_file(exc_file)
logfile = open(os.path.join(outdir, "run2.log"), "wb")
run(args, stdout=logfile, stderr=logfile)
logfile.close()
if not os.path.exists(outsigfile):
raise ValueError(f"did not create {outsigfile}")
return outsigfile
def create_temp_pat_files(outdir, files):
temp_pat_files = []
for i, f in enumerate(files):
new = os.path.join(outdir, f"{i}.pat")
shutil.copy(f, new)
temp_pat_files.append(new)
return temp_pat_files
def run(args, cwd=os.curdir, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
logger.debug("running %s", " ".join(args))
p = subprocess.Popen(args, cwd=cwd, stdout=stdout, stderr=stderr)
# wait
p.communicate()
def process_exc_file(exc_file):
"""
process exclusion file
"""
with open(exc_file, "rb") as f:
lines = f.read().splitlines(keepends=True)
include_functions = (
"__CxxFrameHandler3",
"__strdup",
"mainCRTStartup",
"_mainCRTStartup",
)
new_lines = []
for line in lines:
line = line.decode("utf-8")
if line.startswith(include_functions):
line = "+" + line
new_lines.append(line.encode("utf-8"))
else:
# TODO
# __iswblank_l 00 0000 8BFF558BEC66837D08096A407503585DC3FF7508E8........59595DC3......
# _iswblank 00 0000 8BFF558BEC66837D08096A407503585DC3FF7508E8........59595DC3......
# TODO
# __Toupper 30 7B17 558BEC518B450C5385C056750D8B35........A1........EB058B308B400485
# __Toupper_lk 30 7B17 558BEC518B450C5385C056750D8B35........A1........EB058B308B400485
new_lines.append(line.encode("utf-8"))
# remove header
with open(exc_file, "wb") as f:
f.writelines(new_lines[5:])
def zipsig(outsigfile, save_unzipped_file=True):
if save_unzipped_file:
unzipped_file = f"{outsigfile}.bu"
logger.info(f"saving unzipped file as {unzipped_file}")
shutil.copy(outsigfile, unzipped_file)
args = [PATH_ZIPSIG, outsigfile]
run(args)
def main(argv=None):
if argv is None:
argv = sys.argv[1:]
parser = argparse.ArgumentParser(epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
parser.add_argument(
"outdir",
type=str,
help="path to output directory",
)
parser.add_argument("-e", "--exclude", nargs="*", help="exclude paths that contain exclusion string")
parser.add_argument("-ep", "--exclude_pats", nargs="*", help="exclude pat files that contain exclusion string")
parser.add_argument("-ip", "--include_pats", nargs="*", help="include pat files that contain inclusion string")
group = parser.add_mutually_exclusive_group(required=True)
group.add_argument("--tarballs-root", help="data path to root of tarballs, use with -e and -i")
group.add_argument("--patfiles", nargs="+", help="paths to input .pat files")
parser.add_argument(
"-s", "--sigfile", required=True, help="name of output .sig file, e.g. flare_msvc_rtf_32_64.sig"
)
parser.add_argument(
"-N",
"--no-act",
action="store_true",
help="don't make any changes, use with --debug to view selected .pat files",
)
parser.add_argument("-n", "--signame", default=SIGNAME_DEFAULT, help="signature file title (used by IDA)")
parser.add_argument("-lr", "--reject_functions", action="append", help="reject functions matching the pattern")
parser.add_argument("-li", "--ignore_functions", action="append", help="ignore functions when comparing leaves")
# logging modes
parser.add_argument("-d", "--debug", action="store_true", help="enable debugging output on STDERR")
parser.add_argument("-q", "--quiet", action="store_true", help="disable all output but errors")
args = parser.parse_args(args=argv)
if args.quiet:
logging.basicConfig(level=logging.WARNING)
logging.getLogger().setLevel(logging.WARNING)
elif args.debug:
logging.basicConfig(level=logging.DEBUG)
logging.getLogger().setLevel(logging.DEBUG)
else:
logging.basicConfig(level=logging.INFO)
logging.getLogger().setLevel(logging.INFO)
if args.patfiles and (args.exclude or args.exclude_pats or args.include_pats or args.no_act):
logger.error("-e, -ep, -ip, -N arguments can only be used with --tarballs-root")
return -1
if args.no_act:
for tarball_path in collect_tarball_paths(args.tarballs_root, exclude=args.exclude):
logger.debug("extracting from %s", tarball_path)
extract_pat_files(
args.outdir, tarball_path, exclude=args.exclude_pats, include=args.include_pats, write_files=False
)
return 0
if os.path.exists(args.outdir):
logger.error("%s already exists", args.outdir)
return -1
else:
logger.info("creating output directory %s", args.outdir)
os.mkdir(args.outdir)
if args.signame == SIGNAME_DEFAULT:
args.signame = args.sigfile.replace("-", " ").replace("_", " ").replace(".sig", "").upper()
if args.tarballs_root:
logger.info("collecting tarball paths")
for tarball_path in collect_tarball_paths(args.tarballs_root, exclude=args.exclude):
logger.debug("extracting from %s", tarball_path)
extract_pat_files(args.outdir, tarball_path, exclude=args.exclude_pats, include=args.include_pats)
# rely on wildcard extension after copying files to outdir
patfiles = [os.path.join(args.outdir, "*.pat")]
else:
logger.info("using provided .pat files")
patfiles = args.patfiles
logger.info("creating sig file %s", args.sigfile)
try:
sigpath = create_sig_file_from_pats(
args.outdir, args.sigfile, patfiles, args.signame, args.reject_functions, args.ignore_functions
)
except ValueError as e:
logger.error(str(e))
return -1
logger.info("zipping sig file %s", sigpath)
zipsig(sigpath, save_unzipped_file=True)
return 0
if __name__ == "__main__":
sys.exit(main())
| williballenthin/siglib | 12 | function identification signatures | Python | williballenthin | Willi Ballenthin | HexRaysSA |
x64-windows-static-v140.cmake | CMake | set(VCPKG_TARGET_ARCHITECTURE x64)
set(VCPKG_CRT_LINKAGE static)
set(VCPKG_LIBRARY_LINKAGE static)
set(VCPKG_PLATFORM_TOOLSET v140) | williballenthin/siglib | 12 | function identification signatures | Python | williballenthin | Willi Ballenthin | HexRaysSA |
x64-windows-static-v141.cmake | CMake | set(VCPKG_TARGET_ARCHITECTURE x64)
set(VCPKG_CRT_LINKAGE static)
set(VCPKG_LIBRARY_LINKAGE static)
set(VCPKG_PLATFORM_TOOLSET v141) | williballenthin/siglib | 12 | function identification signatures | Python | williballenthin | Willi Ballenthin | HexRaysSA |
x64-windows-static-v142.cmake | CMake | set(VCPKG_TARGET_ARCHITECTURE x64)
set(VCPKG_CRT_LINKAGE static)
set(VCPKG_LIBRARY_LINKAGE static)
set(VCPKG_PLATFORM_TOOLSET v142) | williballenthin/siglib | 12 | function identification signatures | Python | williballenthin | Willi Ballenthin | HexRaysSA |
x86-windows-static-v140.cmake | CMake | set(VCPKG_TARGET_ARCHITECTURE x86)
set(VCPKG_CRT_LINKAGE static)
set(VCPKG_LIBRARY_LINKAGE static)
set(VCPKG_PLATFORM_TOOLSET v140)
| williballenthin/siglib | 12 | function identification signatures | Python | williballenthin | Willi Ballenthin | HexRaysSA |
x86-windows-static-v141.cmake | CMake | set(VCPKG_TARGET_ARCHITECTURE x86)
set(VCPKG_CRT_LINKAGE static)
set(VCPKG_LIBRARY_LINKAGE static)
set(VCPKG_PLATFORM_TOOLSET v141)
| williballenthin/siglib | 12 | function identification signatures | Python | williballenthin | Willi Ballenthin | HexRaysSA |
x86-windows-static-v142.cmake | CMake | set(VCPKG_TARGET_ARCHITECTURE x86)
set(VCPKG_CRT_LINKAGE static)
set(VCPKG_LIBRARY_LINKAGE static)
set(VCPKG_PLATFORM_TOOLSET v142)
| williballenthin/siglib | 12 | function identification signatures | Python | williballenthin | Willi Ballenthin | HexRaysSA |
create-test-db.py | Python | import sqlite3
import os
# Database file name
DB_FILE = 'succulents_test.db'
def create_test_database():
"""Create a test database with sample succulent data"""
# Remove existing database if it exists
if os.path.exists(DB_FILE):
os.remove(DB_FILE)
print(f"Removed existing database: {DB_FILE}")
# Connect to the database
conn = sqlite3.connect(DB_FILE)
conn.execute("PRAGMA foreign_keys = ON")
cursor = conn.cursor()
# Create tables
print("Creating tables...")
cursor.executescript('''
CREATE TABLE succulents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
image_url TEXT NOT NULL,
description TEXT NOT NULL
);
CREATE TABLE care_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
succulent_id INTEGER NOT NULL,
tag TEXT NOT NULL,
FOREIGN KEY (succulent_id) REFERENCES succulents (id)
);
''')
# Insert sample succulents
print("Inserting sample succulents...")
succulents = [
(
"Echeveria Elegans",
"/api/placeholder/400/320",
"Also known as Mexican Snowball, this rosette-forming succulent has pale blue-green leaves with pink-tinged edges."
),
(
"Haworthia Fasciata",
"/api/placeholder/400/320",
"Commonly called Zebra Plant, this small succulent has distinctive white ridges on its dark green leaves."
),
(
"Sedum Morganianum",
"/api/placeholder/400/320",
"Known as Burro's Tail or Donkey's Tail, this succulent has trailing stems with plump, tear-shaped leaves."
),
(
"Crassula Ovata",
"/api/placeholder/400/320",
"The Jade Plant features thick, woody stems and oval-shaped leaves that store water, making it drought-resistant."
),
(
"Aloe Vera",
"/api/placeholder/400/320",
"A medicinal plant with thick, fleshy leaves containing a gel-like substance used for healing burns and skin conditions."
),
(
"Kalanchoe Blossfeldiana",
"/api/placeholder/400/320",
"A flowering succulent with scalloped-edged leaves and clusters of small, brightly colored flowers."
),
(
"Sempervivum Tectorum",
"/api/placeholder/400/320",
"Known as Hens and Chicks, this succulent forms rosettes that produce offsets around the mother plant."
),
(
"Aeonium Arboreum",
"/api/placeholder/400/320",
"The Tree Aeonium has spoon-shaped leaves arranged in rosettes at the ends of branching stems."
),
(
"Euphorbia Tirucalli",
"/api/placeholder/400/320",
"Commonly called Pencil Cactus or Firesticks, this succulent has pencil-thin, cylindrical stems."
),
(
"Gasteria Bicolor",
"/api/placeholder/400/320",
"Known for its thick, tongue-shaped leaves with white spots, making it an attractive houseplant."
),
(
"Lithops",
"/api/placeholder/400/320",
"Often called Living Stones, these small succulents have evolved to resemble pebbles as a form of camouflage."
),
(
"Senecio Rowleyanus",
"/api/placeholder/400/320",
"String of Pearls features trailing stems with small, spherical leaves resembling beads or pearls."
),
(
"Ceropegia Woodii",
"/api/placeholder/400/320",
"String of Hearts has heart-shaped leaves on thin, trailing stems, making it perfect for hanging baskets."
),
(
"Portulacaria Afra",
"/api/placeholder/400/320",
"Elephant Bush has small, round leaves on reddish-brown stems and is often used in bonsai."
),
(
"Cotyledon Orbiculata",
"/api/placeholder/400/320",
"Pig's Ear has thick, oval leaves with a powdery coating that gives them a silvery-blue appearance."
)
]
cursor.executemany(
"INSERT INTO succulents (name, image_url, description) VALUES (?, ?, ?)",
succulents
)
# Insert care tags
print("Inserting care tags...")
care_tags = [
# Echeveria Elegans
(1, "Low water"),
(1, "Full sun"),
(1, "Well-draining soil"),
(1, "Frost sensitive"),
# Haworthia Fasciata
(2, "Partial shade"),
(2, "Low water"),
(2, "Indoor friendly"),
(2, "Indirect light"),
# Sedum Morganianum
(3, "Bright indirect light"),
(3, "Minimal water"),
(3, "Hanging baskets"),
(3, "Fragile stems"),
# Crassula Ovata
(4, "Bright light"),
(4, "Low water"),
(4, "Good for beginners"),
(4, "Bonsai potential"),
# Aloe Vera
(5, "Bright indirect light"),
(5, "Moderate water"),
(5, "Medicinal"),
(5, "Propagates easily"),
# Kalanchoe Blossfeldiana
(6, "Bright light"),
(6, "Low water"),
(6, "Flowering"),
(6, "Frost sensitive"),
# Sempervivum Tectorum
(7, "Full sun"),
(7, "Low water"),
(7, "Cold hardy"),
(7, "Ground cover"),
# Aeonium Arboreum
(8, "Partial sun"),
(8, "Moderate water"),
(8, "Summer dormant"),
(8, "Branching"),
# Euphorbia Tirucalli
(9, "Full sun"),
(9, "Minimal water"),
(9, "Toxic sap"),
(9, "Fast growing"),
# Gasteria Bicolor
(10, "Filtered light"),
(10, "Low water"),
(10, "Indoor friendly"),
(10, "Slow growing"),
# Lithops
(11, "Bright light"),
(11, "Very little water"),
(11, "Gritty soil"),
(11, "Unique appearance"),
# Senecio Rowleyanus
(12, "Bright indirect light"),
(12, "Sparse watering"),
(12, "Hanging plant"),
(12, "Trailing stems"),
# Ceropegia Woodii
(13, "Medium light"),
(13, "Allow to dry out"),
(13, "Trailing"),
(13, "Decorative"),
# Portulacaria Afra
(14, "Full to partial sun"),
(14, "Low water"),
(14, "Bonsai suitable"),
(14, "Fast growing"),
# Cotyledon Orbiculata
(15, "Full sun"),
(15, "Low water"),
(15, "Drought tolerant"),
(15, "Powdery leaves")
]
cursor.executemany(
"INSERT INTO care_tags (succulent_id, tag) VALUES (?, ?)",
care_tags
)
# Commit changes and close connection
conn.commit()
conn.close()
print(f"Test database '{DB_FILE}' created successfully with 15 succulents and their care tags.")
print("You can now use this database for testing the FastAPI application.")
if __name__ == "__main__":
create_test_database()
| willingc/beach-garden | 0 | succulents for us | Python | willingc | Carol Willing | Willing Consulting |
database-check.py | Python | import sqlite3
import os
import json
# Database file name
DB_FILE = 'succulents_test.db'
def check_database():
"""Check the contents of the test database and display them"""
if not os.path.exists(DB_FILE):
print(f"Error: Database file '{DB_FILE}' not found.")
print("Please run create_test_db.py first to generate the test database.")
return
conn = sqlite3.connect(DB_FILE)
conn.row_factory = sqlite3.Row
cursor = conn.cursor()
# Get count of succulents
cursor.execute("SELECT COUNT(*) FROM succulents")
succulent_count = cursor.fetchone()[0]
# Get count of care tags
cursor.execute("SELECT COUNT(*) FROM care_tags")
tag_count = cursor.fetchone()[0]
print(f"Database '{DB_FILE}' contains {succulent_count} succulents and {tag_count} care tags.")
# Get all succulents with their care tags
cursor.execute("""
SELECT s.id, s.name, s.image_url, s.description
FROM succulents s
ORDER BY s.name
""")
succulents = []
for row in cursor.fetchall():
# Get care tags for this succulent
cursor.execute(
"SELECT tag FROM care_tags WHERE succulent_id = ? ORDER BY tag",
(row['id'],)
)
care_tags = [tag['tag'] for tag in cursor.fetchall()]
succulents.append({
'id': row['id'],
'name': row['name'],
'image': row['image_url'],
'description': row['description'],
'care': care_tags
})
# Print the first succulent as a sample
print("\nSample succulent data:")
print(json.dumps(succulents[0], indent=2))
# Print all succulents names
print("\nAll succulents in the database:")
for i, succulent in enumerate(succulents, 1):
print(f"{i}. {succulent['name']} ({len(succulent['care'])} care tags)")
conn.close()
if __name__ == "__main__":
check_database()
| willingc/beach-garden | 0 | succulents for us | Python | willingc | Carol Willing | Willing Consulting |
main.py | Python | from fastapi import FastAPI, Query, HTTPException, Depends
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.requests import Request
import sqlite3
import os
from typing import List, Optional
from pydantic import BaseModel
import uvicorn
# Create FastAPI app
app = FastAPI(title="Succulent Collection API")
# Set up templates
templates = Jinja2Templates(directory="templates")
# Database configuration - Using the test database
DATABASE = 'succulents_test.db'
# Pydantic models for API responses
class CareTag(BaseModel):
tag: str
class Succulent(BaseModel):
id: int
name: str
image: str
description: str
care: List[str]
# Database helper functions
def get_db_connection():
"""Create a database connection"""
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
return conn
# Mount static files
app.mount("/static", StaticFiles(directory="static"), name="static")
# API Routes
@app.get("/api/succulents", response_model=List[Succulent])
async def get_succulents(search: Optional[str] = Query(None, description="Search term for filtering succulents")):
"""
Get all succulents or search by name, description, or care tag
"""
if not os.path.exists(DATABASE):
raise HTTPException(status_code=500, detail=f"Database '{DATABASE}' not found. Run create_test_db.py first.")
conn = get_db_connection()
cursor = conn.cursor()
try:
if search:
search_term = f"%{search.lower()}%"
# Search for matching succulents with their care tags
query = """
SELECT DISTINCT s.id, s.name, s.image_url, s.description
FROM succulents s
LEFT JOIN care_tags c ON s.id = c.succulent_id
WHERE LOWER(s.name) LIKE ?
OR LOWER(s.description) LIKE ?
OR LOWER(c.tag) LIKE ?
"""
cursor.execute(query, (search_term, search_term, search_term))
else:
cursor.execute("SELECT id, name, image_url, description FROM succulents")
succulents_data = []
for row in cursor.fetchall():
# For each succulent, get its care tags
cursor.execute("SELECT tag FROM care_tags WHERE succulent_id = ?", (row['id'],))
care_tags = [tag['tag'] for tag in cursor.fetchall()]
succulents_data.append({
'id': row['id'],
'name': row['name'],
'image': row['image_url'],
'description': row['description'],
'care': care_tags
})
return succulents_data
finally:
conn.close()
@app.get("/", response_class=HTMLResponse)
async def get_home_page(request: Request):
"""Serve the home page with the succulent gallery"""
return templates.TemplateResponse("index.html", {"request": request})
# Status endpoint to check database connection
@app.get("/api/status")
async def get_status():
"""Check if the database is available and return basic statistics"""
if not os.path.exists(DATABASE):
return {
"status": "error",
"message": f"Database '{DATABASE}' not found. Run create_test_db.py first."
}
try:
conn = get_db_connection()
cursor = conn.cursor()
# Get counts
cursor.execute("SELECT COUNT(*) FROM succulents")
succulent_count = cursor.fetchone()[0]
cursor.execute("SELECT COUNT(*) FROM care_tags")
tag_count = cursor.fetchone()[0]
conn.close()
return {
"status": "ok",
"database": DATABASE,
"succulent_count": succulent_count,
"care_tag_count": tag_count
}
except Exception as e:
return {
"status": "error",
"message": str(e)
}
# For development server
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
| willingc/beach-garden | 0 | succulents for us | Python | willingc | Carol Willing | Willing Consulting |
schema-sql.sql | SQL | DROP TABLE IF EXISTS succulents;
DROP TABLE IF EXISTS care_tags;
CREATE TABLE succulents (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
image_url TEXT NOT NULL,
description TEXT NOT NULL
);
CREATE TABLE care_tags (
id INTEGER PRIMARY KEY AUTOINCREMENT,
succulent_id INTEGER NOT NULL,
tag TEXT NOT NULL,
FOREIGN KEY (succulent_id) REFERENCES succulents (id)
);
| willingc/beach-garden | 0 | succulents for us | Python | willingc | Carol Willing | Willing Consulting |
succulent-gallery-fastapi.py | Python | from fastapi import FastAPI, Query, HTTPException, Depends
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from fastapi.requests import Request
import sqlite3
import os
from typing import List, Optional
from pydantic import BaseModel
import uvicorn
# Create FastAPI app
app = FastAPI(title="Succulent Collection API")
# Set up templates
templates = Jinja2Templates(directory="templates")
# Database configuration
DATABASE = 'succulents.db'
# Pydantic models for API responses
class CareTag(BaseModel):
tag: str
class Succulent(BaseModel):
id: int
name: str
image: str
description: str
care: List[str]
# Database helper functions
def get_db_connection():
"""Create a database connection"""
conn = sqlite3.connect(DATABASE)
conn.row_factory = sqlite3.Row
return conn
def init_db():
"""Initialize the database with the schema"""
if not os.path.exists(DATABASE):
conn = get_db_connection()
with open('schema.sql', 'r') as f:
conn.executescript(f.read())
# Add sample data
populate_sample_data(conn)
conn.close()
def populate_sample_data(conn):
"""Add sample succulents and care tags to the database"""
cursor = conn.cursor()
# Check if data already exists
cursor.execute("SELECT COUNT(*) FROM succulents")
if cursor.fetchone()[0] > 0:
return
# Sample data
sample_data = [
(
"Echeveria Elegans",
"/api/placeholder/400/320",
"Also known as Mexican Snowball, this rosette-forming succulent has pale blue-green leaves with pink-tinged edges."
),
(
"Haworthia Fasciata",
"/api/placeholder/400/320",
"Commonly called Zebra Plant, this small succulent has distinctive white ridges on its dark green leaves."
),
(
"Sedum Morganianum",
"/api/placeholder/400/320",
"Known as Burro's Tail or Donkey's Tail, this succulent has trailing stems with plump, tear-shaped leaves."
),
(
"Crassula Ovata",
"/api/placeholder/400/320",
"The Jade Plant features thick, woody stems and oval-shaped leaves that store water, making it drought-resistant."
),
(
"Aloe Vera",
"/api/placeholder/400/320",
"A medicinal plant with thick, fleshy leaves containing a gel-like substance used for healing burns and skin conditions."
),
(
"Kalanchoe Blossfeldiana",
"/api/placeholder/400/320",
"A flowering succulent with scalloped-edged leaves and clusters of small, brightly colored flowers."
)
]
cursor.executemany(
"INSERT INTO succulents (name, image_url, description) VALUES (?, ?, ?)",
sample_data
)
# Sample care tags
care_data = [
(1, "Low water"),
(1, "Full sun"),
(1, "Well-draining soil"),
(2, "Partial shade"),
(2, "Low water"),
(2, "Indoor friendly"),
(3, "Bright indirect light"),
(3, "Minimal water"),
(3, "Hanging baskets"),
(4, "Bright light"),
(4, "Low water"),
(4, "Good for beginners"),
(5, "Bright indirect light"),
(5, "Moderate water"),
(5, "Medicinal"),
(6, "Bright light"),
(6, "Low water"),
(6, "Flowering")
]
cursor.executemany(
"INSERT INTO care_tags (succulent_id, tag) VALUES (?, ?)",
care_data
)
conn.commit()
# Initialize the database on startup
init_db()
# Mount static files
app.mount("/static", StaticFiles(directory="static"), name="static")
# API Routes
@app.get("/api/succulents", response_model=List[Succulent])
async def get_succulents(search: Optional[str] = Query(None, description="Search term for filtering succulents")):
"""
Get all succulents or search by name, description, or care tag
"""
conn = get_db_connection()
cursor = conn.cursor()
try:
if search:
search_term = f"%{search.lower()}%"
# Search for matching succulents with their care tags
query = """
SELECT DISTINCT s.id, s.name, s.image_url, s.description
FROM succulents s
LEFT JOIN care_tags c ON s.id = c.succulent_id
WHERE LOWER(s.name) LIKE ?
OR LOWER(s.description) LIKE ?
OR LOWER(c.tag) LIKE ?
"""
cursor.execute(query, (search_term, search_term, search_term))
else:
cursor.execute("SELECT id, name, image_url, description FROM succulents")
succulents_data = []
for row in cursor.fetchall():
# For each succulent, get its care tags
cursor.execute("SELECT tag FROM care_tags WHERE succulent_id = ?", (row['id'],))
care_tags = [tag['tag'] for tag in cursor.fetchall()]
succulents_data.append({
'id': row['id'],
'name': row['name'],
'image': row['image_url'],
'description': row['description'],
'care': care_tags
})
return succulents_data
finally:
conn.close()
@app.get("/", response_class=HTMLResponse)
async def get_home_page(request: Request):
"""Serve the home page with the succulent gallery"""
return templates.TemplateResponse("index.html", {"request": request})
# For development server
if __name__ == "__main__":
uvicorn.run("main:app", host="0.0.0.0", port=8000, reload=True)
| willingc/beach-garden | 0 | succulents for us | Python | willingc | Carol Willing | Willing Consulting |
templates/index.html | HTML | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Succulent Collection</title>
<style>
:root {
--primary-color: #4a7c59;
--secondary-color: #7fa88b;
--background-color: #f8f9fa;
--card-bg: #ffffff;
--text-color: #333333;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
}
body {
background-color: var(--background-color);
color: var(--text-color);
line-height: 1.6;
padding: 20px;
}
header {
text-align: center;
margin-bottom: 2rem;
padding: 1rem;
background-color: var(--primary-color);
color: white;
border-radius: 8px;
}
.search-container {
display: flex;
justify-content: center;
margin-bottom: 2rem;
}
#search-input {
padding: 10px 15px;
border: 1px solid #ddd;
border-radius: 4px;
width: 100%;
max-width: 400px;
font-size: 16px;
}
.gallery {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
grid-gap: 20px;
margin: 0 auto;
max-width: 1200px;
}
.card {
background-color: var(--card-bg);
border-radius: 8px;
overflow: hidden;
box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
}
.card:hover {
transform: translateY(-5px);
}
.card-image {
height: 200px;
overflow: hidden;
}
.card-image img {
width: 100%;
height: 100%;
object-fit: cover;
transition: transform 0.3s ease;
}
.card:hover .card-image img {
transform: scale(1.05);
}
.card-content {
padding: 20px;
}
.card-title {
font-size: 1.5rem;
color: var(--primary-color);
margin-bottom: 10px;
}
.card-description {
color: var(--text-color);
font-size: 0.95rem;
}
.care-info {
margin-top: 10px;
display: flex;
flex-wrap: wrap;
gap: 10px;
}
.care-tag {
background-color: var(--secondary-color);
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 0.8rem;
}
footer {
text-align: center;
margin-top: 3rem;
padding: 1rem;
color: var(--text-color);
font-size: 0.9rem;
}
.loading-spinner {
display: none;
text-align: center;
grid-column: 1/-1;
padding: 20px;
}
.loading-spinner.active {
display: block;
}
@media (max-width: 768px) {
.gallery {
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}
}
@media (max-width: 480px) {
.gallery {
grid-template-columns: 1fr;
}
}
</style>
</head>
<body>
<header>
<h1>Beautiful Succulent Collection</h1>
<p>Discover our diverse collection of stunning succulents</p>
</header>
<div class="search-container">
<input type="text" id="search-input" placeholder="Search succulents...">
</div>
<div class="gallery" id="succulent-gallery">
<div class="loading-spinner active" id="loading-spinner">
Loading succulents...
</div>
<!-- Succulent cards will be populated here -->
</div>
<footer>
<p>© 2025 Succulent Collection Gallery. All images are placeholders.</p>
</footer>
<script>
// Function to fetch succulents from API
async function fetchSucculents(searchTerm = "") {
const loadingSpinner = document.getElementById('loading-spinner');
loadingSpinner.classList.add('active');
try {
const url = searchTerm
? `/api/succulents?search=${encodeURIComponent(searchTerm)}`
: '/api/succulents';
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to fetch data: ${response.status}`);
}
const succulents = await response.json();
renderSucculents(succulents);
} catch (error) {
console.error('Error fetching succulents:', error);
const gallery = document.getElementById('succulent-gallery');
gallery.innerHTML = `
<p style="text-align: center; grid-column: 1/-1; color: red;">
Failed to load succulents. Please try again later.
</p>
`;
} finally {
loadingSpinner.classList.remove('active');
}
}
// Function to render succulent cards
function renderSucculents(succulentsArray) {
const gallery = document.getElementById('succulent-gallery');
gallery.innerHTML = '';
if (succulentsArray.length === 0) {
gallery.innerHTML = '<p style="text-align: center; grid-column: 1/-1;">No succulents found matching your search.</p>';
return;
}
succulentsArray.forEach(succulent => {
const card = document.createElement('div');
card.className = 'card';
const careTags = succulent.care.map(care =>
`<span class="care-tag">${care}</span>`
).join('');
card.innerHTML = `
<div class="card-image">
<img src="${succulent.image}" alt="${succulent.name}">
</div>
<div class="card-content">
<h2 class="card-title">${succulent.name}</h2>
<p class="card-description">${succulent.description}</p>
<div class="care-info">
${careTags}
</div>
</div>
`;
gallery.appendChild(card);
});
}
// Search functionality with debounce
let debounceTimeout;
document.getElementById('search-input').addEventListener('input', function(e) {
const searchTerm = e.target.value.trim();
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(() => {
fetchSucculents(searchTerm);
}, 300);
});
// Initial load
document.addEventListener('DOMContentLoaded', () => {
fetchSucculents();
});
</script>
</body>
</html>
| willingc/beach-garden | 0 | succulents for us | Python | willingc | Carol Willing | Willing Consulting |
noxfile.py | Python | from __future__ import annotations
import shutil
from pathlib import Path
import nox
DIR = Path(__file__).parent.resolve()
PROJECT = nox.project.load_toml()
nox.needs_version = ">=2025.2.9"
nox.options.default_venv_backend = "uv|virtualenv"
@nox.session
def lint(session: nox.Session) -> None:
"""Run the linter."""
session.install("pre-commit")
session.run(
"python",
"-m",
"pre_commit",
"run",
"--all-files",
"--show-diff-on-failure",
*session.posargs,
)
@nox.session
def pylint(session: nox.Session) -> None:
"""Run Pylint."""
# This needs to be installed into the package environment, and is slower
# than a pre-commit check
session.install("-e.", "pylint>=3.2")
# Only fail on errors, not warnings
session.run(
"python",
"-m",
"pylint",
"--fail-under=0",
"src/discuss_nutshell",
*session.posargs,
)
@nox.session
def tests(session: nox.Session) -> None:
"""Run the unit and regular tests."""
test_deps = nox.project.dependency_groups(PROJECT, "test")
session.install("-e.", *test_deps)
session.run("python", "-m", "pytest", *session.posargs)
@nox.session(reuse_venv=True, default=False)
def docs(session: nox.Session) -> None:
"""Make or serve the docs. Pass --non-interactive to avoid serving."""
doc_deps = nox.project.dependency_groups(PROJECT, "docs")
session.install("-e.", *doc_deps)
if session.interactive:
session.run("python", "-m", "mkdocs", "serve", "--clean", *session.posargs)
else:
session.run("python", "-m", "mkdocs", "build", "--clean", *session.posargs)
@nox.session(default=False)
def build(session: nox.Session) -> None:
"""
Build an SDist and wheel.
"""
build_path = DIR.joinpath("build")
if build_path.exists():
shutil.rmtree(build_path)
session.install("build")
session.run("python", "-m", "build")
| willingc/discuss-nutshell | 0 | Understand long Discourse threads | Python | willingc | Carol Willing | Willing Consulting |
src/discuss_nutshell/__init__.py | Python | """Discuss Nutshell package."""
from discuss_nutshell._version import __version__
__all__ = ["__version__"]
| willingc/discuss-nutshell | 0 | Understand long Discourse threads | Python | willingc | Carol Willing | Willing Consulting |
src/discuss_nutshell/cli.py | Python | """Command-line interface for discuss-nutshell."""
from pathlib import Path
import typer
from google import genai
from discuss_nutshell.data_loader import load_topic
from discuss_nutshell.data_logger import init_db, log_interaction
from discuss_nutshell.visualize import create_visualization_app
app = typer.Typer()
current_path = Path.cwd()
data_path = current_path / "data"
DB_FILE = data_path / "posts_qa_logs.db"
def extract_text_from_file(file_path: str | Path) -> str:
"""Extract text from a file.
Parameters
----------
file_path : str | Path
Path to the file to read.
Returns
-------
str
The contents of the file as a string.
"""
with Path(file_path).open(encoding="utf-8") as f:
return f.read()
def query_file(file: str | Path, query: str, model: str = "gemini-2.5-flash") -> str:
"""Query the file and return the response.
Parameters
----------
file : str | Path
Path to the file to query.
query : str
The question or query about the file content.
model : str, optional
The Gemini model to use. Default is "gemini-2.5-flash".
Returns
-------
str
The response from the Gemini model.
Notes
-----
Uses the Gemini API to generate responses. All interactions
are logged to the SQLite database.
"""
file_path = Path(file)
if not file_path.exists():
msg = f"File not found: {file}"
raise FileNotFoundError(msg)
filename = file_path.name
file_text = extract_text_from_file(file_path)
context = [file_text, query]
client = genai.Client()
response = client.models.generate_content(
model=model,
contents=context,
)
response_text = str(response.text)
log_interaction(
filename=filename,
query=query,
full_context=context[0] + context[1],
response=response_text,
)
return response_text
@app.command()
def query(file: str, query: str, model: str = "gemini-2.5-flash") -> None:
"""Query a file."""
response = query_file(file, query, model)
print(response)
@app.command()
def visualize(json_file: str = "104906_all_posts.json") -> None:
"""Visualize Discourse posts as cards."""
app = create_visualization_app(json_file)
app.launch()
@app.command()
def load(
topic_id: int, output: str = "data", process: bool = False, verbose: bool = False
) -> None:
"""Load a Discourse topic."""
load_topic(topic_id, output, process, verbose)
def main() -> None:
"""Discuss Nutshell CLI."""
init_db()
app()
if __name__ == "__main__":
main()
| willingc/discuss-nutshell | 0 | Understand long Discourse threads | Python | willingc | Carol Willing | Willing Consulting |
src/discuss_nutshell/data_loader.py | Python | """Load data from Discourse"""
import os
from pathlib import Path
import requests
from discuss_nutshell.preprocessor import (
clean_cooked_posts,
create_dataframe,
drop_columns,
extract_posts,
format_created_at,
read_json,
write_post_files,
write_posts_json,
write_posts_txt,
)
from discuss_nutshell.utils import display_dataframe
token = os.environ.get("DISCOURSE_API_KEY")
headers = {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
REQUEST_TIMEOUT = 30 # seconds
current_path = Path.cwd()
data_path = current_path / "data"
def load_topic(topic, filename):
"""Get a topic from Discourse API and save to JSON file.
Parameters
----------
topic : int
The ID of the topic to retrieve.
filename : Path
Path where the JSON file should be saved.
Notes
-----
The topic_id parameter is currently hardcoded to 104906 in the function body.
"""
response = requests.get(
f"https://discuss.python.org/t/{topic}.json?print=true",
headers=headers,
timeout=REQUEST_TIMEOUT,
)
print(response.status_code, response.headers["Content-Type"])
with Path(filename).open("w", encoding="utf-8") as f:
f.write(response.text)
if __name__ == "__main__":
TOPIC_ID = 104906
current_path = Path.cwd()
data_path = current_path / "data"
file_path = data_path / f"topic_{TOPIC_ID}.json"
# Write a json file for a topic with all the posts
load_topic(TOPIC_ID, file_path)
data = read_json(file_path)
posts = extract_posts(data)
df = create_dataframe(posts)
df = drop_columns(df)
df = format_created_at(df)
df = clean_cooked_posts(df)
display_dataframe(df)
write_post_files(df, data_path)
write_posts_json(df, TOPIC_ID, data_path)
write_posts_txt(df, data_path)
| willingc/discuss-nutshell | 0 | Understand long Discourse threads | Python | willingc | Carol Willing | Willing Consulting |
src/discuss_nutshell/data_logger.py | Python | """Log data to SQLite database."""
import sqlite3
import uuid
from datetime import UTC, datetime
from pathlib import Path
current_path = Path.cwd()
data_path = current_path / "data"
DB_FILE = data_path / "posts_qa_logs.db"
def init_db() -> None:
"""Initialize the SQLite database with interactions table.
Notes
-----
Creates a table named 'interactions' if it doesn't exist with columns:
id, timestamp, post_name, query, full_context, and response.
"""
conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS interactions (
id TEXT PRIMARY KEY,
timestamp TEXT,
post_name TEXT,
query TEXT,
full_context TEXT,
response TEXT)""")
conn.commit()
conn.close()
def log_interaction(
filename: str, query: str, full_context: str, response: str
) -> None:
"""Log the interaction to SQLite database.
Parameters
----------
filename : str
Name of the file that was queried.
query : str
The user's query/question.
full_context : str
The full context (file content + query) sent to the model.
response : str
The response from the model.
Notes
-----
Generates a unique UUID for each interaction and records the current
timestamp in UTC.
"""
conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
interaction_id = str(uuid.uuid4())
timestamp = datetime.now(UTC).isoformat()
c.execute(
"INSERT INTO interactions VALUES (?, ?, ?, ?, ?, ?)",
(interaction_id, timestamp, filename, query, full_context, response),
)
conn.commit()
conn.close()
| willingc/discuss-nutshell | 0 | Understand long Discourse threads | Python | willingc | Carol Willing | Willing Consulting |
src/discuss_nutshell/launch_app.py | Python | """Get a file and query it using Gemini API and Gradio UI."""
import sqlite3
import uuid
from datetime import UTC, datetime
from pathlib import Path
import gradio as gr
from google import genai
current_path = Path.cwd()
data_path = current_path / "data"
DB_FILE = data_path / "posts_qa_logs.db"
def init_db() -> None:
"""Initialize the SQLite database with interactions table.
Notes
-----
Creates a table named 'interactions' if it doesn't exist with columns:
id, timestamp, post_name, query, full_context, and response.
"""
conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
c.execute("""CREATE TABLE IF NOT EXISTS interactions (
id TEXT PRIMARY KEY,
timestamp TEXT,
post_name TEXT,
query TEXT,
full_context TEXT,
response TEXT)""")
conn.commit()
conn.close()
init_db()
# initialize the Gemini client
client = genai.Client()
def extract_text_from_file(file_path: str | Path) -> str:
"""Extract text from a file.
Parameters
----------
file_path : str | Path
Path to the file to read.
Returns
-------
str
The contents of the file as a string.
"""
with Path(file_path).open(encoding="utf-8") as f:
return f.read()
def log_interaction(
filename: str, query: str, full_context: str, response: str
) -> None:
"""Log the interaction to SQLite database.
Parameters
----------
filename : str
Name of the file that was queried.
query : str
The user's query/question.
full_context : str
The full context (file content + query) sent to the model.
response : str
The response from the model.
Notes
-----
Generates a unique UUID for each interaction and records the current
timestamp in UTC.
"""
conn = sqlite3.connect(DB_FILE)
c = conn.cursor()
interaction_id = str(uuid.uuid4())
timestamp = datetime.now(UTC).isoformat()
c.execute(
"INSERT INTO interactions VALUES (?, ?, ?, ?, ?, ?)",
(interaction_id, timestamp, filename, query, full_context, response),
)
conn.commit()
conn.close()
def query_file(file: str | None, query: str) -> str:
"""Query the file and return the response.
Parameters
----------
file : str | None
Path to the file to query. If None, returns an error message.
query : str
The question or query about the file content.
Returns
-------
str
The response from the Gemini model, or an error message if no file
is provided.
Notes
-----
Uses the Gemini 2.5 Flash model to generate responses. All interactions
are logged to the SQLite database.
"""
if file is None:
return "Please upload a file."
filename = Path(file).name
file_text = extract_text_from_file(file)
context = [file_text, query]
response = client.models.generate_content(
model="gemini-2.5-flash",
contents=context,
)
response_text = str(response.text)
log_interaction(
filename=filename,
query=query,
full_context=context[0] + context[1],
response=response_text,
)
return response_text
# Gradio interface setup
with gr.Blocks() as app:
file_upload = gr.File(label="Upload file", type="filepath")
query_input = gr.Textbox(label="Ask a question about the post")
query_button = gr.Button("Submit")
output = gr.Textbox(label="Answer", lines=10)
query_button.click(query_file, inputs=[file_upload, query_input], outputs=output)
if __name__ == "__main__":
app.launch()
| willingc/discuss-nutshell | 0 | Understand long Discourse threads | Python | willingc | Carol Willing | Willing Consulting |
src/discuss_nutshell/preprocessor.py | Python | import json
from pathlib import Path
from typing import Any
import pandas as pd
from discuss_nutshell.utils import clean_html, format_date
def read_json(file_path):
"""Read JSON file.
Parameters
----------
file_path : Path
Path to the JSON file to read.
Returns
-------
dict | list
Parsed JSON data.
"""
with Path(file_path).open(encoding="utf-8") as f:
return json.load(f)
def extract_posts(data: dict[str, Any]) -> list[dict[str, Any]]:
"""Extract individual posts from post stream.
Parameters
----------
data : dict[str, Any]
Discourse topic data containing post_stream.
Returns
-------
list[dict[str, Any]]
List of post dictionaries from the post_stream.
"""
return data["post_stream"]["posts"]
def write_json(data, file_path):
"""Write JSON file.
Parameters
----------
data : dict | list
Data to write as JSON.
file_path : Path
Path where the JSON file should be written.
"""
with Path(file_path).open("w", encoding="utf-8") as f:
json.dump(data, f)
def create_dataframe(posts):
"""Create dataframe from posts.
Parameters
----------
posts : list[dict[str, Any]]
List of post dictionaries.
Returns
-------
pd.DataFrame
DataFrame containing all posts.
"""
return pd.DataFrame(posts)
def drop_columns(df):
"""Drop columns from dataframe.
Parameters
----------
df : pd.DataFrame
DataFrame to process.
Returns
-------
pd.DataFrame
DataFrame with specified columns removed.
Notes
-----
Drops a predefined set of columns that are not needed for analysis.
Uses errors="ignore" to handle missing columns gracefully.
"""
return df.drop(
columns=[
"avatar_template",
"updated_at",
"reply_count",
"reply_to_post_number",
"quote_count",
"incoming_link_count",
"reads",
"readers_count",
"score",
"yours",
"primary_group_name",
"flair_name",
"flair_url",
"flair_bg_color",
"flair_color",
"flair_group_id",
"badges_granted",
"version",
"can_edit",
"can_delete",
"can_recover",
"can_see_hidden_post",
"can_wiki",
"link_counts",
"read",
"user_title",
"title_is_group",
"bookmarked",
"actions_summary",
"moderator",
"admin",
"staff",
"user_id",
"hidden",
"trust_level",
"deleted_at",
"user_deleted",
"edit_reason",
"can_view_edit_history",
"wiki",
"post_url",
"can_accept_answer",
"can_unaccept_answer",
"accepted_answer",
"topic_accepted_answer",
"can_vote",
"reply_to_user",
],
errors="ignore",
)
def format_created_at(df):
"""Format created at date.
Parameters
----------
df : pd.DataFrame
DataFrame with 'created_at' column containing ISO date strings.
Returns
-------
pd.DataFrame
DataFrame with 'created_at' column formatted to readable date strings.
"""
df["created_at"] = df["created_at"].apply(format_date)
return df
def clean_cooked_posts(df):
"""Clean post's HTML content.
Parameters
----------
df : pd.DataFrame
DataFrame with 'cooked' column containing HTML content.
Returns
-------
pd.DataFrame
DataFrame with new 'clean_cooked' column containing cleaned text.
"""
df["clean_cooked"] = df["cooked"].apply(clean_html)
return df
def write_post_files(df, output_path):
"""Write post files to output directory.
Parameters
----------
df : pd.DataFrame
DataFrame containing posts with columns: id, name, created_at,
post_number, and clean_cooked.
output_path : Path
Directory where individual post files should be written.
Notes
-----
Creates individual text files named 'post_{id}.txt' for each post
containing author, creation date, post number, and clean content.
"""
for _index, row in df.iterrows():
post_id = row["id"]
author = row["name"]
created_at = row["created_at"]
number = row["post_number"]
clean_content = row["clean_cooked"]
with Path(output_path / f"post_{post_id}.txt").open("w", encoding="utf-8") as f:
f.write(f"Author: {author}\n")
f.write(f"Created at: {created_at}\n")
f.write(f"Number: {number}\n")
f.write(f"Clean content: {clean_content}\n")
def write_posts_json(df: pd.DataFrame, topic_id: int, output_path: Path) -> None:
"""Write all posts from a topic to a single JSON file.
Parameters
----------
df : pd.DataFrame
DataFrame containing posts with columns: id, name, created_at,
post_number, and clean_cooked.
topic_id : int
ID of the topic.
output_path : Path
Directory where the JSON file should be written.
Notes
-----
Creates a single JSON file named '{topic_id}_all_posts.json' containing
all posts as a list of dictionaries.
"""
# Initialize an empty list to store post dictionaries
posts_list = []
# Iterate through DataFrame rows
for _index, row in df.iterrows():
# Extract data from each row
post_id = row["id"]
author = row["name"]
number = row["post_number"]
created_at = row["created_at"]
clean_content = row["clean_cooked"]
# Create a dictionary for each post
post_dict = {
"id": post_id,
"author": author,
"number": number,
"created_at": created_at,
"clean_content": clean_content,
}
# Append each post dictionary to the list
posts_list.append(post_dict)
# Write the list to a JSON file
output_file = output_path / f"{topic_id}_all_posts.json"
with Path(output_file).open("w", encoding="utf-8") as f:
json.dump(posts_list, f, indent=2)
def write_posts_txt(df, output_path):
"""Write post files to output directory.
Parameters
----------
df : pd.DataFrame
DataFrame containing posts with columns: id, name, created_at,
post_number, and clean_cooked.
output_path : Path
Directory where the text file should be written.
Notes
-----
Appends all posts to a single file named 'all_posts.txt' in the output
directory. Each post includes ID, author, creation date, post number,
and clean content.
"""
for _index, row in df.iterrows():
post_id = row["id"]
author = row["name"]
created_at = row["created_at"]
number = row["post_number"]
clean_content = row["clean_cooked"]
with Path(output_path / "all_posts.txt").open("a", encoding="utf-8") as f:
f.write(f"ID: {post_id}\n")
f.write(f"Author: {author}\n")
f.write(f"Created at: {created_at}\n")
f.write(f"Number: {number}\n")
f.write(f"Clean content: {clean_content}\n")
| willingc/discuss-nutshell | 0 | Understand long Discourse threads | Python | willingc | Carol Willing | Willing Consulting |
src/discuss_nutshell/utils.py | Python | """Helper utilities for notebooks"""
from datetime import datetime
from json import dumps, loads
import pandas as pd
from bs4 import BeautifulSoup
def pprint_json(jstr):
"""Pretty print JSON.
Parameters
----------
jstr : str
JSON string to pretty print.
"""
print(dumps(loads(jstr), indent=2))
def clean_html(html_text):
"""Remove HTML tags and return clean text.
Parameters
----------
html_text : str
HTML text to clean. Can be NaN.
Returns
-------
str
Clean text with HTML tags removed. Returns empty string if input
is NaN.
"""
if pd.isna(html_text):
return ""
soup = BeautifulSoup(html_text, "html.parser")
return soup.get_text(separator=" ", strip=True)
def display_dataframe(df):
"""Display dataframe.
Parameters
----------
df : pd.DataFrame
DataFrame to display.
Notes
-----
Prints the first few rows and column names of the dataframe.
"""
print(df.head())
print(df.columns)
def format_date(iso_date_string: str) -> str:
"""Convert ISO 8601 datetime string to readable format.
Parameters
----------
iso_date_string : str
ISO 8601 formatted datetime string (e.g., "2025-11-22T18:11:23.522Z").
Returns
-------
str
Human-readable date string in YYYY-MM-DD HH:MM format
(e.g., "2025-11-22 18:11").
Examples
--------
>>> format_date("2025-11-22T18:11:23.522Z")
'2025-11-22 18:11'
"""
# Handle UTC timezone indicator
date_str = iso_date_string.replace("Z", "+00:00")
dt = datetime.fromisoformat(date_str)
return dt.strftime("%Y-%m-%d %H:%M")
| willingc/discuss-nutshell | 0 | Understand long Discourse threads | Python | willingc | Carol Willing | Willing Consulting |
src/discuss_nutshell/visualize.py | Python | """Visualize Discourse posts as cards."""
import json
from pathlib import Path
from typing import Any
import gradio as gr
def load_posts_json(file_path: str | Path) -> list[dict[str, Any]]:
"""Load posts from a JSON file.
Parameters
----------
file_path : str | Path
Path to the JSON file containing posts.
Returns
-------
list[dict[str, Any]]
List of post dictionaries.
Raises
------
FileNotFoundError
If the file does not exist.
json.JSONDecodeError
If the file is not valid JSON.
"""
path = Path(file_path)
if not path.exists():
msg = f"File not found: {file_path}"
raise FileNotFoundError(msg)
with path.open(encoding="utf-8") as f:
return json.load(f)
def create_post_card(post: dict[str, Any]) -> str:
"""Create an HTML card for a single post.
Parameters
----------
post : dict[str, Any]
Post dictionary with keys: id, author, number, created_at, clean_content.
Returns
-------
str
HTML string representing the post card.
"""
post_id = post.get("id", "Unknown")
author = post.get("author", "Unknown")
number = post.get("number", "?")
created_at = post.get("created_at", "Unknown")
content = post.get("clean_content", "")
# Escape HTML special characters in content
content_escaped = (
content.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace('"', """)
.replace("'", "'")
)
# Replace newlines with <br> for HTML display
content_formatted = content_escaped.replace("\n", "<br>")
return f"""
<div style="
border: 1px solid #e0e0e0;
border-radius: 8px;
padding: 16px;
margin: 12px 0;
background-color: #ffffff;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
">
<div style="
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 12px;
padding-bottom: 8px;
border-bottom: 1px solid #f0f0f0;
">
<div>
<strong style="color: #1976d2; font-size: 14px;">Post #{number}</strong>
<span style="color: #666; font-size: 12px; margin-left: 8px;">ID: {post_id}</span>
</div>
<div style="text-align: right;">
<div style="color: #333; font-weight: 500; font-size: 14px;">{author}</div>
<div style="color: #999; font-size: 12px;">{created_at}</div>
</div>
</div>
<div style="
color: #333;
line-height: 1.6;
font-size: 14px;
max-height: 400px;
overflow-y: auto;
">
{content_formatted}
</div>
</div>
"""
def display_posts(file_path: str | Path) -> str:
"""Load and display all posts as HTML cards.
Parameters
----------
file_path : str | Path
Path to the JSON file containing posts.
Returns
-------
str
HTML string containing all post cards.
"""
posts = load_posts_json(file_path)
cards = [create_post_card(post) for post in posts]
return f"""
<div style="
max-width: 1200px;
margin: 0 auto;
padding: 20px;
background-color: #f5f5f5;
">
<h1 style="
color: #1976d2;
margin-bottom: 24px;
font-size: 24px;
text-align: center;
">Discourse Posts</h1>
<div>
{"".join(cards)}
</div>
</div>
"""
def create_visualization_app(json_file: str | Path) -> gr.Blocks:
"""Create a Gradio app to visualize posts.
Parameters
----------
json_file : str | Path
Path to the JSON file containing posts.
Returns
-------
gr.Blocks
Gradio Blocks interface for the visualization.
"""
file_path = Path(json_file)
if not file_path.exists():
msg = f"File not found: {json_file}"
raise FileNotFoundError(msg)
posts = load_posts_json(file_path)
total_posts = len(posts)
def update_display(post_number: int) -> str:
"""Update the display based on selected post number.
Parameters
----------
post_number : int
The post number to display (1-indexed).
Returns
-------
str
HTML content for the selected post.
"""
if post_number < 1 or post_number > total_posts:
return "<p>Invalid post number</p>"
post = posts[post_number - 1]
return create_post_card(post)
def show_all_posts() -> str:
"""Display all posts.
Returns
-------
str
HTML content for all posts.
"""
return display_posts(file_path)
with gr.Blocks(
title="Discourse Posts Visualization", theme=gr.themes.Soft()
) as app:
gr.Markdown(
f"# Discourse Posts Visualization\n\n**Total Posts:** {total_posts}"
)
with gr.Row():
with gr.Column(scale=1):
post_slider = gr.Slider(
minimum=1,
maximum=total_posts,
step=1,
value=1,
label="Post Number",
)
view_single_btn = gr.Button("View Single Post", variant="primary")
view_all_btn = gr.Button("View All Posts", variant="secondary")
with gr.Column(scale=3):
output = gr.HTML(label="Post Content")
view_single_btn.click(
fn=update_display,
inputs=post_slider,
outputs=output,
)
view_all_btn.click(
fn=show_all_posts,
outputs=output,
)
# Auto-update when slider changes
post_slider.change(
fn=update_display,
inputs=post_slider,
outputs=output,
)
return app
def main(json_file: str | Path | None = None) -> None:
"""Launch the visualization app.
Parameters
----------
json_file : str | Path | None, optional
Path to the JSON file. If None, defaults to data/104906_all_posts.json.
"""
if json_file is None:
current_path = Path.cwd()
json_file = current_path / "data" / "104906_all_posts.json"
app = create_visualization_app(json_file)
app.launch()
if __name__ == "__main__":
main()
| willingc/discuss-nutshell | 0 | Understand long Discourse threads | Python | willingc | Carol Willing | Willing Consulting |
tests/test_data_loader.py | Python | """Tests for the data_loader module."""
from __future__ import annotations
from typing import TYPE_CHECKING
from unittest.mock import MagicMock, patch
import pytest
import requests
from discuss_nutshell.data_loader import get_topic
if TYPE_CHECKING:
from pathlib import Path
class TestGetTopic:
"""Tests for get_topic function."""
@patch("discuss_nutshell.data_loader.requests.get")
@patch("discuss_nutshell.data_loader.Path")
@patch("builtins.print")
def test_get_topic_success(
self,
mock_print: MagicMock,
mock_path: MagicMock,
mock_get: MagicMock,
tmp_path: Path,
) -> None:
"""Test successful topic retrieval and file writing.
Parameters
----------
mock_print : MagicMock
Mocked print function.
mock_path : MagicMock
Mocked Path class.
mock_get : MagicMock
Mocked requests.get function.
tmp_path : Path
Temporary directory path provided by pytest.
"""
# Setup mock response
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.headers = {"Content-Type": "application/json"}
mock_response.text = '{"test": "data"}'
mock_get.return_value = mock_response
# Setup file mock - Path(filename).open() pattern
mock_file = MagicMock()
mock_context_manager = MagicMock()
mock_context_manager.__enter__ = MagicMock(return_value=mock_file)
mock_context_manager.__exit__ = MagicMock(return_value=None)
mock_path_instance = MagicMock()
mock_path_instance.open.return_value = mock_context_manager
mock_path.return_value = mock_path_instance
# Test
topic_id = 12345
filename = tmp_path / "test_topic.json"
get_topic(topic_id, filename)
# Assertions
mock_get.assert_called_once_with(
f"https://discuss.python.org/t/{topic_id}.json?print=true",
headers={
"Authorization": "Bearer None",
"Content-Type": "application/json",
},
timeout=30,
)
# Verify Path(filename) was called and then .open() was called
mock_path.assert_called_once_with(filename)
mock_path_instance.open.assert_called_once_with("w", encoding="utf-8")
mock_file.write.assert_called_once_with('{"test": "data"}')
mock_print.assert_called_once_with(200, "application/json")
@patch("discuss_nutshell.data_loader.requests.get")
@patch("discuss_nutshell.data_loader.Path")
def test_get_topic_with_api_key(
self,
mock_path: MagicMock,
mock_get: MagicMock,
tmp_path: Path,
) -> None:
"""Test that headers are passed to requests.get.
Parameters
----------
mock_path : MagicMock
Mocked Path class.
mock_get : MagicMock
Mocked requests.get function.
tmp_path : Path
Temporary directory path provided by pytest.
"""
# Patch headers at module level
with patch(
"discuss_nutshell.data_loader.headers",
{
"Authorization": "Bearer test-api-key",
"Content-Type": "application/json",
},
):
# Setup mock response
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.headers = {"Content-Type": "application/json"}
mock_response.text = '{"test": "data"}'
mock_get.return_value = mock_response
# Setup file mock
mock_file = MagicMock()
mock_context_manager = MagicMock()
mock_context_manager.__enter__ = MagicMock(return_value=mock_file)
mock_context_manager.__exit__ = MagicMock(return_value=None)
mock_path_instance = MagicMock()
mock_path_instance.open.return_value = mock_context_manager
mock_path.return_value = mock_path_instance
# Test
topic_id = 12345
filename = tmp_path / "test_topic.json"
get_topic(topic_id, filename)
# Assertions
mock_get.assert_called_once()
call_args = mock_get.call_args
assert call_args[1]["headers"]["Authorization"] == "Bearer test-api-key"
assert call_args[1]["headers"]["Content-Type"] == "application/json"
@patch("discuss_nutshell.data_loader.requests.get")
@patch("discuss_nutshell.data_loader.Path")
def test_get_topic_different_topic_ids(
self,
mock_path: MagicMock,
mock_get: MagicMock,
tmp_path: Path,
) -> None:
"""Test get_topic with different topic IDs.
Parameters
----------
mock_path : MagicMock
Mocked Path class.
mock_get : MagicMock
Mocked requests.get function.
tmp_path : Path
Temporary directory path provided by pytest.
"""
# Setup mock response
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.headers = {"Content-Type": "application/json"}
mock_response.text = '{"test": "data"}'
mock_get.return_value = mock_response
# Setup file mock
mock_file = MagicMock()
mock_context_manager = MagicMock()
mock_context_manager.__enter__ = MagicMock(return_value=mock_file)
mock_context_manager.__exit__ = MagicMock(return_value=None)
mock_path_instance = MagicMock()
mock_path_instance.open.return_value = mock_context_manager
mock_path.return_value = mock_path_instance
# Test with different topic IDs
for topic_id in [104906, 12345, 99999]:
get_topic(topic_id, tmp_path / f"topic_{topic_id}.json")
expected_url = f"https://discuss.python.org/t/{topic_id}.json?print=true"
mock_get.assert_any_call(
expected_url,
headers={
"Authorization": "Bearer None",
"Content-Type": "application/json",
},
timeout=30,
)
@patch("discuss_nutshell.data_loader.requests.get")
@patch("discuss_nutshell.data_loader.Path")
@patch("builtins.print")
def test_get_topic_http_error(
self,
mock_print: MagicMock,
mock_path: MagicMock,
mock_get: MagicMock,
tmp_path: Path,
) -> None:
"""Test get_topic handles HTTP error responses.
Parameters
----------
mock_print : MagicMock
Mocked print function.
mock_path : MagicMock
Mocked Path class.
mock_get : MagicMock
Mocked requests.get function.
tmp_path : Path
Temporary directory path provided by pytest.
"""
# Setup mock response with error status
mock_response = MagicMock()
mock_response.status_code = 404
mock_response.headers = {"Content-Type": "application/json"}
mock_response.text = '{"error": "Not found"}'
mock_get.return_value = mock_response
# Setup file mock
mock_file = MagicMock()
mock_context_manager = MagicMock()
mock_context_manager.__enter__ = MagicMock(return_value=mock_file)
mock_context_manager.__exit__ = MagicMock(return_value=None)
mock_path_instance = MagicMock()
mock_path_instance.open.return_value = mock_context_manager
mock_path.return_value = mock_path_instance
# Test - should still write the error response
topic_id = 12345
filename = tmp_path / "test_topic.json"
get_topic(topic_id, filename)
# Should still print status code
mock_print.assert_called_once_with(404, "application/json")
@patch("discuss_nutshell.data_loader.requests.get")
def test_get_topic_network_error(
self,
mock_get: MagicMock,
tmp_path: Path,
) -> None:
"""Test get_topic handles network errors.
Parameters
----------
mock_get : MagicMock
Mocked requests.get function.
tmp_path : Path
Temporary directory path provided by pytest.
"""
# Setup mock to raise network error
mock_get.side_effect = requests.RequestException("Network error")
# Test - should raise exception
topic_id = 12345
filename = tmp_path / "test_topic.json"
with pytest.raises(requests.RequestException, match="Network error"):
get_topic(topic_id, filename)
@patch("discuss_nutshell.data_loader.requests.get")
def test_get_topic_timeout(
self,
mock_get: MagicMock,
tmp_path: Path,
) -> None:
"""Test get_topic handles timeout errors.
Parameters
----------
mock_get : MagicMock
Mocked requests.get function.
tmp_path : Path
Temporary directory path provided by pytest.
"""
# Setup mock to raise timeout error
mock_get.side_effect = requests.Timeout("Request timed out")
# Test - should raise exception
topic_id = 12345
filename = tmp_path / "test_topic.json"
with pytest.raises(requests.Timeout, match="Request timed out"):
get_topic(topic_id, filename)
@patch("discuss_nutshell.data_loader.requests.get")
@patch("discuss_nutshell.data_loader.Path")
def test_get_topic_file_write_error(
self,
mock_path: MagicMock,
mock_get: MagicMock,
tmp_path: Path,
) -> None:
"""Test get_topic handles file writing errors.
Parameters
----------
mock_path : MagicMock
Mocked Path class.
mock_get : MagicMock
Mocked requests.get function.
tmp_path : Path
Temporary directory path provided by pytest.
"""
# Setup mock response
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.headers = {"Content-Type": "application/json"}
mock_response.text = '{"test": "data"}'
mock_get.return_value = mock_response
# Setup file mock to raise error
mock_path_instance = MagicMock()
mock_path_instance.open.side_effect = OSError("Permission denied")
mock_path.return_value = mock_path_instance
# Test - should raise exception
topic_id = 12345
filename = tmp_path / "test_topic.json"
with pytest.raises(OSError, match="Permission denied"):
get_topic(topic_id, filename)
@patch("discuss_nutshell.data_loader.requests.get")
@patch("discuss_nutshell.data_loader.Path")
def test_get_topic_writes_json_content(
self,
mock_path: MagicMock,
mock_get: MagicMock,
tmp_path: Path,
) -> None:
"""Test that get_topic writes the response text to file.
Parameters
----------
mock_path : MagicMock
Mocked Path class.
mock_get : MagicMock
Mocked requests.get function.
tmp_path : Path
Temporary directory path provided by pytest.
"""
# Setup mock response with JSON content
json_content = '{"id": 123, "title": "Test Topic", "posts": []}'
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.headers = {"Content-Type": "application/json"}
mock_response.text = json_content
mock_get.return_value = mock_response
# Setup file mock
mock_file = MagicMock()
mock_context_manager = MagicMock()
mock_context_manager.__enter__ = MagicMock(return_value=mock_file)
mock_context_manager.__exit__ = MagicMock(return_value=None)
mock_path_instance = MagicMock()
mock_path_instance.open.return_value = mock_context_manager
mock_path.return_value = mock_path_instance
# Test
topic_id = 12345
filename = tmp_path / "test_topic.json"
get_topic(topic_id, filename)
# Assertions
mock_file.write.assert_called_once_with(json_content)
@patch("discuss_nutshell.data_loader.requests.get")
@patch("discuss_nutshell.data_loader.Path")
def test_get_topic_uses_correct_timeout(
self,
mock_path: MagicMock,
mock_get: MagicMock,
tmp_path: Path,
) -> None:
"""Test that get_topic uses the correct timeout value.
Parameters
----------
mock_path : MagicMock
Mocked Path class.
mock_get : MagicMock
Mocked requests.get function.
tmp_path : Path
Temporary directory path provided by pytest.
"""
# Setup mock response
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.headers = {"Content-Type": "application/json"}
mock_response.text = '{"test": "data"}'
mock_get.return_value = mock_response
# Setup file mock
mock_file = MagicMock()
mock_context_manager = MagicMock()
mock_context_manager.__enter__ = MagicMock(return_value=mock_file)
mock_context_manager.__exit__ = MagicMock(return_value=None)
mock_path_instance = MagicMock()
mock_path_instance.open.return_value = mock_context_manager
mock_path.return_value = mock_path_instance
# Test
topic_id = 12345
filename = tmp_path / "test_topic.json"
get_topic(topic_id, filename)
# Assertions - check timeout is 30 seconds
call_args = mock_get.call_args
assert call_args[1]["timeout"] == 30
@patch("discuss_nutshell.data_loader.requests.get")
@patch("discuss_nutshell.data_loader.Path")
def test_get_topic_url_format(
self,
mock_path: MagicMock,
mock_get: MagicMock,
tmp_path: Path,
) -> None:
"""Test that get_topic constructs the correct URL format.
Parameters
----------
mock_path : MagicMock
Mocked Path class.
mock_get : MagicMock
Mocked requests.get function.
tmp_path : Path
Temporary directory path provided by pytest.
"""
# Setup mock response
mock_response = MagicMock()
mock_response.status_code = 200
mock_response.headers = {"Content-Type": "application/json"}
mock_response.text = '{"test": "data"}'
mock_get.return_value = mock_response
# Setup file mock
mock_file = MagicMock()
mock_context_manager = MagicMock()
mock_context_manager.__enter__ = MagicMock(return_value=mock_file)
mock_context_manager.__exit__ = MagicMock(return_value=None)
mock_path_instance = MagicMock()
mock_path_instance.open.return_value = mock_context_manager
mock_path.return_value = mock_path_instance
# Test
topic_id = 104906
filename = tmp_path / "test_topic.json"
get_topic(topic_id, filename)
# Assertions - check URL format
expected_url = f"https://discuss.python.org/t/{topic_id}.json?print=true"
call_args = mock_get.call_args
assert call_args[0][0] == expected_url
| willingc/discuss-nutshell | 0 | Understand long Discourse threads | Python | willingc | Carol Willing | Willing Consulting |
tests/test_package.py | Python | from __future__ import annotations
import importlib.metadata
import discuss_nutshell as m
def test_version():
"""Test that the version matches."""
assert importlib.metadata.version("discuss_nutshell") == m.__version__
| willingc/discuss-nutshell | 0 | Understand long Discourse threads | Python | willingc | Carol Willing | Willing Consulting |
.devcontainer/installMongoDB.sh | Shell | #!/bin/bash
# Install MongoDB
wget -qO - https://www.mongodb.org/static/pgp/server-7.0.asc | sudo apt-key add -
echo "deb [ arch=amd64,arm64 ] https://repo.mongodb.org/apt/ubuntu jammy/mongodb-org/7.0 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org-7.0.list
sudo apt-get update
sudo apt-get install -y mongodb-org
# Create necessary directories and set permissions
sudo mkdir -p /data/db
sudo chown -R mongodb:mongodb /data/db
# Start MongoDB service
sudo mongod --fork --logpath /var/log/mongodb/mongod.log
echo "MongoDB has been installed and started successfully!"
mongod --version
# Run sample MongoDB commands
echo "Current databases:"
mongosh --eval "db.getMongo().getDBNames()" | willingc/skills-introduction-to-repository-management | 0 | Exercise: introduction to repository management | JavaScript | willingc | Carol Willing | Willing Consulting |
.devcontainer/postCreate.sh | Shell | # Prepare python environment
pip install -r requirements.txt
# Prepare MongoDB Dev DB
./.devcontainer/installMongoDB.sh | willingc/skills-introduction-to-repository-management | 0 | Exercise: introduction to repository management | JavaScript | willingc | Carol Willing | Willing Consulting |
src/app.py | Python | """
High School Management System API
A super simple FastAPI application that allows students to view and sign up
for extracurricular activities at Mergington High School.
"""
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import RedirectResponse
import os
from pathlib import Path
from .backend import routers, database
# Initialize web host
app = FastAPI(
title="Mergington High School API",
description="API for viewing and signing up for extracurricular activities"
)
# Initialize database with sample data if empty
database.init_database()
# Mount the static files directory for serving the frontend
current_dir = Path(__file__).parent
app.mount("/static", StaticFiles(directory=os.path.join(current_dir, "static")), name="static")
# Root endpoint to redirect to static index.html
@app.get("/")
def root():
return RedirectResponse(url="/static/index.html")
# Include routers
app.include_router(routers.activities.router)
app.include_router(routers.auth.router)
| willingc/skills-introduction-to-repository-management | 0 | Exercise: introduction to repository management | JavaScript | willingc | Carol Willing | Willing Consulting |
src/backend/__init__.py | Python | from . import routers
from . import database | willingc/skills-introduction-to-repository-management | 0 | Exercise: introduction to repository management | JavaScript | willingc | Carol Willing | Willing Consulting |
src/backend/database.py | Python | """
MongoDB database configuration and setup for Mergington High School API
"""
from pymongo import MongoClient
from argon2 import PasswordHasher
# Connect to MongoDB
client = MongoClient('mongodb://localhost:27017/')
db = client['mergington_high']
activities_collection = db['activities']
teachers_collection = db['teachers']
# Methods
def hash_password(password):
"""Hash password using Argon2"""
ph = PasswordHasher()
return ph.hash(password)
def init_database():
"""Initialize database if empty"""
# Initialize activities if empty
if activities_collection.count_documents({}) == 0:
for name, details in initial_activities.items():
activities_collection.insert_one({"_id": name, **details})
# Initialize teacher accounts if empty
if teachers_collection.count_documents({}) == 0:
for teacher in initial_teachers:
teachers_collection.insert_one({"_id": teacher["username"], **teacher})
# Initial database if empty
initial_activities = {
"Chess Club": {
"description": "Learn strategies and compete in chess tournaments",
"schedule": "Mondays and Fridays, 3:15 PM - 4:45 PM",
"schedule_details": {
"days": ["Monday", "Friday"],
"start_time": "15:15",
"end_time": "16:45"
},
"max_participants": 12,
"participants": ["michael@mergington.edu", "daniel@mergington.edu"]
},
"Programming Class": {
"description": "Learn programming fundamentals and build software projects",
"schedule": "Tuesdays and Thursdays, 7:00 AM - 8:00 AM",
"schedule_details": {
"days": ["Tuesday", "Thursday"],
"start_time": "07:00",
"end_time": "08:00"
},
"max_participants": 20,
"participants": ["emma@mergington.edu", "sophia@mergington.edu"]
},
"Morning Fitness": {
"description": "Early morning physical training and exercises",
"schedule": "Mondays, Wednesdays, Fridays, 6:30 AM - 7:45 AM",
"schedule_details": {
"days": ["Monday", "Wednesday", "Friday"],
"start_time": "06:30",
"end_time": "07:45"
},
"max_participants": 30,
"participants": ["john@mergington.edu", "olivia@mergington.edu"]
},
"Soccer Team": {
"description": "Join the school soccer team and compete in matches",
"schedule": "Tuesdays and Thursdays, 3:30 PM - 5:30 PM",
"schedule_details": {
"days": ["Tuesday", "Thursday"],
"start_time": "15:30",
"end_time": "17:30"
},
"max_participants": 22,
"participants": ["liam@mergington.edu", "noah@mergington.edu"]
},
"Basketball Team": {
"description": "Practice and compete in basketball tournaments",
"schedule": "Wednesdays and Fridays, 3:15 PM - 5:00 PM",
"schedule_details": {
"days": ["Wednesday", "Friday"],
"start_time": "15:15",
"end_time": "17:00"
},
"max_participants": 15,
"participants": ["ava@mergington.edu", "mia@mergington.edu"]
},
"Art Club": {
"description": "Explore various art techniques and create masterpieces",
"schedule": "Thursdays, 3:15 PM - 5:00 PM",
"schedule_details": {
"days": ["Thursday"],
"start_time": "15:15",
"end_time": "17:00"
},
"max_participants": 15,
"participants": ["amelia@mergington.edu", "harper@mergington.edu"]
},
"Drama Club": {
"description": "Act, direct, and produce plays and performances",
"schedule": "Mondays and Wednesdays, 3:30 PM - 5:30 PM",
"schedule_details": {
"days": ["Monday", "Wednesday"],
"start_time": "15:30",
"end_time": "17:30"
},
"max_participants": 20,
"participants": ["ella@mergington.edu", "scarlett@mergington.edu"]
},
"Math Club": {
"description": "Solve challenging problems and prepare for math competitions",
"schedule": "Tuesdays, 7:15 AM - 8:00 AM",
"schedule_details": {
"days": ["Tuesday"],
"start_time": "07:15",
"end_time": "08:00"
},
"max_participants": 10,
"participants": ["james@mergington.edu", "benjamin@mergington.edu"]
},
"Debate Team": {
"description": "Develop public speaking and argumentation skills",
"schedule": "Fridays, 3:30 PM - 5:30 PM",
"schedule_details": {
"days": ["Friday"],
"start_time": "15:30",
"end_time": "17:30"
},
"max_participants": 12,
"participants": ["charlotte@mergington.edu", "amelia@mergington.edu"]
},
"Weekend Robotics Workshop": {
"description": "Build and program robots in our state-of-the-art workshop",
"schedule": "Saturdays, 10:00 AM - 2:00 PM",
"schedule_details": {
"days": ["Saturday"],
"start_time": "10:00",
"end_time": "14:00"
},
"max_participants": 15,
"participants": ["ethan@mergington.edu", "oliver@mergington.edu"]
},
"Science Olympiad": {
"description": "Weekend science competition preparation for regional and state events",
"schedule": "Saturdays, 1:00 PM - 4:00 PM",
"schedule_details": {
"days": ["Saturday"],
"start_time": "13:00",
"end_time": "16:00"
},
"max_participants": 18,
"participants": ["isabella@mergington.edu", "lucas@mergington.edu"]
},
"Sunday Chess Tournament": {
"description": "Weekly tournament for serious chess players with rankings",
"schedule": "Sundays, 2:00 PM - 5:00 PM",
"schedule_details": {
"days": ["Sunday"],
"start_time": "14:00",
"end_time": "17:00"
},
"max_participants": 16,
"participants": ["william@mergington.edu", "jacob@mergington.edu"]
}
}
initial_teachers = [
{
"username": "mrodriguez",
"display_name": "Ms. Rodriguez",
"password": hash_password("art123"),
"role": "teacher"
},
{
"username": "mchen",
"display_name": "Mr. Chen",
"password": hash_password("chess456"),
"role": "teacher"
},
{
"username": "principal",
"display_name": "Principal Martinez",
"password": hash_password("admin789"),
"role": "admin"
}
]
| willingc/skills-introduction-to-repository-management | 0 | Exercise: introduction to repository management | JavaScript | willingc | Carol Willing | Willing Consulting |
src/backend/routers/__init__.py | Python | from . import activities
from . import auth | willingc/skills-introduction-to-repository-management | 0 | Exercise: introduction to repository management | JavaScript | willingc | Carol Willing | Willing Consulting |
src/backend/routers/activities.py | Python | """
Endpoints for the High School Management System API
"""
from fastapi import APIRouter, HTTPException, Query
from fastapi.responses import RedirectResponse
from typing import Dict, Any, Optional, List
from ..database import activities_collection, teachers_collection
router = APIRouter(
prefix="/activities",
tags=["activities"]
)
@router.get("/", response_model=Dict[str, Any])
def get_activities(
day: Optional[str] = None,
start_time: Optional[str] = None,
end_time: Optional[str] = None
) -> Dict[str, Any]:
"""
Get all activities with their details, with optional filtering by day and time
- day: Filter activities occurring on this day (e.g., 'Monday', 'Tuesday')
- start_time: Filter activities starting at or after this time (24-hour format, e.g., '14:30')
- end_time: Filter activities ending at or before this time (24-hour format, e.g., '17:00')
"""
# Build the query based on provided filters
query = {}
if day:
query["schedule_details.days"] = {"$in": [day]}
if start_time:
query["schedule_details.start_time"] = {"$gte": start_time}
if end_time:
query["schedule_details.end_time"] = {"$lte": end_time}
# Query the database
activities = {}
for activity in activities_collection.find(query):
name = activity.pop('_id')
activities[name] = activity
return activities
@router.get("/days", response_model=List[str])
def get_available_days() -> List[str]:
"""Get a list of all days that have activities scheduled"""
# Aggregate to get unique days across all activities
pipeline = [
{"$unwind": "$schedule_details.days"},
{"$group": {"_id": "$schedule_details.days"}},
{"$sort": {"_id": 1}} # Sort days alphabetically
]
days = []
for day_doc in activities_collection.aggregate(pipeline):
days.append(day_doc["_id"])
return days
@router.post("/{activity_name}/signup")
def signup_for_activity(activity_name: str, email: str, teacher_username: Optional[str] = Query(None)):
"""Sign up a student for an activity - requires teacher authentication"""
# Check teacher authentication
if not teacher_username:
raise HTTPException(status_code=401, detail="Authentication required for this action")
teacher = teachers_collection.find_one({"_id": teacher_username})
if not teacher:
raise HTTPException(status_code=401, detail="Invalid teacher credentials")
# Get the activity
activity = activities_collection.find_one({"_id": activity_name})
if not activity:
raise HTTPException(status_code=404, detail="Activity not found")
# Validate student is not already signed up
if email in activity["participants"]:
raise HTTPException(
status_code=400, detail="Already signed up for this activity")
# Add student to participants
result = activities_collection.update_one(
{"_id": activity_name},
{"$push": {"participants": email}}
)
if result.modified_count == 0:
raise HTTPException(status_code=500, detail="Failed to update activity")
return {"message": f"Signed up {email} for {activity_name}"}
@router.post("/{activity_name}/unregister")
def unregister_from_activity(activity_name: str, email: str, teacher_username: Optional[str] = Query(None)):
"""Remove a student from an activity - requires teacher authentication"""
# Check teacher authentication
if not teacher_username:
raise HTTPException(status_code=401, detail="Authentication required for this action")
teacher = teachers_collection.find_one({"_id": teacher_username})
if not teacher:
raise HTTPException(status_code=401, detail="Invalid teacher credentials")
# Get the activity
activity = activities_collection.find_one({"_id": activity_name})
if not activity:
raise HTTPException(status_code=404, detail="Activity not found")
# Validate student is signed up
if email not in activity["participants"]:
raise HTTPException(
status_code=400, detail="Not registered for this activity")
# Remove student from participants
result = activities_collection.update_one(
{"_id": activity_name},
{"$pull": {"participants": email}}
)
if result.modified_count == 0:
raise HTTPException(status_code=500, detail="Failed to update activity")
return {"message": f"Unregistered {email} from {activity_name}"} | willingc/skills-introduction-to-repository-management | 0 | Exercise: introduction to repository management | JavaScript | willingc | Carol Willing | Willing Consulting |
src/backend/routers/auth.py | Python | """
Authentication endpoints for the High School Management System API
"""
from fastapi import APIRouter, HTTPException
from typing import Dict, Any
import hashlib
from ..database import teachers_collection
router = APIRouter(
prefix="/auth",
tags=["auth"]
)
def hash_password(password):
"""Hash password using SHA-256"""
return hashlib.sha256(password.encode()).hexdigest()
@router.post("/login")
def login(username: str, password: str) -> Dict[str, Any]:
"""Login a teacher account"""
# Hash the provided password
hashed_password = hash_password(password)
# Find the teacher in the database
teacher = teachers_collection.find_one({"_id": username})
if not teacher or teacher["password"] != hashed_password:
raise HTTPException(status_code=401, detail="Invalid username or password")
# Return teacher information (excluding password)
return {
"username": teacher["username"],
"display_name": teacher["display_name"],
"role": teacher["role"]
}
@router.get("/check-session")
def check_session(username: str) -> Dict[str, Any]:
"""Check if a session is valid by username"""
teacher = teachers_collection.find_one({"_id": username})
if not teacher:
raise HTTPException(status_code=404, detail="Teacher not found")
return {
"username": teacher["username"],
"display_name": teacher["display_name"],
"role": teacher["role"]
} | willingc/skills-introduction-to-repository-management | 0 | Exercise: introduction to repository management | JavaScript | willingc | Carol Willing | Willing Consulting |
src/static/app.js | JavaScript | document.addEventListener("DOMContentLoaded", () => {
// DOM elements
const activitiesList = document.getElementById("activities-list");
const messageDiv = document.getElementById("message");
const registrationModal = document.getElementById("registration-modal");
const modalActivityName = document.getElementById("modal-activity-name");
const signupForm = document.getElementById("signup-form");
const activityInput = document.getElementById("activity");
const closeRegistrationModal = document.querySelector(".close-modal");
// Search and filter elements
const searchInput = document.getElementById("activity-search");
const searchButton = document.getElementById("search-button");
const categoryFilters = document.querySelectorAll(".category-filter");
const dayFilters = document.querySelectorAll(".day-filter");
const timeFilters = document.querySelectorAll(".time-filter");
// Authentication elements
const loginButton = document.getElementById("login-button");
const userInfo = document.getElementById("user-info");
const displayName = document.getElementById("display-name");
const logoutButton = document.getElementById("logout-button");
const loginModal = document.getElementById("login-modal");
const loginForm = document.getElementById("login-form");
const closeLoginModal = document.querySelector(".close-login-modal");
const loginMessage = document.getElementById("login-message");
// Activity categories with corresponding colors
const activityTypes = {
sports: { label: "Sports", color: "#e8f5e9", textColor: "#2e7d32" },
arts: { label: "Arts", color: "#f3e5f5", textColor: "#7b1fa2" },
academic: { label: "Academic", color: "#e3f2fd", textColor: "#1565c0" },
community: { label: "Community", color: "#fff3e0", textColor: "#e65100" },
technology: { label: "Technology", color: "#e8eaf6", textColor: "#3949ab" },
};
// State for activities and filters
let allActivities = {};
let currentFilter = "all";
let searchQuery = "";
let currentDay = "";
let currentTimeRange = "";
// Authentication state
let currentUser = null;
// Time range mappings for the dropdown
const timeRanges = {
morning: { start: "06:00", end: "08:00" }, // Before school hours
afternoon: { start: "15:00", end: "18:00" }, // After school hours
weekend: { days: ["Saturday", "Sunday"] }, // Weekend days
};
// Initialize filters from active elements
function initializeFilters() {
// Initialize day filter
const activeDayFilter = document.querySelector(".day-filter.active");
if (activeDayFilter) {
currentDay = activeDayFilter.dataset.day;
}
// Initialize time filter
const activeTimeFilter = document.querySelector(".time-filter.active");
if (activeTimeFilter) {
currentTimeRange = activeTimeFilter.dataset.time;
}
}
// Function to set day filter
function setDayFilter(day) {
currentDay = day;
// Update active class
dayFilters.forEach((btn) => {
if (btn.dataset.day === day) {
btn.classList.add("active");
} else {
btn.classList.remove("active");
}
});
fetchActivities();
}
// Function to set time range filter
function setTimeRangeFilter(timeRange) {
currentTimeRange = timeRange;
// Update active class
timeFilters.forEach((btn) => {
if (btn.dataset.time === timeRange) {
btn.classList.add("active");
} else {
btn.classList.remove("active");
}
});
fetchActivities();
}
// Check if user is already logged in (from localStorage)
function checkAuthentication() {
const savedUser = localStorage.getItem("currentUser");
if (savedUser) {
try {
currentUser = JSON.parse(savedUser);
updateAuthUI();
// Verify the stored user with the server
validateUserSession(currentUser.username);
} catch (error) {
console.error("Error parsing saved user", error);
logout(); // Clear invalid data
}
}
// Set authentication class on body
updateAuthBodyClass();
}
// Validate user session with the server
async function validateUserSession(username) {
try {
const response = await fetch(
`/auth/check-session?username=${encodeURIComponent(username)}`
);
if (!response.ok) {
// Session invalid, log out
logout();
return;
}
// Session is valid, update user data
const userData = await response.json();
currentUser = userData;
localStorage.setItem("currentUser", JSON.stringify(userData));
updateAuthUI();
} catch (error) {
console.error("Error validating session:", error);
}
}
// Update UI based on authentication state
function updateAuthUI() {
if (currentUser) {
loginButton.classList.add("hidden");
userInfo.classList.remove("hidden");
displayName.textContent = currentUser.display_name;
} else {
loginButton.classList.remove("hidden");
userInfo.classList.add("hidden");
displayName.textContent = "";
}
updateAuthBodyClass();
// Refresh the activities to update the UI
fetchActivities();
}
// Update body class for CSS targeting
function updateAuthBodyClass() {
if (currentUser) {
document.body.classList.remove("not-authenticated");
} else {
document.body.classList.add("not-authenticated");
}
}
// Login function
async function login(username, password) {
try {
const response = await fetch(
`/auth/login?username=${encodeURIComponent(
username
)}&password=${encodeURIComponent(password)}`,
{
method: "POST",
}
);
const data = await response.json();
if (!response.ok) {
showLoginMessage(
data.detail || "Invalid username or password",
"error"
);
return false;
}
// Login successful
currentUser = data;
localStorage.setItem("currentUser", JSON.stringify(data));
updateAuthUI();
closeLoginModalHandler();
showMessage(`Welcome, ${currentUser.display_name}!`, "success");
return true;
} catch (error) {
console.error("Error during login:", error);
showLoginMessage("Login failed. Please try again.", "error");
return false;
}
}
// Logout function
function logout() {
currentUser = null;
localStorage.removeItem("currentUser");
updateAuthUI();
showMessage("You have been logged out.", "info");
}
// Show message in login modal
function showLoginMessage(text, type) {
loginMessage.textContent = text;
loginMessage.className = `message ${type}`;
loginMessage.classList.remove("hidden");
}
// Open login modal
function openLoginModal() {
loginModal.classList.remove("hidden");
loginModal.classList.add("show");
loginMessage.classList.add("hidden");
loginForm.reset();
}
// Close login modal
function closeLoginModalHandler() {
loginModal.classList.remove("show");
setTimeout(() => {
loginModal.classList.add("hidden");
loginForm.reset();
}, 300);
}
// Event listeners for authentication
loginButton.addEventListener("click", openLoginModal);
logoutButton.addEventListener("click", logout);
closeLoginModal.addEventListener("click", closeLoginModalHandler);
// Close login modal when clicking outside
window.addEventListener("click", (event) => {
if (event.target === loginModal) {
closeLoginModalHandler();
}
});
// Handle login form submission
loginForm.addEventListener("submit", async (event) => {
event.preventDefault();
const username = document.getElementById("username").value;
const password = document.getElementById("password").value;
await login(username, password);
});
// Show loading skeletons
function showLoadingSkeletons() {
activitiesList.innerHTML = "";
// Create more skeleton cards to fill the screen since they're smaller now
for (let i = 0; i < 9; i++) {
const skeletonCard = document.createElement("div");
skeletonCard.className = "skeleton-card";
skeletonCard.innerHTML = `
<div class="skeleton-line skeleton-title"></div>
<div class="skeleton-line"></div>
<div class="skeleton-line skeleton-text short"></div>
<div style="margin-top: 8px;">
<div class="skeleton-line" style="height: 6px;"></div>
<div class="skeleton-line skeleton-text short" style="height: 8px; margin-top: 3px;"></div>
</div>
<div style="margin-top: auto;">
<div class="skeleton-line" style="height: 24px; margin-top: 8px;"></div>
</div>
`;
activitiesList.appendChild(skeletonCard);
}
}
// Format schedule for display - handles both old and new format
function formatSchedule(details) {
// If schedule_details is available, use the structured data
if (details.schedule_details) {
const days = details.schedule_details.days.join(", ");
// Convert 24h time format to 12h AM/PM format for display
const formatTime = (time24) => {
const [hours, minutes] = time24.split(":").map((num) => parseInt(num));
const period = hours >= 12 ? "PM" : "AM";
const displayHours = hours % 12 || 12; // Convert 0 to 12 for 12 AM
return `${displayHours}:${minutes
.toString()
.padStart(2, "0")} ${period}`;
};
const startTime = formatTime(details.schedule_details.start_time);
const endTime = formatTime(details.schedule_details.end_time);
return `${days}, ${startTime} - ${endTime}`;
}
// Fallback to the string format if schedule_details isn't available
return details.schedule;
}
// Function to determine activity type (this would ideally come from backend)
function getActivityType(activityName, description) {
const name = activityName.toLowerCase();
const desc = description.toLowerCase();
if (
name.includes("soccer") ||
name.includes("basketball") ||
name.includes("sport") ||
name.includes("fitness") ||
desc.includes("team") ||
desc.includes("game") ||
desc.includes("athletic")
) {
return "sports";
} else if (
name.includes("art") ||
name.includes("music") ||
name.includes("theater") ||
name.includes("drama") ||
desc.includes("creative") ||
desc.includes("paint")
) {
return "arts";
} else if (
name.includes("science") ||
name.includes("math") ||
name.includes("academic") ||
name.includes("study") ||
name.includes("olympiad") ||
desc.includes("learning") ||
desc.includes("education") ||
desc.includes("competition")
) {
return "academic";
} else if (
name.includes("volunteer") ||
name.includes("community") ||
desc.includes("service") ||
desc.includes("volunteer")
) {
return "community";
} else if (
name.includes("computer") ||
name.includes("coding") ||
name.includes("tech") ||
name.includes("robotics") ||
desc.includes("programming") ||
desc.includes("technology") ||
desc.includes("digital") ||
desc.includes("robot")
) {
return "technology";
}
// Default to "academic" if no match
return "academic";
}
// Function to fetch activities from API with optional day and time filters
async function fetchActivities() {
// Show loading skeletons first
showLoadingSkeletons();
try {
// Build query string with filters if they exist
let queryParams = [];
// Handle day filter
if (currentDay) {
queryParams.push(`day=${encodeURIComponent(currentDay)}`);
}
// Handle time range filter
if (currentTimeRange) {
const range = timeRanges[currentTimeRange];
// Handle weekend special case
if (currentTimeRange === "weekend") {
// Don't add time parameters for weekend filter
// Weekend filtering will be handled on the client side
} else if (range) {
// Add time parameters for before/after school
queryParams.push(`start_time=${encodeURIComponent(range.start)}`);
queryParams.push(`end_time=${encodeURIComponent(range.end)}`);
}
}
const queryString =
queryParams.length > 0 ? `?${queryParams.join("&")}` : "";
const response = await fetch(`/activities${queryString}`);
const activities = await response.json();
// Save the activities data
allActivities = activities;
// Apply search and filter, and handle weekend filter in client
displayFilteredActivities();
} catch (error) {
activitiesList.innerHTML =
"<p>Failed to load activities. Please try again later.</p>";
console.error("Error fetching activities:", error);
}
}
// Function to display filtered activities
function displayFilteredActivities() {
// Clear the activities list
activitiesList.innerHTML = "";
// Apply client-side filtering - this handles category filter and search, plus weekend filter
let filteredActivities = {};
Object.entries(allActivities).forEach(([name, details]) => {
const activityType = getActivityType(name, details.description);
// Apply category filter
if (currentFilter !== "all" && activityType !== currentFilter) {
return;
}
// Apply weekend filter if selected
if (currentTimeRange === "weekend" && details.schedule_details) {
const activityDays = details.schedule_details.days;
const isWeekendActivity = activityDays.some((day) =>
timeRanges.weekend.days.includes(day)
);
if (!isWeekendActivity) {
return;
}
}
// Apply search filter
const searchableContent = [
name.toLowerCase(),
details.description.toLowerCase(),
formatSchedule(details).toLowerCase(),
].join(" ");
if (
searchQuery &&
!searchableContent.includes(searchQuery.toLowerCase())
) {
return;
}
// Activity passed all filters, add to filtered list
filteredActivities[name] = details;
});
// Check if there are any results
if (Object.keys(filteredActivities).length === 0) {
activitiesList.innerHTML = `
<div class="no-results">
<h4>No activities found</h4>
<p>Try adjusting your search or filter criteria</p>
</div>
`;
return;
}
// Display filtered activities
Object.entries(filteredActivities).forEach(([name, details]) => {
renderActivityCard(name, details);
});
}
// Function to render a single activity card
function renderActivityCard(name, details) {
const activityCard = document.createElement("div");
activityCard.className = "activity-card";
// Calculate spots and capacity
const totalSpots = details.max_participants;
const takenSpots = details.participants.length;
const spotsLeft = totalSpots - takenSpots;
const capacityPercentage = (takenSpots / totalSpots) * 100;
const isFull = spotsLeft <= 0;
// Determine capacity status class
let capacityStatusClass = "capacity-available";
if (isFull) {
capacityStatusClass = "capacity-full";
} else if (capacityPercentage >= 75) {
capacityStatusClass = "capacity-near-full";
}
// Determine activity type
const activityType = getActivityType(name, details.description);
const typeInfo = activityTypes[activityType];
// Format the schedule using the new helper function
const formattedSchedule = formatSchedule(details);
// Create activity tag
const tagHtml = `
<span class="activity-tag" style="background-color: ${typeInfo.color}; color: ${typeInfo.textColor}">
${typeInfo.label}
</span>
`;
// Create capacity indicator
const capacityIndicator = `
<div class="capacity-container ${capacityStatusClass}">
<div class="capacity-bar-bg">
<div class="capacity-bar-fill" style="width: ${capacityPercentage}%"></div>
</div>
<div class="capacity-text">
<span>${takenSpots} enrolled</span>
<span>${spotsLeft} spots left</span>
</div>
</div>
`;
activityCard.innerHTML = `
${tagHtml}
<h4>${name}</h4>
<p>${details.description}</p>
<p class="tooltip">
<strong>Schedule:</strong> ${formattedSchedule}
<span class="tooltip-text">Regular meetings at this time throughout the semester</span>
</p>
${capacityIndicator}
<div class="participants-list">
<h5>Current Participants:</h5>
<ul>
${details.participants
.map(
(email) => `
<li>
${email}
${
currentUser
? `
<span class="delete-participant tooltip" data-activity="${name}" data-email="${email}">
✖
<span class="tooltip-text">Unregister this student</span>
</span>
`
: ""
}
</li>
`
)
.join("")}
</ul>
</div>
<div class="activity-card-actions">
${
currentUser
? `
<button class="register-button" data-activity="${name}" ${
isFull ? "disabled" : ""
}>
${isFull ? "Activity Full" : "Register Student"}
</button>
`
: `
<div class="auth-notice">
Teachers can register students.
</div>
`
}
</div>
`;
// Add click handlers for delete buttons
const deleteButtons = activityCard.querySelectorAll(".delete-participant");
deleteButtons.forEach((button) => {
button.addEventListener("click", handleUnregister);
});
// Add click handler for register button (only when authenticated)
if (currentUser) {
const registerButton = activityCard.querySelector(".register-button");
if (!isFull) {
registerButton.addEventListener("click", () => {
openRegistrationModal(name);
});
}
}
activitiesList.appendChild(activityCard);
}
// Event listeners for search and filter
searchInput.addEventListener("input", (event) => {
searchQuery = event.target.value;
displayFilteredActivities();
});
searchButton.addEventListener("click", (event) => {
event.preventDefault();
searchQuery = searchInput.value;
displayFilteredActivities();
});
// Add event listeners to category filter buttons
categoryFilters.forEach((button) => {
button.addEventListener("click", () => {
// Update active class
categoryFilters.forEach((btn) => btn.classList.remove("active"));
button.classList.add("active");
// Update current filter and display filtered activities
currentFilter = button.dataset.category;
displayFilteredActivities();
});
});
// Add event listeners to day filter buttons
dayFilters.forEach((button) => {
button.addEventListener("click", () => {
// Update active class
dayFilters.forEach((btn) => btn.classList.remove("active"));
button.classList.add("active");
// Update current day filter and fetch activities
currentDay = button.dataset.day;
fetchActivities();
});
});
// Add event listeners for time filter buttons
timeFilters.forEach((button) => {
button.addEventListener("click", () => {
// Update active class
timeFilters.forEach((btn) => btn.classList.remove("active"));
button.classList.add("active");
// Update current time filter and fetch activities
currentTimeRange = button.dataset.time;
fetchActivities();
});
});
// Open registration modal
function openRegistrationModal(activityName) {
modalActivityName.textContent = activityName;
activityInput.value = activityName;
registrationModal.classList.remove("hidden");
// Add slight delay to trigger animation
setTimeout(() => {
registrationModal.classList.add("show");
}, 10);
}
// Close registration modal
function closeRegistrationModalHandler() {
registrationModal.classList.remove("show");
setTimeout(() => {
registrationModal.classList.add("hidden");
signupForm.reset();
}, 300);
}
// Event listener for close button
closeRegistrationModal.addEventListener(
"click",
closeRegistrationModalHandler
);
// Close modal when clicking outside of it
window.addEventListener("click", (event) => {
if (event.target === registrationModal) {
closeRegistrationModalHandler();
}
});
// Create and show confirmation dialog
function showConfirmationDialog(message, confirmCallback) {
// Create the confirmation dialog if it doesn't exist
let confirmDialog = document.getElementById("confirm-dialog");
if (!confirmDialog) {
confirmDialog = document.createElement("div");
confirmDialog.id = "confirm-dialog";
confirmDialog.className = "modal hidden";
confirmDialog.innerHTML = `
<div class="modal-content">
<h3>Confirm Action</h3>
<p id="confirm-message"></p>
<div style="display: flex; justify-content: flex-end; gap: 10px; margin-top: 20px;">
<button id="cancel-button" class="cancel-btn">Cancel</button>
<button id="confirm-button" class="confirm-btn">Confirm</button>
</div>
</div>
`;
document.body.appendChild(confirmDialog);
// Style the buttons
const cancelBtn = confirmDialog.querySelector("#cancel-button");
const confirmBtn = confirmDialog.querySelector("#confirm-button");
cancelBtn.style.backgroundColor = "#f1f1f1";
cancelBtn.style.color = "#333";
confirmBtn.style.backgroundColor = "#dc3545";
confirmBtn.style.color = "white";
}
// Set the message
const confirmMessage = document.getElementById("confirm-message");
confirmMessage.textContent = message;
// Show the dialog
confirmDialog.classList.remove("hidden");
setTimeout(() => {
confirmDialog.classList.add("show");
}, 10);
// Handle button clicks
const cancelButton = document.getElementById("cancel-button");
const confirmButton = document.getElementById("confirm-button");
// Remove any existing event listeners
const newCancelButton = cancelButton.cloneNode(true);
const newConfirmButton = confirmButton.cloneNode(true);
cancelButton.parentNode.replaceChild(newCancelButton, cancelButton);
confirmButton.parentNode.replaceChild(newConfirmButton, confirmButton);
// Add new event listeners
newCancelButton.addEventListener("click", () => {
confirmDialog.classList.remove("show");
setTimeout(() => {
confirmDialog.classList.add("hidden");
}, 300);
});
newConfirmButton.addEventListener("click", () => {
confirmCallback();
confirmDialog.classList.remove("show");
setTimeout(() => {
confirmDialog.classList.add("hidden");
}, 300);
});
// Close when clicking outside
confirmDialog.addEventListener("click", (event) => {
if (event.target === confirmDialog) {
confirmDialog.classList.remove("show");
setTimeout(() => {
confirmDialog.classList.add("hidden");
}, 300);
}
});
}
// Handle unregistration with confirmation
async function handleUnregister(event) {
// Check if user is authenticated
if (!currentUser) {
showMessage(
"You must be logged in as a teacher to unregister students.",
"error"
);
return;
}
const activity = event.target.dataset.activity;
const email = event.target.dataset.email;
// Show confirmation dialog
showConfirmationDialog(
`Are you sure you want to unregister ${email} from ${activity}?`,
async () => {
try {
const response = await fetch(
`/activities/${encodeURIComponent(
activity
)}/unregister?email=${encodeURIComponent(
email
)}&teacher_username=${encodeURIComponent(currentUser.username)}`,
{
method: "POST",
}
);
const result = await response.json();
if (response.ok) {
showMessage(result.message, "success");
// Refresh the activities list
fetchActivities();
} else {
showMessage(result.detail || "An error occurred", "error");
}
} catch (error) {
showMessage("Failed to unregister. Please try again.", "error");
console.error("Error unregistering:", error);
}
}
);
}
// Show message function
function showMessage(text, type) {
messageDiv.textContent = text;
messageDiv.className = `message ${type}`;
messageDiv.classList.remove("hidden");
// Hide message after 5 seconds
setTimeout(() => {
messageDiv.classList.add("hidden");
}, 5000);
}
// Handle form submission
signupForm.addEventListener("submit", async (event) => {
event.preventDefault();
// Check if user is authenticated
if (!currentUser) {
showMessage(
"You must be logged in as a teacher to register students.",
"error"
);
return;
}
const email = document.getElementById("email").value;
const activity = activityInput.value;
try {
const response = await fetch(
`/activities/${encodeURIComponent(
activity
)}/signup?email=${encodeURIComponent(
email
)}&teacher_username=${encodeURIComponent(currentUser.username)}`,
{
method: "POST",
}
);
const result = await response.json();
if (response.ok) {
showMessage(result.message, "success");
closeRegistrationModalHandler();
// Refresh the activities list after successful signup
fetchActivities();
} else {
showMessage(result.detail || "An error occurred", "error");
}
} catch (error) {
showMessage("Failed to sign up. Please try again.", "error");
console.error("Error signing up:", error);
}
});
// Expose filter functions to window for future UI control
window.activityFilters = {
setDayFilter,
setTimeRangeFilter,
};
// Initialize app
checkAuthentication();
initializeFilters();
fetchActivities();
});
| willingc/skills-introduction-to-repository-management | 0 | Exercise: introduction to repository management | JavaScript | willingc | Carol Willing | Willing Consulting |
src/static/index.html | HTML | <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mergington High School Activities</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<header>
<h1>Mergington High School</h1>
<h2>Extracurricular Activities</h2>
<div id="user-controls">
<div id="user-status">
<button id="login-button" class="icon-button">
<span class="user-icon">👤</span>
<span>Login</span>
</button>
<div id="user-info" class="hidden">
<span id="display-name"></span>
<button id="logout-button">Logout</button>
</div>
</div>
</div>
</header>
<main>
<section id="activities-container">
<div class="main-content-layout">
<!-- Left Sidebar for Filters -->
<aside class="sidebar-filters">
<h3>Filter Activities</h3>
<!-- Search Box -->
<div class="search-box">
<input
type="text"
id="activity-search"
placeholder="Search activities..."
/>
<button id="search-button" aria-label="Search">
<span class="search-icon">🔍</span>
</button>
</div>
<div class="filter-container">
<div class="filter-label">Filter by category:</div>
<div class="category-filters" id="category-filters">
<button class="category-filter active" data-category="all">
All
</button>
<button class="category-filter" data-category="sports">
Sports
</button>
<button class="category-filter" data-category="arts">
Arts
</button>
<button class="category-filter" data-category="academic">
Academic
</button>
<button class="category-filter" data-category="community">
Community
</button>
<button class="category-filter" data-category="technology">
Technology
</button>
</div>
</div>
<!-- Day Filter -->
<div class="filter-container day-filter-container">
<div class="filter-label">Filter by day:</div>
<div class="day-filters" id="day-filters">
<button class="day-filter active" data-day="">All Days</button>
<button class="day-filter" data-day="Monday">Monday</button>
<button class="day-filter" data-day="Tuesday">Tuesday</button>
<button class="day-filter" data-day="Wednesday">
Wednesday
</button>
<button class="day-filter" data-day="Thursday">Thursday</button>
<button class="day-filter" data-day="Friday">Friday</button>
<button class="day-filter" data-day="Saturday">Saturday</button>
<button class="day-filter" data-day="Sunday">Sunday</button>
</div>
</div>
<!-- Time Filter -->
<div class="filter-container time-filter-container">
<div class="filter-label">Filter by time:</div>
<div class="time-filters">
<button class="time-filter active" data-time="">
All Times
</button>
<button class="time-filter" data-time="morning">
Before School
</button>
<button class="time-filter" data-time="afternoon">
After School
</button>
<button class="time-filter" data-time="weekend">Weekend</button>
</div>
</div>
</aside>
<!-- Activities Content -->
<div class="activities-content">
<div id="activities-list">
<!-- Activities will be loaded here -->
<p>Loading activities...</p>
</div>
<div id="message" class="hidden message"></div>
</div>
</div>
</section>
</main>
<footer>
<p>© 2023 Mergington High School</p>
</footer>
<!-- Registration Modal -->
<div id="registration-modal" class="modal hidden">
<div class="modal-content">
<span class="close-modal">×</span>
<h3>Register for <span id="modal-activity-name"></span></h3>
<form id="signup-form">
<div class="form-group">
<label for="email">Student Email:</label>
<input
type="email"
id="email"
required
placeholder="your-email@mergington.edu"
/>
</div>
<input type="hidden" id="activity" value="" />
<button type="submit">Register</button>
</form>
</div>
</div>
<!-- Login Modal -->
<div id="login-modal" class="modal hidden">
<div class="modal-content">
<span class="close-login-modal">×</span>
<h3>Teacher Login</h3>
<form id="login-form">
<div class="form-group">
<label for="username">Username:</label>
<input
type="text"
id="username"
required
placeholder="Enter your username"
/>
</div>
<div class="form-group">
<label for="password">Password:</label>
<input
type="password"
id="password"
required
placeholder="Enter your password"
/>
</div>
<button type="submit">Login</button>
</form>
<div id="login-message" class="hidden message"></div>
</div>
</div>
<script src="app.js"></script>
</body>
</html>
| willingc/skills-introduction-to-repository-management | 0 | Exercise: introduction to repository management | JavaScript | willingc | Carol Willing | Willing Consulting |
src/static/styles.css | CSS | /* Color palette */
:root {
/* Primary colors */
--primary: #1a237e;
--primary-light: #534bae;
--primary-dark: #000051;
--primary-text: #ffffff;
/* Secondary colors */
--secondary: #ff6f00;
--secondary-light: #ffa040;
--secondary-dark: #c43e00;
--secondary-text: #ffffff;
/* Neutral colors */
--background: #f5f5f5;
--surface: #ffffff;
--text-primary: #333333;
--text-secondary: #666666;
--border: #e0e0e0;
--border-light: #f0f0f0;
--border-focus: #d0d0d0;
/* Feedback colors */
--success: #2e7d32;
--success-light: #e8f5e9;
--warning: #ff9800;
--warning-light: #fff3cd;
--error: #c62828;
--error-light: #ffebee;
--info: #0c5460;
--info-light: #d1ecf1;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: Arial, sans-serif;
}
body {
font-family: Arial, sans-serif;
line-height: 1.4;
color: var(--text-primary);
max-width: 1200px;
margin: 0 auto;
padding: 12px;
background-color: var(--background);
font-size: 0.9rem;
}
header {
text-align: center;
padding: 12px 0;
margin-bottom: 15px;
background-color: var(--primary);
color: var(--primary-text);
border-radius: 5px;
box-shadow: 0 3px 6px rgba(0, 0, 0, 0.16);
position: relative;
display: flex;
flex-direction: column;
align-items: center;
}
header h1 {
margin-bottom: 5px;
font-size: 1.6rem;
}
header h2 {
font-size: 1.2rem;
}
main {
display: flex;
flex-wrap: wrap;
justify-content: center;
}
section {
background-color: var(--surface);
padding: 15px;
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
width: 100%;
}
section h3 {
margin-bottom: 15px;
padding-bottom: 8px;
border-bottom: 1px solid var(--border);
color: var(--primary);
font-size: 1.1rem;
}
/* New Layout Styles */
.main-content-layout {
display: flex;
flex-direction: column;
gap: 15px;
}
.sidebar-filters {
padding: 15px;
background-color: var(--surface);
border-radius: 5px;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}
.sidebar-filters h3 {
margin-bottom: 15px;
padding-bottom: 8px;
border-bottom: 1px solid var(--border);
color: var(--primary);
font-size: 1.1rem;
}
.activities-content {
flex: 1;
}
/* Desktop layout */
@media (min-width: 768px) {
.main-content-layout {
flex-direction: row;
align-items: flex-start;
}
.sidebar-filters {
width: 200px; /* Reduced from 250px to 200px to make the sidebar narrower */
position: sticky;
top: 15px;
max-height: calc(100vh - 30px);
overflow-y: auto;
}
.activities-content {
flex: 1;
}
}
#activities-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
gap: 15px;
width: 100%;
}
.activity-card {
padding: 12px;
border: 1px solid var(--border);
border-radius: 6px;
background-color: var(--surface);
display: flex;
flex-direction: column;
height: 100%;
transition: all 0.3s ease;
box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05);
position: relative;
overflow: hidden;
font-size: 0.85rem;
}
.activity-card:hover {
transform: translateY(-5px);
box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
border-color: var(--border-focus);
}
.activity-card h4 {
margin-bottom: 8px;
color: var(--primary);
font-size: 1rem;
letter-spacing: 0.3px;
padding-bottom: 6px;
border-bottom: 1px solid var(--border-light);
}
.activity-card p {
margin-bottom: 8px;
line-height: 1.4;
}
.activity-card-actions {
margin-top: auto;
padding-top: 10px;
display: flex;
justify-content: center;
}
/* Activity Tag */
.activity-tag {
position: absolute;
top: 8px;
right: 8px;
background: #e8eaf6;
color: #3949ab;
font-size: 0.65rem;
font-weight: bold;
padding: 2px 6px;
border-radius: 10px;
text-transform: uppercase;
letter-spacing: 0.3px;
}
/* Capacity Indicator */
.capacity-container {
margin: 8px 0;
width: 100%;
}
.capacity-bar-bg {
height: 6px;
background-color: var(--border-light);
border-radius: 3px;
overflow: hidden;
}
.capacity-text {
display: flex;
justify-content: space-between;
margin-top: 3px;
font-size: 0.7rem;
color: var(--text-secondary);
}
.capacity-full .capacity-bar-fill {
background-color: var(--error);
}
.capacity-near-full .capacity-bar-fill {
background-color: var(--warning);
}
.capacity-available .capacity-bar-fill {
background-color: var(--success);
}
/* Participants list */
.participants-list {
margin-top: 8px;
padding-top: 8px;
border-top: 1px solid var(--border-light);
}
.participants-list h5 {
color: var(--primary);
margin-bottom: 5px;
font-size: 0.8em;
}
.participants-list ul {
list-style-type: none;
padding-left: 0;
margin: 0;
max-height: 100px;
}
.participants-list li {
padding: 2px 0;
color: var(--text-secondary);
font-size: 0.8em;
display: flex;
justify-content: space-between;
align-items: center;
}
/* Buttons */
.register-button {
background: linear-gradient(145deg, var(--secondary), var(--secondary-dark));
color: var(--secondary-text);
margin-top: 10px;
padding: 6px 12px;
width: 100%;
font-weight: bold;
border-radius: 20px;
box-shadow: 0 2px 4px rgba(255, 111, 0, 0.2);
transition: all 0.3s ease;
display: flex;
justify-content: center;
align-items: center;
font-size: 0.85rem;
letter-spacing: 0.3px;
text-transform: uppercase;
border: none;
}
button {
background-color: var(--primary);
color: white;
border: none;
padding: 6px 12px;
font-size: 0.85rem;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.2s;
}
/* Tooltip styles */
.tooltip {
position: relative;
display: inline-block;
cursor: pointer;
}
.tooltip .tooltip-text {
visibility: hidden;
background-color: rgba(33, 33, 33, 0.9);
color: #fff;
text-align: center;
padding: 8px 12px;
border-radius: 4px;
font-size: 0.8rem;
position: absolute;
z-index: 1;
bottom: 125%;
left: 50%;
transform: translateX(-50%);
opacity: 0;
transition: opacity 0.2s, visibility 0.2s;
width: max-content;
max-width: 250px;
pointer-events: none;
box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
}
.tooltip:hover .tooltip-text {
visibility: visible;
opacity: 1;
}
/* Special positioning for delete participant tooltip */
.delete-participant {
cursor: pointer;
}
.delete-participant .tooltip-text {
left: auto;
right: calc(100% + 8px);
top: 50%;
bottom: auto;
transform: translateY(-50%);
white-space: nowrap;
}
/* Activity skeletons for loading state */
.skeleton-card {
padding: 12px;
border: 1px solid var(--border);
border-radius: 6px;
background-color: var(--surface);
display: flex;
flex-direction: column;
height: 180px;
position: relative;
overflow: hidden;
}
.skeleton-line {
height: 10px;
margin-bottom: 8px;
background: linear-gradient(
90deg,
var(--border-light) 25%,
var(--border) 50%,
var(--border-light) 75%
);
background-size: 200% 100%;
border-radius: 3px;
animation: shimmer 1.5s infinite;
}
.skeleton-title {
height: 18px;
width: 70%;
margin-bottom: 10px;
}
.skeleton-text {
width: 100%;
}
.skeleton-text.short {
width: 60%;
}
@keyframes shimmer {
0% {
background-position: -200% 0;
}
100% {
background-position: 200% 0;
}
}
/* Modal animation */
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
opacity: 0;
transition: opacity 0.3s ease;
}
.modal.show {
opacity: 1;
}
.modal-content {
background-color: var(--surface);
padding: 18px;
border-radius: 5px;
width: 90%;
max-width: 350px;
position: relative;
transform: translateY(-20px);
transition: transform 0.3s ease;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
border: 1px solid var(--border);
}
.modal.show .modal-content {
transform: translateY(0);
}
.close-modal,
.close-login-modal {
position: absolute;
right: 12px;
top: 8px;
font-size: 18px;
cursor: pointer;
color: var(--text-secondary);
line-height: 1;
}
/* Login modal specific styling */
#login-modal .modal-content h3 {
color: var(--primary);
font-size: 1.2rem;
margin-bottom: 15px;
text-align: center;
}
/* Hidden class - critical for showing/hiding elements */
.hidden {
display: none !important;
}
/* More compact no-results message */
.no-results {
text-align: center;
padding: 12px;
color: var(--text-secondary);
background-color: var(--surface);
border-radius: 6px;
border: 1px dashed var(--border);
margin: 10px 0;
font-size: 0.85rem;
}
footer {
text-align: center;
margin-top: 20px;
padding: 10px;
color: var(--text-secondary);
font-size: 0.8rem;
}
/* Search and Filter Components - Updated for Sidebar */
.search-box {
display: flex;
width: 100%;
margin-bottom: 15px;
}
.search-box input {
flex: 1;
min-width: 0; /* Add this to prevent input from overflowing */
padding: 6px 10px;
border: 1px solid var(--border);
border-right: none;
border-radius: 20px 0 0 20px;
font-size: 0.85rem;
transition: all 0.3s ease;
}
.search-box input:focus {
outline: none;
border-color: var(--primary-light);
box-shadow: 0 0 0 2px rgba(83, 75, 174, 0.1);
}
.search-box button {
width: 36px;
height: 100%; /* Make button match input height */
min-height: 32px; /* Ensure minimum clickable area */
background: var(--primary);
color: white;
border: none;
border-radius: 0 20px 20px 0;
cursor: pointer;
transition: background-color 0.3s ease;
padding: 0;
display: flex;
align-items: center;
justify-content: center;
}
.search-box button:hover {
background-color: var(--primary-light);
}
.search-icon {
font-size: 1rem;
}
.filter-container {
margin-bottom: 15px;
display: flex;
flex-direction: column;
gap: 6px;
}
.filter-label {
font-weight: 600;
color: var(--text-primary);
font-size: 0.8rem;
}
.category-filters,
.day-filters,
.time-filters {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.category-filter,
.day-filter,
.time-filter {
background-color: var(--background);
border: 1px solid var(--border);
color: var(--text-primary);
padding: 4px 10px;
border-radius: 15px;
font-size: 0.75rem;
cursor: pointer;
transition: all 0.2s ease;
}
.category-filter.active,
.day-filter.active,
.time-filter.active {
background-color: var(--primary);
color: white;
border-color: var(--primary-dark);
}
.category-filter:hover,
.day-filter:hover,
.time-filter:hover {
background-color: var(--primary-light);
color: white;
}
.time-filters {
width: 100%;
}
.reset-button {
background-color: var(--border);
color: var(--text-primary);
padding: 5px 12px;
border-radius: 15px;
font-size: 0.8rem;
font-weight: 500;
cursor: pointer;
transition: all 0.2s ease;
align-self: flex-start;
}
.reset-button:hover {
background-color: var(--border-focus);
}
/* Responsive adjustments for mobile */
@media (max-width: 767px) {
.sidebar-filters {
margin-bottom: 15px;
}
.main-content-layout {
flex-direction: column;
}
#activities-list {
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
}
.sidebar-filters {
width: 100%;
}
}
/* User controls in header */
#user-controls {
position: absolute;
top: 10px;
right: 15px;
}
#user-status {
display: flex;
align-items: center;
}
#user-info {
display: flex;
align-items: center;
gap: 10px;
}
#display-name {
margin-right: 5px;
font-weight: 500;
}
.icon-button {
display: flex;
align-items: center;
gap: 5px;
background-color: rgba(255, 255, 255, 0.2);
border-radius: 20px;
padding: 4px 12px;
font-size: 0.85rem;
transition: background-color 0.2s;
}
.icon-button:hover {
background-color: rgba(255, 255, 255, 0.3);
}
.user-icon {
font-size: 1rem;
}
#logout-button {
padding: 3px 10px;
background-color: rgba(255, 255, 255, 0.2);
font-size: 0.8rem;
border-radius: 20px;
}
#logout-button:hover {
background-color: rgba(255, 255, 255, 0.3);
}
| willingc/skills-introduction-to-repository-management | 0 | Exercise: introduction to repository management | JavaScript | willingc | Carol Willing | Willing Consulting |
notebooks/app.py | Python | import marimo
__generated_with = "0.10.12"
app = marimo.App(width="medium")
@app.cell
def _():
import marimo as mo
mo.md("Hello")
return (mo,)
@app.cell
def test_cell():
from utils import add
assert add(1, 2) == 3
assert 2 == 2
return
if __name__ == "__main__":
app.run()
| willingc/test-marimo | 0 | Python | willingc | Carol Willing | Willing Consulting | |
notebooks/notebook.py | Python | import marimo
__generated_with = "0.13.10"
app = marimo.App(width="medium")
@app.cell
def _():
import marimo as mo
return (mo,)
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
# A marimo notebook
You can import your library code.
"""
)
return
@app.cell
def _():
from utils import add
return (add,)
@app.cell
def _(add):
add(1, 2)
return
if __name__ == "__main__":
app.run()
| willingc/test-marimo | 0 | Python | willingc | Carol Willing | Willing Consulting | |
src/utils.py | Python | def add(a: int, b: int) -> int:
return a + b
def subtract(a: int, b: int) -> int:
return a - b
| willingc/test-marimo | 0 | Python | willingc | Carol Willing | Willing Consulting | |
tests/test_sample.py | Python | from utils import add, subtract
def test_add():
assert add(1, 2) == 3
def test_subtract():
assert subtract(1, 2) == -1
| willingc/test-marimo | 0 | Python | willingc | Carol Willing | Willing Consulting | |
examples/marimo/untitled.py | Python | import marimo
__generated_with = "0.13.11"
app = marimo.App()
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
# Vectors and Linear Algebra
A *vector* is an ordered array of numbers (`list`) where each number has an assigned place.
Vectors are used to represent points in vector space.
Vectors must only contain numerical, usually floats.
Vectors in the same space must have the same number of dimensions.
"""
)
return
@app.cell
def _():
import marimo as mo
return (mo,)
if __name__ == "__main__":
app.run()
| willingc/tidy-nb | 1 | Utilties to convert python files to and from notebooks | Python | willingc | Carol Willing | Willing Consulting |
examples/marimo/vectors.py | Python | import marimo
__generated_with = "0.13.11"
app = marimo.App()
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
# Vectors and Linear Algebra
A *vector* is an ordered array of numbers (`list`) where each number has an assigned place.
Vectors are used to represent points in vector space.
Vectors must only contain numerical, usually floats.
Vectors in the same space must have the same number of dimensions.
"""
)
return
@app.cell
def _():
import numpy as np
return (np,)
@app.cell
def _(np):
np.array(range(4))
return
@app.cell
def _(np):
x = np.array(range(4))
x
return (x,)
@app.cell
def _(x):
x[3] = 4
return
@app.cell
def _(x):
x
return
@app.cell
def _(x):
x * 2
return
@app.cell(hide_code=True)
def _(mo):
mo.md(
r"""
## Vector length and normalization
length is also called *norm*
square each and take the root of the sum
"""
)
return
@app.cell
def _(np):
x_1 = np.array([3, 4])
return (x_1,)
@app.cell
def _(np, x_1):
np.linalg.norm(x_1)
return
@app.cell
def _(x_1):
y = x_1 * 2
return (y,)
@app.cell
def _(y):
y
return
@app.cell
def _(np, y):
np.linalg.norm(y)
return
@app.cell
def _(np, x_1):
x_normalized = x_1 / np.linalg.norm(x_1)
return (x_normalized,)
@app.cell
def _(x_normalized):
x_normalized
return
@app.cell
def _(np, x_normalized):
np.linalg.norm(x_normalized)
return
@app.cell(hide_code=True)
def _(mo):
mo.md(r"""Normalization scales the vector so all its dimensions are less than 1. Makes it easier to compute cosine distance between to vectors.""")
return
@app.cell
def _():
import marimo as mo
return (mo,)
if __name__ == "__main__":
app.run()
| willingc/tidy-nb | 1 | Utilties to convert python files to and from notebooks | Python | willingc | Carol Willing | Willing Consulting |
hello.py | Python | def main():
print("Hello from tidy-nb!")
if __name__ == "__main__":
main()
| willingc/tidy-nb | 1 | Utilties to convert python files to and from notebooks | Python | willingc | Carol Willing | Willing Consulting |
src/jupyter_to_marimo.py | Python | #!/usr/bin/env python3
"""
Convert Jupyter notebook (.ipynb) to marimo notebook (.py) format.
Usage:
python jupyter_to_marimo.py input.ipynb output.py
"""
import json
import re
import sys
from pathlib import Path
from typing import List, Dict, Any, Set
def sanitize_function_name(name: str) -> str:
"""Convert a string to a valid Python function name."""
# Replace invalid characters with underscore
name = re.sub(r'[^a-zA-Z0-9_]', '_', name)
# Ensure it starts with a letter or underscore
if name and name[0].isdigit():
name = f'_{name}'
# Ensure it's not empty
if not name:
name = 'cell'
return name
def extract_variables(code: str) -> Set[str]:
"""
Extract variable names that are assigned in the code.
This helps determine what should be returned from the cell.
"""
import ast
variables = set()
try:
tree = ast.parse(code)
for node in ast.walk(tree):
if isinstance(node, ast.Assign):
for target in node.targets:
if isinstance(target, ast.Name):
variables.add(target.id)
elif isinstance(target, ast.Tuple) or isinstance(target, ast.List):
for elt in target.elts:
if isinstance(elt, ast.Name):
variables.add(elt.id)
elif isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name):
variables.add(node.target.id)
elif isinstance(node, ast.AugAssign) and isinstance(node.target, ast.Name):
variables.add(node.target.id)
except SyntaxError:
pass
return variables
def detect_imports(code: str) -> Set[str]:
"""Detect import statements and imported names."""
import ast
imports = set()
try:
tree = ast.parse(code)
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
name = alias.asname if alias.asname else alias.name
imports.add(name.split('.')[0]) # Get the top-level module
elif isinstance(node, ast.ImportFrom):
for alias in node.names:
name = alias.asname if alias.asname else alias.name
if name != '*':
imports.add(name)
except SyntaxError:
pass
return imports
def determine_return_variables(code: str, cell_index: int) -> List[str]:
"""
Determine what variables should be returned from a marimo cell.
"""
variables = extract_variables(code)
imports = detect_imports(code)
# Filter out common temporary variables and imports
filtered_vars = []
temp_patterns = {'_', 'temp', 'tmp', 'i', 'j', 'k', 'idx', 'index'}
for var in variables:
if (var not in imports and
var not in temp_patterns and
not var.startswith('_') and
not var.isupper()): # Skip constants
filtered_vars.append(var)
# Sort for consistency
return sorted(filtered_vars)
def process_code_cell(source: List[str], cell_index: int) -> str:
"""
Convert a Jupyter code cell to a marimo cell function.
"""
# Join source lines
code = '\n'.join(source).strip()
if not code:
return ""
# Generate function name
func_name = f"cell_{cell_index + 1}"
# Determine return variables
return_vars = determine_return_variables(code, cell_index)
# Create the marimo cell
lines = ["@app.cell"]
lines.append(f"def {func_name}():")
# Indent the code
for line in code.split('\n'):
if line.strip():
lines.append(f" {line}")
else:
lines.append("")
# Add return statement if there are variables to return
if return_vars:
if len(return_vars) == 1:
lines.append(f" return {return_vars[0]}")
else:
vars_str = ', '.join(return_vars)
lines.append(f" return {vars_str}")
else:
lines.append(" return")
return '\n'.join(lines)
def process_markdown_cell(source: List[str]) -> str:
"""
Convert a Jupyter markdown cell to a marimo markdown cell.
"""
# Join source lines
content = ''.join(source).strip()
if not content:
return ""
# Escape triple quotes in the content
content = content.replace('"""', '\\"\\"\\"')
lines = ["@app.cell"]
lines.append("def markdown_cell():")
lines.append(" mo.md(")
lines.append(" r\"\"\"")
# Add markdown content with proper indentation
for line in content.split('\n'):
lines.append(f" {line}")
lines.append(" \"\"\"")
lines.append(" )")
lines.append(" return")
return '\n'.join(lines)
def convert_jupyter_to_marimo(input_path: str, output_path: str) -> None:
"""
Convert a Jupyter notebook to marimo format.
"""
input_file = Path(input_path)
output_file = Path(output_path)
if not input_file.exists():
print(f"Error: Input file '{input_path}' not found.")
return
# Read the Jupyter notebook
try:
with open(input_file, 'r', encoding='utf-8') as f:
notebook = json.load(f)
except Exception as e:
print(f"Error reading input file: {e}")
return
# Validate notebook format
if 'cells' not in notebook:
print("Error: Invalid Jupyter notebook format (no 'cells' key found).")
return
# Generate marimo code
marimo_lines = []
# Add marimo imports and app initialization
marimo_lines.extend([
"import marimo",
"",
"__generated_with = \"0.8.0\"",
"app = marimo.App(width=\"medium\")",
"",
])
# Track if we need to import mo for markdown cells
has_markdown = any(cell.get('cell_type') == 'markdown' for cell in notebook['cells'])
if has_markdown:
marimo_lines.extend([
"@app.cell",
"def imports():",
" import marimo as mo",
" return mo,",
"",
])
# Process each cell
code_cell_count = 0
for i, cell in enumerate(notebook['cells']):
cell_type = cell.get('cell_type', 'code')
source = cell.get('source', [])
if cell_type == 'code':
code_cell_count += 1
cell_content = process_code_cell(source, code_cell_count - 1)
if cell_content:
marimo_lines.append(cell_content)
marimo_lines.append("")
elif cell_type == 'markdown':
cell_content = process_markdown_cell(source)
if cell_content:
marimo_lines.append(cell_content)
marimo_lines.append("")
# Add the main execution block
marimo_lines.extend([
"",
"if __name__ == \"__main__\":",
" app.run()"
])
# Write the marimo notebook
try:
with open(output_file, 'w', encoding='utf-8') as f:
f.write('\n'.join(marimo_lines))
print(f"Successfully converted '{input_path}' to '{output_path}'")
print(f"Processed {len(notebook['cells'])} cells ({code_cell_count} code cells).")
if has_markdown:
print("Note: Markdown cells converted to mo.md() calls.")
except Exception as e:
print(f"Error writing output file: {e}")
def analyze_notebook(input_path: str) -> None:
"""
Analyze a Jupyter notebook and show conversion preview.
"""
input_file = Path(input_path)
if not input_file.exists():
print(f"Error: Input file '{input_path}' not found.")
return
try:
with open(input_file, 'r', encoding='utf-8') as f:
notebook = json.load(f)
except Exception as e:
print(f"Error reading input file: {e}")
return
if 'cells' not in notebook:
print("Error: Invalid Jupyter notebook format.")
return
print(f"Jupyter Notebook Analysis: {input_path}")
print("=" * 50)
code_cells = 0
markdown_cells = 0
raw_cells = 0
for i, cell in enumerate(notebook['cells']):
cell_type = cell.get('cell_type', 'unknown')
source_lines = len(cell.get('source', []))
if cell_type == 'code':
code_cells += 1
elif cell_type == 'markdown':
markdown_cells += 1
elif cell_type == 'raw':
raw_cells += 1
print(f"Cell {i+1}: {cell_type} ({source_lines} lines)")
print(f"\nSummary:")
print(f"- Code cells: {code_cells}")
print(f"- Markdown cells: {markdown_cells}")
print(f"- Raw cells: {raw_cells}")
print(f"- Total cells: {len(notebook['cells'])}")
def main():
"""Main function to handle command line arguments."""
if len(sys.argv) < 2:
print("Usage:")
print(" python jupyter_to_marimo.py <input.ipynb> <output.py> # Convert notebook")
print(" python jupyter_to_marimo.py --analyze <input.ipynb> # Analyze notebook")
print("\nExamples:")
print(" python jupyter_to_marimo.py my_notebook.ipynb my_notebook.py")
print(" python jupyter_to_marimo.py --analyze my_notebook.ipynb")
sys.exit(1)
if sys.argv[1] == "--analyze":
if len(sys.argv) != 3:
print("Usage: python jupyter_to_marimo.py --analyze <input.ipynb>")
sys.exit(1)
analyze_notebook(sys.argv[2])
else:
if len(sys.argv) != 3:
print("Usage: python jupyter_to_marimo.py <input.ipynb> <output.py>")
sys.exit(1)
input_path = sys.argv[1]
output_path = sys.argv[2]
convert_jupyter_to_marimo(input_path, output_path)
if __name__ == "__main__":
main()
| willingc/tidy-nb | 1 | Utilties to convert python files to and from notebooks | Python | willingc | Carol Willing | Willing Consulting |
src/marimo_to_jupyter.py | Python | #!/usr/bin/env python3
"""
Convert marimo notebook (.py) to Jupyter notebook (.ipynb) format.
Usage:
python marimo_to_jupyter.py input.py output.ipynb
"""
import ast
import json
import re
import sys
from pathlib import Path
from typing import List, Dict, Any
def parse_marimo_notebook(content: str) -> List[Dict[str, Any]]:
"""
Parse a marimo notebook and extract cells.
Marimo notebooks use @app.cell decorators to define cells.
"""
cells = []
# Parse the Python AST
try:
tree = ast.parse(content)
except SyntaxError as e:
print(f"Error parsing Python file: {e}")
return cells
# Find all function definitions with @app.cell decorator
for node in ast.walk(tree):
if isinstance(node, ast.FunctionDef):
# Check if function has @app.cell decorator
has_app_cell = any(
(isinstance(decorator, ast.Attribute) and
isinstance(decorator.value, ast.Name) and
decorator.value.id == 'app' and
decorator.attr == 'cell') or
(isinstance(decorator, ast.Call) and
isinstance(decorator.func, ast.Attribute) and
isinstance(decorator.func.value, ast.Name) and
decorator.func.value.id == 'app' and
decorator.func.attr == 'cell')
for decorator in node.decorator_list
)
if has_app_cell:
# Extract the function body
cell_source = ast.get_source_segment(content, node)
if cell_source:
# Remove the function definition wrapper and decorator
lines = cell_source.split('\n')
# Find the start of the function body (after def line)
body_start = 0
for i, line in enumerate(lines):
if line.strip().startswith('def '):
body_start = i + 1
break
# Extract function body and remove indentation
body_lines = lines[body_start:]
if body_lines:
# Remove common indentation
min_indent = float('inf')
for line in body_lines:
if line.strip(): # Skip empty lines
indent = len(line) - len(line.lstrip())
min_indent = min(min_indent, indent)
if min_indent == float('inf'):
min_indent = 0
# Remove the common indentation
cleaned_lines = []
for line in body_lines:
if line.strip():
cleaned_lines.append(line[min_indent:])
else:
cleaned_lines.append('')
cell_content = '\n'.join(cleaned_lines).strip()
# Remove return statement if it's the last line
lines = cell_content.split('\n')
if lines and lines[-1].strip().startswith('return '):
lines[-1] = lines[-1].replace('return ', '', 1)
cell_content = '\n'.join(lines)
cells.append({
'cell_type': 'code',
'source': cell_content,
'metadata': {},
'execution_count': None,
'outputs': []
})
# If no cells found with decorators, try to split by function definitions
if not cells:
cells = fallback_parse(content)
return cells
def fallback_parse(content: str) -> List[Dict[str, Any]]:
"""
Fallback parser for marimo files that don't use standard decorators.
Split by function definitions or other patterns.
"""
cells = []
# Split by function definitions
functions = re.split(r'\n(?=def\s+\w+)', content)
for func in functions:
func = func.strip()
if func:
# Skip imports and module-level code in the first section
if not func.startswith('def '):
# This might be imports or module-level code
if any(line.strip().startswith(('import ', 'from ')) for line in func.split('\n')):
cell_type = 'code'
else:
cell_type = 'code'
else:
cell_type = 'code'
cells.append({
'cell_type': cell_type,
'source': func,
'metadata': {},
'execution_count': None,
'outputs': []
})
return cells
def create_jupyter_notebook(cells: List[Dict[str, Any]]) -> Dict[str, Any]:
"""
Create a Jupyter notebook structure from parsed cells.
"""
notebook = {
'cells': [],
'metadata': {
'kernelspec': {
'display_name': 'Python 3',
'language': 'python',
'name': 'python3'
},
'language_info': {
'name': 'python',
'version': '3.8.0',
'mimetype': 'text/x-python',
'codemirror_mode': {
'name': 'ipython',
'version': 3
},
'pygments_lexer': 'ipython3',
'nbconvert_exporter': 'python',
'file_extension': '.py'
}
},
'nbformat': 4,
'nbformat_minor': 4
}
for cell in cells:
jupyter_cell = {
'cell_type': cell['cell_type'],
'metadata': cell['metadata'],
'source': cell['source'].split('\n') if cell['source'] else ['']
}
if cell['cell_type'] == 'code':
jupyter_cell['execution_count'] = cell['execution_count']
jupyter_cell['outputs'] = cell['outputs']
notebook['cells'].append(jupyter_cell)
return notebook
def convert_marimo_to_jupyter(input_path: str, output_path: str) -> None:
"""
Convert a marimo notebook to Jupyter format.
"""
input_file = Path(input_path)
output_file = Path(output_path)
if not input_file.exists():
print(f"Error: Input file '{input_path}' not found.")
return
# Read the marimo notebook
try:
with open(input_file, 'r', encoding='utf-8') as f:
content = f.read()
except Exception as e:
print(f"Error reading input file: {e}")
return
# Parse the marimo notebook
cells = parse_marimo_notebook(content)
if not cells:
print("Warning: No cells found in the marimo notebook.")
# Create a single cell with the entire content
cells = [{
'cell_type': 'code',
'source': content,
'metadata': {},
'execution_count': None,
'outputs': []
}]
# Create Jupyter notebook structure
notebook = create_jupyter_notebook(cells)
# Write the Jupyter notebook
try:
with open(output_file, 'w', encoding='utf-8') as f:
json.dump(notebook, f, indent=2, ensure_ascii=False)
print(f"Successfully converted '{input_path}' to '{output_path}'")
print(f"Created {len(cells)} cells in the Jupyter notebook.")
except Exception as e:
print(f"Error writing output file: {e}")
def main():
"""Main function to handle command line arguments."""
if len(sys.argv) != 3:
print("Usage: python marimo_to_jupyter.py <input.py> <output.ipynb>")
print("\nExample:")
print(" python marimo_to_jupyter.py my_notebook.py my_notebook.ipynb")
sys.exit(1)
input_path = sys.argv[1]
output_path = sys.argv[2]
convert_marimo_to_jupyter(input_path, output_path)
if __name__ == "__main__":
main()
| willingc/tidy-nb | 1 | Utilties to convert python files to and from notebooks | Python | willingc | Carol Willing | Willing Consulting |
src/tidy_nb/__init__.py | Python | """
Tidy NB - A tool for tidying notebooks.
"""
__version__ = '0.1.0' | willingc/tidy-nb | 1 | Utilties to convert python files to and from notebooks | Python | willingc | Carol Willing | Willing Consulting |
src/tidy_nb/__main__.py | Python | """Allow running tidy_nb as a script."""
from .cli import main
raise SystemExit(main()) | willingc/tidy-nb | 1 | Utilties to convert python files to and from notebooks | Python | willingc | Carol Willing | Willing Consulting |
src/tidy_nb/cli.py | Python | """CLI for tidy_nb."""
from __future__ import annotations
import argparse
from typing import TYPE_CHECKING
from . import __doc__ as pkg_description
from . import __version__
if TYPE_CHECKING:
from typing import Sequence
PROG = __package__
def main(argv: Sequence[str] | None = None) -> int:
"""Main entry point for the tidy_nb CLI."""
parser = argparse.ArgumentParser(prog=PROG, description=pkg_description)
parser.add_argument('notebooks', nargs='*', help='Notebooks to tidy.')
parser.add_argument(
'--version',
action='version',
version=f'%(prog)s {__version__}',
help='Show the version and exit.',
)
args = parser.parse_args(argv)
nb_processed = None
for nb in args.notebooks:
print(f'Tidying notebook: {nb}')
if nb_processed:
return 1
return 0
if __name__ == '__main__':
raise SystemExit(main()) | willingc/tidy-nb | 1 | Utilties to convert python files to and from notebooks | Python | willingc | Carol Willing | Willing Consulting |
tests/test_basic.py | Python | import pytest
def test_pulse():
pass
| willingc/tidy-nb | 1 | Utilties to convert python files to and from notebooks | Python | willingc | Carol Willing | Willing Consulting |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.