### Start Development Server Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Starts the local development server after node modules have been installed. ```bash make dev ``` -------------------------------- ### Run Storybook Dev Server Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Starts the Storybook development server for isolated component development and demonstration. Ensure Node.js is installed and managed via NVM or nodenv. ```sh npm run storybook ``` -------------------------------- ### Install Dependencies Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Run this command to install project dependencies both inside the Docker container and on your host machine. ```bash make install ``` -------------------------------- ### Get All Projects for a User Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Fetches all projects associated with a given user ID. ```typescript // Get all projects for a user const userProjects = await projects.getForUser(userId); ``` -------------------------------- ### Run Dev Server with Remote Stack Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Installs dependencies and runs the development server using the `dev:remote` script to connect to the staging API. ```bash npm install npm run dev:remote ``` -------------------------------- ### Get Pinned Projects Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Retrieves projects that have been pinned by the user. ```typescript // Get pinned projects const pinnedProjects = await projects.getPinnedProjects(); ``` -------------------------------- ### Node Version Management Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Installs and manages Node.js versions using NVM or nodenv. Recommended for ensuring consistent Node.js environments. ```sh node -v nvm install 20 # or nvm install --lts ``` -------------------------------- ### Handle API Responses and Errors in TypeScript Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Demonstrates fetching data from an API endpoint, handling potential errors, and processing successful responses. Includes examples for getting CSRF tokens, paginating results, and handling private asset redirects. ```typescript import { getApiResponse, getAll, getPrivateAsset, getCsrfToken, isErrorCode } from "$lib/utils/api"; // Get CSRF token from cookies const csrfToken = getCsrfToken(); // Handle API response with error checking const response = await fetch(endpoint, { credentials: "include" }); const { data, error } = await getApiResponse(response); if (error) { console.error(`API Error ${error.status}: ${error.message}`); if (error.errors) { // Handle validation errors Object.entries(error.errors).forEach(([field, messages]) => { console.error(`${field}: ${messages.join(", ")}`); }); } } else { console.log("Success:", data); } // Paginate through all results const allItems = await getAll(endpoint, 100); // Handle private asset redirect (S3 presigned URLs) const assetUrl = await getPrivateAsset(privateUrl); // Check for error status codes if (isErrorCode(response.status)) { console.error("Request failed"); } ``` -------------------------------- ### Document Creation and Upload Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Create a new document to get a presigned URL for file uploads. Use the upload function with the URL and file object. ```typescript // Create a new document (returns presigned_url for upload) const { data: newDoc } = await documents.create({ title: "My Document", access: "private", language: "eng", source: "FOIA Request" }, csrf_token); // Upload file to presigned URL if (newDoc?.presigned_url) { await documents.upload(new URL(newDoc.presigned_url), file); } ``` -------------------------------- ### Legacy Document Viewer Embed Script Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Provides an example of how to use the legacy DV.load API for backwards compatibility to embed document viewers in web pages. ```javascript // Legacy DV.load API (for backwards compatibility) DV.load("https://www.documentcloud.org/documents/123-my-document.html", { container: "#document-viewer", width: 800, height: 600, sidebar: true, text: true, pdf: true, page: 5, note: 123, responsive: true, responsiveOffset: 100 }); ``` -------------------------------- ### Get Organizations for a User Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Fetches the list of organizations a user belongs to. ```typescript // Get organizations a user belongs to const orgs = await accounts.userOrgs(user); ``` -------------------------------- ### Get Single Project Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Retrieves a specific project using its unique ID. ```typescript // Get a single project const { data: project } = await projects.get(projectId); ``` -------------------------------- ### Get Organization Upgrade URL Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Generates the URL for an organization's upgrade page, typically used for billing or plan changes. ```typescript // Get upgrade URL for billing const upgradeUrl = accounts.getUpgradeUrl(org); ``` -------------------------------- ### Get Users in an Organization Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Retrieves a list of users who are members of a specific organization. ```typescript // Get users in an organization const orgMembers = await accounts.orgUsers(org); ``` -------------------------------- ### Note URL Generation and Utilities Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Generate various URLs for notes, including a hash URL, a full URL with document context, and a canonical URL. Check if a note is page-level and get its dimensions. ```typescript // Generate URLs for notes const hashUrl = notes.noteHashUrl(note); // #document/p3/a557 const fullUrl = notes.noteUrl(document, note); const canonicalUrl = notes.canonicalNoteUrl(document, note); // Check if note is page-level (no region) if (notes.isPageLevel(note)) { console.log("This is a page-level note"); } // Get note dimensions const noteWidth = notes.width(note); const noteHeight = notes.height(note); ``` -------------------------------- ### List and Get Notes Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Retrieve a list of all notes associated with a document or fetch a specific note using document and note IDs. ```typescript import * as notes from "$lib/api/notes"; // List all notes on a document const { data: notesList } = await notes.list(documentId); // Get a specific note const { data: note } = await notes.get(documentId, noteId); ``` -------------------------------- ### Get Current Logged-in User Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Retrieves information about the currently authenticated user, including their name and organization count. Includes a helper to get the user's name. ```typescript import * as accounts from "$lib/api/accounts"; // Get the current logged-in user const user = await accounts.getMe(); if (user) { console.log(`Logged in as: ${accounts.getUserName(user)}`); console.log(`Organizations: ${user.organizations.length}`); } ``` -------------------------------- ### RangeBuilder Component Source: https://github.com/muckrock/documentcloud-frontend/blob/main/src/lib/components/documents/search/README.md A modal component for building date or number range queries. It offers preset shortcuts and custom input fields for start and end bounds. ```svelte console.log(`Range updated: ${start} to ${end}`)} /> ``` -------------------------------- ### Retrieve Document Content and URLs Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Get the text content of a document, iterating through its pages. Generate URLs for the PDF, a specific page image, and an embeddable widget. ```typescript // Get text content const text = await documents.text(doc); text.pages.forEach(page => console.log(page.contents)); // URL utilities const pdfUrl = documents.pdfUrl(doc); const pageImage = documents.pageImageUrl(doc, 1, "large"); const embedUrl = documents.embedUrl(doc, new URLSearchParams({ sidebar: "0" })); ``` -------------------------------- ### Manage Document Sections Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Use the Sections API to manage document table of contents entries for navigation. This includes listing, getting, creating, updating, and deleting sections. ```typescript import * as sections from "$lib/api/sections"; // List all sections in a document const sectionList = await sections.list(documentId); // Get a specific section const section = await sections.get(documentId, sectionId); // Create a new section const { data: newSection } = await sections.create( documentId, { page_number: 5, title: "Chapter 2: Findings" }, csrf_token ); // Update a section const { data: updated } = await sections.update( documentId, sectionId, { title: "Updated Chapter Title" }, csrf_token ); // Delete a section await sections.remove(documentId, sectionId, csrf_token); ``` -------------------------------- ### Import Configuration Constants in JavaScript Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Shows how to import various configuration constants such as API URLs, limits, and language codes from a central configuration file. ```javascript import { BASE_API_URL, APP_URL, EMBED_URL, SQUARELET_BASE, CSRF_HEADER_NAME, CSRF_COOKIE_NAME, DEFAULT_PER_PAGE, MAX_PER_PAGE, PDF_SIZE_LIMIT, DOCUMENT_SIZE_LIMIT, UPLOAD_LIMIT, LANGUAGE_CODES, LANGUAGE_MAP, DOCUMENT_TYPES, } from "@/config/config.js"; // Image size constants const IMAGE_WIDTHS = { xlarge: 2000, large: 1000, normal: 700, small: 180, thumbnail: 60 }; ``` -------------------------------- ### Build for Production Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Compiles the production version of the application. This command is automatically executed during Netlify and Github Actions builds. ```bash make build ``` -------------------------------- ### Run Unit Tests Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Executes the unit test suite for the project. ```bash npm run test:unit ``` -------------------------------- ### Configure Local Hosts Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Adds an entry to your hosts file to map a domain to your local machine for development. ```bash echo "127.0.0.1 www.dev.documentcloud.org" | sudo tee -a /etc/hosts ``` -------------------------------- ### Create New Project Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Creates a new project with specified title, description, and privacy/pinning settings. Requires a CSRF token. ```typescript // Create a new project const { data: newProject } = await projects.create({ title: "Investigation 2024", description: "Documents related to ongoing investigation", private: true, pinned: true }, csrf_token); ``` -------------------------------- ### Lint Codebase with Knip Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Runs Knip to identify and clean up unused files and dependencies in the codebase. Review output for potential errors before committing. ```bash npm run knip ``` -------------------------------- ### List Projects with Pagination Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Use this to retrieve a paginated list of projects. Requires `per_page` and a `cursor` for subsequent requests. ```typescript import * as projects from "$lib/api/projects"; // List projects with pagination const { data: projectList } = await projects.list({ per_page: 25, cursor: "" }); ``` -------------------------------- ### Create Local Certificate Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Generates a local SSL certificate for the custom localhost domain used with the remote stack. ```bash mkdir certs && cd certs mkcert -install mkcert local.staging.documentcloud.org ``` -------------------------------- ### Run Python Translation Script Source: https://github.com/muckrock/documentcloud-frontend/blob/main/utility/README.md Execute the translate.py script using uv to manage dependencies. Ensure Ollama is running locally with the llama3.2 model. ```sh ollama pull llama3.2 ollama serve # if not already sarted uv run utilities/translate.py json src/langs/json/en.json -d src/langs/json/it.json -l Italian ``` -------------------------------- ### Create Page-Level and Region Notes Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Create a page-level note by specifying the page number and content. For region-specific notes, include bounding box coordinates (x1, y1, x2, y2) as percentages. ```typescript // Create a page-level note (no coordinates) const { data: pageNote } = await notes.create(documentId, { page_number: 0, title: "Important Section", content: "This section contains key findings.", access: "public" }, csrf_token); // Create a region-specific note with bounding box const { data: regionNote } = await notes.create(documentId, { page_number: 2, title: "Highlighted Text", content: "This paragraph is significant.", access: "private", x1: 0.1, // coordinates as percentage of page (0-1) y1: 0.2, x2: 0.9, y2: 0.35 }, csrf_token); ``` -------------------------------- ### List Collaborators on Project Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Retrieves all collaborators for a given project and logs their username and access level. ```typescript import * as collaborators from "$lib/api/collaborators"; // List all collaborators on a project const projectUsers = await collaborators.list(projectId); projectUsers.forEach(({ user, access }) => { console.log(`${user.name}: ${access}`); // "view" | "edit" | "admin" }); ``` -------------------------------- ### Run Playwright Tests Locally Source: https://github.com/muckrock/documentcloud-frontend/blob/main/tests/README.md Execute Playwright tests by setting the URL environment variable to your running site instance. ```sh URL=https://www.dev.documentcloud.org npx playwright test ``` -------------------------------- ### Run Browser Tests Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Executes browser-based tests using Playwright. Ensure the frontend, backend, and Squarelet are running before executing this command. ```bash npm run test:browser ``` -------------------------------- ### List Users with Filters Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Retrieves a list of users, allowing filtering by name prefix and organization. Returns paginated data. ```typescript // List users with filters const { data: users } = await accounts.listUsers({ name__istartswith: "john", organization: "123" }); ``` -------------------------------- ### Decoration Plugin - Syntax Highlighting Source: https://github.com/muckrock/documentcloud-frontend/blob/main/src/lib/components/documents/search/README.md Applies visual syntax highlighting to the ProseMirror editor content without altering the document structure. It highlights operators, parentheses, and prefixes. ```typescript import { EditorState, Plugin, PluginKey } from "prosemirror-state"; import { Decoration, DecorationSet } from "prosemirror-view"; import { schema } from "../prosemirror/schema"; // Assuming schema is imported export const decorationPluginKey = new PluginKey("decoration"); export function decorationPlugin() { return new Plugin({ key: decorationPluginKey, state: { init(config, editorState) { return DecorationSet.empty; }, apply(tr, value, editorState, newState) { // Re-calculate decorations after each transaction const builder = newState.schema.cached.get("decorationBuilder"); if (!builder) { // Build decorations based on the current document state // This involves parsing the serialized query string or analyzing the ProseMirror doc const decorations = []; // Example: Highlight boolean operators newState.doc.descendants((node, pos) => { if (node.type.name === "text") { const text = node.text; if (text) { const andMatch = text.match(/AND/g); if (andMatch) { andMatch.forEach(match => { const index = text.indexOf(match); decorations.push( Decoration.inline(pos + index, pos + index + match.length, { class: "ProseMirror-decoration-operator", // CSS class for styling }) ); }); } // Add similar logic for OR, NOT, parentheses, prefixes (+/-) } } }); return DecorationSet.create(newState.doc, decorations); } return value; }, }, props: { decorations(state) { return this.getState(state); }, }, }); } ``` -------------------------------- ### Manage DocumentCloud Add-ons Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Use the Add-ons API to manage DocumentCloud extensions for AI analysis, export, and document processing. This includes listing, dispatching, scheduling, and managing add-on runs. ```typescript import * as addons from "$lib/api/addons"; // List available add-ons const { data: addonList } = await addons.getAddons({ active: true, category: "ai" }); // Get pinned (active) add-ons const { data: pinned } = await addons.getPinnedAddons(); // Get a specific add-on by repository const addon = await addons.getAddon("MuckRock", "documentcloud-hello-world"); // Dispatch an add-on run on selected documents const { data: run } = await addons.dispatch({ addon: addon.id, parameters: { language: "en", model: "gpt-4" }, documents: [123, 456, 789] }, csrf_token); // Dispatch add-on on a search query const { data: queryRun } = await addons.dispatch({ addon: addon.id, parameters: {}, query: "project:1234 access:public" }, csrf_token); // Schedule a recurring add-on event const { data: scheduled } = await addons.dispatch({ addon: addon.id, parameters: {}, event: addons.eventValues.daily, // 0=disabled, 1=hourly, 2=daily, 3=weekly, 4=upload query: "user:me" }, csrf_token); // Get add-on run history const { data: history } = await addons.history({ per_page: 25, dismissed: false }); // Get scheduled events const { data: events } = await addons.scheduled(); // Update a scheduled event await addons.update(eventId, { addon: addon.id, parameters: { updated: true }, event: addons.eventValues.weekly }, csrf_token); // Cancel a running add-on await addons.cancel(runUuid, csrf_token); // Rate an add-on run await addons.rate(runUuid, 1, csrf_token); // 1=positive, 0=neutral, -1=negative // Dismiss a completed run notification await addons.dismiss(runUuid, csrf_token); // Build and validate payload from form data const payload = addons.buildPayload(addon, formData, true); if (!payload.valid) { console.error("Validation errors:", payload.errors); } ``` -------------------------------- ### Accounts API Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Handle user authentication, organization management, and account settings. ```APIDOC ## Accounts API ### Description The Accounts API handles user authentication, organization management, and account settings. ### Methods - **Get the current logged-in user** - **Endpoint**: `/me` (implied) - **Response Example**: ```json { "id": "user_id", "name": "User Name", "organizations": [ { "id": "org_id_1", "name": "Organization 1" } ] } ``` - **Get organizations a user belongs to** - **Endpoint**: `/users/{userId}/orgs` (implied) - **Path Parameters**: - `userId` (string) - Required - The ID of the user. - **Get users in an organization** - **Endpoint**: `/orgs/{orgId}/users` (implied) - **Path Parameters**: - `orgId` (string) - Required - The ID of the organization. - **Switch active organization** - **Endpoint**: `/orgs/{orgId}/set` - **Method**: POST - **Path Parameters**: - `orgId` (string) - Required - The ID of the organization to switch to. - **Headers**: - `X-CSRF-Token`: (string) - Required - CSRF token for authentication. - **List users with filters** - **Endpoint**: `/users` - **Method**: GET - **Query Parameters**: - `name__istartswith` (string) - Optional - Filter users by name starting with (case-insensitive). - `organization` (string) - Optional - Filter users by organization ID. - **Response Example**: ```json { "data": [ { "id": "user_id_2", "name": "John Doe" } ] } ``` - **List organizations** - **Endpoint**: `/orgs` - **Method**: GET - **Query Parameters**: - `name__istartswith` (string) - Optional - Filter organizations by name starting with (case-insensitive). - **Response Example**: ```json { "data": [ { "id": "org_id_2", "name": "News Org" } ] } ``` - **Create/destroy mail key for email uploads** - **Endpoint**: `/mailkey` - **Method**: POST (create), DELETE (destroy) - **Headers**: - `X-CSRF-Token`: (string) - Required - CSRF token for authentication. - **Response Example (create)**: ```json { "key": "generated_mail_key" } ``` - **Check organization premium status** - **Function**: `isPremiumOrg(org)` - Returns `true` if the organization is premium, `false` otherwise. - **Parameters**: - `org` (object) - Required - The organization object. - **Get credit balance for an organization** - **Function**: `getCreditBalance(org)` - Returns the available credit balance for the organization. - **Parameters**: - `org` (object) - Required - The organization object. - **Get upgrade URL for billing** - **Function**: `getUpgradeUrl(org)` - Returns the URL for upgrading the organization's plan. - **Parameters**: - `org` (object) - Required - The organization object. ``` -------------------------------- ### Local Cloudflare Worker Emulation Source: https://github.com/muckrock/documentcloud-frontend/blob/main/docs/cloudflare.md Emulate the Cloudflare Worker environment locally for testing and validation. This command is primarily for validating Wrangler configurations. ```bash npx wrangler dev --config wrangler.staging.jsonc ``` -------------------------------- ### Add Documents to Project Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Adds one or more documents to a project. Requires the project ID, an array of document IDs, and a CSRF token. ```typescript // Add documents to a project await projects.add(projectId, [docId1, docId2, docId3], csrf_token); ``` -------------------------------- ### Edit Project Metadata Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Updates the title and description of an existing project. Requires the project ID and a CSRF token. ```typescript // Edit project metadata await projects.edit(projectId, { title: "Updated Project Name", description: "New description" }, csrf_token); ``` -------------------------------- ### Autocomplete Data - Range Configurations Source: https://github.com/muckrock/documentcloud-frontend/blob/main/src/lib/components/documents/search/README.md Specifies predefined range shortcuts and configurations for date and numeric fields, used by the RangeBuilder component. ```typescript export const rangeConfigurations = { date: { shortcuts: [ { label: "Last week", value: { start: "-7d/d", end: "now/d" } }, { label: "Last month", value: { start: "-1M/d", end: "now/d" } }, ], // ... other date range options }, number: { // ... number range options }, }; ``` -------------------------------- ### Decoration Plugin - Syntax Error Highlighting Source: https://github.com/muckrock/documentcloud-frontend/blob/main/src/lib/components/documents/search/README.md Identifies and visually marks syntax errors within the serialized query string, such as empty quotes or unbalanced parentheses, using wavy underlines. ```typescript // Within the decorationPlugin function's apply method: newState.doc.descendants((node, pos) => { if (node.type.name === "text") { const text = node.text; if (text) { // Example: Detect empty quotes const emptyQuoteMatch = text.match(/""/g); if (emptyQuoteMatch) { emptyQuoteMatch.forEach(match => { const index = text.indexOf(match); decorations.push( Decoration.inline(pos + index, pos + index + match.length, { class: "ProseMirror-decoration-error", // CSS class for wavy underline }) ); }); } // Add similar logic for unbalanced quotes, incomplete ranges, etc. } } }); // Ensure the ProseMirror-editor CSS includes styles for .ProseMirror-decoration-error // e.g., .ProseMirror-decoration-error { text-decoration: wavy underline red; } ``` -------------------------------- ### Generate Project URLs Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Generates canonical and embeddable URLs for a project. The embed URL can accept URL search parameters. ```typescript // Generate project URLs const projectUrl = projects.canonicalUrl(project); const embedUrl = projects.embedUrl(project, new URLSearchParams({ per_page: "12" })); ``` -------------------------------- ### ChipEditor Component Usage Source: https://github.com/muckrock/documentcloud-frontend/blob/main/src/lib/components/documents/search/README.md A popover component for editing chip parameters like prefix, boost, or deletion. It uses @floating-ui/dom for positioning and supports keyboard navigation. ```svelte { /* handle close */ }} onUpdate={(params) => { /* handle update */ }} /> ``` -------------------------------- ### Run Unit Tests in Watch Mode Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Executes unit tests and automatically re-runs them as code changes are detected. ```bash npm run test:watch ``` -------------------------------- ### List Organizations Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Retrieves a list of organizations, allowing filtering by name prefix. Returns paginated data. ```typescript // List organizations const { data: orgs } = await accounts.listOrgs({ name__istartswith: "news" }); ``` -------------------------------- ### Autocomplete Plugin - Field Stage Source: https://github.com/muckrock/documentcloud-frontend/blob/main/src/lib/components/documents/search/README.md Implements the first stage of the multi-stage autocomplete system. It displays a dropdown of matching field names as the user types. ```typescript import { EditorState, Plugin, PluginKey } from "prosemirror-state"; import { EditorView } from "prosemirror-view"; import { findAutocompleteTrigger } from "./autocomplete-utils"; // Assume this utility exists export const autocompletePluginKey = new PluginKey("autocomplete"); export function autocompletePlugin(options: { getFieldSuggestions: (query: string) => Promise }) { return new Plugin({ key: autocompletePluginKey, state: { init(config, editorState) { return { active: false, stage: "field", suggestions: [], query: "", }; }, apply(tr, value, editorState, newState) { // Handle transactions to update plugin state // e.g., when typing, check for trigger characters const trigger = findAutocompleteTrigger(tr); if (trigger) { return { active: true, stage: "field", suggestions: [], query: trigger.text, }; } // If typing continues and it's not a trigger, update query if (tr.docChanged && value.active && value.stage === "field") { const { from, to } = tr.selection; const textBeforeCursor = newState.doc.textBetween(from - 1, from); if (textBeforeCursor === " ") { // Example: space triggers field search return { ...value, query: "", // Reset query or update based on context }; } // Update query based on actual text changes return { ...value, query: newState.doc.textBetween(trigger.pos, from) // Adjust logic as needed }; } // Handle closing the dropdown (e.g., on Escape key) if (value.active && !trigger) { return { ...value, active: false }; } return value; }, }, props: { handleKeyDown(view: EditorView, event: KeyboardEvent): boolean { const pluginState = autocompletePluginKey.getState(view.state); if (!pluginState || !pluginState.active) return false; if (event.key === "Escape") { view.dispatch(view.state.tr.setMeta(autocompletePluginKey, { active: false })); return true; } // Handle ArrowUp, ArrowDown, Enter, Tab for selection // ... return false; }, decorations(state: EditorState) { // Apply decorations for syntax highlighting or errors // ... return null; }, // ... other plugin properties like filter, appendTransaction, etc. }, }); } ``` -------------------------------- ### Add-ons API Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt The Add-ons API manages DocumentCloud extensions for AI analysis, export, and document processing. ```APIDOC ## Add-ons API ### Description Manages DocumentCloud extensions for AI analysis, export, and document processing. ### Method GET ### Endpoint /api/addons ### Query Parameters - **active** (boolean) - Optional - Filter by active add-ons. - **category** (string) - Optional - Filter by add-on category (e.g., "ai"). ### Response #### Success Response (200) - **data** (array) - A list of available add-ons. ## Get Pinned Add-ons ### Description Retrieves a list of pinned (active) add-ons. ### Method GET ### Endpoint /api/addons/pinned ### Response #### Success Response (200) - **data** (array) - A list of pinned add-ons. ## Get Specific Add-on ### Description Retrieves a specific add-on by its repository. ### Method GET ### Endpoint /api/addons/:owner/:repo ### Parameters #### Path Parameters - **owner** (string) - Required - The owner of the add-on repository. - **repo** (string) - Required - The name of the add-on repository. ### Response #### Success Response (200) - **id** (string) - The unique identifier of the add-on. ## Dispatch Add-on Run ### Description Dispatches an add-on run on selected documents or a search query. ### Method POST ### Endpoint /api/addons/dispatch ### Request Body - **addon** (string) - Required - The ID of the add-on to dispatch. - **parameters** (object) - Optional - Parameters for the add-on run. - **documents** (array of integers) - Optional - A list of document IDs to run the add-on on. - **query** (string) - Optional - A search query to run the add-on on. - **event** (integer) - Optional - Schedule a recurring event (0=disabled, 1=hourly, 2=daily, 3=weekly, 4=upload). ### Request Example ```json { "addon": "addon_id", "parameters": {"language": "en", "model": "gpt-4"}, "documents": [123, 456, 789] } ``` ```json { "addon": "addon_id", "parameters": {}, "query": "project:1234 access:public" } ``` ```json { "addon": "addon_id", "parameters": {}, "event": 2, "query": "user:me" } ``` ### Response #### Success Response (200) - **data** (object) - Information about the dispatched run. ## Get Add-on Run History ### Description Retrieves the history of add-on runs. ### Method GET ### Endpoint /api/addons/history ### Query Parameters - **per_page** (integer) - Optional - Number of results per page. - **dismissed** (boolean) - Optional - Filter by dismissed notifications. ### Response #### Success Response (200) - **data** (array) - A list of add-on run history items. ## Get Scheduled Add-on Events ### Description Retrieves a list of scheduled add-on events. ### Method GET ### Endpoint /api/addons/scheduled ### Response #### Success Response (200) - **data** (array) - A list of scheduled events. ## Update Scheduled Add-on Event ### Description Updates a scheduled add-on event. ### Method PUT ### Endpoint /api/addons/scheduled/:eventId ### Parameters #### Path Parameters - **eventId** (string) - Required - The ID of the event to update. ### Request Body - **addon** (string) - Required - The ID of the add-on. - **parameters** (object) - Optional - Updated parameters for the event. - **event** (integer) - Optional - The updated event schedule (0=disabled, 1=hourly, 2=daily, 3=weekly, 4=upload). ### Response #### Success Response (200) - **data** (object) - Information about the updated event. ## Cancel Add-on Run ### Description Cancels a running add-on. ### Method DELETE ### Endpoint /api/addons/cancel/:runUuid ### Parameters #### Path Parameters - **runUuid** (string) - Required - The UUID of the run to cancel. ## Rate Add-on Run ### Description Rates an add-on run. ### Method POST ### Endpoint /api/addons/rate/:runUuid ### Parameters #### Path Parameters - **runUuid** (string) - Required - The UUID of the run to rate. ### Request Body - **rating** (integer) - Required - The rating (-1=negative, 0=neutral, 1=positive). ## Dismiss Add-on Run Notification ### Description Dismisses a completed run notification. ### Method POST ### Endpoint /api/addons/dismiss/:runUuid ### Parameters #### Path Parameters - **runUuid** (string) - Required - The UUID of the run to dismiss. ## Build and Validate Payload ### Description Builds and validates a payload from form data for an add-on. ### Method POST ### Endpoint /api/addons/payload/build ### Request Body - **addon** (object) - Required - The add-on object. - **formData** (object) - Required - The form data. - **validate** (boolean) - Required - Whether to validate the payload. ### Response #### Success Response (200) - **valid** (boolean) - Indicates if the payload is valid. - **errors** (array) - A list of validation errors, if any. ``` -------------------------------- ### Projects API Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Manage projects, which are collections of documents with collaborative access control. ```APIDOC ## Projects API ### Description The Projects API enables organizing documents into collections with collaborative access control. ### Methods - **List projects with pagination** - **Endpoint**: `/projects` (implied) - **Query Parameters**: - `per_page` (number) - Optional - Number of projects per page. - `cursor` (string) - Optional - Cursor for pagination. - **Response Example**: ```json { "data": [ { "id": "project_id_1", "title": "Investigation 2024", "description": "Documents related to ongoing investigation", "private": true, "pinned": true } ] } ``` - **Get a single project** - **Endpoint**: `/projects/{projectId}` - **Path Parameters**: - `projectId` (string) - Required - The ID of the project. - **Response Example**: ```json { "data": { "id": "project_id_1", "title": "Investigation 2024", "description": "Documents related to ongoing investigation", "private": true, "pinned": true } } ``` - **Get all projects for a user** - **Endpoint**: `/users/{userId}/projects` (implied) - **Path Parameters**: - `userId` (string) - Required - The ID of the user. - **Get pinned projects** - **Endpoint**: `/projects/pinned` (implied) - **Create a new project** - **Endpoint**: `/projects` - **Method**: POST - **Request Body**: - `title` (string) - Required - The title of the project. - `description` (string) - Optional - The description of the project. - `private` (boolean) - Optional - Whether the project is private. - `pinned` (boolean) - Optional - Whether the project is pinned. - **Headers**: - `X-CSRF-Token`: (string) - Required - CSRF token for authentication. - **Response Example**: ```json { "data": { "id": "new_project_id", "title": "Investigation 2024", "description": "Documents related to ongoing investigation", "private": true, "pinned": true } } ``` - **Edit project metadata** - **Endpoint**: `/projects/{projectId}` - **Method**: PUT - **Path Parameters**: - `projectId` (string) - Required - The ID of the project. - **Request Body**: - `title` (string) - Optional - The updated title of the project. - `description` (string) - Optional - The updated description of the project. - **Headers**: - `X-CSRF-Token`: (string) - Required - CSRF token for authentication. - **Pin/unpin a project** - **Endpoint**: `/projects/{projectId}/pin` - **Method**: PUT - **Path Parameters**: - `projectId` (string) - Required - The ID of the project. - **Request Body**: - `pinned` (boolean) - Required - Whether to pin (true) or unpin (false) the project. - **Headers**: - `X-CSRF-Token`: (string) - Required - CSRF token for authentication. - **Add documents to a project** - **Endpoint**: `/projects/{projectId}/documents` - **Method**: POST - **Path Parameters**: - `projectId` (string) - Required - The ID of the project. - **Request Body**: - `docIds` (array of strings) - Required - An array of document IDs to add. - **Headers**: - `X-CSRF-Token`: (string) - Required - CSRF token for authentication. - **Remove documents from a project** - **Endpoint**: `/projects/{projectId}/documents` - **Method**: DELETE - **Path Parameters**: - `projectId` (string) - Required - The ID of the project. - **Request Body**: - `docIds` (array of strings) - Required - An array of document IDs to remove. - **Headers**: - `X-CSRF-Token`: (string) - Required - CSRF token for authentication. - **Delete a project** - **Endpoint**: `/projects/{projectId}` - **Method**: DELETE - **Path Parameters**: - `projectId` (string) - Required - The ID of the project. - **Headers**: - `X-CSRF-Token`: (string) - Required - CSRF token for authentication. - **Note**: Documents are not deleted when a project is deleted. - **Generate project URLs** - **Function**: `canonicalUrl(project)` - Returns the canonical URL for a project. - **Function**: `embedUrl(project, searchParams)` - Returns an embeddable URL for a project with optional search parameters. - **Parameters**: - `project` (object) - Required - The project object. - `searchParams` (URLSearchParams) - Optional - URL search parameters. ``` -------------------------------- ### Update Hosts for Remote Stack Source: https://github.com/muckrock/documentcloud-frontend/blob/main/README.md Modifies the hosts file to point to a custom localhost for developing against the staging API. ```bash echo "127.0.0.1 local.staging.documentcloud.org" | sudo tee -a /etc/hosts ``` -------------------------------- ### Pin/Unpin Project Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Toggles the pinned status of a project. Requires the project ID and a CSRF token. ```typescript // Pin/unpin a project await projects.pinProject(projectId, true, csrf_token); ``` -------------------------------- ### RangeChip Component Source: https://github.com/muckrock/documentcloud-frontend/blob/main/src/lib/components/documents/search/README.md Displays a range query with field name, inclusive/exclusive brackets, and formatted bounds. It is styled distinctly from field-value chips. ```svelte ``` -------------------------------- ### Add Collaborator by Email Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Adds a new collaborator to a project using their email address and specified access level. Handles potential errors during addition. Requires a CSRF token. ```typescript // Add a collaborator by email const { data: newCollab, error } = await collaborators.add( projectId, { email: "colleague@example.com", access: "edit" }, csrf_token ); if (error) { console.error("Failed to add collaborator:", error.message); } ``` -------------------------------- ### Collaborators API Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Manage user access and permissions within projects. ```APIDOC ## Collaborators API ### Description The Collaborators API manages user access and permissions within projects. ### Methods - **List all collaborators on a project** - **Endpoint**: `/projects/{projectId}/collaborators` - **Method**: GET - **Path Parameters**: - `projectId` (string) - Required - The ID of the project. - **Response Example**: ```json [ { "user": { "id": "user_id_1", "name": "Alice" }, "access": "edit" } ] ``` - **Add a collaborator by email** - **Endpoint**: `/projects/{projectId}/collaborators` - **Method**: POST - **Path Parameters**: - `projectId` (string) - Required - The ID of the project. - **Request Body**: - `email` (string) - Required - The email address of the collaborator to add. - `access` (string) - Required - The access level ('view', 'edit', 'admin'). - **Headers**: - `X-CSRF-Token`: (string) - Required - CSRF token for authentication. - **Response Example**: ```json { "data": { "user": { "id": "new_user_id", "name": "Bob" }, "access": "edit" }, "error": null } ``` - **Update collaborator permissions** - **Endpoint**: `/projects/{projectId}/collaborators/{userId}` - **Method**: PUT - **Path Parameters**: - `projectId` (string) - Required - The ID of the project. - `userId` (string) - Required - The ID of the user whose permissions are being updated. - **Request Body**: - `access` (string) - Required - The new access level ('view', 'edit', 'admin'). - **Headers**: - `X-CSRF-Token`: (string) - Required - CSRF token for authentication. - **Remove a collaborator** - **Endpoint**: `/projects/{projectId}/collaborators/{userId}` - **Method**: DELETE - **Path Parameters**: - `projectId` (string) - Required - The ID of the project. - `userId` (string) - Required - The ID of the user to remove. - **Headers**: - `X-CSRF-Token`: (string) - Required - CSRF token for authentication. ``` -------------------------------- ### SearchEditor Component Structure Source: https://github.com/muckrock/documentcloud-frontend/blob/main/src/lib/components/documents/search/README.md The root Svelte component for the search UI. It manages the editor's state and exposes methods for programmatic control. Only structural changes emit 'change' events. ```svelte console.log("Query changed:", e.detail)} /> ``` -------------------------------- ### Delete Project Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Deletes a project. Note that this action does not delete the documents within the project. Requires the project ID and a CSRF token. ```typescript // Delete a project (documents are not deleted) await projects.destroy(projectId, csrf_token); ``` -------------------------------- ### Search and Retrieve Documents Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Use the search method to find documents based on a query and options like highlighting and pagination. Retrieve a single document by its ID. ```typescript import * as documents from "$lib/api/documents"; // Search documents with query and options const { data, error } = await documents.search("government records", { hl: true, // highlight matches per_page: 25, cursor: "", version: "2.0" }); if (data) { console.log(`Found ${data.count} documents`); data.results.forEach(doc => { console.log(`${doc.title} - ${doc.status}`); }); } // Get a single document by ID const { data: doc } = await documents.get(12345); console.log(doc.title, doc.page_count, doc.access); ``` -------------------------------- ### Create/Destroy Mail Key Source: https://context7.com/muckrock/documentcloud-frontend/llms.txt Manages a mail key used for email uploads. Includes functions to create and destroy the key, both requiring a CSRF token. ```typescript // Create/destroy mail key for email uploads const mailkey = await accounts.createMailkey(csrf_token); await accounts.destroyMailkey(csrf_token); ```