### Install Dependencies and Start Development Server Source: https://github.com/polubis/4markdown/blob/main/README.md Installs project dependencies using npm with legacy peer dependency resolution and starts the development server. Requires Node.js and npm to be installed. ```bash npm i --legacy-peer-deps npm run start ``` -------------------------------- ### Build Project for Production Source: https://github.com/polubis/4markdown/blob/main/README.md Generates a production-ready build of the project. This command should be run after development is complete and before deployment. Requires Node.js and npm. ```bash npm run build ``` -------------------------------- ### Run Unit Tests Source: https://github.com/polubis/4markdown/blob/main/README.md Executes unit tests in watch mode, allowing for continuous testing during development. Requires Node.js and npm. ```bash npm run test:watch ``` -------------------------------- ### Development Environment Variables Source: https://github.com/polubis/4markdown/blob/main/README.md Configuration for development environment variables. These variables are crucial for the application to connect to necessary services and are typically obtained from the project administrator. ```env GATSBY_API_URL= GATSBY_API_KEY= GATSBY_AUTH_DOMAIN= GATSBY_PROJECT_ID= GATSBY_STORAGE_BUCKET= GATSBY_MESSAGING_SENDER_ID= GATSBY_APP_ID= GATSBY_MEASUREMENT_ID= ``` -------------------------------- ### JavaScript Block Code Example Source: https://github.com/polubis/4markdown/blob/main/static/intro.md A basic JavaScript code block example. ```javascript const a = 5; if (a > 5) return; ``` -------------------------------- ### Initialize Image Upload State Hook (TypeScript) Source: https://github.com/polubis/4markdown/blob/main/DS.md Initializes the state hook for image uploads using the defined UploadImageState model. This hook is required for every state management use case. ```typescript // [store]/[images]/index.ts file import { state } from 'development-kit/state'; import type { UploadImageState } from './models'; const useUploadImageState = state({ is: `idle` }); export { useUploadImageState }; ``` -------------------------------- ### Table Rendering in Markdown Source: https://github.com/polubis/4markdown/blob/main/static/intro.md Provides an example of creating a table in markdown, supporting various typography elements within cells. ```markdown | Name | Age | Country | Occupation | |-------------|-----|------------|----------------| | John Doe | 29 | **USA** | Software Dev | | Jane Smith | 34 | ~~Canada~~ | Graphic Designer| | Mike Johnson| 42 | UK | Product Manager| | Emily White | 25 | *Australia* | Data Analyst | | Sam Brown | 37 | `Germany` | Project Lead | ``` -------------------------------- ### Create Image Reset Action (TypeScript) Source: https://github.com/polubis/4markdown/blob/main/DS.md Defines a synchronous action to reset the image upload state. Actions are optional and should be created only when needed to avoid duplication. They must be synchronous and have no side effects. ```typescript // [store]/[images]/actions.ts file import { useUploadImageState } from '.'; import type { UploadImageState } from './models'; const resetImagesAction = (state: UploadImageState): void => { if (state.is !== `idle`) useUploadImageState.swap(state); }; export { resetImagesAction }; ``` -------------------------------- ### Define Image State Model (TypeScript) Source: https://github.com/polubis/4markdown/blob/main/DS.md Defines the shape of the state for image uploads using the Transaction type. This is a required step for all state management use cases. ```typescript // [store]/[images]/models.ts file import type { Transaction } from 'development-kit/utility-types'; type UploadImageState = Transaction; export type { UploadImageState }; ``` -------------------------------- ### Define Local Component Type (TypeScript) Source: https://github.com/polubis/4markdown/blob/main/DS.md An example of defining a type inline for a local component's props when the component is used for readability and does not have many properties passed to it. ```typescript // A component used primarily for readability, to avoid large chunks of JSX const SocialShare = ({ content }: { content: string }) => {}; ``` -------------------------------- ### Implement Image Upload Act (TypeScript) Source: https://github.com/polubis/4markdown/blob/main/DS.md An asynchronous act that handles the process of uploading an image. It updates the state to 'busy', calls the API, and then updates the state to 'ok' or 'fail' based on the result. Acts are globally available, reusable functions that can encapsulate complex processes. ```typescript // [acts]/upload-image.act.ts import { getAPI, parseError } from 'api-4markdown'; import { readFileAsBase64 } from 'development-kit/file-reading'; import type { API4MarkdownDto } from 'api-4markdown-contracts'; import { useUploadImageState } from 'store/images'; import type { AsyncResult } from 'development-kit/utility-types'; const uploadImageAct = async ( image: File, ): AsyncResult> => { try { useUploadImageState.swap({ is: `busy` }); const data = await getAPI().call(`uploadImage`)({ image: await readFileAsBase64(image), }); useUploadImageState.swap({ is: `ok` }); return { is: `ok`, data }; } catch (rawError: unknown) { const error = parseError(rawError); useUploadImageState.swap({ is: `fail`, error }); return { is: `fail`, error }; } }; export { uploadImageAct }; ``` -------------------------------- ### Create Image Selector (TypeScript) Source: https://github.com/polubis/4markdown/blob/main/DS.md Defines a selector to access the 'images' property from the UploadImageState. Selectors are used to avoid duplication in state access logic and must have explicit return types. ```typescript // [store]/[images]/selectors.ts file import { useUploadImageState } from '.'; import type { UploadImageState } from './models'; const imageSelector = (state: UploadImageState): UploadImageState['images'] => state.images; export { imageSelector }; ``` -------------------------------- ### Upload Base64 Image with TypeScript Source: https://context7.com/polubis/4markdown/llms.txt Handles the upload of base64-encoded images using 'uploadImageAct'. It provides feedback on upload progress, success (returning image URLs of different sizes), or failure. It also includes an example of how to handle file input and read files as data URLs. Dependencies include 'acts/upload-image.act' and 'store/upload-image'. ```typescript import { uploadImageAct } from "acts/upload-image.act"; import { useUploadImageState } from "store/upload-image"; async function uploadScreenshot(base64Image: string) { // Start upload await uploadImageAct(base64Image); // Check upload state const state = useUploadImageState.get(); if (state.is === "ok") { console.log("Small image URL:", state.sm); console.log("Medium image URL:", state.md); console.log("Large image URL:", state.lg); // Embed in markdown: ![Description](${state.md}) } else if (state.is === "fail") { console.error("Upload failed:", state.error.message); } else { console.log("Upload in progress..."); } } // Example with file input function handleFileSelect(event: React.ChangeEvent) { const file = event.target.files?.[0]; if (file) { const reader = new FileReader(); reader.onload = (e) => { uploadScreenshot(e.target?.result as string); }; reader.readAsDataURL(file); } } ``` -------------------------------- ### Display Mindmap Examples Modal with React Source: https://github.com/polubis/4markdown/blob/main/CHANGE_LOG.md A React functional component that utilizes the `useSimpleFeature` hook from '@greenonsoftware/react-kit' to manage modal visibility. It renders a button to open a modal containing "Mindmap Examples" using components from a 'design-system' library. The modal can be closed by clicking a close button. ```jsx import React from 'react'; import { Button } from 'design-system/button'; import { Modal } from 'design-system/modal'; import { useSimpleFeature } from '@greenonsoftware/react-kit'; const ExamplesContainer = () => { const examplesModal = useSimpleFeature(); return ( <> {examplesModal.isOn && ( )} ); }; export { ExamplesContainer }; ``` -------------------------------- ### Get User Documents in TypeScript Source: https://context7.com/polubis/4markdown/llms.txt Retrieves all documents associated with the authenticated user. It calls `getYourDocumentsAction` and then accesses the documents from the `docsStoreSelectors`. The function logs the total number of documents and details of each document, including its name, visibility, and path. ```typescript import { getYourDocumentsAction } from "actions/get-your-documents.action"; import { docsStoreSelectors } from "store/docs/docs.store"; async function loadUserDocuments() { await getYourDocumentsAction(); // Access documents from store const docsState = docsStoreSelectors.ok(); console.log("Total documents:", docsState.docs.length); docsState.docs.forEach(doc => { console.log(`${doc.name} (${doc.visibility}) - ${doc.path}`); // Document properties: id, name, code, path, visibility, cdate, mdate }); } ``` -------------------------------- ### Image Rendering in Markdown Source: https://github.com/polubis/4markdown/blob/main/static/intro.md Demonstrates the markdown syntax for rendering images, including an optional description. ```markdown ![image alt](image url) // Add here enter for better formatting *description* // Description is optional ``` -------------------------------- ### Ordered, Unordered, and Todo Lists in Markdown Source: https://github.com/polubis/4markdown/blob/main/static/intro.md Demonstrates how to create ordered, unordered, and todo lists using markdown syntax. Supports nesting with tabs or spaces. ```markdown // @@@ Ordered 1. First 2. Second // @@@ Unordered - First - Second // @@@ Todo list - [x] First - [ ] Second // or 1. [x] First 2. [ ] Second // [space] and first letter are important! ``` ```markdown 1. First level - Child 1 - Child 2 - [x] Child 3 - [ ] Child 4 2. Second level 1. Child 2.1 2. Child 2.2 ``` -------------------------------- ### Math Syntax Block Rendering in Markdown Source: https://github.com/polubis/4markdown/blob/main/static/intro.md Shows how to render mathematical formulas in a block using double dollar signs. ```markdown $$ overline{x} = \frac{1}{n}\left(\sum_{i=1}^{n}{x_{i}}\right) $$ ``` -------------------------------- ### State Management - Auth Store in TypeScript Source: https://context7.com/polubis/4markdown/llms.txt Demonstrates authentication state management using the Zustand store pattern. It shows how to use `useAuthStore`, `authStoreActions`, and `authStoreSelectors` within a React component to display user information or sign-in/sign-out options. Actions for authorizing and unauthorizing users are also provided. ```typescript import { useAuthStore, authStoreActions, authStoreSelectors } from "store/auth/auth.store"; // In React component function ProfileButton() { const authState = useAuthStore(); if (authState.is === "idle") { return
Loading...
; } if (authState.is === "unauthorized") { return ; } // authState.is === "authorized" return (
{authState.user.name} {authState.user.name}
); } // Outside component - actions authStoreActions.authorize({ uid: "user123", name: "John Doe", avatar: "https://example.com/avatar.jpg" }); authStoreActions.unauthorize(); // Get authorized state (throws if not authorized) try { const authorized = authStoreSelectors.authorized(); console.log("Current user:", authorized.user.name); } catch (error) { console.log("User not authorized"); } ``` -------------------------------- ### Gatsby Build API - Create Pages in TypeScript Source: https://context7.com/polubis/4markdown/llms.txt This TypeScript code snippet, intended for `gatsby-node.ts`, outlines the process of generating static pages during a Gatsby build. It involves fetching data from Firebase, creating pages for documents and mindmaps, generating a search index, and organizing content by tags and ratings. The build command is `npm run build`, outputting to the `public/` directory. ```typescript // In gatsby-node.ts import { createPages } from "./gatsby-node"; // This function runs during Gatsby build // It fetches all permanent documents and mindmaps // Creates static pages for each document and mindmap // Generates search-data.json for client-side search // Creates paginated education zone pages // Organizes content by tags and ratings // Example of generated pages: // - / (home page) // - /document-path (individual document pages) // - /mindmap/mindmap-id (mindmap pages) // - /education-zone/ (paginated document lists) // - /education-zone/react (tag-filtered pages) // - /education-rank/ (top-rated documents) // Build command: npm run build // Output: public/ directory with static HTML files ``` -------------------------------- ### Block Code Rendering in Markdown Source: https://github.com/polubis/4markdown/blob/main/static/intro.md Illustrates how to render blocks of code in markdown, with support for specifying the language. JavaScript is the default. ```markdown The comments marker "//" is added to allow the display of "```" in the snippet. Normally, you don't need this //``` const a = 5; if (a > 5) return; //``` // or //```typescript // Language is optional (JavaScript is default) const a = 5; if (a > 5) return; //``` ``` -------------------------------- ### Inline Code Formatting in Markdown Source: https://github.com/polubis/4markdown/blob/main/static/intro.md Illustrates how to format inline code using backticks. ```markdown const a = 5 ``` -------------------------------- ### Mathematical Expression Formatting in Markdown Source: https://github.com/polubis/4markdown/blob/main/static/intro.md Demonstrates how to format mathematical expressions inline using dollar signs. ```markdown $overline{x} = \frac{1}{n}\left(\sum_{i=1}^{n}{x_{i}}\right)$ ``` -------------------------------- ### Create Interactive Mindmap with TypeScript Source: https://context7.com/polubis/4markdown/llms.txt Sets up and saves an interactive mindmap structure including nodes and edges. It utilizes store management for the mindmap's state and an asynchronous action for saving. Dependencies include 'acts/create-mindmap.act' and 'store/mindmap-creator'. ```typescript import { createMindmapAct } from "acts/create-mindmap.act"; import { useMindmapCreatorState } from "store/mindmap-creator"; // Setup mindmap structure in store useMindmapCreatorState.set({ nodes: [ { id: "1", type: "input", data: { label: "Main Topic" }, position: { x: 250, y: 5 } }, { id: "2", data: { label: "Subtopic 1" }, position: { x: 100, y: 100 } }, { id: "3", data: { label: "Subtopic 2" }, position: { x: 400, y: 100 } } ], edges: [ { id: "e1-2", source: "1", target: "2" }, { id: "e1-3", source: "1", target: "3" } ], orientation: "vertical" }); // Create mindmap async function saveMindmap() { await createMindmapAct({ name: "Project Architecture", description: "System architecture overview", tags: ["architecture", "design"] }); console.log("Mindmap created and saved"); } ``` -------------------------------- ### Quote Rendering in Markdown Source: https://github.com/polubis/4markdown/blob/main/static/intro.md Shows how to create a blockquote in markdown using the greater-than symbol. ```markdown // Remember about space > The best developers understand the value of pair programming ``` -------------------------------- ### AI Content Rewriting - Rewrite Documentation (TypeScript) Source: https://context7.com/polubis/4markdown/llms.txt Rewrites existing text content using AI assistance, allowing for different personas and styles. The function takes the original text and a persona as input, returning the rewritten content and the remaining token count. It depends on the 'acts/rewrite-with-assistant.act' module. ```typescript import { rewriteWithAssistantAct } from "acts/rewrite-with-assistant.act"; async function improveContent() { const originalText = "This is my draft documentation that needs improvement."; const result = await rewriteWithAssistantAct({ input: originalText, persona: "professional" // Options: "professional", "casual", "technical" }); if (result.is === "ok") { console.log("Rewritten content:", result.data.output); console.log("Tokens remaining:", result.data.tokensAfter); } else { console.error("Rewrite failed:", result.error.message); } } ``` -------------------------------- ### Firebase Authentication - User Login (TypeScript) Source: https://context7.com/polubis/4markdown/llms.txt Handles user authentication using Google OAuth or email/password via Firebase. It initializes the API, logs in users, and listens for authentication state changes to update the application's authorization store. Dependencies include the 'api-4markdown' library. ```typescript import { getAPI } from "api-4markdown"; // Initialize API first (typically in app bootstrap) import { initializeAPI } from "api-4markdown"; const api = initializeAPI("2025-01-18T12:00:00.000Z"); // Cache version // Login user with Google OAuth popup async function handleLogin() { try { await getAPI().logIn(); console.log("User authenticated successfully"); } catch (error) { console.error("Authentication failed:", error); } } // Listen to authentication state changes getAPI().onAuthChange( (user) => { if (user) { console.log("User logged in:", user.uid, user.displayName); // Update auth store authStoreActions.authorize({ uid: user.uid, name: user.displayName, avatar: user.photoURL, }); } else { console.log("User logged out"); authStoreActions.unauthorize(); } }, (error) => console.error("Auth error:", error) ); ``` -------------------------------- ### AI Content Generation - Create Markdown Content (TypeScript) Source: https://context7.com/polubis/4markdown/llms.txt Generates markdown content using AI based on a structured prompt that includes details like profession, desired style, and structure. The output includes the generated markdown and remaining token count. This function requires the 'acts/create-content-with-ai.act' module and interacts with the document creator state. ```typescript import { createContentWithAIAct } from "acts/create-content-with-ai.act"; async function generateDocumentation() { const result = await createContentWithAIAct({ name: "React Hooks Guide", description: "A comprehensive guide explaining React hooks with examples", profession: "Software Developer", style: ["technical", "practical"], structure: "tutorial", sample: "Include code examples and best practices", prompt: "Focus on useState and useEffect hooks" }); if (result.is === "ok") { console.log("Generated content:", result.data.output); console.log("Tokens remaining:", result.data.tokensAfter); // Use the generated markdown content useDocumentCreatorState.set({ code: result.data.output }); } else { console.error("AI generation failed:", result.error.message); } } ``` -------------------------------- ### Search Static Content Index with TypeScript Source: https://context7.com/polubis/4markdown/llms.txt Searches a pre-generated static content index for documents using the 'searchStaticContentAct' action. It returns documents that match the search query based on title and description. The function handles successful searches and logs errors if the search fails. It depends on 'acts/search-static-content.act'. ```typescript import { searchStaticContentAct } from "acts/search-static-content.act"; async function searchDocuments(query: string) { const result = await searchStaticContentAct(); if (result.is === "ok") { // Filter results by query const filtered = result.data.filter(item => item.title.toLowerCase().includes(query.toLowerCase()) || item.description.toLowerCase().includes(query.toLowerCase()) ); console.log("Search results:", filtered); // Each item contains: { title, description, url } filtered.forEach(item => { console.log(`${item.title}: ${item.url}`); }); } else { console.error("Search failed:", result.error.message); } } ``` -------------------------------- ### Create Document - New Markdown Document (TypeScript) Source: https://context7.com/polubis/4markdown/llms.txt Creates a new markdown document with a specified name and initial content. The document is stored in Firebase and automatically added to the application's document store, becoming the active document. This function relies on the 'acts/create-document.act' module and Zustand for state management. ```typescript import { createDocumentAct } from "acts/create-document.act"; import { useDocumentCreatorState } from "store/document-creator"; // Set document content in store first useDocumentCreatorState.set({ code: "# My Document\n\nThis is the content of my markdown document.\n\n## Features\n- Item 1\n- Item 2" }); // Create document async function createNewDocument() { const result = await createDocumentAct({ name: "Getting Started Guide" }); if (result.is === "ok") { console.log("Document created successfully"); // Document is automatically added to docs store // and set as active document } else { console.error("Failed to create document:", result.error.message); } } ``` -------------------------------- ### Rate Document with TypeScript Source: https://context7.com/polubis/4markdown/llms.txt Allows users to rate documents using the 'rateDocumentAct' action. It takes a document ID and a category (e.g., 'perfect', 'good') as input. The function handles successful updates and logs errors if the rating fails. It depends on 'acts/rate-document.act'. ```typescript import { rateDocumentAct } from "acts/rate-document.act"; async function rateArticle(documentId: string) { const result = await rateDocumentAct({ documentId: documentId, category: "perfect" // Options: "perfect", "good", "decent", "bad", "ugly" }); if (result.is === "ok") { console.log("Updated rating:", result.data); // Rating object contains counts: { perfect: 5, good: 3, decent: 1, bad: 0, ugly: 0 } } else { console.error("Rating failed:", result.error.message); } } ``` -------------------------------- ### Update Document Visibility with TypeScript Source: https://context7.com/polubis/4markdown/llms.txt Changes the visibility status of a document to 'private', 'public', or 'permanent' using the 'updateDocumentVisibilityAction'. Permanent visibility requires additional metadata like name, description, and tags. This function depends on 'actions/update-document-visibility.action'. ```typescript import { updateDocumentVisibilityAction } from "actions/update-document-visibility.action"; async function publishDocument(documentId: string) { await updateDocumentVisibilityAction({ id: documentId, mdate: new Date().toISOString(), visibility: "permanent", // Options: "private", "public", "permanent" // Required for permanent visibility: name: "Ultimate React Guide", description: "Complete guide to React development", tags: ["react", "javascript", "frontend"] }); console.log("Document visibility updated"); } ``` -------------------------------- ### Generate Gatsby Build ID with Node.js Source: https://github.com/polubis/4markdown/blob/main/CHANGE_LOG.md This Node.js script, intended for Gatsby's onPreBootstrap hook, generates a unique build ID using `randomUUID()` and sets it as the GATSBY_BUILD_ID environment variable. It has no external dependencies beyond Node.js's built-in `crypto` module for `randomUUID`. ```javascript const fitViewOptions = { duration: 700, }; export const onPreBootstrap: GatsbyNode['onPreBootstrap'] = () => { const buildId = randomUUID(); process.env.GATSBY_BUILD_ID = buildId; }; ``` -------------------------------- ### Report Bug in TypeScript Source: https://context7.com/polubis/4markdown/llms.txt Submits a bug report to the system. This function uses the `reportBugAct` to send the bug's title, description, and the current page URL. It includes error handling to log any failures during submission. ```typescript import { reportBugAct } from "acts/report-bug.act"; async function submitBugReport() { try { await reportBugAct({ title: "Editor syntax highlighting broken", description: "When using triple backticks for code blocks, the syntax highlighting doesn't work for TypeScript.", url: window.location.href }); console.log("Bug report submitted successfully"); } catch (error) { console.error("Failed to submit bug report:", error); } } ``` -------------------------------- ### Update User Profile in TypeScript Source: https://context7.com/polubis/4markdown/llms.txt Updates user profile details such as display name, bio, social links, and avatar. It uses the `updateYourUserProfileAct` function and accepts an optional avatar in base64 format. The function handles avatar updates, no-ops, or removal. ```typescript import { updateYourUserProfileAct } from "acts/update-your-user-profile.act"; async function saveProfile(avatarBase64?: string) { await updateYourUserProfileAct({ displayName: "John Developer", bio: "Full-stack developer passionate about React and TypeScript", blogUrl: "https://myblog.com", githubUrl: "https://github.com/johndoe", linkedInUrl: "https://linkedin.com/in/johndoe", twitterUrl: "https://twitter.com/johndoe", fbUrl: "", mdate: new Date().toISOString(), avatar: avatarBase64 ? { type: "update", data: avatarBase64 } : { type: "noop" } // avatar: { type: "remove" } to delete avatar }); console.log("Profile updated successfully"); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.