repo
stringclasses
254 values
file_path
stringlengths
29
241
code
stringlengths
100
233k
tokens
int64
14
69.4k
matter-ecs/matter
matter-ecs-matter-f31981b/lib/topoRuntime.luau
local stack = {} local function newStackFrame(node) return { node = node, accessedKeys = {}, } end local function cleanup() local currentFrame = stack[#stack] for baseKey, state in pairs(currentFrame.node.system) do for key, value in pairs(state.storage) do if not currentFrame.accessedKeys[baseKey] or not currentFrame.accessedKeys[baseKey][key] then local cleanupCallback = state.cleanupCallback if cleanupCallback then local shouldAbortCleanup = cleanupCallback(value) if shouldAbortCleanup then continue end end state.storage[key] = nil end end end end local function start(node, fn) table.insert(stack, newStackFrame(node)) fn() cleanup() table.remove(stack, #stack) end local function withinTopoContext() return #stack ~= 0 end local function useFrameState() return stack[#stack].node.frame end local function useCurrentSystem() if #stack == 0 then return end return stack[#stack].node.currentSystem end --[=[ @within Matter :::tip **Don't use this function directly in your systems.** This function is used for implementing your own topologically-aware functions. It should not be used in your systems directly. You should use this function to implement your own utilities, similar to `useEvent` and `useThrottle`. ::: `useHookState` does one thing: it returns a table. An empty, pristine table. Here's the cool thing though: it always returns the *same* table, based on the script and line where *your function* (the function calling `useHookState`) was called. ### Uniqueness If your function is called multiple times from the same line, perhaps within a loop, the default behavior of `useHookState` is to uniquely identify these by call count, and will return a unique table for each call. However, you can override this behavior: you can choose to key by any other value. This means that in addition to script and line number, the storage will also only return the same table if the unique value (otherwise known as the "discriminator") is the same. ### Cleaning up As a second optional parameter, you can pass a function that is automatically invoked when your storage is about to be cleaned up. This happens when your function (and by extension, `useHookState`) ceases to be called again next frame (keyed by script, line number, and discriminator). Your cleanup callback is passed the storage table that's about to be cleaned up. You can then perform cleanup work, like disconnecting events. *Or*, you could return `true`, and abort cleaning up altogether. If you abort cleanup, your storage will stick around another frame (even if your function wasn't called again). This can be used when you know that the user will (or might) eventually call your function again, even if they didn't this frame. (For example, caching a value for a number of seconds). If cleanup is aborted, your cleanup function will continue to be called every frame, until you don't abort cleanup, or the user actually calls your function again. ### Example: useThrottle This is the entire implementation of the built-in `useThrottle` function: ```lua local function cleanup(storage) return os.clock() < storage.expiry end local function useThrottle(seconds, discriminator) local storage = useHookState(discriminator, cleanup) if storage.time == nil or os.clock() - storage.time >= seconds then storage.time = os.clock() storage.expiry = os.clock() + seconds return true end return false end ``` A lot of talk for something so simple, right? @param discriminator? any -- A unique value to additionally key by @param cleanupCallback (storage: {}) -> boolean? -- A function to run when the storage for this hook is cleaned up ]=] local function useHookState(discriminator, cleanupCallback): {} local file, line = debug.info(3, "sl") local fn = debug.info(2, "f") local baseKey = string.format("%s:%s:%d", tostring(fn), file, line) local currentFrame = stack[#stack] if currentFrame == nil then error("Attempt to access topologically-aware storage outside of a Loop-system context.", 3) end if not currentFrame.accessedKeys[baseKey] then currentFrame.accessedKeys[baseKey] = {} end local accessedKeys = currentFrame.accessedKeys[baseKey] local key = #accessedKeys if discriminator ~= nil then if type(discriminator) == "number" then discriminator = tostring(discriminator) end key = discriminator end accessedKeys[key] = true if not currentFrame.node.system[baseKey] then currentFrame.node.system[baseKey] = { storage = {}, cleanupCallback = cleanupCallback, } end local storage = currentFrame.node.system[baseKey].storage if not storage[key] then storage[key] = {} end return storage[key] end return { start = start, useHookState = useHookState, useFrameState = useFrameState, useCurrentSystem = useCurrentSystem, withinTopoContext = withinTopoContext, }
1,192
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lune/lib/parseArgs.luau
local FLAG_PATTERN = "%-%-(%w+)" local FLAG_ALL_IN_ONE_PATTERN = `{FLAG_PATTERN}=(%w+)` local function parseArgs(args: { string }) local parsedArgs: { [string]: string | boolean | number } = {} local skipNextToken = false for index, token in args do -- When `--foo bar` is used, these are both individual tokens that we -- process at the same time. In those cases, we need to skip the next -- token (`bar`) since it has already been picked up as a flag value if skipNextToken then skipNextToken = false continue end -- handle `--foo=bar` pattern local flagName, flagValue = token:match(FLAG_ALL_IN_ONE_PATTERN) if flagName and flagValue then parsedArgs[flagName] = flagValue continue end flagName = token:match(FLAG_PATTERN) if flagName then local nextToken = args[index + 1] if nextToken then -- When processing `--foo` in `--foo --bar` treat it like a boolean if nextToken:match(FLAG_PATTERN) then parsedArgs[flagName] = true else parsedArgs[flagName] = nextToken skipNextToken = true end else parsedArgs[flagName] = true end else error(`something went wrong: {token}`) end end return parsedArgs end return parseArgs
354
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/build.luau
local FlipbookBatteries = require("@luaupkg/flipbook-batteries") local cli = require("@luaupkg/batteries/cli") local fs = require("@std/fs") local path = require("@std/path") local pp = require("@luaupkg/batteries/pp") local process = require("@std/process") local richterm = require("@luaupkg/batteries/richterm") local toml = require("@luaupkg/batteries/toml") local buildSystem = require("@scripts/lib/build-system") local createRojoProjectAsync = require("@scripts/lib/createRojoProjectAsync") local getStudioPluginsPath = require("@scripts/lib/getStudioPluginsPath") local project = require("@repo/project") local copyInto = FlipbookBatteries.copyInto local dotenv = FlipbookBatteries.dotenv local run = FlipbookBatteries.run local watch = FlipbookBatteries.watch local WALLY_MANIFEST_PATH = path.resolve("wally.toml") type BuildContext = buildSystem.BuildContext dotenv() local args = cli.parser() args:add("script", "positional", { help = "Path to the script being run. Provided automatically by Lute", }) args:add("subcommand", "positional", { help = `Can be "plugin" or "workspace"`, default = "plugin", }) args:add("channel", "option", { help = "Channel to build for", aliases = { "c" }, default = "prod", }) args:add("target", "option", { help = "Target to build for", aliases = { "t" }, default = "roblox", }) args:add("output", "option", { help = "Full path to the rbxm file to build", aliases = { "o" }, default = tostring(path.join(getStudioPluginsPath(), project.PLUGIN_FILENAME)), }) args:add("watch", "flag", { help = "Watch for changes and recompile automatically", aliases = { "w" }, }) args:add("skip-reload", "flag", { help = "Skip reloading the plugin in Roblox Studio", }) args:add("clean", "flag", { help = "Performs a full rebuild of the project", }) args:parse({ ... }) local subcommand = args:get("subcommand") assert( subcommand == "plugin" or subcommand == "workspace", `bad value for subcommand (must be one of "plugin" or "workspace", got "{subcommand}")` ) local channel = args:get("channel") assert(channel == "dev" or channel == "prod", `bad value for channel (must be one of "dev" or "prod", got "{channel}")`) local target = args:get("target") assert( target == "roblox" or target == "rotriever", `bad value for target (must be one of "roblox" or "rotriever", got "{target}")` ) local output = args:get("output") assert(typeof(output) == "string", `bad value for output (string expected, got {typeof(output)})`) local function readWallyManifestAsync() return toml.deserialize(fs.readfiletostring(WALLY_MANIFEST_PATH)) end local function getCommitHash() local commitHash = run("git", { "rev-parse", "--short", "HEAD" }, { captureOutput = true, }) assert(commitHash ~= nil and commitHash ~= "", "commit hash is empty") return commitHash end -- This environment variable comes from `.env` and is required to be set. This -- condition just makes sure if it's _not_ set that the user will then go and -- get their `.env` file in order if not process.env.BASE_URL then error(table.concat({ "One or more critical environment variables are not set.", "Please make sure to copy `.env.template` to `.env`. If you already have a `.env` file, make sure the environment variables from the template match your local copy", }, "\n\n")) end local context: BuildContext = { channel = channel, target = target, shouldRebuild = args:has("clean"), dest = path.join(project.BUILD_PATH, channel, target), env = { BUILD_VERSION = (readWallyManifestAsync() :: any).package.version, BUILD_CHANNEL = if channel == "prod" then "production" else "development", BUILD_HASH = getCommitHash(), BASE_URL = process.env.BASE_URL, LOG_LEVEL = process.env.LOG_LEVEL, }, cache = buildSystem.readBuildCacheAsync(), } local function buildPluginBinary() if subcommand ~= "plugin" then return end buildSystem.runBuildGroupAsync({ name = "🔌 plugin binary", paths = { context.dest }, context = context, step = function() local projectPath = path.resolve(path.join(context.dest, "../default.project.json")) createRojoProjectAsync(projectPath, { name = "Flipbook", tree = { ["$path"] = tostring(path.resolve(context.dest)), }, }) local dest = path.resolve(path.join(context.dest, "..", project.PLUGIN_FILENAME)) run("rojo", { "build", projectPath, "-o", dest, }) fs.remove(projectPath) if args:has("skip-reload") then if output:match(tostring(getStudioPluginsPath())) then return end end copyInto(dest, output) end, }) end local function build() local startTime = os.clock() local contextNoCache = table.clone(context) contextNoCache.cache = nil :: any print(richterm.dim(`build context: {pp(contextNoCache)}`)) buildSystem.compileAsync(context) buildSystem.writeBuildCacheAsync(context.cache) buildPluginBinary() print(`build completed in {("%.2f"):format(os.clock() - startTime)}s`) end build() if args:has("watch") then local function onChanged(filePath: path.path) if tostring(filePath):match(tostring(project.WORKSPACE_PATH)) then local memberPath = tostring(filePath):match(`({project.WORKSPACE_PATH}/[%w%-]+)/`) buildSystem.compileWorkspaceMemberAsync(memberPath, context) buildSystem.writeBuildCacheAsync(context.cache) buildPluginBinary() else build() end end watch({ roots = { tostring(project.SOURCE_PATH), tostring(project.WORKSPACE_PATH), }, excludedFilePatterns = { ".*Packages", "build", }, onChanged = onChanged, }) end
1,422
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/bump-version.luau
local cli = require("@luaupkg/batteries/cli") local fs = require("@std/fs") local findAndReplace = require("@scripts/lib/findAndReplace") local semver = require("@scripts/lib/semver") type VersionComponent = semver.VersionComponent local function validateVersionBump(versionBump: string): VersionComponent versionBump = versionBump:lower() if versionBump == "major" or versionBump == "minor" or versionBump == "patch" then return versionBump else error(`invalid version bump, must be "major", "minor", or "patch" (got "{versionBump}")`) end end local function getNextVersion(currentVersion: string, versionBump: VersionComponent) local versionParts = semver.splitVersionComponents(currentVersion) if versionBump == "major" then versionParts = { versionParts[1] + 1, 0, 0 } elseif versionBump == "minor" then versionParts = { versionParts[1], versionParts[2] + 1, 0 } elseif versionBump == "patch" then versionParts = { versionParts[1], versionParts[2], versionParts[3] + 1 } end return table.concat(versionParts, ".") end local args = cli.parser() args:add("versionBump", "positional", { help = `Can be one of "major", "minor", or "patch"`, required = true, }) local argsNoScript = { ... } table.remove(argsNoScript, 1) args:parse(argsNoScript) -- The only package we publish is FlipbookCore, so the following makes no -- attempt to bump the version of any of our other workspace members do local MANIFEST_PATHS = { "wally.toml", "workspace/flipbook-core/wally.toml", "workspace/flipbook-core/rotriever.toml", } local bumpedVersionComponent = args:get("versionBump") print("bumpedVersionComponent") local versionBump: VersionComponent = validateVersionBump(bumpedVersionComponent) -- The root Wally manifest is the source of truth for the current version local wallyPath = MANIFEST_PATHS[1] assert(fs.exists(wallyPath), `no wally.toml found at the root of the repo`) local currentVersion = semver.getVersionFromManifest(wallyPath) local nextVersion = getNextVersion(currentVersion, versionBump) for _, manifestPath in MANIFEST_PATHS do local manifestVersion = semver.getVersionFromManifest(manifestPath) if fs.exists(manifestPath) then findAndReplace(manifestPath, `version = "{manifestVersion}"`, `version = "{nextVersion}"`) print(`bumped version in {manifestPath} to {nextVersion} (was {manifestVersion})`) end end end
625
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/build-system/compileWorkspaceMemberAsync.luau
local FlipbookBatteries = require("@luaupkg/flipbook-batteries") local fs = require("@std/fs") local path = require("@std/path") local project = require("@repo/project") local runBuildGroupAsync = require("@scripts/lib/build-system/runBuildGroupAsync") local types = require("@scripts/lib/build-system/types") local copyInto = FlipbookBatteries.copyInto local run = FlipbookBatteries.run type BuildContext = types.BuildContext local function compileWorkspaceMemberAsync(memberPath: path.pathlike, context: BuildContext): path.path local relativeMemberPath = path.relative(project.REPO_PATH, memberPath) local memberBuildPath = path.join(memberPath, "build") runBuildGroupAsync({ name = `📦 build {relativeMemberPath}`, paths = { memberPath, }, context = context, step = function() fs.removedirectory(memberBuildPath, { recursive = true, }) fs.createdirectory(memberBuildPath, { makeparents = true, }) run("darklua", { "process", path.join(relativeMemberPath, "src"), memberBuildPath, }, { env = context.env, }) end, }) if context.channel == "prod" then runBuildGroupAsync({ name = `✂️ prune {relativeMemberPath}`, paths = { memberBuildPath }, context = context, step = function() for _, pattern in project.PROD_CONFIG.prunedFiles do run("find", { memberBuildPath, "-type", "f", "-name", `"{pattern}"`, "-delete" }) end end, }) end local dest = path.join(context.dest, relativeMemberPath) fs.removedirectory(dest, { recursive = true, }) copyInto(memberBuildPath, dest) return memberBuildPath end return compileWorkspaceMemberAsync
423
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/build-system/hashPath.luau
local crypto = require("@lute/crypto") local fs = require("@std/fs") local path = require("@std/path") local HASH_METHOD = crypto.hash.md5 local function bufferToHex(buf: buffer): string local hex = "" for i = 0, buffer.len(buf) - 1 do hex ..= ("%02x"):format(buffer.readu8(buf, i)) end return hex end local function hashFile(filePath: path.pathlike): string local content = fs.readfiletostring(filePath) return bufferToHex(crypto.digest(HASH_METHOD, content)) end local function hashDir(dirPath: path.pathlike): string local hashes = {} for _, file in fs.listdirectory(dirPath) do local filePath = path.join(dirPath, file.name) if file.type == "dir" then table.insert(hashes, hashDir(filePath)) else table.insert(hashes, hashFile(filePath)) end end local joinedHash = table.concat(hashes, "") return bufferToHex(crypto.digest(HASH_METHOD, joinedHash)) end local function hashPath(filePath: path.pathlike): string assert(fs.exists(filePath), `no file found at {filePath}`) if fs.type(filePath) == "dir" then return hashDir(filePath) else return hashFile(filePath) end end return hashPath
290
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/build-system/init.luau
local types = require("@self/types") export type BuildContext = types.BuildContext return { compileAsync = require("@self/compileAsync"), compileWorkspaceMemberAsync = require("@self/compileWorkspaceMemberAsync"), readBuildCacheAsync = require("@self/readBuildCacheAsync"), writeBuildCacheAsync = require("@self/writeBuildCacheAsync"), runBuildGroupAsync = require("@self/runBuildGroupAsync"), }
85
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/build-system/readBuildCacheAsync.luau
local fs = require("@std/fs") local json = require("@std/json") local project = require("@repo/project") local types = require("@scripts/lib/build-system/types") local function readBuildCacheAsync(): types.BuildCache if fs.exists(project.BUILD_CACHE_PATH) then local content = fs.readfiletostring(project.BUILD_CACHE_PATH) if content and content ~= "" then return json.deserialize(content) :: any end end return {} end return readBuildCacheAsync
105
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/build-system/runBuildGroupAsync.luau
local fs = require("@std/fs") local process = require("@std/process") local richterm = require("@luaupkg/batteries/richterm") local hashPath = require("@scripts/lib/build-system/hashPath") local types = require("@scripts/lib/build-system/types") type BuildGroup = types.BuildGroup local function trimDecimals(n: number, decmimalPlaces: number) local factor = math.pow(10, decmimalPlaces) return math.floor(n * factor) / factor end local function runBuildGroupAsync(buildGroup: BuildGroup) local prefix = richterm.bold(`[{buildGroup.name}]`) local buildCache = buildGroup.context.cache local changedPaths = {} for _, filePath in buildGroup.paths do assert(fs.exists(filePath), `attempt to run build group with invalid path (found nothing at {filePath})`) local key = `{buildGroup.context.channel}-{buildGroup.context.target}-{filePath}` local hash = hashPath(filePath) if hash ~= buildCache[key] or buildGroup.context.shouldRebuild then buildCache[key] = hash table.insert(changedPaths, filePath) end end if #changedPaths == 0 then return end local processedBuildGroup = table.clone(buildGroup) processedBuildGroup.paths = changedPaths print(`{prefix} starting build step...`) local startTime = os.clock() local ok, err = (xpcall :: any)(function() buildGroup.step(processedBuildGroup) end, debug.traceback) if ok then local elapsedMs = trimDecimals((os.clock() - startTime) * 1000, 3) local message = richterm.cyan(`step completed in {elapsedMs}ms`) print(`{prefix} {message}`) else local message = richterm.red(`step failed: {err}`) print(`{prefix} {message}`) process.exit(1) end end return runBuildGroupAsync
415
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/build-system/types.luau
local path = require("@std/path") export type Channel = "prod" | "dev" export type Target = "roblox" | "rotriever" export type BuildCache = { -- Maps file path to MD5 hash [string]: string, } export type BuildContext = { channel: Channel, target: Target, dest: path.path, env: { [string]: string }, shouldRebuild: boolean, cache: BuildCache, } export type BuildGroup = { name: string, paths: { path.pathlike }, context: BuildContext, step: (self: BuildGroup) -> (), } return nil
132
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/build-system/writeBuildCacheAsync.luau
local fs = require("@std/fs") local json = require("@std/json") local project = require("@repo/project") local types = require("@scripts/lib/build-system/types") local function writeBuildCacheAsync(buildCache: types.BuildCache) local contents = json.serialize(buildCache :: json.object, true) fs.writestringtofile(project.BUILD_CACHE_PATH, contents) end return writeBuildCacheAsync
82
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/clean.luau
local fs = require("@std/fs") local path = require("@std/path") local getStudioPluginsPath = require("@scripts/lib/getStudioPluginsPath") local project = require("@repo/project") local PATHS_TO_CLEAN: { path.pathlike } = { project.BUILD_PATH, path.join(getStudioPluginsPath(), project.PLUGIN_FILENAME), project.PLUGIN_FILENAME, } local function clean() for _, pathToClean in PATHS_TO_CLEAN do local filePath = path.resolve(pathToClean) if fs.exists(filePath) then print(`removing {filePath}`) if fs.type(filePath) == "dir" then fs.removedirectory(filePath, { recursive = true, }) else fs.remove(filePath) end end end end return clean
168
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/createRojoProjectAsync.luau
local fs = require("@std/fs") local json = require("@std/json") local path = require("@std/path") local function createRojoProjectAsync(projectPath: path.pathlike, projectContent: json.value): path.path local resolvedProjectPath = path.resolve(projectPath) fs.writestringtofile(resolvedProjectPath, json.serialize(projectContent, true)) return resolvedProjectPath end return createRojoProjectAsync
88
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/findAndReplace.luau
local fs = require("@std/fs") local path = require("@std/path") local function findAndReplace(filePath: path.pathlike, match: string, replacement: string) local content = fs.readfiletostring(filePath) content = content:gsub(match, replacement) fs.writestringtofile(filePath, content) end return findAndReplace
70
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/getDescendants.luau
local fs = require("@std/fs") local path = require("@std/path") local function reduce(rootPath: path.path, accumulator: { path.path }): { path.path } for _, child in fs.listdirectory(rootPath) do local childPath = path.join(rootPath, child.name) table.insert(accumulator, childPath) if child.type == "dir" then reduce(childPath, accumulator) end end return accumulator end local function getDescendants(dirPath: path.pathlike): { path.path } local rootPath = path.resolve(dirPath) if fs.type(rootPath) ~= "dir" then return {} end return reduce(rootPath, {}) end return getDescendants
152
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/getStudioPluginsPath.luau
local path = require("@std/path") local process = require("@std/process") local system = require("@std/system") local function getStudioPluginPath(): path.path if system.os == "Darwin" then return path.join(process.homedir(), "Documents/Roblox/Plugins") else return path.join(process.homedir(), "AppData/Local/Roblox/Plugins") end end return getStudioPluginPath
93
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/packToRbxm.luau
local FlipbookBatteries = require("@luaupkg/flipbook-batteries") local fs = require("@std/fs") local path = require("@std/path") local system = require("@std/system") local createRojoProjectAsync = require("@scripts/lib/createRojoProjectAsync") local run = FlipbookBatteries.run local function packToRbxm(filePath: path.pathlike): path.path local projectPath = path.join(system.tmpdir(), "default.project.json") local resolvedFilePath = path.resolve(filePath) createRojoProjectAsync(projectPath, { name = path.basename(filePath), tree = { ["$path"] = tostring(resolvedFilePath), }, }) local outputPath = path.resolve(`{resolvedFilePath}.rbxm`) run("rojo", { "build", tostring(projectPath), "-o", tostring(outputPath), }) fs.remove(projectPath) return outputPath end return packToRbxm
206
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/semver.luau
local fs = require("@std/fs") local toml = require("@luaupkg/batteries/toml") export type VersionComponent = "major" | "minor" | "patch" local function getVersionFromManifest(manifestPath: string) local manifest = toml.deserialize(fs.readfiletostring(manifestPath)) if manifest.workspace then return (manifest.workspace :: any).version elseif manifest.package then return (manifest.package :: any).version else error(`Could not find a 'version' field in {manifestPath}`) end end local function splitVersionComponents(version: string): { number } local stringVersionParts = version:split(".") local versionParts: { number } = {} for _, stringVersionPart in stringVersionParts do local versionPart = tonumber(stringVersionPart) assert( versionPart, `Invalid version part '{stringVersionPart}' in version '{version}' (could not convert to number)` ) table.insert(versionParts, versionPart) end return versionParts end return { getVersionFromManifest = getVersionFromManifest, splitVersionComponents = splitVersionComponents, }
241
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lib/waitForTasks.luau
local task = require("@lute/task") local function waitForTasks(tasks: { thread }) local running = table.clone(tasks) while #running > 0 do for index, job in running do if coroutine.status(job) == "dead" then table.remove(running, index) end end task.wait() end end return waitForTasks
80
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/lint.luau
local FlipbookBatteries = require("@luaupkg/flipbook-batteries") local path = require("@std/path") local process = require("@std/process") local project = require("@repo/project") local run = FlipbookBatteries.run local findWhere = FlipbookBatteries.findWhere local function findLuaFiles() local result = {} for _, folder in project.FOLDERS_TO_LINT do local matches = findWhere(folder, function(filePath) return path.extname(filePath) == ".lua" end) for _, match in matches do table.insert(result, match) end end return result end run("selene", { table.unpack(project.FOLDERS_TO_LINT) }) run("stylua", { "--check", table.unpack(project.FOLDERS_TO_LINT), }) local files = findLuaFiles() if #files > 0 then print("[err] the following file(s) are using the '.lua' extension. Please change to '.luau' and try again") print(`{table.concat(files, "\n")}`) process.exit(1) end
237
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/serve-docs.luau
local FlipbookBatteries = require("@luaupkg/flipbook-batteries") local run = FlipbookBatteries.run run("npm", { "install", }, { cwd = "docs", }) run("npm", { "start", }, { cwd = "docs", })
65
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/.lute/tasks/run-tests.luau
local ReplicatedStorage = game:GetService("ReplicatedStorage") -- This path is defined in tests.project.json local TestRunner = (require :: any)(ReplicatedStorage.Flipbook.workspace["test-runner"]) TestRunner.runTests() return nil
51
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/project.luau
local path = require("@std/path") return { REPO_PATH = path.resolve("."), SOURCE_PATH = path.resolve("./src"), BUILD_PATH = path.resolve("./build"), BUILD_CACHE_PATH = path.resolve("./build/build-cache.json"), PACKAGES_PATH = path.resolve("./Packages"), ROBLOX_PACKAGES_PATH = path.resolve("./RobloxPackages"), ROBLOX_PACKAGES_VERSION = "0.710.0.7100702", SCRIPTS_PATH = path.resolve("./.lute"), EXAMPLE_PATH = path.resolve("./example"), WORKSPACE_PATH = path.resolve("./workspace"), LUAU_PACKAGES_PATH = path.resolve("./LuauPackages"), PLUGIN_FILENAME = "Flipbook.rbxm", SOURCEMAP_PATH = path.resolve("./sourcemap.json"), DARKLUA_SOURCEMAP_PATH = path.resolve("./sourcemap-darklua.json"), ROJO_BUILD_PROJECT = path.resolve("./build.project.json"), ROJO_TESTS_PROJECT = path.resolve("./tests.project.json"), FOLDERS_TO_LINT = { "src", ".lute", }, PROD_CONFIG = { prunedDirs = { path.resolve("./workspace/code-samples"), path.resolve("./workspace/example"), path.resolve("./workspace/template"), path.resolve("./workspace/test-runner"), }, prunedFiles = { "*.spec.lua*", "*.story.lua*", "*.storybook.lua*", "jest.config.lua*", }, }, }
321
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/Default/Button.story.luau
return { story = function() local button = Instance.new("TextButton") button.Text = "Button" button.TextSize = 16 button.Font = Enum.Font.BuilderSansExtraBold button.TextColor3 = Color3.fromRGB(50, 50, 50) button.BackgroundColor3 = Color3.fromRGB(255, 255, 255) button.BorderSizePixel = 0 button.Size = UDim2.fromOffset(200, 40) button.Activated:Connect(function() print("clicked") end) return button end, }
126
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/Fusion/Fusion.storybook.luau
local Fusion = require("@pkg/Fusion") return { name = "Fusion", storyRoots = { script.Parent, }, packages = { Fusion = Fusion, }, }
42
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/Fusion/FusionButton.luau
local Fusion = require("@pkg/Fusion") local New = Fusion.New local OnEvent = Fusion.OnEvent local function FusionButton(props: { text: string, onActivated: () -> (), }) return New("TextButton")({ Text = props.text, TextSize = 16, Font = Enum.Font.BuilderSansExtraBold, TextColor3 = Color3.fromRGB(50, 50, 50), BackgroundColor3 = Color3.fromRGB(255, 255, 255), BorderSizePixel = 0, Size = UDim2.fromOffset(200, 40), [OnEvent("Activated")] = props.onActivated, }) end return FusionButton
152
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/Fusion/FusionButton.story.luau
local FusionButton = require("./FusionButton") return { story = function() return FusionButton({ text = "Click Me", onActivated = function() print("click") end, }) end, }
49
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/FusionStoryteller/Fusion.storybook.luau
local Fusion = require("@pkg/Fusion") local Storyteller = require("@pkg/Storyteller") local storybook: Storyteller.Storybook = { name = "Fusion (Storyteller)", storyRoots = { script.Parent, }, packages = { Fusion = Fusion, }, } return storybook
73
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/FusionStoryteller/FusionButton.story.luau
local Storyteller = require("@pkg/Storyteller") local FusionButton = require("./FusionButton") local story: Storyteller.Story<any> = { story = function() return FusionButton({ text = "Click Me", onActivated = function() print("click") end, }) end, } return story
75
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/React/React.storybook.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") return { name = "React", storyRoots = { script.Parent, }, packages = { React = React, ReactRoblox = ReactRoblox, }, }
64
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/React/ReactButton.luau
local React = require("@pkg/React") local function ReactButton(props: { text: string, onActivated: () -> (), }) return React.createElement("TextButton", { Text = props.text, TextSize = 16, Font = Enum.Font.BuilderSansExtraBold, TextColor3 = Color3.fromRGB(50, 50, 50), BackgroundColor3 = Color3.fromRGB(255, 255, 255), BorderSizePixel = 0, Size = UDim2.fromOffset(200, 40), [React.Event.Activated] = props.onActivated, }) end return ReactButton
139
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/React/ReactButton.story.luau
local React = require("@pkg/React") local ReactButton = require("./ReactButton") return { story = function() return React.createElement(ReactButton, { text = "Click Me", onActivated = function() print("click") end, }) end, }
61
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/React/ReactButtonControls.luau
local React = require("@pkg/React") local function ReactButton(props: { text: string, isDisabled: boolean, onActivated: () -> (), }) return React.createElement("TextButton", { Text = props.text, TextSize = 16, Font = Enum.Font.BuilderSansExtraBold, TextColor3 = Color3.fromRGB(50, 50, 50), BackgroundColor3 = Color3.fromRGB(255, 255, 255), AutoButtonColor = if props.isDisabled then false else true, BorderSizePixel = 0, Size = UDim2.fromOffset(200, 40), [React.Event.Activated] = if props.isDisabled then nil else props.onActivated, }, { Overlay = if props.isDisabled then React.createElement("Frame", { Size = UDim2.fromScale(1, 1), BackgroundColor3 = Color3.fromRGB(0, 0, 0), BackgroundTransparency = 0.6, }) else nil, }) end return ReactButton
236
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/React/ReactButtonControls.story.luau
local React = require("@pkg/React") local ReactButtonControls = require("./ReactButtonControls") local controls = { text = "Click Me", isDisabled = false, } type Props = { controls: typeof(controls), } return { controls = controls, story = function(props: Props) return React.createElement(ReactButtonControls, { text = props.controls.text, isDisabled = props.controls.isDisabled, onActivated = function() print("click") end, }) end, }
109
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/React/ReactButtonExplicitPackages.story.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") return { story = function() return React.createElement("TextButton", { Text = "Click Me", TextSize = 16, Font = Enum.Font.BuilderSansExtraBold, TextColor3 = Color3.fromRGB(50, 50, 50), BackgroundColor3 = Color3.fromRGB(255, 255, 255), BorderSizePixel = 0, Size = UDim2.fromOffset(200, 40), [React.Event.Activated] = function() print("clicked") end, }) end, packages = { React = React, ReactRoblox = ReactRoblox, }, }
169
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/ReactStoryteller/React.storybook.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") local Storyteller = require("@pkg/Storyteller") local storybook: Storyteller.Storybook = { name = "React (Storyteller)", storyRoots = { script.Parent, }, packages = { React = React, ReactRoblox = ReactRoblox, }, } return storybook
95
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/ReactStoryteller/ReactButton.story.luau
local React = require("@pkg/React") local Storyteller = require("@pkg/Storyteller") local ReactButton = require("./ReactButton") local story: Storyteller.Story<any> = { story = function() return React.createElement(ReactButton, { text = "Click Me", onActivated = function() print("click") end, }) end, } return story
87
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/ReactStoryteller/ReactButtonControls.story.luau
local React = require("@pkg/React") local Storyteller = require("@pkg/Storyteller") local ReactButton = require("./ReactButton") local controls: Storyteller.StoryControlsSchema = { text = Storyteller.createStringControl("Click Me"), isDisabled = Storyteller.createBooleanControl(false), } local story: Storyteller.Story<any> = { controls = controls, story = function(props) return React.createElement(ReactButton, { text = props.controls.text, isDisabled = props.controls.isDisabled, onActivated = function() print("click") end, }) end, } return story
138
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/Roact/Roact.storybook.luau
local Roact = require("@pkg/Roact") return { name = "Roact", storyRoots = { script.Parent, }, packages = { Roact = Roact, }, }
46
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/Roact/RoactButton.luau
local Roact = require("@pkg/Roact") local RoactButton = Roact.Component:extend("RoactButton") function RoactButton:render() return Roact.createElement("TextButton", { Text = self.props.text, TextSize = 16, Font = Enum.Font.BuilderSansExtraBold, TextColor3 = Color3.fromRGB(50, 50, 50), BackgroundColor3 = Color3.fromRGB(255, 255, 255), BorderSizePixel = 0, Size = UDim2.fromOffset(200, 40), [Roact.Event.Activated] = self.props.onActivated, }) end return RoactButton
150
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/Roact/RoactButton.story.luau
local Roact = require("@pkg/Roact") local RoactButton = require("./RoactButton") return { story = function() return Roact.createElement(RoactButton, { text = "Click Me", onActivated = function() print("click") end, }) end, }
67
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/RoactStoryteller/Roact.storybook.luau
local Roact = require("@pkg/Roact") local Storyteller = require("@pkg/Storyteller") local storybook: Storyteller.Storybook = { name = "Roact (Storyteller)", storyRoots = { script.Parent, }, packages = { Roact = Roact, }, } return storybook
77
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/code-samples/src/RoactStoryteller/RoactButton.story.luau
local Roact = require("@pkg/Roact") local Storyteller = require("@pkg/Storyteller") local RoactButton = require("./RoactButton") local story: Storyteller.Story<any> = { story = function() return Roact.createElement(RoactButton, { text = "Click Me", onActivated = function() print("click") end, }) end, } return story
93
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/ArrayControls.story.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") local Sift = require("@pkg/Sift") local fonts = Sift.Array.sort(Enum.Font:GetEnumItems(), function(a: Enum.Font, z: Enum.Font) return a.Name < z.Name end) fonts = Sift.Array.unshift(fonts, Enum.Font.Gotham) local controls = { font = fonts, } type Props = { controls: { font: Enum.Font, }, } return { summary = "Example of using array controls to set the font for a TextLabel", controls = controls, react = React, reactRoblox = ReactRoblox, story = function(props: Props) return React.createElement("TextLabel", { Text = props.controls.font.Name, Font = props.controls.font, TextScaled = true, TextColor3 = Color3.fromRGB(0, 0, 0), BackgroundColor3 = Color3.fromRGB(255, 255, 255), Size = UDim2.fromOffset(300, 100), }) end, }
239
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/Button.luau
local Roact = require("@pkg/Roact") export type Props = { text: string, onActivated: () -> (), } local function Button(props: Props) return Roact.createElement("TextButton", { Text = props.text, TextSize = 16, Font = Enum.Font.GothamBold, TextColor3 = Color3.fromRGB(255, 255, 255), BackgroundColor3 = Color3.fromRGB(239, 31, 90), BorderSizePixel = 0, AutomaticSize = Enum.AutomaticSize.XY, [Roact.Event.Activated] = props.onActivated, }, { Padding = Roact.createElement("UIPadding", { PaddingTop = UDim.new(0, 8), PaddingRight = UDim.new(0, 8), PaddingBottom = UDim.new(0, 8), PaddingLeft = UDim.new(0, 8), }), }) end return Button
220
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/Button.story.luau
local Button = require("./Button") local Roact = require("@pkg/Roact") return { summary = "A generic button component that can be used anywhere", roact = Roact, story = Roact.createElement(Button, { text = "Click me", onActivated = function() print("click") end, }), }
74
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/ButtonWithControls.luau
local Roact = require("@pkg/Roact") export type Props = { text: string, isDisabled: boolean?, onActivated: (() -> ())?, } local function ButtonWithControls(props) local color = if props.isDisabled then Color3.fromRGB(82, 82, 82) else Color3.fromRGB(239, 31, 90) return Roact.createElement("TextButton", { Text = props.text, TextSize = 16, Font = Enum.Font.GothamBold, TextColor3 = Color3.fromRGB(255, 255, 255), BackgroundColor3 = color, BorderSizePixel = 0, AutomaticSize = Enum.AutomaticSize.XY, [Roact.Event.Activated] = if props.isDisabled then nil else props.onActivated, }, { Padding = Roact.createElement("UIPadding", { PaddingTop = UDim.new(0, 8), PaddingRight = UDim.new(0, 8), PaddingBottom = UDim.new(0, 8), PaddingLeft = UDim.new(0, 8), }), }) end return ButtonWithControls
259
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/ButtonWithControls.story.luau
local ButtonWithControls = require("./ButtonWithControls") local Roact = require("@pkg/Roact") local controls = { isDisabled = false, text = "Click me", } type Props = { controls: typeof(controls), } return { summary = "A generic button component that can be used anywhere", controls = controls, roact = Roact, story = function(props: Props) return Roact.createElement(ButtonWithControls, { text = props.controls.text, isDisabled = props.controls.isDisabled, onActivated = function() print("click") end, }) end, }
132
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/CanvasTests/AutomaticSize.story.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") return { summary = "AutoamticSize test for the story preview", react = React, reactRoblox = ReactRoblox, story = function() return React.createElement("TextLabel", { Size = UDim2.new(0, 0, 0, 0), AutomaticSize = Enum.AutomaticSize.XY, TextSize = 24, Text = script.Name, Font = Enum.Font.GothamBold, }) end, }
127
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/CanvasTests/AutomaticSizeExceedsBounds.story.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") return { summary = "AutoamticSize test using a height that exceeds the story preview", react = React, reactRoblox = ReactRoblox, story = function() return React.createElement("TextLabel", { Size = UDim2.fromScale(1, 0), AutomaticSize = Enum.AutomaticSize.Y, TextSize = 24, Text = script.Name .. string.rep("\nLine", 100), Font = Enum.Font.GothamBold, }) end, }
134
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/CanvasTests/Offset.story.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") return { summary = "Offset test for the story preview", react = React, reactRoblox = ReactRoblox, story = function() return React.createElement("TextLabel", { Size = UDim2.fromOffset(2000, 2000), AutomaticSize = Enum.AutomaticSize.None, TextSize = 24, Text = script.Name, Font = Enum.Font.GothamBold, }) end, }
120
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/CanvasTests/Resizing.story.luau
local RunService = game:GetService("RunService") local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") local RESIZE_DURATION = 3 -- seconds local MAX_SIZE = 2000 -- px local function Story() local alpha, setAlpha = React.useState(0) React.useEffect(function() local conn = RunService.Heartbeat:Connect(function(dt: number) setAlpha(function(prev) local newAlpha = prev + (dt / RESIZE_DURATION) return if newAlpha > 1 then 0 else newAlpha end) end) return function() conn:Disconnect() end end, {}) return React.createElement("TextLabel", { Size = UDim2.fromOffset(MAX_SIZE * alpha, MAX_SIZE * alpha), AutomaticSize = Enum.AutomaticSize.None, TextSize = 24, Text = script.Name, Font = Enum.Font.GothamBold, }) end return { summary = "Resizing test for the story preview", react = React, reactRoblox = ReactRoblox, story = function() return React.createElement(Story) end, }
255
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/CanvasTests/Scale.story.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") return { summary = "Scale test for the story preview", react = React, reactRoblox = ReactRoblox, story = function() return React.createElement("TextLabel", { Size = UDim2.fromScale(1, 1), AutomaticSize = Enum.AutomaticSize.None, TextSize = 24, Text = script.Name, Font = Enum.Font.GothamBold, }) end, }
118
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/CanvasTests/ScrollingFrame.story.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") return { summary = "ScrollingFrame test for the story preview", react = React, reactRoblox = ReactRoblox, story = function() return React.createElement("ScrollingFrame", { Size = UDim2.fromScale(1, 1), }, { Label = React.createElement("TextLabel", { Size = UDim2.fromScale(1, 1), AutomaticSize = Enum.AutomaticSize.None, TextSize = 24, Text = script.Name, Font = Enum.Font.GothamBold, }), }) end, }
152
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/Counter.luau
local Roact = require("@pkg/Roact") local Counter = Roact.Component:extend("Counter") export type Props = { increment: number, waitTime: number, } export type State = { count: number, } function Counter:init() self:setState({ count = 0, }) end function Counter:render() return Roact.createElement("TextLabel", { Text = self.state.count, TextScaled = true, Font = Enum.Font.Gotham, TextColor3 = Color3.fromRGB(0, 0, 0), BackgroundColor3 = Color3.fromRGB(255, 255, 255), Size = UDim2.fromOffset(300, 100), }, { Padding = Roact.createElement("UIPadding", { PaddingTop = UDim.new(0, 8), PaddingRight = UDim.new(0, 8), PaddingBottom = UDim.new(0, 8), PaddingLeft = UDim.new(0, 8), }), }) end function Counter:didMount() local props: Props = self.props self.isMounted = true task.spawn(function() while self.isMounted do self:setState(function(prev: State) return { count = prev.count + props.increment, } end) task.wait(props.waitTime) end end) end function Counter:willUnmount() self.isMounted = false end return Counter
319
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/Counter.story.luau
local Counter = require("./Counter") local Roact = require("@pkg/Roact") local controls = { increment = 1, waitTime = 1, } type Props = { controls: typeof(controls), } return { summary = "A simple counter that increments every second", controls = controls, roact = Roact, story = function(props: Props) return Roact.createElement(Counter, { increment = props.controls.increment, waitTime = props.controls.waitTime, }) end, }
113
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/Functional.story.luau
local controls = { text = "Functional Story", } type Props = { controls: typeof(controls), } return { summary = "This story uses a function with a cleanup callback to create and mount the gui elements. This works similarly to Hoarcekat stories but also supports controls and other metadata. Check out the source to learn more", controls = controls, story = function(parent: GuiObject, props: Props) local label = Instance.new("TextLabel") label.Text = props.controls.text label.Font = Enum.Font.Gotham label.TextColor3 = Color3.fromRGB(0, 0, 0) label.BackgroundColor3 = Color3.fromRGB(255, 255, 255) label.TextSize = 16 label.AutomaticSize = Enum.AutomaticSize.XY local padding = Instance.new("UIPadding") padding.PaddingTop = UDim.new(0, 8) padding.PaddingRight = padding.PaddingTop padding.PaddingBottom = padding.PaddingTop padding.PaddingLeft = padding.PaddingTop padding.Parent = label label.Parent = parent return function() label:Destroy() end end, }
254
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/Hoarcekat.story.luau
local Roact = require("@pkg/Roact") return function(target: Instance) local root = Roact.createElement("TextLabel", { Text = "Hoarcekat Story", TextScaled = true, TextColor3 = Color3.fromRGB(255, 255, 255), BackgroundColor3 = Color3.fromRGB(0, 0, 0), Size = UDim2.fromOffset(300, 100), }, { Padding = Roact.createElement("UIPadding", { PaddingTop = UDim.new(0, 8), PaddingRight = UDim.new(0, 8), PaddingBottom = UDim.new(0, 8), PaddingLeft = UDim.new(0, 8), }), }) local tree = Roact.mount(root, target) return function() Roact.unmount(tree) end end
194
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/ReactCounter.luau
local React = require("@pkg/React") export type Props = { increment: number, waitTime: number, } local function ReactCounter(props: Props) local count, setCount = React.useState(0) React.useEffect(function() local isMounted = true task.spawn(function() while isMounted do setCount(function(prev) return prev + props.increment end) task.wait(props.waitTime) end end) return function() isMounted = false end end, { props }) return React.createElement("TextLabel", { Text = count, TextScaled = true, Font = Enum.Font.Gotham, TextColor3 = Color3.fromRGB(0, 0, 0), BackgroundColor3 = Color3.fromRGB(255, 255, 255), Size = UDim2.fromOffset(300, 100), }, { Padding = React.createElement("UIPadding", { PaddingTop = UDim.new(0, 8), PaddingRight = UDim.new(0, 8), PaddingBottom = UDim.new(0, 8), PaddingLeft = UDim.new(0, 8), }), }) end return ReactCounter
274
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/ReactCounter.story.luau
local React = require("@pkg/React") local ReactCounter = require("./ReactCounter") local ReactRoblox = require("@pkg/ReactRoblox") local controls = { increment = 1, waitTime = 1, } type Props = { controls: typeof(controls), } return { summary = "A simple counter that increments every second. This is a copy of the Counter component, but written with React", controls = controls, react = React, reactRoblox = ReactRoblox, story = function(props: Props) return React.createElement(ReactCounter, { increment = props.controls.increment, waitTime = props.controls.waitTime, }) end, }
147
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Examples/StoryProps.story.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") local Storyteller = require("@pkg/Storyteller") return { story = function(props: Storyteller.StoryProps) local children: { [string]: React.Node } = {} for key, value in props do children[key] = React.createElement(Foundation.Text, { tag = "auto-xy content-default text-body-large", Text = `- {key}: {value}`, }) end return React.createElement(Foundation.View, { tag = "col gap-small", }, children) end, packages = { React = React, ReactRoblox = ReactRoblox, }, }
170
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/OrphanedStory.story.luau
local React = require("@pkg/React") local ReactRoblox = require("@pkg/ReactRoblox") return { story = function() return React.createElement("TextLabel", { Text = "Free from the shackles of storybooks", TextSize = 16, Font = Enum.Font.Gotham, TextColor3 = Color3.fromRGB(255, 255, 255), BackgroundTransparency = 1, AutomaticSize = Enum.AutomaticSize.XY, }) end, packages = { React = React, ReactRoblox = ReactRoblox, }, }
135
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/example/src/Unavailable.storybook.luau
error("This storybook has an error!") return { name = "Unavailable Storybook", storyRoots = { script.Parent, }, }
31
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/About/AboutView.story.luau
local React = require("@pkg/React") local AboutView = require("./AboutView") return { story = function() return React.createElement(AboutView) end, }
36
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/About/BuildInfo.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") local BUILD_INFO = { { label = "Version", value = _G.BUILD_VERSION }, { label = "Channel", value = _G.BUILD_CHANNEL }, { label = "Hash", value = _G.BUILD_HASH }, } export type Props = { layoutOrder: number?, } local function BuildInfo(props: Props) local children: { [string]: React.Node } = {} for _, info in BUILD_INFO do children[info.label] = React.createElement(Foundation.Text, { tag = "auto-xy text-body-medium content-muted", LayoutOrder = nextLayoutOrder(), Text = `{info.label}: {info.value}`, }) end return React.createElement(Foundation.View, { tag = "auto-xy col gap-medium align-x-center", LayoutOrder = props.layoutOrder, }, children) end return BuildInfo
216
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/About/RobloxProfile.story.luau
local React = require("@pkg/React") local RobloxProfile = require("./RobloxProfile") local controls = { userId = 1, } type Props = { controls: typeof(controls), } return { controls = controls, story = function(props: Props) local userId = assert(tonumber(props.controls.userId)) return React.createElement(RobloxProfile, { userId = userId, }) end, }
92
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/Branding.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local constants = require("@root/constants") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") local useTokens = Foundation.Hooks.useTokens local e = React.createElement type Props = { layoutOrder: number?, } local function Branding(props: Props) local tokens = useTokens() return e(Foundation.View, { tag = "auto-xy row gap-small align-y-center", LayoutOrder = props.layoutOrder, }, { Icon = e(Foundation.Image, { LayoutOrder = nextLayoutOrder(), Image = constants.FLIPBOOK_LOGO, Size = UDim2.fromOffset(tokens.Size.Size_800, tokens.Size.Size_800), }), Typography = e(Foundation.Text, { tag = "auto-xy text-heading-medium", LayoutOrder = nextLayoutOrder(), Text = "Flipbook", }), }) end return Branding
217
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/Branding.story.luau
local React = require("@pkg/React") local Branding = require("./Branding") return { summary = "Icon and Typography for Flipbook", controls = {}, story = function() return React.createElement(Branding) end, }
51
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/CharmTypes.luau
local CharmTypes = {} export type Getter<T> = () -> T export type Update<T> = ((T) -> T) | T export type Setter<T> = (Update<T>) -> T return CharmTypes
47
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/CodeBlock.luau
local Foundation = require("@rbxpkg/Foundation") local Highlighter = require("@pkg/Highlighter") local React = require("@pkg/React") local Sift = require("@pkg/Sift") local SelectableTextLabel = require("@root/Common/SelectableTextLabel") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") local useMemo = React.useMemo local useTokens = Foundation.Hooks.useTokens local function getLineNumbers(str: string): string return Sift.List.reduce(str:split("\n"), function(accumulator, _item, index) return if index == 1 then tostring(index) else `{accumulator}\n{index}` end, "") end export type Props = { source: string, sourceColor: Color3?, layoutOrder: number?, } local function CodeBlock(props: Props) local tokens = useTokens() local isFocused, setIsFocused = React.useBinding(false) local sourceColor = useMemo(function() return if props.sourceColor then props.sourceColor else tokens.Color.Content.Default.Color3 end, { props.sourceColor, tokens } :: { unknown }) local source = useMemo(function() if props.sourceColor then return props.source else return table.concat( Highlighter.buildRichTextLines({ src = props.source, }), "\n" ) end end, { props.source }) return React.createElement(Foundation.View, { tag = "size-full-0 auto-y bg-surface-200 gap-medium row radius-medium padding-medium", LayoutOrder = props.layoutOrder, }, { LineNumbers = React.createElement("TextLabel", { LayoutOrder = nextLayoutOrder(), AutomaticSize = Enum.AutomaticSize.XY, Text = getLineNumbers(source), TextSize = tokens.Typography.BodyMedium.FontSize, LineHeight = 1, BackgroundTransparency = 1, Font = Enum.Font.RobotoMono, TextColor3 = tokens.Color.Content.Muted.Color3, TextXAlignment = Enum.TextXAlignment.Right, }), SourceCodeWrapper = React.createElement(Foundation.ScrollView, { tag = "size-full-0 auto-y shrink", scroll = { AutomaticSize = Enum.AutomaticSize.Y, AutomaticCanvasSize = Enum.AutomaticSize.XY, CanvasSize = UDim2.fromScale(0, 0), ScrollingDirection = Enum.ScrollingDirection.X, HorizontalScrollBarInset = Enum.ScrollBarInset.Always, }, layout = { FillDirection = Enum.FillDirection.Vertical, }, LayoutOrder = nextLayoutOrder(), }, { SourceCode = React.createElement(SelectableTextLabel, { RichText = true, LayoutOrder = nextLayoutOrder(), AutomaticSize = Enum.AutomaticSize.XY, Text = isFocused:map(function(value: boolean) return if value == true then props.source else source end), TextColor3 = sourceColor, TextSize = tokens.Typography.BodyMedium.FontSize, TextWrapped = false, LineHeight = 1, Font = Enum.Font.RobotoMono, [React.Event.Focused] = function() setIsFocused(true) end, [React.Event.FocusLost] = function() setIsFocused(false) end, }), }), }) end return CodeBlock
735
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/CodeBlock.story.luau
local React = require("@pkg/React") local CodeBlock = require("./CodeBlock") return { summary = "Previews a block of code", story = function() return React.createElement(CodeBlock, { source = "local function add(a: number, b: number): number\n\treturn a + b\nend", }) end, }
75
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/ContextProviders.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local ContextStack = require("@root/Common/ContextStack") local NavigationContext = require("@root/Navigation/NavigationContext") local PluginStore = require("@root/Plugin/PluginStore") local useThemeName = require("@root/Common/useThemeName") local useEffect = React.useEffect export type Props = { plugin: Plugin, overlayGui: GuiBase2d?, children: React.Node?, } local function ContextProviders(props: Props) local themeName: "Dark" | "Light" = useThemeName() useEffect(function() PluginStore.get().setPlugin(props.plugin) end, { props.plugin }) return React.createElement(ContextStack, { providers = { React.createElement(Foundation.FoundationProvider, { theme = themeName, overlayGui = props.overlayGui, }), React.createElement(NavigationContext.Provider, { defaultScreen = "Home", }), }, }, props.children) end return ContextProviders
222
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/ContextStack.luau
local React = require("@pkg/React") export type Props = { providers: { React.ReactElement<any, any> }, children: React.ReactNode, } local function ContextStack(props: Props) local mostRecent = props.children for providerIndex = #props.providers, 1, -1 do local providerElement = props.providers[providerIndex] mostRecent = React.cloneElement(providerElement, nil, mostRecent) end return mostRecent end return ContextStack
101
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/SelectableTextLabel.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local Sift = require("@pkg/Sift") local useTokens = Foundation.Hooks.useTokens local defaultProps = { AutomaticSize = Enum.AutomaticSize.XY, BackgroundTransparency = 1, ClearTextOnFocus = false, ClipsDescendants = true, TextEditable = false, TextWrapped = true, TextXAlignment = Enum.TextXAlignment.Left, TextYAlignment = Enum.TextYAlignment.Top, } local function SelectableTextLabel(providedProps) local tokens = useTokens() local font = tokens.Typography.BodyMedium local color = tokens.Color.Content.Default local props = Sift.Dictionary.merge(defaultProps, { TextSize = font.FontSize, Font = font.Font, TextColor3 = color.Color3, TextTransparency = color.Transparency, }, providedProps) return React.createElement("TextBox", props) end return SelectableTextLabel
207
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/SelectableTextLabel.story.luau
local React = require("@pkg/React") local SelectableTextLabel = require("./SelectableTextLabel") local controls = { text = "Ad proident sit nulla incididunt do nisi amet velit velit...", } type Props = { controls: typeof(controls), } return { summary = "A styled TextLabel with selectable text. Click and drag with the mouse to select content", controls = controls, story = function(props: Props) return React.createElement(SelectableTextLabel, { Text = props.controls.text, }) end, }
110
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/getAncestors.luau
local function getAncestors(instance: Instance): { Instance } local ancestors = {} local parent = instance.Parent while parent do table.insert(ancestors, parent) parent = parent.Parent end return ancestors end return getAncestors
56
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/getBuildInfo.luau
local function getBuildInfo(): { version: string, channel: string, hash: string } return { version = _G.BUILD_VERSION, channel = _G.BUILD_CHANNEL, hash = _G.BUILD_HASH, } end return getBuildInfo
57
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/getInstancePath.luau
local PATH_SEPARATOR = "/" local function getInstancePath(instance: Instance, pathSeparator: string?): string local separator = if pathSeparator then pathSeparator else PATH_SEPARATOR local path = {} local current = instance while current and current.Parent ~= nil do table.insert(path, 1, current.Name) current = current.Parent end return table.concat(path, separator) end return getInstancePath
84
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/mapRanges.luau
local function mapRanges(num: number, min0: number, max0: number, min1: number, max1: number): number if max0 == min0 then error("Range of zero") end return (((num - min0) * (max1 - min1)) / (max0 - min0)) + min1 end return mapRanges
80
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/nextLayoutOrder.luau
local layoutOrder = 0 local function nextLayoutOrder() layoutOrder += 1 return layoutOrder end return nextLayoutOrder
30
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/useEvent.luau
local React = require("@pkg/React") local function useEvent(event: RBXScriptSignal, callback: (...any) -> ()) React.useEffect(function() local conn = event:Connect(callback) return function() conn:Disconnect() end end) end return useEvent
62
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/usePrevious.luau
local React = require("@pkg/React") local function usePrevious(value: any) local previous = React.useRef(nil) React.useEffect(function() previous.current = value end, { value }) return previous.current end return usePrevious
53
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/useThemeName.luau
local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local UserSettingsStore = require("@root/UserSettings/UserSettingsStore") local useMemo = React.useMemo local useState = React.useState local useEffect = React.useEffect local useSignalState = ReactCharm.useSignalState export type ThemeName = "Dark" | "Light" local MOCK_STUDIO = { ThemeChanged = Instance.new("BindableEvent").Event, Theme = { Name = "Light", }, } local function useThemeName(): ThemeName local userSettingsStore = useSignalState(UserSettingsStore.get) local userSettings = useSignalState(userSettingsStore.getStorage) local studio: Studio = useMemo(function() local success, result = pcall(function() return (settings() :: any).Studio end) return if success then result else MOCK_STUDIO end, {}) local studioTheme, setStudioTheme = useState(studio.Theme.Name) local theme = useMemo(function(): ThemeName if userSettings.theme ~= "system" then if userSettings.theme == "dark" then return "Dark" elseif userSettings.theme == "light" then return "Light" end else if studioTheme == "Dark" or studioTheme == "Light" then return studioTheme end end return "Dark" end, { userSettings.theme, studioTheme } :: { unknown }) useEffect(function(): any local conn = studio.ThemeChanged:Connect(function() setStudioTheme(studio.Theme.Name) end) return function() conn:Disconnect() end end, { studio }) return theme :: ThemeName end return useThemeName
370
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Common/useZoom.luau
local React = require("@pkg/React") local ZOOM_INCREMENT = 0.25 local function useZoom(story: ModuleScript?) local value, setValue = React.useState(0) local zoomIn = React.useCallback(function() setValue(value + ZOOM_INCREMENT) end, { value, setValue } :: { unknown }) local zoomOut = React.useCallback(function() setValue(value - ZOOM_INCREMENT) end, { value, setValue } :: { unknown }) React.useEffect(function() setValue(0) end, { story }) return { value = value, zoomIn = zoomIn, zoomOut = zoomOut, } end return useZoom
145
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Feedback/DiscardChangesDialog.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") export type Props = { onKeepEditing: () -> (), onDiscard: () -> (), } local function DiscardChangesDialog(props: Props) return React.createElement(Foundation.Dialog.Root, { disablePortal = false, hasBackdrop = true, }, { Title = React.createElement(Foundation.Dialog.Title, { text = "Discard feedback", }), Content = React.createElement(Foundation.Dialog.Content, nil, { Message = React.createElement(Foundation.Text, { tag = "auto-xy padding-top-medium", Text = "Are you sure you want to discard your changes?", LayoutOrder = nextLayoutOrder(), }), }), Actions = React.createElement(Foundation.Dialog.Actions, { actions = { { variant = Foundation.Enums.ButtonVariant.Standard :: Foundation.ButtonVariant, text = "Keep editing", onActivated = props.onKeepEditing, }, { variant = Foundation.Enums.ButtonVariant.Emphasis, text = "Discard", onActivated = props.onDiscard, }, }, LayoutOrder = nextLayoutOrder(), }), }) end return DiscardChangesDialog
288
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Feedback/DiscardChangesDialog.story.luau
local React = require("@pkg/React") local DiscardChangesDialog = require("./DiscardChangesDialog") return { story = function() return React.createElement(DiscardChangesDialog, { onKeepEditing = function() print("onKeepEditing") end, onDiscard = function() print("onDiscard") end, }) end, }
79
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Feedback/FeedbackDialog.story.luau
local React = require("@pkg/React") local FeedbackDialog = require("./FeedbackDialog") return { story = function() return React.createElement(FeedbackDialog, { onClose = function() print("onClose") end, }) end, }
55
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Feedback/SuccessDialog.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local nextLayoutOrder = require("@root/Common/nextLayoutOrder") export type Props = { onClose: () -> (), } local function SuccessDialog(props: Props) return React.createElement(Foundation.Dialog.Root, { disablePortal = false, hasBackdrop = true, }, { Title = React.createElement(Foundation.Dialog.Title, { text = "Feedback posted", LayoutOrder = nextLayoutOrder(), }), Content = React.createElement(Foundation.Dialog.Content, { LayoutOrder = nextLayoutOrder(), }, { Message = React.createElement(Foundation.Text, { tag = "auto-xy text-wrap text-align-x-left text-align-y-top padding-top-medium", Text = "Your feedback has been submitted! Thank you for helping us to improve Flipbook", }), }), Actions = React.createElement(Foundation.Dialog.Actions, { actions = { { variant = Foundation.Enums.ButtonVariant.Emphasis, text = "Close", onActivated = props.onClose, }, }, LayoutOrder = nextLayoutOrder(), }), }) end return SuccessDialog
264
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Feedback/SuccessDialog.story.luau
local React = require("@pkg/React") local SuccessDialog = require("./SuccessDialog") return { story = function() return React.createElement(SuccessDialog, { onClose = function() print("onClose") end, }) end, }
55
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Feedback/postFeedbackAsync.luau
local getBuildInfo = require("@root/Common/getBuildInfo") local getLocalUserId = require("@root/Telemetry/getLocalUserId") local requestAsync = require("@root/Http/requestAsync") local function postFeedbackAsync(title: string, body: string) local buildInfo = getBuildInfo() return requestAsync(`{_G.BASE_URL}/feedback`, { method = "POST", body = { title = title, body = body, userId = tostring(getLocalUserId()), buildVersion = buildInfo.version, buildChannel = buildInfo.channel, buildHash = buildInfo.hash, }, }) end return postFeedbackAsync
138
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Http/requestAsync.luau
local HttpService = game:GetService("HttpService") local Sift = require("@pkg/Sift") local logger = require("@root/logger") local function requestAsync( url: string, options: { method: string?, headers: { [string]: string | number | boolean }?, body: { [any]: any }?, }? ) local requestOptions = Sift.Dictionary.join({ method = "GET", headers = {}, }, options) local body if requestOptions and requestOptions.body then if typeof(requestOptions.body) == "table" then requestOptions.headers["Content-Type"] = "application/json" body = HttpService:JSONEncode(requestOptions.body) else body = tostring(requestOptions.body) end end logger:Debug(`{requestOptions.method} {url}`) local res local success, err = pcall(function() res = HttpService:RequestAsync({ Url = url, Method = requestOptions.method, Headers = requestOptions.headers, Body = body, }) end) if not success then logger:Warn("failed to communicate with backend:", err) end if res and not res.Success then logger:Warn("failed sending event to backend:", res.StatusMessage) end return res end return requestAsync
277
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Logs/LogLine.luau
local HttpService = game:GetService("HttpService") local Foundation = require("@rbxpkg/Foundation") local Log = require("@pkg/Log") local React = require("@pkg/React") local useMemo = React.useMemo local useTokens = Foundation.Hooks.useTokens type LogEvent = typeof(Log.LogEvent.new(Log.LogLevel.Information, {}, {})) local function isLogLevel(str: string) local lower = str:lower() return lower == "debug" or lower == "warn" or lower == "info" or lower == "err" end local function getLogLevelColor(tokens: Foundation.Tokens, logLevel: string): Color3 local lower = logLevel:lower() if lower == "debug" then return tokens.Color.Content.Muted.Color3 elseif lower == "warn" then return tokens.Color.System.Warning.Color3 elseif lower == "err" then return tokens.Color.System.Alert.Color3 elseif lower == "info" then return tokens.Color.System.Success.Color3 else return tokens.Color.Content.Muted.Color3 end end export type Props = { event: LogEvent, } local function LogLine(props: Props) local tokens = useTokens() local fontStyle = tokens.Typography.BodyMedium local info = useMemo(function() local text = "" local timestamp = DateTime.fromUnixTimestamp(props.event.Timestamp) :FormatLocalTime("YYYY-MM-DD hh:mm:ss A", "en-us") text ..= timestamp if #props.event.Prefixes > 0 then for _, prefix in props.event.Prefixes do if isLogLevel(prefix) then local color = getLogLevelColor(tokens, prefix):ToHex() text = `{text} <font color="#{color}">{prefix}</font>` else text = `{text} {prefix}` end end end local color = tokens.Color.Content.Muted.Color3:ToHex() text = `<font color="#{color}">{text}</font>` return text end, { props.event }) local message = "" for _, arg in props.event.Args do if typeof(arg) == "table" then message ..= HttpService:JSONEncode(arg) else message ..= tostring(arg) end message ..= " " end return React.createElement(Foundation.Text, { tag = "auto-xy text-wrap text-align-x-left text-align-y-top content-emphasis", Text = `{info}: {message}`, RichText = true, fontStyle = { Font = Enum.Font.RobotoMono, FontSize = fontStyle.FontSize, LineHeight = fontStyle.LineHeight, }, }) end return LogLine
581
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Logs/LogsStore/createLogsStore.luau
local Charm = require("@pkg/Charm") local Log = require("@pkg/Log") local Sift = require("@pkg/Sift") type LogEvent = typeof(Log.LogEvent.new(Log.LogLevel.Information, {}, {})) local function createLogsStore() local getHistory, setHistory = Charm.signal({}) local function addLine(event: LogEvent) setHistory(function(prev) return Sift.List.append(prev, event) end) end return { getHistory = getHistory, addLine = addLine, } end return createLogsStore
118
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Logs/LogsStore/init.luau
local Charm = require("@pkg/Charm") local createLogsStore = require("@self/createLogsStore") return { get = Charm.computed(createLogsStore), }
34
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Logs/LogsView.luau
local Foundation = require("@rbxpkg/Foundation") local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local LogLine = require("./LogLine") local LogsStore = require("./LogsStore") local useState = React.useState local useSignalState = ReactCharm.useSignalState local function LogsView() local logsStore = useSignalState(LogsStore.get) local history = useSignalState(logsStore.getHistory) local maxLines, _setMaxLine = useState(100) local children: { [string]: React.Node } = {} for i = math.min(#history, maxLines), 1, -1 do children[`Line{i}`] = React.createElement(LogLine, { event = history[i], }) end return React.createElement(Foundation.ScrollView, { tag = "size-full col gap-xsmall padding-medium", scroll = { AutomaticCanvasSize = Enum.AutomaticSize.Y, CanvasSize = UDim2.fromScale(1, 0), ScrollingDirection = Enum.ScrollingDirection.Y, }, layout = { FillDirection = Enum.FillDirection.Vertical, }, }, children) end return LogsView
261
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Logs/LogsView.story.luau
local React = require("@pkg/React") local LogsView = require("./LogsView") return { story = function() return React.createElement(LogsView) end, }
36
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Navigation/NavigationContext.luau
local React = require("@pkg/React") local fireEventAsync = require("@root/Telemetry/fireEventAsync") local navigationEnums = require("@root/Navigation/enums") local usePrevious = require("@root/Common/usePrevious") local useCallback = React.useCallback local useContext = React.useContext local useMemo = React.useMemo local useState = React.useState local useEffect = React.useEffect type Screen = navigationEnums.Screen export type NavigationContext = { navigateTo: (newScreen: Screen) -> (), goBack: () -> (), getBreadcrumbs: () -> { string }, canGoBack: () -> boolean, currentScreen: Screen, } local Context = React.createContext({} :: NavigationContext) export type Props = { defaultScreen: Screen, children: React.Node?, } local function Provider(props: Props) local stack: { Screen }, setStack = useState({ props.defaultScreen }) local prevStack = usePrevious(stack) local navigateTo = useCallback(function(newScreen: Screen) setStack(function(prev) local new = table.clone(prev) table.insert(new, newScreen) return new end) end, {}) local currentScreen = useMemo(function() return stack[#stack] end, { stack }) local canGoBack = useMemo(function() return #stack > 1 end, { stack }) local goBack = useCallback(function() if canGoBack then setStack(function(prev) local new = table.clone(prev) table.remove(new) return new end) end end, { canGoBack }) useEffect(function() if stack ~= prevStack then task.spawn(function() fireEventAsync({ eventName = "PageChanged", properties = { page = stack[#stack], }, }) end) end end, { stack }) return React.createElement(Context.Provider, { value = { navigateTo = navigateTo, goBack = goBack, breadcrumbs = stack, currentScreen = currentScreen, }, }, props.children) end local function use(): NavigationContext return useContext(Context) end return { Context = Context, Provider = Provider, use = use, }
461
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Navigation/Screen.luau
local React = require("@pkg/React") local Storyteller = require("@pkg/Storyteller") local AboutView = require("@root/About/AboutView") local LogsView = require("@root/Logs/LogsView") local NavigationContext = require("@root/Navigation/NavigationContext") local NoStorySelected = require("@root/Storybook/NoStorySelected") local SettingsView = require("@root/UserSettings/SettingsView") local StoryView = require("@root/Storybook/StoryView") local StorybookError = require("@root/Storybook/StorybookError") local useMemo = React.useMemo type LoadedStorybook = Storyteller.LoadedStorybook type UnavailableStorybook = Storyteller.UnavailableStorybook export type Props = { story: ModuleScript?, storybook: LoadedStorybook?, unavailableStorybook: UnavailableStorybook?, } local function Screen(props: Props) local navigation = NavigationContext.use() local currentScreen = navigation.currentScreen local screenElement = useMemo(function(): React.Node if currentScreen == "Home" then if props.story and props.storybook then return React.createElement(StoryView, { storyModule = props.story, storybook = props.storybook, }) elseif props.unavailableStorybook then return React.createElement(StorybookError, { unavailableStorybook = props.unavailableStorybook, }) else return React.createElement(NoStorySelected) end elseif currentScreen == "Settings" then return React.createElement(SettingsView) elseif currentScreen == "About" then return React.createElement(AboutView) elseif currentScreen == "Logs" then return React.createElement(LogsView) end return nil :: never end, { props, currentScreen } :: { unknown }) return screenElement end return Screen
397
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Navigation/enums.luau
local enums = {} export type Screen = "Home" | "Settings" | "About" | "Logs" enums.Screen = { Home = "Home" :: "Home", Settings = "Settings" :: "Settings", About = "About" :: "About", Logs = "Logs" :: "Logs", } return enums
71
flipbook-labs/flipbook
flipbook-labs-flipbook-8c386f7/workspace/flipbook-core/src/Panels/DragHandle.luau
local RunService = game:GetService("RunService") local React = require("@pkg/React") local ReactCharm = require("@pkg/ReactCharm") local Sift = require("@pkg/Sift") local PluginStore = require("@root/Plugin/PluginStore") local types = require("@root/Panels/types") local useColors = require("@root/Common/useColors") local useSignalState = ReactCharm.useSignalState local defaultProps = { size = 8, -- px hoverIconX = "rbxasset://textures/StudioUIEditor/icon_resize2.png", hoverIconY = "rbxasset://textures/StudioUIEditor/icon_resize4.png", } local useCallback = React.useCallback local useEffect = React.useEffect local useState = React.useState export type Props = { handle: types.DragHandle, onDrag: (delta: Vector2) -> (), onDragEnd: (() -> ())?, } type InternalProps = Props & typeof(defaultProps) local function DragHandle(providedProps: Props) local props: InternalProps = Sift.Dictionary.merge(defaultProps, providedProps) local colors = useColors() local pluginStore = useSignalState(PluginStore.get) local plugin = useSignalState(pluginStore.getPlugin) local isDragging, setIsDragging = useState(false) local isHovered, setIsHovered = useState(false) local mouseInput: InputObject?, setMouseInput = useState(nil :: InputObject?) local getHandleProperties = useCallback(function() local hitboxSize: UDim2 local highlightSize: UDim2 local position: UDim2 local anchorPoint: Vector2 if props.handle == "Right" or props.handle == "Left" then hitboxSize = UDim2.new(0, props.size, 1, 0) highlightSize = UDim2.new(0, props.size / 4, 1, 0) if props.handle == "Right" then position = UDim2.fromScale(1, 0) anchorPoint = Vector2.new(0.5, 0) else position = UDim2.fromScale(0, 0) anchorPoint = Vector2.new(0, 0) end elseif props.handle == "Top" or props.handle == "Bottom" then hitboxSize = UDim2.new(1, 0, 0, props.size) highlightSize = UDim2.new(1, 0, 0, props.size / 4) if props.handle == "Bottom" then position = UDim2.fromScale(0, 1) anchorPoint = Vector2.new(0, 0.5) else position = UDim2.fromScale(0, 0) anchorPoint = Vector2.new(0, 0) end end return hitboxSize, highlightSize, position, anchorPoint end, { props.handle, props.size } :: { unknown }) local onInputBegan = useCallback(function(_rbx, input: InputObject) if input.UserInputType == Enum.UserInputType.MouseButton1 then setIsDragging(true) elseif input.UserInputType == Enum.UserInputType.MouseMovement then setIsHovered(true) setMouseInput(input) end end, { isDragging }) local onInputEnded = useCallback(function(_rbx, input: InputObject) if input.UserInputType == Enum.UserInputType.MouseButton1 then setIsDragging(false) setMouseInput(nil) if props.onDragEnd then props.onDragEnd() end end end, { props.onDragEnd }) local onMouseEnter = useCallback(function() setIsHovered(true) end, {}) local onMouseLeave = useCallback(function() setIsHovered(false) end, {}) local hitboxSize, highlightSize, position, anchorPoint = getHandleProperties() useEffect(function(): any if mouseInput and isDragging then local lastPosition = mouseInput.Position local conn = RunService.Heartbeat:Connect(function() local delta = mouseInput.Position - lastPosition if props.onDrag and delta ~= Vector3.zero then props.onDrag(Vector2.new(delta.X, delta.Y)) end lastPosition = mouseInput.Position end) return function() conn:Disconnect() end else return nil end end, { mouseInput, isDragging } :: { unknown }) useEffect(function() if plugin then local mouse = plugin:GetMouse() if isHovered or isDragging then if props.handle == "Left" or props.handle == "Right" then mouse.Icon = props.hoverIconX elseif props.handle == "Top" or props.handle == "Bottom" then mouse.Icon = props.hoverIconY end else mouse.Icon = "" end end end, { plugin, isDragging, isHovered } :: { unknown }) return React.createElement("ImageButton", { Size = hitboxSize, Position = position, AnchorPoint = anchorPoint, BackgroundTransparency = 1, [React.Event.InputBegan] = onInputBegan, [React.Event.InputEnded] = onInputEnded, [React.Event.MouseEnter] = onMouseEnter :: any, [React.Event.MouseLeave] = onMouseLeave :: any, }, { Highlght = React.createElement("Frame", { Size = highlightSize, BorderSizePixel = 0, BackgroundTransparency = if isHovered or isDragging then colors.accent.Transparency else 1, BackgroundColor3 = colors.accent.Color3, }), }) end return DragHandle
1,247