diff options
author | bobzel <zzzman@gmail.com> | 2025-03-06 16:17:47 -0500 |
---|---|---|
committer | bobzel <zzzman@gmail.com> | 2025-03-06 16:17:47 -0500 |
commit | 5ad858090f3006631062877d90120e3cc505fada (patch) | |
tree | 9f87a8e1e7098a1025f6f4aac332dbc854db5be3 /src | |
parent | 9c2a7c14fd9d0e44609aab30c6323583162009db (diff) | |
parent | adaa107aac8558fa6f46e6ba1263c650c212d506 (diff) |
Merge branch 'master' into aarav_edit
Diffstat (limited to 'src')
173 files changed, 5927 insertions, 5315 deletions
diff --git a/src/ClientUtils.ts b/src/ClientUtils.ts index 8c9dd0a32..e1f490c1a 100644 --- a/src/ClientUtils.ts +++ b/src/ClientUtils.ts @@ -1,4 +1,4 @@ -import * as Color from 'color'; +import Color from 'color'; import * as React from 'react'; import { ColorResult } from 'react-color'; import * as rp from 'request-promise'; @@ -599,7 +599,7 @@ export function StopEvent(e: React.PointerEvent | React.MouseEvent | React.Keybo export function setupMoveUpEvents( target: object, - e: React.PointerEvent, + e: React.PointerEvent | PointerEvent, moveEvent: (e: PointerEvent, down: number[], delta: number[]) => boolean, upEvent: (e: PointerEvent, movement: number[], isClick: boolean) => void, clickEvent: (e: PointerEvent, doubleTap?: boolean) => unknown, diff --git a/src/client/Network.ts b/src/client/Network.ts index 3b0406141..a2ecf1bea 100644 --- a/src/client/Network.ts +++ b/src/client/Network.ts @@ -1,5 +1,4 @@ import formidable from 'formidable'; -import * as requestPromise from 'request-promise'; import { ClientUtils } from '../ClientUtils'; import { Utils } from '../Utils'; import { Upload } from '../server/SharedMediaTypes'; @@ -16,13 +15,17 @@ export namespace Networking { } export function PostToServer(relativeRoute: string, body?: unknown) { - const options = { - uri: ClientUtils.prepend(relativeRoute), + return fetch(ClientUtils.prepend(relativeRoute), { method: 'POST', - body, - json: true, - }; - return requestPromise.post(options); + headers: { + 'Content-Type': 'application/json', + }, + body: body ? JSON.stringify(body) : undefined, + }).then(async response => { + if (response.ok) return response.json() as object; + + return await response.text().then(text => ({ error: '' + response.status + ':' + response.statusText + '-' + text })); + }); } /** diff --git a/src/client/apis/GoogleAuthenticationManager.tsx b/src/client/apis/GoogleAuthenticationManager.tsx index 5269f763b..94ce42d8d 100644 --- a/src/client/apis/GoogleAuthenticationManager.tsx +++ b/src/client/apis/GoogleAuthenticationManager.tsx @@ -11,7 +11,8 @@ const AuthenticationUrl = 'https://accounts.google.com/o/oauth2/v2/auth'; const prompt = 'Paste authorization code here...'; @observer -export class GoogleAuthenticationManager extends React.Component<{}> { +export class GoogleAuthenticationManager extends React.Component<object> { + // eslint-disable-next-line no-use-before-define public static Instance: GoogleAuthenticationManager; private authenticationLink: Opt<string> = undefined; @observable private openState = false; @@ -19,7 +20,7 @@ export class GoogleAuthenticationManager extends React.Component<{}> { @observable private showPasteTargetState = false; @observable private success: Opt<boolean> = undefined; @observable private displayLauncher = true; - @observable private credentials: any; + @observable private credentials: { user_info: { name: string; picture: string }; access_token: string } | undefined = undefined; private disposer: Opt<IReactionDisposer>; private set isOpen(value: boolean) { @@ -35,25 +36,25 @@ export class GoogleAuthenticationManager extends React.Component<{}> { } public fetchOrGenerateAccessToken = async (displayIfFound = false) => { - let response: any = await Networking.FetchFromServer('/readGoogleAccessToken'); + const response = await Networking.FetchFromServer('/readGoogleAccessToken'); // if this is an authentication url, activate the UI to register the new access token if (new RegExp(AuthenticationUrl).test(response)) { this.isOpen = true; this.authenticationLink = response; - return new Promise<string>(async resolve => { + return new Promise<string>(resolve => { this.disposer?.(); this.disposer = reaction( () => this.authenticationCode, async authenticationCode => { if (authenticationCode && /\d{1}\/[\w-]{55}/.test(authenticationCode)) { this.disposer?.(); - const response = await Networking.PostToServer('/writeGoogleAccessToken', { authenticationCode }); + const response2 = await Networking.PostToServer('/writeGoogleAccessToken', { authenticationCode }); runInAction(() => { this.success = true; - this.credentials = response; + this.credentials = response2 as { user_info: { name: string; picture: string }; access_token: string }; }); this.resetState(); - resolve(response.access_token); + resolve((response2 as { access_token: string }).access_token); } } ); @@ -61,16 +62,16 @@ export class GoogleAuthenticationManager extends React.Component<{}> { } // otherwise, we already have a valid, stored access token and user info - response = JSON.parse(response); + const response2 = JSON.parse(response) as { user_info: { name: string; picture: string }; access_token: string }; if (displayIfFound) { runInAction(() => { this.success = true; - this.credentials = response; + this.credentials = response2; }); this.resetState(-1, -1); this.isOpen = true; } - return response.access_token; + return (response2 as { access_token: string }).access_token; }; resetState = action((visibleForMS: number = 3000, fadesOutInMS: number = 500) => { @@ -106,7 +107,7 @@ export class GoogleAuthenticationManager extends React.Component<{}> { } }); - constructor(props: {}) { + constructor(props: object) { super(props); GoogleAuthenticationManager.Instance = this; } @@ -128,8 +129,8 @@ export class GoogleAuthenticationManager extends React.Component<{}> { {this.showPasteTargetState ? <input className={'paste-target'} onChange={action(e => (this.authenticationCode = e.currentTarget.value))} placeholder={prompt} /> : null} {this.credentials ? ( <> - <img className={'avatar'} src={this.credentials.userInfo.picture} /> - <span className={'welcome'}>Welcome to Dash, {this.credentials.userInfo.name}</span> + <img className={'avatar'} src={this.credentials.user_info.picture} /> + <span className={'welcome'}>Welcome to Dash, {this.credentials.user_info.name}</span> <div className={'disconnect'} onClick={async () => { diff --git a/src/client/apis/google_docs/GoogleApiClientUtils.ts b/src/client/apis/google_docs/GoogleApiClientUtils.ts index 0b303eacf..c1ac352b1 100644 --- a/src/client/apis/google_docs/GoogleApiClientUtils.ts +++ b/src/client/apis/google_docs/GoogleApiClientUtils.ts @@ -1,7 +1,5 @@ -/* eslint-disable no-restricted-syntax */ /* eslint-disable no-use-before-define */ import { docs_v1 as docsV1 } from 'googleapis'; -// eslint-disable-next-line node/no-deprecated-api import { isArray } from 'util'; import { EditorState } from 'prosemirror-state'; import { Opt } from '../../../fields/Doc'; @@ -37,7 +35,7 @@ export namespace GoogleApiClientUtils { text: string | string[]; requests: docsV1.Schema$Request[]; } - export type IdHandler = (id: DocumentId) => any; + export type IdHandler = (id: DocumentId) => unknown; export type CreationResult = Opt<DocumentId>; export type ReadLinesResult = Opt<{ title?: string; bodyLines?: string[] }>; export type ReadResult = { title: string; body: string }; @@ -145,7 +143,7 @@ export namespace GoogleApiClientUtils { if (paragraphs.length) { const target = paragraphs[paragraphs.length - 1]; if (target.paragraph && target.paragraph.elements) { - length = target.paragraph.elements.length; + const length = target.paragraph.elements.length; if (length) { const final = target.paragraph.elements[length - 1]; return final.endIndex ? final.endIndex - 1 : undefined; @@ -208,13 +206,13 @@ export namespace GoogleApiClientUtils { }); export const setStyle = async (options: UpdateOptions) => { - const replies: any = await update({ + const replies = await update({ documentId: options.documentId, requests: options.requests, }); - if ('errors' in replies) { + if (replies && 'errors' in replies) { console.log('Write operation failed:'); - console.log(replies.errors.map((error: any) => error.message)); + console.log(replies); //.errors.map((error: any) => error.message)); } return replies; }; @@ -229,7 +227,6 @@ export namespace GoogleApiClientUtils { const { mode } = options; if (!(index && mode === WriteMode.Insert)) { const schema = await retrieve({ documentId }); - // eslint-disable-next-line no-cond-assign if (!schema || !(index = Utils.endOf(schema))) { return undefined; } @@ -258,10 +255,10 @@ export namespace GoogleApiClientUtils { return undefined; } requests.push(...options.content.requests); - const replies: any = await update({ documentId, requests }); - if ('errors' in replies) { + const replies = await update({ documentId, requests }); + if (replies && 'errors' in replies) { console.log('Write operation failed:'); - console.log(replies.errors.map((error: any) => error.message)); + console.log(replies); // .errors.map((error: any) => error.message)); } return replies; }; diff --git a/src/client/apis/google_docs/GooglePhotosClientUtils.ts b/src/client/apis/google_docs/GooglePhotosClientUtils.ts index b238f07e9..4b86a8341 100644 --- a/src/client/apis/google_docs/GooglePhotosClientUtils.ts +++ b/src/client/apis/google_docs/GooglePhotosClientUtils.ts @@ -1,5 +1,5 @@ /* eslint-disable no-use-before-define */ -import Photos = require('googlephotos'); +import Photos from 'googlephotos'; import { AssertionError } from 'assert'; import { EditorState } from 'prosemirror-state'; import { ClientUtils } from '../../../ClientUtils'; @@ -118,7 +118,7 @@ export namespace GooglePhotos { } export namespace Import { - export type CollectionConstructor = (data: Array<Doc>, options: DocumentOptions, ...args: any) => Doc; + export type CollectionConstructor = (data: Array<Doc>, options: DocumentOptions, ...args: unknown[]) => Doc; export const CollectionFromSearch = async (constructor: CollectionConstructor, requested: Opt<Partial<Query.SearchOptions>>): Promise<Doc> => { await GoogleAuthenticationManager.Instance.fetchOrGenerateAccessToken(); @@ -147,7 +147,7 @@ export namespace GooglePhotos { values.forEach(async value => { const searched = (await ContentSearch({ included: [value] }))?.mediaItems?.map(({ id }) => id); searched?.forEach(async id => { - const image = await Cast(idMapping[id], Doc); + const image = await Cast(idMapping[id as string], Doc); if (image) { const key = image[Id]; const tags = tagMapping.get(key); @@ -193,7 +193,7 @@ export namespace GooglePhotos { } export interface SearchResponse { - mediaItems: any[]; + mediaItems: MediaItem[]; nextPageToken: string; } @@ -204,7 +204,7 @@ export namespace GooglePhotos { const found = 0; do { // eslint-disable-next-line no-await-in-loop - const response: any = await photos.mediaItems.search(albumId, pageSize, nextPageTokenStored); + const response = await photos.mediaItems.search(albumId, pageSize, nextPageTokenStored); mediaItems.push(...response.mediaItems); nextPageTokenStored = response.nextPageToken; } while (found); @@ -278,9 +278,9 @@ export namespace GooglePhotos { return undefined; }; - export const WriteMediaItemsToServer = async (body: { mediaItems: any[] }): Promise<UploadInformation[]> => { + export const WriteMediaItemsToServer = async (body: { mediaItems: MediaItem[] }): Promise<UploadInformation[]> => { const uploads = await Networking.PostToServer('/googlePhotosMediaGet', body); - return uploads; + return uploads as UploadInformation[]; }; export const UploadThenFetch = async (sources: Doc[], album?: AlbumReference, descriptionKey = 'caption') => { @@ -320,7 +320,7 @@ export namespace GooglePhotos { }); if (media.length) { const results = await Networking.PostToServer('/googlePhotosMediaPost', { media, album }); - return results; + return results as Opt<ImageUploadResults>; } return undefined; }; @@ -331,7 +331,7 @@ export namespace GooglePhotos { if (typeof target === 'string') { description = target; } else if (target instanceof RichTextField) { - description = RichTextUtils.ToPlainText(EditorState.fromJSON(new FormattedTextBox({} as any).config, JSON.parse(target.Data))); + description = RichTextUtils.ToPlainText(EditorState.fromJSON(FormattedTextBox.MakeConfig(undefined, undefined), JSON.parse(target.Data))); } return description; }; diff --git a/src/client/apis/gpt/GPT.ts b/src/client/apis/gpt/GPT.ts index dc4607b94..29b6ab989 100644 --- a/src/client/apis/gpt/GPT.ts +++ b/src/client/apis/gpt/GPT.ts @@ -1,14 +1,22 @@ import { ChatCompletionMessageParam, Image } from 'openai/resources'; import { openai } from './setup'; +export enum GPTDocCommand { + AssignTags = 1, + Filter = 2, + GetInfo = 3, + Sort = 4, +} + +export const DescriptionSeperator = '======'; +export const DocSeperator = '------'; + enum GPTCallType { SUMMARY = 'summary', COMPLETION = 'completion', EDIT = 'edit', CHATCARD = 'chatcard', // a single flashcard style response to a question FLASHCARD = 'flashcard', // a set of flashcard qustion/answer responses to a topic - QUIZ = 'quiz', - SORT = 'sort', DESCRIBE = 'describe', MERMAID = 'mermaid', DATA = 'data', @@ -16,15 +24,17 @@ enum GPTCallType { PRONUNCIATION = 'pronunciation', DRAW = 'draw', COLOR = 'color', - RUBRIC = 'rubric', // needs to be filled in below - TYPE = 'type', // needs to be filled in below - SUBSET = 'subset', // needs to be filled in below - INFO = 'info', // needs to be filled in below TEMPLATE = 'template', VIZSUM = 'vizsum', VIZSUM2 = 'vizsum2', FILL = 'fill', COMPLETEPROMPT = 'completeprompt', + QUIZDOC = 'quiz_doc', + MAKERUBRIC = 'make_rubric', // create a definition rubric for a document to be used when quizzing the user + COMMANDTYPE = 'command_type', // Determine the type of command being made (GPTQueryType - eg., AssignTags, Sort, Filter, DocInfo, GenInfo) and possibly some parameters (eg, Tag type for Tags) + SUBSETDOCS = 'subset_docs', // select a subset of documents based on their descriptions + DOCINFO = 'doc_info', // provide information about a document + SORTDOCS = 'sort_docs', } type GPTCallOpts = { @@ -34,7 +44,7 @@ type GPTCallOpts = { prompt: string; }; -const callTypeMap: { [type: string]: GPTCallOpts } = { +const callTypeMap: { [type in GPTCallType]: GPTCallOpts } = { // newest model: gpt-4 summary: { model: 'gpt-4-turbo', maxTokens: 256, temp: 0.5, prompt: 'Summarize the text given in simpler terms.' }, edit: { model: 'gpt-4-turbo', maxTokens: 256, temp: 0.5, prompt: 'Reword the text.' }, @@ -58,11 +68,17 @@ const callTypeMap: { [type: string]: GPTCallOpts } = { temp: 0.5, prompt: "You are a helpful resarch assistant. Analyze the user's data to find meaningful patterns and/or correlation. Please only return a JSON with a correlation column 1 propert, a correlation column 2 property, and an analysis property. ", }, - sort: { + sort_docs: { model: 'gpt-4o', maxTokens: 2048, temp: 0.25, - prompt: "The user is going to give you a list of descriptions. Each one is separated by `======` on either side. Descriptions will vary in length, so make sure to only separate when you see `======`. Sort them by the user's specifications. Make sure each description is only in the list once. Each item should be separated by `======`. Immediately afterward, surrounded by `------` on BOTH SIDES, provide some insight into your reasoning for the way you sorted (and mention nothing about the formatting details given in this description). It is VERY important that you format it exactly as described, ensuring the proper number of `=` and `-` (6 of each) and NO commas", + prompt: `The user is going to give you a list of descriptions. + Each one is separated by '${DescriptionSeperator}' on either side. + Descriptions will vary in length, so make sure to only separate when you see '${DescriptionSeperator}'. + Sort them by the user's specifications. + Make sure each description is only in the list once. Each item should be separated by '${DescriptionSeperator}'. + Immediately afterward, surrounded by '${DocSeperator}' on BOTH SIDES, provide some insight into your reasoning for the way you sorted (and mention nothing about the formatting details given in this description). + It is VERY important that you format it exactly as described, ensuring the proper number of '${DescriptionSeperator[0]}' and '${DocSeperator[0]}' (${DescriptionSeperator.length} of each) and NO commas`, }, describe: { model: 'gpt-4-vision-preview', maxTokens: 2048, temp: 0, prompt: 'Describe these images in 3-5 words' }, flashcard: { @@ -72,7 +88,7 @@ const callTypeMap: { [type: string]: GPTCallOpts } = { prompt: 'Make flashcards out of this text with each question and answer labeled as question and answer. Create a title for each question and asnwer that is labeled as "title". Do not label each flashcard and do not include asterisks: ', }, chatcard: { model: 'gpt-4-turbo', maxTokens: 512, temp: 0.5, prompt: 'Answer the following question as a short flashcard response. Do not include a label.' }, - quiz: { + quiz_doc: { model: 'gpt-4-turbo', maxTokens: 1024, temp: 0, @@ -88,7 +104,7 @@ const callTypeMap: { [type: string]: GPTCallOpts } = { model: 'gpt-4-turbo', maxTokens: 512, temp: 0.5, - prompt: 'You will be given a list of field descriptions for multiple templates in the format {field #0: “description”}{field #1: “description”}{...}, and a list of column descriptions in the format {“title”: “description”}{...}. Your job is to match columns with fields based on their descriptions. Your output should be in the following JSON format: {“Template title”:{“#”: “title”, “#”: “title”, “#”: “title” …}, “Template title”:{“#”: “title”, “#”: “title”, “#”: “title” …}} where “Template title” represents the template, # represents the field # and “title” the title of the column assigned to it. A filled out example might look like {“fivefield2”:{“0”:”Name”, “1”:”Image”, “2”:”Caption”, “3”:”Position”, “4”:”Stats”}, “fivefield3”:{0:”Image”, 1:”Name”, 2:”Caption”, 3:”Stats”, 4:”Position”}. Include one object for each template. IT IS VERY IMPORTANT THAT YOU ONLY INCLUDE TEXT IN THE FORMAT ABOVE, WITH NO ADDITIONS WHATSOEVER. Do not include extraneous ‘#’ characters, ‘column’ for columns, or ‘template’ for templates: ONLY THE TITLES AND NUMBERS. There should never be one column assigned to more than one field (ie. if the “name” column is assigned to field 1, it can’t be assigned to any other fields) . Do this for each template whose fields are described. The descriptions are as follows:', + prompt: 'You will be given a list of field descriptions for one or more templates in the format {field #0: “description”}{field #1: “description”}{...}, and a list of column descriptions in the format {“title”: “description”}{...}. Your job is to match columns with fields based on their descriptions. Your output should be in the following JSON format: {“template_title”:{“#”: “title”, “#”: “title”, “#”: “title” …}, “template_title”:{“#”: “title”, “#”: “title”, “#”: “title” …}} where “template_title” is the templates title as specified in the description provided, # represents the field # and “title” the title of the column assigned to it. A filled out example might look like {“fivefield2”:{“0”:”Name”, “1”:”Image”, “2”:”Caption”, “3”:”Position”, “4”:”Stats”}, “fivefield3”:{0:”Image”, 1:”Name”, 2:”Caption”, 3:”Stats”, 4:”Position”}. Include one object for each template. IT IS VERY IMPORTANT THAT YOU ONLY INCLUDE TEXT IN THE FORMAT ABOVE, WITH NO ADDITIONS WHATSOEVER. Do not include extraneous ‘#’ characters, ‘column’ for columns, or ‘template’ for templates: ONLY THE TITLES AND NUMBERS. There should never be one column assigned to more than one field (ie. if the “name” column is assigned to field 1, it can’t be assigned to any other fields) . Do this for each template whose fields are described. The descriptions are as follows:', }, vizsum: { model: 'gpt-4-turbo', @@ -103,12 +119,12 @@ const callTypeMap: { [type: string]: GPTCallOpts } = { prompt: 'Your job is to provide structured information on columns in a dataset based on example rows. You will categorize each column in two ways: by type and size. The size categories are as follows: tiny (one or two words), small (a sentence/multiple words), medium (a few sentences), large (a longer paragraph), and huge (a very long or multiple paragraphs). The type categories are as follows: visual (links/file paths to images, pdfs, maps, or any other visual media type), and text (plain text that isn’t a link/file path). Visual media should be assumed to have size “medium” “large” or “huge”. You will give your responses in JSON format, like so: {“title (of column)”:{“type”:”text”, “size”:”small”}, “title (of column)”:{“type”:”visual”, “size”:”medium”}, …}. DO NOT INCLUDE ANY OTHER TEXT, ONLY THE JSON.', }, fill: { - model: 'gpt-4-turbo', + model: 'gpt-4o', maxTokens: 512, temp: 0.5, prompt: 'Your job is to generate content for fields based on a user prompt and background context given to you. You will be given the content of the other fields present in the format: ---- Field # (field title): content ---- Field # (field title): content ----- (etc.) You will be given info on the columns to generate for in the format ---- title: , prompt: , word limit: , assigned field: ----. For each column, based on the prompt, word limit, and the context of existing fields, you should generate a short response in the following JSON format: {“___”(where ___ is the title from the column description with no additions): {“number”:”#” (where # is the assigned field of the column), “content”:”response” (where response is your response to the prompt in the column info)}}. Here’s another example of the format with only one column: {“position”: {“number”:”2”, “content”:”*your response goes here*”}}. ONLY INCLUDE THE JSON TEXT WITH NO OTHER ADDED TEXT. YOUR RESPONSE MUST BE VALID JSON. The word limit for each column applies only to that column’s response. Do not include speculation or information that you can’t glean from your factual knowledge or the content of the other fields (no description of images you can’t see, for example). You should include one object per column you are provided info on.', }, - completeprompt: { model: 'gpt-4-turbo', maxTokens: 512, temp: 0.5, prompt: 'Your prompt is as follows:' }, + completeprompt: { model: 'gpt-4o', maxTokens: 512, temp: 0.5, prompt: 'Your prompt is as follows:' }, draw: { model: 'gpt-4o', maxTokens: 1024, @@ -121,38 +137,45 @@ const callTypeMap: { [type: string]: GPTCallOpts } = { temp: 0.5, prompt: 'You will be coloring drawings. You will be given what the drawing is, then a list of descriptions for parts of the drawing. Based on each description, respond with the stroke and fill color that it should be. Follow the rules: 1. Avoid using black for stroke color 2. Make the stroke color 1-3 shades darker than the fill color 3. Use the same colors when possible. Format as {#abcdef #abcdef}, making sure theres a color for each description, and do not include any additional text.', }, - type: { + command_type: { model: 'gpt-4-turbo', maxTokens: 1024, temp: 0, prompt: `I'm going to provide you with a question. Based on the question, is the user asking you to - 1. Assigns docs with tags(like star / heart etc)/labels, - 2. Filter docs, - 3. Provide information about a specific doc - 4. Provide a specific doc based on a question/information - 5. Provide general information - 6. Put cards in a specific order. - Answer with only the number for 2-6. For number one, provide the number (1) and the appropriate tag`, + ${GPTDocCommand.AssignTags}. Assigns docs with tags(like star / heart etc)/labels. + ${GPTDocCommand.GetInfo}. Provide information about a specific doc. + ${GPTDocCommand.Filter}. Filter docs based on a question/information. + ${GPTDocCommand.Sort}. Put docs in a specific order. + Answer with only the number for ${GPTDocCommand.GetInfo}-${GPTDocCommand.Sort}. + For number one, provide the number (${GPTDocCommand.AssignTags}) and the appropriate tag`, }, - subset: { + subset_docs: { model: 'gpt-4-turbo', maxTokens: 1024, temp: 0, - prompt: "I'm going to give you a list of descriptions. Each one is separated by `======` on either side. Descriptions will vary in length, so make sure to only separate when you see `======`. Based on the question the user asks, provide a subset of the given descriptions that best matches the user's specifications. Make sure each description is only in the list once. Each item should be separated by `======`. Immediately afterward, surrounded by `------` on BOTH SIDES, provide some insight into your reasoning in the 2nd person (and mention nothing about the formatting details given in this description). It is VERY important that you format it exactly as described, ensuring the proper number of `=` and `-` (6 of each) and no commas", + prompt: `I'm going to give you a list of descriptions. + Each one is separated by '${DescriptionSeperator}' on either side. + Descriptions will vary in length, so make sure to only separate when you see '${DescriptionSeperator}'. + Based on the question the user asks, provide a subset of the given descriptions that best matches the user's specifications. + Make sure each description is only in the list once. Each item should be separated by '${DescriptionSeperator}'. + Immediately afterward, surrounded by '${DocSeperator}' on BOTH SIDES, provide some insight into your reasoning in the 2nd person (and mention nothing about the formatting details given in this description). + It is VERY important that you format it exactly as described, ensuring the proper number of '${DescriptionSeperator[0]}' and '${DocSeperator[0]}' (${DescriptionSeperator.length} of each) and NO commas`, }, - info: { + doc_info: { model: 'gpt-4-turbo', maxTokens: 1024, temp: 0, - prompt: "Answer the user's question with a short (<100 word) response. If a particular document is selected I will provide that information (which may help with your response)", + prompt: `Answer the user's question with a short (<100 word) response. + If a particular document is selected I will provide that information (which may help with your response)`, }, - rubric: { + make_rubric: { model: 'gpt-4-turbo', maxTokens: 1024, temp: 0, - prompt: "BRIEFLY (<25 words) provide a definition for the following term. It will be used as a rubric to evaluate the user's understanding of the topic", + prompt: `BRIEFLY (<25 words) provide a definition for the following term. + It will be used as a rubric to evaluate the user's understanding of the topic`, }, }; let lastCall = ''; @@ -164,17 +187,15 @@ let lastResp = ''; * @returns AI Output */ const gptAPICall = async (inputTextIn: string, callType: GPTCallType, prompt?: string, dontCache?: boolean) => { - const inputText = inputTextIn + ([GPTCallType.SUMMARY, GPTCallType.FLASHCARD, GPTCallType.QUIZ, GPTCallType.STACK].includes(callType) ? '.' : ''); + const inputText = inputTextIn + ([GPTCallType.SUMMARY, GPTCallType.FLASHCARD, GPTCallType.QUIZDOC, GPTCallType.STACK].includes(callType) ? '.' : ''); const opts = callTypeMap[callType]; if (!opts) { console.log('The query type:' + callType + ' requires a configuration.'); return 'Error connecting with API.'; } - if (lastCall === inputText && dontCache !== true) return lastResp; + if (lastCall === inputText && dontCache !== true && lastResp) return lastResp; try { - lastCall = inputText; - - const usePrompt = prompt ? prompt + opts.prompt : opts.prompt; + const usePrompt = prompt ? prompt + '.' + opts.prompt : opts.prompt; const messages: ChatCompletionMessageParam[] = [ { role: 'system', content: usePrompt }, { role: 'user', content: inputText }, @@ -186,8 +207,12 @@ const gptAPICall = async (inputTextIn: string, callType: GPTCallType, prompt?: s temperature: opts.temp, max_tokens: opts.maxTokens, }); - lastResp = response.choices[0].message.content ?? ''; - return lastResp; + const result = response.choices[0].message.content ?? ''; + if (!dontCache) { + lastResp = result; + lastCall = inputText; + } + return result; } catch (err) { console.log(err); return 'Error connecting with API.'; diff --git a/src/client/documents/DocUtils.ts b/src/client/documents/DocUtils.ts index 5a39a9720..7e0416447 100644 --- a/src/client/documents/DocUtils.ts +++ b/src/client/documents/DocUtils.ts @@ -10,7 +10,7 @@ import { DateField } from '../../fields/DateField'; import { Doc, DocListCast, Field, FieldResult, FieldType, LinkedTo, Opt, StrListCast } from '../../fields/Doc'; import { DocData } from '../../fields/DocSymbols'; import { Id } from '../../fields/FieldSymbols'; -import { InkDataFieldName, InkField } from '../../fields/InkField'; +import { InkData, InkDataFieldName, InkField } from '../../fields/InkField'; import { List, ListFieldName } from '../../fields/List'; import { ProxyField } from '../../fields/Proxy'; import { RichTextField } from '../../fields/RichTextField'; @@ -33,7 +33,10 @@ import { TaskCompletionBox } from '../views/nodes/TaskCompletedBox'; import { DocumentType } from './DocumentTypes'; import { Docs, DocumentOptions } from './Documents'; import { DocumentView } from '../views/nodes/DocumentView'; -import { CollectionFreeFormView } from '../views/collections/collectionFreeForm'; +import { INode, parse } from 'svgson'; +import { SVGToBezier, SVGType } from '../util/bezierFit'; +import { SmartDrawHandler } from '../views/smartdraw/SmartDrawHandler'; +import { PointData } from '../../pen-gestures/GestureTypes'; export namespace DocUtils { function HasFunctionFilter(val: string) { @@ -393,7 +396,10 @@ export namespace DocUtils { })) as ContextMenuProps[]; documentList.push({ description: ':Smart Drawing', - event: e => (DocumentView.Selected().lastElement().ComponentView as CollectionFreeFormView)?.showSmartDraw(e?.x || 0, e?.y || 0), + event: e => + DocumentView.Selected() + .lastElement() + .ComponentView?.showSmartDraw?.(e?.x || 0, e?.y || 0), icon: 'file', }); @@ -705,6 +711,8 @@ export namespace DocUtils { // annotationOn, backgroundColor: backgroundColor ?? StrCast(Doc.UserDoc().textBackgroundColor), + borderColor: Doc.UserDoc().borderColor as string, + borderWidth: Doc.UserDoc().borderWidth as number, x, y, title, @@ -731,6 +739,8 @@ export namespace DocUtils { _layout_fitWidth: true, _layout_autoHeight: true, backgroundColor: StrCast(Doc.UserDoc().textBackgroundColor), + borderColor: Doc.UserDoc().borderColor as string, + borderWidth: Doc.UserDoc().borderWidth as number, text_fitBox: BoolCast(Doc.UserDoc().fitBox), text_align: StrCast(Doc.UserDoc().textAlign), text_fontColor: StrCast(Doc.UserDoc().fontColor), @@ -787,6 +797,57 @@ export namespace DocUtils { return generatedDocuments; } + export async function openSVGfile(file: File, options: DocumentOptions) { + const reader = new FileReader(); + const scale = 1; + const startPoint = { X: (options.x as number) ?? 0, Y: (options.y as number) ?? 0 }; + const buffer = await new Promise<string>((res, rej) => { + reader.onload = event => { + const fileContent = event.target?.result; + // Process the file content here + console.log(fileContent); + typeof fileContent === 'string' ? res(fileContent) : rej(); + }; + + reader.readAsText(file); + }); + const svg = buffer.match(/<svg[^>]*>([\s\S]*?)<\/svg>/g); + if (svg) { + const svgObject = await parse(svg[0]); + const strokeData: [InkData, string, string][] = []; + const tl = { X: Number.MAX_SAFE_INTEGER, Y: Number.MAX_SAFE_INTEGER }; + let last: PointData = { X: 0, Y: 0 }; + const processStroke = (child: INode) => { + child.attributes.d + .split(/[\n]?M/) + .slice(1) + .map((d, ind) => { + const convertedBezier: InkData = SVGToBezier(child.name as SVGType, { ...child, d: '\nM' + d } as unknown as Record<string, string>, last); + last = convertedBezier.lastElement(); + convertedBezier.forEach(point => { + if (point.X < tl.X) tl.X = point.X; + if (point.Y < tl.Y) tl.Y = point.Y; + }); + strokeData.push([convertedBezier, child.attributes.stroke || 'black', ind === 0 ? child.attributes.fill : child.attributes.fill === 'none' ? child.attributes.fill : DashColor(child.attributes.fill).negate().toString()]); + }); + }; + const processNode = (parent: INode) => { + if (parent.children.length) parent.children.forEach(processNode); + else if (parent.type !== 'text') processStroke(parent); + }; + processNode(svgObject); + + const mapStroke = (pd: PointData): PointData => ({ X: startPoint.X + (pd.X - tl.X) * scale, Y: startPoint.Y + (pd.Y - tl.Y) * scale }); + + return SmartDrawHandler.CreateDrawingDoc( + strokeData.map(sdata => [sdata[0].map(mapStroke), sdata[1], sdata[2]] as [PointData[], string, string]), + { autoColor: true }, + '', + undefined + ); + } + } + export function uploadFileToDoc(file: File, options: DocumentOptions, overwriteDoc: Doc) { const generatedDocuments: Doc[] = []; // Since this file has an overwriteDoc, we can set the client tracking guid to the overwriteDoc's guid. diff --git a/src/client/documents/DocumentTypes.ts b/src/client/documents/DocumentTypes.ts index 65cd499c9..00f5dedd6 100644 --- a/src/client/documents/DocumentTypes.ts +++ b/src/client/documents/DocumentTypes.ts @@ -63,6 +63,7 @@ export enum CollectionViewType { Multirow = 'multirow', NoteTaking = 'notetaking', Pile = 'pileup', + Pivot = 'pivot', Schema = 'schema', Stacking = 'stacking', StackedTimeline = 'stacked timeline', diff --git a/src/client/documents/Documents.ts b/src/client/documents/Documents.ts index 873eb3f20..fe6e6b22d 100644 --- a/src/client/documents/Documents.ts +++ b/src/client/documents/Documents.ts @@ -240,8 +240,8 @@ export class DocumentOptions { dataViz?: string; dataViz_savedTemplates?: LISTt; - borderWidth?: STRt = new StrInfo('Width of user-added border', false); - borderColor?: STRt = new StrInfo('Color of user-added border', false); + borderWidth?: NUMt = new NumInfo('Width of docuent border', false); + borderColor?: STRt = new StrInfo('Color of document border', false); text_fontColor?: STRt = new StrInfo('Color of text', false); hCentering?: 'h-left' | 'h-center' | 'h-right'; isDefaultTemplateDoc?: BOOLt = new BoolInfo(''); @@ -384,6 +384,9 @@ export class DocumentOptions { presentation_duration?: NUMt = new NumInfo('the duration of the slide in presentation view', false); presentation_zoomText?: BOOLt = new BoolInfo('whether text anchors should shown in a larger box when following links to make them stand out', false); + data_annotations?: List<Doc>; + _data_usePath?: STRt = new StrInfo("description of field key to display in image box ('alternate','alternate:hover', 'data:hover'). defaults to primary", false); + data_alternates?: List<Doc>; data?: FieldType; data_useCors?: BOOLt = new BoolInfo('whether CORS protocol should be used for web page'); _face_showImages?: BOOLt = new BoolInfo('whether to show images in uniqe face Doc'); diff --git a/src/client/util/CaptureManager.scss b/src/client/util/CaptureManager.scss index 8679a0101..e7cbb4287 100644 --- a/src/client/util/CaptureManager.scss +++ b/src/client/util/CaptureManager.scss @@ -1,5 +1,3 @@ -@import '../views/global/globalCssVariables.module'; - .capture-interface { //background-color: whitesmoke !important; width: 450px; diff --git a/src/client/util/CurrentUserUtils.ts b/src/client/util/CurrentUserUtils.ts index 6ca181d92..8736225d0 100644 --- a/src/client/util/CurrentUserUtils.ts +++ b/src/client/util/CurrentUserUtils.ts @@ -445,7 +445,6 @@ pie title Minerals in my tap water { toolTip: "Tap or drag to create a view slide", title: "View Slide", icon: "address-card", dragFactory: doc.emptyViewSlide as Doc, clickFactory: DocCast(doc.emptyViewSlide), openFactoryLocation: OpenWhere.overlay,funcs: { hidden: "IsNoviceMode()"}}, { toolTip: "Tap or drag to create a data note", title: "DataNote", icon: "window-maximize", dragFactory: doc.emptyHeader as Doc, clickFactory: DocCast(doc.emptyHeader), openFactoryAsDelegate: true, funcs: { hidden: "IsNoviceMode()"} }, { toolTip: "Toggle a Calculator REPL", title: "replviewer", icon: "calculator", clickFactory: '<ScriptingRepl />' as unknown as Doc, openFactoryLocation: OpenWhere.overlay}, // hack: clickFactory is not a Doc but will get interpreted as a custom UI by the openDoc() onClick script - // { toolTip: "Toggle an UndoStack", title: "undostacker", icon: "calculator", clickFactory: "<UndoStack />" as any, openFactoryLocation: OpenWhere.overlay}, ].map(tuple => ( { openFactoryLocation: OpenWhere.addRight, scripts: { onClick: 'openDoc(copyDragFactory(this.clickFactory,this.openFactoryAsDelegate), this.openFactoryLocation)', @@ -674,12 +673,13 @@ pie title Minerals in my tap water CurrentUserUtils.createToolButton(opts), scripts, funcs); const btnDescs = [// setup reactions to change the highlights on the undo/redo buttons -- would be better to encode this in the undo/redo buttons, but the undo/redo stacks are not wired up that way yet - { scripts: { onClick: "undo()"}, opts: { title: "Undo", icon: "undo-alt", toolTip: "Undo ⌘Z" }}, - { scripts: { onClick: "redo()"}, opts: { title: "Redo", icon: "redo-alt", toolTip: "Redo ⌘⇧Z" }}, - { scripts: { }, opts: { title: "undoStack", layout: "<UndoStack>", toolTip: "Undo/Redo Stack"}}, // note: layout fields are hacks -- they don't actually run through the JSX parser (yet) - { scripts: { }, opts: { title: "linker", layout: "<LinkingUI>", toolTip: "link started"}}, - { scripts: { }, opts: { title: "currently playing", layout: "<CurrentlyPlayingUI>", toolTip: "currently playing media"}}, - { scripts: { }, opts: { title: "Branching", layout: "<Branching>", toolTip: "Branch, baby!"}} + { scripts: { onClick: "undo()"}, opts: { title: "Undo", icon: "undo-alt", toolTip: "Undo ⌘Z" }}, + { scripts: { onClick: "redo()"}, opts: { title: "Redo", icon: "redo-alt", toolTip: "Redo ⌘⇧Z" }}, + { scripts: { }, opts: { title: "undoStack", layout: "<UndoStack>", toolTip: "Undo/Redo Stack"}}, // note: layout fields are hacks -- they don't actually run through the JSX parser (yet) + { scripts: { }, opts: { title: "linker", layout: "<LinkingUI>", toolTip: "link started"}}, + { scripts: { }, opts: { title: "currently playing", layout: "<CurrentlyPlayingUI>", toolTip: "currently playing media"}}, + { scripts: { onClick: "hideUI()"},opts: { title: "Toggle UI", icon: "portrait", toolTip: "Toggle visibility of UI buttons"}}, + { scripts: { }, opts: { title: "Branching", layout: "<Branching>", toolTip: "Branch, baby!"}} ]; const btns = btnDescs.map(desc => dockBtn({_width: 30, _height: 30, defaultDoubleClick: 'ignore', undoIgnoreFields: new List<string>(['opacity']), _dragOnlyWithinContainer: true, ...desc.opts}, desc.scripts)); const dockBtnsReqdOpts:DocumentOptions = { @@ -710,11 +710,7 @@ pie title Minerals in my tap water { title: "Type", icon:"eye", toolTip:"Sort by document type", btnType: ButtonType.ToggleButton, expertMode: false, toolType:"docType", funcs: {}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}}, { title: "Color", icon:"palette", toolTip:"Sort by document color", btnType: ButtonType.ToggleButton, expertMode: false, toolType:"color", funcs: {}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}}, { title: "Tags", icon:"bolt", toolTip:"Sort by document's tags", btnType: ButtonType.ToggleButton, expertMode: false, toolType:"tag", funcs: {}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}}, - { title: "Sort", icon: "sort" , toolTip: "Manage sort order / lock status", btnType: ButtonType.MultiToggleButton, toolType:"alignment", ignoreClick: true, - subMenu: [ - { title: "Ascending", toolTip: "Sort the cards in ascending order", btnType: ButtonType.ToggleButton, icon: "sort-up", toolType:"up", ignoreClick: true, scripts: {onClick: '{ return showFreeform(this.toolType, _readOnly_);}'} }, - { title: "Descending",toolTip: "Sort the cards in descending order",btnType: ButtonType.ToggleButton, icon: "sort-down",toolType:"down",ignoreClick: true, scripts: {onClick: '{ return showFreeform(this.toolType, _readOnly_);}'} }, - ]}, + { title: "Reverse", icon: "sort-up", toolTip: "Sort the cards in reverse order", btnType: ButtonType.ToggleButton, expertMode: false, toolType:"reverse", funcs: {}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'} }, ] } @@ -738,7 +734,7 @@ pie title Minerals in my tap water } static viewTools(): Button[] { return [ - { title: "Show Tags", icon: "id-card", toolTip: "Toggle tags", btnType: ButtonType.ToggleButton, ignoreClick: true, expertMode: false, toolType:"toggle-tags",funcs: { }, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'} }, + { title: "Tags", icon: "id-card", toolTip: "Toggle Tags display", btnType: ButtonType.ToggleButton, ignoreClick: true, expertMode: false, toolType:"toggle-tags",funcs: { }, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'} }, { title: "Snap", icon: "th", toolTip: "Show Snap Lines", btnType: ButtonType.ToggleButton, ignoreClick: true, expertMode: false, toolType:"snaplines", funcs: { hidden: `!SelectedDocType("${CollectionViewType.Freeform}", this.expertMode)`}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}}, // Only when floating document is selected in freeform { title: "Grid", icon: "border-all", toolTip: "Show Grid", btnType: ButtonType.ToggleButton, ignoreClick: true, expertMode: false, toolType:"grid", funcs: { hidden: `!SelectedDocType("${CollectionViewType.Freeform}", this.expertMode)`}, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'}}, // Only when floating document is selected in freeform { title: "Fit All", icon: "object-group", toolTip:"Fit Docs to View (double tap to persist)", @@ -830,18 +826,20 @@ pie title Minerals in my tap water return [ { btnList: new List<string>([CollectionViewType.Freeform, CollectionViewType.Card, CollectionViewType.Carousel,CollectionViewType.Carousel3D, CollectionViewType.Masonry, CollectionViewType.Multicolumn, CollectionViewType.Multirow, CollectionViewType.Linear, - CollectionViewType.Map, CollectionViewType.NoteTaking, CollectionViewType.Schema, CollectionViewType.Stacking, + CollectionViewType.Map, CollectionViewType.NoteTaking, CollectionViewType.Pivot, CollectionViewType.Schema, CollectionViewType.Stacking, CollectionViewType.Calendar, CollectionViewType.Grid, CollectionViewType.Tree, CollectionViewType.Time, ]), title: "Perspective", toolTip: "View", btnType: ButtonType.DropdownList, ignoreClick: true, width: 100, scripts: { script: '{ return setView(value, shiftKey, _readOnly_); }'}}, { title: "Pin", icon: "map-pin", toolTip: "Pin View to Trail", btnType: ButtonType.ClickButton, expertMode: false, width: 30, scripts: { onClick: 'pinWithView(altKey)'}, funcs: {hidden: "IsNoneSelected()"}}, { title: "Header", icon: "heading", toolTip: "Doc Titlebar Color", btnType: ButtonType.ColorButton, expertMode: false, ignoreClick: true, scripts: { script: 'return setHeaderColor(value, _readOnly_)'} }, { title: "Template",icon: "scroll", toolTip: "Default Note Template",btnType: ButtonType.ToggleButton, expertMode: false, toolType:DocumentType.RTF, scripts: { onClick: '{ return setDefaultTemplate(_readOnly_); }'} }, { title: "Fill", icon: "fill-drip", toolTip: "Fill/Background Color",btnType: ButtonType.ColorButton, expertMode: false, ignoreClick: true, width: 30, scripts: { script: 'return setBackgroundColor(value, _readOnly_)'} }, // Only when a document is selected + { title: "Border", icon: "pen", toolTip: "Border Color", btnType: ButtonType.ColorButton, expertMode: false, ignoreClick: true, width: 30, scripts: { script: 'return setBorderColor(value, _readOnly_)'} }, // Only when a document is selected + { title: "B.Width", toolTip: "Border width", btnType: ButtonType.NumberSliderButton, ignoreClick: true, scripts: {script: '{ return setBorderWidth(value, _readOnly_);}'}, numBtnMin: 0, linearBtnWidth:40}, { title: "Overlay", icon: "layer-group", toolTip: "Overlay", btnType: ButtonType.ToggleButton, expertMode: true, toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectedDocType(this.toolType, this.expertMode, true)'}, scripts: { onClick: '{ return toggleOverlay(_readOnly_); }'}}, // Only when floating document is selected in freeform { title: "Back", icon: "chevron-left", toolTip: "Prev Animation Frame", btnType: ButtonType.ClickButton, expertMode: true, toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectedDocType(this.toolType, this.expertMode)'}, width: 30, scripts: { onClick: 'prevKeyFrame(_readOnly_)'}}, { title: "Num", icon:"", toolTip: "Frame # (click to toggle edit mode)",btnType: ButtonType.TextButton, expertMode: true, toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectedDocType(this.toolType, this.expertMode)', buttonText: 'selectedDocs()?.lastElement()?.currentFrame?.toString()'}, width: 20, scripts: { onClick: '{ return curKeyFrame(_readOnly_);}'}}, { title: "Fwd", icon: "chevron-right", toolTip: "Next Animation Frame", btnType: ButtonType.ClickButton, expertMode: true, toolType:CollectionViewType.Freeform, funcs: {hidden: '!SelectedDocType(this.toolType, this.expertMode)'}, width: 30, scripts: { onClick: 'nextKeyFrame(_readOnly_)'}}, - { title: "Chat", icon:"lightbulb", toolTip: "Toggle Chat Assistant",btnType: ButtonType.ToggleButton, expertMode: false, toolType:"toggle-chat", funcs: {}, width: 30, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'} }, + { title: "Chat", icon: "lightbulb", toolTip: "Toggle Chat Assistant",btnType: ButtonType.ToggleButton, expertMode: false, toolType:"toggle-chat", funcs: {}, width: 30, scripts: { onClick: '{ return showFreeform(this.toolType, _readOnly_);}'} }, { title: "Filter", icon: "=", toolTip: "Filter cards by tags", subMenu: CurrentUserUtils.filterTools(), ignoreClick:true, toolType:DocumentType.COL, funcs: {hidden: '!SelectedDocType(this.toolType, this.expertMode)'}, btnType: ButtonType.MultiToggleButton, width: 30, backgroundColor: doc.userVariantColor as string}, { title: "Sort", icon: "Sort", toolTip: "Sort Documents", subMenu: CurrentUserUtils.sortTools(), expertMode: false, toolType:DocumentType.COL, funcs: {hidden: `!SelectedDocType(this.toolType, this.expertMode)`, linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`} }, // Always available { title: "Text", icon: "Text", toolTip: "Text functions", subMenu: CurrentUserUtils.textTools(), expertMode: false, toolType:DocumentType.RTF, funcs: { linearView_IsOpen: `SelectedDocType(this.toolType, this.expertMode)`} }, // Always available @@ -913,7 +911,7 @@ pie title Minerals in my tap water CurrentUserUtils.createToolButton(opts), scripts, funcs); const btnDescs = [// setup reactions to change the highlights on the undo/redo buttons -- would be better to encode this in the undo/redo buttons, but the undo/redo stacks are not wired up that way yet - { opts: { title: "Replicate",icon:"camera",toolTip: "Copy dashboard layout",btnType: ButtonType.ClickButton, expertMode: true}, scripts: { onClick: `snapshotDashboard()`}}, + { opts: { title: "Replicate",icon:"camera",toolTip:"Copy dashboard layout",btnType: ButtonType.ClickButton, expertMode: true}, scripts: { onClick: `snapshotDashboard()`}}, { opts: { title: "Recordings", toolTip: "Workspace Recordings", btnType: ButtonType.DropdownList,expertMode: false, ignoreClick: true, width: 100}, funcs: {hidden: `false`, btnList:`getWorkspaceRecordings()`},scripts: { script: `{ return replayWorkspace(value, _readOnly_); }`, onDragScript: `{ return startRecordingDrag(value); }`}}, { opts: { title: "Stop Rec",icon: "stop", toolTip: "Stop recording", btnType: ButtonType.ClickButton, expertMode: false}, funcs: {hidden: `!isWorkspaceRecording()`}, scripts: { onClick: `stopWorkspaceRecording()`}}, { opts: { title: "Play", icon: "play", toolTip: "Play recording", btnType: ButtonType.ClickButton, expertMode: false}, funcs: {hidden: `isWorkspaceReplaying() !== "${mediaState.Paused}"`}, scripts: { onClick: `resumeWorkspaceReplaying(getCurrentRecording())`}}, diff --git a/src/client/util/DocumentManager.ts b/src/client/util/DocumentManager.ts index acb35f7eb..e33449782 100644 --- a/src/client/util/DocumentManager.ts +++ b/src/client/util/DocumentManager.ts @@ -354,9 +354,10 @@ export class DocumentManager { // bcz: should this delay be an options parameter? setTimeout(() => { Doc.linkFollowHighlight(viewSpec ? [docView.Document, viewSpec] : docView.Document, undefined, options.effect); - if (options.zoomTextSelections && Doc.IsUnhighlightTimerSet() && contextView && targetDoc.text_html) { + const zoomableText = StrCast(targetDoc.text_html, StrCast(targetDoc.ai_firefly_prompt)); + if (options.zoomTextSelections && Doc.IsUnhighlightTimerSet() && contextView && zoomableText) { // if the docView is a text anchor, the contextView is the PDF/Web/Text doc - contextView.setTextHtmlOverlay(StrCast(targetDoc.text_html), options.effect); + contextView.setTextHtmlOverlay(zoomableText, options.effect); DocumentManager._overlayViews.add(contextView); } Doc.AddUnHighlightWatcher(() => { diff --git a/src/client/util/DragManager.ts b/src/client/util/DragManager.ts index 81ea840f1..2a7859f09 100644 --- a/src/client/util/DragManager.ts +++ b/src/client/util/DragManager.ts @@ -555,9 +555,12 @@ export namespace DragManager { let scrollAwaiter: Opt<NodeJS.Timeout>; let startWindowDragTimer: NodeJS.Timeout | undefined; + const startCanEmbed = SnappingManager.CanEmbed; const moveHandler = (e: PointerEvent) => { e.preventDefault(); // required or dragging text menu link item ends up dragging the link button as native drag/drop if (docDragData) { + if (e.ctrlKey) SnappingManager.SetCanEmbed(true); + else if (!startCanEmbed) SnappingManager.SetCanEmbed(false); docDragData.userDropAction = e.ctrlKey && e.altKey ? dropActionType.copy : e.shiftKey ? dropActionType.move : e.ctrlKey ? dropActionType.embed : docDragData.defaultDropAction; const targClassName = e.target instanceof HTMLElement && typeof e.target.className === 'string' ? e.target.className : ''; if (['lm_tab', 'lm_title_wrap', 'lm_tabs', 'lm_header'].includes(targClassName) && docDragData.draggedDocuments.length === 1) { diff --git a/src/client/util/History.ts b/src/client/util/History.ts index 0d0c056a4..9728e3177 100644 --- a/src/client/util/History.ts +++ b/src/client/util/History.ts @@ -1,10 +1,6 @@ /* eslint-disable no-use-before-define */ /* eslint-disable no-empty */ -/* eslint-disable no-continue */ -/* eslint-disable guard-for-in */ -/* eslint-disable no-restricted-syntax */ /* eslint-disable no-param-reassign */ -import * as qs from 'query-string'; import { Doc } from '../../fields/Doc'; import { OmitKeys, ClientUtils } from '../../ClientUtils'; import { DocServer } from '../DocServer'; @@ -82,7 +78,7 @@ export namespace HistoryUtil { // } // } - const parsers: { [type: string]: (pathname: string[], opts: qs.ParsedQuery) => ParsedUrl | undefined } = {}; + const parsers: { [type: string]: (pathname: string[], opts: URLSearchParams) => ParsedUrl | undefined } = {}; const stringifiers: { [type: string]: (state: ParsedUrl) => string } = {}; type ParserValue = true | 'none' | 'json' | ((value: string) => string | null | (string | null)[]); @@ -91,8 +87,8 @@ export namespace HistoryUtil { [key: string]: ParserValue; }; - function addParser(type: string, requiredFields: Parser, optionalFields: Parser, customParser?: (pathname: string[], opts: qs.ParsedQuery, current: ParsedUrl) => ParsedUrl | null | undefined) { - function parse(parser: ParserValue, value: string | (string | null)[] | null | undefined) { + function addParser(type: string, requiredFields: Parser, optionalFields: Parser, customParser?: (pathname: string[], opts: URLSearchParams, current: ParsedUrl) => ParsedUrl | null | undefined) { + function parseValue(parser: ParserValue, value: string | (string | null)[] | null | undefined) { if (value === undefined || value === null) { return value; } @@ -108,21 +104,21 @@ export namespace HistoryUtil { parsers[type] = (pathname, opts) => { const current: DocUrl & { [key: string]: null | (string | null)[] | string } = { type: 'doc', docId: '' }; for (const required in requiredFields) { - if (!(required in opts)) { + if (!opts.has(required)) { return undefined; } const parser = requiredFields[required]; - const value = parse(parser, opts[required]); + const value = parseValue(parser, opts.get(required)); if (value !== null && value !== undefined) { current[required] = value; } } for (const opt in optionalFields) { - if (!(opt in opts)) { + if (!opts.has(opt)) { continue; } const parser = optionalFields[opt]; - const value = parse(parser, opts[opt]); + const value = parseValue(parser, opts.get(opt)); if (value !== undefined) { current[opt] = value; } @@ -148,12 +144,12 @@ export namespace HistoryUtil { path = customStringifier(state, path); } const queryObj = OmitKeys(state, keys).extract; - const query: { [key: string]: string | null } = {}; + const query = new URLSearchParams(); Object.keys(queryObj).forEach(key => { - query[key] = queryObj[key] === null ? null : JSON.stringify(queryObj[key]); + query.set(key, queryObj[key] === null ? '' : JSON.stringify(queryObj[key])); }); - const queryString = qs.stringify(query); - return path + (queryString ? `?${queryString}` : ''); + const qstr = query.toString(); + return path + (qstr ? `?${qstr}` : ''); }; } @@ -170,7 +166,7 @@ export namespace HistoryUtil { export function parseUrl(location: Location | URL): ParsedUrl | undefined { const pathname = location.pathname.substring(1); const { search } = location; - const opts = search.length ? qs.parse(search, { sort: false }) : {}; + const opts = new URLSearchParams(search); const pathnameSplit = pathname.split('/'); const type = pathnameSplit[0]; diff --git a/src/client/util/Import & Export/ImageUtils.ts b/src/client/util/Import & Export/ImageUtils.ts index 8d4eefa7e..43807397f 100644 --- a/src/client/util/Import & Export/ImageUtils.ts +++ b/src/client/util/Import & Export/ImageUtils.ts @@ -4,22 +4,16 @@ import { DocData } from '../../../fields/DocSymbols'; import { Id } from '../../../fields/FieldSymbols'; import { Cast, NumCast, StrCast } from '../../../fields/Types'; import { ImageField } from '../../../fields/URLField'; +import { Upload } from '../../../server/SharedMediaTypes'; import { Networking } from '../../Network'; export namespace ImageUtils { - export type imgInfo = { - contentSize: number; - nativeWidth: number; - nativeHeight: number; - source: string; - exifData: { error: string | undefined; data: string }; - }; - export const ExtractImgInfo = async (document: Doc): Promise<imgInfo | undefined> => { + export const ExtractImgInfo = async (document: Doc) => { const field = Cast(document.data, ImageField); - return field ? Networking.PostToServer('/inspectImage', { source: field.url.href }) : undefined; + return field ? (Networking.PostToServer('/inspectImage', { source: field.url.href }) as Promise<Upload.InspectionResults>) : undefined; }; - export const AssignImgInfo = (document: Doc, data?: imgInfo) => { + export const AssignImgInfo = (document: Doc, data?: Upload.InspectionResults) => { if (data) { data.nativeWidth && (document._height = (NumCast(document._width) * data.nativeHeight) / data.nativeWidth); const proto = document[DocData]; diff --git a/src/client/util/PingManager.ts b/src/client/util/PingManager.ts index 255e9cee0..0e4f8cab0 100644 --- a/src/client/util/PingManager.ts +++ b/src/client/util/PingManager.ts @@ -1,44 +1,37 @@ -import { action, makeObservable, observable, runInAction } from 'mobx'; +import { action, makeObservable, observable } from 'mobx'; import { Networking } from '../Network'; import { SnappingManager } from './SnappingManager'; export class PingManager { + PING_INTERVAL_SECONDS = 1; + // not used now, but may need to clear interval + private _interval: NodeJS.Timeout | null = null; // create static instance and getter for global use // eslint-disable-next-line no-use-before-define - @observable static _instance: PingManager; + @observable private static _instance: PingManager; @observable IsBeating = true; static get Instance(): PingManager { return PingManager._instance; } - // not used now, but may need to clear interval - private _interval: NodeJS.Timeout | null = null; - INTERVAL_SECONDS = 1; constructor() { makeObservable(this); PingManager._instance = this; - this._interval = setInterval(this.sendPing, this.INTERVAL_SECONDS * 1000); + this._interval = setInterval(this.sendPing, this.PING_INTERVAL_SECONDS * 1000); } - private setIsBeating = action((status: boolean) => { - this.IsBeating = status; - setTimeout(this.showAlert, 100); - }); + showAlert = () => alert(PingManager.Instance.IsBeating ? 'The server connection is active' : 'The server connection has been interrupted.NOTE: Any changes made will appear to persist but will be lost after a browser refreshes.'); - showAlert = () => { - alert(PingManager.Instance.IsBeating ? 'The server connection is active' : 'The server connection has been interrupted.NOTE: Any changes made will appear to persist but will be lost after a browser refreshes.'); - }; - sendPing = async (): Promise<void> => { - try { - const res = await Networking.PostToServer('/ping', { date: new Date() }); - runInAction(() => { - SnappingManager.SetServerVersion(res.message); - }); - !this.IsBeating && this.setIsBeating(true); - } catch { - if (this.IsBeating) { - this.setIsBeating(false); - } - } + sendPing = () => { + const setIsBeating = action((status: boolean) => { + this.IsBeating = status; + setTimeout(this.showAlert, 100); + }); + Networking.PostToServer('/ping', { date: new Date() }) + .then(res => { + SnappingManager.SetServerVersion((res as { message: string }).message); + !this.IsBeating && setIsBeating(true); + }) + .catch(() => this.IsBeating && setIsBeating(false)); }; } diff --git a/src/client/util/SettingsManager.scss b/src/client/util/SettingsManager.scss index dbfc48c63..f81f17589 100644 --- a/src/client/util/SettingsManager.scss +++ b/src/client/util/SettingsManager.scss @@ -1,5 +1,3 @@ -@import '../views/global/globalCssVariables.module'; - .settings-interface { //background-color: whitesmoke !important; width: 450px; diff --git a/src/client/util/SettingsManager.tsx b/src/client/util/SettingsManager.tsx index 5d041f7b4..6ea242fc3 100644 --- a/src/client/util/SettingsManager.tsx +++ b/src/client/util/SettingsManager.tsx @@ -598,7 +598,8 @@ export class SettingsManager extends React.Component<object> { }); } else { const passwordBundle = { curr_pass: this._curr_password, new_pass: this._new_password, new_confirm: this._new_confirm }; - const { error } = await Networking.PostToServer('/internalResetPassword', passwordBundle); + const reset = await Networking.PostToServer('/internalResetPassword', passwordBundle); + const { error } = reset as { error: { msg: string }[] }; runInAction(() => { this._passwordResultText = error ? 'Error: ' + error[0].msg + '...' : 'Password successfully updated!'; }); diff --git a/src/client/util/SharingManager.tsx b/src/client/util/SharingManager.tsx index efc8e79a6..3a248400b 100644 --- a/src/client/util/SharingManager.tsx +++ b/src/client/util/SharingManager.tsx @@ -502,7 +502,6 @@ export class SharingManager extends React.Component<object> { } }; - // eslint-disable-next-line react/sort-comp public close = action(() => { this.isOpen = false; this.selectedUsers = null; // resets the list of users and selected users (in the react-select component) @@ -517,7 +516,6 @@ export class SharingManager extends React.Component<object> { this.layoutDocAcls = false; }); - // eslint-disable-next-line react/no-unused-class-component-methods public open = (target?: DocumentView, targetDoc?: Doc) => { this.populateUsers(); runInAction(() => { @@ -534,7 +532,6 @@ export class SharingManager extends React.Component<object> { * @param group * @param emailId */ - // eslint-disable-next-line react/no-unused-class-component-methods shareWithAddedMember = (group: Doc, emailId: string, retry: boolean = true) => { const user = this.users.find(({ user: { email } }) => email === emailId)!; if (group.docsShared) { @@ -559,7 +556,6 @@ export class SharingManager extends React.Component<object> { /** * Called from the properties sidebar to change permissions of a user. */ - // eslint-disable-next-line react/no-unused-class-component-methods shareFromPropertiesSidebar = undoable((shareWith: string, permission: SharingPermissions, docs: Doc[], layout: boolean) => { if (layout) this.layoutDocAcls = true; if (shareWith !== 'Guest') { @@ -583,7 +579,6 @@ export class SharingManager extends React.Component<object> { * @param group * @param emailId */ - // eslint-disable-next-line react/no-unused-class-component-methods removeMember = (group: Doc, emailId: string) => { const user: ValidatedUser = this.users.find(({ user: { email } }) => email === emailId)!; @@ -607,7 +602,6 @@ export class SharingManager extends React.Component<object> { * Removes a group's permissions from documents that have been shared with it. * @param group */ - // eslint-disable-next-line react/no-unused-class-component-methods removeGroup = (group: Doc) => { if (group.docsShared) { DocListCast(group.docsShared).forEach(doc => { diff --git a/src/client/util/SnappingManager.ts b/src/client/util/SnappingManager.ts index 2a150dc5a..3bbc297b8 100644 --- a/src/client/util/SnappingManager.ts +++ b/src/client/util/SnappingManager.ts @@ -16,6 +16,7 @@ export class SnappingManager { @observable _shiftKey = false; @observable _ctrlKey = false; @observable _metaKey = false; + @observable _hideUI = false; @observable _showPresPaths = false; @observable _isLinkFollowing = false; @observable _isDragging: boolean = false; @@ -32,6 +33,7 @@ export class SnappingManager { @observable _hideDecorations: boolean = false; @observable _keepGestureMode: boolean = false; // for whether primitive selection enters a one-shot or persistent mode @observable _inkShape: Gestures | undefined = undefined; + @observable _chatVisible: boolean = false; private constructor() { SnappingManager._manager = this; @@ -52,6 +54,7 @@ export class SnappingManager { public static get ShiftKey() { return this.Instance._shiftKey; } // prettier-ignore public static get CtrlKey() { return this.Instance._ctrlKey; } // prettier-ignore public static get MetaKey() { return this.Instance._metaKey; } // prettier-ignore + public static get HideUI() { return this.Instance._hideUI; } // prettier-ignore public static get ShowPresPaths() { return this.Instance._showPresPaths; } // prettier-ignore public static get IsLinkFollowing(){ return this.Instance._isLinkFollowing; } // prettier-ignore public static get IsDragging() { return this.Instance._isDragging; } // prettier-ignore @@ -66,11 +69,13 @@ export class SnappingManager { public static get HideDecorations(){ return this.Instance._hideDecorations; } // prettier-ignore public static get KeepGestureMode(){ return this.Instance._keepGestureMode; } // prettier-ignore public static get InkShape() { return this.Instance._inkShape; } // prettier-ignore + public static get ChatVisible() { return this.Instance._chatVisible; } // prettier-ignore public static SetLongPress = (press: boolean) => runInAction(() => {this.Instance._longPress = press}); // prettier-ignore public static SetShiftKey = (down: boolean) => runInAction(() => {this.Instance._shiftKey = down}); // prettier-ignore public static SetCtrlKey = (down: boolean) => runInAction(() => {this.Instance._ctrlKey = down}); // prettier-ignore public static SetMetaKey = (down: boolean) => runInAction(() => {this.Instance._metaKey = down}); // prettier-ignore + public static SetHideUI = (vis: boolean) => runInAction(() => {this.Instance._hideUI = vis}); // prettier-ignore public static SetShowPresPaths = (paths:boolean) => runInAction(() => {this.Instance._showPresPaths = paths}); // prettier-ignore public static SetIsLinkFollowing= (follow:boolean)=> runInAction(() => {this.Instance._isLinkFollowing = follow}); // prettier-ignore public static SetIsDragging = (drag: boolean) => runInAction(() => {this.Instance._isDragging = drag}); // prettier-ignore @@ -85,6 +90,7 @@ export class SnappingManager { public static SetHideDecorations= (state:boolean) =>runInAction(() => {this.Instance._hideDecorations = state}); // prettier-ignore public static SetKeepGestureMode= (state:boolean) =>runInAction(() => {this.Instance._keepGestureMode = state}); // prettier-ignore public static SetInkShape = (shape?:Gestures)=>runInAction(() => {this.Instance._inkShape = shape}); // prettier-ignore + public static SetChatVisible = (vis:boolean) =>runInAction(() => {this.Instance._chatVisible = vis}); // prettier-ignore public static userColor: string | undefined; public static userVariantColor: string | undefined; diff --git a/src/client/util/bezierFit.ts b/src/client/util/bezierFit.ts index 7ef370d48..0399fe1d5 100644 --- a/src/client/util/bezierFit.ts +++ b/src/client/util/bezierFit.ts @@ -1,8 +1,7 @@ /* eslint-disable no-use-before-define */ -/* eslint-disable prefer-destructuring */ /* eslint-disable no-param-reassign */ -/* eslint-disable camelcase */ import { Point } from '../../pen-gestures/ndollar'; +import { numberRange } from '../../Utils'; export enum SVGType { Rect = 'rect', @@ -625,13 +624,132 @@ export function GenerateControlPoints(coordinates: Point[], alpha = 0.1) { return [...firstEnd, ...points, ...lastEnd]; } -export function SVGToBezier(name: SVGType, attributes: any): Point[] { +function convertRelativePathCmdsToAbsolute(pathData: string): string { + const commands = pathData.match(/[a-zA-Z][^a-zA-Z]*/g); + let currentX = 0; + let currentY = 0; + let startX = 0; + let startY = 0; + const absoluteCommands = commands?.map(command => { + const values = command + .slice(1) + .trim() + .split(/[\s,]+/) + .map(v => +v); + + switch (command[0]) { + case 'M': + currentX = values[0]; + currentY = values[1]; + startX = currentX; + startY = currentY; + return `M${currentX},${currentY}`; + case 'm': + currentX += values[0]; + currentY += values[1]; + startX = currentX; + startY = currentY; + return `M${currentX},${currentY}`; + case 'L': + currentX = values[values.length - 2]; + currentY = values[values.length - 1]; + return `L${values.join(',')}`; + case 'l': { + let str = ''; + for (let i = 0; i < values.length; i += 2) { + str += (i === 0 ? 'L':',') + (values[i] + currentX) + + ',' + (values[i + 1] + currentY); // prettier-ignore + currentX += values[i]; + currentY += values[i + 1]; + } + return str; + } + case 'H': + currentX = values[0]; + return `H${currentX}`; + case 'h': + currentX += values[0]; + return `H${currentX}`; + case 'V': + currentY = values[0]; + return `V${currentY}`; + case 'v': + currentY += values[0]; + return `V${currentY}`; + case 'C': + currentX = values[values.length - 2]; + currentY = values[values.length - 1]; + return `C${values.join(',')}`; + case 'c': { + let str = ''; + for (let i = 0; i < values.length; i += 6) { + str += (i === 0 ? 'C':',') + (values[i] + currentX) + + ',' + (values[i + 1] + currentY) + + ',' + (values[i + 2] + currentX) + + ',' + (values[i + 3] + currentY) + + ',' + (values[i + 4] + currentX) + + ',' + (values[i + 5] + currentY); // prettier-ignore + currentX += values[i + 4]; + currentY += values[i + 5]; + } + return str; + } + case 'S': + currentX = values[2]; + currentY = values[3]; + return `S${values.join(',')}`; + case 's': + return `S${values.map((v, i) => (i % 2 === 0 ? (currentX += v) : (currentY += v))).join(',')}`; + case 'Q': + currentX = values[values.length - 2]; + currentY = values[values.length - 1]; + return `Q${values.join(',')}`; + case 'q': { + let str = ''; + for (let i = 0; i < values.length; i += 4) { + str += (i === 0 ? 'Q':',') + (values[i] + currentX) + + ',' + (values[i + 1] + currentY) + + ',' + (values[i + 2] + currentX) + + ',' + (values[i + 3] + currentY); // prettier-ignore + currentX += values[i + 2]; + currentY += values[i + 3]; + } + return str; + } + case 'T': + currentX = values[0]; + currentY = values[1]; + return `T${currentX},${currentY}`; + case 't': + currentX += values[0]; + currentY += values[1]; + return `T${currentX},${currentY}`; + case 'A': + currentX = values[5]; + currentY = values[6]; + return `A${values.join(',')}`; + case 'a': + return `A${values.map((v, i) => (i % 2 === 0 ? (currentX += v) : (currentY += v))).join(',')}`; + case 'Z': + case 'z': + currentX = startX; + currentY = startY; + return 'Z'; + default: + return command; + } + }); + + return absoluteCommands?.join(' ') ?? pathData; +} + +export function SVGToBezier(name: SVGType, attributes: Record<string, string>, last: { X: number; Y: number }): Point[] { switch (name) { case 'line': { - const x1 = parseInt(attributes.x1); - const x2 = parseInt(attributes.x2); - const y1 = parseInt(attributes.y1); - const y2 = parseInt(attributes.y2); + const x1 = +attributes.x1; + const x2 = +attributes.x2; + const y1 = +attributes.y1; + const y2 = +attributes.y2; return [ { X: x1, Y: y1 }, { X: x1, Y: y1 }, @@ -642,10 +760,10 @@ export function SVGToBezier(name: SVGType, attributes: any): Point[] { case 'circle': case 'ellipse': { const c = 0.551915024494; - const centerX = parseInt(attributes.cx); - const centerY = parseInt(attributes.cy); - const radiusX = parseInt(attributes.rx) || parseInt(attributes.r); - const radiusY = parseInt(attributes.ry) || parseInt(attributes.r); + const centerX = +attributes.cx; + const centerY = +attributes.cy; + const radiusX = +attributes.rx || +attributes.r; + const radiusY = +attributes.ry || +attributes.r; return [ { X: centerX, Y: centerY + radiusY }, { X: centerX + c * radiusX, Y: centerY + radiusY }, @@ -666,10 +784,10 @@ export function SVGToBezier(name: SVGType, attributes: any): Point[] { ]; } case 'rect': { - const x = parseInt(attributes.x); - const y = parseInt(attributes.y); - const width = parseInt(attributes.width); - const height = parseInt(attributes.height); + const x = +attributes.x; + const y = +attributes.y; + const width = +attributes.width; + const height = +attributes.height; return [ { X: x, Y: y }, { X: x, Y: y }, @@ -690,57 +808,73 @@ export function SVGToBezier(name: SVGType, attributes: any): Point[] { ]; } case 'path': { - const coordList: Point[] = []; - const [startX, startY] = attributes.d.match(/M(-?\d+\.?\d*),(-?\d+\.?\d*)/).slice(1); - const startPt = { X: parseInt(startX), Y: parseInt(startY) }; - coordList.push(startPt); - const matches: RegExpMatchArray[] = Array.from( - attributes.d.matchAll(/Q(-?\d+\.?\d*),(-?\d+\.?\d*) (-?\d+\.?\d*),(-?\d+\.?\d*)|C(-?\d+\.?\d*),(-?\d+\.?\d*) (-?\d+\.?\d*),(-?\d+\.?\d*) (-?\d+\.?\d*),(-?\d+\.?\d*)|L(-?\d+\.?\d*),(-?\d+\.?\d*)/g) + const cmds = new Map<string, number>([ + ['A', 7], + ['C', 6], + ['Q', 4], + ['L', 2], + ['V', 1], + ['H', 1], + ['Z', 0], + ['M', 2], + ]); + const cmdReg = (letter: string) => `${letter}?${numberRange(cmds.get(letter)??0).map(() => '[, ]?(-?\\d*\\.?\\d*)').join('')}`; // prettier-ignore + const pathdata = convertRelativePathCmdsToAbsolute( + attributes.d + .replace(/([0-9])-/g, '$1,-') // numbers are smooshed together - put a ',' between number-number => number,-number + .replace(/([.][0-9]+)(?=\.)/g, '$1,') // numbers are smooshed together - put a ',' between .number.number => .number,.number + .trim() ); - let lastPt: Point = startPt; - matches.forEach(match => { - if (match[0].startsWith('Q')) { - coordList.push({ X: parseInt(match[1]), Y: parseInt(match[2]) }); - coordList.push({ X: parseInt(match[1]), Y: parseInt(match[2]) }); - coordList.push({ X: parseInt(match[3]), Y: parseInt(match[4]) }); - coordList.push({ X: parseInt(match[3]), Y: parseInt(match[4]) }); - lastPt = { X: parseInt(match[3]), Y: parseInt(match[4]) }; - } else if (match[0].startsWith('C')) { - coordList.push({ X: parseInt(match[5]), Y: parseInt(match[6]) }); - coordList.push({ X: parseInt(match[7]), Y: parseInt(match[8]) }); - coordList.push({ X: parseInt(match[9]), Y: parseInt(match[10]) }); - coordList.push({ X: parseInt(match[9]), Y: parseInt(match[10]) }); - lastPt = { X: parseInt(match[9]), Y: parseInt(match[10]) }; - } else { - coordList.push(lastPt); - coordList.push({ X: parseInt(match[11]), Y: parseInt(match[12]) }); - coordList.push({ X: parseInt(match[11]), Y: parseInt(match[12]) }); - coordList.push({ X: parseInt(match[11]), Y: parseInt(match[12]) }); - lastPt = { X: parseInt(match[11]), Y: parseInt(match[12]) }; - } - }); - const hasZ = attributes.d.match(/Z/); - if (hasZ || attributes.fill) { - coordList.push(lastPt); - coordList.push(startPt); - coordList.push(startPt); - } else { - coordList.pop(); - } + const move = pathdata.match(cmdReg('M')); + const start = move?.slice(1).map(v => +v) ?? [last.X, last.Y]; + const coordList: Point[] = []; + for (let prev = coordList.lastElement() ?? { X: start[0], Y: start[1] }, + pathcmd = pathdata.slice(move?.[0].length ?? 0).trim(), + m = move, + lastCmd = ''; + pathcmd; + pathcmd = pathcmd.slice(m?.[0].length ?? 1).trim(), + prev = coordList.lastElement() + ) { + lastCmd = Array.from(cmds.keys()).includes(pathcmd[0]) ? pathcmd[0] : lastCmd; // command character is first, otherwise we're continuing coordinates for the last command + m = pathcmd.match(new RegExp(cmdReg(lastCmd)))!; // matches command + number parameters specific to command + switch (m ? lastCmd : 'error') { + case 'Q': // convert quadratic to Bezier + ((Q) => coordList.push( + prev, + { X: prev.X + (2 / 3) * (Q[0] - prev.X), Y: prev.Y + (2 / 3) * (Q[1] - prev.Y) }, + { X: Q[2] + (2 / 3) * (Q[0] - Q[2]), Y: Q[3] + (2 / 3) * (Q[1] - Q[3]) }, + { X: Q[2], Y: Q[3] } + ))([+m[1], +m[2], +m[3], +m[4]]); + break; case 'C': // bezier curve + coordList.push(prev, { X: +m[1], Y: +m[2] }, { X: +m[3], Y: +m[4] }, { X: +m[5], Y: +m[6] }); + break; case 'L': // convert line to bezier + coordList.push(prev, prev, { X: +m[1], Y: +m[2] }, { X: +m[1], Y: +m[2] }); + break; case 'H': // convert horiz line to bezier + coordList.push(prev, prev, { X: +m[1], Y: prev.Y }, { X: +m[1], Y: prev.Y }); + break; case 'V': // convert vert line to bezier + coordList.push(prev, prev, { X: prev.X, Y: +m[1] }, { X: prev.X, Y: +m[1] }); + break; case 'A': // convert arc to bezier + console.log('SKIPPING arc - conversion to bezier not implemented'); + break; case 'Z': + break; + default: + // eslint-disable-next-line no-debugger + debugger; + } // prettier-ignore + } // prettier-ignore return coordList; } case 'polygon': { - const coords: RegExpMatchArray[] = Array.from(attributes.points.matchAll(/(-?\d+\.?\d*),(-?\d+\.?\d*)/g)); - let list: Point[] = []; + const coords = Array.from(attributes.points.matchAll(/(-?\d+\.?\d*),(-?\d+\.?\d*)/g)); + const list: Point[] = []; coords.forEach(coord => { - list.push({ X: parseInt(coord[1]), Y: parseInt(coord[2]) }); - list.push({ X: parseInt(coord[1]), Y: parseInt(coord[2]) }); - list.push({ X: parseInt(coord[1]), Y: parseInt(coord[2]) }); - list.push({ X: parseInt(coord[1]), Y: parseInt(coord[2]) }); + list.push({ X: +coord[1], Y: +coord[2] }); + list.push({ X: +coord[1], Y: +coord[2] }); + list.push({ X: +coord[1], Y: +coord[2] }); + list.push({ X: +coord[1], Y: +coord[2] }); }); - const firstPts = list.splice(0, 2); - list = list.concat(firstPts); - return list; + return list.concat(list.splice(0, 2)); // repeat start point to close } default: return []; diff --git a/src/client/util/node_modules/type_decls.d b/src/client/util/node_modules/type_decls.d index 9058b4394..8605b9f5b 100644 --- a/src/client/util/node_modules/type_decls.d +++ b/src/client/util/node_modules/type_decls.d @@ -67,8 +67,9 @@ interface RegExp { readonly sticky: boolean; readonly unicode: boolean; } -interface Date { +declare class Date { now() : string; + constructor(date:string); } interface String { codePointAt(pos: number): number | undefined; @@ -170,6 +171,7 @@ declare class VideoField extends URLField { [Copy](): ObjectField; } declare class ImageField extends URLField { [Copy](): ObjectField; } declare class WebField extends URLField { [Copy](): ObjectField; } declare class PdfField extends URLField { [Copy](): ObjectField; } +declare class DateField extends URLField { [Copy](): ObjectField; constructor(date:Date); } declare const ComputedField: any; declare const CompileScript: any; diff --git a/src/client/util/reportManager/ReportManager.scss b/src/client/util/reportManager/ReportManager.scss index fd343ac8e..806741c22 100644 --- a/src/client/util/reportManager/ReportManager.scss +++ b/src/client/util/reportManager/ReportManager.scss @@ -1,4 +1,4 @@ -@import '../../views/global/globalCssVariables.module'; +@use '../../views/global/globalCssVariables.module' as global; // header @@ -97,7 +97,7 @@ background: transparent; // &:hover { - // // border-bottom-color: $text-gray; + // // border-bottom-color: global.$text-gray; // } // &:focus { // // border-bottom-color: #4476f7; diff --git a/src/client/util/request-image-size.ts b/src/client/util/request-image-size.ts index c619192ed..32ab23618 100644 --- a/src/client/util/request-image-size.ts +++ b/src/client/util/request-image-size.ts @@ -1,4 +1,3 @@ -/* eslint-disable @typescript-eslint/no-var-requires */ /** * request-image-size: Detect image dimensions via request. * Licensed under the MIT license. @@ -11,12 +10,11 @@ */ // const imageSize = require('image-size'); -const HttpError = require('standard-http-error'); +import * as HttpError from 'standard-http-error'; import * as request from 'request'; import { imageSize } from 'image-size'; import { ISizeCalculationResult } from 'image-size/dist/types/interface'; - -module.exports = function requestImageSize(url: string) { +export function requestImageSize(url: string): Promise<ISizeCalculationResult> { if (!url) { return Promise.reject(new Error('You should provide an URI string or a "request" options object.')); } @@ -60,4 +58,5 @@ module.exports = function requestImageSize(url: string) { req.on('error', reject); }); -}; +} +export default requestImageSize; diff --git a/src/client/views/AntimodeMenu.scss b/src/client/views/AntimodeMenu.scss index 2ebf673fe..c2f6ae62d 100644 --- a/src/client/views/AntimodeMenu.scss +++ b/src/client/views/AntimodeMenu.scss @@ -1,12 +1,11 @@ -@import './global/globalCssVariables.module'; +@use './global/globalCssVariables.module' as global; .antimodeMenu-cont { position: absolute; z-index: 10001; - height: $antimodemenu-height; + height: global.$antimodemenu-height; width: fit-content; - border-radius: $standard-border-radius; - overflow: hidden; + border-radius: global.$standard-border-radius; // box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.25); // border-radius: 0px 6px 6px 6px; display: flex; diff --git a/src/client/views/ContextMenu.scss b/src/client/views/ContextMenu.scss index 88e147a03..d22c4d096 100644 --- a/src/client/views/ContextMenu.scss +++ b/src/client/views/ContextMenu.scss @@ -1,9 +1,9 @@ -@import 'global/globalCssVariables.module.scss'; +@use 'global/globalCssVariables.module.scss' as global; .contextMenu-cont { position: absolute; display: flex; - z-index: $contextMenu-zindex; + z-index: global.$contextMenu-zindex; box-shadow: 0px 3px 4px rgba(0, 0, 0, 30%); flex-direction: column; background: whitesmoke; @@ -109,7 +109,7 @@ .contextMenu-item:hover { border-width: 0.11px; border-style: none; - border-color: $medium-gray; // rgb(187, 186, 186); + border-color: global.$medium-gray; // rgb(187, 186, 186); border-bottom-style: solid; border-top-style: solid; @@ -139,7 +139,7 @@ transition: all 0.1s; border-width: 0.11px; border-style: none; - border-color: $medium-gray; // rgb(187, 186, 186); + border-color: global.$medium-gray; // rgb(187, 186, 186); // padding: 10px 0px 10px 0px; white-space: nowrap; font-size: 13px; @@ -184,7 +184,7 @@ .top-bar { height: 20px; width: 100%; - display: flex; + display: flex; .close-menu { margin-top: 0; @@ -200,7 +200,7 @@ } } - .bottom-box{ + .bottom-box { display: flex; flex-direction: row; justify-content: center; @@ -209,11 +209,11 @@ height: 100%; width: 100%; - .width-selector{ + .width-selector { width: 100px; } - .max-min-selector{ + .max-min-selector { height: 15px; width: 30px; } diff --git a/src/client/views/DashboardView.scss b/src/client/views/DashboardView.scss index 25feca7bf..daa711bc4 100644 --- a/src/client/views/DashboardView.scss +++ b/src/client/views/DashboardView.scss @@ -1,4 +1,4 @@ -@import './global/globalCssVariables.module'; +@use './global/globalCssVariables.module' as global; $dashboard-left-menu-width: 250px; $dashboard-view-padding: 20px; @@ -61,9 +61,9 @@ $dashboard-container-width: 250px; font-size: 120px; font-weight: 100; text-align: center; - border: solid 2px $light-gray; + border: solid 2px global.$light-gray; cursor: pointer; - color: $light-gray; + color: global.$light-gray; display: flex; display: flex; justify-content: center; @@ -71,8 +71,8 @@ $dashboard-container-width: 250px; position: relative; &:hover { - color: $light-blue; - border: solid 2px $light-blue; + color: global.$light-blue; + border: solid 2px global.$light-blue; } .background { @@ -91,14 +91,14 @@ $dashboard-container-width: 250px; cursor: pointer; width: $dashboard-container-width; height: $dashboard-container-height; - outline: solid 2px $light-gray; + outline: solid 2px global.$light-gray; outline-offset: -2px; display: flex; flex-direction: column; overflow: hidden; &:hover { - outline: solid 2px $light-blue; + outline: solid 2px global.$light-blue; } .title { @@ -144,7 +144,7 @@ $dashboard-container-width: 250px; } .new-dashboard { - color: $dark-gray; + color: global.$dark-gray; padding: 10px; display: flex; width: 100%; diff --git a/src/client/views/DocumentButtonBar.scss b/src/client/views/DocumentButtonBar.scss index ede277aae..f19fecfa6 100644 --- a/src/client/views/DocumentButtonBar.scss +++ b/src/client/views/DocumentButtonBar.scss @@ -1,4 +1,4 @@ -@import 'global/globalCssVariables.module'; +@use 'global/globalCssVariables.module' as global; $linkGap: 3px; @@ -7,13 +7,13 @@ $linkGap: 3px; } .documentButtonBar-linkButton-empty:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); cursor: pointer; } .documentButtonBar-linkButton-nonempty:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); cursor: pointer; } @@ -32,7 +32,6 @@ $linkGap: 3px; .tags { width: 40px; - } } .documentButtonBar-followTypes { @@ -92,8 +91,8 @@ $linkGap: 3px; border-radius: 50%; opacity: 0.9; pointer-events: auto; - background-color: $dark-gray; - color: $white; + background-color: global.$dark-gray; + color: global.$white; text-transform: uppercase; letter-spacing: 2px; font-size: 75%; @@ -104,7 +103,7 @@ $linkGap: 3px; align-items: center; &:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); cursor: pointer; } @@ -132,12 +131,12 @@ $linkGap: 3px; text-align: center; border-radius: 50%; pointer-events: auto; - background-color: $dark-gray; + background-color: global.$dark-gray; border: none; transition: 0.2s ease all; &:hover { - background-color: $medium-gray; + background-color: global.$medium-gray; } } @@ -148,7 +147,7 @@ $linkGap: 3px; text-align: center; border-radius: 50%; pointer-events: auto; - background-color: $dark-gray; + background-color: global.$dark-gray; border: none; transition: 0.2s ease all; display: flex; @@ -157,8 +156,8 @@ $linkGap: 3px; align-items: center; &:hover { - background-color: $black; - + background-color: global.$black; + .documentButtonBar-pinTypes { display: flex; } diff --git a/src/client/views/DocumentButtonBar.tsx b/src/client/views/DocumentButtonBar.tsx index a9f03a658..b17dbc93d 100644 --- a/src/client/views/DocumentButtonBar.tsx +++ b/src/client/views/DocumentButtonBar.tsx @@ -28,6 +28,7 @@ import { DocumentLinksButton } from './nodes/DocumentLinksButton'; import { DocumentView } from './nodes/DocumentView'; import { OpenWhere } from './nodes/OpenWhere'; import { DashFieldView } from './nodes/formattedText/DashFieldView'; +import { SmartDrawHandler } from './smartdraw/SmartDrawHandler'; @observer export class DocumentButtonBar extends ObservableReactComponent<{ views: () => (DocumentView | undefined)[]; stack?: unknown }> { @@ -319,7 +320,22 @@ export class DocumentButtonBar extends ObservableReactComponent<{ views: () => ( const targetDoc = this.view0?.Document; return !targetDoc ? null : ( <Tooltip title={<div className="dash-ai-editor-button">Edit with AI</div>}> - <div className="documentButtonBar-icon" style={{ color: 'white' }} onClick={undoable(() => this.view0?.toggleAIEditor(), 'toggle AI editor')}> + <div + className="documentButtonBar-icon" + style={{ color: 'white' }} + onPointerDown={e => + setupMoveUpEvents( + this, + e, + me => { + this.view0?.docViewPath().slice(-2)[0]?.ComponentView?.showSmartDraw?.(me.x, me.y, true); + SmartDrawHandler.Instance.startDragging(me); + return true; + }, + emptyFunction, + undoable(() => this.view0?.toggleAIEditor(), 'toggle AI editor') + ) + }> <FontAwesomeIcon className="documentdecorations-icon" icon="robot" /> </div> </Tooltip> diff --git a/src/client/views/DocumentDecorations.scss b/src/client/views/DocumentDecorations.scss index 346df10d5..a5afb1305 100644 --- a/src/client/views/DocumentDecorations.scss +++ b/src/client/views/DocumentDecorations.scss @@ -1,4 +1,4 @@ -@import 'global/globalCssVariables.module'; +@use 'global/globalCssVariables.module' as global; $linkGap: 3px; $headerHeight: 20px; @@ -195,14 +195,14 @@ $resizeHandler: 8px; .documentDecorations-titleSpan { width: 100%; border-radius: 8px; - background: $light-gray; + background: global.$contextMenu-zindex; display: inline-block; cursor: move; } } .documentDecorations-titleBackground { - background: $light-gray; + background: global.$light-gray; border-radius: 8px; width: 100%; height: 100%; @@ -314,7 +314,7 @@ $resizeHandler: 8px; .documentDecorations-bottomResizer, .documentDecorations-rightResizer { pointer-events: auto; - background: $medium-gray-dim; + background: global.$medium-gray-dim; //opacity: 0.2; &:hover { opacity: 1; @@ -344,7 +344,7 @@ $resizeHandler: 8px; border-radius: 100%; left: 7px; top: 7px; - background: $medium-gray; + background: global.$medium-gray; height: 10; width: 10; opacity: 0.5; @@ -378,7 +378,7 @@ $resizeHandler: 8px; transform: translate(0px, -25%); padding-bottom: 100%; border-radius: 100%; - border: solid $medium-gray 10px; + border: solid global.$medium-gray 10px; } .documentDecorations-topLeftResizer, @@ -497,13 +497,13 @@ $resizeHandler: 8px; } .linkButton-empty:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); cursor: pointer; } .linkButton-nonempty:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); cursor: pointer; } @@ -520,7 +520,7 @@ $resizeHandler: 8px; align-items: center; gap: 5px; //top: 4px; - background: $light-gray; + background: global.$light-gray; opacity: 0.2; pointer-events: all; transition: opacity 1s; @@ -542,8 +542,8 @@ $resizeHandler: 8px; text-align: center; border-radius: 50%; pointer-events: auto; - color: $dark-gray; - border: $dark-gray 1px solid; + color: global.$dark-gray; + border: global.$dark-gray 1px solid; } .linkButton-linker:hover { @@ -558,8 +558,8 @@ $resizeHandler: 8px; border-radius: 50%; opacity: 0.9; pointer-events: auto; - background-color: $dark-gray; - color: $white; + background-color: global.$dark-gray; + color: global.$white; text-transform: uppercase; letter-spacing: 2px; font-size: 75%; @@ -570,7 +570,7 @@ $resizeHandler: 8px; align-items: center; &:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); cursor: pointer; } @@ -600,13 +600,13 @@ $resizeHandler: 8px; border-radius: 50%; opacity: 0.9; font-size: 14; - background-color: $dark-gray; - color: $white; + background-color: global.$dark-gray; + color: global.$white; text-align: center; cursor: pointer; &:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); } } @@ -616,9 +616,9 @@ $resizeHandler: 8px; top: 25px; left: 0px; width: max-content; - font-family: $sans-serif; + font-family: global.$sans-serif; font-size: 12px; - background-color: $light-gray; + background-color: global.$light-gray; padding: 2px 12px; list-style: none; diff --git a/src/client/views/DocumentDecorations.tsx b/src/client/views/DocumentDecorations.tsx index 54ff3904d..54e050f9f 100644 --- a/src/client/views/DocumentDecorations.tsx +++ b/src/client/views/DocumentDecorations.tsx @@ -284,8 +284,8 @@ export class DocumentDecorations extends ObservableReactComponent<DocumentDecora embedding.y = -NumCast(embedding._height) / 2; CollectionDockingView.AddSplit(Docs.Create.FreeformDocument([embedding], { title: 'Tab for ' + embedding.title }), OpenWhereMod.right); } else if (e.altKey) { - // open same document in new tab - CollectionDockingView.ToggleSplit(selView.Document, OpenWhereMod.right); + // open same document in new tab or in custom editor + selView.ComponentView?.docEditorView?.() ?? CollectionDockingView.ToggleSplit(selView.Document, OpenWhereMod.right); } else { let openDoc = selView.Document; if (openDoc.layout_fieldKey === 'layout_icon') { @@ -566,7 +566,7 @@ export class DocumentDecorations extends ObservableReactComponent<DocumentDecora } doc._width = Math.max(NumCast(doc._width_min, 25), NumCast(doc._width) * scale.x); - doc._height = Math.max(NumCast(doc._height_min), NumCast(doc._height) * scale.y); + doc._height = Math.max(NumCast(doc._height_min, 10), NumCast(doc._height) * scale.y); const { deltaX, deltaY } = this.realignRefPt(doc, refCent, initWidth || 1, initHeight || 1); doc.x = NumCast(doc.x) + deltaX; doc.y = NumCast(doc.y) + deltaY; @@ -821,7 +821,7 @@ export class DocumentDecorations extends ObservableReactComponent<DocumentDecora {hideDeleteButton ? null : topBtn('close', 'times', undefined, () => this.onCloseClick(true), 'Close')} {hideResizers || hideDeleteButton ? null : topBtn('minimize', 'window-maximize', undefined, () => this.onCloseClick(undefined), 'Minimize')} {titleArea} - {hideOpenButton ? <div /> : topBtn('open', 'external-link-alt', this.onMaximizeDown, undefined, 'Open in Lightbox (ctrl: as alias, shift: in new collection)')} + {hideOpenButton ? <div /> : topBtn('open', 'external-link-alt', this.onMaximizeDown, undefined, 'Open in Lightbox (ctrl: as alias, shift: in new collection, opption: in editor view)')} </div> {hideResizers ? null : ( <> diff --git a/src/client/views/InkTranscription.tsx b/src/client/views/InkTranscription.tsx index c5a9d3ba4..e800e0ae3 100644 --- a/src/client/views/InkTranscription.tsx +++ b/src/client/views/InkTranscription.tsx @@ -4,7 +4,7 @@ import * as React from 'react'; import { imageUrlToBase64 } from '../../ClientUtils'; import { aggregateBounds } from '../../Utils'; import { Doc, DocListCast } from '../../fields/Doc'; -import { InkData, InkField, InkTool } from '../../fields/InkField'; +import { InkData, InkField, InkInkTool, InkTool } from '../../fields/InkField'; import { Cast, DateCast, ImageCast, NumCast } from '../../fields/Types'; import { ImageField, URLField } from '../../fields/URLField'; import { gptHandwriting } from '../apis/gpt/GPT'; @@ -297,7 +297,7 @@ export class InkTranscription extends React.Component { */ createInkGroup() { // TODO nda - if document being added to is a inkGrouping then we can just add to that group - if (Doc.ActiveTool === InkTool.Write) { + if (Doc.ActiveTool === InkTool.Ink && Doc.ActiveInk === InkInkTool.Write) { CollectionFreeFormView.collectionsWithUnprocessedInk.forEach(ffView => { // TODO: nda - will probably want to go through ffView unprocessed docs and then see if any of the inksToGroup docs are in it and only use those const selected = ffView.unprocessedDocs; diff --git a/src/client/views/LightboxView.tsx b/src/client/views/LightboxView.tsx index e3df01bbb..5698da785 100644 --- a/src/client/views/LightboxView.tsx +++ b/src/client/views/LightboxView.tsx @@ -18,7 +18,7 @@ import { GestureOverlay } from './GestureOverlay'; import './LightboxView.scss'; import { ObservableReactComponent } from './ObservableReactComponent'; import { OverlayView } from './OverlayView'; -import { DefaultStyleProvider, returnEmptyDocViewList, wavyBorderPath } from './StyleProvider'; +import { DefaultStyleProvider, returnEmptyDocViewList /* wavyBorderPath */ } from './StyleProvider'; import { DocumentView } from './nodes/DocumentView'; import { OpenWhere, OpenWhereMod } from './nodes/OpenWhere'; import { StickerPalette } from './smartdraw/StickerPalette'; @@ -93,7 +93,7 @@ export class LightboxView extends ObservableReactComponent<LightboxViewProps> { savedKeys.forEach(key => { lightDoc[key] = this._savedState[key]; }); - this._savedState = {}; + lightDoc !== doc && (this._savedState = {}); if (doc) { lightDoc !== doc && @@ -136,9 +136,7 @@ export class LightboxView extends ObservableReactComponent<LightboxViewProps> { return this.SetLightboxDoc( doc, undefined, - [...DocListCast(doc[Doc.LayoutFieldKey(doc)]), ...DocListCast(doc[Doc.LayoutFieldKey(doc) + '_annotations']).filter(anno => anno.annotationOn !== doc), ...this._future].sort( - (a, b) => NumCast(b._timecodeToShow) - NumCast(a._timecodeToShow) - ), + [...DocListCast(doc[Doc.LayoutFieldKey(doc) + '_annotations']).filter(anno => anno.annotationOn !== doc), ...this._future].sort((a, b) => NumCast(b._timecodeToShow) - NumCast(a._timecodeToShow)), layoutTemplate ); }; @@ -265,75 +263,80 @@ export class LightboxView extends ObservableReactComponent<LightboxViewProps> { /> </div> ); - return !this._doc ? ( - <OverlayView /> - ) : ( - <div - className="lightboxView-frame" - style={{ background: SnappingManager.userBackgroundColor }} - onPointerDown={e => { - downx = e.clientX; - downy = e.clientY; - }} - onClick={e => ClientUtils.isClick(e.clientX, e.clientY, downx, downy, Date.now()) && this.SetLightboxDoc(undefined)}> - <div - className="lightboxView-contents" - style={{ - left: this.leftBorder, - top: this.topBorder, - width: this.lightboxWidth(), - height: this.lightboxHeight(), - clipPath: `path('${Doc.UserDoc().renderStyle === 'comic' ? wavyBorderPath(this.lightboxWidth(), this.lightboxHeight()) : undefined}')`, - background: SnappingManager.userBackgroundColor, - }}> - <GestureOverlay isActive> - <DocumentView - key={this._doc[Id]} // this makes a new DocumentView when the document changes which makes link following work, otherwise no DocView is registered for the new Doc - ref={action((r: DocumentView | null) => { - this._docView = r !== null ? r : undefined; - })} - Document={this._doc} - PanelWidth={this.lightboxWidth} - PanelHeight={this.lightboxHeight} - LayoutTemplate={this.lightboxDocTemplate} - isDocumentActive={returnTrue} // without this being true, sidebar annotations need to be activated before text can be selected. - isContentActive={returnTrue} - styleProvider={DefaultStyleProvider} - ScreenToLocalTransform={this.lightboxScreenToLocal} - renderDepth={0} - suppressSetHeight={!!this._doc._layout_fitWidth} - containerViewPath={returnEmptyDocViewList} - childFilters={returnEmptyFilter} - childFiltersByRanges={returnEmptyFilter} - searchFilterDocs={returnEmptyDoclist} - addDocument={undefined} - removeDocument={undefined} - whenChildContentsActiveChanged={emptyFunction} - addDocTab={this.AddDocTab} - pinToPres={DocumentView.PinDoc} - focus={emptyFunction} - /> - </GestureOverlay> + return ( + <> + <div style={{ display: this._doc ? 'none' : undefined }}> + <OverlayView /> </div> + {!this._doc ? null : ( + <div + className="lightboxView-frame" + style={{ background: SnappingManager.userBackgroundColor }} + onPointerDown={e => { + downx = e.clientX; + downy = e.clientY; + }} + onClick={e => ClientUtils.isClick(e.clientX, e.clientY, downx, downy, Date.now()) && this.SetLightboxDoc(undefined)}> + <div + className="lightboxView-contents" + style={{ + left: this.leftBorder, + top: this.topBorder, + width: this.lightboxWidth(), + height: this.lightboxHeight(), + // clipPath: `path('${Doc.UserDoc().renderStyle === 'comic' ? wavyBorderPath(this.lightboxWidth(), this.lightboxHeight()) : undefined}')`, + background: SnappingManager.userBackgroundColor, + }}> + <GestureOverlay isActive> + <DocumentView + key={this._doc[Id]} // this makes a new DocumentView when the document changes which makes link following work, otherwise no DocView is registered for the new Doc + ref={action((r: DocumentView | null) => { + this._docView = r !== null ? r : undefined; + })} + Document={this._doc} + PanelWidth={this.lightboxWidth} + PanelHeight={this.lightboxHeight} + LayoutTemplate={this.lightboxDocTemplate} + isDocumentActive={returnTrue} // without this being true, sidebar annotations need to be activated before text can be selected. + isContentActive={returnTrue} + styleProvider={DefaultStyleProvider} + ScreenToLocalTransform={this.lightboxScreenToLocal} + renderDepth={0} + suppressSetHeight={!!this._doc._layout_fitWidth} + containerViewPath={returnEmptyDocViewList} + childFilters={returnEmptyFilter} + childFiltersByRanges={returnEmptyFilter} + searchFilterDocs={returnEmptyDoclist} + addDocument={undefined} + removeDocument={undefined} + whenChildContentsActiveChanged={emptyFunction} + addDocTab={this.AddDocTab} + pinToPres={DocumentView.PinDoc} + focus={emptyFunction} + /> + </GestureOverlay> + </div> - {this._showPalette && <StickerPalette ref={r => (this._annoPaletteView = r)} Document={DocCast(Doc.UserDoc().myLightboxDrawings)} />} - {this.renderNavBtn(0, undefined, this._props.PanelHeight / 2 - 12.5, 'chevron-left', this._doc && this._history.length ? true : false, this.previous)} - {this.renderNavBtn( - this._props.PanelWidth - Math.min(this._props.PanelWidth / 4, this._props.maxBorder[0]), - undefined, - this._props.PanelHeight / 2 - 12.5, - 'chevron-right', - this._doc && this._future.length ? true : false, - this.next, - this.future().length.toString() + {this._showPalette && <StickerPalette ref={r => (this._annoPaletteView = r)} Document={DocCast(Doc.UserDoc().myLightboxDrawings)} />} + {this.renderNavBtn(0, undefined, this._props.PanelHeight / 2 - 12.5, 'chevron-left', this._doc && this._history.length ? true : false, this.previous)} + {this.renderNavBtn( + this._props.PanelWidth - Math.min(this._props.PanelWidth / 4, this._props.maxBorder[0]), + undefined, + this._props.PanelHeight / 2 - 12.5, + 'chevron-right', + this._doc && this._future.length ? true : false, + this.next, + this.future().length.toString() + )} + <LightboxTourBtn lightboxDoc={this.lightboxDoc} navBtn={this.renderNavBtn} future={this.future} stepInto={this.stepInto} /> + {toggleBtn('lightboxView-navBtn', 'toggle reading view', BoolCast(this._doc?._layout_fitWidth), 'book-open', 'book', this.toggleFitWidth)} + {toggleBtn('lightboxView-tabBtn', 'open document in a tab', false, 'file-export', '', this.downloadDoc)} + {toggleBtn('lightboxView-paletteBtn', 'toggle sticker palette', this._showPalette === true, 'palette', '', this.togglePalette)} + {toggleBtn('lightboxView-penBtn', 'toggle pen annotation', Doc.ActiveTool === InkTool.Ink, 'pen', '', this.togglePen)} + {toggleBtn('lightboxView-exploreBtn', 'toggle navigate only mode', SnappingManager.ExploreMode, 'globe-americas', '', this.toggleExplore)} + </div> )} - <LightboxTourBtn lightboxDoc={this.lightboxDoc} navBtn={this.renderNavBtn} future={this.future} stepInto={this.stepInto} /> - {toggleBtn('lightboxView-navBtn', 'toggle reading view', BoolCast(this._doc?._layout_fitWidth), 'book-open', 'book', this.toggleFitWidth)} - {toggleBtn('lightboxView-tabBtn', 'open document in a tab', false, 'file-export', '', this.downloadDoc)} - {toggleBtn('lightboxView-paletteBtn', 'toggle sticker palette', this._showPalette === true, 'palette', '', this.togglePalette)} - {toggleBtn('lightboxView-penBtn', 'toggle pen annotation', Doc.ActiveTool === InkTool.Ink, 'pen', '', this.togglePen)} - {toggleBtn('lightboxView-exploreBtn', 'toggle navigate only mode', SnappingManager.ExploreMode, 'globe-americas', '', this.toggleExplore)} - </div> + </> ); } } diff --git a/src/client/views/Main.scss b/src/client/views/Main.scss index 02916e48e..bea1de435 100644 --- a/src/client/views/Main.scss +++ b/src/client/views/Main.scss @@ -1,5 +1,5 @@ -@import 'global/globalCssVariables.module'; -@import 'nodeModuleOverrides'; +@use 'global/globalCssVariables.module' as global; +// bcz: fix @import 'nodeModuleOverrides'; :root { --flyoutHandleWidth: 28px; @@ -10,8 +10,8 @@ body { width: 100%; height: 100%; overflow: hidden; - font-family: $sans-serif; - font-size: $body-text; + font-family: global.$sans-serif; + font-size: global.$body-text; margin: 0; position: absolute; top: 0; @@ -54,7 +54,7 @@ button { background: black; outline: none; border: 0px; - color: $white; + color: global.$white; text-transform: uppercase; letter-spacing: 2px; font-size: 75%; @@ -63,7 +63,7 @@ button { } button:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); cursor: pointer; } diff --git a/src/client/views/Main.tsx b/src/client/views/Main.tsx index 8087a0e6d..e5347e692 100644 --- a/src/client/views/Main.tsx +++ b/src/client/views/Main.tsx @@ -91,7 +91,6 @@ FieldLoader.ServerLoadStatus = { requested: 0, retrieved: 0, message: 'cache' }; document.getElementById('root')!.addEventListener('wheel', event => event.ctrlKey && event.preventDefault(), true); const startload = (document as unknown as { startLoad: number }).startLoad; // see index.html in deploy/ const loading = Date.now() - (startload ? Number(startload) : Date.now() - 3000); - console.log('Loading Time = ' + loading); const d = new Date(); d.setTime(d.getTime() + 100 * 24 * 60 * 60 * 1000); const expires = 'expires=' + d.toUTCString(); diff --git a/src/client/views/MainView.scss b/src/client/views/MainView.scss index e204759ab..db949285b 100644 --- a/src/client/views/MainView.scss +++ b/src/client/views/MainView.scss @@ -1,5 +1,5 @@ -@import 'global/globalCssVariables.module.scss'; -@import 'nodeModuleOverrides'; +@use 'global/globalCssVariables.module.scss' as global; +@use 'nodeModuleOverrides' as overrides; html { overscroll-behavior-x: none; } @@ -68,10 +68,10 @@ body { } .mainView-container { - color: $dark-gray; + color: global.$dark-gray; .lm_goldenlayout { - background: $medium-gray; + background: global.$medium-gray; } } @@ -93,7 +93,7 @@ body { .mainView-propertiesDragger-minified, .mainView-propertiesDragger { //background-color: rgb(140, 139, 139); - background-color: $light-gray; + background-color: global.$light-gray; height: 55px; width: 17px; position: absolute; @@ -133,10 +133,10 @@ body { flex-direction: column; position: relative; height: 100%; - background: $medium-gray; + background: global.$medium-gray; .documentView-node-topmost { - background: $light-gray; + background: global.$light-gray; } } @@ -153,12 +153,12 @@ body { } .mainView-libraryHandle { - background-color: $light-gray; + background-color: global.$light-gray; } .mainView-leftMenuPanel { min-width: var(--menuPanelWidth); - border-right: $standard-border; + border-right: global.$standard-border; .collectionStackingView { scrollbar-width: none; diff --git a/src/client/views/MainView.tsx b/src/client/views/MainView.tsx index d748b70ae..ef8d0c197 100644 --- a/src/client/views/MainView.tsx +++ b/src/client/views/MainView.tsx @@ -59,7 +59,7 @@ import { ImageLabelHandler } from './collections/collectionFreeForm/ImageLabelHa import { MarqueeOptionsMenu } from './collections/collectionFreeForm/MarqueeOptionsMenu'; import { CollectionLinearView } from './collections/collectionLinear'; import { LinkMenu } from './linking/LinkMenu'; -import { DocCreatorMenu } from './nodes/DataVizBox/DocCreatorMenu'; +import { DocCreatorMenu } from './nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu'; import { SchemaCSVPopUp } from './nodes/DataVizBox/SchemaCSVPopUp'; import { DocButtonState } from './nodes/DocumentLinksButton'; import { DocumentView, DocumentViewInternal } from './nodes/DocumentView'; @@ -75,7 +75,6 @@ import { RichTextMenu } from './nodes/formattedText/RichTextMenu'; import ImageEditorBox from './nodes/imageEditor/ImageEditor'; import { PresBox } from './nodes/trails'; import { AnchorMenu } from './pdf/AnchorMenu'; -import { GPTPopup } from './pdf/GPTPopup/GPTPopup'; import { SmartDrawHandler } from './smartdraw/SmartDrawHandler'; import { TopBar } from './topbar/TopBar'; @@ -98,7 +97,7 @@ export class MainView extends ObservableReactComponent<object> { @observable private _sidebarContent: Doc = Doc.MyLeftSidebarPanel; @observable private _leftMenuFlyoutWidth: number = 0; @computed get _hideUI() { - return this.mainDoc && this.mainDoc._type_collection !== CollectionViewType.Docking; + return SnappingManager.HideUI || (this.mainDoc && this.mainDoc._type_collection !== CollectionViewType.Docking); } @computed private get dashboardTabHeight() { @@ -710,7 +709,7 @@ export class MainView extends ObservableReactComponent<object> { childFiltersByRanges={returnEmptyFilter} searchFilterDocs={returnEmptyDoclist} suppressSetHeight - renderDepth={this._hideUI ? 0 : -1} + renderDepth={-1} /> </> ); @@ -1141,7 +1140,7 @@ export class MainView extends ObservableReactComponent<object> { <PreviewCursor /> <TaskCompletionBox /> <ContextMenu /> - <DocCreatorMenu /> + <DocCreatorMenu addDocTab={DocumentViewInternal.addDocTabFunc} /> <ImageLabelHandler /> <SmartDrawHandler /> <AnchorMenu /> @@ -1154,7 +1153,6 @@ export class MainView extends ObservableReactComponent<object> { <InkTranscription /> {this.snapLines} <LightboxView key="lightbox" PanelWidth={this._windowWidth} addSplit={CollectionDockingView.AddSplit} PanelHeight={this._windowHeight} maxBorder={this.lightboxMaxBorder} /> - <GPTPopup key="gptpopup" /> <SchemaCSVPopUp key="schemacsvpopup" /> <ImageEditorBox imageEditorOpen={ImageEditor.Open} imageEditorSource={ImageEditor.Source} imageRootDoc={ImageEditor.RootDoc} addDoc={ImageEditor.AddDoc} /> </div> @@ -1167,6 +1165,10 @@ ScriptingGlobals.add(function selectMainMenu(doc: Doc) { MainView.Instance.selectMenu(doc); }); // eslint-disable-next-line prefer-arrow-callback +ScriptingGlobals.add(function hideUI() { + SnappingManager.SetHideUI(!SnappingManager.HideUI); +}); +// eslint-disable-next-line prefer-arrow-callback ScriptingGlobals.add(function createNewPresentation() { return MainView.Instance.createNewPresentation(); }, 'creates a new presentation when called'); diff --git a/src/client/views/MainViewModal.tsx b/src/client/views/MainViewModal.tsx index 178eefe2c..b05292c47 100644 --- a/src/client/views/MainViewModal.tsx +++ b/src/client/views/MainViewModal.tsx @@ -1,4 +1,3 @@ -/* eslint-disable react/require-default-props */ import { isDark } from '@dash/components'; import { observer } from 'mobx-react'; import * as React from 'react'; diff --git a/src/client/views/OverlayView.scss b/src/client/views/OverlayView.scss index 33a297fd4..2e8621b5b 100644 --- a/src/client/views/OverlayView.scss +++ b/src/client/views/OverlayView.scss @@ -4,7 +4,7 @@ top: 0; width: 100vw; height: 100vh; - z-index: 1001; // shouold be greater than LightboxView's z-index so that link lines and the presentation mini player appear + z-index: 2002; // shouold be greater than LightboxView's z-index so that link lines and the presentation mini player appear /* background-color: pink; */ user-select: none; } @@ -17,6 +17,7 @@ top: 0; left: 0; pointer-events: all; + box-shadow: black 5px 5px 5px; } .overlayWindow-outerDiv, @@ -26,27 +27,30 @@ } .overlayWindow-titleBar { - flex: 0 1 30px; + flex: 0 1 20px; background: darkslategray; color: whitesmoke; text-align: center; cursor: move; + z-index: 1; } .overlayWindow-content { flex: 1 1 auto; display: flex; flex-direction: column; + z-index: 0; } .overlayWindow-closeButton { float: right; - height: 30px; - width: 30px; + height: 20px; + width: 20px; + padding: 0; + background-color: inherit; } .overlayWindow-resizeDragger { - background-color: rgb(0, 0, 0); position: absolute; right: 0px; bottom: 0px; diff --git a/src/client/views/OverlayView.tsx b/src/client/views/OverlayView.tsx index 5e9677b45..6686a162e 100644 --- a/src/client/views/OverlayView.tsx +++ b/src/client/views/OverlayView.tsx @@ -18,6 +18,8 @@ import { ObservableReactComponent } from './ObservableReactComponent'; import './OverlayView.scss'; import { DefaultStyleProvider, returnEmptyDocViewList } from './StyleProvider'; import { DocumentView, DocumentViewInternal } from './nodes/DocumentView'; +import { SnappingManager } from '../util/SnappingManager'; +import { GPTPopup } from './pdf/GPTPopup/GPTPopup'; export type OverlayDisposer = () => void; @@ -27,12 +29,17 @@ export type OverlayElementOptions = { width?: number; height?: number; title?: string; + onClick?: (e: React.MouseEvent) => void; + isHidden?: () => boolean; + backgroundColor?: string; }; export interface OverlayWindowProps { children: JSX.Element; overlayOptions: OverlayElementOptions; - onClick: () => void; + onClick: (e: React.MouseEvent) => void; + isHidden?: () => boolean; + backgroundColor?: string; } @observer @@ -93,15 +100,17 @@ export class OverlayWindow extends ObservableReactComponent<OverlayWindowProps> render() { return ( - <div className="overlayWindow-outerDiv" style={{ transform: `translate(${this.x}px, ${this.y}px)`, width: this.width, height: this.height }}> - <div className="overlayWindow-titleBar" onPointerDown={this.onPointerDown}> + <div + className="overlayWindow-outerDiv" + style={{ display: this.props.isHidden?.() ? 'none' : undefined, backgroundColor: this._props.backgroundColor, transform: `translate(${this.x}px, ${this.y}px)`, width: this.width, height: this.height }}> + <div className="overlayWindow-titleBar" onPointerDown={this.onPointerDown} style={{ backgroundColor: SnappingManager.userVariantColor, color: SnappingManager.userColor }}> {this._props.overlayOptions.title || 'Untitled'} <button type="button" onClick={this._props.onClick} className="overlayWindow-closeButton"> X </button> </div> <div className="overlayWindow-content">{this.props.children}</div> - <div className="overlayWindow-resizeDragger" onPointerDown={this.onResizerPointerDown} /> + <div className="overlayWindow-resizeDragger" style={{ backgroundColor: SnappingManager.userVariantColor }} onPointerDown={this.onResizerPointerDown} /> </div> ); } @@ -118,6 +127,16 @@ export class OverlayView extends ObservableReactComponent<object> { makeObservable(this); if (!OverlayView.Instance) { OverlayView.Instance = this; + this.addWindow(<GPTPopup />, { + x: 400, + y: 200, + width: 500, + height: 400, + title: 'GPT', // + backgroundColor: 'transparent', + isHidden: () => !SnappingManager.ChatVisible, + onClick: () => SnappingManager.SetChatVisible(false), + }); new ResizeObserver( action(entries => { Array.from(entries).forEach(entry => { @@ -166,7 +185,7 @@ export class OverlayView extends ObservableReactComponent<object> { if (index !== -1) this._elements.splice(index, 1); }); const wincontents = ( - <OverlayWindow onClick={() => remove(wincontents)} key={Utils.GenerateGuid()} overlayOptions={options}> + <OverlayWindow isHidden={options.isHidden} backgroundColor={options.backgroundColor} onClick={options.onClick ?? (() => remove(wincontents))} key={Utils.GenerateGuid()} overlayOptions={options}> {contents} </OverlayWindow> ); diff --git a/src/client/views/PreviewCursor.tsx b/src/client/views/PreviewCursor.tsx index 7e597879d..eb4e75f74 100644 --- a/src/client/views/PreviewCursor.tsx +++ b/src/client/views/PreviewCursor.tsx @@ -46,8 +46,6 @@ export class PreviewCursor extends ObservableReactComponent<object> { this.Visible = false; }); - // tests for URL and makes web document - const re = /^https?:\/\//g; const plain = e.clipboardData.getData('text/plain'); if (plain && newPoint) { // tests for youtube and makes video document @@ -62,7 +60,7 @@ export class PreviewCursor extends ObservableReactComponent<object> { y: newPoint[1], }; this._slowLoadDocuments?.(plain.split('v=')[1].split('&')[0], options, generatedDocuments, '', undefined, this._addDocument ?? returnFalse).then(batch.end); - } else if (re.test(plain)) { + } else if ((/^https?:\/\//g).test(plain)) { // tests for URL and makes web document const url = plain; if (!url.startsWith(window.location.href)) { undoable( diff --git a/src/client/views/PropertiesButtons.scss b/src/client/views/PropertiesButtons.scss index b8c73b6d3..6c2cda346 100644 --- a/src/client/views/PropertiesButtons.scss +++ b/src/client/views/PropertiesButtons.scss @@ -1,4 +1,4 @@ -@import 'global/globalCssVariables.module.scss'; +@use 'global/globalCssVariables.module.scss' as global; $linkGap: 3px; @@ -7,13 +7,13 @@ $linkGap: 3px; } .propertiesButtons-linkButton-empty:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); cursor: pointer; } .propertiesButtons-linkButton-nonempty:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); cursor: pointer; } @@ -46,19 +46,19 @@ $linkGap: 3px; // margin-left: 4px; &:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); cursor: pointer; } } .propertiesButtons-linkButton-empty.toggle-on { - background-color: $medium-blue; - color: $white; + background-color: global.$medium-blue; + color: global.$white; width: 100%; } .propertiesButtons-linkButton-empty.toggle-hover { - background-color: $light-blue; - color: $black; + background-color: global.$light-blue; + color: global.$black; width: 100%; } .propertiesButtons-linkButton-empty.toggle-off { @@ -88,7 +88,7 @@ $linkGap: 3px; cursor: pointer; text-align: center; margin-top: 5px; - border: 0.5px solid $medium-gray; + border: 0.5px solid global.$medium-gray; background-color: rgb(230, 230, 230); border-radius: 5px; padding: 4px; @@ -111,7 +111,7 @@ $linkGap: 3px; .list-item { cursor: pointer; - color: $black; + color: global.$black; width: 100%; height: 25px; font-weight: 400; diff --git a/src/client/views/PropertiesSection.scss b/src/client/views/PropertiesSection.scss index d32da1bf1..f7138dd50 100644 --- a/src/client/views/PropertiesSection.scss +++ b/src/client/views/PropertiesSection.scss @@ -1,5 +1,3 @@ -@import './global/globalCssVariables.module.scss'; - .propertiesView-section { .propertiesView-content { padding: 10px; diff --git a/src/client/views/PropertiesView.scss b/src/client/views/PropertiesView.scss index 7866e67e7..280de4893 100644 --- a/src/client/views/PropertiesView.scss +++ b/src/client/views/PropertiesView.scss @@ -1,4 +1,4 @@ -@import './global/globalCssVariables.module.scss'; +@use './global/globalCssVariables.module.scss' as global; .propertiesView-presentationTrails-title { display: flex; @@ -28,7 +28,7 @@ font-family: 'Roboto'; font-size: 12px; cursor: auto; - border-left: $standard-border; + border-left: global.$standard-border; .slider-text { font-size: 8px; @@ -567,7 +567,7 @@ height: fit-content; &:hover { - border: 0.75px solid $medium-blue; + border: 0.75px solid global.$medium-blue; } } diff --git a/src/client/views/PropertiesView.tsx b/src/client/views/PropertiesView.tsx index bed96f600..11adf7435 100644 --- a/src/client/views/PropertiesView.tsx +++ b/src/client/views/PropertiesView.tsx @@ -152,9 +152,16 @@ export class PropertiesView extends ObservableReactComponent<PropertiesViewProps return this.selectedDoc?.isGroup; } @computed get isStack() { - return [CollectionViewType.Masonry, CollectionViewType.Multicolumn, CollectionViewType.Multirow, CollectionViewType.Stacking, CollectionViewType.NoteTaking, CollectionViewType.Carousel].includes( - this.selectedDoc?.type_collection as CollectionViewType - ); + return [ + CollectionViewType.Masonry, + CollectionViewType.Multicolumn, + CollectionViewType.Multirow, + CollectionViewType.Stacking, + CollectionViewType.NoteTaking, + CollectionViewType.Card, + CollectionViewType.Carousel, + CollectionViewType.Grid, + ].includes(this.selectedDoc?.type_collection as CollectionViewType); } rtfWidth = () => (!this.selectedLayoutDoc ? 0 : Math.min(NumCast(this.selectedLayoutDoc?._width), this._props.width - 20)); diff --git a/src/client/views/ScriptBox.tsx b/src/client/views/ScriptBox.tsx index 9c36e6d26..d05b0a6b6 100644 --- a/src/client/views/ScriptBox.tsx +++ b/src/client/views/ScriptBox.tsx @@ -1,4 +1,3 @@ -/* eslint-disable react/require-default-props */ import { action, makeObservable, observable } from 'mobx'; import { observer } from 'mobx-react'; import * as React from 'react'; diff --git a/src/client/views/StyleProp.ts b/src/client/views/StyleProp.ts index 56367e70b..1ef7a9e1f 100644 --- a/src/client/views/StyleProp.ts +++ b/src/client/views/StyleProp.ts @@ -5,6 +5,7 @@ export enum StyleProp { Opacity = 'opacity', // opacity of the document view BoxShadow = 'boxShadow', // box shadow - used for making collections standout and for showing clusters in free form views BorderRounding = 'borderRounding', // border radius of the document view + Border = 'border', // border of document view Color = 'color', // foreground color of Document view items BackgroundColor = 'backgroundColor', // background color of a document view FillColor = 'fillColor', // fill color of an ink stroke or shape diff --git a/src/client/views/StyleProvider.tsx b/src/client/views/StyleProvider.tsx index bebc9a341..b04b1ae65 100644 --- a/src/client/views/StyleProvider.tsx +++ b/src/client/views/StyleProvider.tsx @@ -206,33 +206,40 @@ export function DefaultStyleProvider(doc: Opt<Doc>, props: Opt<FieldViewProps & const rounding = StrCast(doc?.[fieldKey + 'borderRounding'], StrCast(doc?.layout_borderRounding, doc?._type_collection === CollectionViewType.Pile ? '50%' : '')); return (doc?.[StrCast(doc?.layout_fieldKey)] instanceof Doc || doc?.isTemplateDoc) ? StrCast(doc._layout_borderRounding,rounding) : rounding; } + case StyleProp.Border: { + const bcolor = StrCast(doc?.borderColor, StrCast(doc?.[fieldKey + 'borderColor'], StrCast(doc?.layout_borderColor))); + return bcolor + " " + + StrCast(doc?.borderStyle, StrCast(doc?.[fieldKey + 'borderStyle'], StrCast(doc?.layout_borderStyle, "solid"))) + " " + + (StrCast(doc?.borderWidth || doc?.[fieldKey + 'borderWidth'] || doc?.layout_borderWidth) || + (NumCast(doc?.borderWidth, NumCast(doc?.[fieldKey + 'borderWidth'], NumCast(doc?.layout_borderWidth, bcolor ?1:0)))+"px")) + } // Doc.IsComicStyle(doc) && // renderDepth && // !doc?.layout_isSvg && //case StyleProp. - case StyleProp.BorderPath: { - const docWidth = Number(doc?._width); - const borderWidth = Number(StrCast(doc?.borderWidth)); - //console.log(borderWidth); - const ratio = borderWidth / docWidth; - const borderRadius = Number(StrCast(layoutDoc?._layout_borderRounding).replace('px', '')); - const radiusRatio = borderRadius / docWidth; - const radius = radiusRatio * ((2 * borderWidth) + docWidth); + // case StyleProp.BorderPath: { + // const docWidth = Number(doc?._width); + // const borderWidth = Number(StrCast(doc?.borderWidth)); + // //console.log(borderWidth); + // const ratio = borderWidth / docWidth; + // const borderRadius = Number(StrCast(layoutDoc?._layout_borderRounding).replace('px', '')); + // const radiusRatio = borderRadius / docWidth; + // const radius = radiusRatio * ((2 * borderWidth) + docWidth); - const borderPath = doc && border(doc, NumCast(doc._width), NumCast(doc._height), radius, -ratio/2); - return !borderPath - ? null - : { - clipPath: `path('${borderPath}')`, - jsx: ( - <div key="border2" className="documentView-customBorder" style={{ pointerEvents: 'none' }}> - <svg style={{ overflow: 'visible', height: '100%' }} viewBox={`0 0 ${PanelWidth?.()} ${PanelHeight?.()}`}> - <path d={borderPath} style={{ stroke: StrCast(doc?.borderColor), fill: 'transparent', strokeWidth: `${StrCast(doc?.borderWidth)}px` }} /> - </svg> - </div> - ), - }; - } + // const borderPath = doc && border(doc, NumCast(doc._width), NumCast(doc._height), radius, -ratio/2); + // return !borderPath + // ? null + // : { + // clipPath: `path('${borderPath}')`, + // jsx: ( + // <div key="border2" className="documentView-customBorder" style={{ pointerEvents: 'none' }}> + // <svg style={{ overflow: 'visible', height: '100%' }} viewBox={`0 0 ${PanelWidth?.()} ${PanelHeight?.()}`}> + // <path d={borderPath} style={{ stroke: StrCast(doc?.borderColor), fill: 'transparent', strokeWidth: `${StrCast(doc?.borderWidth)}px` }} /> + // </svg> + // </div> + // ), + // }; + // } case StyleProp.HeaderMargin: return ([CollectionViewType.Stacking, CollectionViewType.NoteTaking, CollectionViewType.Masonry, CollectionViewType.Tree].includes(doc?._type_collection as CollectionViewType) || (doc?.type === DocumentType.RTF && !layoutShowTitle()?.includes('noMargin')) || diff --git a/src/client/views/StyleProviderQuiz.tsx b/src/client/views/StyleProviderQuiz.tsx index b3fb8c930..db9ab831a 100644 --- a/src/client/views/StyleProviderQuiz.tsx +++ b/src/client/views/StyleProviderQuiz.tsx @@ -125,7 +125,7 @@ export namespace styleProviderQuiz { try { const hrefBase64 = await createCanvas(img); const response = await gptImageLabel(hrefBase64, 'Make flashcards out of this image with each question and answer labeled as "question" and "answer". Do not label each flashcard and do not include asterisks: '); - AnchorMenu.Instance.transferToFlashcard(response, NumCast(img.layoutDoc['x']), NumCast(img.layoutDoc['y'])); + AnchorMenu.Instance.transferToFlashcard(response, NumCast(img.layoutDoc.x), NumCast(img.layoutDoc.y)); } catch (error) { console.log('Error', error); } @@ -265,7 +265,7 @@ export namespace styleProviderQuiz { '. ' + rubricText + '. One sentence and evaluate based on meaning, not wording. Provide a hex color at the beginning with a period after it on a scale of green (minor details missed) to red (big error) for how correct the answer is. Example: "#FFFFFF. Pasta is delicious."'; - const response = await gptAPICall(queryText, GPTCallType.QUIZ); + const response = await gptAPICall(queryText, GPTCallType.QUIZDOC); const hexSent = extractHexAndSentences(response); doc.quiz = hexSent.sentences?.replace(/UserAnswer/g, "user's answer").replace(/Rubric/g, 'rubric'); doc.backgroundColor = '#' + hexSent.hexNumber; diff --git a/src/client/views/TagsView.tsx b/src/client/views/TagsView.tsx index b70e21918..93d6fb684 100644 --- a/src/client/views/TagsView.tsx +++ b/src/client/views/TagsView.tsx @@ -398,8 +398,7 @@ export class TagsView extends ObservableReactComponent<TagViewProps> { e.stopPropagation(); }} type="text" - placeholder="Input tags for document..." - aria-label="tagsView-input" + placeholder="Enter #tags or @metadata" className="tagsView-input" style={{ width: '100%', borderRadius: '5px' }} /> diff --git a/src/client/views/TemplateMenu.scss b/src/client/views/TemplateMenu.scss index 36a9ce6d0..8879fc20d 100644 --- a/src/client/views/TemplateMenu.scss +++ b/src/client/views/TemplateMenu.scss @@ -1,4 +1,4 @@ -@import 'global/globalCssVariables.module.scss'; +@use 'global/globalCssVariables.module.scss' as global; .templating-menu { position: absolute; pointer-events: auto; @@ -24,15 +24,15 @@ cursor: pointer; &:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); } } .template-list { - font-family: $sans-serif; + font-family: global.$sans-serif; font-size: 12px; - background-color: $light-gray; + background-color: global.$light-gray; padding: 2px 12px; list-style: none; position: relative; diff --git a/src/client/views/ViewBoxInterface.ts b/src/client/views/ViewBoxInterface.ts index a66a20cf6..0ddac8914 100644 --- a/src/client/views/ViewBoxInterface.ts +++ b/src/client/views/ViewBoxInterface.ts @@ -22,6 +22,9 @@ export abstract class ViewBoxInterface<P> extends ObservableReactComponent<React return ''; // } promoteCollection?: () => void; // moves contents of collection to parent + hasChildDocs?: () => Doc[]; + docEditorView?: () => void; + showSmartDraw?: (x: number, y: number, regenerate?: boolean) => void; updateIcon?: (usePanelDimensions?: boolean) => Promise<void>; // updates the icon representation of the document getAnchor?: (addAsAnnotation: boolean, pinData?: PinProps) => Doc; // returns an Anchor Doc that represents the current state of the doc's componentview (e.g., the current playhead location of a an audio/video box) restoreView?: (viewSpec: Doc) => boolean; // DEPRECATED: do not use, it will go away. see PresBox.restoreTargetDocView diff --git a/src/client/views/_nodeModuleOverrides.scss b/src/client/views/_nodeModuleOverrides.scss index db69d6e44..d06380271 100644 --- a/src/client/views/_nodeModuleOverrides.scss +++ b/src/client/views/_nodeModuleOverrides.scss @@ -1,9 +1,9 @@ -@import './global/globalCssVariables.module.scss'; +@use './global/globalCssVariables.module.scss' as global; // this file is for overriding all the css from installed node modules // goldenlayout stuff div .lm_header { - background: $dark-gray; + background: global.$dark-gray; overflow: hidden; height: 27px !important; } @@ -30,13 +30,13 @@ div .lm_header { /* Handle */ .lm_header:hover::-webkit-scrollbar-thumb { -webkit-appearance: none; - background: $dark-gray; + background: global.$dark-gray; } /* Handle on hover */ .lm_header:hover::-webkit-scrollbar-thumb:hover { -webkit-appearance: none; - background: $dark-gray; + background: global.$dark-gray; } .lm_tabs { @@ -44,7 +44,7 @@ div .lm_header { position: absolute; width: calc(100% - 60px); overflow: scroll; - background: transparent; //$dark-gray; + background: transparent; //global.$dark-gray; border-radius: 0px; } @@ -54,7 +54,7 @@ div .lm_header { // min-height: 1.35em; // padding-bottom: 0px; // border-radius: 5px; - font-family: $sans-serif !important; + font-family: global.$sans-serif !important; } // @TODO the ril__navgiation buttons in the img gallery are a lil messed up but I can't figure out diff --git a/src/client/views/animationtimeline/Region.scss b/src/client/views/animationtimeline/Region.scss index b390ae34e..df82febea 100644 --- a/src/client/views/animationtimeline/Region.scss +++ b/src/client/views/animationtimeline/Region.scss @@ -1,4 +1,4 @@ -@import './../global/globalCssVariables.module.scss'; +@use './../global/globalCssVariables.module.scss' as global; $timelineColor: #9acedf; $timelineDark: #77a1aa; @@ -14,11 +14,11 @@ $timelineDark: #77a1aa; height: 200px; top: 50%; position: relative; - background-color: $white; + background-color: global.$white; .menutable { tr:nth-child(odd) { - background-color: $light-gray; + background-color: global.$light-gray; } } } @@ -70,7 +70,7 @@ $timelineDark: #77a1aa; height: 100%; position: absolute; pointer-events: none; - background: linear-gradient(to left, $timelineColor 10%, $white); + background: linear-gradient(to left, $timelineColor 10%, global.$white); } .fadeRight { @@ -78,7 +78,7 @@ $timelineDark: #77a1aa; height: 100%; position: absolute; pointer-events: none; - background: linear-gradient(to right, $timelineColor 10%, $white); + background: linear-gradient(to right, $timelineColor 10%, global.$white); } .divider { diff --git a/src/client/views/animationtimeline/Timeline.scss b/src/client/views/animationtimeline/Timeline.scss index 35ba0fa7f..e1d3b190c 100644 --- a/src/client/views/animationtimeline/Timeline.scss +++ b/src/client/views/animationtimeline/Timeline.scss @@ -1,4 +1,4 @@ -@import './../global/globalCssVariables.module.scss'; +@use './../global/globalCssVariables.module.scss' as global; $timelineColor: #9acedf; $timelineDark: #77a1aa; @@ -159,7 +159,7 @@ $timelineDark: #77a1aa; width: 100%; height: 300px; position: absolute; - background-color: $light-gray; + background-color: global.$light-gray; border-bottom: 2px solid $timelineDark; transition: transform 500ms ease; @@ -247,7 +247,7 @@ $timelineDark: #77a1aa; top: 0px; width: 100px; height: 30%; - border: 1px solid $dark-gray; + border: 1px solid global.$dark-gray; font-size: 12px; line-height: 11px; background-color: $timelineDark; diff --git a/src/client/views/animationtimeline/TimelineMenu.scss b/src/client/views/animationtimeline/TimelineMenu.scss index de2042f17..5398a4a97 100644 --- a/src/client/views/animationtimeline/TimelineMenu.scss +++ b/src/client/views/animationtimeline/TimelineMenu.scss @@ -1,9 +1,9 @@ -@import './../global/globalCssVariables.module.scss'; +@use './../global/globalCssVariables.module.scss' as global; .timeline-menu-container { position: absolute; display: flex; - box-shadow: $medium-gray 0.2vw 0.2vw 0.4vw; + box-shadow: global.$medium-gray 0.2vw 0.2vw 0.4vw; flex-direction: column; background: whitesmoke; z-index: 10000; @@ -14,7 +14,7 @@ border: solid #bbbbbbbb 1px; .timeline-menu-input { - font: $sans-serif; + font: global.$sans-serif; font-size: 13px; width: 100%; text-transform: uppercase; @@ -33,11 +33,11 @@ border-top-left-radius: 15px; border-top-right-radius: 15px; text-transform: uppercase; - background: $dark-gray; + background: global.$dark-gray; letter-spacing: 2px; .timeline-menu-header-desc { - font: $sans-serif; + font: global.$sans-serif; font-size: 13px; text-align: center; color: whitesmoke; @@ -72,15 +72,15 @@ .timeline-menu-item:hover { border-width: 0.11px; border-style: none; - border-color: $medium-gray; + border-color: global.$medium-gray; border-bottom-style: solid; border-top-style: solid; - background: $medium-blue; + background: global.$medium-blue; } .timeline-menu-desc { padding-left: 10px; - font: $sans-serif; + font: global.$sans-serif; font-size: 13px; } } diff --git a/src/client/views/animationtimeline/TimelineOverview.scss b/src/client/views/animationtimeline/TimelineOverview.scss index 2878232e6..8336f2b2f 100644 --- a/src/client/views/animationtimeline/TimelineOverview.scss +++ b/src/client/views/animationtimeline/TimelineOverview.scss @@ -1,4 +1,4 @@ -@import './../global/globalCssVariables.module.scss'; +@use './../global/globalCssVariables.module.scss' as global; $timelineColor: #9acedf; $timelineDark: #77a1aa; diff --git a/src/client/views/animationtimeline/Track.scss b/src/client/views/animationtimeline/Track.scss index f56b2fe5f..7f5e8b8f3 100644 --- a/src/client/views/animationtimeline/Track.scss +++ b/src/client/views/animationtimeline/Track.scss @@ -1,12 +1,12 @@ -@import './../global/globalCssVariables.module.scss'; +@use './../global/globalCssVariables.module.scss' as global; .track-container { .track { .inner { top: 0px; width: calc(100%); - background-color: $white; - border: 1px solid $dark-gray; + background-color: global.$white; + border: 1px solid global.$dark-gray; position: relative; z-index: 100; } diff --git a/src/client/views/collections/CollectionCardDeckView.scss b/src/client/views/collections/CollectionCardDeckView.scss index 79c53db08..e6cc398af 100644 --- a/src/client/views/collections/CollectionCardDeckView.scss +++ b/src/client/views/collections/CollectionCardDeckView.scss @@ -1,5 +1,3 @@ -@import '../global/globalCssVariables.module.scss'; - .collectionCardView-outer { height: 100%; width: 100%; @@ -11,6 +9,7 @@ display: flex; transform-origin: top left; align-items: center; + position: relative; } button { @@ -35,6 +34,12 @@ .collectionCardView-cardSizeDragger { position: absolute; top: 0; + width: 28px; + height: 28px; + > svg { + width: 100%; + height: 100%; + } } .no-card-span { diff --git a/src/client/views/collections/CollectionCardDeckView.tsx b/src/client/views/collections/CollectionCardDeckView.tsx index 43464e50c..756b37f99 100644 --- a/src/client/views/collections/CollectionCardDeckView.tsx +++ b/src/client/views/collections/CollectionCardDeckView.tsx @@ -1,22 +1,22 @@ -import { IReactionDisposer, ObservableMap, action, computed, makeObservable, observable, reaction, runInAction } from 'mobx'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import * as CSS from 'csstype'; +import { action, computed, IReactionDisposer, makeObservable, observable, ObservableMap, reaction, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import { computedFn } from 'mobx-utils'; import * as React from 'react'; -import * as CSS from 'csstype'; -import { ClientUtils, imageUrlToBase64, returnFalse, returnNever, returnZero, setupMoveUpEvents } from '../../../ClientUtils'; +import { ClientUtils, returnFalse, returnNever, returnZero, setupMoveUpEvents } from '../../../ClientUtils'; import { emptyFunction } from '../../../Utils'; import { Doc, DocListCast, Opt } from '../../../fields/Doc'; -import { Animation, DocData } from '../../../fields/DocSymbols'; +import { Animation } from '../../../fields/DocSymbols'; import { Id } from '../../../fields/FieldSymbols'; import { List } from '../../../fields/List'; import { ScriptField } from '../../../fields/ScriptField'; -import { BoolCast, DocCast, NumCast, RTFCast, ScriptCast, StrCast } from '../../../fields/Types'; -import { URLField } from '../../../fields/URLField'; -import { gptImageLabel } from '../../apis/gpt/GPT'; +import { BoolCast, DocCast, NumCast, ScriptCast, StrCast } from '../../../fields/Types'; import { DocumentType } from '../../documents/DocumentTypes'; import { Docs } from '../../documents/Documents'; import { DragManager } from '../../util/DragManager'; import { dropActionType } from '../../util/DropActionTypes'; +import { SettingsManager } from '../../util/SettingsManager'; import { SnappingManager } from '../../util/SnappingManager'; import { Transform } from '../../util/Transform'; import { undoable, UndoManager } from '../../util/UndoManager'; @@ -25,11 +25,8 @@ import { StyleProp } from '../StyleProp'; import { TagItem } from '../TagsView'; import { DocumentView, DocumentViewProps } from '../nodes/DocumentView'; import { FocusViewOptions } from '../nodes/FocusViewOptions'; -import { GPTPopup } from '../pdf/GPTPopup/GPTPopup'; import './CollectionCardDeckView.scss'; -import { CollectionSubView, docSortings, SubCollectionViewProps } from './CollectionSubView'; -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { SettingsManager } from '../../util/SettingsManager'; +import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView'; /** * New view type specifically for studying more dynamically. Allows you to reorder docs however you see fit, easily @@ -42,7 +39,6 @@ import { SettingsManager } from '../../util/SettingsManager'; export class CollectionCardView extends CollectionSubView() { private _dropDisposer?: DragManager.DragDropDisposer; private _disposers: { [key: string]: IReactionDisposer } = {}; - private _textToDoc = new Map<string, Doc>(); private _oldWheel: HTMLElement | null = null; private _dropped = false; // set when a card doc has just moved and the drop method has been called - prevents the pointerUp method from hiding doc decorations (which needs to be done when clicking on a card to animate it to front/center) private _setCurDocScript = () => ScriptField.MakeScript('scriptContext.layoutDoc._card_curDoc=this', { scriptContext: 'any' })!; @@ -74,22 +70,7 @@ export class CollectionCardView extends CollectionSubView() { return Math.ceil(this.cardDeckWidth / this.cardWidth); } - /** - * update's gpt's doc-text list and initializes callbacks - */ - childPairStringListAndUpdateSortDesc = () => - this.childPairStringList().then(sortDesc => { - GPTPopup.Instance.setSortDesc(sortDesc.join()); - GPTPopup.Instance.onSortComplete = this.processGptOutput; - GPTPopup.Instance.onQuizRandom = this.quizMode; - }); - componentDidMount() { - this._disposers.chatVis = reaction( - () => GPTPopup.Instance.Visible, - vis => !vis && this.onGptHide() - ); - GPTPopup.Instance.setRegenerateCallback(this.Document, this.childPairStringListAndUpdateSortDesc); this._props.setContentViewBox?.(this); // if card deck moves, then the child doc views are hidden so their screen to local transforms will return empty rectangles // when inquired from the dom (below in childScreenToLocal). When the doc is actually rendered, we need to act like the @@ -110,12 +91,7 @@ export class CollectionCardView extends CollectionSubView() { ); } - onGptHide = () => Doc.setDocFilter(this.Document, 'tags', '#chat', 'remove'); componentWillUnmount() { - GPTPopup.Instance.setSortDesc(''); - GPTPopup.Instance.onSortComplete = undefined; - GPTPopup.Instance.onQuizRandom = undefined; - GPTPopup.Instance.setRegenerateCallback(undefined, null); Object.keys(this._disposers).forEach(key => this._disposers[key]?.()); this._dropDisposer?.(); } @@ -130,7 +106,7 @@ export class CollectionCardView extends CollectionSubView() { * Circle arc size, in radians, to layout cards */ @computed get archAngle() { - return NumCast(this.layoutDoc.card_arch, 90) * (Math.PI / 180) * (this.childCards.length < this._maxRowCount ? this.childCards.length / this._maxRowCount : 1); + return NumCast(this.layoutDoc.card_arch, 90) * (Math.PI / 180) * (this.childDocsNoInk.length < this._maxRowCount ? this.childDocsNoInk.length / this._maxRowCount : 1); } /** * Spacing card rows as a percent of Doc size. 100 means rows spread out to fill 100% of the Doc vertically. Default is 60% @@ -142,7 +118,7 @@ export class CollectionCardView extends CollectionSubView() { /** * The child documents to be rendered-- everything other than ink/link docs (which are marks as being svg's) */ - @computed get childCards() { + @computed get childDocsNoInk() { return this.childLayoutPairs.filter(pair => !pair.layout.layout_isSvg); } @@ -150,8 +126,8 @@ export class CollectionCardView extends CollectionSubView() { * how much to scale down the contents of the view so that everything will fit */ @computed get fitContentScale() { - const length = Math.min(this.childCards.length, this._maxRowCount); - return (this.childPanelWidth() * length) / this._props.PanelWidth(); + const length = Math.min(this.childDocsNoInk.length, this._maxRowCount); + return (this.childPanelWidth() * length) / (this._props.PanelWidth() - 2 * this.xMargin); } @computed get nativeScaling() { @@ -162,23 +138,20 @@ export class CollectionCardView extends CollectionSubView() { return NumCast(this.layoutDoc._xMargin, Math.max(3, 0.05 * this._props.PanelWidth())); } + @computed get yMargin() { + return this._props.yPadding || NumCast(this.layoutDoc._yMargin, Math.min(5, 0.05 * this._props.PanelWidth())); + } + @computed get cardDeckWidth() { return this._props.PanelWidth() - 2 * this.xMargin; } - /** - * When in quiz mode, randomly selects a document - */ - quizMode = () => { - this.layoutDoc._card_curDoc = this.childDocs[Math.floor(Math.random() * this.childDocs.length)]; - }; - setHoveredNodeIndex = action((index: number) => { if (!SnappingManager.IsDragging) this._hoveredNodeIndex = index; }); isSelected = (doc: Doc) => this._docRefs.get(doc)?.IsSelected; - childPanelWidth = () => NumCast(this.layoutDoc.childPanelWidth, Math.max(150, this._props.PanelWidth() / (this.childCards.length > this._maxRowCount ? this._maxRowCount : this.childCards.length) / this.nativeScaling)); + childPanelWidth = () => NumCast(this.layoutDoc.childPanelWidth, Math.max(150, this._props.PanelWidth() / (this.childDocsNoInk.length > this._maxRowCount ? this._maxRowCount : this.childDocsNoInk.length) / this.nativeScaling)); childPanelHeight = () => this._props.PanelHeight() * this.fitContentScale; onChildDoubleClick = () => ScriptCast(this.layoutDoc.onChildDoubleClick); isContentActive = () => this._props.isSelected() || this._props.isContentActive() || this.isAnyChildContentActive(); @@ -322,10 +295,10 @@ export class CollectionCardView extends CollectionSubView() { * @returns number of cards in row that contains index */ cardsInRowThatIncludesCardIndex = (index: number) => { - if (this.childCards.length < this._maxRowCount) { - return this.childCards.length; + if (this.childDocsNoInk.length < this._maxRowCount) { + return this.childDocsNoInk.length; } - const totalCards = this.childCards.length; + const totalCards = this.childDocsNoInk.length; if (index < totalCards - (totalCards % this._maxRowCount)) { return this._maxRowCount; } @@ -389,103 +362,6 @@ export class CollectionCardView extends CollectionSubView() { : this.translateY(index); }; - /** - * A list of the text content of all the child docs. RTF documents will have just their text and pdf documents will have the first 50 words. - * Image documents are converted to bse64 and gpt generates a description for them. all other documents use their title. This string is - * inputted into the gpt prompt to sort everything together - * @returns - */ - childPairStringList = () => { - const docToText = (doc: Doc) => { - switch (doc.type) { - case DocumentType.PDF: return StrCast(doc.text).split(/\s+/).slice(0, 50).join(' '); // first 50 words of pdf text - case DocumentType.IMG: return this.getImageDesc(doc); - case DocumentType.RTF: return StrCast(RTFCast(doc.text).Text); - default: return StrCast(doc.title); - } // prettier-ignore - }; - const docTextPromises = this.childCards - .map(pair => pair.layout) - .map(async doc => { - const docText = (await docToText(doc)) ?? ''; - doc.gptInputText = docText; - this._textToDoc.set(docText.replace(/\n/g, ' ').trim(), doc); - return `======${docText.replace(/\n/g, ' ').trim()}======`; - }); - return Promise.all<string>(docTextPromises); - }; - - /** - * Calls the gpt API to generate descriptions for the images in the view - * @param image - * @returns - */ - getImageDesc = async (image: Doc) => { - if (StrCast(image.description)) return StrCast(image.description); // Return existing description - const { href } = (image.data as URLField).url; - const hrefParts = href.split('.'); - const hrefComplete = `${hrefParts[0]}_o.${hrefParts[1]}`; - try { - const hrefBase64 = await imageUrlToBase64(hrefComplete); - const response = await gptImageLabel(hrefBase64, 'Give three to five labels to describe this image.'); - image[DocData].description = response.trim(); - return response; // Return the response from gptImageLabel - } catch (error) { - console.log(error); - } - return ''; - }; - - /** - * Processes gpt's output depending on the type of question the user asked. Converts gpt's string output to - * usable code - * @param gptOutput - * @param questionType - * @param tag - */ - processGptOutput = (gptOutput: string, questionType: string, tag?: string) => - undoable(() => { - // Split the string into individual list items - const listItems = gptOutput.split('======').filter(item => item.trim() !== ''); - - if (questionType === '2' || questionType === '4') { - this.childDocs.forEach(d => { - TagItem.removeTagFromDoc(d, '#chat'); - }); - } - - if (questionType === '6') { - this.Document[this._props.fieldKey + '_sort'] = docSortings.Chat; - } - - listItems.forEach((item, index) => { - const normalizedItem = item.trim(); - // find the corresponding Doc in the textToDoc map - const doc = this._textToDoc.get(normalizedItem); - if (doc) { - switch (questionType) { - case '6': - doc.chatIndex = index; - break; - case '1': - if (tag) { - const hashTag = tag.startsWith('#') ? tag : '#' + tag[0].toLowerCase() + tag.slice(1); - const filterTag = Doc.MyFilterHotKeys.map(key => StrCast(key.toolType)).find(key => key.includes(tag)) ?? hashTag; - TagItem.addTagToDoc(doc, filterTag); - } - break; - case '2': - case '4': - TagItem.addTagToDoc(doc, '#chat'); - Doc.setDocFilter(this.Document, 'tags', '#chat', 'check'); - break; - } - } else { - console.warn(`No matching document found for item: ${normalizedItem}`); - } - }); - }, '')(); - childScreenToLocal = computedFn((doc: Doc, index: number, isSelected: boolean) => () => { // need to explicitly trigger an invalidation since we're reading everything from the Dom this._forceChildXf; @@ -531,8 +407,8 @@ export class CollectionCardView extends CollectionSubView() { setupMoveUpEvents( this, e, - (emove: PointerEvent, down: number[], delta: number[]) => { - this.layoutDoc._cardWidth = Math.max(10, delta[0] < 0 ? Math.floor(this.cardWidth + delta[0]) : Math.ceil(this.cardWidth + delta[0])); + (emove: PointerEvent) => { + this.layoutDoc._cardWidth = Math.max(10, this.ScreenToLocalBoxXf().transformPoint(emove.clientX, 0)[0] - this.xMargin); return false; }, action(() => { @@ -625,7 +501,7 @@ export class CollectionCardView extends CollectionSubView() { curDoc = () => DocCast(this.layoutDoc._card_curDoc); render() { - const fitContentScale = this.childCards.length === 0 ? 1 : this.fitContentScale; + const fitContentScale = this.childDocsNoInk.length === 0 ? 1 : this.fitContentScale; return ( <div className="collectionCardView-outer" @@ -637,6 +513,8 @@ export class CollectionCardView extends CollectionSubView() { style={{ background: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.BackgroundColor) as string, color: this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.Color) as string, + paddingLeft: this.xMargin, + paddingRight: this.xMargin, }}> <div className="collectionCardView-inner" @@ -644,6 +522,7 @@ export class CollectionCardView extends CollectionSubView() { transform: `scale(${1 / fitContentScale})`, height: `${100 * fitContentScale}%`, width: `${100 * fitContentScale}%`, + top: this.yMargin, }}> <div className="collectionCardView-cardwrapper" @@ -657,15 +536,14 @@ export class CollectionCardView extends CollectionSubView() { <div className="collectionCardView-flashcardUI" style={{ - pointerEvents: this.childCards.length === 0 ? undefined : 'none', + pointerEvents: this.childDocsNoInk.length === 0 ? undefined : 'none', height: `${100 / this.nativeScaling / fitContentScale}%`, width: `${100 / this.nativeScaling / fitContentScale}%`, transform: `scale(${this.nativeScaling * fitContentScale})`, - }}> - {this.flashCardUI(this.curDoc, this.docViewProps, this.answered)} - </div> + }}></div> </div> + {this.flashCardUI(this.curDoc, this.docViewProps, this.answered)} <div className="collectionCardView-cardSizeDragger" onPointerDown={this.cardSizerDown} diff --git a/src/client/views/collections/CollectionCarousel3DView.scss b/src/client/views/collections/CollectionCarousel3DView.scss index 42e112906..13e6b54c2 100644 --- a/src/client/views/collections/CollectionCarousel3DView.scss +++ b/src/client/views/collections/CollectionCarousel3DView.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .collectionCarousel3DView-outer { height: 100%; position: relative; @@ -10,8 +10,8 @@ .carousel-wrapper { display: flex; position: absolute; - top: $CAROUSEL3D_TOP * 1%; - height: ($CAROUSEL3D_SIDE_SCALE * 100) * 1%; + top: global.$CAROUSEL3D_TOP * 1%; + height: (global.$CAROUSEL3D_SIDE_SCALE * 100) * 1%; align-items: center; transition: transform 0.3s cubic-bezier(0.455, 0.03, 0.515, 0.955); @@ -24,7 +24,7 @@ pointer-events: none; opacity: 0.5; z-index: 1; - transform: scale($CAROUSEL3D_SIDE_SCALE); + transform: scale(global.$CAROUSEL3D_SIDE_SCALE); user-select: none; } @@ -32,7 +32,7 @@ pointer-events: unset; opacity: 1; z-index: 2; - transform: scale($CAROUSEL3D_CENTER_SCALE); + transform: scale(global.$CAROUSEL3D_CENTER_SCALE); } } @@ -80,7 +80,7 @@ .carousel3DView-back { top: 0; background: transparent; - width: calc((1 - #{$CAROUSEL3D_CENTER_SCALE} * 0.33) / 2 * 100%); + width: calc((1 - #{global.$CAROUSEL3D_CENTER_SCALE} * 0.33) / 2 * 100%); height: 100%; } diff --git a/src/client/views/collections/CollectionCarouselView.tsx b/src/client/views/collections/CollectionCarouselView.tsx index 87c6e3e5c..a7d217076 100644 --- a/src/client/views/collections/CollectionCarouselView.tsx +++ b/src/client/views/collections/CollectionCarouselView.tsx @@ -249,9 +249,9 @@ export class CollectionCarouselView extends CollectionSubView() { position: 'relative', }}> {this.content} - {this.flashCardUI(this.curDoc, this.docViewProps, this.answered)} {this.navButtons} </div> + {this.flashCardUI(this.curDoc, this.docViewProps, this.answered)} </div> ); } diff --git a/src/client/views/collections/CollectionDockingView.scss b/src/client/views/collections/CollectionDockingView.scss index a747ef45f..7c19d39da 100644 --- a/src/client/views/collections/CollectionDockingView.scss +++ b/src/client/views/collections/CollectionDockingView.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .lm_root { position: relative; @@ -285,7 +285,7 @@ background: transparent; border: solid 0px transparent; cursor: grab; - color: $black; + color: global.$black; } .collectiondockingview-container .lm_splitter { opacity: 0.2; @@ -378,7 +378,7 @@ ul.lm_tabs::before { z-index: 1; text-align: center; font-size: 18; - color: $dark-gray; + color: global.$dark-gray; img { position: relative; @@ -491,7 +491,7 @@ ul.lm_tabs::before { } .lm_content { - background: $white; + background: global.$white; } .lm_controls { @@ -557,7 +557,7 @@ ul.lm_tabs::before { } .flexlayout__splitter { - background-color: $dark-gray; + background-color: global.$dark-gray; } .flexlayout__splitter:hover { @@ -626,7 +626,7 @@ ul.lm_tabs::before { position: absolute; box-sizing: border-box; background-color: #222; - color: $dark-gray; + color: global.$dark-gray; } .flexlayout__tab_button { @@ -709,7 +709,7 @@ ul.lm_tabs::before { } .flexlayout__tab_header_outer { - background-color: $dark-gray; + background-color: global.$dark-gray; position: absolute; left: 0; right: 0; @@ -769,28 +769,28 @@ ul.lm_tabs::before { } .flexlayout__border_top { - background-color: $dark-gray; + background-color: global.$dark-gray; border-bottom: 1px solid #ddd; box-sizing: border-box; overflow: hidden; } .flexlayout__border_bottom { - background-color: $dark-gray; + background-color: global.$dark-gray; border-top: 1px solid #333; box-sizing: border-box; overflow: hidden; } .flexlayout__border_left { - background-color: $dark-gray; + background-color: global.$dark-gray; border-right: 1px solid #333; box-sizing: border-box; overflow: hidden; } .flexlayout__border_right { - background-color: $dark-gray; + background-color: global.$dark-gray; border-left: 1px solid #333; box-sizing: border-box; overflow: hidden; diff --git a/src/client/views/collections/CollectionDockingView.tsx b/src/client/views/collections/CollectionDockingView.tsx index 539b49c86..e51bc18ef 100644 --- a/src/client/views/collections/CollectionDockingView.tsx +++ b/src/client/views/collections/CollectionDockingView.tsx @@ -48,8 +48,7 @@ export class CollectionDockingView extends CollectionSubView() { // eslint-disable-next-line no-use-before-define @observable public static Instance: CollectionDockingView | undefined = undefined; - private _reactionDisposer?: IReactionDisposer; - private _lightboxReactionDisposer?: IReactionDisposer; + private _disposers: { [key: string]: IReactionDisposer } = {}; private _containerRef = React.createRef<HTMLDivElement>(); private _flush: UndoManager.Batch | undefined; private _unmounting = false; @@ -341,12 +340,12 @@ export class CollectionDockingView extends CollectionSubView() { this._unmounting = false; SetPropSetterCb('title', this.titleChanged); // this overrides any previously assigned callback for the property if (this._containerRef.current) { - this._lightboxReactionDisposer = reaction( + this._disposers.lightbox = reaction( () => DocumentView.LightboxDoc(), doc => setTimeout(() => !doc && this.onResize()) ); new ResizeObserver(this.onResize).observe(this._containerRef.current); - this._reactionDisposer = reaction( + this._disposers.docking = reaction( () => StrCast(this.Document.dockingConfig), config => { if (!this._goldenLayout || this._ignoreStateChange !== config) { @@ -356,12 +355,16 @@ export class CollectionDockingView extends CollectionSubView() { this._ignoreStateChange = ''; } ); - reaction( + this._disposers.panel = reaction( () => this._props.PanelWidth(), - width => !this._goldenLayout && width > 20 && setTimeout(() => this.setupGoldenLayout()), // need to wait for the collectiondockingview-container to have it's width/height since golden layout reads that to configure its windows + width => { + if (!this._goldenLayout && width > 20) { + setTimeout(() => this.setupGoldenLayout()); + } + }, // need to wait for the collectiondockingview-container to have it's width/height since golden layout reads that to configure its windows { fireImmediately: true } ); - reaction( + this._disposers.color = reaction( () => [SnappingManager.userBackgroundColor, SnappingManager.userBackgroundColor], () => { clearStyleSheetRules(CollectionDockingView._highlightStyleSheet); @@ -376,6 +379,7 @@ export class CollectionDockingView extends CollectionSubView() { componentWillUnmount: () => void = () => { this._unmounting = true; + Object.values(this._disposers).forEach(d => d()); try { this._goldenLayout.unbind('stackCreated', this.stackCreated); this._goldenLayout.unbind('tabDestroyed', this.tabDestroyed); @@ -385,9 +389,6 @@ export class CollectionDockingView extends CollectionSubView() { setTimeout(() => this._goldenLayout?.destroy()); window.removeEventListener('resize', this.onResize); window.removeEventListener('mouseup', this.onPointerUp); - - this._reactionDisposer?.(); - this._lightboxReactionDisposer?.(); }; // ViewBoxInterface overrides @@ -426,7 +427,7 @@ export class CollectionDockingView extends CollectionSubView() { @action onPointerUp = (): void => { - window.removeEventListener('pointerup', this.onPointerUp); + window.removeEventListener('mouseup', this.onPointerUp); DragManager.CompleteWindowDrag = undefined; setTimeout(this.endUndoBatch, 100); }; diff --git a/src/client/views/collections/CollectionMasonryViewFieldRow.tsx b/src/client/views/collections/CollectionMasonryViewFieldRow.tsx index 710c00841..a0d5f9f70 100644 --- a/src/client/views/collections/CollectionMasonryViewFieldRow.tsx +++ b/src/client/views/collections/CollectionMasonryViewFieldRow.tsx @@ -258,7 +258,6 @@ export class CollectionMasonryViewFieldRow extends ObservableReactComponent<CMVF const stackPad = showChrome ? `0px ${this._props.parent.xMargin}px` : `${this._props.parent.yMargin}px ${this._props.parent.xMargin}px 0px ${this._props.parent.xMargin}px `; return this.collapsed ? null : ( <div style={{ position: 'relative' }}> - {this._props.showHandle && this._props.parent._props.isContentActive() ? this._props.parent.columnDragger : null} {showChrome ? ( <div className="collectionStackingView-addDocumentButton" diff --git a/src/client/views/collections/CollectionMenu.scss b/src/client/views/collections/CollectionMenu.scss index 45d9394ed..11fce720c 100644 --- a/src/client/views/collections/CollectionMenu.scss +++ b/src/client/views/collections/CollectionMenu.scss @@ -1,13 +1,13 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .collectionMenu-container { display: flex; position: relative; align-content: center; justify-content: space-between; - background-color: $dark-gray; + background-color: global.$dark-gray; height: 40px; - border-bottom: $standard-border; + border-bottom: global.$standard-border; padding: 0 10px; align-items: center; overflow-x: auto; diff --git a/src/client/views/collections/CollectionNoteTakingView.scss b/src/client/views/collections/CollectionNoteTakingView.scss index 95fda7b0a..0d24a56b5 100644 --- a/src/client/views/collections/CollectionNoteTakingView.scss +++ b/src/client/views/collections/CollectionNoteTakingView.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .collectionNoteTakingView-DocumentButtons { opacity: 0; @@ -58,7 +58,7 @@ .documentButtonMenu { position: relative; height: fit-content; - border-bottom: $standard-border; + border-bottom: global.$standard-border; display: flex; justify-content: center; flex-direction: column; @@ -70,11 +70,11 @@ width: 90%; margin: 5px; font-size: 11px; - background-color: $light-blue; - color: $medium-blue; + background-color: global.$light-blue; + color: global.$medium-blue; padding: 10px; border-radius: 10px; - border: solid 2px $medium-blue; + border: solid 2px global.$medium-blue; } } @@ -146,9 +146,9 @@ padding: 10px; height: 2vw; width: 100%; - font-family: $sans-serif; - background: $dark-gray; - color: $white; + font-family: global.$sans-serif; + background: global.$dark-gray; + color: global.$white; } .collectionNoteTakingView-columnDragger { @@ -206,7 +206,7 @@ margin-left: 2px; margin-right: 2px; margin-top: 2px; - background: $medium-gray; + background: global.$medium-gray; height: 5px; &.active { @@ -258,7 +258,7 @@ text-align: center; margin: auto; margin-bottom: 10px; - background: $medium-gray; + background: global.$medium-gray; // overflow: hidden; overflow is visible so the color menu isn't hidden -ftong .editableView-input:hover, @@ -279,7 +279,7 @@ display: flex; align-items: center; justify-content: center; - color: $dark-gray; + color: global.$dark-gray; .editableView-container-editing-oneLine, .editableView-container-editing { diff --git a/src/client/views/collections/CollectionPivotView.tsx b/src/client/views/collections/CollectionPivotView.tsx new file mode 100644 index 000000000..2600c0f57 --- /dev/null +++ b/src/client/views/collections/CollectionPivotView.tsx @@ -0,0 +1,147 @@ +import { action, computed, makeObservable, observable, runInAction } from 'mobx'; +import { observer } from 'mobx-react'; +import * as React from 'react'; +import { returnTrue } from '../../../ClientUtils'; +import { Doc, Opt, StrListCast } from '../../../fields/Doc'; +import { List } from '../../../fields/List'; +import { ObjectField } from '../../../fields/ObjectField'; +import { ComputedField, ScriptField } from '../../../fields/ScriptField'; +import { NumCast, StrCast } from '../../../fields/Types'; +import { Docs } from '../../documents/Documents'; +import { ScriptingGlobals } from '../../util/ScriptingGlobals'; +import { FieldsDropdown } from '../FieldsDropdown'; +import { PinDocView } from '../PinFuncs'; +import { DocumentView } from '../nodes/DocumentView'; +import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView'; +import './CollectionTimeView.scss'; +import { ViewDefBounds, computePivotLayout } from './collectionFreeForm/CollectionFreeFormLayoutEngines'; +import { CollectionFreeFormView } from './collectionFreeForm/CollectionFreeFormView'; + +@observer +export class CollectionPivotView extends CollectionSubView() { + _changing = false; + @observable _collapsed: boolean = false; + @observable _childClickedScript: Opt<ScriptField> = undefined; + @observable _viewDefDivClick: Opt<ScriptField> = undefined; + @observable _focusPivotField: Opt<string> = undefined; + + constructor(props: SubCollectionViewProps) { + super(props); + makeObservable(this); + } + + componentDidMount() { + this._props.setContentViewBox?.(this); + runInAction(() => { + this._childClickedScript = ScriptField.MakeScript('openInLightbox(this)', { this: Doc.name }); + this._viewDefDivClick = ScriptField.MakeScript('pivotColumnClick(this,payload)', { payload: 'any' }); + }); + } + + get pivotField() { + return this._focusPivotField || StrCast(this.layoutDoc._pivotField); + } + + getAnchor = (addAsAnnotation: boolean) => { + const anchor = Docs.Create.ConfigDocument({ + title: ComputedField.MakeFunction(`"${this.pivotField}"])`) as unknown as string, // title can take a functiono or a string + annotationOn: this.Document, + }); + PinDocView(anchor, { pinData: { collectionType: true, pivot: true, filters: true } }, this.Document); + addAsAnnotation && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_annotations', anchor); // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered + return anchor; + }; + + @action + scrollPreview = (docView: DocumentView, anchor: Doc /* , focusSpeed: number, options: FocusViewOptions */) => { + // if in preview, then override document's fields with view spec + this._focusFilters = StrListCast(anchor.config_docFilters); + this._focusRangeFilters = StrListCast(anchor.config_docRangeFilters); + this._focusPivotField = StrCast(anchor.config_pivotField); + return undefined; + }; + + toggleVisibility = action(() => { + this._collapsed = !this._collapsed; + }); + + goTo = (prevFilterIndex: number) => { + this.layoutDoc._pivotField = this.layoutDoc['_prevPivotFields' + prevFilterIndex]; + this.layoutDoc._childFilters = ObjectField.MakeCopy(this.layoutDoc['_prevDocFilter' + prevFilterIndex] as ObjectField); + this.layoutDoc._childFiltersByRanges = ObjectField.MakeCopy(this.layoutDoc['_prevDocRangeFilters' + prevFilterIndex] as ObjectField); + this.layoutDoc._prevFilterIndex = prevFilterIndex; + }; + + @action + contentsDown = () => { + const prevFilterIndex = NumCast(this.layoutDoc._prevFilterIndex); + if (prevFilterIndex > 0) { + this.goTo(prevFilterIndex - 1); + } else { + this.layoutDoc._childFilters = new List([]); + } + }; + layoutEngine = () => computePivotLayout.name; + @computed get contents() { + return ( + <div className="collectionTimeView-innards" key="timeline" style={{ pointerEvents: this._props.isContentActive() ? undefined : 'none' }} onClick={this.contentsDown}> + <CollectionFreeFormView + {...this._props} + engineProps={{ pivotField: this.pivotField, childFilters: this.childDocFilters, childFiltersByRanges: this.childDocRangeFilters }} + fitContentsToBox={returnTrue} + childClickScript={this._childClickedScript} + viewDefDivClick={this._viewDefDivClick} + layoutEngine={this.layoutEngine} + /> + </div> + ); + } + + render() { + return ( + <div className="collectionTimeView-pivot" style={{ width: this._props.PanelWidth(), height: '100%' }}> + {this.contents} + <div style={{ right: 0, top: 0, position: 'absolute' }}> + <FieldsDropdown + Document={this.Document} + selectFunc={fieldKey => { + this.layoutDoc._pivotField = fieldKey; + }} + placeholder={StrCast(this.layoutDoc._pivotField)} + /> + </div> + </div> + ); + } +} + +// eslint-disable-next-line prefer-arrow-callback +ScriptingGlobals.add(function pivotColumnClick(pivotDoc: Doc, bounds: ViewDefBounds) { + const pivotField = StrCast(pivotDoc._pivotField, 'author'); + let prevFilterIndex = NumCast(pivotDoc._prevFilterIndex); + const originalFilter = StrListCast(ObjectField.MakeCopy(pivotDoc._childFilters as ObjectField)); + pivotDoc['_prevDocFilter' + prevFilterIndex] = ObjectField.MakeCopy(pivotDoc._childFilters as ObjectField); + pivotDoc['_prevDocRangeFilters' + prevFilterIndex] = ObjectField.MakeCopy(pivotDoc._childFiltersByRanges as ObjectField); + pivotDoc['_prevPivotFields' + prevFilterIndex] = pivotField; + pivotDoc._prevFilterIndex = ++prevFilterIndex; + pivotDoc._childFilters = new List(); + setTimeout( + action(() => { + const filterVals = bounds.payload as string[]; + filterVals.map(filterVal => Doc.setDocFilter(pivotDoc, pivotField, filterVal, 'check')); + const pivotView = DocumentView.getDocumentView(pivotDoc); + if (pivotDoc && pivotView?.ComponentView instanceof CollectionPivotView && filterVals.length === 1) { + if (pivotView?.ComponentView.childDocs.length && pivotView.ComponentView.childDocs[0][filterVals[0]]) { + pivotDoc._pivotField = filterVals[0]; + } + } + const newFilters = StrListCast(pivotDoc._childFilters); + if (newFilters.length && originalFilter.length && newFilters.lastElement() === originalFilter.lastElement()) { + pivotDoc._prevFilterIndex = --prevFilterIndex; + pivotDoc['_prevDocFilter' + prevFilterIndex] = undefined; + pivotDoc['_prevDocRangeFilters' + prevFilterIndex] = undefined; + pivotDoc['_prevPivotFields' + prevFilterIndex] = undefined; + } + }) + ); +}); diff --git a/src/client/views/collections/CollectionStackedTimeline.scss b/src/client/views/collections/CollectionStackedTimeline.scss index 0ced3f9e3..d05c0ffde 100644 --- a/src/client/views/collections/CollectionStackedTimeline.scss +++ b/src/client/views/collections/CollectionStackedTimeline.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .collectionStackedTimeline-timelineContainer { height: 100%; @@ -6,7 +6,7 @@ overflow-x: auto; overflow-y: hidden; border: none; - background-color: $white; + background-color: global.$white; border-width: 0 2px 0 2px; &:hover { @@ -28,7 +28,7 @@ .collectionStackedTimeline { position: absolute; - background: $off-white; + background: global.$off-white; z-index: 1000; height: 100%; overflow: hidden; @@ -36,7 +36,7 @@ .collectionStackedTimeline-trim-shade { position: absolute; height: 100%; - background-color: $dark-gray; + background-color: global.$dark-gray; opacity: 0.3; top: 0; } @@ -45,7 +45,7 @@ height: 100%; position: absolute; box-sizing: border-box; - border: 2px solid $medium-blue; + border: 2px solid global.$medium-blue; display: flex; justify-content: space-between; max-width: 100%; @@ -53,7 +53,7 @@ left: 0; .collectionStackedTimeline-trim-handle { - background-color: $medium-blue; + background-color: global.$medium-blue; height: 100%; width: 5px; cursor: ew-resize; @@ -65,12 +65,12 @@ width: 10px; top: 2.5%; height: 95%; - background: $light-blue; + background: global.$light-blue; border-radius: 3px; opacity: 0.3; z-index: 500; border-style: solid; - border-color: $medium-blue; + border-color: global.$medium-blue; border-width: 1px; } @@ -84,12 +84,12 @@ } .collectionStackedTimeline-current { - background-color: $pink; + background-color: global.$pink; } .collectionStackedTimeline-hover { display: none; - background-color: $medium-blue; + background-color: global.$medium-blue; } .collectionStackedTimeline-marker-timeline { @@ -97,14 +97,14 @@ top: 2.5%; height: 95%; border-radius: 4px; - //background: $light-gray; + //background: global.$light-gray; &:hover { opacity: 1; } .collectionStackedTimeline-left-resizer, .collectionStackedTimeline-resizer { - background: $dark-gray; + background: global.$dark-gray; position: absolute; top: 0; height: 100%; @@ -141,7 +141,7 @@ .hoverTime { position: absolute; - color: $dark-gray; + color: global.$dark-gray; transform: translate(0, -100%); font-weight: bold; diff --git a/src/client/views/collections/CollectionStackingView.scss b/src/client/views/collections/CollectionStackingView.scss index 6400a0a8e..05ac52ff9 100644 --- a/src/client/views/collections/CollectionStackingView.scss +++ b/src/client/views/collections/CollectionStackingView.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .collectionMasonryView { display: inline; @@ -12,120 +12,124 @@ position: relative; height: 100%; width: 100%; -} - -// TODO:glr Turn this into a seperate class -.documentButtonMenu { - position: relative; - height: fit-content; - border-bottom: $standard-border; - display: flex; - justify-content: center; - flex-direction: column; - align-items: center; - align-content: center; - padding: 5px 0 5px 0; - .documentExplanation { - width: 90%; - margin: 5px; - font-size: 11px; - color: $medium-blue; - padding: 10px; - border-radius: 5px; - border: solid 0.5px $medium-blue; + .collectionStackingView-columnDragger { + width: 28; + height: 28; + position: absolute; + margin-left: -5; + z-index: 10; + > svg { + width: 100%; + height: 100%; + } } -} -.collectionStackingView, -.collectionMasonryView { - height: 100%; - width: 100%; - position: absolute; - top: 0; - overflow-y: auto; - overflow-x: hidden; - flex-wrap: wrap; - transition: top 0.5s; - - > div { + // TODO:glr Turn this into a seperate class + .documentButtonMenu { position: relative; - display: block; - } - - .collectionStackingViewFieldColumn { + height: fit-content; + border-bottom: global.$standard-border; display: flex; + justify-content: center; flex-direction: column; + align-items: center; + align-content: center; + padding: 5px 0 5px 0; + + .documentExplanation { + width: 90%; + margin: 5px; + font-size: 11px; + color: global.$medium-blue; + padding: 10px; + border-radius: 5px; + border: solid 0.5px global.$medium-blue; + } } - .collectionSchemaView-previewDoc { + .collectionStackingView, + .collectionMasonryView { height: 100%; + width: 100%; position: absolute; - } + top: 0; + overflow-y: auto; + overflow-x: hidden; + flex-wrap: wrap; + transition: top 0.5s; - .collectionStackingView-docView-container { - width: 45%; - margin: 5% 2.5%; - padding-left: 2.5%; - height: auto; - } + > div { + position: relative; + display: block; + } - .collectionStackingView-flexCont { - display: flex; - flex-direction: row; - flex-wrap: wrap; - align-items: center; - } + .collectionStackingViewFieldColumn { + display: flex; + flex-direction: column; + } - .collectionStackingView-masonrySingle, - .collectionStackingView-masonryGrid { - width: 100%; - display: grid; - top: 0; - left: 0; - } + .collectionSchemaView-previewDoc { + height: 100%; + position: absolute; + } - .collectionStackingView-masonrySingle { - height: 100%; - position: absolute; - } + .collectionStackingView-docView-container { + width: 45%; + margin: 5% 2.5%; + padding-left: 2.5%; + height: auto; + } - .collectionStackingView-masonryGrid { - margin: auto; - height: max-content; - position: relative; - grid-auto-rows: 0px; - } + .collectionStackingView-flexCont { + display: flex; + flex-direction: row; + flex-wrap: wrap; + align-items: center; + } - .collectionStackingView-masonrySingle { - width: 100%; - height: 100%; - position: absolute; - display: flex; - flex-direction: column; - top: 0; - left: 0; - width: 100%; - position: absolute; - } + .collectionStackingView-masonrySingle, + .collectionStackingView-masonryGrid { + width: 100%; + display: grid; + top: 0; + left: 0; + } - .collectionStackingView-description { - font-size: 100%; - margin-bottom: 1vw; - padding: 10px; - height: 2vw; - width: 100%; - font-family: $sans-serif; - background: $dark-gray; - color: $white; - } + .collectionStackingView-masonrySingle { + height: 100%; + position: absolute; + } - .collectionStackingView-columnDragger { - width: 15; - height: 15; - position: absolute; - margin-left: -5; - z-index: 10; + .collectionStackingView-masonryGrid { + margin: auto; + height: max-content; + position: relative; + grid-auto-rows: 0px; + } + + .collectionStackingView-masonrySingle { + width: 100%; + height: 100%; + position: absolute; + display: flex; + flex-direction: column; + top: 0; + left: 0; + width: 100%; + position: absolute; + } + + .collectionStackingView-description { + font-size: 100%; + margin-bottom: 1vw; + padding: 10px; + height: 2vw; + width: 100%; + font-family: global.$sans-serif; + background: global.$dark-gray; + color: global.$white; + } } // Documents in stacking view @@ -149,7 +153,7 @@ .collectionStackingView-collapseBar { margin-top: 2px; - background: $medium-gray; + background: global.$medium-gray; height: 5px; width: 100%; display: none; @@ -207,11 +211,11 @@ text-align: center; margin: auto; margin-bottom: 10px; - background: $medium-gray; + background: global.$medium-gray; // overflow: hidden; overflow is visible so the color menu isn't hidden -ftong .editableView-input { - color: $dark-gray; + color: global.$dark-gray; } .editableView-input:hover, @@ -232,7 +236,7 @@ display: flex; align-items: center; justify-content: center; - color: $dark-gray; + color: global.$dark-gray; .editableView-container-editing-oneLine, .editableView-container-editing { diff --git a/src/client/views/collections/CollectionStackingView.tsx b/src/client/views/collections/CollectionStackingView.tsx index a57256424..96125f2c2 100644 --- a/src/client/views/collections/CollectionStackingView.tsx +++ b/src/client/views/collections/CollectionStackingView.tsx @@ -110,7 +110,9 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection } // columnWidth handles the margin on the left and right side of the documents @computed get columnWidth() { - return Math.min(this._props.PanelWidth() - 2 * this.xMargin, this.isStackingView ? Number.MAX_VALUE : this.layoutDoc._columnWidth === -1 ? this._props.PanelWidth() - 2 * this.xMargin : NumCast(this.layoutDoc._columnWidth, 250)); + const availableWidth = this._props.PanelWidth() - 2 * this.xMargin; + const cwid = availableWidth / (NumCast(this.Document._layout_columnCount) || this._props.PanelWidth() / NumCast(this.Document._layout_columnWidth, this._props.PanelWidth() / 4)); + return Math.min(availableWidth, this.isStackingView ? Number.MAX_VALUE : cwid - this.gridGap); } @computed get NodeWidth() { @@ -221,6 +223,9 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection return fields; } + setAutoHeight = () => this._props.setHeight?.(this.headerMargin + (this.isStackingView ? Math.max(...this._refList.map(DivHeight)) : 2 * this.yMargin + this._refList.reduce((p, r) => p + DivHeight(r), 0))); + observer = new ResizeObserver(this.setAutoHeight); + componentDidMount() { super.componentDidMount?.(); this._props.setContentViewBox?.(this); @@ -232,10 +237,21 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection this.dataDoc['_' + this.fieldKey + '_columnHeaders'] = new List(); } ); + // reset section headers when a new filter is inputted + this._disposers.width = reaction( + () => [this._props.PanelWidth() - 2 * this.xMargin, NumCast(this.Document._layout_columnWidth, 250)], + ([pw, cw]) => { + if (!this.isStackingView && Math.round(pw / cw)) { + this.layoutDoc._layout_columnCount = Math.round(pw / cw); + } + } + ); + this._disposers.autoHeight = reaction( - () => this.layoutDoc._layout_autoHeight, - layoutAutoHeight => layoutAutoHeight && this._props.setHeight?.(this.headerMargin + (this.isStackingView ? Math.max(...this._refList.map(DivHeight)) : this._refList.reduce((p, r) => p + DivHeight(r), 0))) + () => [this.layoutDoc._layout_autoHeight, this.yMargin], + ([autoH]) => autoH && this.setAutoHeight() ); + this._disposers.refList = reaction( () => ({ refList: this._refList.slice(), autoHeight: this.layoutDoc._layout_autoHeight && !DocumentView.LightboxContains(this.DocumentView?.()) }), ({ refList, autoHeight }) => { @@ -435,8 +451,8 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection ); }; @action - onDividerMove = (e: PointerEvent, down: number[], delta: number[]) => { - this.layoutDoc._columnWidth = Math.max(10, this.columnWidth + delta[0]); + onDividerMove = (e: PointerEvent) => { + this.Document._layout_columnWidth = Math.max(10, (this._props.DocumentView?.().screenToViewTransform().transformPoint(e.clientX, 0)[0] ?? 0) - this.xMargin); return false; }; @@ -446,7 +462,7 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection className="collectionStackingView-columnDragger" onPointerDown={this.columnDividerDown} ref={this._draggerRef} - style={{ cursor: this._cursor, color: SettingsManager.userColor, left: `${this.columnWidth + this.xMargin}px`, top: `${Math.max(0, this.yMargin - 9)}px` }}> + style={{ cursor: this._cursor, color: SettingsManager.userColor, left: `${NumCast(this.Document._layout_columnWidth) + this.xMargin}px` }}> <FontAwesomeIcon icon="arrows-alt-h" /> </div> ); @@ -590,24 +606,29 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection } const rows = () => (!this.isStackingView ? 1 : Math.max(1, Math.min(docList.length, Math.floor((this._props.PanelWidth() - 2 * this.xMargin) / (this.columnWidth + this.gridGap))))); return ( - <CollectionMasonryViewFieldRow - showHandle={first} - Document={this.Document} - chromeHidden={this.chromeHidden} - pivotField={this.pivotField} - refList={this._refList} - key={heading ? heading.heading : ''} - rows={rows} - headings={this.headings} - heading={heading ? heading.heading : ''} - headingObject={heading} - docList={docList} - parent={this} - type={type} - createDropTarget={this.createDashEventsTarget} - screenToLocalTransform={this.ScreenToLocalBoxXf} - setDocHeight={this.setDocHeight} - /> + <div key={(heading?.heading ?? '') + 'head'}> + {this._props.isContentActive() && !this.isStackingView && !this.chromeHidden ? this.columnDragger : null} + <div style={{ top: this.yMargin }}> + <CollectionMasonryViewFieldRow + showHandle={first} + Document={this.Document} + chromeHidden={this.chromeHidden} + pivotField={this.pivotField} + refList={this._refList} + key={heading ? heading.heading : ''} + rows={rows} + headings={this.headings} + heading={heading ? heading.heading : ''} + headingObject={heading} + docList={docList} + parent={this} + type={type} + createDropTarget={this.createDashEventsTarget} + screenToLocalTransform={this.ScreenToLocalBoxXf} + setDocHeight={this.setDocHeight} + /> + </div> + </div> ); }; @@ -699,8 +720,6 @@ export class CollectionStackingView extends CollectionSubView<Partial<collection return this._props.isContentActive() === false ? 'none' : undefined; } - observer = new ResizeObserver(() => this._props.setHeight?.(this.headerMargin + (this.isStackingView ? Math.max(...this._refList.map(DivHeight)) : this._refList.reduce((p, r) => p + DivHeight(r), 0)))); - onPassiveWheel = (e: WheelEvent) => e.stopPropagation(); render() { TraceMobx(); diff --git a/src/client/views/collections/CollectionSubView.tsx b/src/client/views/collections/CollectionSubView.tsx index 5e99bec39..655894e40 100644 --- a/src/client/views/collections/CollectionSubView.tsx +++ b/src/client/views/collections/CollectionSubView.tsx @@ -28,6 +28,7 @@ import { FieldViewProps } from '../nodes/FieldView'; import { DocumentView, DocumentViewProps } from '../nodes/DocumentView'; import { FlashcardPracticeUI } from './FlashcardPracticeUI'; import { OpenWhere, OpenWhereMod } from '../nodes/OpenWhere'; +import { Upload } from '../../../server/SharedMediaTypes'; export enum docSortings { Time = 'time', @@ -37,6 +38,9 @@ export enum docSortings { Tag = 'tag', None = '', } + +export const ChatSortField = 'chat_sortIndex'; + export interface CollectionViewProps extends React.PropsWithChildren<FieldViewProps> { isAnnotationOverlay?: boolean; // is the collection an annotation overlay (eg an overlay on an image/video/etc) isAnnotationOverlayScrollable?: boolean; // whether the annotation overlay can be vertically scrolled (just for tree views, currently) @@ -121,6 +125,7 @@ export function CollectionSubView<X>() { return this.dataDoc[this._props.fieldKey]; // this used to be 'layoutDoc', but then template fields will get ignored since the template is not a proto of the layout. hopefully nothing depending on the previous code. } + hasChildDocs = () => this.childLayoutPairs.map(pair => pair.layout); @computed get childLayoutPairs(): { layout: Doc; data: Doc }[] { const { Document, TemplateDataDocument } = this._props; const validPairs = this.childDocs @@ -228,23 +233,21 @@ export function CollectionSubView<X>() { childSortedDocs = (docsIn: Doc[], dragIndex: number) => { const sortType = StrCast(this.Document[this._props.fieldKey + '_sort']) as docSortings; - const isDesc = BoolCast(this.Document[this._props.fieldKey + '_sort_desc']); + const isDesc = BoolCast(this.Document[this._props.fieldKey + '_sort_reverse']); const docs = docsIn.slice(); - if (sortType) { - docs.sort((docA, docB) => { - const [typeA, typeB] = (() => { - switch (sortType) { - default: - case docSortings.Type: return [StrCast(docA.type), StrCast(docB.type)]; - case docSortings.Chat: return [NumCast(docA.chatIndex, 9999), NumCast(docB.chatIndex,9999)]; - case docSortings.Time: return [DateCast(docA.author_date)?.date ?? Date.now(), DateCast(docB.author_date)?.date ?? Date.now()]; - case docSortings.Color:return [DashColor(StrCast(docA.backgroundColor)).hsv().hue(), DashColor(StrCast(docB.backgroundColor)).hsv().hue()]; - case docSortings.Tag: return [StrListCast(docA.tags).join(""), StrListCast(docB.tags).join("")]; - } - })(); //prettier-ignore - return (typeA < typeB ? -1 : typeA > typeB ? 1 : 0) * (isDesc ? 1 : -1); - }); - } + sortType && docs.sort((docA, docB) => { + const [typeA, typeB] = (() => { + switch (sortType) { + default: + case docSortings.Type: return [StrCast(docA.type), StrCast(docB.type)]; + case docSortings.Chat: return [NumCast(docA[ChatSortField], 9999), NumCast(docB[ChatSortField], 9999)]; + case docSortings.Time: return [DateCast(docA.author_date)?.date ?? Date.now(), DateCast(docB.author_date)?.date ?? Date.now()]; + case docSortings.Color:return [DashColor(StrCast(docA.backgroundColor)).hsv().hue(), DashColor(StrCast(docB.backgroundColor)).hsv().hue()]; + case docSortings.Tag: return [StrListCast(docA.tags).join(""), StrListCast(docB.tags).join("")]; + } + })(); + return (typeA < typeB ? -1 : typeA > typeB ? 1 : 0) * (isDesc ? -1 : 1); + }); //prettier-ignore if (dragIndex !== -1) { const draggedDoc = DragManager.docsBeingDragged[0]; const originalIndex = docs.findIndex(doc => doc === draggedDoc); @@ -405,7 +408,7 @@ export function CollectionSubView<X>() { const imgSrc = img.split('src="')[1].split('"')[0]; const imgOpts = { ...options, _width: 300 }; if (imgSrc.startsWith('data:image') && imgSrc.includes('base64')) { - const result = (await Networking.PostToServer('/uploadRemoteImage', { sources: [imgSrc] })).lastElement(); + const result = ((await Networking.PostToServer('/uploadRemoteImage', { sources: [imgSrc] })) as Upload.ImageInformation[]).lastElement(); const newImgSrc = result.accessPaths.agnostic.client.indexOf('dashblobstore') === -1 // ? ClientUtils.prepend(result.accessPaths.agnostic.client) @@ -538,12 +541,17 @@ export function CollectionSubView<X>() { DocUtils.uploadYoutubeVideoLoading(files, {}, loading); } else { generatedDocuments.push( - ...files.map(file => { - const loading = Docs.Create.LoadingDocument(file, options); - Doc.addCurrentlyLoading(loading); - DocUtils.uploadFileToDoc(file, {}, loading); - return loading; - }) + ...(await Promise.all( + files.map(async file => { + if (file.name.endsWith('svg')) { + return (await DocUtils.openSVGfile(file, options)) as Doc; + } + const loading = Docs.Create.LoadingDocument(file, options); + Doc.addCurrentlyLoading(loading); + DocUtils.uploadFileToDoc(file, {}, loading); + return loading; + }) + )) ); } if (generatedDocuments.length) { diff --git a/src/client/views/collections/CollectionTimeView.tsx b/src/client/views/collections/CollectionTimeView.tsx index d75c633ac..98bd06221 100644 --- a/src/client/views/collections/CollectionTimeView.tsx +++ b/src/client/views/collections/CollectionTimeView.tsx @@ -1,33 +1,22 @@ -import { action, computed, makeObservable, observable, runInAction } from 'mobx'; +import { action, computed, makeObservable, observable } from 'mobx'; import { observer } from 'mobx-react'; import * as React from 'react'; import { returnFalse, returnTrue, setupMoveUpEvents } from '../../../ClientUtils'; import { emptyFunction } from '../../../Utils'; import { Doc, Opt, StrListCast } from '../../../fields/Doc'; -import { List } from '../../../fields/List'; -import { ObjectField } from '../../../fields/ObjectField'; -import { listSpec } from '../../../fields/Schema'; -import { ComputedField, ScriptField } from '../../../fields/ScriptField'; -import { Cast, NumCast, StrCast } from '../../../fields/Types'; +import { NumCast, StrCast } from '../../../fields/Types'; import { Docs } from '../../documents/Documents'; -import { ScriptingGlobals } from '../../util/ScriptingGlobals'; -import { ContextMenu } from '../ContextMenu'; -import { ContextMenuProps } from '../ContextMenuItem'; import { FieldsDropdown } from '../FieldsDropdown'; import { PinDocView } from '../PinFuncs'; import { DocumentView } from '../nodes/DocumentView'; import { CollectionSubView, SubCollectionViewProps } from './CollectionSubView'; import './CollectionTimeView.scss'; -import { ViewDefBounds, computePivotLayout, computeTimelineLayout } from './collectionFreeForm/CollectionFreeFormLayoutEngines'; +import { computeTimelineLayout } from './collectionFreeForm/CollectionFreeFormLayoutEngines'; import { CollectionFreeFormView } from './collectionFreeForm/CollectionFreeFormView'; @observer export class CollectionTimeView extends CollectionSubView() { - _changing = false; - @observable _layoutEngine = computePivotLayout.name; @observable _collapsed: boolean = false; - @observable _childClickedScript: Opt<ScriptField> = undefined; - @observable _viewDefDivClick: Opt<ScriptField> = undefined; @observable _focusPivotField: Opt<string> = undefined; constructor(props: SubCollectionViewProps) { @@ -37,10 +26,6 @@ export class CollectionTimeView extends CollectionSubView() { componentDidMount() { this._props.setContentViewBox?.(this); - runInAction(() => { - this._childClickedScript = ScriptField.MakeScript('openInLightbox(this)', { this: Doc.name }); - this._viewDefDivClick = ScriptField.MakeScript('pivotColumnClick(this,payload)', { payload: 'any' }); - }); } get pivotField() { @@ -49,19 +34,10 @@ export class CollectionTimeView extends CollectionSubView() { getAnchor = (addAsAnnotation: boolean) => { const anchor = Docs.Create.ConfigDocument({ - title: ComputedField.MakeFunction(`"${this.pivotField}"])`) as unknown as string, // title can take a functiono or a string annotationOn: this.Document, }); PinDocView(anchor, { pinData: { collectionType: true, pivot: true, filters: true } }, this.Document); - - if (addAsAnnotation) { - // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered - if (Cast(this.dataDoc[this._props.fieldKey + '_annotations'], listSpec(Doc), null) !== undefined) { - Cast(this.dataDoc[this._props.fieldKey + '_annotations'], listSpec(Doc), []).push(anchor); - } else { - this.dataDoc[this._props.fieldKey + '_annotations'] = new List<Doc>([anchor]); - } - } + addAsAnnotation && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_annotations', anchor); // when added as an annotation, links to anchors can be found as links to the document even if the anchors are not rendered return anchor; }; @@ -74,7 +50,6 @@ export class CollectionTimeView extends CollectionSubView() { return undefined; }; - layoutEngine = () => this._layoutEngine; toggleVisibility = action(() => { this._collapsed = !this._collapsed; }); @@ -126,105 +101,24 @@ export class CollectionTimeView extends CollectionSubView() { ); }; - goTo = (prevFilterIndex: number) => { - this.layoutDoc._pivotField = this.layoutDoc['_prevPivotFields' + prevFilterIndex]; - this.layoutDoc._childFilters = ObjectField.MakeCopy(this.layoutDoc['_prevDocFilter' + prevFilterIndex] as ObjectField); - this.layoutDoc._childFiltersByRanges = ObjectField.MakeCopy(this.layoutDoc['_prevDocRangeFilters' + prevFilterIndex] as ObjectField); - this.layoutDoc._prevFilterIndex = prevFilterIndex; - }; - - @action - contentsDown = () => { - const prevFilterIndex = NumCast(this.layoutDoc._prevFilterIndex); - if (prevFilterIndex > 0) { - this.goTo(prevFilterIndex - 1); - } else { - this.layoutDoc._childFilters = new List([]); - } - }; - + layoutEngine = () => computeTimelineLayout.name; @computed get contents() { return ( - <div className="collectionTimeView-innards" key="timeline" style={{ pointerEvents: this._props.isContentActive() ? undefined : 'none' }} onClick={this.contentsDown}> + <div className="collectionTimeView-innards" key="timeline" style={{ pointerEvents: this._props.isContentActive() ? undefined : 'none' }}> <CollectionFreeFormView {...this._props} engineProps={{ pivotField: this.pivotField, childFilters: this.childDocFilters, childFiltersByRanges: this.childDocRangeFilters }} fitContentsToBox={returnTrue} - childClickScript={this._childClickedScript} - viewDefDivClick={this.layoutEngine() === computeTimelineLayout.name ? undefined : this._viewDefDivClick} layoutEngine={this.layoutEngine} /> </div> ); } - public static SyncTimelineToPresentation(doc: Doc) { - const fieldKey = Doc.LayoutFieldKey(doc); - doc[fieldKey + '-timelineCur'] = ComputedField.MakeFunction("(activePresentationItem()[this._pivotField || 'year'] || 0)"); - } - specificMenu = () => { - const layoutItems: ContextMenuProps[] = []; - const doc = this.layoutDoc; - - layoutItems.push({ - description: 'Force Timeline', - event: () => { - doc._forceRenderEngine = computeTimelineLayout.name; - }, - icon: 'compress-arrows-alt', - }); - layoutItems.push({ - description: 'Force Pivot', - event: () => { - doc._forceRenderEngine = computePivotLayout.name; - }, - icon: 'compress-arrows-alt', - }); - layoutItems.push({ - description: 'Auto Time/Pivot layout', - event: () => { - doc._forceRenderEngine = undefined; - }, - icon: 'compress-arrows-alt', - }); - layoutItems.push({ description: 'Sync with presentation', event: () => CollectionTimeView.SyncTimelineToPresentation(doc), icon: 'compress-arrows-alt' }); - - ContextMenu.Instance.addItem({ description: 'Options...', subitems: layoutItems, icon: 'eye' }); - }; - render() { - let nonNumbers = 0; - this.childDocs.forEach(doc => { - const num = NumCast(doc[this.pivotField], Number(StrCast(doc[this.pivotField]))); - if (isNaN(num)) { - nonNumbers++; - } - }); - const forceLayout = StrCast(this.layoutDoc._forceRenderEngine); - const doTimeline = forceLayout ? forceLayout === computeTimelineLayout.name : nonNumbers / this.childDocs.length < 0.1 && this._props.PanelWidth() / this._props.PanelHeight() > 6; - if (doTimeline !== (this._layoutEngine === computeTimelineLayout.name)) { - if (!this._changing) { - this._changing = true; - setTimeout( - action(() => { - this._layoutEngine = doTimeline ? computeTimelineLayout.name : computePivotLayout.name; - this._changing = false; - }), - 0 - ); - } - } - return ( - <div className={'collectionTimeView' + (doTimeline ? '' : '-pivot')} onContextMenu={this.specificMenu} style={{ width: this._props.PanelWidth(), height: '100%' }}> + <div className="collectionTimeView" style={{ width: this._props.PanelWidth(), height: '100%' }}> {this.contents} - {!this._props.isSelected() || !doTimeline ? null : ( - <> - <div className="collectionTimeView-thumb-min collectionTimeView-thumb" key="min" onPointerDown={this.onMinDown} /> - <div className="collectionTimeView-thumb-max collectionTimeView-thumb" key="mid" onPointerDown={this.onMaxDown} /> - <div className="collectionTimeView-thumb-mid collectionTimeView-thumb" key="max" onPointerDown={this.onMidDown} /> - </> - )} <div style={{ right: 0, top: 0, position: 'absolute' }}> <FieldsDropdown Document={this.Document} @@ -234,38 +128,14 @@ export class CollectionTimeView extends CollectionSubView() { placeholder={StrCast(this.layoutDoc._pivotField)} /> </div> + {!this._props.isSelected() ? null : ( + <> + <div className="collectionTimeView-thumb-min collectionTimeView-thumb" key="min" onPointerDown={this.onMinDown} /> + <div className="collectionTimeView-thumb-max collectionTimeView-thumb" key="mid" onPointerDown={this.onMaxDown} /> + <div className="collectionTimeView-thumb-mid collectionTimeView-thumb" key="max" onPointerDown={this.onMidDown} /> + </> + )} </div> ); } } - -// eslint-disable-next-line prefer-arrow-callback -ScriptingGlobals.add(function pivotColumnClick(pivotDoc: Doc, bounds: ViewDefBounds) { - const pivotField = StrCast(pivotDoc._pivotField, 'author'); - let prevFilterIndex = NumCast(pivotDoc._prevFilterIndex); - const originalFilter = StrListCast(ObjectField.MakeCopy(pivotDoc._childFilters as ObjectField)); - pivotDoc['_prevDocFilter' + prevFilterIndex] = ObjectField.MakeCopy(pivotDoc._childFilters as ObjectField); - pivotDoc['_prevDocRangeFilters' + prevFilterIndex] = ObjectField.MakeCopy(pivotDoc._childFiltersByRanges as ObjectField); - pivotDoc['_prevPivotFields' + prevFilterIndex] = pivotField; - pivotDoc._prevFilterIndex = ++prevFilterIndex; - pivotDoc._childFilters = new List(); - setTimeout( - action(() => { - const filterVals = bounds.payload as string[]; - filterVals.map(filterVal => Doc.setDocFilter(pivotDoc, pivotField, filterVal, 'check')); - const pivotView = DocumentView.getDocumentView(pivotDoc); - if (pivotDoc && pivotView?.ComponentView instanceof CollectionTimeView && filterVals.length === 1) { - if (pivotView?.ComponentView.childDocs.length && pivotView.ComponentView.childDocs[0][filterVals[0]]) { - pivotDoc._pivotField = filterVals[0]; - } - } - const newFilters = StrListCast(pivotDoc._childFilters); - if (newFilters.length && originalFilter.length && newFilters.lastElement() === originalFilter.lastElement()) { - pivotDoc._prevFilterIndex = --prevFilterIndex; - pivotDoc['_prevDocFilter' + prevFilterIndex] = undefined; - pivotDoc['_prevDocRangeFilters' + prevFilterIndex] = undefined; - pivotDoc['_prevPivotFields' + prevFilterIndex] = undefined; - } - }) - ); -}); diff --git a/src/client/views/collections/CollectionTreeView.scss b/src/client/views/collections/CollectionTreeView.scss index bbbef78b4..2a03ea708 100644 --- a/src/client/views/collections/CollectionTreeView.scss +++ b/src/client/views/collections/CollectionTreeView.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .collectionTreeView-container { transform-origin: top left; @@ -12,7 +12,7 @@ width: 100%; position: relative; top: 0; - // background: $light-gray; + // background: global.$light-gray; font-size: 13px; overflow: auto; user-select: none; @@ -21,7 +21,7 @@ ul { list-style: none; - padding-left: $TREE_BULLET_WIDTH; + padding-left: global.$TREE_BULLET_WIDTH; margin-bottom: 1px; // otherwise vertical scrollbars may pop up for no apparent reason.... > .contentFittingDocumentView { width: unset; @@ -47,7 +47,7 @@ } .delete-button { - color: $medium-gray; + color: global.$medium-gray; // float: right; margin-left: 15px; // margin-top: 3px; @@ -90,7 +90,7 @@ .collectionTreeView-subtitle { font-style: italic; font-size: 8pt; - color: $medium-gray; + color: global.$medium-gray; } .docContainer { diff --git a/src/client/views/collections/CollectionView.scss b/src/client/views/collections/CollectionView.scss index de53a2c62..06c324bd0 100644 --- a/src/client/views/collections/CollectionView.scss +++ b/src/client/views/collections/CollectionView.scss @@ -1,10 +1,10 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .collectionView { border-width: 0; - border-color: $light-gray; + border-color: global.$light-gray; border-style: solid; - border-radius: 0 0 $border-radius $border-radius; + border-radius: 0 0 global.$border-radius global.$border-radius; box-sizing: border-box; border-radius: inherit; width: 100%; diff --git a/src/client/views/collections/CollectionView.tsx b/src/client/views/collections/CollectionView.tsx index 6f0833a22..7ba8989ce 100644 --- a/src/client/views/collections/CollectionView.tsx +++ b/src/client/views/collections/CollectionView.tsx @@ -15,12 +15,14 @@ import { ContextMenuProps } from '../ContextMenuItem'; import { ViewBoxAnnotatableComponent } from '../DocComponent'; import { FieldView } from '../nodes/FieldView'; import { OpenWhere } from '../nodes/OpenWhere'; +import { CalendarBox } from '../nodes/calendarBox/CalendarBox'; import { CollectionCardView } from './CollectionCardDeckView'; import { CollectionCarousel3DView } from './CollectionCarousel3DView'; import { CollectionCarouselView } from './CollectionCarouselView'; import { CollectionDockingView } from './CollectionDockingView'; import { CollectionNoteTakingView } from './CollectionNoteTakingView'; import { CollectionPileView } from './CollectionPileView'; +import { CollectionPivotView } from './CollectionPivotView'; import { CollectionStackingView } from './CollectionStackingView'; import { CollectionViewProps, SubCollectionViewProps } from './CollectionSubView'; import { CollectionTimeView } from './CollectionTimeView'; @@ -32,7 +34,6 @@ import { CollectionLinearView } from './collectionLinear'; import { CollectionMulticolumnView } from './collectionMulticolumn/CollectionMulticolumnView'; import { CollectionMultirowView } from './collectionMulticolumn/CollectionMultirowView'; import { CollectionSchemaView } from './collectionSchema/CollectionSchemaView'; -import { CalendarBox } from '../nodes/calendarBox/CalendarBox'; @observer export class CollectionView extends ViewBoxAnnotatableComponent<CollectionViewProps>() { @@ -89,6 +90,8 @@ export class CollectionView extends ViewBoxAnnotatableComponent<CollectionViewPr TraceMobx(); if (type === undefined) return null; switch (type) { + default: + case CollectionViewType.Freeform: return <CollectionFreeFormView key="collview" {...props} />; case CollectionViewType.Schema: return <CollectionSchemaView key="collview" {...props} />; case CollectionViewType.Calendar: return <CalendarBox key="collview" {...props} />; case CollectionViewType.Docking: return <CollectionDockingView key="collview" {...props} />; @@ -103,10 +106,9 @@ export class CollectionView extends ViewBoxAnnotatableComponent<CollectionViewPr case CollectionViewType.NoteTaking: return <CollectionNoteTakingView key="collview" {...props} />; case CollectionViewType.Masonry: return <CollectionStackingView key="collview" {...props} />; case CollectionViewType.Time: return <CollectionTimeView key="collview" {...props} />; + case CollectionViewType.Pivot: return <CollectionPivotView key="collview" {...props} />; case CollectionViewType.Grid: return <CollectionGridView key="collview" {...props} />; case CollectionViewType.Card: return <CollectionCardView key="collview" {...props} />; - case CollectionViewType.Freeform: - default: return <CollectionFreeFormView key="collview" {...props} />; } }; @@ -126,7 +128,8 @@ export class CollectionView extends ViewBoxAnnotatableComponent<CollectionViewPr { description: 'Carousel', event: () => func(CollectionViewType.Carousel), icon: 'columns' }, { description: '3D Carousel', event: () => func(CollectionViewType.Carousel3D), icon: 'columns' }, { description: 'Calendar', event: () => func(CollectionViewType.Calendar), icon: 'columns' }, - { description: 'Pivot/Time', event: () => func(CollectionViewType.Time), icon: 'columns' }, + { description: 'Pivot', event: () => func(CollectionViewType.Pivot), icon: 'columns' }, + { description: 'Time', event: () => func(CollectionViewType.Time), icon: 'columns' }, { description: 'Map', event: () => func(CollectionViewType.Map), icon: 'globe-americas' }, { description: 'Grid', event: () => func(CollectionViewType.Grid), icon: 'th-list' }, ]; diff --git a/src/client/views/collections/TabDocView.scss b/src/client/views/collections/TabDocView.scss index dd4c0b881..397e35ca9 100644 --- a/src/client/views/collections/TabDocView.scss +++ b/src/client/views/collections/TabDocView.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .tabDocView-content { height: 100%; diff --git a/src/client/views/collections/TreeView.scss b/src/client/views/collections/TreeView.scss index 2ab1a5ac1..78794d112 100644 --- a/src/client/views/collections/TreeView.scss +++ b/src/client/views/collections/TreeView.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .treeView-label { max-height: 1.5em; @@ -14,7 +14,7 @@ .bullet-outline { position: relative; width: fit-content; - color: $medium-gray; + color: global.$medium-gray; transform: scale(0.5); display: inline-flex; align-items: center; @@ -66,7 +66,7 @@ min-height: 20px; min-width: 15px; margin-right: 3px; - color: $medium-gray; + color: global.$medium-gray; border: #80808030 1px solid; border-radius: 5px; z-index: 1; diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx index bebdbd731..241a56a88 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormLayoutEngines.tsx @@ -4,7 +4,7 @@ import { Id, ToString } from '../../../../fields/FieldSymbols'; import { ObjectField } from '../../../../fields/ObjectField'; import { RefField } from '../../../../fields/RefField'; import { listSpec } from '../../../../fields/Schema'; -import { Cast, NumCast, StrCast } from '../../../../fields/Types'; +import { Cast, DateCast, NumCast, StrCast } from '../../../../fields/Types'; import { aggregateBounds } from '../../../../Utils'; export interface ViewDefBounds { @@ -107,7 +107,7 @@ export function computePassLayout(poolData: Map<string, PoolData>, pivotDoc: Doc } function toNumber(val: FieldResult<FieldType>) { - return val === undefined ? undefined : NumCast(val, Number(StrCast(val))); + return val === undefined ? undefined : DateCast(val) ? DateCast(val).date.getMilliseconds() : NumCast(val, Number(StrCast(val))); } export function computeStarburstLayout(poolData: Map<string, PoolData>, pivotDoc: Doc, childPairs: { layout: Doc; data?: Doc }[], panelDim: number[], viewDefsToJSX: (views: ViewDefBounds[]) => ViewDefResult[] /* , engineProps: any */) { @@ -295,7 +295,7 @@ export function computeTimelineLayout(poolData: Map<string, PoolData>, pivotDoc: let minTime = minTimeReq === undefined ? Number.MAX_VALUE : minTimeReq; let maxTime = maxTimeReq === undefined ? -Number.MAX_VALUE : maxTimeReq; childPairs.forEach(pair => { - const num = NumCast(pair.layout[timelineFieldKey], Number(StrCast(pair.layout[timelineFieldKey]))); + const num = toNumber(pair.layout[timelineFieldKey]) ?? 0; if (!isNaN(num) && (!minTimeReq || num >= minTimeReq) && (!maxTimeReq || num <= maxTimeReq)) { !pivotDateGroups.get(num) && pivotDateGroups.set(num, []); pivotDateGroups.get(num)!.push(pair.layout); diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss index 46bd37f6d..cce0ff684 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.scss @@ -1,4 +1,4 @@ -@import '../../global/globalCssVariables.module.scss'; +@use '../../global/globalCssVariables.module.scss' as global; .collectionfreeformview-none { position: inherit; @@ -32,9 +32,9 @@ .collectionfreeformview-mask-empty, .collectionfreeformview-mask { z-index: 5000; - width: $INK_MASK_SIZE; - height: $INK_MASK_SIZE; - transform: translate($INK_MASK_SIZE_HALF, $INK_MASK_SIZE_HALF); + width: global.$INK_MASK_SIZE; + height: global.$INK_MASK_SIZE; + transform: translate(global.$INK_MASK_SIZE_HALF, global.$INK_MASK_SIZE_HALF); pointer-events: none; position: absolute; background-color: transparent; @@ -211,11 +211,11 @@ //nested freeform views // .collectionfreeformview-container { - // background-image: linear-gradient(to right, $light-color-secondary 1px, transparent 1px), - // linear-gradient(to bottom, $light-color-secondary 1px, transparent 1px); + // background-image: linear-gradient(to right, global.$light-color-secondary 1px, transparent 1px), + // linear-gradient(to bottom, global.$light-color-secondary 1px, transparent 1px); // background-size: 30px 30px; // } - border: 0px solid $light-gray; + border: 0px solid global.$light-gray; border-radius: inherit; box-sizing: border-box; position: absolute; @@ -233,7 +233,7 @@ box-sizing: border-box; width: 98%; height: 98%; - border-radius: $border-radius; + border-radius: global.$border-radius; } //this is an animation for the blinking cursor! diff --git a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx index 3c31b584e..43addfc29 100644 --- a/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx +++ b/src/client/views/collections/collectionFreeForm/CollectionFreeFormView.tsx @@ -30,7 +30,7 @@ import { CompileScript } from '../../../util/Scripting'; import { ScriptingGlobals } from '../../../util/ScriptingGlobals'; import { freeformScrollMode, SnappingManager } from '../../../util/SnappingManager'; import { Transform } from '../../../util/Transform'; -import { undoable, undoBatch, UndoManager } from '../../../util/UndoManager'; +import { undoable, UndoManager } from '../../../util/UndoManager'; import { Timeline } from '../../animationtimeline/Timeline'; import { ContextMenu } from '../../ContextMenu'; import { InkingStroke } from '../../InkingStroke'; @@ -344,7 +344,7 @@ export class CollectionFreeFormView extends CollectionSubView<Partial<collection focusOnPoint = (options: FocusViewOptions) => { const { pointFocus, zoomTime, didMove } = options; if (!this.Document.isGroup && pointFocus && !didMove) { - const dfltScale = this.isAnnotationOverlay ? 1 : 0.5; + const dfltScale = this.isAnnotationOverlay ? 1 : 0.25; if (this.layoutDoc[this.scaleFieldKey] !== dfltScale) { this.zoomSmoothlyAboutPt(this.screenToFreeformContentsXf.transformPoint(pointFocus.X, pointFocus.Y), dfltScale, zoomTime); options.didMove = true; @@ -1230,47 +1230,15 @@ export class CollectionFreeFormView extends CollectionSubView<Partial<collection }; @action - showSmartDraw = (x: number, y: number) => { - SmartDrawHandler.Instance.CreateDrawingDoc = this.createDrawingDoc; - SmartDrawHandler.Instance.RemoveDrawing = this.removeDrawing; - SmartDrawHandler.Instance.AddDrawing = this.addDrawing; - SmartDrawHandler.Instance.displaySmartDrawHandler(x, y, NumCast(this.layoutDoc[this.scaleFieldKey])); + showSmartDraw = (x: number, y: number, regenerate?: boolean) => { + const sm = SmartDrawHandler.Instance; + sm.RemoveDrawing = this.removeDrawing; + sm.AddDrawing = this.addDrawing; + (regenerate ? sm.displayRegenerate : sm.displaySmartDrawHandler)(x, y, NumCast(this.layoutDoc[this.scaleFieldKey])); }; _drawing: Doc[] = []; _drawingContainer: Doc | undefined = undefined; - /** - * Function that creates a drawing--a group of ink strokes--to go with the smart draw function. - */ - @undoBatch - createDrawingDoc = (strokeData: [InkData, string, string][], opts: DrawingOptions) => { - this._drawing = []; - const xf = this.screenToFreeformContentsXf; - strokeData.forEach((stroke: [InkData, string, string]) => { - const bounds = InkField.getBounds(stroke[0]); - const B = xf.transformBounds(bounds.left, bounds.top, bounds.width, bounds.height); - const inkWidth = ActiveInkWidth() * this.ScreenToLocalBoxXf().Scale; - const inkDoc = Docs.Create.InkDocument( - stroke[0], - { title: 'stroke', - x: B.x - inkWidth / 2, - y: B.y - inkWidth / 2, - _width: B.width + inkWidth, - _height: B.height + inkWidth, - stroke_showLabel: BoolCast(Doc.UserDoc().activeHideTextLabels)}, // prettier-ignore - inkWidth, - opts.autoColor ? stroke[1] : ActiveInkColor(), - ActiveInkBezierApprox(), - stroke[2] === 'none' ? ActiveInkFillColor() : stroke[2], - ActiveInkArrowStart(), - ActiveInkArrowEnd(), - ActiveInkDash(), - ActiveIsInkMask() - ); - this._drawing.push(inkDoc); - }); - return MarqueeView.getCollection(this._drawing, undefined, true, { left: opts.x, top: opts.y, width: 1, height: 1 }); - }; /** * Part of regenerating a drawing--deletes the old drawing. @@ -1291,9 +1259,9 @@ export class CollectionFreeFormView extends CollectionSubView<Partial<collection /** * Adds the created drawing to the freeform canvas and sets the metadata. */ - addDrawing = (doc: Doc, opts: DrawingOptions, gptRes: string) => { + addDrawing = (doc: Doc, opts: DrawingOptions, gptRes: string, x?: number, y?: number) => { const docData = doc[DocData]; - docData.title = opts.text.match(/^(.*?)~~~.*$/)?.[1] || opts.text; + docData.title = opts.text; docData._width = opts.size; docData.ai_drawing_input = opts.text; docData.ai_drawing_complexity = opts.complexity; @@ -1302,6 +1270,9 @@ export class CollectionFreeFormView extends CollectionSubView<Partial<collection docData.ai_drawing_data = gptRes; docData.ai = 'gpt'; this._drawingContainer = doc; + if (x !== undefined && y !== undefined) { + [doc.x, doc.y] = this.screenToFreeformContentsXf.transformPoint(x, y); + } this.addDocument(doc); this._batch?.end(); }; @@ -2003,7 +1974,6 @@ export class CollectionFreeFormView extends CollectionSubView<Partial<collection optionItems.push({ description: 'Regenerate AI Drawing', event: action(() => { - SmartDrawHandler.Instance.CreateDrawingDoc = this.createDrawingDoc; SmartDrawHandler.Instance.AddDrawing = this.addDrawing; SmartDrawHandler.Instance.RemoveDrawing = this.removeDrawing; !SmartDrawHandler.Instance.ShowRegenerate ? SmartDrawHandler.Instance.displayRegenerate(this._downX, this._downY - 10) : SmartDrawHandler.Instance.hideRegenerate(); diff --git a/src/client/views/collections/collectionFreeForm/ImageLabelHandler.tsx b/src/client/views/collections/collectionFreeForm/ImageLabelHandler.tsx index f050b9846..1a44e094d 100644 --- a/src/client/views/collections/collectionFreeForm/ImageLabelHandler.tsx +++ b/src/client/views/collections/collectionFreeForm/ImageLabelHandler.tsx @@ -9,7 +9,8 @@ import { MarqueeOptionsMenu } from './MarqueeOptionsMenu'; import './ImageLabelHandler.scss'; @observer -export class ImageLabelHandler extends ObservableReactComponent<{}> { +export class ImageLabelHandler extends ObservableReactComponent<object> { + // eslint-disable-next-line no-use-before-define static Instance: ImageLabelHandler; @observable _display: boolean = false; @@ -19,11 +20,10 @@ export class ImageLabelHandler extends ObservableReactComponent<{}> { @observable _currentLabel: string = ''; @observable _labelGroups: string[] = []; - constructor(props: any) { + constructor(props: object) { super(props); makeObservable(this); ImageLabelHandler.Instance = this; - console.log('Instantiated label handler!'); } @action @@ -41,8 +41,8 @@ export class ImageLabelHandler extends ObservableReactComponent<{}> { }; @action - addLabel = (label: string) => { - label = label.toUpperCase().trim(); + addLabel = (labelIn: string) => { + const label = labelIn.toUpperCase().trim(); if (label.length > 0) { if (!this._labelGroups.includes(label)) { this._labelGroups = [...this._labelGroups, label]; @@ -96,10 +96,10 @@ export class ImageLabelHandler extends ObservableReactComponent<{}> { <div> {this._labelGroups.map(group => { return ( - <div> + <div key={group}> <p>{group}</p> <IconButton - tooltip={'Remove Label'} + tooltip="Remove Label" onPointerDown={() => { this.removeLabel(group); }} diff --git a/src/client/views/collections/collectionGrid/CollectionGridView.scss b/src/client/views/collections/collectionGrid/CollectionGridView.scss index 845b07c51..4edaf9745 100644 --- a/src/client/views/collections/collectionGrid/CollectionGridView.scss +++ b/src/client/views/collections/collectionGrid/CollectionGridView.scss @@ -21,11 +21,11 @@ width: 100%; } - .react-grid-item>.react-resizable-handle { + .react-grid-item > .react-resizable-handle { z-index: 4; // doesn't work on prezi otherwise } - .react-grid-item>.react-resizable-handle::after { + .react-grid-item > .react-resizable-handle::after { // grey so it can be seen on the audiobox border-right: 2px solid slategrey; border-bottom: 2px solid slategrey; @@ -41,7 +41,6 @@ position: absolute; height: 3; left: 5; - top: 30; transform-origin: left; transform: rotate(90deg); outline: none; @@ -103,7 +102,7 @@ span::before, span::after { - content: ""; + content: ''; width: 50%; position: relative; display: inline-block; @@ -128,10 +127,8 @@ } } } - } - /* Chrome, Safari, Edge, Opera */ input::-webkit-outer-spin-button, input::-webkit-inner-spin-button { @@ -140,6 +137,6 @@ input::-webkit-inner-spin-button { } /* Firefox */ -input[type=number] { +input[type='number'] { -moz-appearance: textfield; -}
\ No newline at end of file +} diff --git a/src/client/views/collections/collectionGrid/CollectionGridView.tsx b/src/client/views/collections/collectionGrid/CollectionGridView.tsx index 6dffb80f1..80bf4bd12 100644 --- a/src/client/views/collections/collectionGrid/CollectionGridView.tsx +++ b/src/client/views/collections/collectionGrid/CollectionGridView.tsx @@ -9,7 +9,7 @@ import { emptyFunction } from '../../../../Utils'; import { Docs } from '../../../documents/Documents'; import { DragManager } from '../../../util/DragManager'; import { Transform } from '../../../util/Transform'; -import { undoable, undoBatch } from '../../../util/UndoManager'; +import { undoable } from '../../../util/UndoManager'; import { ContextMenu } from '../../ContextMenu'; import { ContextMenuProps } from '../../ContextMenuItem'; import { DocumentView } from '../../nodes/DocumentView'; @@ -22,9 +22,9 @@ export class CollectionGridView extends CollectionSubView() { private _containerRef: React.RefObject<HTMLDivElement> = React.createRef(); private _changeListenerDisposer: Opt<Lambda>; // listens for changes in this.childLayoutPairs private _resetListenerDisposer: Opt<Lambda>; // listens for when the reset button is clicked + private _dropLocation: object = {}; // sets the drop location for external drops @observable private _rowHeight: Opt<number> = undefined; // temporary store of row height to make change undoable @observable private _scroll: number = 0; // required to make sure the decorations box container updates on scroll - private dropLocation: object = {}; // sets the drop location for external drops constructor(props: SubCollectionViewProps) { super(props); @@ -48,14 +48,20 @@ export class CollectionGridView extends CollectionSubView() { } @computed get colWidthPlusGap() { - return (this._props.PanelWidth() - this.margin) / this.numCols; + return (this._props.PanelWidth() - 2 * this.xMargin - this.gridGap) / this.numCols; } @computed get rowHeightPlusGap() { - return this.rowHeight + this.margin; + return this.rowHeight + this.gridGap; } - @computed get margin() { - return NumCast(this.Document.margin, 10); + @computed get xMargin() { + return NumCast(this.layoutDoc._xMargin, Math.max(3, 0.05 * this._props.PanelWidth())); + } + @computed get yMargin() { + return this._props.yPadding || NumCast(this.layoutDoc._yMargin, Math.min(5, 0.05 * this._props.PanelWidth())); + } + @computed get gridGap() { + return NumCast(this.Document._gridGap, 10); } // sets the margin between grid nodes @computed get flexGrid() { @@ -77,10 +83,10 @@ export class CollectionGridView extends CollectionSubView() { pairs.forEach((pair, i) => { const existing = oldLayouts.find(l => l.i === pair.layout[Id]); if (existing) newLayouts.push(existing); - else if (Object.keys(this.dropLocation).length) { + else if (Object.keys(this._dropLocation).length) { // external drop - this.addLayoutItem(newLayouts, this.makeLayoutItem(pair.layout, this.dropLocation as { x: number; y: number }, !this.flexGrid)); - this.dropLocation = {}; + this.addLayoutItem(newLayouts, this.makeLayoutItem(pair.layout, this._dropLocation as { x: number; y: number }, !this.flexGrid)); + this._dropLocation = {}; } else { // internal drop this.addLayoutItem(newLayouts, this.makeLayoutItem(pair.layout, this.unflexedPosition(i), !this.flexGrid)); @@ -115,30 +121,29 @@ export class CollectionGridView extends CollectionSubView() { * @returns the default location of the grid node (i.e. when the grid is static) * @param index */ - unflexedPosition(index: number): Omit<Layout, 'i'> { - return { - x: (index % (Math.floor(this.numCols / this.defaultW) || 1)) * this.defaultW, - y: Math.floor(index / (Math.floor(this.numCols / this.defaultH) || 1)) * this.defaultH, - w: this.defaultW, - h: this.defaultH, - static: true, - }; - } + unflexedPosition = (index: number): Omit<Layout, 'i'> => ({ + x: (index % (Math.floor(this.numCols / this.defaultW) || 1)) * this.defaultW, + y: Math.floor(index / (Math.floor(this.numCols / this.defaultH) || 1)) * this.defaultH, + w: this.defaultW, + h: this.defaultH, + static: true, + }); /** * Maps the x- and y- coordinates of the event to a grid cell. */ - screenToCell(sx: number, sy: number) { - const pt = this.ScreenToLocalBoxXf().transformPoint(sx, sy); - const x = Math.floor(pt[0] / this.colWidthPlusGap); - const y = Math.floor((pt[1] + this._scroll) / this.rowHeight); + screenToCell = (sx: number, sy: number) => { + const [ptx, pty] = this.ScreenToLocalBoxXf().transformPoint(sx, sy); + const x = Math.floor((ptx + this.xMargin) / this.colWidthPlusGap); + const y = Math.floor((pty + this.yMargin + this._scroll) / this.rowHeight); return { x, y }; - } + }; /** * Creates a layout object for a grid item */ - makeLayoutItem = (doc: Doc, pos: { x: number; y: number }, Static: boolean = false, w: number = this.defaultW, h: number = this.defaultH) => ({ i: doc[Id], w, h, x: pos.x, y: pos.y, static: Static }); + makeLayoutItem = (doc: Doc, pos: { x: number; y: number }, Static: boolean = false, w: number = this.defaultW, h: number = this.defaultH) => + ({ i: doc[Id], w, h, x: pos.x, y: pos.y, static: Static }); // prettier-ignore /** * Adds a layout to the list of layouts. @@ -152,9 +157,9 @@ export class CollectionGridView extends CollectionSubView() { /** * @returns the transform that will correctly place the document decorations box. */ - private lookupIndividualTransform = (layout: Layout) => { + lookupIndividualTransform = (layout: Layout) => { const xypos = this.flexGrid ? layout : this.unflexedPosition(this.renderedLayoutList.findIndex(l => l.i === layout.i)); - const pos = { x: xypos.x * this.colWidthPlusGap + this.margin, y: xypos.y * this.rowHeightPlusGap + this.margin - this._scroll }; + const pos = { x: xypos.x * this.colWidthPlusGap + this.gridGap + this.xMargin, y: xypos.y * this.rowHeightPlusGap + this.gridGap - this._scroll + this.yMargin }; return this.ScreenToLocalBoxXf().translate(-pos.x, -pos.y); }; @@ -169,9 +174,9 @@ export class CollectionGridView extends CollectionSubView() { /** * Stores the layout list on the Document as JSON */ - setLayoutList(layouts: Layout[]) { + setLayoutList = (layouts: Layout[]) => { this.Document.gridLayoutString = JSON.stringify(layouts); - } + }; isContentActive = () => this._props.isSelected() || this._props.isContentActive(); isChildContentActive = () => (this._props.isDocumentActive?.() && (this._props.childDocumentsActive?.() || BoolCast(this.Document.childDocumentsActive)) ? true : undefined); @@ -183,29 +188,27 @@ export class CollectionGridView extends CollectionSubView() { * @param height * @returns the `ContentFittingDocumentView` of the node */ - getDisplayDoc(layout: Doc, dxf: () => Transform, width: () => number, height: () => number) { - return ( - <DocumentView - {...this._props} - Document={layout} - TemplateDataDocument={layout.resolvedDataDoc as Doc} - NativeWidth={returnZero} - NativeHeight={returnZero} - fitWidth={this._props.childLayoutFitWidth} - containerViewPath={this.childContainerViewPath} - renderDepth={this._props.renderDepth + 1} - isContentActive={this.isChildContentActive} - PanelWidth={width} - PanelHeight={height} - ScreenToLocalTransform={dxf} - setContentViewBox={emptyFunction} - whenChildContentsActiveChanged={this._props.whenChildContentsActiveChanged} - onClickScript={this.onChildClickHandler} - dontCenter={StrCast(this.layoutDoc.layout_dontCenter) as 'x' | 'y' | 'xy'} - showTags={BoolCast(this.layoutDoc.showChildTags) || BoolCast(this.Document._layout_showTags)} - /> - ); - } + getDisplayDoc = (layout: Doc, dxf: () => Transform, width: () => number, height: () => number) => ( + <DocumentView + {...this._props} + Document={layout} + TemplateDataDocument={layout.resolvedDataDoc as Doc} + NativeWidth={returnZero} + NativeHeight={returnZero} + fitWidth={this._props.childLayoutFitWidth} + containerViewPath={this.childContainerViewPath} + renderDepth={this._props.renderDepth + 1} + isContentActive={this.isChildContentActive} + PanelWidth={width} + PanelHeight={height} + ScreenToLocalTransform={dxf} + setContentViewBox={emptyFunction} + whenChildContentsActiveChanged={this._props.whenChildContentsActiveChanged} + onClickScript={this.onChildClickHandler} + dontCenter={StrCast(this.layoutDoc.layout_dontCenter) as 'x' | 'y' | 'xy'} + showTags={BoolCast(this.layoutDoc.showChildTags) || BoolCast(this.Document._layout_showTags)} + /> + ); /** * Saves the layouts received from the Grid to the Document. @@ -238,15 +241,14 @@ export class CollectionGridView extends CollectionSubView() { * @returns a list of `ContentFittingDocumentView`s inside wrapper divs. * The key of the wrapper div must be the same as the `i` value of the corresponding layout. */ - @computed - private get contents(): JSX.Element[] { + @computed get contents(): JSX.Element[] { const collector: JSX.Element[] = []; if (this.renderedLayoutList.length === this.childLayoutPairs.length) { this.renderedLayoutList.forEach(l => { const child = this.childLayoutPairs.find(c => c.layout[Id] === l.i); const dxf = () => this.lookupIndividualTransform(l); - const width = () => (this.flexGrid ? l.w : this.defaultW) * this.colWidthPlusGap - this.margin; - const height = () => (this.flexGrid ? l.h : this.defaultH) * this.rowHeightPlusGap - this.margin; + const width = () => (this.flexGrid ? l.w : this.defaultW) * this.colWidthPlusGap - this.gridGap; + const height = () => (this.flexGrid ? l.h : this.defaultH) * this.rowHeightPlusGap - this.gridGap; child && collector.push( <div key={child.layout[Id]} className={'document-wrapper' + (this.flexGrid && this._props.isSelected() ? '' : ' static')}> @@ -295,7 +297,7 @@ export class CollectionGridView extends CollectionSubView() { * Handles external drop of images/PDFs etc from outside Dash. */ onExternalDrop = async (e: React.DragEvent): Promise<void> => { - this.dropLocation = this.screenToCell(e.clientX, e.clientY); + this._dropLocation = this.screenToCell(e.clientX, e.clientY); super.onExternalDrop(e, {}); }; @@ -316,12 +318,13 @@ export class CollectionGridView extends CollectionSubView() { this, e, returnFalse, - action(() => { - undoable(() => { + undoable( + action(() => { this.Document.gridRowHeight = this._rowHeight; - }, 'changing row height')(); - this._rowHeight = undefined; - }), + this._rowHeight = undefined; + }), + 'changing row height' + ), emptyFunction, false, false @@ -391,14 +394,14 @@ export class CollectionGridView extends CollectionSubView() { <div className="collectionGridView-gridContainer" ref={this._containerRef} - style={{ backgroundColor: StrCast(this.layoutDoc._backgroundColor, 'white') }} + style={{ backgroundColor: StrCast(this.layoutDoc._backgroundColor, 'white'), padding: `${this.yMargin} ${this.xMargin}` }} onWheel={e => e.stopPropagation()} onScroll={action(e => { if (!this._props.isSelected()) e.currentTarget.scrollTop = this._scroll; else this._scroll = e.currentTarget.scrollTop; })}> <Grid - width={this._props.PanelWidth()} + width={this._props.PanelWidth() - 2 * this.xMargin} nodeList={this.contents.length ? this.contents : null} layout={this.contents.length ? this.renderedLayoutList : undefined} childrenDraggable={!!this._props.isSelected()} @@ -408,15 +411,15 @@ export class CollectionGridView extends CollectionSubView() { transformScale={this.ScreenToLocalBoxXf().Scale} compactType={this.compaction} // determines whether nodes should remain in position, be bound to the top, or to the left preventCollision={BoolCast(this.Document.gridPreventCollision)} // determines whether nodes should move out of the way (i.e. collide) when other nodes are dragged over them - margin={this.margin} + margin={this.gridGap} /> <input className="rowHeightSlider" type="range" - style={{ width: this._props.PanelHeight() - 30 }} + style={{ width: this._props.PanelHeight() - 2 * this.yMargin }} min={1} value={this.rowHeight} - max={this._props.PanelHeight() - 30} + max={this._props.PanelHeight() - 2 * this.yMargin} onPointerDown={this.onSliderDown} onChange={this.onSliderChange} /> diff --git a/src/client/views/collections/collectionLinear/CollectionLinearView.scss b/src/client/views/collections/collectionLinear/CollectionLinearView.scss index b8ceec139..0dfaed38a 100644 --- a/src/client/views/collections/collectionLinear/CollectionLinearView.scss +++ b/src/client/views/collections/collectionLinear/CollectionLinearView.scss @@ -1,12 +1,12 @@ -@import '../../global/globalCssVariables.module.scss'; -@import '../../_nodeModuleOverrides'; +@use '../../global/globalCssVariables.module.scss' as global; +// bcz fix @import '../../_nodeModuleOverrides'; .collectionLinearView { width: 100%; } .collectionLinearView-label { color: black; - background-color: $light-gray; + background-color: global.$light-gray; width: 100%; } .collectionLinearView-outer { @@ -32,8 +32,8 @@ } > span { - background: $dark-gray; - color: $white; + background: global.$dark-gray; + color: global.$white; border-radius: 18px; margin-right: 6px; cursor: pointer; @@ -44,7 +44,7 @@ } .bottomPopup-background { - background: $medium-blue; + background: global.$medium-blue; display: flex; border-radius: 10px; height: 35; @@ -55,7 +55,7 @@ } .bottomPopup-text { - color: $white; + color: global.$white; display: inline; white-space: nowrap; padding-left: 8px; @@ -72,7 +72,7 @@ padding-left: 8px; padding-right: 8px; vertical-align: middle; - background-color: $light-gray; + background-color: global.$light-gray; border-radius: 3px; color: black; margin-right: 5px; @@ -86,7 +86,7 @@ padding-left: 8px; padding-right: 8px; vertical-align: middle; - background-color: $close-red; + background-color: global.$close-red; border-radius: 3px; color: black; } @@ -94,13 +94,13 @@ > label { pointer-events: all; cursor: pointer; - background-color: $medium-blue; + background-color: global.$medium-blue; padding: 5; border-radius: 2px; height: 100%; min-width: 25; margin: 0; - color: $white; + color: global.$white; display: flex; font-weight: 100; transition: transform 0.2s; diff --git a/src/client/views/collections/collectionSchema/CollectionSchemaView.scss b/src/client/views/collections/collectionSchema/CollectionSchemaView.scss index 817ceac97..0bf78f57c 100644 --- a/src/client/views/collections/collectionSchema/CollectionSchemaView.scss +++ b/src/client/views/collections/collectionSchema/CollectionSchemaView.scss @@ -1,4 +1,4 @@ -@import '../../global/globalCssVariables.module.scss'; +@use '../../global/globalCssVariables.module.scss' as global; .collectionSchemaView { cursor: default; @@ -7,7 +7,7 @@ flex-direction: row; .schema-table { - background-color: $white; + background-color: global.$white; cursor: grab; width: 100%; @@ -49,10 +49,10 @@ .schema-column-menu, .schema-filter-menu { - background: $light-gray; + background: global.$light-gray; position: absolute; - border: 1px solid $medium-gray; - border-bottom: 2px solid $medium-gray; + border: 1px solid global.$medium-gray; + border-bottom: 2px solid global.$medium-gray; max-height: 201px; display: flex; overflow: hidden; @@ -66,7 +66,7 @@ width: 100%; &:hover { - background-color: $medium-gray; + background-color: global.$medium-gray; } .schema-search-result-type { font-family: 'Courier New', Courier, monospace; @@ -74,8 +74,8 @@ .schema-search-result-type, .schema-search-result-desc { - color: $dark-gray; - font-size: $body-text; + color: global.$dark-gray; + font-size: global.$body-text; } .schema-search-result-desc { font-style: italic; @@ -120,9 +120,9 @@ .schema-column-menu-button { cursor: pointer; padding: 2px 5px; - background: $medium-blue; + background: global.$medium-blue; border-radius: 9999px; - color: $white; + color: global.$white; width: fit-content; margin: 5px; align-self: center; @@ -141,7 +141,7 @@ } .schema-column-header { - background-color: $light-gray; + background-color: global.$light-gray; font-weight: bold; display: flex; flex-direction: row; @@ -149,7 +149,7 @@ align-items: center; padding: 0; z-index: 1; - border: 1px solid $medium-gray; + border: 1px solid global.$medium-gray; .schema-column-title { flex-grow: 2; @@ -175,7 +175,7 @@ cursor: ew-resize; &:hover { - background-color: $light-blue; + background-color: global.$light-blue; } } @@ -188,7 +188,7 @@ min-width: 5px; transform: translate(-3px, 0px); align-self: flex-start; - background-color: $medium-gray; + background-color: global.$medium-gray; }*/ // creates awkward thick gray borders between colheaders } @@ -202,7 +202,7 @@ } .schema-header-row { - background-color: $light-gray; + background-color: global.$light-gray; overflow: hidden; } @@ -226,7 +226,7 @@ .schema-table-cell, .row-menu { - border: 1px solid $medium-gray; + border: 1px solid global.$medium-gray; overflow-x: hidden; overflow-y: auto; display: inline-flex; @@ -264,7 +264,7 @@ .row-menu-infos { position: absolute; top: 3; - left: 3; + left: 3; z-index: 1; display: flex; justify-content: flex-end; @@ -278,7 +278,7 @@ .schema-row-button, .schema-header-button { - color: $dark-gray; + color: global.$dark-gray; margin: 3px; cursor: pointer; display: flex; @@ -294,7 +294,7 @@ width: 17px; height: 17px; border-radius: 30%; - background-color: $dark-gray; + background-color: global.$dark-gray; color: white; margin: 3px; cursor: pointer; @@ -311,5 +311,3 @@ outline: none; height: 100%; } - - diff --git a/src/client/views/global/globalScripts.ts b/src/client/views/global/globalScripts.ts index b44292164..835c28daa 100644 --- a/src/client/views/global/globalScripts.ts +++ b/src/client/views/global/globalScripts.ts @@ -68,6 +68,49 @@ ScriptingGlobals.add(function setView(view: string, shiftKey: boolean, checkResu // toggle: Set overlay status of selected document // eslint-disable-next-line prefer-arrow-callback +ScriptingGlobals.add(function setBorderColor(color?: string, checkResult?: boolean) { + const selectedViews = DocumentView.Selected(); + const defaultBorder = () => StrCast(Doc.UserDoc().borderColor, 'transparent'); + const setDefaultBorder = (c: string) => { Doc.UserDoc().borderColor = c; }; // prettier-ignore + const fieldKey = 'borderColor'; + if (selectedViews.length) { + if (checkResult) { + const selView = selectedViews.lastElement(); + const layoutFrameNumber = Cast(selView.containerViewPath?.().lastElement()?.Document?._currentFrame, 'number'); // frame number that container is at which determines layout frame values + const contentFrameNumber = Cast(selView.Document?._currentFrame, 'number', layoutFrameNumber ?? null); // frame number that content is at which determines what content is displayed + return CollectionFreeFormDocumentView.getStringValues(selView?.Document, contentFrameNumber)[fieldKey] || defaultBorder(); + } + setDefaultBorder(color ?? 'transparent'); + selectedViews.forEach(dv => { + const layoutFrameNumber = Cast(dv.containerViewPath?.().lastElement()?.Document?._currentFrame, 'number'); // frame number that container is at which determines layout frame values + const contentFrameNumber = Cast(dv.Document?._currentFrame, 'number', layoutFrameNumber ?? null); // frame number that content is at which determines what content is displayed + if (contentFrameNumber !== undefined) { + const obj: { [key: string]: Opt<string> } = {}; + obj[fieldKey] = color; + CollectionFreeFormDocumentView.setStringValues(contentFrameNumber, dv.Document, obj); + } else { + const dataKey = Doc.LayoutFieldKey(dv.Document); + const alternate = (dv.layoutDoc[dataKey + '_usePath'] ? '_' + dv.layoutDoc[dataKey + '_usePath'] : '').replace(':hover', ''); + dv.layoutDoc[fieldKey + alternate] = undefined; + dv.dataDoc[fieldKey + alternate] = color; + } + }); + } else { + const selected = DocumentView.SelectedDocs().length ? DocumentView.SelectedDocs() : LinkManager.Instance.currentLink ? [LinkManager.Instance.currentLink] : []; + if (checkResult) { + return (selected.lastElement() ?? Doc.UserDoc()).borderColor ?? defaultBorder(); + } + if (!selected.length) setDefaultBorder(color ?? 'transparent'); + else + selected.forEach(doc => { + doc[DocData].borderColor = color; + }); + } + return ''; +}); + +// toggle: Set overlay status of selected document +// eslint-disable-next-line prefer-arrow-callback ScriptingGlobals.add(function setBackgroundColor(color?: string, checkResult?: boolean) { const selectedViews = DocumentView.Selected(); const selectedDoc = selectedViews.lastElement()?.Document; @@ -84,7 +127,7 @@ ScriptingGlobals.add(function setBackgroundColor(color?: string, checkResult?: b const contentFrameNumber = Cast(selView.Document?._currentFrame, 'number', layoutFrameNumber ?? null); // frame number that content is at which determines what content is displayed return CollectionFreeFormDocumentView.getStringValues(selView?.Document, contentFrameNumber)[fieldKey] || defaultFill(); } - setDefaultFill(color ?? 'transparent'); + !selectedViews.length && setDefaultFill(color ?? 'transparent'); selectedViews.forEach(dv => { const fieldKey = dv.Document._layout_isSvg ? 'fillColor' : 'backgroundColor'; const layoutFrameNumber = Cast(dv.containerViewPath?.().lastElement()?.Document?._currentFrame, 'number'); // frame number that container is at which determines layout frame values @@ -152,7 +195,7 @@ ScriptingGlobals.add(function toggleOverlay(checkResult?: boolean) { // eslint-disable-next-line prefer-arrow-callback ScriptingGlobals.add(function showFreeform( - attr: 'flashcards' | 'hcenter' | 'vcenter' | 'grid' | 'snaplines' | 'clusters' | 'viewAll' | 'fitOnce' | 'time' | 'docType' | 'color' | 'chat' | 'up' | 'down' | 'toggle-chat' | 'toggle-tags' | 'tag', + attr: 'flashcards' | 'hcenter' | 'vcenter' | 'grid' | 'snaplines' | 'clusters' | 'viewAll' | 'fitOnce' | 'time' | 'docType' | 'color' | 'chat' | 'reverse' | 'toggle-chat' | 'toggle-tags' | 'tag', checkResult?: boolean, persist?: boolean ) { @@ -163,7 +206,7 @@ ScriptingGlobals.add(function showFreeform( } // prettier-ignore - const map: Map<'flashcards' | 'hcenter' | 'vcenter' | 'grid' | 'snaplines' | 'clusters' | 'viewAll' | 'fitOnce' | 'time' | 'docType' | 'color' | 'chat' | 'up' | 'down'| 'toggle-chat' | 'toggle-tags' | 'tag', + const map: Map<'flashcards' | 'hcenter' | 'vcenter' | 'grid' | 'snaplines' | 'clusters' | 'viewAll' | 'fitOnce' | 'time' | 'docType' | 'color' | 'chat' | 'reverse'| 'toggle-chat' | 'toggle-tags' | 'tag', { waitForRender?: boolean; checkResult: (doc: Doc) => boolean; @@ -214,29 +257,20 @@ ScriptingGlobals.add(function showFreeform( checkResult: (doc: Doc) => StrCast(doc?.[Doc.LayoutFieldKey(doc)+"_sort"]) === "tag", setDoc: (doc: Doc, dv: DocumentView) => { doc[Doc.LayoutFieldKey(doc)+"_sort"] === "tag" ? doc[Doc.LayoutFieldKey(doc)+"_sort"] = '' : doc[Doc.LayoutFieldKey(doc)+"_sort"] = docSortings.Tag}, // prettier-ignore }], - ['up', { - checkResult: (doc: Doc) => BoolCast(!doc?.[Doc.LayoutFieldKey(doc)+"_sort_desc"]), - setDoc: (doc: Doc, dv: DocumentView) => { doc[Doc.LayoutFieldKey(doc)+"_sort_desc"] = undefined; }, - }], - ['down', { - checkResult: (doc: Doc) => BoolCast(doc?.[Doc.LayoutFieldKey(doc)+"_sort_desc"]), - setDoc: (doc: Doc, dv: DocumentView) => { doc[Doc.LayoutFieldKey(doc)+"_sort_desc"] = true; }, + ['reverse', { + checkResult: (doc: Doc) => BoolCast(doc?.[Doc.LayoutFieldKey(doc)+"_sort_reverse"]), + setDoc: (doc: Doc, dv: DocumentView) => { doc[Doc.LayoutFieldKey(doc)+"_sort_reverse"] = !doc[Doc.LayoutFieldKey(doc)+"_sort_reverse"]; }, }], ['toggle-chat', { - checkResult: (doc: Doc) => GPTPopup.Instance.Visible, + checkResult: (doc: Doc) => SnappingManager.ChatVisible, setDoc: (doc: Doc, dv: DocumentView) => { - if (GPTPopup.Instance.Visible){ + if (SnappingManager.ChatVisible){ doc[Doc.LayoutFieldKey(doc)+"_sort"] = ''; - GPTPopup.Instance.setVisible(false); - + SnappingManager.SetChatVisible(false); } else { - GPTPopup.Instance.setVisible(true); - GPTPopup.Instance.setMode(GPTPopupMode.CARD); - GPTPopup.Instance.setCardsDoneLoading(true); - + SnappingManager.SetChatVisible(true); + GPTPopup.Instance.setMode(GPTPopupMode.GPT_MENU); } - - }, }], ['toggle-tags', { @@ -417,6 +451,18 @@ ScriptingGlobals.add(function activeEraserTool() { return StrCast(Doc.UserDoc().activeEraserTool, InkEraserTool.Stroke); }, 'returns the current eraser tool'); +// eslint-disable-next-line prefer-arrow-callback +ScriptingGlobals.add(function setBorderWidth(value: number, checkResult?: boolean) { + const selected = DocumentView.SelectedDocs().lastElement(); + if (checkResult) return NumCast((selected ?? Doc.UserDoc()).borderWidth); + if (!selected) Doc.UserDoc().borderWidth = value; + else + DocumentView.SelectedDocs().map(doc => { + doc.borderWidth = value; + }); + return undefined; +}, 'sets the border width of the selected document'); + // toggle: Set overlay status of selected document // eslint-disable-next-line prefer-arrow-callback ScriptingGlobals.add(function setInkProperty(option: InkProperty, value: string | number, checkResult?: boolean) { diff --git a/src/client/views/linking/LinkMenu.scss b/src/client/views/linking/LinkMenu.scss index 636b6415c..ebf60b287 100644 --- a/src/client/views/linking/LinkMenu.scss +++ b/src/client/views/linking/LinkMenu.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .linkMenu { width: auto; diff --git a/src/client/views/linking/LinkMenuItem.scss b/src/client/views/linking/LinkMenuItem.scss index 66ddd6eca..3cd60c87f 100644 --- a/src/client/views/linking/LinkMenuItem.scss +++ b/src/client/views/linking/LinkMenuItem.scss @@ -1,7 +1,7 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .linkMenu-item { - // border-top: 0.5px solid $medium-gray; + // border-top: 0.5px solid global.$medium-gray; position: relative; display: flex; border-top: 0.5px solid #cdcdcd; @@ -120,7 +120,7 @@ border-radius: 50%; pointer-events: auto; background-color: red; - color: $white; + color: global.$white; font-size: 65%; transition: transform 0.2s; text-align: center; @@ -138,7 +138,7 @@ } &:hover { - background: $medium-gray; + background: global.$medium-gray; cursor: pointer; } } diff --git a/src/client/views/newlightbox/ButtonMenu/ButtonMenu.scss b/src/client/views/newlightbox/ButtonMenu/ButtonMenu.scss index 74fbfbb2c..cb1e11780 100644 --- a/src/client/views/newlightbox/ButtonMenu/ButtonMenu.scss +++ b/src/client/views/newlightbox/ButtonMenu/ButtonMenu.scss @@ -1,15 +1,15 @@ -@import '../NewLightboxStyles.scss'; +@use '../NewLightboxStyles.scss' as newstyles; .newLightboxButtonMeny-container { width: 100vw; height: 100vh; - + &.dark { - background: $black; + background: newstyles.$black; } - + &.light, &.default { - background: $white; + background: newstyles.$white; } -}
\ No newline at end of file +} diff --git a/src/client/views/newlightbox/ExploreView/ExploreView.scss b/src/client/views/newlightbox/ExploreView/ExploreView.scss index 5a8ab2f87..2c264c514 100644 --- a/src/client/views/newlightbox/ExploreView/ExploreView.scss +++ b/src/client/views/newlightbox/ExploreView/ExploreView.scss @@ -1,4 +1,4 @@ -@import '../NewLightboxStyles.scss'; +@use '../NewLightboxStyles.scss' as newstyles; .exploreView-container { width: 100%; @@ -6,39 +6,39 @@ border-radius: 20px; position: relative; // transform: scale(1); - background: $gray-l1; - border-top: $standard-border; - border-color: $gray-l2; + background: newstyles.$gray-l1; + border-top: newstyles.$standard-border; + border-color: newstyles.$gray-l2; border-radius: 0px 0px 20px 20px; transform-origin: 50% 50%; overflow: hidden; &.dark { - background: $black; + background: newstyles.$black; } - + &.light, &.default { - background: $gray-l1; + background: newstyles.$gray-l1; } .exploreView-doc { - width: 60px; - height: 80px; - position: absolute; - background: $blue-l2; - // opacity: 0.8; - transform-origin: 50% 50%; - transform: translate(-50%, -50%) scale(1); - cursor: pointer; - transition: 0.2s ease; - overflow: hidden; - font-size: 9px; - padding: 10px; - border-radius: 5px; + width: 60px; + height: 80px; + position: absolute; + background: newstyles.$blue-l2; + // opacity: 0.8; + transform-origin: 50% 50%; + transform: translate(-50%, -50%) scale(1); + cursor: pointer; + transition: 0.2s ease; + overflow: hidden; + font-size: 9px; + padding: 10px; + border-radius: 5px; - &:hover { - transform: translate(calc(-50% * 1.125), calc(-50% * 1.125)) scale(1.5); - } + &:hover { + transform: translate(calc(-50% * 1.125), calc(-50% * 1.125)) scale(1.5); + } } -}
\ No newline at end of file +} diff --git a/src/client/views/newlightbox/Header/LightboxHeader.scss b/src/client/views/newlightbox/Header/LightboxHeader.scss index a9e60ea98..5b316890d 100644 --- a/src/client/views/newlightbox/Header/LightboxHeader.scss +++ b/src/client/views/newlightbox/Header/LightboxHeader.scss @@ -1,9 +1,9 @@ -@import '../NewLightboxStyles.scss'; +@use '../NewLightboxStyles.scss' as newstyles; .newLightboxHeader-container { width: 100%; height: 100%; - background: $gray-l1; + background: newstyles.$gray-l1; border-radius: 20px 20px 0px 0px; padding: 20px; display: grid; @@ -29,13 +29,13 @@ grid-row: 2; .type { padding: 2px 7px !important; - background: $gray-l2; + background: newstyles.$gray-l2; } } .lb-label { - color: $gray-l3; - font-weight: $h1-weight; + color: newstyles.$gray-l3; + font-weight: newstyles.$h1-weight; } .lb-button { @@ -47,25 +47,25 @@ justify-content: space-evenly; align-items: center; transition: 0.2s ease; - gap: 5px; - font-size: $body-size; + gap: 5px; + font-size: newstyles.$body-size; height: fit-content; &:hover { - background: $gray-l2; + background: newstyles.$gray-l2; } &.true { - background: $blue-l1; + background: newstyles.$blue-l1; } } - + &.dark { - background: $black; + background: newstyles.$black; } - + &.light, &.default { - background: $white; + background: newstyles.$white; } -}
\ No newline at end of file +} diff --git a/src/client/views/newlightbox/RecommendationList/RecommendationList.scss b/src/client/views/newlightbox/RecommendationList/RecommendationList.scss index 40dd47e47..99c935e0c 100644 --- a/src/client/views/newlightbox/RecommendationList/RecommendationList.scss +++ b/src/client/views/newlightbox/RecommendationList/RecommendationList.scss @@ -1,4 +1,4 @@ -@import '../NewLightboxStyles.scss'; +@use '../NewLightboxStyles.scss' as newstyles; .recommendationlist-container { height: calc(100% - 40px); @@ -7,111 +7,110 @@ overflow-y: scroll; .recommendations { - height: fit-content; - padding: 20px; - display: flex; - flex-direction: column; - gap: 20px; - background: $gray-l1; - border-radius: 0px 0px 20px 20px; + height: fit-content; + padding: 20px; + display: flex; + flex-direction: column; + gap: 20px; + background: newstyles.$gray-l1; + border-radius: 0px 0px 20px 20px; } .header { - top: 0px; - position: sticky; - background: $gray-l1; - border-bottom: $standard-border; - border-color: $gray-l2; - display: flex; - flex-direction: column; - justify-content: flex-start; - align-items: flex-start; - border-radius: 20px 20px 0px 0px; - padding: 20px; - z-index: 2; - gap: 10px; - color: $text-color-lm; - - .lb-label { - color: $gray-l3; - font-weight: $h1-weight; - font-size: $body-size; - } - - .lb-caret { + top: 0px; + position: sticky; + background: newstyles.$gray-l1; + border-bottom: newstyles.$standard-border; + border-color: newstyles.$gray-l2; display: flex; - flex-direction: row; - justify-content: flex-end; - align-items: center; - gap: 5px; - cursor: pointer; - width: 100%; - user-select: none; - font-size: $body-size; - } + flex-direction: column; + justify-content: flex-start; + align-items: flex-start; + border-radius: 20px 20px 0px 0px; + padding: 20px; + z-index: 2; + gap: 10px; + color: newstyles.$text-color-lm; - .more { - width: 100%; - } + .lb-label { + color: newstyles.$gray-l3; + font-weight: newstyles.$h1-weight; + font-size: newstyles.$body-size; + } - &.dark { - color: $text-color-dm; - } + .lb-caret { + display: flex; + flex-direction: row; + justify-content: flex-end; + align-items: center; + gap: 5px; + cursor: pointer; + width: 100%; + user-select: none; + font-size: newstyles.$body-size; + } - .title { - height: 30px; - min-height: 30px; - font-size: $h1-size; - font-weight: $h1-weight; - text-align: left; - display: flex; - justify-content: space-between; - align-items: center; - width: 100%; - } + .more { + width: 100%; + } - .keywords { - display: flex; - flex-flow: row wrap; - gap: 5px; + &.dark { + color: newstyles.$text-color-dm; + } - .keyword-input { - padding: 3px 7px; - background: $gray-l2; - outline: none; - border: none; - height: 21.5px; - color: $text-color-lm; + .title { + height: 30px; + min-height: 30px; + font-size: newstyles.$h1-size; + font-weight: newstyles.$h1-weight; + text-align: left; + display: flex; + justify-content: space-between; + align-items: center; + width: 100%; } - .keyword { - padding: 3px 7px; - width: fit-content; - background: $gray-l2; - display: flex; - justify-content: center; - align-items: center; - flex-direction: row; - gap: 10px; - font-size: $body-size; - font-weight: $body-weight; + .keywords { + display: flex; + flex-flow: row wrap; + gap: 5px; - &.loading { - animation: skeleton-loading-l2 1s linear infinite alternate; - min-width: 70px; - height: 21.5px; - } - } + .keyword-input { + padding: 3px 7px; + background: newstyles.$gray-l2; + outline: none; + border: none; + height: 21.5px; + color: newstyles.$text-color-lm; + } + + .keyword { + padding: 3px 7px; + width: fit-content; + background: newstyles.$gray-l2; + display: flex; + justify-content: center; + align-items: center; + flex-direction: row; + gap: 10px; + font-size: newstyles.$body-size; + font-weight: newstyles.$body-weight; - } + &.loading { + animation: skeleton-loading-l2 1s linear infinite alternate; + min-width: 70px; + height: 21.5px; + } + } + } } - + &.dark { - background: $black; + background: newstyles.$black; } - + &.light, &.default { - background: $gray-l1; + background: newstyles.$gray-l1; } -}
\ No newline at end of file +} diff --git a/src/client/views/newlightbox/components/EditableText/EditableText.scss b/src/client/views/newlightbox/components/EditableText/EditableText.scss index 7828538ab..8007e8d43 100644 --- a/src/client/views/newlightbox/components/EditableText/EditableText.scss +++ b/src/client/views/newlightbox/components/EditableText/EditableText.scss @@ -1,34 +1,34 @@ -@import '../../NewLightboxStyles.scss'; +@use '../../NewLightboxStyles.scss' as newstyles; .lb-editableText, .lb-displayText { padding: 4px 7px !important; - border: $standard-border !important; - border-color: $gray-l2 !important; + border: newstyles.$standard-border !important; + border-color: newstyles.$gray-l2 !important; } .lb-editableText { - -webkit-appearance: none; - overflow: hidden; - font-size: inherit; - border: none; - outline: none; - width: 100%; - margin: 0px; - padding: 0px; - box-shadow: none !important; - background: none; - - &:focus { + -webkit-appearance: none; + overflow: hidden; + font-size: inherit; + border: none; outline: none; - background-color: $blue-l1; - } + width: 100%; + margin: 0px; + padding: 0px; + box-shadow: none !important; + background: none; + + &:focus { + outline: none; + background-color: newstyles.$blue-l1; + } } .lb-displayText { - cursor: text !important; - width: 100%; - display: flex; - align-items: center; - font-size: inherit; -}
\ No newline at end of file + cursor: text !important; + width: 100%; + display: flex; + align-items: center; + font-size: inherit; +} diff --git a/src/client/views/newlightbox/components/Recommendation/Recommendation.scss b/src/client/views/newlightbox/components/Recommendation/Recommendation.scss index c86c63ba0..cf6b5ccb1 100644 --- a/src/client/views/newlightbox/components/Recommendation/Recommendation.scss +++ b/src/client/views/newlightbox/components/Recommendation/Recommendation.scss @@ -1,4 +1,4 @@ -@import '../../NewLightboxStyles.scss'; +@use '../../NewLightboxStyles.scss' as newstyles; .recommendation-container { width: 100%; @@ -8,22 +8,22 @@ display: grid; grid-template-columns: 0% 100%; grid-template-rows: auto auto auto auto auto; - gap: 5px 0px; + gap: 5px 0px; padding: 10px; cursor: pointer; transition: 0.2s ease; - border: $standard-border; - border-color: $gray-l2; + border: newstyles.$standard-border; + border-color: newstyles.$gray-l2; background: white; &:hover { - // background: white !important; - transform: scale(1.02); - z-index: 0; + // background: white !important; + transform: scale(1.02); + z-index: 0; - .title { - text-decoration: underline; - } + .title { + text-decoration: underline; + } } &.previewUrl { @@ -39,18 +39,18 @@ grid-template-rows: auto auto auto auto auto; gap: 5px 10px; - .image-container, - .title, - .info, - .source, - .explainer, - .hide-rec { - animation: skeleton-loading-l3 1s linear infinite alternate; - } + .image-container, + .title, + .info, + .source, + .explainer, + .hide-rec { + animation: skeleton-loading-l3 1s linear infinite alternate; + } - .title { - border-radius: 20px; - } + .title { + border-radius: 20px; + } } .distance-container, @@ -64,62 +64,62 @@ } .image-container { - grid-row: 2/5; - grid-column: 1; - border-radius: 20px; - overflow: hidden; + grid-row: 2/5; + grid-column: 1; + border-radius: 20px; + overflow: hidden; - .image { - width: 100%; - height: 100%; - object-fit: cover; - } + .image { + width: 100%; + height: 100%; + object-fit: cover; + } } .title { - grid-row: 1; - grid-column: 1/3; - border-radius: 20px; - font-size: $h2-size; - font-weight: $h2-weight; - overflow: hidden; - border-radius: 0px; - min-height: 30px; + grid-row: 1; + grid-column: 1/3; + border-radius: 20px; + font-size: newstyles.$h2-size; + font-weight: newstyles.$h2-weight; + overflow: hidden; + border-radius: 0px; + min-height: 30px; } .info { - grid-row: 2; - grid-column: 2; - border-radius: 20px; - display: flex; - flex-direction: row; - gap: 5px; - font-size: $body-size; + grid-row: 2; + grid-column: 2; + border-radius: 20px; + display: flex; + flex-direction: row; + gap: 5px; + font-size: newstyles.$body-size; .lb-type { padding: 2px 7px !important; - background: $gray-l2; + background: newstyles.$gray-l2; } } .lb-label { - color: $gray-l3; - font-weight: $h1-weight; - font-size: $body-size; + color: newstyles.$gray-l3; + font-weight: newstyles.$h1-weight; + font-size: newstyles.$body-size; } .source { grid-row: 3; grid-column: 2; border-radius: 20px; - font-size: $body-size; + font-size: newstyles.$body-size; display: flex; justify-content: flex-start; align-items: center; .lb-source { padding: 2px 7px !important; - background: $gray-l2; + background: newstyles.$gray-l2; border-radius: 10px; white-space: nowrap; max-width: 130px; @@ -134,7 +134,7 @@ border-radius: 20px; font-size: 10px; width: 100%; - background: $blue-l1; + background: newstyles.$blue-l1; border-radius: 0; padding: 10px; @@ -145,7 +145,7 @@ gap: 3px; .concept { padding: 2px 7px !important; - background: $gray-l2; + background: newstyles.$gray-l2; } } } @@ -154,7 +154,7 @@ grid-row: 5; grid-column: 2; border-radius: 20px; - font-size: $body-size; + font-size: newstyles.$body-size; display: flex; align-items: center; margin-top: 5px; @@ -162,15 +162,15 @@ justify-content: flex-end; text-transform: underline; } - + &.dark { - background: $black; - border-color: $white; + background: newstyles.$black; + border-color: newstyles.$white; } - + &.light, &.default { - background: $white; - border-color: $white; + background: newstyles.$white; + border-color: newstyles.$white; } -}
\ No newline at end of file +} diff --git a/src/client/views/newlightbox/components/SkeletonDoc/SkeletonDoc.scss b/src/client/views/newlightbox/components/SkeletonDoc/SkeletonDoc.scss index e541e3f3c..bbc730144 100644 --- a/src/client/views/newlightbox/components/SkeletonDoc/SkeletonDoc.scss +++ b/src/client/views/newlightbox/components/SkeletonDoc/SkeletonDoc.scss @@ -1,82 +1,81 @@ -@import '../../NewLightboxStyles.scss'; +@use '../../NewLightboxStyles.scss' as newstyles; .skeletonDoc-container { - display: flex; - flex-direction: column; - height: calc(100% - 40px); - margin: 20px; - gap: 20px; + display: flex; + flex-direction: column; + height: calc(100% - 40px); + margin: 20px; + gap: 20px; - .header { - width: calc(100% - 20px); - height: 80px; - background: $gray-l2; - animation: skeleton-loading-l2 1s linear infinite alternate; - display: grid; - grid-template-rows: 60% 40%; - padding: 10px; - grid-template-columns: auto auto auto auto; - border-radius: 20px; + .header { + width: calc(100% - 20px); + height: 80px; + background: newstyles.$gray-l2; + animation: skeleton-loading-l2 1s linear infinite alternate; + display: grid; + grid-template-rows: 60% 40%; + padding: 10px; + grid-template-columns: auto auto auto auto; + border-radius: 20px; - .title { - grid-row: 1; - grid-column: 1 / 5; - display: flex; - width: fit-content; - height: 100%; - min-width: 500px; - font-size: $title-size; - animation: skeleton-loading-l3 1s linear infinite alternate; - border-radius: 20px; - } + .title { + grid-row: 1; + grid-column: 1 / 5; + display: flex; + width: fit-content; + height: 100%; + min-width: 500px; + font-size: newstyles.$title-size; + animation: skeleton-loading-l3 1s linear infinite alternate; + border-radius: 20px; + } - .type { - display: flex; - padding: 3px 7px; - width: fit-content; - height: fit-content; - margin-top: 8px; - min-height: 15px; - min-width: 60px; - grid-row: 2; - grid-column: 1; - animation: skeleton-loading-l3 1s linear infinite alternate; - border-radius: 20px; - } + .type { + display: flex; + padding: 3px 7px; + width: fit-content; + height: fit-content; + margin-top: 8px; + min-height: 15px; + min-width: 60px; + grid-row: 2; + grid-column: 1; + animation: skeleton-loading-l3 1s linear infinite alternate; + border-radius: 20px; + } - .buttons-container { - grid-row: 1 / 3; - grid-column: 5; - display: flex; - justify-content: flex-end; - align-items: center; - gap: 10px; + .buttons-container { + grid-row: 1 / 3; + grid-column: 5; + display: flex; + justify-content: flex-end; + align-items: center; + gap: 10px; - .button { - width: 50px; - height: 50px; - border-radius: 100%; - animation: skeleton-loading-l3 1s linear infinite alternate; - } + .button { + width: 50px; + height: 50px; + border-radius: 100%; + animation: skeleton-loading-l3 1s linear infinite alternate; + } + } } - } - - .content { - width: 100%; - flex: 1; - -webkit-flex: 1; /* Chrome */ - background: $gray-l2; - animation: skeleton-loading-l2 1s linear infinite alternate; - border-radius: 20px; - } + .content { + width: 100%; + flex: 1; + -webkit-flex: 1; /* Chrome */ + background: newstyles.$gray-l2; + animation: skeleton-loading-l2 1s linear infinite alternate; + border-radius: 20px; + } // &.dark { - // background: $black; + // background: newstyles.$black; // } - + // &.light, // &.default { - // background: $white; + // background: newstyles.$white; // } -}
\ No newline at end of file +} diff --git a/src/client/views/newlightbox/components/Template/Template.scss b/src/client/views/newlightbox/components/Template/Template.scss index 5b72ddaf9..c2fb9fba4 100644 --- a/src/client/views/newlightbox/components/Template/Template.scss +++ b/src/client/views/newlightbox/components/Template/Template.scss @@ -1,15 +1,15 @@ -@import '../../NewLightboxStyles.scss'; +@use '../../NewLightboxStyles.scss' as newstyles; .template-container { width: 100vw; height: 100vh; - + &.dark { - background: $black; + background: newstyles.$black; } - + &.light, &.default { - background: $white; + background: newstyles.$white; } -}
\ No newline at end of file +} diff --git a/src/client/views/nodes/AudioBox.scss b/src/client/views/nodes/AudioBox.scss index 4337401e3..933a383ea 100644 --- a/src/client/views/nodes/AudioBox.scss +++ b/src/client/views/nodes/AudioBox.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .audiobox-container { width: 100%; @@ -19,30 +19,30 @@ .audiobox-dictation { width: 40px; - background: $medium-gray; - color: $dark-gray; + background: global.$medium-gray; + color: global.$dark-gray; display: flex; justify-content: center; align-items: center; &:hover { - color: $black; + color: global.$black; } } .audiobox-start-record { - color: $white; - background: $dark-gray; + color: global.$white; + background: global.$dark-gray; display: flex; align-items: center; justify-content: center; - font-size: $body-text; + font-size: global.$body-text; width: 100%; height: 100%; gap: 5px; &:hover { - background: $black; + background: global.$black; } } @@ -54,11 +54,11 @@ gap: 5px; width: 100%; height: 100%; - background: $dark-gray; + background: global.$dark-gray; color: white; .record-timecode { - font-size: $large-header; + font-size: global.$large-header; } .record-button { @@ -66,7 +66,7 @@ width: 30px; height: 30px; border-radius: 50%; - background: $dark-gray; + background: global.$dark-gray; display: flex; align-items: center; justify-content: center; @@ -76,7 +76,7 @@ } &:hover { - background: $black; + background: global.$black; } } } @@ -87,10 +87,10 @@ display: flex; flex-direction: column; align-items: center; - background: $dark-gray; + background: global.$dark-gray; width: 100%; height: 100%; - color: $white; + color: global.$white; .audiobox-button { margin: 2.5px; @@ -98,7 +98,7 @@ width: 25px; height: 25px; border-radius: 50%; - background: $dark-gray; + background: global.$dark-gray; display: flex; align-items: center; justify-content: center; @@ -108,7 +108,7 @@ } &:hover { - background: $black; + background: global.$black; } } @@ -132,7 +132,7 @@ height: 6px; cursor: pointer; box-shadow: 0; - background: $light-gray; + background: global.$light-gray; border-radius: 3px; } @@ -142,7 +142,7 @@ height: 10px; width: 10px; border-radius: 10px; - background: $medium-blue; + background: global.$medium-blue; cursor: pointer; -webkit-appearance: none; margin-top: -2px; @@ -180,12 +180,12 @@ .audiobox-playback { width: 100%; height: 100%; - background: $white; + background: global.$white; .audiobox-timeline { height: calc(100% - 50px); width: 100%; - background: $white; + background: global.$white; position: absolute; } @@ -203,7 +203,7 @@ width: 100%; height: 20px; padding: 3px; - font-size: $small-text; + font-size: global.$small-text; .bottom-controls-middle { display: flex; diff --git a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx index beea6ab3c..ce1e9280a 100644 --- a/src/client/views/nodes/CollectionFreeFormDocumentView.tsx +++ b/src/client/views/nodes/CollectionFreeFormDocumentView.tsx @@ -69,7 +69,7 @@ export class CollectionFreeFormDocumentView extends DocComponent<CollectionFreeF { key: 'freeform_panX' }, { key: 'freeform_panY' }, ]; // fields that are configured to be animatable using animation frames - public static animStringFields = ['backgroundColor', 'color', 'fillColor']; // fields that are configured to be animatable using animation frames + public static animStringFields = ['backgroundColor', 'borderColor', 'color', 'fillColor']; // fields that are configured to be animatable using animation frames public static animDataFields = (doc: Doc) => (Doc.LayoutFieldKey(doc) ? [Doc.LayoutFieldKey(doc)] : []); // fields that are configured to be animatable using animation frames public static from(dv?: DocumentView): CollectionFreeFormDocumentView | undefined { return dv?._props.reactParent instanceof CollectionFreeFormDocumentView ? dv._props.reactParent : undefined; @@ -180,7 +180,7 @@ export class CollectionFreeFormDocumentView extends DocComponent<CollectionFreeF const timecode = Math.round(time); Object.keys(vals).forEach(val => { const findexed = Cast(d[`${val}_indexed`], listSpec('number'), []).slice(); - findexed[timecode] = vals[val] || 0; + findexed[timecode] = vals[val] as unknown as number; d[`${val}_indexed`] = new List<number>(findexed); }); } diff --git a/src/client/views/nodes/ComparisonBox.tsx b/src/client/views/nodes/ComparisonBox.tsx index cb0831d3c..5315612e1 100644 --- a/src/client/views/nodes/ComparisonBox.tsx +++ b/src/client/views/nodes/ComparisonBox.tsx @@ -291,7 +291,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>() this.askGPTPhonemes(this._inputValue); this._renderSide = this.backKey; this._outputValue = ''; - } else if (this._inputValue) this.askGPT(GPTCallType.QUIZ); + } else if (this._inputValue) this.askGPT(GPTCallType.QUIZDOC); }; onPointerMove = ({ movementX }: PointerEvent) => { @@ -511,7 +511,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>() */ askGPT = async (callType: GPTCallType) => { const questionText = this.frontText; - const queryText = questionText + (callType == GPTCallType.QUIZ ? ' UserAnswer: ' + this._inputValue + '. ' + ' Rubric: ' + this.backText : ''); + const queryText = questionText + (callType == GPTCallType.QUIZDOC ? ' UserAnswer: ' + this._inputValue + '. ' + ' Rubric: ' + this.backText : ''); this.loading = true; const res = !this.frontText @@ -522,7 +522,7 @@ export class ComparisonBox extends ViewBoxAnnotatableComponent<FieldViewProps>() case GPTCallType.CHATCARD: DocCast(this.dataDoc[this.backKey])[DocData].text = resp; break; - case GPTCallType.QUIZ: + case GPTCallType.QUIZDOC: this._renderSide = this.backKey; this._outputValue = resp.replace(/UserAnswer/g, "user's answer").replace(/Rubric/g, 'rubric'); break; diff --git a/src/client/views/nodes/DataVizBox/DataVizBox.tsx b/src/client/views/nodes/DataVizBox/DataVizBox.tsx index b874d077b..d5e37b3b5 100644 --- a/src/client/views/nodes/DataVizBox/DataVizBox.tsx +++ b/src/client/views/nodes/DataVizBox/DataVizBox.tsx @@ -32,11 +32,12 @@ import { DocumentView } from '../DocumentView'; import { FieldView, FieldViewProps } from '../FieldView'; import { FocusViewOptions } from '../FocusViewOptions'; import './DataVizBox.scss'; -import { Col, DataVizTemplateInfo, DocCreatorMenu, LayoutType, TemplateFieldSize, TemplateFieldType } from './DocCreatorMenu'; +import { Col, DataVizTemplateInfo, DocCreatorMenu, LayoutType} from './DocCreatorMenu/DocCreatorMenu'; import { Histogram } from './components/Histogram'; import { LineChart } from './components/LineChart'; import { PieChart } from './components/PieChart'; import { TableBox } from './components/TableBox'; +import { TemplateFieldSize, TemplateFieldType } from './DocCreatorMenu/TemplateBackend'; export enum DataVizView { TABLE = 'table', @@ -171,7 +172,6 @@ export class DataVizBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { const colInfo = this.colsInfo.get(colTitle); if (colInfo) { colInfo.title = newTitle; - console.log(colInfo.title); } else { this.colsInfo.set(colTitle, { title: newTitle, desc: '', type: TemplateFieldType.UNSET, sizes: [] }); } @@ -489,7 +489,7 @@ export class DataVizBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { } // Changing which document to add the annotation to (the currently selected PDF) - GPTPopup.Instance.setSidebarId('data_sidebar'); + GPTPopup.Instance.setSidebarFieldKey('data_sidebar'); GPTPopup.Instance.addDoc = this.sidebarAddDocument; }; @@ -510,7 +510,6 @@ export class DataVizBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { openDocCreatorMenu = (x: number, y: number) => { DocCreatorMenu.Instance.toggleDisplay(x, y); DocCreatorMenu.Instance.setDataViz(this); - DocCreatorMenu.Instance.setTemplateDocs(this.getPossibleTemplates()); }; specificContextMenu = (e: React.MouseEvent) => { @@ -523,7 +522,7 @@ export class DataVizBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { }; askGPT = action(async () => { - GPTPopup.Instance.setSidebarId('data_sidebar'); + GPTPopup.Instance.setSidebarFieldKey('data_sidebar'); GPTPopup.Instance.addDoc = this.sidebarAddDocument; GPTPopup.Instance.createFilteredDoc = this.createFilteredDoc; GPTPopup.Instance.setDataJson(''); @@ -622,107 +621,6 @@ export class DataVizBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { } }; - getPossibleTemplates = (): Doc[] => { - const linkedDocs: Doc[] = LinkManager.Instance.getAllRelatedLinks(this.Document).map(d => DocCast(LinkManager.getOppositeAnchor(d, this.Document))); - const linkedCollections: Doc[] = linkedDocs.filter(doc => doc.type === 'config').map(doc => DocCast(doc.annotationOn)); - const isColumnTitle = (title: string): boolean => { - const colTitles: string[] = Object.keys(this.records[0]); - for (let i = 0; i < colTitles.length; ++i) { - if (colTitles[i] === title) { - return true; - } - } - return false; - }; - const isValidTemplate = (collection: Doc) => { - const childDocs = DocListCast(collection[Doc.LayoutFieldKey(collection)]); - for (let i = 0; i < childDocs.length; ++i) { - if (isColumnTitle(String(childDocs[i].title))) return true; - } - return false; - }; - return linkedCollections.filter(col => isValidTemplate(col)); - }; - - ApplyTemplateTo = (templateDoc: Doc, target: Doc, targetKey: string, titleTarget: string | undefined) => { - if (!Doc.AreProtosEqual(target[targetKey] as Doc, templateDoc)) { - if (target.resolvedDataDoc) { - target[targetKey] = new PrefetchProxy(templateDoc); - } else { - titleTarget && (Doc.GetProto(target).title = titleTarget); - const setDoc = [AclAdmin, AclEdit, AclAugment].includes(GetEffectiveAcl(Doc.GetProto(target))) ? Doc.GetProto(target) : target; - setDoc[targetKey] = new PrefetchProxy(templateDoc); - } - } - return target; - }; - - applyLayout = (templateInfo: DataVizTemplateInfo, docs: Doc[]) => { - if (templateInfo.layout.type === LayoutType.Stacked) return; - const columns: number = templateInfo.columns; - const xGap: number = templateInfo.layout.xMargin; - const yGap: number = templateInfo.layout.yMargin; - // const repeat: number = templateInfo.layout.repeat; - const startX: number = templateInfo.referencePos.x; - const startY: number = templateInfo.referencePos.y; - const templWidth = Number(templateInfo.doc._width); - const templHeight = Number(templateInfo.doc._height); - - let i: number = 0; - let docsChanged: number = 0; - let curX: number = startX; - let curY: number = startY; - - while (docsChanged < docs.length) { - while (i < columns && docsChanged < docs.length) { - docs[docsChanged].x = curX; - docs[docsChanged].y = curY; - curX += templWidth + xGap; - ++docsChanged; - ++i; - } - - i = 0; - curX = startX; - curY += templHeight + yGap; - } - }; - - // @action addSavedLayout = (layout: DataVizTemplateLayout) => { - // const saved = Cast(this.layoutDoc.dataViz_savedTemplates, listSpec('RefField')); - - // } - - @action - createDocsFromTemplate = (templateInfo: DataVizTemplateInfo) => { - if (!templateInfo.doc) return; - const mainCollection = this.DocumentView?.().containerViewPath?.().lastElement()?.ComponentView as CollectionFreeFormView; - const fields: string[] = Array.from(Object.keys(this.records[0])); - const selectedRows = NumListCast(this.layoutDoc.dataViz_selectedRows); - const docs: Doc[] = selectedRows.map(row => { - const values: string[] = []; - fields.forEach(col => values.push(this.records[row][col])); - - const proto = new Doc(); - proto.author = ClientUtils.CurrentUserEmail(); - values.forEach((val, i) => { - proto[fields[i]] = val as FieldType; - }); - - const target = Doc.MakeDelegate(proto); - const targetKey = StrCast(templateInfo.doc!.layout_fieldKey, 'layout'); - const applied = this.ApplyTemplateTo(templateInfo.doc!, target, targetKey, templateInfo.doc!.title + `${row}`); - target.layout_fieldKey = targetKey; - - //this.applyImagesTo(target, fields); - return applied; - }); - - docs.forEach(doc => mainCollection.addDocument(doc)); - - this.applyLayout(templateInfo, docs); - }; - /** * creates a new dataviz document filter from this one * it appears to the right of this document, with the diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu.tsx b/src/client/views/nodes/DataVizBox/DocCreatorMenu.tsx deleted file mode 100644 index 7fc906e59..000000000 --- a/src/client/views/nodes/DataVizBox/DocCreatorMenu.tsx +++ /dev/null @@ -1,2367 +0,0 @@ -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { Colors } from '@dash/components'; -import { action, computed, makeObservable, observable, reaction, runInAction } from 'mobx'; -import { observer } from 'mobx-react'; -import { IDisposer } from 'mobx-utils'; -import * as React from 'react'; -import ReactLoading from 'react-loading'; -import { ClientUtils, returnEmptyFilter, returnFalse, returnTrue, setupMoveUpEvents } from '../../../../ClientUtils'; -import { emptyFunction } from '../../../../Utils'; -import { Doc, NumListCast, StrListCast, returnEmptyDoclist } from '../../../../fields/Doc'; -import { Id } from '../../../../fields/FieldSymbols'; -import { Cast, DocCast, ImageCast, StrCast } from '../../../../fields/Types'; -import { ImageField } from '../../../../fields/URLField'; -import { Networking } from '../../../Network'; -import { GPTCallType, gptAPICall, gptImageCall } from '../../../apis/gpt/GPT'; -import { Docs } from '../../../documents/Documents'; -import { DragManager } from '../../../util/DragManager'; -import { MakeTemplate } from '../../../util/DropConverter'; -import { SnappingManager } from '../../../util/SnappingManager'; -import { UndoManager, undoable } from '../../../util/UndoManager'; -import { LightboxView } from '../../LightboxView'; -import { ObservableReactComponent } from '../../ObservableReactComponent'; -import { CollectionFreeFormView } from '../../collections/collectionFreeForm/CollectionFreeFormView'; -import { DocumentView, DocumentViewInternal } from '../DocumentView'; -import { FieldViewProps } from '../FieldView'; -import { OpenWhere } from '../OpenWhere'; -import { DataVizBox } from './DataVizBox'; -import './DocCreatorMenu.scss'; -import { DefaultStyleProvider, returnEmptyDocViewList } from '../../StyleProvider'; -import { Transform } from '../../../util/Transform'; -import { IconProp } from '@fortawesome/fontawesome-svg-core'; - -export enum LayoutType { - Stacked = 'stacked', - Grid = 'grid', - Row = 'row', - Column = 'column', - Custom = 'custom', -} - -@observer -export class DocCreatorMenu extends ObservableReactComponent<FieldViewProps> { - static Instance: DocCreatorMenu; - - private _disposers: { [name: string]: IDisposer } = {}; - - private _ref: HTMLDivElement | null = null; - - @observable _templateDocs: Doc[] = []; - @observable _selectedTemplate: Doc | undefined = undefined; - @observable _columns: Col[] = []; - @observable _selectedCols: { title: string; type: string; desc: string }[] | undefined = []; - - @observable _layout: { type: LayoutType; yMargin: number; xMargin: number; columns?: number; repeat: number } = { type: LayoutType.Grid, yMargin: 0, xMargin: 0, repeat: 0 }; - @observable _layoutPreview: boolean = true; - @observable _layoutPreviewScale: number = 1; - @observable _savedLayouts: DataVizTemplateLayout[] = []; - @observable _expandedPreview: { icon: ImageField; doc: Doc } | undefined = undefined; - - @observable _suggestedTemplates: Doc[] = []; - @observable _GPTOpt: boolean = false; - @observable _userPrompt: string = ''; - @observable _callCount: number = 0; - @observable _GPTLoading: boolean = false; - - @observable _pageX: number = 0; - @observable _pageY: number = 0; - @observable _indicatorX: number | undefined = undefined; - @observable _indicatorY: number | undefined = undefined; - - @observable _hoveredLayoutPreview: number | undefined = undefined; - @observable _mouseX: number = -1; - @observable _mouseY: number = -1; - @observable _startPos?: { x: number; y: number }; - @observable _shouldDisplay: boolean = false; - - @observable _menuContent: 'templates' | 'options' | 'saved' | 'dashboard' = 'templates'; - @observable _dragging: boolean = false; - @observable _draggingIndicator: boolean = false; - @observable _dataViz?: DataVizBox; - @observable _interactionLock: any; - @observable _snapPt: any; - @observable _resizeHdlId: string = ''; - @observable _resizing: boolean = false; - @observable _offset: { x: number; y: number } = { x: 0, y: 0 }; - @observable _resizeUndo: UndoManager.Batch | undefined = undefined; - @observable _initDimensions: { width: number; height: number; x?: number; y?: number } = { width: 300, height: 400, x: undefined, y: undefined }; - @observable _menuDimensions: { width: number; height: number } = { width: 400, height: 400 }; - @observable _editing: boolean = false; - - constructor(props: any) { - super(props); - makeObservable(this); - DocCreatorMenu.Instance = this; - //setTimeout(() => this.generateTemplates('')); - } - - @action setDataViz = (dataViz: DataVizBox) => { - this._dataViz = dataViz; - }; - @action setTemplateDocs = (docs: Doc[]) => { - this._templateDocs = docs.map(doc => (doc.annotationOn ? DocCast(doc.annotationOn) : doc)); - }; - @action setGSuggestedTemplates = (docs: Doc[]) => { - this._suggestedTemplates = docs; - }; - - @computed get docsToRender() { - return this._selectedTemplate ? NumListCast(this._dataViz?.layoutDoc.dataViz_selectedRows) : []; - } - - @computed get rowsCount() { - switch (this._layout.type) { - case LayoutType.Row: - case LayoutType.Stacked: - return 1; - case LayoutType.Column: - return this.docsToRender.length; - case LayoutType.Grid: - return Math.ceil(this.docsToRender.length / (this._layout.columns ?? 1)) ?? 0; - default: - return 0; - } - } - - @computed get columnsCount() { - switch (this._layout.type) { - case LayoutType.Row: - return this.docsToRender.length; - case LayoutType.Column: - case LayoutType.Stacked: - return 1; - case LayoutType.Grid: - return this._layout.columns ?? 0; - default: - return 0; - } - } - - @computed get selectedFields() { - return StrListCast(this._dataViz?.layoutDoc._dataViz_axes); - } - - @computed get fieldsInfos(): Col[] { - const colInfo = this._dataViz?.colsInfo; - return this.selectedFields - .map(field => { - const fieldInfo = colInfo?.get(field); - - const col: Col = { - title: field, - type: fieldInfo?.type ?? TemplateFieldType.UNSET, - desc: fieldInfo?.desc ?? '', - sizes: fieldInfo?.sizes ?? [TemplateFieldSize.MEDIUM], - }; - - if (fieldInfo?.defaultContent !== undefined) { - col.defaultContent = fieldInfo.defaultContent; - } - - return col; - }) - .concat(this._columns); - } - - @computed get canMakeDocs() { - return this._selectedTemplate !== undefined && this._layout !== undefined; - } - - get bounds(): { t: number; b: number; l: number; r: number } { - const rect = this._ref?.getBoundingClientRect(); - const bounds = { t: rect?.top ?? 0, b: rect?.bottom ?? 0, l: rect?.left ?? 0, r: rect?.right ?? 0 }; - return bounds; - } - - setUpButtonClick = (e: any, func: Function) => { - setupMoveUpEvents( - this, - e, - returnFalse, - emptyFunction, - undoable(clickEv => { - clickEv.stopPropagation(); - clickEv.preventDefault(); - func(); - }, 'create docs') - ); - }; - - @action - onPointerDown = (e: PointerEvent) => { - this._mouseX = e.clientX; - this._mouseY = e.clientY; - }; - - @action - onPointerUp = (e: PointerEvent) => { - if (this._resizing) { - this._initDimensions.width = this._menuDimensions.width; - this._initDimensions.height = this._menuDimensions.height; - this._initDimensions.x = this._pageX; - this._initDimensions.y = this._pageY; - document.removeEventListener('pointermove', this.onResize); - SnappingManager.SetIsResizing(undefined); - this._resizing = false; - } - if (this._dragging) { - document.removeEventListener('pointermove', this.onDrag); - this._dragging = false; - } - if (e.button !== 2 && !e.ctrlKey) return; - const curX = e.clientX; - const curY = e.clientY; - if (Math.abs(this._mouseX - curX) > 1 || Math.abs(this._mouseY - curY) > 1) { - this._shouldDisplay = false; - } - }; - - componentDidMount() { - document.addEventListener('pointerdown', this.onPointerDown, true); - document.addEventListener('pointerup', this.onPointerUp); - this._disposers.templates = reaction( - () => this._templateDocs.slice(), - docs => this.updateIcons(docs) - ); - this._disposers.gpt = reaction( - () => this._suggestedTemplates.slice(), - docs => this.updateIcons(docs) - ); - //this._disposers.columns = reaction(() => this._dataViz?.layoutDoc._dataViz_axes, () => {this.generateTemplates('')}) - this._disposers.lightbox = reaction( - () => LightboxView.LightboxDoc(), - doc => { - // NOTE: bcz; commented this out because the doc creator would appear everytime I close out of the lightbox - // doc ? this._shouldDisplay && this.closeMenu() : !this._shouldDisplay && this.openMenu(); - } - ); - //this._disposers.fields = reaction(() => this._dataViz?.axes, cols => this._selectedCols = cols?.map(col => { return {title: col, type: '', desc: ''}})) - } - - componentWillUnmount() { - Object.values(this._disposers).forEach(disposer => disposer?.()); - document.removeEventListener('pointerdown', this.onPointerDown, true); - document.removeEventListener('pointerup', this.onPointerUp); - } - - updateIcons = (docs: Doc[]) => { - console.log('called'); - docs.map(this.getIcon); - }; - - @action - updateSelectedCols = (cols: string[]) => { - this._selectedCols; - }; - - @action - toggleDisplay = (x: number, y: number) => { - if (this._shouldDisplay) { - this._shouldDisplay = false; - } else { - this._pageX = x; - this._pageY = y; - this._shouldDisplay = true; - } - }; - - @action - closeMenu = () => { - this._shouldDisplay = false; - }; - - @action - openMenu = () => { - const allTemplates = this._templateDocs.concat(this._suggestedTemplates); - this._shouldDisplay = true; - this.updateIcons(allTemplates); - }; - - @action - onResizePointerDown = (e: React.PointerEvent): void => { - this._resizing = true; - document.addEventListener('pointermove', this.onResize); - SnappingManager.SetIsResizing(DocumentView.Selected().lastElement()?.Document[Id]); // turns off pointer events on things like youtube videos and web pages so that dragging doesn't get "stuck" when cursor moves over them - e.stopPropagation(); - const id = (this._resizeHdlId = e.currentTarget.className); - const pad = id.includes('Left') || id.includes('Right') ? Number(getComputedStyle(e.target as any).width.replace('px', '')) / 2 : 0; - const bounds = e.currentTarget.getBoundingClientRect(); - this._offset = { - x: id.toLowerCase().includes('left') ? bounds.right - e.clientX - pad : bounds.left - e.clientX + pad, // - y: id.toLowerCase().includes('top') ? bounds.bottom - e.clientY - pad : bounds.top - e.clientY + pad, - }; - this._resizeUndo = UndoManager.StartBatch('drag resizing'); - this._snapPt = { x: e.pageX, y: e.pageY }; - }; - - @action - onResize = (e: any): boolean => { - const dragHdl = this._resizeHdlId.split(' ')[1]; - const thisPt = DragManager.snapDrag(e, -this._offset.x, -this._offset.y, this._offset.x, this._offset.y); - - const { scale, refPt, transl } = this.getResizeVals(thisPt, dragHdl); - !this._interactionLock && runInAction(async () => { // resize selected docs if we're not in the middle of a resize (ie, throttle input events to frame rate) - this._interactionLock = true; - const scaleAspect = {x: scale.x, y: scale.y}; - this.resizeView(refPt, scaleAspect, transl); // prettier-ignore - await new Promise<any>(res => { setTimeout(() => { res(this._interactionLock = undefined)})}); - }); // prettier-ignore - return true; - }; - - @action - onDrag = (e: any): boolean => { - this._pageX = e.pageX - (this._startPos?.x ?? 0); - this._pageY = e.pageY - (this._startPos?.y ?? 0); - this._initDimensions.x = this._pageX; - this._initDimensions.y = this._pageY; - return true; - }; - - getResizeVals = (thisPt: { x: number; y: number }, dragHdl: string) => { - const [w, h] = [this._initDimensions.width, this._initDimensions.height]; - const [moveX, moveY] = [thisPt.x - this._snapPt.x, thisPt.y - this._snapPt.y]; - let vals: { scale: { x: number; y: number }; refPt: [number, number]; transl: { x: number; y: number } }; - switch (dragHdl) { - case 'topLeft': vals = { scale: { x: 1 - moveX / w, y: 1 -moveY / h }, refPt: [this.bounds.r, this.bounds.b], transl: {x: moveX, y: moveY } }; break; - case 'topRight': vals = { scale: { x: 1 + moveX / w, y: 1 -moveY / h }, refPt: [this.bounds.l, this.bounds.b], transl: {x: 0, y: moveY } }; break; - case 'top': vals = { scale: { x: 1, y: 1 -moveY / h }, refPt: [this.bounds.l, this.bounds.b], transl: {x: 0, y: moveY } }; break; - case 'left': vals = { scale: { x: 1 - moveX / w, y: 1 }, refPt: [this.bounds.r, this.bounds.t], transl: {x: moveX, y: 0 } }; break; - case 'bottomLeft': vals = { scale: { x: 1 - moveX / w, y: 1 + moveY / h }, refPt: [this.bounds.r, this.bounds.t], transl: {x: moveX, y: 0 } }; break; - case 'right': vals = { scale: { x: 1 + moveX / w, y: 1 }, refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break; - case 'bottomRight':vals = { scale: { x: 1 + moveX / w, y: 1 + moveY / h }, refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break; - case 'bottom': vals = { scale: { x: 1, y: 1 + moveY / h }, refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break; - default: vals = { scale: { x: 1, y: 1 }, refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break; - } // prettier-ignore - return vals; - }; - - resizeView = (refPt: number[], scale: { x: number; y: number }, translation: { x: number; y: number }) => { - const refCent = [refPt[0], refPt[1]]; // fixed reference point for resize (ie, a point that doesn't move) - if (this._initDimensions.x === undefined) this._initDimensions.x = this._pageX; - if (this._initDimensions.y === undefined) this._initDimensions.y = this._pageY; - const { height, width, x, y } = this._initDimensions; - - this._menuDimensions.width = Math.max(300, scale.x * width); - this._menuDimensions.height = Math.max(200, scale.y * height); - this._pageX = x + translation.x; - this._pageY = y + translation.y; - }; - - async getIcon(doc: Doc) { - const docView = DocumentView.getDocumentView(doc); - if (docView) { - docView.ComponentView?.updateIcon?.(); - return new Promise<ImageField | undefined>(res => setTimeout(() => res(ImageCast(docView.Document.icon)), 500)); - } - return undefined; - } - - @action updateSelectedTemplate = (template: Doc) => { - if (this._selectedTemplate === template) { - this._selectedTemplate = undefined; - return; - } else { - this._selectedTemplate = template; - MakeTemplate(template); - } - }; - - @action updateSelectedSavedLayout = (layout: DataVizTemplateLayout) => { - this._layout.xMargin = layout.layout.xMargin; - this._layout.yMargin = layout.layout.yMargin; - this._layout.type = layout.layout.type; - this._layout.columns = layout.columns; - }; - - isSelectedLayout = (layout: DataVizTemplateLayout) => { - return this._layout.xMargin === layout.layout.xMargin && this._layout.yMargin === layout.layout.yMargin && this._layout.type === layout.layout.type && this._layout.columns === layout.columns; - }; - - @action - generateTemplates = async (inputText: string) => { - ++this._callCount; - const origCount = this._callCount; - - let prompt: string = `(#${origCount}) Please generate for the fields:`; - this.selectedFields?.forEach(field => (prompt += ` ${field},`)); - prompt += ` (-----NOT A FIELD-----) Additional prompt: ${inputText}`; - - this._GPTLoading = true; - - try { - const res = await gptAPICall(prompt, GPTCallType.TEMPLATE); - - if (res && this._callCount === origCount) { - this._suggestedTemplates = []; - const templates: { template_type: string; fieldVals: { title: string; tlx: string; tly: string; brx: string; bry: string }[] }[] = JSON.parse(res); - this.createGeneratedTemplates(templates, 500, 500); - } - } catch (err) { - console.error(err); - } - }; - - @action - createGeneratedTemplates = (layouts: { template_type: string; fieldVals: { title: string; tlx: string; tly: string; brx: string; bry: string }[] }[], tempWidth: number, tempHeight: number) => { - const mainCollection = this._dataViz?.DocumentView?.().containerViewPath?.().lastElement()?.ComponentView as CollectionFreeFormView; - const GPTTemplates: Doc[] = []; - - layouts.forEach(layout => { - const fields: Doc[] = layout.fieldVals.map(field => { - const left: number = (Number(field.tlx) * tempWidth) / 2; - const top: number = Number(field.tly) * tempHeight / 2; //prettier-ignore - const right: number = (Number(field.brx) * tempWidth) / 2; - const bottom: number = Number(field.bry) * tempHeight / 2; //prettier-ignore - const height = bottom - top; - const width = right - left; - const doc = !field.title.includes('$$') - ? Docs.Create.TextDocument('', { _height: height, _width: width, title: field.title, x: left, y: top, text_fontSize: `${height / 2}` }) - : Docs.Create.ImageDocument('', { _height: height, _width: width, title: field.title.replace(/\$\$/g, ''), x: left, y: top }); - return doc; - }); - - const template = Docs.Create.FreeformDocument(fields, { _height: tempHeight, _width: tempWidth, title: layout.template_type, x: 400000, y: 400000 }); - - mainCollection.addDocument(template); - - GPTTemplates.push(template); - }); - - setTimeout(() => { - this.setGSuggestedTemplates(GPTTemplates); /*GPTTemplates.forEach(template => mainCollection.removeDocument(template))*/ - }, 100); - - this.forceUpdate(); - }; - - editTemplate = (doc: Doc) => { - //this.closeMenu(); - DocumentViewInternal.addDocTabFunc(doc, OpenWhere.addRight); - DocumentView.DeselectAll(); - Doc.UnBrushDoc(doc); - }; - - removeTemplate = (doc: Doc) => { - this._templateDocs.splice(this._templateDocs.indexOf(doc), 1); - }; - - testTemplate = async () => { - this.updateIcons(this._suggestedTemplates.slice()); - this.forceUpdate(); - - // try { - // const res = await gptImageCall('Image of panda eating a cookie'); - - // if (res) { - // const result = await Networking.PostToServer('/uploadRemoteImage', { sources: res }); - - // console.log(result); - // } - // } catch (e) { - // console.log(e); - // } - }; - - @action addField = () => { - const newFields: Col[] = this._columns.concat([{ title: '', type: TemplateFieldType.UNSET, desc: '', sizes: [] }]); - this._columns = newFields; - }; - - @action removeField = (field: { title: string; type: string; desc: string }) => { - if (this._dataViz?.axes.includes(field.title)) { - this._dataViz.selectAxes(this._dataViz.axes.filter(col => col !== field.title)); - } else { - const toRemove = this._columns.filter(f => f === field); - if (!toRemove) return; - - if (toRemove.length > 1) { - while (toRemove.length > 1) { - toRemove.pop(); - } - } - - if (this._columns.length === 1) { - this._columns = []; - } else { - this._columns.splice(this._columns.indexOf(toRemove[0]), 1); - } - } - }; - - @action setColTitle = (column: Col, title: string) => { - if (this.selectedFields.includes(column.title)) { - this._dataViz?.setColumnTitle(column.title, title); - } else { - column.title = title; - } - this.forceUpdate(); - }; - - @action setColType = (column: Col, type: TemplateFieldType) => { - if (this.selectedFields.includes(column.title)) { - this._dataViz?.setColumnType(column.title, type); - } else { - column.type = type; - } - this.forceUpdate(); - }; - - modifyColSizes = (column: Col, size: TemplateFieldSize, valid: boolean) => { - if (this.selectedFields.includes(column.title)) { - this._dataViz?.modifyColumnSizes(column.title, size, valid); - } else { - if (!valid && column.sizes.includes(size)) { - column.sizes.splice(column.sizes.indexOf(size), 1); - } else if (valid && !column.sizes.includes(size)) { - column.sizes.push(size); - } - } - this.forceUpdate(); - }; - - setColDesc = (column: Col, desc: string) => { - if (this.selectedFields.includes(column.title)) { - this._dataViz?.setColumnDesc(column.title, desc); - } else { - column.desc = desc; - } - this.forceUpdate(); - }; - - generateGPTImage = async (prompt: string): Promise<string | undefined> => { - console.log(prompt); - - try { - const res = await gptImageCall(prompt); - - if (res) { - const result = await Networking.PostToServer('/uploadRemoteImage', { sources: res }); - const source = ClientUtils.prepend(result[0].accessPaths.agnostic.client); - return source; - } - } catch (e) { - console.log(e); - } - }; - - matchesForTemplate = (template: TemplateDocInfos, cols: Col[]): number[][] => { - const colMatchesField = (col: Col, field: Field) => { - return field.sizes?.some(size => col.sizes?.includes(size)) && field.types?.includes(col.type); - }; - - const matches: number[][] = Array(template.fields.length) - .fill([]) - .map(() => []); - - template.fields.forEach((field, i) => { - cols.forEach((col, v) => { - if (colMatchesField(col, field)) { - matches[i].push(v); - } - }); - }); - - return matches; - }; - - maxMatches = (fieldsCt: number, matches: number[][]) => { - const used: boolean[] = Array(fieldsCt).fill(false); - const mt: number[] = Array(fieldsCt).fill(-1); - - const augmentingPath = (v: number): boolean => { - if (used[v]) return false; - used[v] = true; - for (const to of matches[v]) { - if (mt[to] === -1 || augmentingPath(mt[to])) { - mt[to] = v; - return true; - } - } - return false; - }; - - for (let v = 0; v < fieldsCt; ++v) { - used.fill(false); - augmentingPath(v); - } - - let count: number = 0; - - for (let i = 0; i < fieldsCt; ++i) { - if (mt[i] !== -1) ++count; - } - - return count; - }; - - findValidTemplates = (cols: Col[], templates: TemplateDocInfos[]) => { - let validTemplates: any[] = []; - templates.forEach(template => { - const numFields = template.fields.length; - if (!(numFields === cols.length)) return; - const matches = this.matchesForTemplate(template, cols); - if (this.maxMatches(numFields, matches) === numFields) { - validTemplates.push(template.title); - } - }); - - validTemplates = validTemplates.map(title => TemplateLayouts.getTemplateByTitle(title)); - - return validTemplates; - }; - - // createColumnField = (template: TemplateDocInfos, field: Field, column: Col): Doc => { - - // if (field.subfields) { - // const doc = FieldFuncs.FreeformField({ - // tl: field.tl, - // br: field.br }, - // template.height, - // template.width, - // column.title, - // '', - // field.opts - // ); - - // field.subfields[1].forEach(f => { - // const fDoc = () - // }) - - // } - - // return new Doc; - // } - - /** - * Populates a preset template framework with content from a datavizbox or any AI-generated content. - * @param template the preloaded template framework being filled in - * @param assignments a list of template field numbers (from top to bottom) and their assigned columns from the linked dataviz - * @returns a doc containing the fully rendered template - */ - fillPresetTemplate = async (template: TemplateDocInfos, assignments: { [field: string]: Col }): Promise<Doc> => { - const wordLimit = (size: TemplateFieldSize) => { - switch (size) { - case TemplateFieldSize.TINY: - return 2; - case TemplateFieldSize.SMALL: - return 5; - case TemplateFieldSize.MEDIUM: - return 20; - case TemplateFieldSize.LARGE: - return 50; - case TemplateFieldSize.HUGE: - return 100; - default: - return 10; - } - }; - - const renderTextCalls = async (): Promise<Doc[]> => { - const rendered: Doc[] = []; - - if (GPTTextCalls.length) { - try { - const prompt = fieldContent + GPTTextAssignment; - - const res = await gptAPICall(prompt, GPTCallType.FILL); - - if (res) { - const assignments: { [title: string]: { number: string; content: string } } = JSON.parse(res); - //console.log('assignments', GPTAssignments, 'assignment string', GPTAssignmentString, 'field content', fieldContent, 'response', res, 'assignments', assignments); - Object.entries(assignments).forEach(([title, info]) => { - const field: Field = template.fields[Number(info.number)]; - const col = this.getColByTitle(title); - - const doc = FieldUtils.TextField( - { - tl: field.tl, - br: field.br, - }, - template.height, - template.width, - col.title, - info.content ?? '', - field.opts - ); - - rendered.push(doc); - }); - } - } catch (err) { - console.log(err); - } - } - - return rendered; - }; - - const createGeneratedImage = async (fieldNum: string, col: Col, prompt: string) => { - const url = await this.generateGPTImage(prompt); - const field: Field = template.fields[Number(fieldNum)]; - const doc = FieldUtils.ImageField( - { - tl: field.tl, - br: field.br, - }, - template.height, - template.width, - col.title, - url ?? '', - field.opts - ); - - return doc; - }; - - const renderImageCalls = async (): Promise<Doc[]> => { - const rendered: Doc[] = []; - const calls = GPTIMGCalls; - - if (calls.length) { - try { - const renderedImages: Doc[] = await Promise.all( - calls.map(async ([fieldNum, col]) => { - const sysPrompt = - 'Your job is to create a prompt for an AI image generator to help it generate an image based on existing content in a template and a user prompt. Your prompt should focus heavily on visual elements to help the image generator; avoid unecessary info that might distract it. ONLY INCLUDE THE PROMPT, NO OTHER TEXT OR EXPLANATION. The existing content is as follows: ' + - fieldContent + - ' **** The user prompt is: ' + - col.desc; - - const prompt = await gptAPICall(sysPrompt, GPTCallType.COMPLETEPROMPT); - console.log(sysPrompt, prompt); - - return createGeneratedImage(fieldNum, col, prompt); - }) - ); - - const renderedTemplates: Doc[] = await Promise.all(renderedImages); - renderedTemplates.forEach(doc => rendered.push(doc)); - } catch (e) { - console.log(e); - } - } - - return rendered; - }; - - const fields: Doc[] = []; - - const GPTAssignments = Object.entries(assignments).filter(([f, col]) => this._columns.includes(col)); - const nonGPTAssignments: [string, Col][] = Object.entries(assignments).filter(a => !GPTAssignments.includes(a)); - const GPTTextCalls = GPTAssignments.filter(([str, col]) => col.type === TemplateFieldType.TEXT); - const GPTIMGCalls = GPTAssignments.filter(([str, col]) => col.type === TemplateFieldType.VISUAL); - - const stringifyGPTInfo = (calls: [string, Col][]): string => { - let string: string = '*** COLUMN INFO:'; - calls.forEach(([fieldNum, col]) => { - string += `--- title: ${col.title}, prompt: ${col.desc}, word limit: ${wordLimit(col.sizes[0])} words, assigned field: ${fieldNum} ---`; - }); - return (string += ' ***'); - }; - - const GPTTextAssignment = stringifyGPTInfo(GPTTextCalls); - - let fieldContent: string = ''; - - Object.entries(nonGPTAssignments).forEach(([f, strCol]) => { - const field: Field = template.fields[Number(f)]; - const col = strCol[1]; - - const doc = (col.type === TemplateFieldType.VISUAL ? FieldUtils.ImageField : FieldUtils.TextField)( - { - tl: field.tl, - br: field.br, - }, - template.height, - template.width, - col.title, - col.defaultContent ?? '', - field.opts - ); - - fieldContent += `--- Field #${f} (title: ${col.title}): ${col.defaultContent ?? ''} ---`; - - fields.push(doc); - }); - - template.decorations.forEach(dec => { - const doc = FieldUtils.FreeformField( - { - tl: dec.tl, - br: dec.br, - }, - template.height, - template.width, - '', - '', - dec.opts - ); - - fields.push(doc); - }); - - const createMainDoc = (): Doc => { - const main = Docs.Create.FreeformDocument(fields, { - _height: template.height, - _width: template.width, - title: template.title, - backgroundColor: template.opts.backgroundColor, - _layout_borderRounding: `${template.opts.cornerRounding}px` ?? '0px', - borderWidth: template.opts.borderWidth, - borderColor: template.opts.borderColor, - x: 40000, - y: 40000, - }); - - const mainCollection = this._dataViz?.DocumentView?.().containerViewPath?.().lastElement()?.ComponentView as CollectionFreeFormView; - mainCollection.addDocument(main); - - return main; - }; - - const textCalls = await renderTextCalls(); - const imageCalls = await renderImageCalls(); - - textCalls.forEach(doc => { - fields.push(doc); - }); - imageCalls.forEach(doc => { - fields.push(doc); - }); - - return createMainDoc(); - }; - - compileFieldDescriptions = (templates: TemplateDocInfos[]): string => { - let descriptions: string = ''; - templates.forEach(template => { - descriptions += `---------- NEW TEMPLATE TO INCLUDE: Description of template ${template.title}'s fields: `; - template.fields.forEach((field, index) => { - descriptions += `{Field #${index}: ${field.description}} `; - }); - }); - - return descriptions; - }; - - compileColDescriptions = (cols: Col[]): string => { - let descriptions: string = ' ------------- COL DESCRIPTIONS START HERE:'; - cols.forEach(col => (descriptions += `{title: ${col.title}, sizes: ${String(col.sizes)}, type: ${col.type}, descreiption: ${col.desc}} `)); - - return descriptions; - }; - - getColByTitle = (title: string) => { - return this.fieldsInfos.filter(col => col.title === title)[0]; - }; - - @action - assignColsToFields = async (templates: TemplateDocInfos[], cols: Col[]): Promise<[TemplateDocInfos, { [field: number]: Col }][]> => { - const fieldDescriptions: string = this.compileFieldDescriptions(templates); - const colDescriptions: string = this.compileColDescriptions(cols); - - const inputText = fieldDescriptions.concat(colDescriptions); - - ++this._callCount; - const origCount = this._callCount; - - let prompt: string = `(${origCount}) ${inputText}`; - - this._GPTLoading = true; - - try { - const res = await gptAPICall(prompt, GPTCallType.TEMPLATE); - - if (res && this._callCount === origCount) { - const assignments: { [templateTitle: string]: { [field: string]: string } } = JSON.parse(res); - const brokenDownAssignments: [TemplateDocInfos, { [field: number]: Col }][] = []; - - Object.entries(assignments).forEach(([tempTitle, assignment]) => { - const template = TemplateLayouts.getTemplateByTitle(tempTitle); - if (!template) return; - const toObj = Object.entries(assignment).reduce( - (a, [fieldNum, colTitle]) => { - a[Number(fieldNum)] = this.getColByTitle(colTitle); - return a; - }, - {} as { [field: number]: Col } - ); - brokenDownAssignments.push([template, toObj]); - }); - return brokenDownAssignments; - } - } catch (err) { - console.error(err); - } - - return []; - }; - - generatePresetTemplates = async () => { - this._dataViz?.updateColDefaults(); - - const cols = this.fieldsInfos; - const templates = this.findValidTemplates(cols, TemplateLayouts.allTemplates); - - const assignments: [TemplateDocInfos, { [field: number]: Col }][] = await this.assignColsToFields(templates, cols); - - const renderedTemplatePromises: Promise<Doc>[] = assignments.map(([template, assignments]) => this.fillPresetTemplate(template, assignments)); - - const renderedTemplates: Doc[] = await Promise.all(renderedTemplatePromises); - - setTimeout(() => { - this.setGSuggestedTemplates(renderedTemplates); - this._GPTLoading = false; - }); - }; - - @action setExpandedView = (info: { icon: ImageField; doc: Doc } | undefined) => { - if (info) { - const doc = info.doc; - const wrapper: Doc = Docs.Create.FreeformDocument([info.doc], { _height: NumListCast(doc._height)[0], _width: NumListCast(doc._width)[0], title: '' }); - const newInfo = { icon: new ImageField(''), doc: wrapper }; - this._expandedPreview = newInfo; - } else { - this._expandedPreview = info; - } - }; - - get editingWindow() { - const doc = this._expandedPreview?.doc ?? new Doc(); - const rendered = ( - <div className="docCreatorMenu-expanded-template-preview"> - <CollectionFreeFormView - Document={this._expandedPreview!.doc} - docViewPath={returnEmptyDocViewList} - childLayoutTemplate={() => Cast(doc.childLayoutTemplate, Doc, null)} - isContentActive={emptyFunction} - isAnyChildContentActive={() => true} - select={emptyFunction} - isSelected={returnFalse} - fieldKey={Doc.LayoutFieldKey(doc)} - addDocument={returnFalse} - moveDocument={returnFalse} - removeDocument={returnFalse} - PanelWidth={() => this._menuDimensions.width - 10} - PanelHeight={() => this._menuDimensions.height - 60} - ScreenToLocalTransform={() => new Transform(-this._pageX, -this._pageY, 1)} - renderDepth={5} - whenChildContentsActiveChanged={emptyFunction} - focus={emptyFunction} - styleProvider={DefaultStyleProvider} - addDocTab={this._props.addDocTab} - // eslint-disable-next-line no-use-before-define - pinToPres={() => undefined} - childFilters={returnEmptyFilter} - childFiltersByRanges={returnEmptyFilter} - searchFilterDocs={returnEmptyDoclist} - fitContentsToBox={returnTrue} - xPadding={0} - yPadding={0} - /> - </div> - ); - - return ( - <div className="docCreatorMenu-expanded-template-preview"> - <div className="top-panel" /> - {rendered} - <div className="right-buttons-panel"> - <button - className="docCreatorMenu-menu-button section-reveal-options top-right" - onPointerDown={e => - this.setUpButtonClick(e, () => { - this._expandedPreview && this.updateIcons(this._suggestedTemplates.slice()); - this.setExpandedView(undefined); - }) - }> - <FontAwesomeIcon icon="minimize" /> - </button> - <button className="docCreatorMenu-menu-button section-reveal-options top-right-lower" onPointerDown={e => this.setUpButtonClick(e, () => this._expandedPreview && this._templateDocs.push(this._expandedPreview.doc))}> - <FontAwesomeIcon icon="plus" color="white" /> - </button> - </div> - </div> - ); - } - - get templatesPreviewContents() { - const renderedTemplates: Doc[] = []; - - const GPTOptions = <div></div>; - - //<img className='docCreatorMenu-preview-image expanded' src={this._expandedPreview.icon!.url.href.replace(".png", "_o.png")} /> - - return ( - <div className={`docCreatorMenu-templates-view`}> - {this._expandedPreview ? ( - this.editingWindow - ) : ( - <div> - <div className="docCreatorMenu-section" style={{ height: this._GPTOpt ? 200 : 200 }}> - <div className="docCreatorMenu-section-topbar"> - <div className="docCreatorMenu-section-title">Suggested Templates</div> - <button className="docCreatorMenu-menu-button section-reveal-options" onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => (this._menuContent = 'dashboard')))}> - <FontAwesomeIcon icon="gear" /> - </button> - </div> - <div className="docCreatorMenu-templates-preview-window" style={{ justifyContent: this._GPTLoading || this._menuDimensions.width > 400 ? 'center' : '' }}> - {this._GPTLoading ? ( - <div className="loading-spinner"> - <ReactLoading type="spin" color={StrCast(Doc.UserDoc().userVariantColor)} height={30} width={30} /> - </div> - ) : ( - this._suggestedTemplates - ?.map(doc => ({ icon: ImageCast(doc.icon), doc })) - .filter(info => info.icon && info.doc) - .map(info => ( - <div - className="docCreatorMenu-preview-window" - style={{ - border: this._selectedTemplate === info.doc ? `solid 3px ${Colors.MEDIUM_BLUE}` : '', - boxShadow: this._selectedTemplate === info.doc ? `0 0 15px rgba(68, 118, 247, .8)` : '', - }} - onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this.updateSelectedTemplate(info.doc)))}> - <button - className="option-button left" - onPointerDown={e => - this.setUpButtonClick(e, () => { - this.setExpandedView(info); - }) - }> - <FontAwesomeIcon icon="magnifying-glass" color="white" /> - </button> - <button className="option-button right" onPointerDown={e => this.setUpButtonClick(e, () => this._templateDocs.push(info.doc))}> - <FontAwesomeIcon icon="plus" color="white" /> - </button> - <img className="docCreatorMenu-preview-image" src={info.icon!.url.href.replace('.png', '_o.png')} /> - </div> - )) - )} - </div> - <div className="docCreatorMenu-GPT-options"> - <div className="docCreatorMenu-GPT-options-container"> - <button className="docCreatorMenu-menu-button" onPointerDown={e => this.setUpButtonClick(e, () => this.generatePresetTemplates())}> - <FontAwesomeIcon icon="arrows-rotate" /> - </button> - </div> - {this._GPTOpt ? GPTOptions : null} - </div> - </div> - <hr className="docCreatorMenu-option-divider full no-margin" /> - <div className="docCreatorMenu-section"> - <div className="docCreatorMenu-section-topbar"> - <div className="docCreatorMenu-section-title">Your Templates</div> - <button className="docCreatorMenu-menu-button section-reveal-options" onPointerDown={e => this.setUpButtonClick(e, () => (this._GPTOpt = !this._GPTOpt))}> - <FontAwesomeIcon icon="gear" /> - </button> - </div> - <div className="docCreatorMenu-templates-preview-window" style={{ justifyContent: this._menuDimensions.width > 400 ? 'center' : '' }}> - <div className="docCreatorMenu-preview-window empty" onPointerDown={e => this.testTemplate()}> - <FontAwesomeIcon icon="plus" color="rgb(160, 160, 160)" /> - </div> - {this._templateDocs - .map(doc => ({ icon: ImageCast(doc.icon), doc })) - .filter(info => info.icon && info.doc) - .map(info => { - if (renderedTemplates.includes(info.doc)) return undefined; - renderedTemplates.push(info.doc); - return ( - <div - className="docCreatorMenu-preview-window" - style={{ - border: this._selectedTemplate === info.doc ? `solid 3px ${Colors.MEDIUM_BLUE}` : '', - boxShadow: this._selectedTemplate === info.doc ? `0 0 15px rgba(68, 118, 247, .8)` : '', - }} - onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this.updateSelectedTemplate(info.doc)))}> - <button - className="option-button left" - onPointerDown={e => - this.setUpButtonClick(e, () => { - this.editTemplate(info.doc); - }) - }> - <FontAwesomeIcon icon="pencil" color="black" /> - </button> - <button - className="option-button right" - onPointerDown={e => - this.setUpButtonClick(e, () => { - this.removeTemplate(info.doc); - }) - }> - <FontAwesomeIcon icon="trash" color="black" /> - </button> - <img className="docCreatorMenu-preview-image" src={info.icon!.url.href.replace('.png', '_o.png')} /> - </div> - ); - })} - </div> - </div> - </div> - )} - </div> - ); - } - - get savedLayoutsPreviewContents() { - return ( - <div className="docCreatorMenu-preview-container"> - {this._savedLayouts.map((layout, index) => ( - <div - className="docCreatorMenu-preview-window" - style={{ - border: this.isSelectedLayout(layout) ? `solid 3px ${Colors.MEDIUM_BLUE}` : '', - boxShadow: this.isSelectedLayout(layout) ? `0 0 15px rgba(68, 118, 247, .8)` : '', - }} - onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this.updateSelectedSavedLayout(layout)))}> - {this.layoutPreviewContents(87, layout, true, index)} - </div> - ))} - </div> - ); - } - - @action updateXMargin = (input: string) => { - this._layout.xMargin = Number(input); - }; - @action updateYMargin = (input: string) => { - this._layout.yMargin = Number(input); - }; - @action updateColumns = (input: string) => { - this._layout.columns = Number(input); - }; - - get layoutConfigOptions() { - const optionInput = (icon: string, func: Function, def?: number, key?: string, noMargin?: boolean) => { - return ( - <div className="docCreatorMenu-option-container small no-margin" key={key} style={{ marginTop: noMargin ? '0px' : '' }}> - <div className="docCreatorMenu-option-title config layout-config"> - <FontAwesomeIcon icon={icon as any} /> - </div> - <input defaultValue={def} onInput={e => func(e.currentTarget.value)} className="docCreatorMenu-input config layout-config" /> - </div> - ); - }; - - switch (this._layout.type) { - case LayoutType.Row: - return <div className="docCreatorMenu-configuration-bar">{optionInput('arrows-left-right', this.updateXMargin, this._layout.xMargin, '0')}</div>; - case LayoutType.Column: - return <div className="docCreatorMenu-configuration-bar">{optionInput('arrows-up-down', this.updateYMargin, this._layout.yMargin, '1')}</div>; - case LayoutType.Grid: - return ( - <div className="docCreatorMenu-configuration-bar"> - {optionInput('arrows-up-down', this.updateYMargin, this._layout.xMargin, '2')} - {optionInput('arrows-left-right', this.updateXMargin, this._layout.xMargin, '3')} - {optionInput('table-columns', this.updateColumns, this._layout.columns, '4', true)} - </div> - ); - case LayoutType.Stacked: - return null; - default: - break; - } - } - - // doc = () => { - // return Docs.Create.FreeformDocument([], { _height: 200, _width: 200, title: 'title'}); - // } - - screenToLocalTransform = () => this._props.ScreenToLocalTransform(); - - layoutPreviewContents = (outerSpan: number, altLayout?: DataVizTemplateLayout, small: boolean = false, id?: number) => { - const doc: Doc | undefined = altLayout ? altLayout.template : this._selectedTemplate; - if (!doc) return; - - const layout = altLayout ? altLayout.layout : this._layout; - - const docWidth: number = Number(doc._width); - const docHeight: number = Number(doc._height); - const horizontalSpan: number = (docWidth + layout.xMargin) * (altLayout ? altLayout.columns : this.columnsCount) - layout.xMargin; - const verticalSpan: number = (docHeight + layout.yMargin) * (altLayout ? altLayout.rows : this.rowsCount) - layout.yMargin; - const largerSpan: number = horizontalSpan > verticalSpan ? horizontalSpan : verticalSpan; - const scaledDown = (input: number) => { - return input / ((largerSpan / outerSpan) * this._layoutPreviewScale); - }; - const fontSize = Math.min(scaledDown(docWidth / 3), scaledDown(docHeight / 3)); - - return ( - // <div className='divvv' style={{width: 100, height: 100, border: `1px solid white`}}> - // <CollectionFreeFormView - // // eslint-disable-next-line react/jsx-props-no-spreading - // {...this._props} - // Document={new Doc()} - // isContentActive={returnFalse} - // setContentViewBox={emptyFunction} - // NativeWidth={() => 100} - // NativeHeight={() => 100} - // pointerEvents={SnappingManager.IsDragging ? returnAll : returnNone} - // isAnnotationOverlay - // isAnnotationOverlayScrollable - // childDocumentsActive={returnFalse} - // fieldKey={this._props.fieldKey + '_annotations'} - // dropAction={dropActionType.move} - // select={emptyFunction} - // addDocument={returnFalse} - // removeDocument={returnFalse} - // moveDocument={returnFalse} - // renderDepth={this._props.renderDepth + 1}> - // {null} - // </CollectionFreeFormView> - // </div> - <div className="docCreatorMenu-layout-preview-window-wrapper" id={String(id) ?? undefined}> - <div className="docCreatorMenu-zoom-button-container"> - <button className="docCreatorMenu-zoom-button" onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => (this._layoutPreviewScale *= 1.25)))}> - <FontAwesomeIcon icon={'minus'} /> - </button> - <button className="docCreatorMenu-zoom-button zoom-in" onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => (this._layoutPreviewScale *= 0.75)))}> - <FontAwesomeIcon icon={'plus'} /> - </button> - {altLayout ? ( - <button className="docCreatorMenu-zoom-button trash" onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this._savedLayouts.splice(this._savedLayouts.indexOf(altLayout), 1)))}> - <FontAwesomeIcon icon={'trash'} /> - </button> - ) : null} - </div> - { - <div - id={String(id) ?? undefined} - className={`docCreatorMenu-layout-preview-window ${small ? 'small' : ''}`} - style={{ - gridTemplateColumns: `repeat(${altLayout ? altLayout.columns : this.columnsCount}, ${scaledDown(docWidth)}px`, - gridTemplateRows: `${scaledDown(docHeight)}px`, - gridAutoRows: `${scaledDown(docHeight)}px`, - rowGap: `${scaledDown(layout.yMargin)}px`, - columnGap: `${scaledDown(layout.xMargin)}px`, - }}> - {this._layout.type === LayoutType.Stacked ? ( - <div - className="docCreatorMenu-layout-preview-item" - style={{ - width: scaledDown(docWidth), - height: scaledDown(docHeight), - fontSize: fontSize, - }}> - All - </div> - ) : ( - this.docsToRender.map(num => ( - <div - onMouseEnter={() => this._dataViz?.setSpecialHighlightedRow(num)} - onMouseLeave={() => this._dataViz?.setSpecialHighlightedRow(undefined)} - className="docCreatorMenu-layout-preview-item" - style={{ - width: scaledDown(docWidth), - height: scaledDown(docHeight), - fontSize: fontSize, - }}> - {num} - </div> - )) - )} - </div> - } - </div> - ); - }; - - get optionsMenuContents() { - const layoutEquals = (layout: DataVizTemplateLayout) => {}; //TODO: ADD LATER - - const layoutOption = (option: LayoutType, optStyle?: {}, specialFunc?: Function) => { - return ( - <div - className="docCreatorMenu-dropdown-option" - style={optStyle} - onPointerDown={e => - this.setUpButtonClick(e, () => { - specialFunc?.(); - runInAction(() => (this._layout.type = option)); - }) - }> - {option} - </div> - ); - }; - - const selectionBox = (width: number, height: number, icon: string, specClass?: string, options?: JSX.Element[], manual?: boolean): JSX.Element => { - return ( - <div className="docCreatorMenu-option-container"> - <div className={`docCreatorMenu-option-title config ${specClass}`} style={{ width: width * 0.4, height: height }}> - <FontAwesomeIcon icon={icon as any} /> - </div> - {manual ? ( - <input className={`docCreatorMenu-input config ${specClass}`} style={{ width: width * 0.6, height: height }} /> - ) : ( - <select className={`docCreatorMenu-input config ${specClass}`} style={{ width: width * 0.6, height: height }}> - {options} - </select> - )} - </div> - ); - }; - - const repeatOptions = [0, 1, 2, 3, 4, 5]; - - return ( - <div className="docCreatorMenu-menu-container"> - <div className="docCreatorMenu-option-container layout"> - <div className="docCreatorMenu-dropdown-hoverable"> - <div className="docCreatorMenu-option-title">{this._layout.type ? this._layout.type.toUpperCase() : 'Choose Layout'}</div> - <div className="docCreatorMenu-dropdown-content"> - {layoutOption(LayoutType.Stacked)} - {layoutOption(LayoutType.Grid, undefined, () => { - if (!this._layout.columns) this._layout.columns = Math.ceil(Math.sqrt(this.docsToRender.length)); - })} - {layoutOption(LayoutType.Row)} - {layoutOption(LayoutType.Column)} - {layoutOption(LayoutType.Custom, { borderBottom: `0px` })} - </div> - </div> - <button className="docCreatorMenu-menu-button preview-toggle" onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => (this._layoutPreview = !this._layoutPreview)))}> - <FontAwesomeIcon icon={this._layoutPreview ? 'minus' : 'magnifying-glass'} /> - </button> - </div> - {this._layout.type ? this.layoutConfigOptions : null} - {this._layoutPreview ? this.layoutPreviewContents(this._menuDimensions.width * 0.75) : null} - {selectionBox( - 60, - 20, - 'repeat', - undefined, - repeatOptions.map(num => <option onPointerDown={e => (this._layout.repeat = num)}>{`${num}x`}</option>) - )} - <hr className="docCreatorMenu-option-divider" /> - <div className="docCreatorMenu-general-options-container"> - <button - className="docCreatorMenu-save-layout-button" - onPointerDown={e => - setupMoveUpEvents( - this, - e, - returnFalse, - emptyFunction, - undoable(clickEv => { - clickEv.stopPropagation(); - if (!this._selectedTemplate) return; - const layout: DataVizTemplateLayout = { - template: this._selectedTemplate, - layout: { type: this._layout.type, xMargin: this._layout.xMargin, yMargin: this._layout.yMargin, repeat: 0 }, - columns: this.columnsCount, - rows: this.rowsCount, - docsNumList: this.docsToRender, - }; - if (!this._savedLayouts.includes(layout)) { - this._savedLayouts.push(layout); - } - }, 'make docs') - ) - }> - <FontAwesomeIcon icon="floppy-disk" /> - </button> - <button - className="docCreatorMenu-create-docs-button" - style={{ backgroundColor: this.canMakeDocs ? '' : 'rgb(155, 155, 155)', border: this.canMakeDocs ? '' : 'solid 2px rgb(180, 180, 180)' }} - onPointerDown={e => - setupMoveUpEvents( - this, - e, - returnFalse, - emptyFunction, - undoable(clickEv => { - clickEv.stopPropagation(); - if (!this._selectedTemplate) return; - const templateInfo: DataVizTemplateInfo = { doc: this._selectedTemplate, layout: this._layout, referencePos: { x: this._pageX + 450, y: this._pageY }, columns: this.columnsCount }; - this._dataViz?.createDocsFromTemplate(templateInfo); - }, 'make docs') - ) - }> - <FontAwesomeIcon icon="plus" /> - </button> - </div> - </div> - ); - } - - get dashboardContents() { - const sizes: string[] = ['tiny', 'small', 'medium', 'large', 'huge']; - - const fieldPanel = (field: Col) => { - return ( - <div className="field-panel"> - <div className="top-bar"> - <span className="field-title">{`${field.title} Field`}</span> - <button className="docCreatorMenu-menu-button section-reveal-options no-margin" onPointerDown={e => this.setUpButtonClick(e, () => this.removeField(field))} style={{ position: 'absolute', right: '0px' }}> - <FontAwesomeIcon icon="minus" /> - </button> - </div> - <div className="opts-bar"> - <div className="opt-box"> - <div className="top-bar"> Title </div> - <textarea className="content" style={{ width: '100%', height: 'calc(100% - 20px)' }} defaultValue={field.title} placeholder={'Enter title'} onChange={e => this.setColTitle(field, e.target.value)} /> - </div> - <div className="opt-box"> - <div className="top-bar"> Type </div> - <div className="content"> - <span className="type-display">{field.type === TemplateFieldType.TEXT ? 'Text Field' : field.type === TemplateFieldType.VISUAL ? 'File Field' : ''}</span> - <div className="bubbles"> - <input - className="bubble" - type="radio" - name="type" - onClick={() => { - this.setColType(field, TemplateFieldType.TEXT); - }} - /> - <div className="text">Text</div> - <input - className="bubble" - type="radio" - name="type" - onClick={() => { - this.setColType(field, TemplateFieldType.VISUAL); - }} - /> - <div className="text">File</div> - </div> - </div> - </div> - </div> - <div className="sizes-box"> - <div className="top-bar"> Valid Sizes </div> - <div className="content"> - <div className="bubbles"> - {sizes.map(size => ( - <> - <input - className="bubble" - type="checkbox" - name="type" - checked={field.sizes.includes(size as TemplateFieldSize)} - onChange={e => { - this.modifyColSizes(field, size as TemplateFieldSize, e.target.checked); - }} - /> - <div className="text">{size}</div> - </> - ))} - </div> - </div> - </div> - <div className="desc-box"> - <div className="top-bar"> Prompt </div> - <textarea - className="content" - onChange={e => this.setColDesc(field, e.target.value)} - defaultValue={field.desc === this._dataViz?.GPTSummary?.get(field.title)?.desc ? '' : field.desc} - placeholder={this._dataViz?.GPTSummary?.get(field.title)?.desc ?? 'Add a description/prompt to help with template generation.'} - /> - </div> - </div> - ); - }; - - return ( - <div className="docCreatorMenu-dashboard-view"> - <div className="topbar"> - <button className="docCreatorMenu-menu-button section-reveal-options" onPointerDown={e => this.setUpButtonClick(e, this.addField)}> - <FontAwesomeIcon icon="plus" /> - </button> - <button className="docCreatorMenu-menu-button section-reveal-options float-right" onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => (this._menuContent = 'templates')))}> - <FontAwesomeIcon icon="arrow-left" /> - </button> - </div> - <div className="panels-container">{this.fieldsInfos.map(field => fieldPanel(field))}</div> - </div> - ); - } - - get renderSelectedViewType() { - switch (this._menuContent) { - case 'templates': - return this.templatesPreviewContents; - case 'options': - return this.optionsMenuContents; - case 'saved': - return this.savedLayoutsPreviewContents; - case 'dashboard': - return this.dashboardContents; - default: - return undefined; - } - } - - get resizePanes() { - const ref = this._ref?.getBoundingClientRect(); - const height: number = ref?.height ?? 0; - const width: number = ref?.width ?? 0; - - return [ - <div className='docCreatorMenu-resizer top' onPointerDown={this.onResizePointerDown} style={{width: width, left: 0, top: -7}}/>, - <div className='docCreatorMenu-resizer right' onPointerDown={this.onResizePointerDown} style={{height: height, left: width - 3, top: 0}}/>, - <div className='docCreatorMenu-resizer bottom' onPointerDown={this.onResizePointerDown} style={{width: width, left: 0, top: height - 3}}/>, - <div className='docCreatorMenu-resizer left' onPointerDown={this.onResizePointerDown} style={{height: height, left: -7, top: 0}}/>, - <div className='docCreatorMenu-resizer topRight' onPointerDown={this.onResizePointerDown} style={{left: width - 5, top: -10, cursor: 'nesw-resize'}}/>, - <div className='docCreatorMenu-resizer topLeft' onPointerDown={this.onResizePointerDown} style={{left: -10, top: -10, cursor: 'nwse-resize'}}/>, - <div className='docCreatorMenu-resizer bottomRight' onPointerDown={this.onResizePointerDown} style={{left: width - 5, top: height - 5, cursor: 'nwse-resize'}}/>, - <div className='docCreatorMenu-resizer bottomLeft' onPointerDown={this.onResizePointerDown} style={{left: -10, top: height - 5, cursor: 'nesw-resize'}}/> - ]; //prettier-ignore - } - - render() { - const topButton = (icon: string, opt: string, func: Function, tag: string) => { - return ( - <div className={`top-button-container ${tag} ${opt === this._menuContent ? 'selected' : ''}`}> - <div - className="top-button-content" - onPointerDown={e => - this.setUpButtonClick(e, () => - runInAction(() => { - func(); - }) - ) - }> - <FontAwesomeIcon icon={icon as any} /> - </div> - </div> - ); - }; - - const onPreviewSelected = () => { - this._menuContent = 'templates'; - }; - const onSavedSelected = () => { - this._menuContent = 'dashboard'; - }; - const onOptionsSelected = () => { - this._menuContent = 'options'; - if (!this._layout.columns) this._layout.columns = Math.ceil(Math.sqrt(this.docsToRender.length)); - }; - - return ( - <div className="docCreatorMenu"> - {!this._shouldDisplay ? undefined : ( - <div - className="docCreatorMenu-cont" - ref={r => (this._ref = r)} - style={{ - display: '', - left: this._pageX, - top: this._pageY, - width: this._menuDimensions.width, - height: this._menuDimensions.height, - background: SnappingManager.userBackgroundColor, - color: SnappingManager.userColor, - }}> - {this.resizePanes} - <div - className="docCreatorMenu-menu" - onPointerDown={e => - setupMoveUpEvents( - this, - e, - e => { - this._dragging = true; - this._startPos = { x: 0, y: 0 }; - this._startPos.x = e.pageX - (this._ref?.getBoundingClientRect().left ?? 0); - this._startPos.y = e.pageY - (this._ref?.getBoundingClientRect().top ?? 0); - document.addEventListener('pointermove', this.onDrag); - return true; - }, - emptyFunction, - undoable(clickEv => { - clickEv.stopPropagation(); - }, 'drag menu') - ) - }> - <div className="docCreatorMenu-top-buttons-container"> - {topButton('table-cells', 'templates', onPreviewSelected, 'left')} - {topButton('bars', 'options', onOptionsSelected, 'middle')} - {topButton('floppy-disk', 'saved', onSavedSelected, 'right')} - </div> - <button className="docCreatorMenu-menu-button close-menu" onPointerDown={e => this.setUpButtonClick(e, this.closeMenu)}> - <FontAwesomeIcon icon={'minus'} /> - </button> - </div> - {this.renderSelectedViewType} - </div> - )} - </div> - ); - } -} - -export interface DataVizTemplateInfo { - doc: Doc; - layout: { type: LayoutType; xMargin: number; yMargin: number; repeat: number }; - columns: number; - referencePos: { x: number; y: number }; -} - -export interface DataVizTemplateLayout { - template: Doc; - docsNumList: number[]; - layout: { type: LayoutType; xMargin: number; yMargin: number; repeat: number }; - columns: number; - rows: number; -} - -export enum TemplateFieldType { - TEXT = 'text', - VISUAL = 'visual', - UNSET = 'unset', -} - -export enum TemplateFieldSize { - TINY = 'tiny', - SMALL = 'small', - MEDIUM = 'medium', - LARGE = 'large', - HUGE = 'huge', -} - -export type Col = { - sizes: TemplateFieldSize[]; - desc: string; - title: string; - type: TemplateFieldType; - defaultContent?: string; -}; -export interface FieldOpts { - backgroundColor?: string; - color?: string; - cornerRounding?: number; - borderWidth?: string; - borderColor?: string; - contentXCentering?: 'h-left' | 'h-center' | 'h-right'; - contentYCentering?: 'top' | 'center' | 'bottom'; - opacity?: number; - rotation?: number; - //animation?: boolean; - fontBold?: boolean; - fontTransform?: 'uppercase' | 'lowercase'; - fieldViewType?: 'freeform' | 'stacked'; -} - -export type Field = { - tl: [number, number]; - br: [number, number]; - opts: FieldOpts; - subfields?: Field[]; - types?: TemplateFieldType[]; - sizes?: TemplateFieldSize[]; - isDecoration?: boolean; - description?: string; -}; - -// class ContentField implements Field { -// tl: [number, number]; -// br: [number, number]; -// opts: FieldOpts; -// subfields?: Field[]; -// types?: TemplateFieldType[]; -// sizes?: TemplateFieldSize[]; -// description?: string; - -// constructor( tl: [number, number], br: [number, number], -// opts: FieldOpts, subfields?: Field[], -// types?: TemplateFieldType[], -// sizes?: TemplateFieldSize[], -// description?: string) { -// this.tl = tl; -// this.br = br; -// this.opts = opts; -// this.subfields = subfields; -// this.types = types; -// this.sizes = sizes; -// this.description = description; -// } - -// render = (content: any): Doc => { -// return new Doc; -// } -// } - -type DecorationField = Field; - -type InkDecoration = {}; - -type TemplateDecorations = Field | InkDecoration; - -interface TemplateOpts extends FieldOpts {} - -export interface TemplateDocInfos { - title: string; - height: number; - width: number; - opts: TemplateOpts; - fields: Field[]; - decorations: Field[]; -} - -export class TemplateLayouts { - public static get allTemplates(): TemplateDocInfos[] { - return Object.values(TemplateLayouts).filter(value => typeof value === 'object' && value !== null && 'title' in value) as TemplateDocInfos[]; - } - - public static getTemplateByTitle = (title: string): TemplateDocInfos | undefined => { - switch (title) { - case 'fourfield1': - return TemplateLayouts.FourField001; - case 'fourfield2': - return TemplateLayouts.FourField002; - // case 'fourfield3': - // return TemplateLayouts.FourField003; - case 'fourfield4': - return TemplateLayouts.FourField004; - case 'threefield1': - return TemplateLayouts.ThreeField001; - case 'threefield2': - return TemplateLayouts.ThreeField002; - default: - break; - } - - return undefined; - }; - - public static FourField001: TemplateDocInfos = { - title: 'fourfield1', - width: 416, - height: 700, - opts: { - backgroundColor: '#C0B887', - cornerRounding: 20, - borderColor: '#6B461F', - borderWidth: '12', - }, - fields: [ - { - tl: [-0.95, -1], - br: [0.95, -0.85], - types: [TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.TINY], - description: 'A title field for very short text that contextualizes the content.', - opts: { - backgroundColor: 'transparent', - color: '#F1F0E9', - contentXCentering: 'h-center', - fontBold: true, - }, - }, - { - tl: [-0.87, -0.83], - br: [0.87, 0.2], - types: [TemplateFieldType.TEXT, TemplateFieldType.VISUAL], - sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], - description: 'The main focus of the template; could be an image, long text, etc.', - opts: { - cornerRounding: 20, - borderColor: '#8F5B25', - borderWidth: '6', - backgroundColor: '#CECAB9', - }, - }, - { - tl: [-0.8, 0.2], - br: [0.8, 0.3], - types: [TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], - description: 'A caption for field #2, very short to short text that contextualizes the content of field #2', - opts: { - backgroundColor: 'transparent', - contentXCentering: 'h-center', - color: '#F1F0E9', - }, - }, - { - tl: [-0.87, 0.37], - br: [0.87, 0.96], - types: [TemplateFieldType.TEXT, TemplateFieldType.VISUAL], - sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], - description: 'A medium-sized field for medium/long text.', - opts: { - cornerRounding: 15, - borderColor: '#8F5B25', - borderWidth: '6', - backgroundColor: '#CECAB9', - }, - }, - ], - decorations: [], - }; - - public static FourField002: TemplateDocInfos = { - title: 'fourfield2', - width: 425, - height: 778, - opts: { - backgroundColor: '#242425', - }, - fields: [ - { - tl: [-0.83, -0.95], - br: [0.83, -0.2], - types: [TemplateFieldType.VISUAL, TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE], - description: 'A medium to large-sized field suitable for an image or longer text that should be the main focus.', - opts: { - borderWidth: '8', - borderColor: '#F8E71C', - }, - }, - { - tl: [-0.65, -0.2], - br: [0.65, -0.02], - types: [TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.TINY], - description: 'A tiny field for just a word or two of plain text.', - opts: { - backgroundColor: 'transparent', - color: 'white', - contentXCentering: 'h-center', - fontTransform: 'uppercase', - }, - }, - { - tl: [-0.65, 0], - br: [0.65, 0.18], - types: [TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.TINY], - description: 'A tiny field for just a word or two of plain text.', - opts: { - backgroundColor: 'transparent', - color: 'white', - contentXCentering: 'h-center', - fontTransform: 'uppercase', - }, - }, - { - tl: [-0.83, 0.2], - br: [0.83, 0.95], - types: [TemplateFieldType.TEXT, TemplateFieldType.VISUAL], - sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], - description: 'A medium to large-sized field suitable for an image or longer text that should be the main focus, or share focus with field 1.', - opts: { - borderWidth: '8', - borderColor: '#F8E71C', - color: 'white', - backgroundColor: '#242425', - }, - }, - ], - decorations: [ - { - tl: [-0.8, -0.075], - br: [-0.525, 0.075], - opts: { - backgroundColor: '#F8E71C', - rotation: 45, - }, - }, - { - tl: [-0.3075, -0.0245], - br: [-0.2175, 0.0245], - opts: { - backgroundColor: '#F8E71C', - rotation: 45, - }, - }, - { - tl: [-0.045, -0.0245], - br: [0.045, 0.0245], - opts: { - backgroundColor: '#F8E71C', - rotation: 45, - }, - }, - { - tl: [0.2175, -0.0245], - br: [0.3075, 0.0245], - opts: { - backgroundColor: '#F8E71C', - rotation: 45, - }, - }, - { - tl: [0.525, -0.075], - br: [0.8, 0.075], - opts: { - backgroundColor: '#F8E71C', - rotation: 45, - }, - }, - ], - }; - - // public static FourField003: TemplateDocInfos = { - // title: 'fourfield3', - // width: 477, - // height: 662, - // opts: { - // backgroundColor: '#9E9C95' - // }, - // fields: [{ - // tl: [-.875, -.9], - // br: [.875, .7], - // types: [TemplateFieldType.VISUAL], - // sizes: [TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], - // description: '', - // opts: { - // borderWidth: '15', - // borderColor: '#E0E0DA', - // } - // }, { - // tl: [-.95, .8], - // br: [-.1, .95], - // types: [TemplateFieldType.TEXT], - // sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], - // description: '', - // opts: { - // backgroundColor: 'transparent', - // color: 'white', - // contentXCentering: 'h-right', - // } - // }, { - // tl: [.1, .8], - // br: [.95, .95], - // types: [TemplateFieldType.TEXT], - // sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], - // description: '', - // opts: { - // backgroundColor: 'transparent', - // color: 'red', - // fontTransform: 'uppercase', - // contentXCentering: 'h-left' - // } - // }, { - // tl: [0, -.9], - // br: [.85, -.66], - // types: [TemplateFieldType.TEXT, TemplateFieldType.VISUAL], - // sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], - // description: '', - // opts: { - // backgroundColor: 'transparent', - // contentXCentering: 'h-right' - // } - // }], - // decorations: [{ - // tl: [-.025, .8], - // br: [.025, .95], - // opts: { - // backgroundColor: '#E0E0DA', - // } - // }] - // }; - - public static FourField004: TemplateDocInfos = { - title: 'fourfield4', - width: 414, - height: 583, - opts: { - backgroundColor: '#6CCAF0', - borderColor: '#1088C3', - borderWidth: '10', - }, - fields: [ - { - tl: [-0.86, -0.92], - br: [-0.075, -0.77], - types: [TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.TINY], - description: 'A tiny field for just a word or two of plain text.', - opts: { - backgroundColor: '#E2B4F5', - borderWidth: '9', - borderColor: '#9222F1', - contentXCentering: 'h-center', - }, - }, - { - tl: [0.075, -0.92], - br: [0.86, -0.77], - types: [TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.TINY], - description: 'A tiny field for just a word or two of plain text.', - opts: { - backgroundColor: '#F5B4DD', - borderWidth: '9', - borderColor: '#E260F3', - contentXCentering: 'h-center', - }, - }, - { - tl: [-0.81, -0.64], - br: [0.81, 0.48], - types: [TemplateFieldType.VISUAL], - sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], - description: 'A large to huge field for visual content that is the main content of the template.', - opts: { - borderWidth: '16', - borderColor: '#A2BD77', - }, - }, - { - tl: [-0.86, 0.6], - br: [0.86, 0.92], - types: [TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE], - description: 'A medium to large field for text that describes the visual content above', - opts: { - borderWidth: '9', - borderColor: '#F0D601', - backgroundColor: '#F3F57D', - }, - }, - ], - decorations: [ - { - tl: [-0.852, -0.67], - br: [0.852, 0.51], - opts: { - backgroundColor: 'transparent', - borderColor: '#007C0C', - borderWidth: '10', - }, - }, - ], - }; - - public static ThreeField001: TemplateDocInfos = { - title: 'threefield1', - width: 575, - height: 770, - opts: { - backgroundColor: '#DDD3A9', - }, - fields: [ - { - tl: [-0.66, -0.747], - br: [0.66, 0.247], - types: [TemplateFieldType.VISUAL], - sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], - description: 'A medium to large field for visual content that is the central focus.', - opts: { - borderColor: 'yellow', - borderWidth: '8', - rotation: 45, - }, - }, - { - tl: [-0.7, 0.2], - br: [0.7, 0.46], - types: [TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], - description: 'A very small text field for one to a few words. A good caption for the image.', - opts: { - backgroundColor: 'transparent', - contentXCentering: 'h-center', - }, - }, - { - tl: [-0.95, 0.5], - br: [0.95, 0.95], - types: [TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE], - description: 'A medium to large text field for a thorough description of the image. ', - opts: { - backgroundColor: 'transparent', - color: 'white', - }, - }, - ], - decorations: [ - { - tl: [0.2, -1.32], - br: [1.8, -0.66], - opts: { - backgroundColor: '#CEB155', - rotation: 45, - }, - }, - { - tl: [-1.8, -1.32], - br: [-0.2, -0.66], - opts: { - backgroundColor: '#CEB155', - rotation: 135, - }, - }, - { - tl: [0.33, 0.75], - br: [1.66, 1.25], - opts: { - backgroundColor: '#CEB155', - rotation: 135, - }, - }, - { - tl: [-1.66, 0.75], - br: [-0.33, 1.25], - opts: { - backgroundColor: '#CEB155', - rotation: 45, - }, - }, - ], - }; - - public static ThreeField002: TemplateDocInfos = { - title: 'threefield2', - width: 477, - height: 662, - opts: { - backgroundColor: '#9E9C95', - }, - fields: [ - { - tl: [-0.875, -0.9], - br: [0.875, 0.7], - types: [TemplateFieldType.VISUAL], - sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], - description: 'A medium to large visual field for the main content of the template', - opts: { - borderWidth: '15', - borderColor: '#E0E0DA', - }, - }, - { - tl: [0.1, 0.775], - br: [0.95, 0.975], - types: [TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], - description: 'A very small text field for one to a few words. The content should represent a general categorization of the image.', - opts: { - backgroundColor: 'transparent', - color: '#AF0D0D', - fontTransform: 'uppercase', - fontBold: true, - contentXCentering: 'h-left', - }, - }, - { - tl: [-0.95, 0.775], - br: [-0.1, 0.975], - types: [TemplateFieldType.TEXT], - sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], - description: 'A very small text field for one to a few words. The content should contextualize field 2.', - opts: { - backgroundColor: 'transparent', - color: 'black', - contentXCentering: 'h-right', - }, - }, - ], - decorations: [ - { - tl: [-0.025, 0.8], - br: [0.025, 0.95], - opts: { - backgroundColor: '#E0E0DA', - }, - }, - ], - }; -} - -export class FieldUtils { - public static contentFields = (fields: Field[]) => { - let toRet: Field[] = []; - fields.forEach(field => { - if (!field.isDecoration) { - toRet.push(field); - } - toRet = toRet.concat(FieldUtils.contentFields(field.subfields ?? [])); - }); - - return toRet; - }; - - public static calculateFontSize = (contWidth: number, contHeight: number, text: string, uppercase: boolean): number => { - const words: string[] = text.split(/\s+/).filter(Boolean); - - let currFontSize = 1; - let rowsCount = 1; - let currTextHeight = currFontSize * rowsCount * 2; - - while (currTextHeight <= contHeight) { - let wordIndex = 0; - let currentRowWidth = 0; - let wordsInCurrRow = 0; - rowsCount = 1; - - while (wordIndex < words.length) { - const word = words[wordIndex]; - const wordWidth = word.length * currFontSize * 0.5; - //console.log(wordWidth) - - if (currentRowWidth + wordWidth <= contWidth) { - currentRowWidth += wordWidth; - ++wordsInCurrRow; - } else { - if (words.length !== 1 && words.length > wordsInCurrRow) { - rowsCount++; - currentRowWidth = wordWidth; - wordsInCurrRow = 1; - } else { - break; - } - } - - wordIndex++; - } - - currTextHeight = rowsCount * currFontSize * 2; - //console.log(rowsCount, currFontSize, currTextHeight) - - currFontSize += 1; - } - - return currFontSize - 1; - }; - - private static getDimensions = (coords: { tl: [number, number]; br: [number, number] }, parentWidth: number, parentHeight: number): { width: number; height: number; coord: { x: number; y: number } } => { - const l = (coords.tl[0] * parentHeight) / 2; - const t = coords.tl[1] * parentWidth / 2; //prettier-ignore - const r = (coords.br[0] * parentHeight) / 2; - const b = coords.br[1] * parentWidth / 2; //prettier-ignore - const width = r - l; - const height = b - t; - const coord = { x: l, y: t }; - //console.log(coords, parentWidth, parentHeight, height); - return { width, height, coord }; - }; - - public static FreeformField = (coords: { tl: [number, number]; br: [number, number] }, parentWidth: number, parentHeight: number, title: string, content: string, opts: FieldOpts) => { - const { width, height, coord } = FieldUtils.getDimensions(coords, parentWidth, parentHeight); - - const docWithBasicOpts = Docs.Create.FreeformDocument([], { - isDefaultTemplateDoc: true, - _height: height, - _width: width, - title: title, - x: coord.x, - y: coord.y, - backgroundColor: opts.backgroundColor ?? '', - _layout_borderRounding: `${opts.cornerRounding ?? 0}px`, - borderColor: opts.borderColor, - borderWidth: opts.borderWidth, - opacity: opts.opacity, - hCentering: opts.contentXCentering, - _rotation: opts.rotation, - }); - - return docWithBasicOpts; - }; - - public static TextField = (coords: { tl: [number, number]; br: [number, number] }, parentWidth: number, parentHeight: number, title: string, content: string, opts: FieldOpts) => { - const { width, height, coord } = FieldUtils.getDimensions(coords, parentWidth, parentHeight); - - const docWithBasicOpts = Docs.Create.TextDocument(content, { - isDefaultTemplateDoc: true, - _height: height, - _width: width, - title: title, - x: coord.x, - y: coord.y, - text_fontSize: `${FieldUtils.calculateFontSize(width, height, content, true)}`, - backgroundColor: opts.backgroundColor ?? '', - text_fontColor: opts.color, - contentBold: opts.fontBold, - text_transform: opts.fontTransform, - color: opts.color, - _layout_borderRounding: `${opts.cornerRounding ?? 0}px`, - borderColor: opts.borderColor, - borderWidth: opts.borderWidth, - opacity: opts.opacity, - hCentering: opts.contentXCentering, - _rotation: opts.rotation, - }); - - docWithBasicOpts._layout_hideScroll = true; - - return docWithBasicOpts; - }; - - public static ImageField = (coords: { tl: [number, number]; br: [number, number] }, parentWidth: number, parentHeight: number, title: string, content: string, opts: FieldOpts) => { - const { width, height, coord } = FieldUtils.getDimensions(coords, parentWidth, parentHeight); - - const doc = Docs.Create.ImageDocument(content, { - isDefaultTemplateDoc: true, - _height: height, - _width: width, - title: title, - x: coord.x, - y: coord.y, - _layout_fitWidth: false, - backgroundColor: opts.backgroundColor ?? '', - _layout_borderRounding: `${opts.cornerRounding ?? 0}px`, - borderColor: opts.borderColor, - borderWidth: opts.borderWidth, - opacity: opts.opacity, - _rotation: opts.rotation, - }); - - //setTimeout(() => {doc._height = height; doc._width = width}, 10); - - return doc; - }; - - public static CarouselField = (coords: { tl: [number, number]; br: [number, number] }, parentWidth: number, parentHeight: number, title: string, fields: Doc[]) => { - const { width, height, coord } = FieldUtils.getDimensions(coords, parentWidth, parentHeight); - - const doc = Docs.Create.Carousel3DDocument(fields, { _height: height, _width: width, title: title, x: coord.x, y: coord.y, text_fontSize: `${height / 2}` }); - - return doc; - }; -} - -// public static FourField002: TemplateDocInfos = { -// width: 450, -// height: 600, -// fields: [{ -// tl: [-.6, -.9], -// br: [.6, -.8], -// types: [FieldType.TEXT], -// sizes: [FieldSize.TINY] -// }, { -// tl: [-.9, -.7], -// br: [.9, .2], -// types: [FieldType.TEXT, FieldType.VISUAL], -// sizes: [FieldSize.MEDIUM, FieldSize.LARGE, FieldSize.HUGE] -// }, { -// tl: [-.9, .3], -// br: [-.05, .9], -// types: [FieldType.TEXT], -// sizes: [FieldSize.TINY] -// }, { -// tl: [.05, .3], -// br: [.9, .9], -// types: [FieldType.TEXT, FieldType.VISUAL], -// sizes: [FieldSize.MEDIUM, FieldSize.LARGE, FieldSize.HUGE] -// }] -// }; - -// public static TwoFieldPlusCarousel: TemplateDocInfos = { -// width: 500, -// height: 600, -// fields: [{ -// tl: [-.9, -.99], -// br: [.9, -.7], -// types: [FieldType.TEXT], -// sizes: [FieldSize.TINY] -// }, { -// tl: [-.9, -.65], -// br: [.9, .35], -// types: [], -// sizes: [] -// }, { -// tl: [-.9, .4], -// br: [.9, .95], -// types: [FieldType.TEXT], -// sizes: [FieldSize.TINY] -// }] -// }; -// } diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu.scss b/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.scss index 4ea904b8e..57f4a1e94 100644 --- a/src/client/views/nodes/DataVizBox/DocCreatorMenu.scss +++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.scss @@ -7,7 +7,7 @@ .docCreatorMenu-cont { position: absolute; - z-index: 100000; + z-index: 1000; // box-shadow: 0px 3px 4px rgba(0, 0, 0, 30%); // background: whitesmoke; // color: black; @@ -45,9 +45,10 @@ font-size: 12px; width: 18px; height: 18px; - border-radius: 2px; font-size: 12px; margin-left: auto; + margin-right: 5px; + margin-bottom: 3px; } &.options { @@ -292,6 +293,7 @@ display: flex; flex-direction: column; justify-content: flex-start; + color: black; position: relative; width: 100%; height: 100%; @@ -324,6 +326,7 @@ height: 113px; margin-top: 10px; margin-left: 10px; + color: none; border: 1px solid rgb(163, 163, 163); border-radius: 5px; box-shadow: 5px 5px rgb(29, 29, 31); @@ -350,6 +353,7 @@ border: 0px; padding: 0px; font-size: 15px; + z-index: 1000; &.right { position: absolute; @@ -422,6 +426,7 @@ align-items: center; overflow-y: scroll; position: relative; + color: black; height: 125px; width: calc(100% - 10px); -ms-overflow-style: none; @@ -524,8 +529,6 @@ background: whitesmoke; background-color: rgb(34, 34, 37); border-radius: 5px; - border-top-right-radius: 0px; - border-bottom-right-radius: 0px; border: 1px solid rgb(180, 180, 180); padding: 0px; font-size: 12px; @@ -634,6 +637,8 @@ height: calc(100% - 30px); border: 1px solid rgb(180, 180, 180); border-radius: 5px; + -ms-overflow-style: none; + scrollbar-width: none; .docCreatorMenu-option-container{ width: 180px; @@ -686,13 +691,24 @@ } .docCreatorMenu-layout-preview-window-wrapper { + flex: 0 0 auto; display: flex; justify-content: center; align-items: center; - width: 85%; - height: auto; + color: black; + width: calc(100% - 50px); + height: calc(100% - 50px); position: relative; - padding: 0px; + border: 1px solid rgb(180, 180, 180); + padding: 10px; + margin-left: 20px; + margin-right: 20px; + + &.loading { + width: 100px; + height: 100px; + border: none; + } &:hover .docCreatorMenu-zoom-button-container { display: block; diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx b/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx new file mode 100644 index 000000000..64416c26d --- /dev/null +++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu/DocCreatorMenu.tsx @@ -0,0 +1,1458 @@ +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { Colors } from '@dash/components'; +import { action, computed, makeObservable, observable, runInAction } from 'mobx'; +import { observer } from 'mobx-react'; +import { IDisposer } from 'mobx-utils'; +import * as React from 'react'; +import ReactLoading from 'react-loading'; +import { ClientUtils, returnEmptyFilter, returnFalse, setupMoveUpEvents } from '../../../../../ClientUtils'; +import { emptyFunction } from '../../../../../Utils'; +import { Doc, NumListCast, StrListCast, returnEmptyDoclist } from '../../../../../fields/Doc'; +import { Id } from '../../../../../fields/FieldSymbols'; +import { ImageCast, StrCast } from '../../../../../fields/Types'; +import { ImageField } from '../../../../../fields/URLField'; +import { Networking } from '../../../../Network'; +import { GPTCallType, gptAPICall, gptImageCall } from '../../../../apis/gpt/GPT'; +import { Docs, DocumentOptions } from '../../../../documents/Documents'; +import { DragManager } from '../../../../util/DragManager'; +import { SnappingManager } from '../../../../util/SnappingManager'; +import { UndoManager, undoable } from '../../../../util/UndoManager'; +import { ObservableReactComponent } from '../../../ObservableReactComponent'; +import { CollectionFreeFormView } from '../../../collections/collectionFreeForm/CollectionFreeFormView'; +import { DocumentView, DocumentViewInternal } from '../../DocumentView'; +import { OpenWhere } from '../../OpenWhere'; +import { DataVizBox } from '../DataVizBox'; +import './DocCreatorMenu.scss'; +import { DefaultStyleProvider } from '../../../StyleProvider'; +import { Transform } from '../../../../util/Transform'; +import { TemplateFieldSize, TemplateFieldType, TemplateLayouts } from './TemplateBackend'; +import { TemplateManager } from './TemplateManager'; +import { Template } from './Template'; +import { Field, FieldContentType } from './FieldTypes/Field'; +import { IconProp } from '@fortawesome/fontawesome-svg-core'; +import { Upload } from '../../../../../server/SharedMediaTypes'; + +export enum LayoutType { + FREEFORM = 'Freeform', + CAROUSEL = 'Carousel', + CAROUSEL3D = '3D Carousel', + MASONRY = 'Masonry', + CARD = 'Card View', +} + +export interface DataVizTemplateInfo { + doc: Doc; + layout: { type: LayoutType; xMargin: number; yMargin: number; repeat: number }; + columns: number; + referencePos: { x: number; y: number }; +} + +export interface DataVizTemplateLayout { + template: Doc; + docsNumList: number[]; + layout: { type: LayoutType; xMargin: number; yMargin: number; repeat: number }; + columns: number; + rows: number; +} + +export type Col = { + sizes: TemplateFieldSize[]; + desc: string; + title: string; + type: TemplateFieldType; + defaultContent?: string; +}; + +interface DocCreateMenuProps { + addDocTab: (doc: Doc | Doc[], where: OpenWhere) => boolean; +} + +@observer +export class DocCreatorMenu extends ObservableReactComponent<DocCreateMenuProps> { + // eslint-disable-next-line no-use-before-define + static Instance: DocCreatorMenu; + + private _disposers: { [name: string]: IDisposer } = {}; + + private _ref: HTMLDivElement | null = null; + + private templateManager: TemplateManager; + + @observable _fullyRenderedDocs: Doc[] = []; + @observable _renderedDocCollectionPreview: Doc | undefined = undefined; + @observable _renderedDocCollection: Doc | undefined = undefined; + @observable _docsRendering: boolean = false; + + @observable _userTemplates: { template: Template; doc: Doc }[] = []; //!!! used to keep track of all templates, should be refactored to work with actual templates and not docs + @observable _selectedTemplate: Template | undefined = undefined; + @observable _currEditingTemplate: Template | undefined = undefined; + + @observable _userCreatedFields: Col[] = []; + @observable _selectedCols: { title: string; type: string; desc: string }[] | undefined = []; + + @observable _layout: { type: LayoutType; yMargin: number; xMargin: number; columns?: number; repeat: number } = { type: LayoutType.FREEFORM, yMargin: 10, xMargin: 10, columns: 3, repeat: 0 }; + @observable _layoutPreviewScale: number = 1; + @observable _savedLayouts: DataVizTemplateLayout[] = []; + @observable _expandedPreview: Doc | undefined = undefined; + + @observable _suggestedTemplates: Template[] = []; + @observable _suggestedTemplatePreviews: { doc: Doc; template: Template }[] = []; + @observable _GPTOpt: boolean = false; + @observable _callCount: number = 0; + @observable _GPTLoading: boolean = false; + + @observable _pageX: number = 0; + @observable _pageY: number = 0; + + @observable _hoveredLayoutPreview: number | undefined = undefined; + @observable _mouseX: number = -1; + @observable _mouseY: number = -1; + @observable _startPos?: { x: number; y: number }; + @observable _shouldDisplay: boolean = false; + + @observable _menuContent: 'templates' | 'options' | 'saved' | 'dashboard' = 'templates'; + @observable _dragging: boolean = false; + @observable _draggingIndicator: boolean = false; + @observable _dataViz?: DataVizBox; + @observable _interactionLock: boolean | undefined; + @observable _snapPt: { x: number; y: number } = { x: 0, y: 0 }; + @observable _resizeHdlId: string = ''; + @observable _resizing: boolean = false; + @observable _offset: { x: number; y: number } = { x: 0, y: 0 }; + @observable _resizeUndo: UndoManager.Batch | undefined = undefined; + @observable _initDimensions: { width: number; height: number; x?: number; y?: number } = { width: 300, height: 400, x: undefined, y: undefined }; + @observable _menuDimensions: { width: number; height: number } = { width: 400, height: 400 }; + @observable _editing: boolean = false; + + constructor(props: DocCreateMenuProps) { + super(props); + makeObservable(this); + DocCreatorMenu.Instance = this; + this.templateManager = new TemplateManager(TemplateLayouts.allTemplates); + } + + @action setDataViz = (dataViz: DataVizBox) => { + this._dataViz = dataViz; + this._selectedTemplate = undefined; + this._renderedDocCollection = undefined; + this._renderedDocCollectionPreview = undefined; + this._fullyRenderedDocs = []; + this._suggestedTemplatePreviews = []; + this._suggestedTemplates = []; + this._userCreatedFields = []; + }; + @action addUserTemplate = (template: Template) => { + this._userTemplates.push({ template: template.cloneBase(), doc: template.getRenderedDoc() }); + }; + @action removeUserTemplate = (template: Template) => { + this._userTemplates = this._userTemplates.filter(info => info.template !== template); + }; + @action updateTemplatePreview = (template: Template) => { + template.renderUpdates(); + const preview = { template: template, doc: template.getRenderedDoc() }; + this._suggestedTemplatePreviews = this._suggestedTemplatePreviews.map(t => { return t.template === preview.template ? preview : t }); //prettier-ignore + this._userTemplates = this._userTemplates.map(t => { return t.template === preview.template ? preview : t }); //prettier-ignore + }; + @action setSuggestedTemplates = (templates: Template[]) => { + this._suggestedTemplates = templates; + this._suggestedTemplatePreviews = templates.map(template => {return {template: template, doc: template.getRenderedDoc()}}); //prettier-ignore + }; + + @computed get docsToRender() { + return this._selectedTemplate ? NumListCast(this._dataViz?.layoutDoc.dataViz_selectedRows) : []; + } + + @computed get rowsCount() { + switch (this._layout.type) { + case LayoutType.FREEFORM: + return Math.ceil(this.docsToRender.length / (this._layout.columns ?? 1)) ?? 0; + case LayoutType.CAROUSEL3D: + return 1.8; + default: + return 1; + } + } + + @computed get columnsCount() { + switch (this._layout.type) { + case LayoutType.FREEFORM: + return this._layout.columns ?? 0; + case LayoutType.CAROUSEL3D: + return 3; + default: + return 1; + } + } + + @computed get selectedFields() { + return StrListCast(this._dataViz?.layoutDoc._dataViz_axes); + } + + @computed get fieldsInfos(): Col[] { + const colInfo = this._dataViz?.colsInfo; + return this.selectedFields + .map(field => { + const fieldInfo = colInfo?.get(field); + + const col: Col = { + title: field, + type: fieldInfo?.type ?? TemplateFieldType.UNSET, + desc: fieldInfo?.desc ?? '', + sizes: fieldInfo?.sizes ?? [TemplateFieldSize.MEDIUM], + }; + + if (fieldInfo?.defaultContent !== undefined) { + col.defaultContent = fieldInfo.defaultContent; + } + + return col; + }) + .concat(this._userCreatedFields); + } + + @computed get canMakeDocs() { + return this._selectedTemplate !== undefined && this._layout !== undefined; + } + + get bounds(): { t: number; b: number; l: number; r: number } { + const rect = this._ref?.getBoundingClientRect(); + const bounds = { t: rect?.top ?? 0, b: rect?.bottom ?? 0, l: rect?.left ?? 0, r: rect?.right ?? 0 }; + return bounds; + } + + setUpButtonClick = (e: React.PointerEvent, func: () => void) => { + setupMoveUpEvents( + this, + e, + returnFalse, + emptyFunction, + undoable(clickEv => { + clickEv.stopPropagation(); + clickEv.preventDefault(); + func(); + }, 'create docs') + ); + }; + + @action + onPointerDown = (e: PointerEvent) => { + this._mouseX = e.clientX; + this._mouseY = e.clientY; + }; + + @action + onPointerUp = (e: PointerEvent) => { + if (this._resizing) { + this._initDimensions.width = this._menuDimensions.width; + this._initDimensions.height = this._menuDimensions.height; + this._initDimensions.x = this._pageX; + this._initDimensions.y = this._pageY; + document.removeEventListener('pointermove', this.onResize); + SnappingManager.SetIsResizing(undefined); + this._resizing = false; + } + if (this._dragging) { + document.removeEventListener('pointermove', this.onDrag); + this._dragging = false; + } + if (e.button !== 2 && !e.ctrlKey) return; + const curX = e.clientX; + const curY = e.clientY; + if (Math.abs(this._mouseX - curX) > 1 || Math.abs(this._mouseY - curY) > 1) { + this._shouldDisplay = false; + } + }; + + componentDidMount() { + document.addEventListener('pointerdown', this.onPointerDown, true); + document.addEventListener('pointerup', this.onPointerUp); + } + + componentWillUnmount() { + Object.values(this._disposers).forEach(disposer => disposer?.()); + document.removeEventListener('pointerdown', this.onPointerDown, true); + document.removeEventListener('pointerup', this.onPointerUp); + } + + @action + toggleDisplay = (x: number, y: number) => { + if (this._shouldDisplay) { + this._shouldDisplay = false; + } else { + this._pageX = x; + this._pageY = y; + this._shouldDisplay = true; + } + }; + + @action + closeMenu = () => { + this._shouldDisplay = false; + }; + + @action + openMenu = () => { + this._shouldDisplay = true; + }; + + @action + onResizePointerDown = (e: React.PointerEvent): void => { + this._resizing = true; + document.addEventListener('pointermove', this.onResize); + SnappingManager.SetIsResizing(DocumentView.Selected().lastElement()?.Document[Id]); // turns off pointer events on things like youtube videos and web pages so that dragging doesn't get "stuck" when cursor moves over them + e.stopPropagation(); + const id = (this._resizeHdlId = e.currentTarget.className); + const pad = id.includes('Left') || id.includes('Right') ? Number(getComputedStyle(e.target as HTMLElement).width.replace('px', '')) / 2 : 0; + const bounds = e.currentTarget.getBoundingClientRect(); + this._offset = { + x: id.toLowerCase().includes('left') ? bounds.right - e.clientX - pad : bounds.left - e.clientX + pad, // + y: id.toLowerCase().includes('top') ? bounds.bottom - e.clientY - pad : bounds.top - e.clientY + pad, + }; + this._resizeUndo = UndoManager.StartBatch('drag resizing'); + this._snapPt = { x: e.pageX, y: e.pageY }; + }; + + @action + onResize = (e: PointerEvent): boolean => { + const dragHdl = this._resizeHdlId.split(' ')[1]; + const thisPt = DragManager.snapDrag(e, -this._offset.x, -this._offset.y, this._offset.x, this._offset.y); + + const { scale, refPt, transl } = this.getResizeVals(thisPt, dragHdl); + !this._interactionLock && runInAction(async () => { // resize selected docs if we're not in the middle of a resize (ie, throttle input events to frame rate) + this._interactionLock = true; + const scaleAspect = {x: scale.x, y: scale.y}; + this.resizeView(refPt, scaleAspect, transl); // prettier-ignore + await new Promise<boolean | undefined>(res => { setTimeout(() => { res(this._interactionLock = undefined)})}); + }); // prettier-ignore + return true; + }; + + @action + onDrag = (e: PointerEvent): boolean => { + this._pageX = e.pageX - (this._startPos?.x ?? 0); + this._pageY = e.pageY - (this._startPos?.y ?? 0); + this._initDimensions.x = this._pageX; + this._initDimensions.y = this._pageY; + return true; + }; + + getResizeVals = (thisPt: { x: number; y: number }, dragHdl: string) => { + const [w, h] = [this._initDimensions.width, this._initDimensions.height]; + const [moveX, moveY] = [thisPt.x - this._snapPt!.x, thisPt.y - this._snapPt!.y]; + let vals: { scale: { x: number; y: number }; refPt: [number, number]; transl: { x: number; y: number } }; + switch (dragHdl) { + case 'topLeft': vals = { scale: { x: 1 - moveX / w, y: 1 -moveY / h }, refPt: [this.bounds.r, this.bounds.b], transl: {x: moveX, y: moveY } }; break; + case 'topRight': vals = { scale: { x: 1 + moveX / w, y: 1 -moveY / h }, refPt: [this.bounds.l, this.bounds.b], transl: {x: 0, y: moveY } }; break; + case 'top': vals = { scale: { x: 1, y: 1 -moveY / h }, refPt: [this.bounds.l, this.bounds.b], transl: {x: 0, y: moveY } }; break; + case 'left': vals = { scale: { x: 1 - moveX / w, y: 1 }, refPt: [this.bounds.r, this.bounds.t], transl: {x: moveX, y: 0 } }; break; + case 'bottomLeft': vals = { scale: { x: 1 - moveX / w, y: 1 + moveY / h }, refPt: [this.bounds.r, this.bounds.t], transl: {x: moveX, y: 0 } }; break; + case 'right': vals = { scale: { x: 1 + moveX / w, y: 1 }, refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break; + case 'bottomRight':vals = { scale: { x: 1 + moveX / w, y: 1 + moveY / h }, refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break; + case 'bottom': vals = { scale: { x: 1, y: 1 + moveY / h }, refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break; + default: vals = { scale: { x: 1, y: 1 }, refPt: [this.bounds.l, this.bounds.t], transl: {x: 0, y: 0 } }; break; + } // prettier-ignore + return vals; + }; + + resizeView = (refPt: number[], scale: { x: number; y: number }, translation: { x: number; y: number }) => { + if (this._initDimensions.x === undefined) this._initDimensions.x = this._pageX; + if (this._initDimensions.y === undefined) this._initDimensions.y = this._pageY; + const { height, width, x, y } = this._initDimensions; + + this._menuDimensions.width = Math.max(300, scale.x * width); + this._menuDimensions.height = Math.max(200, scale.y * height); + this._pageX = x + translation.x; + this._pageY = y + translation.y; + }; + + async getIcon(doc: Doc) { + const docView = DocumentView.getDocumentView(doc); + if (docView) { + docView.ComponentView?.updateIcon?.(); + return new Promise<ImageField | undefined>(res => setTimeout(() => res(ImageCast(docView.Document.icon)), 500)); + } + return undefined; + } + + @action updateSelectedTemplate = async (template: Template) => { + if (this._selectedTemplate === template) { + this._selectedTemplate = undefined; + return; + } else { + this._selectedTemplate = template; + template.renderUpdates(); + this._fullyRenderedDocs = (await this.createDocsFromTemplate(template)) ?? []; + this.updateRenderedDocCollection(); + } + }; + + @action updateSelectedSavedLayout = (layout: DataVizTemplateLayout) => { + this._layout.xMargin = layout.layout.xMargin; + this._layout.yMargin = layout.layout.yMargin; + this._layout.type = layout.layout.type; + this._layout.columns = layout.columns; + }; + + isSelectedLayout = (layout: DataVizTemplateLayout) => { + return this._layout.xMargin === layout.layout.xMargin && this._layout.yMargin === layout.layout.yMargin && this._layout.type === layout.layout.type && this._layout.columns === layout.columns; + }; + + editTemplate = (doc: Doc) => { + DocumentViewInternal.addDocTabFunc(doc, OpenWhere.addRight); + DocumentView.DeselectAll(); + Doc.UnBrushDoc(doc); + }; + + @action addField = () => { + const newFields: Col[] = this._userCreatedFields.concat([{ title: '', type: TemplateFieldType.UNSET, desc: '', sizes: [] }]); + this._userCreatedFields = newFields; + }; + + @action removeField = (field: { title: string; type: string; desc: string }) => { + if (this._dataViz?.axes.includes(field.title)) { + this._dataViz.selectAxes(this._dataViz.axes.filter(col => col !== field.title)); + } else { + const toRemove = this._userCreatedFields.filter(f => f === field); + if (!toRemove) return; + + if (toRemove.length > 1) { + while (toRemove.length > 1) { + toRemove.pop(); + } + } + + if (this._userCreatedFields.length === 1) { + this._userCreatedFields = []; + } else { + this._userCreatedFields.splice(this._userCreatedFields.indexOf(toRemove[0]), 1); + } + } + }; + + @action setColTitle = (column: Col, title: string) => { + if (this.selectedFields.includes(column.title)) { + this._dataViz?.setColumnTitle(column.title, title); + } else { + column.title = title; + } + this.forceUpdate(); + }; + + @action setColType = (column: Col, type: TemplateFieldType) => { + if (this.selectedFields.includes(column.title)) { + this._dataViz?.setColumnType(column.title, type); + } else { + column.type = type; + } + this.forceUpdate(); + }; + + modifyColSizes = (column: Col, size: TemplateFieldSize, valid: boolean) => { + if (this.selectedFields.includes(column.title)) { + this._dataViz?.modifyColumnSizes(column.title, size, valid); + } else { + if (!valid && column.sizes.includes(size)) { + column.sizes.splice(column.sizes.indexOf(size), 1); + } else if (valid && !column.sizes.includes(size)) { + column.sizes.push(size); + } + } + this.forceUpdate(); + }; + + setColDesc = (column: Col, desc: string) => { + if (this.selectedFields.includes(column.title)) { + this._dataViz?.setColumnDesc(column.title, desc); + } else { + column.desc = desc; + } + this.forceUpdate(); + }; + + generateGPTImage = async (prompt: string): Promise<string | undefined> => { + try { + const res = await gptImageCall(prompt); + + if (res) { + const result = (await Networking.PostToServer('/uploadRemoteImage', { sources: res })) as Upload.FileInformation[]; + const source = ClientUtils.prepend(result[0].accessPaths.agnostic.client); + return source; + } + } catch (e) { + console.log(e); + } + }; + + /** + * Populates a preset template framework with content from a datavizbox or any AI-generated content. + * @param template the preloaded template framework being filled in + * @param assignments a list of template field numbers (from top to bottom) and their assigned columns from the linked dataviz + * @returns a doc containing the fully rendered template + */ + applyGPTContentToTemplate = async (template: Template, assignments: { [field: string]: Col }): Promise<Template | undefined> => { + const GPTTextCalls = Object.entries(assignments).filter(([, col]) => col.type === TemplateFieldType.TEXT && this._userCreatedFields.includes(col)); + const GPTIMGCalls = Object.entries(assignments).filter(([, col]) => col.type === TemplateFieldType.VISUAL && this._userCreatedFields.includes(col)); + + if (GPTTextCalls.length) { + const promises = GPTTextCalls.map(([str, col]) => { + return this.renderGPTTextCall(template, col, Number(str)); + }); + + await Promise.all(promises); + } + + if (GPTIMGCalls.length) { + const promises = GPTIMGCalls.map(async ([fieldNum, col]) => { + return this.renderGPTImageCall(template, col, Number(fieldNum)); + }); + + await Promise.all(promises); + } + + return template; + }; + + compileFieldDescriptions = (templates: Template[]): string => { + let descriptions: string = ''; + templates.forEach(template => { + descriptions += `---------- NEW TEMPLATE TO INCLUDE: The title is: ${template.mainField.getTitle()}. Its fields are: `; + descriptions += template.descriptionSummary; + }); + + return descriptions; + }; + + compileColDescriptions = (cols: Col[]): string => { + let descriptions: string = ' ------------- COL DESCRIPTIONS START HERE:'; + cols.forEach(col => (descriptions += `{title: ${col.title}, sizes: ${String(col.sizes)}, type: ${col.type}, descreiption: ${col.desc}} `)); + + return descriptions; + }; + + getColByTitle = (title: string) => { + return this.fieldsInfos.filter(col => col.title === title)[0]; + }; + + @action + assignColsToFields = async (templates: Template[], cols: Col[]): Promise<[Template, { [field: number]: Col }][]> => { + const fieldDescriptions: string = this.compileFieldDescriptions(templates); + const colDescriptions: string = this.compileColDescriptions(cols); + + const inputText = fieldDescriptions.concat(colDescriptions); + + ++this._callCount; + const origCount = this._callCount; + + const prompt: string = `(${origCount}) ${inputText}`; + + this._GPTLoading = true; + + try { + const res = await gptAPICall(prompt, GPTCallType.TEMPLATE); + + if (res) { + const assignments: { [templateTitle: string]: { [fieldID: string]: string } } = JSON.parse(res); + const brokenDownAssignments: [Template, { [fieldID: number]: Col }][] = []; + + Object.entries(assignments).forEach(([tempTitle, assignment]) => { + const template = templates.filter(t => t.mainField.getTitle() === tempTitle)[0]; + if (!template) return; + const toObj = Object.entries(assignment).reduce( + (a, [fieldID, colTitle]) => { + const col = this.getColByTitle(colTitle); + if (!this._userCreatedFields.includes(col)) { + // do the following for any fields not added by the user; will change in the future, for now only GPT content works with user-added fields + const field = template.getFieldByID(Number(fieldID)); + field.setContent(col.defaultContent ?? '', col.type === TemplateFieldType.VISUAL ? FieldContentType.IMAGE : FieldContentType.STRING); + field.setTitle(col.title); + } else { + a[Number(fieldID)] = this.getColByTitle(colTitle); + } + return a; + }, + {} as { [field: number]: Col } + ); + brokenDownAssignments.push([template, toObj]); + }); + + return brokenDownAssignments; + } + } catch (err) { + console.error(err); + } + + return []; + }; + + generatePresetTemplates = async () => { + this._dataViz?.updateColDefaults(); + + const cols = this.fieldsInfos; + const templates = this.templateManager.getValidTemplates(cols); + + const assignments: [Template, { [field: number]: Col }][] = await this.assignColsToFields(templates, cols); + + const renderedTemplatePromises: Promise<Template | undefined>[] = assignments.map(([template, asns]) => this.applyGPTContentToTemplate(template, asns)); + + await Promise.all(renderedTemplatePromises); + + setTimeout(() => { + this.setSuggestedTemplates(templates); + this._GPTLoading = false; + }); + }; + + renderGPTImageCall = async (template: Template, col: Col, fieldNumber: number): Promise<boolean> => { + const generateAndLoadImage = async (fieldNum: string, column: Col, prompt: string) => { + const url = await this.generateGPTImage(prompt); + const field: Field = template.getFieldByID(Number(fieldNum)); + + field.setContent(url ?? '', FieldContentType.IMAGE); + field.setTitle(column.title); + }; + + const fieldContent: string = template.compiledContent; + + try { + const sysPrompt = + 'Your job is to create a prompt for an AI image generator to help it generate an image based on existing content in a template and a user prompt. Your prompt should focus heavily on visual elements to help the image generator; avoid unecessary info that might distract it. ONLY INCLUDE THE PROMPT, NO OTHER TEXT OR EXPLANATION. The existing content is as follows: ' + + fieldContent + + ' **** The user prompt is: ' + + col.desc; + + const prompt = await gptAPICall(sysPrompt, GPTCallType.COMPLETEPROMPT); + + await generateAndLoadImage(String(fieldNumber), col, prompt); + } catch (e) { + console.log(e); + } + return true; + }; + + renderGPTTextCall = async (template: Template, col: Col, fieldNum: number): Promise<boolean> => { + const wordLimit = (size: TemplateFieldSize) => { + switch (size) { + case TemplateFieldSize.TINY: + return 2; + case TemplateFieldSize.SMALL: + return 5; + case TemplateFieldSize.MEDIUM: + return 20; + case TemplateFieldSize.LARGE: + return 50; + case TemplateFieldSize.HUGE: + return 100; + default: + return 10; + } + }; + + const textAssignment = `--- title: ${col.title}, prompt: ${col.desc}, word limit: ${wordLimit(col.sizes[0])} words, assigned field: ${fieldNum} ---`; + + const fieldContent: string = template.compiledContent; + + try { + const prompt = fieldContent + textAssignment; + + const res = await gptAPICall(`${++this._callCount}: ${prompt}`, GPTCallType.FILL); + + if (res) { + const assignments: { [title: string]: { number: string; content: string } } = JSON.parse(res); + Object.entries(assignments).forEach(([title, info]) => { + const field: Field = template.getFieldByID(Number(info.number)); + const column = this.getColByTitle(title); + + field.setContent(info.content ?? '', FieldContentType.STRING); + field.setTitle(column.title); + }); + } + } catch (err) { + console.log(err); + } + + return true; + }; + + createDocsFromTemplate = async (template: Template) => { + const dv = this._dataViz; + + if (!dv) return; + + this._docsRendering = true; + + const fields: string[] = Array.from(Object.keys(dv.records[0])); + const selectedRows = NumListCast(dv.layoutDoc.dataViz_selectedRows); + + const rowContents: { [title: string]: string }[] = selectedRows.map(row => { + const values: { [title: string]: string } = {}; + fields.forEach(col => { + values[col] = dv.records[row][col]; + }); + + return values; + }); + + const processContent = async (content: { [title: string]: string }) => { + const templateCopy = template.cloneBase(); + + fields + .filter(title => title) + .forEach(title => { + const field = templateCopy.getFieldByTitle(title); + if (field === undefined) { + return; + } + field.setContent(content[title]); + }); + + const gptPromises = this._userCreatedFields + .filter(field => field.type === TemplateFieldType.TEXT) + .map(field => { + const title = field.title; + const templateField = templateCopy.getFieldByTitle(title); + if (templateField === undefined) { + return; + } + const templatefieldID = templateField.getID; + + return this.renderGPTTextCall(templateCopy, field, templatefieldID); + }); + + const imagePromises = this._userCreatedFields + .filter(field => field.type === TemplateFieldType.VISUAL) + .map(field => { + const title = field.title; + const templateField = templateCopy.getFieldByTitle(title); + if (templateField === undefined) { + return; + } + const templatefieldID = templateField.getID; + + return this.renderGPTImageCall(templateCopy, field, templatefieldID); + }); + + await Promise.all(gptPromises); + + await Promise.all(imagePromises); + + return templateCopy.getRenderedDoc(); + }; + + const promises = rowContents.map(content => processContent(content)); + + const renderedDocs = await Promise.all(promises); + + this._docsRendering = false; + + return renderedDocs; + }; + + addRenderedCollectionToMainview = () => { + const collection = this._renderedDocCollection; + if (!collection) return; + const mainCollection = this._dataViz?.DocumentView?.().containerViewPath?.().lastElement()?.ComponentView as CollectionFreeFormView; + collection.x = this._pageX - this._menuDimensions.width; + collection.y = this._pageY - this._menuDimensions.height; + mainCollection.addDocument(collection); + this.closeMenu(); + }; + + @action setExpandedView = (template: Template | undefined) => { + if (template) { + this._currEditingTemplate = template; + this._expandedPreview = template.mainField.renderedDoc(); //Docs.Create.FreeformDocument([doc], { _height: NumListCast(doc._height)[0], _width: NumListCast(doc._width)[0], title: ''}); + } else { + this._currEditingTemplate = undefined; + this._expandedPreview = undefined; + } + }; + + get editingWindow() { + const rendered = !this._expandedPreview ? null : ( + <div className="docCreatorMenu-expanded-template-preview"> + <DocumentView + Document={this._expandedPreview} + isContentActive={emptyFunction} + addDocument={returnFalse} + moveDocument={returnFalse} + removeDocument={returnFalse} + PanelWidth={() => this._menuDimensions.width - 10} + PanelHeight={() => this._menuDimensions.height - 60} + ScreenToLocalTransform={() => new Transform(-this._pageX - 5, -this._pageY - 35, 1)} + renderDepth={5} + whenChildContentsActiveChanged={emptyFunction} + focus={emptyFunction} + styleProvider={DefaultStyleProvider} + addDocTab={DocumentViewInternal.addDocTabFunc} + pinToPres={() => undefined} + childFilters={returnEmptyFilter} + childFiltersByRanges={returnEmptyFilter} + searchFilterDocs={returnEmptyDoclist} + fitContentsToBox={returnFalse} + fitWidth={returnFalse} + /> + </div> + ); + + return ( + <div className="docCreatorMenu-expanded-template-preview"> + <div className="top-panel" /> + {rendered} + <div className="right-buttons-panel"> + <button + className="docCreatorMenu-menu-button section-reveal-options top-right" + onPointerDown={e => + this.setUpButtonClick(e, () => { + this._currEditingTemplate && this.updateTemplatePreview(this._currEditingTemplate); + this.setExpandedView(undefined); + }) + }> + <FontAwesomeIcon icon="minimize" /> + </button> + <button + className="docCreatorMenu-menu-button section-reveal-options top-right-lower" + onPointerDown={e => + this.setUpButtonClick(e, () => { + this._currEditingTemplate?.resetToBase(); + this.setExpandedView(this._currEditingTemplate); + }) + }> + <FontAwesomeIcon icon="arrows-rotate" color="white" /> + </button> + </div> + </div> + ); + } + + get templatesPreviewContents() { + const GPTOptions = <div></div>; + + return ( + <div className={`docCreatorMenu-templates-view`}> + {this._expandedPreview ? ( + this.editingWindow + ) : ( + <div> + <div className="docCreatorMenu-section" style={{ height: this._GPTOpt ? 200 : 200 }}> + <div className="docCreatorMenu-section-topbar"> + <div className="docCreatorMenu-section-title">Suggested Templates</div> + <button className="docCreatorMenu-menu-button section-reveal-options" onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => (this._menuContent = 'dashboard')))}> + <FontAwesomeIcon icon="gear" /> + </button> + </div> + <div className="docCreatorMenu-templates-preview-window" style={{ justifyContent: this._GPTLoading || this._menuDimensions.width > 400 ? 'center' : '' }}> + {this._GPTLoading ? ( + <div className="loading-spinner"> + <ReactLoading type="spin" color={StrCast(Doc.UserDoc().userVariantColor)} height={30} width={30} /> + </div> + ) : ( + this._suggestedTemplatePreviews.map(({ doc, template }) => ( + <div + className="docCreatorMenu-preview-window" + key="0" + style={{ + border: this._selectedTemplate === template ? `solid 3px ${Colors.MEDIUM_BLUE}` : '', + boxShadow: this._selectedTemplate === template ? `0 0 15px rgba(68, 118, 247, .8)` : '', + }} + onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this.updateSelectedTemplate(template)))}> + <button + className="option-button left" + onPointerDown={e => + this.setUpButtonClick(e, () => { + this.setExpandedView(template); + }) + }> + <FontAwesomeIcon icon="magnifying-glass" color="white" /> + </button> + <button className="option-button right" onPointerDown={e => this.setUpButtonClick(e, () => this.addUserTemplate(template))}> + <FontAwesomeIcon icon="plus" color="white" /> + </button> + <DocumentView + Document={doc} + isContentActive={emptyFunction} // !!! should be return false + addDocument={returnFalse} + moveDocument={returnFalse} + removeDocument={returnFalse} + PanelWidth={() => (this._selectedTemplate === template ? 104 : 111)} + PanelHeight={() => (this._selectedTemplate === template ? 104 : 111)} + ScreenToLocalTransform={() => new Transform(-this._pageX - 5, -this._pageY - 35, 1)} + renderDepth={1} + whenChildContentsActiveChanged={emptyFunction} + focus={emptyFunction} + styleProvider={DefaultStyleProvider} + addDocTab={this._props.addDocTab} + pinToPres={() => undefined} + childFilters={returnEmptyFilter} + childFiltersByRanges={returnEmptyFilter} + searchFilterDocs={returnEmptyDoclist} + fitContentsToBox={returnFalse} + fitWidth={returnFalse} + hideDecorations={true} + /> + </div> + )) + )} + </div> + <div className="docCreatorMenu-GPT-options"> + <div className="docCreatorMenu-GPT-options-container"> + <button className="docCreatorMenu-menu-button" onPointerDown={e => this.setUpButtonClick(e, () => this.generatePresetTemplates())}> + <FontAwesomeIcon icon="arrows-rotate" /> + </button> + </div> + {this._GPTOpt ? GPTOptions : null} + </div> + </div> + <hr className="docCreatorMenu-option-divider full no-margin" /> + <div className="docCreatorMenu-section"> + <div className="docCreatorMenu-section-topbar"> + <div className="docCreatorMenu-section-title">Your Templates</div> + <button className="docCreatorMenu-menu-button section-reveal-options" onPointerDown={e => this.setUpButtonClick(e, () => (this._GPTOpt = !this._GPTOpt))}> + <FontAwesomeIcon icon="gear" /> + </button> + </div> + <div className="docCreatorMenu-templates-preview-window" style={{ justifyContent: this._menuDimensions.width > 400 ? 'center' : '' }}> + <div className="docCreatorMenu-preview-window empty"> + <FontAwesomeIcon icon="plus" color="rgb(160, 160, 160)" /> + </div> + {this._userTemplates.map(({ template, doc }) => ( + <div + className="docCreatorMenu-preview-window" + key="0" + style={{ + border: this._selectedTemplate === template ? `solid 3px ${Colors.MEDIUM_BLUE}` : '', + boxShadow: this._selectedTemplate === template ? `0 0 15px rgba(68, 118, 247, .8)` : '', + }} + onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => this.updateSelectedTemplate(template)))}> + <button + className="option-button left" + onPointerDown={e => + this.setUpButtonClick(e, () => { + this.setExpandedView(template); + }) + }> + <FontAwesomeIcon icon="magnifying-glass" color="white" /> + </button> + <button className="option-button right" onPointerDown={e => this.setUpButtonClick(e, () => this.removeUserTemplate(template))}> + <FontAwesomeIcon icon="minus" color="white" /> + </button> + <DocumentView + Document={doc} + isContentActive={emptyFunction} // !!! should be return false + addDocument={returnFalse} + moveDocument={returnFalse} + removeDocument={returnFalse} + PanelWidth={() => (this._selectedTemplate === template ? 104 : 111)} + PanelHeight={() => (this._selectedTemplate === template ? 104 : 111)} + ScreenToLocalTransform={() => new Transform(-this._pageX - 5, -this._pageY - 35, 1)} + renderDepth={1} + whenChildContentsActiveChanged={emptyFunction} + focus={emptyFunction} + styleProvider={DefaultStyleProvider} + addDocTab={this._props.addDocTab} + pinToPres={() => undefined} + childFilters={returnEmptyFilter} + childFiltersByRanges={returnEmptyFilter} + searchFilterDocs={returnEmptyDoclist} + fitContentsToBox={returnFalse} + fitWidth={returnFalse} + hideDecorations={true} + /> + </div> + ))} + </div> + </div> + </div> + )} + </div> + ); + } + + @action updateXMargin = (input: string) => { + this._layout.xMargin = Number(input); + setTimeout(() => { + if (!this._renderedDocCollection || !this._fullyRenderedDocs) return; + this.applyLayout(this._renderedDocCollection, this._fullyRenderedDocs); + }); + }; + @action updateYMargin = (input: string) => { + this._layout.yMargin = Number(input); + setTimeout(() => { + if (!this._renderedDocCollection || !this._fullyRenderedDocs) return; + this.applyLayout(this._renderedDocCollection, this._fullyRenderedDocs); + }); + }; + @action updateColumns = (input: string) => { + this._layout.columns = Number(input); + this.updateRenderedDocCollection(); + }; + + get layoutConfigOptions() { + const optionInput = (icon: string, func: (input: string) => void, def?: number, key?: string, noMargin?: boolean) => { + return ( + <div className="docCreatorMenu-option-container small no-margin" key={key} style={{ marginTop: noMargin ? '0px' : '' }}> + <div className="docCreatorMenu-option-title config layout-config"> + <FontAwesomeIcon icon={icon as IconProp} /> + </div> + <input defaultValue={def} onInput={e => func(e.currentTarget.value)} className="docCreatorMenu-input config layout-config" /> + </div> + ); + }; + + switch (this._layout.type) { + case LayoutType.FREEFORM: + return ( + <div className="docCreatorMenu-configuration-bar"> + {optionInput('arrows-up-down', this.updateYMargin, this._layout.xMargin, '2')} + {optionInput('arrows-left-right', this.updateXMargin, this._layout.xMargin, '3')} + {optionInput('table-columns', this.updateColumns, this._layout.columns, '4', true)} + </div> + ); + default: + break; + } + } + + applyLayout = (collection: Doc, docs: Doc[]) => { + const { horizontalSpan, verticalSpan } = this.previewInfo; + collection._height = verticalSpan; + collection._width = horizontalSpan; + + const layout = this._layout; + const columns: number = layout.columns ?? this.columnsCount; + const xGap: number = layout.xMargin; + const yGap: number = layout.yMargin; + // const repeat: number = templateInfo.layout.repeat; + const startX: number = -Number(collection._width) / 2; + const startY: number = -Number(collection._height) / 2; + const docHeight: number = Number(docs[0]._height); + const docWidth: number = Number(docs[0]._width); + + if (columns === 0 || docs.length === 0) { + return; + } + + let i: number = 0; + let docsChanged: number = 0; + let curX: number = startX; + let curY: number = startY; + + while (docsChanged < docs.length) { + while (i < columns && docsChanged < docs.length) { + docs[docsChanged].x = curX; + docs[docsChanged].y = curY; + curX += docWidth + xGap; + ++docsChanged; + ++i; + } + i = 0; + curX = startX; + curY += docHeight + yGap; + } + }; + + @computed + get previewInfo() { + const docHeight: number = Number(this._fullyRenderedDocs[0]._height); + const docWidth: number = Number(this._fullyRenderedDocs[0]._width); + const layout = this._layout; + return { + docHeight: docHeight, + docWidth: docWidth, + horizontalSpan: (docWidth + layout.xMargin) * this.columnsCount - layout.xMargin, + verticalSpan: (docHeight + layout.yMargin) * this.rowsCount - layout.yMargin, + }; + } + + /** + * Updates the preview that shows how all docs will be rendered in the chosen collection type. + @type the type of collection the docs should render to (ie. freeform, carousel, card) + */ + updateRenderedDocCollection = () => { + if (!this._fullyRenderedDocs) return; + + const { horizontalSpan, verticalSpan } = this.previewInfo; + + const collectionFactory = (): ((docs: Doc[], options: DocumentOptions) => Doc) => { + switch (this._layout.type) { + case LayoutType.CAROUSEL3D: + return Docs.Create.Carousel3DDocument; + case LayoutType.FREEFORM: + return Docs.Create.FreeformDocument; + case LayoutType.CARD: + return Docs.Create.CardDeckDocument; + case LayoutType.MASONRY: + return Docs.Create.MasonryDocument; + case LayoutType.CAROUSEL: + return Docs.Create.CarouselDocument; + default: + return Docs.Create.FreeformDocument; + } + }; + + const collection: Doc = collectionFactory()(this._fullyRenderedDocs, { + isDefaultTemplateDoc: true, + _height: verticalSpan, + _width: horizontalSpan, + title: 'title', + backgroundColor: 'gray', + }); + + this.applyLayout(collection, this._fullyRenderedDocs); + + this._renderedDocCollection = collection; + }; + + layoutPreviewContents = () => { + return this._docsRendering ? ( + <div className="docCreatorMenu-layout-preview-window-wrapper loading"> + <div className="loading-spinner"> + <ReactLoading type="spin" color={StrCast(Doc.UserDoc().userVariantColor)} height={30} width={30} /> + </div> + </div> + ) : !this._renderedDocCollection ? null : ( + <div className="docCreatorMenu-layout-preview-window-wrapper"> + <DocumentView + Document={this._renderedDocCollection} + isContentActive={emptyFunction} + addDocument={returnFalse} + moveDocument={returnFalse} + removeDocument={returnFalse} + PanelWidth={() => this._menuDimensions.width - 80} + PanelHeight={() => this._menuDimensions.height - 105} + ScreenToLocalTransform={() => new Transform(-this._pageX - 5, -this._pageY - 35, 1)} + renderDepth={5} + whenChildContentsActiveChanged={emptyFunction} + focus={emptyFunction} + styleProvider={DefaultStyleProvider} + addDocTab={this._props.addDocTab} + pinToPres={() => undefined} + childFilters={returnEmptyFilter} + childFiltersByRanges={returnEmptyFilter} + searchFilterDocs={returnEmptyDoclist} + fitContentsToBox={returnFalse} + fitWidth={returnFalse} + hideDecorations={true} + /> + </div> + ); + }; + + get optionsMenuContents() { + const layoutOption = (option: LayoutType, optStyle?: object, specialFunc?: () => void) => { + return ( + <div + className="docCreatorMenu-dropdown-option" + style={optStyle} + onPointerDown={e => + this.setUpButtonClick(e, () => { + specialFunc?.(); + runInAction(() => { + this._layout.type = option; + this.updateRenderedDocCollection(); + }); + }) + }> + {option} + </div> + ); + }; + + const selectionBox = (width: number, height: number, icon: string, specClass?: string, options?: JSX.Element[], manual?: boolean): JSX.Element => { + return ( + <div className="docCreatorMenu-option-container"> + <div className={`docCreatorMenu-option-title config ${specClass}`} style={{ width: width * 0.4, height: height }}> + <FontAwesomeIcon icon={icon as IconProp} /> + </div> + {manual ? ( + <input className={`docCreatorMenu-input config ${specClass}`} style={{ width: width * 0.6, height: height }} /> + ) : ( + <select className={`docCreatorMenu-input config ${specClass}`} style={{ width: width * 0.6, height: height }}> + {options} + </select> + )} + </div> + ); + }; + + const repeatOptions = [0, 1, 2, 3, 4, 5]; + + return ( + <div className="docCreatorMenu-menu-container"> + <div className="docCreatorMenu-option-container layout"> + <div className="docCreatorMenu-dropdown-hoverable"> + <div className="docCreatorMenu-option-title">{this._layout.type ? this._layout.type.toUpperCase() : 'Choose Layout'}</div> + <div className="docCreatorMenu-dropdown-content"> + {layoutOption(LayoutType.FREEFORM, undefined, () => { + if (!this._layout.columns) this._layout.columns = Math.ceil(Math.sqrt(this.docsToRender.length)); + })} + {layoutOption(LayoutType.CAROUSEL)} + {layoutOption(LayoutType.CAROUSEL3D)} + {layoutOption(LayoutType.MASONRY)} + </div> + </div> + </div> + {this._layout.type ? this.layoutConfigOptions : null} + {this.layoutPreviewContents()} + {selectionBox( + 60, + 20, + 'repeat', + undefined, + repeatOptions.map(num => <option key={num} onPointerDown={() => (this._layout.repeat = num)}>{`${num}x`}</option>) + )} + <hr className="docCreatorMenu-option-divider" /> + <div className="docCreatorMenu-general-options-container"> + <button + className="docCreatorMenu-save-layout-button" + onPointerDown={e => + setupMoveUpEvents( + this, + e, + returnFalse, + emptyFunction, + undoable(clickEv => { + clickEv.stopPropagation(); + if (!this._selectedTemplate) return; + const layout: DataVizTemplateLayout = { + template: this._selectedTemplate.getRenderedDoc(), + layout: { type: this._layout.type, xMargin: this._layout.xMargin, yMargin: this._layout.yMargin, repeat: 0 }, + columns: this.columnsCount, + rows: this.rowsCount, + docsNumList: this.docsToRender, + }; + if (!this._savedLayouts.includes(layout)) { + this._savedLayouts.push(layout); + } + }, 'make docs') + ) + }> + <FontAwesomeIcon icon="floppy-disk" /> + </button> + <button + className="docCreatorMenu-create-docs-button" + style={{ backgroundColor: this.canMakeDocs ? '' : 'rgb(155, 155, 155)', border: this.canMakeDocs ? '' : 'solid 2px rgb(180, 180, 180)' }} + onPointerDown={e => + setupMoveUpEvents( + this, + e, + returnFalse, + emptyFunction, + undoable(clickEv => { + clickEv.stopPropagation(); + if (!this._selectedTemplate) return; + this.addRenderedCollectionToMainview(); + }, 'make docs') + ) + }> + <FontAwesomeIcon icon="plus" /> + </button> + </div> + </div> + ); + } + + get dashboardContents() { + const sizes: string[] = ['tiny', 'small', 'medium', 'large', 'huge']; + + const fieldPanel = (field: Col, id: number) => { + return ( + <div className="field-panel" key={id}> + <div className="top-bar"> + <span className="field-title">{`${field.title} Field`}</span> + <button className="docCreatorMenu-menu-button section-reveal-options no-margin" onPointerDown={e => this.setUpButtonClick(e, () => this.removeField(field))} style={{ position: 'absolute', right: '0px' }}> + <FontAwesomeIcon icon="minus" /> + </button> + </div> + <div className="opts-bar"> + <div className="opt-box"> + <div className="top-bar"> Title </div> + <textarea className="content" style={{ width: '100%', height: 'calc(100% - 20px)' }} value={field.title} placeholder={'Enter title'} onChange={e => this.setColTitle(field, e.target.value)} /> + </div> + <div className="opt-box"> + <div className="top-bar"> Type </div> + <div className="content"> + <span className="type-display">{field.type === TemplateFieldType.TEXT ? 'Text Field' : field.type === TemplateFieldType.VISUAL ? 'File Field' : ''}</span> + <div className="bubbles"> + <input + className="bubble" + type="radio" + name="type" + onClick={() => { + this.setColType(field, TemplateFieldType.TEXT); + }} + /> + <div className="text">Text</div> + <input + className="bubble" + type="radio" + name="type" + onClick={() => { + this.setColType(field, TemplateFieldType.VISUAL); + }} + /> + <div className="text">File</div> + </div> + </div> + </div> + </div> + <div className="sizes-box"> + <div className="top-bar"> Valid Sizes </div> + <div className="content"> + <div className="bubbles"> + {sizes.map(size => ( + <> + <input + className="bubble" + type="checkbox" + name="type" + checked={field.sizes.includes(size as TemplateFieldSize)} + onChange={e => { + this.modifyColSizes(field, size as TemplateFieldSize, e.target.checked); + }} + /> + <div className="text">{size}</div> + </> + ))} + </div> + </div> + </div> + <div className="desc-box"> + <div className="top-bar"> Prompt </div> + <textarea + className="content" + onChange={e => this.setColDesc(field, e.target.value)} + defaultValue={field.desc === this._dataViz?.GPTSummary?.get(field.title)?.desc ? '' : field.desc} + placeholder={this._dataViz?.GPTSummary?.get(field.title)?.desc ?? 'Add a description/prompt to help with template generation.'} + /> + </div> + </div> + ); + }; + + return ( + <div className="docCreatorMenu-dashboard-view"> + <div className="topbar"> + <button className="docCreatorMenu-menu-button section-reveal-options" onPointerDown={e => this.setUpButtonClick(e, this.addField)}> + <FontAwesomeIcon icon="plus" /> + </button> + <button className="docCreatorMenu-menu-button section-reveal-options float-right" onPointerDown={e => this.setUpButtonClick(e, () => runInAction(() => (this._menuContent = 'templates')))}> + <FontAwesomeIcon icon="arrow-left" /> + </button> + </div> + <div className="panels-container">{this.fieldsInfos.map((field, i) => fieldPanel(field, i))}</div> + </div> + ); + } + + get renderSelectedViewType() { + switch (this._menuContent) { + case 'templates': + return this.templatesPreviewContents; + case 'options': + return this.optionsMenuContents; + case 'dashboard': + return this.dashboardContents; + default: + return undefined; + } + } + + get resizePanes() { + const ref = this._ref?.getBoundingClientRect(); + const height: number = ref?.height ?? 0; + const width: number = ref?.width ?? 0; + + return [ + <div className='docCreatorMenu-resizer top' key='0' onPointerDown={this.onResizePointerDown} style={{width: width, left: 0, top: -7}}/>, + <div className='docCreatorMenu-resizer left' key='1' onPointerDown={this.onResizePointerDown} style={{height: height, left: -7, top: 0}}/>, + <div className='docCreatorMenu-resizer right' key='2' onPointerDown={this.onResizePointerDown} style={{height: height, left: width - 3, top: 0}}/>, + <div className='docCreatorMenu-resizer bottom' key='3' onPointerDown={this.onResizePointerDown} style={{width: width, left: 0, top: height - 3}}/>, + <div className='docCreatorMenu-resizer topLeft' key='4' onPointerDown={this.onResizePointerDown} style={{left: -10, top: -10, cursor: 'nwse-resize'}}/>, + <div className='docCreatorMenu-resizer topRight' key='5' onPointerDown={this.onResizePointerDown} style={{left: width - 5, top: -10, cursor: 'nesw-resize'}}/>, + <div className='docCreatorMenu-resizer bottomLeft' key='6' onPointerDown={this.onResizePointerDown} style={{left: -10, top: height - 5, cursor: 'nesw-resize'}}/>, + <div className='docCreatorMenu-resizer bottomRight' key='7' onPointerDown={this.onResizePointerDown} style={{left: width - 5, top: height - 5, cursor: 'nwse-resize'}}/>, + ]; //prettier-ignore + } + + render() { + const topButton = (icon: string, opt: string, func: () => void, tag: string) => { + return ( + <div className={`top-button-container ${tag} ${opt === this._menuContent ? 'selected' : ''}`}> + <div + className="top-button-content" + onPointerDown={e => + this.setUpButtonClick(e, () => + runInAction(() => { + func(); + }) + ) + }> + <FontAwesomeIcon icon={icon as IconProp} /> + </div> + </div> + ); + }; + + const onPreviewSelected = () => { + this._menuContent = 'templates'; + }; + const onSavedSelected = () => { + this._menuContent = 'dashboard'; + }; + const onOptionsSelected = () => { + this._menuContent = 'options'; + if (!this._layout.columns) this._layout.columns = Math.ceil(Math.sqrt(this.docsToRender.length)); + }; + + return ( + <div className="docCreatorMenu"> + {!this._shouldDisplay ? undefined : ( + <div + className="docCreatorMenu-cont" + ref={r => (this._ref = r)} + style={{ + display: '', + left: this._pageX, + top: this._pageY, + width: this._menuDimensions.width, + height: this._menuDimensions.height, + background: SnappingManager.userBackgroundColor, + color: SnappingManager.userColor, + }}> + {this.resizePanes} + <div + className="docCreatorMenu-menu" + onPointerDown={e => + setupMoveUpEvents( + this, + e, + event => { + this._dragging = true; + this._startPos = { x: 0, y: 0 }; + this._startPos.x = event.pageX - (this._ref?.getBoundingClientRect().left ?? 0); + this._startPos.y = event.pageY - (this._ref?.getBoundingClientRect().top ?? 0); + document.addEventListener('pointermove', this.onDrag); + return true; + }, + emptyFunction, + undoable(clickEv => { + clickEv.stopPropagation(); + }, 'drag menu') + ) + }> + <div className="docCreatorMenu-top-buttons-container"> + {topButton('lightbulb', 'templates', onPreviewSelected, 'left')} + {topButton('magnifying-glass', 'options', onOptionsSelected, 'middle')} + {topButton('bars', 'saved', onSavedSelected, 'right')} + </div> + <button className="docCreatorMenu-menu-button close-menu" onPointerDown={e => this.setUpButtonClick(e, this.closeMenu)}> + <FontAwesomeIcon icon={'minus'} /> + </button> + </div> + {this.renderSelectedViewType} + </div> + )} + </div> + ); + } +} diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/DynamicField.tsx b/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/DynamicField.tsx new file mode 100644 index 000000000..c5254c17d --- /dev/null +++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/DynamicField.tsx @@ -0,0 +1,117 @@ +import { Doc } from "../../../../../../fields/Doc"; +import { Docs } from "../../../../../documents/Documents"; +import { Field, FieldDimensions, FieldSettings, ViewType } from "./Field"; +import { FieldUtils } from "./FieldUtils"; +import { StaticField } from "./StaticField"; + +export class DynamicField implements Field { + private subfields: Field[] = []; + + private id: number; + private settings: FieldSettings; + private title: string = ''; + + private parent: Field; + private dimensions: FieldDimensions; + + constructor(settings: FieldSettings, id: number, parent?: Field) { + this.id = id; + this.settings = settings; + if (settings.title) { this.title = settings.title }; + if (!parent) { + this.parent = this; + this.dimensions = {width: this.settings.br[0] - this.settings.tl[0], height: this.settings.br[1] - this.settings.tl[1], coord: {x: this.settings.tl[0], y: this.settings.tl[1]}}; + } else { + this.parent = parent; + this.dimensions = FieldUtils.getLocalDimensions({tl: settings.tl, br: settings.br}, this.parent.getDimensions); + } + this.subfields = this.setupSubfields(); + } + + setContent = () => { return }; + getContent = () => { return '' }; + + setTitle = (title: string) => { this.title = title }; + getTitle = () => { return this.title }; + + get getSubfields() { return this.subfields }; + get getAllSubfields() { + let fields: Field[] = []; + this.subfields?.forEach(field => { + fields.push(field); + fields = fields.concat(field.getAllSubfields) + }); + return fields; + }; + + get getDimensions() { return this.dimensions }; + get getID() { return this.id }; + get getViewType() { return this.settings.viewType }; + + get getDescription(): string { + return this.settings.description ?? ''; + } + + matches = (): Array<number> => { + return []; + } + + updateRenderedDoc = () => { + return new Doc(); + } + + setupSubfields = (): Field[] => { + const fields: Field[] = []; + this.settings.subfields?.forEach((fieldSettings, index) => { + let field: Field; + const type = fieldSettings.viewType; + + const id = Number(String(this.id) + String(index)); + + if (type == ViewType.CAROUSEL3D || type === ViewType.FREEFORM) { + field = new DynamicField(fieldSettings, id, this); + } else { + field = new StaticField(fieldSettings, this, id); + } + fields.push(field); + }); + return fields; + } + + applyAttributes = (field: Field) => { + field.setTitle(this.title); + field.updateRenderedDoc(this.renderedDoc()); + } + + getChildDimensions = (coords: { tl: [number, number]; br: [number, number] }): FieldDimensions => { + const l = (coords.tl[0] * this.dimensions.height) / 2; + const t = coords.tl[1] * this.dimensions.width / 2; //prettier-ignore + const r = (coords.br[0] * this.dimensions.height) / 2; + const b = coords.br[1] * this.dimensions.width / 2; //prettier-ignore + const width = r - l; + const height = b - t; + const coord = { x: l, y: t }; + return { width, height, coord }; + }; + + renderedDoc = (): Doc => { + let doc: Doc; + switch (this.settings.viewType) { + case ViewType.CAROUSEL3D: + doc = Docs.Create.Carousel3DDocument(this.subfields.map(field => field.renderedDoc()), { + title: this.title, + }); + FieldUtils.applyBasicOpts(doc, this.dimensions, this.settings); + return doc; + case ViewType.FREEFORM: + doc = Docs.Create.FreeformDocument(this.subfields.map(field => field.renderedDoc()), { + title: this.title, + }); + FieldUtils.applyBasicOpts(doc, this.dimensions, this.settings); + return doc; + default: + return new Doc(); + } + } + +} diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/Field.tsx b/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/Field.tsx new file mode 100644 index 000000000..ea9b566b3 --- /dev/null +++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/Field.tsx @@ -0,0 +1,66 @@ +import { Doc } from "../../../../../../fields/Doc"; +import { Col } from "../DocCreatorMenu"; +import { TemplateFieldSize, TemplateFieldType } from "../TemplateBackend"; + +export enum FieldContentType { + STRING = 'string', + IMAGE = 'image', +} + +export enum ViewType { + CAROUSEL3D = 'carousel3d', + FREEFORM = 'freeform', + STATIC = 'static', + DEC = 'decoration' +} + +export type FieldDimensions = { + width: number; + height: number; + coord: {x: number, y: number}; +} + +export interface FieldOpts { + backgroundColor?: string; + color?: string; + cornerRounding?: number; + borderWidth?: string; + borderColor?: string; + contentXCentering?: 'h-left' | 'h-center' | 'h-right'; + contentYCentering?: 'top' | 'center' | 'bottom'; + opacity?: number; + rotation?: number; + fontBold?: boolean; + fontTransform?: 'uppercase' | 'lowercase'; + fieldViewType?: 'freeform' | 'stacked'; +} + +export type FieldSettings = { + tl: [number, number]; + br: [number, number]; + opts: FieldOpts; + viewType: ViewType; + title?: string; + subfields?: FieldSettings[]; + types?: TemplateFieldType[]; + sizes?: TemplateFieldSize[]; + description?: string; +}; + +export interface Field { + getContent: () => string; + setContent: (content: string, type?: FieldContentType) => void; + getDimensions: FieldDimensions; + getSubfields: Field[]; + getAllSubfields: Field[]; + getID: number; + getViewType: ViewType; + getDescription: string; + getTitle: () => string; + setTitle: (title: string) => void; + setupSubfields: () => Field[]; + applyAttributes: (field: Field) => void; + renderedDoc: () => Doc; + matches: (cols: Col[]) => number[]; + updateRenderedDoc: (oldDoc?: Doc) => Doc; +}
\ No newline at end of file diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/FieldUtils.tsx b/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/FieldUtils.tsx new file mode 100644 index 000000000..3886774d2 --- /dev/null +++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/FieldUtils.tsx @@ -0,0 +1,79 @@ +import { Doc } from "../../../../../../fields/Doc"; +import { ComputedField, ScriptField } from "../../../../../../fields/ScriptField"; +import { Col } from "../DocCreatorMenu"; +import { TemplateFieldSize, TemplateFieldType, TemplateLayouts } from "../TemplateBackend"; +import { FieldDimensions, FieldSettings } from "./Field"; + +export class FieldUtils { + public static getLocalDimensions = (coords: { tl: [number, number]; br: [number, number] }, parentDimensions: FieldDimensions): FieldDimensions => { + const l = (coords.tl[0] * parentDimensions.width) / 2; + const t = coords.tl[1] * parentDimensions.height / 2; //prettier-ignore + const r = (coords.br[0] * parentDimensions.width) / 2; + const b = coords.br[1] * parentDimensions.height / 2; //prettier-ignore + const width = r - l; + const height = b - t; + const coord = { x: l, y: t }; + return { width, height, coord }; + }; + + public static applyBasicOpts = (doc: Doc, parentDimensions: FieldDimensions, settings: FieldSettings, oldDoc?: Doc) => { + const opts = settings.opts; + doc.isDefaultTemplateDoc = oldDoc ? oldDoc.isDefaultTemplateDoc : true; + doc._layout_hideScroll = oldDoc ? oldDoc._layout_hideScroll : true; + doc.x = oldDoc ? oldDoc.x : parentDimensions.coord.x; + doc.y = oldDoc ? oldDoc.y : parentDimensions.coord.y; + doc._height = oldDoc ? oldDoc.height : parentDimensions.height; + doc._width = oldDoc ? oldDoc.width : parentDimensions.width; + doc.backgroundColor = oldDoc ? oldDoc.backgroundColor : opts.backgroundColor ?? ''; + doc._layout_borderRounding = !opts.cornerRounding ? '0px' : ScriptField.MakeFunction(`${opts.cornerRounding} * this.width + 'px'`); + doc.borderColor = oldDoc ? oldDoc.borderColor : opts.borderColor; + doc.borderWidth = oldDoc ? oldDoc.borderWidth : opts.borderWidth; + doc.opacity = oldDoc ? oldDoc.opacity : opts.opacity; + doc._rotation = oldDoc ? oldDoc._rotation : opts.rotation; + doc.hCentering = oldDoc ? oldDoc.hCentering : opts.contentXCentering; + doc.nativeWidth = parentDimensions.width; + doc.nativeHeight = parentDimensions.height; + doc._layout_nativeDimEditable = true; + }; + + public static calculateFontSize = (contWidth: number, contHeight: number, text: string, uppercase: boolean): number => { + const words: string[] = text.split(/\s+/).filter(Boolean); + + let currFontSize = 1; + let rowsCount = 1; + let currTextHeight = currFontSize * rowsCount * 2; + + while (currTextHeight <= contHeight) { + let wordIndex = 0; + let currentRowWidth = 0; + let wordsInCurrRow = 0; + rowsCount = 1; + + while (wordIndex < words.length) { + const word = words[wordIndex]; + const wordWidth = word.length * currFontSize * 0.7; + + if (currentRowWidth + wordWidth <= contWidth) { + currentRowWidth += wordWidth; + ++wordsInCurrRow; + } else { + if (words.length !== 1 && words.length > wordsInCurrRow) { + rowsCount++; + currentRowWidth = wordWidth; + wordsInCurrRow = 1; + } else { + break; + } + } + + wordIndex++; + } + + currTextHeight = rowsCount * currFontSize * 2; + + currFontSize += 1; + } + + return currFontSize - 1; + }; +}
\ No newline at end of file diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/StaticField.tsx b/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/StaticField.tsx new file mode 100644 index 000000000..47b43f051 --- /dev/null +++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu/FieldTypes/StaticField.tsx @@ -0,0 +1,147 @@ +import { Doc } from "../../../../../../fields/Doc"; +import { Docs } from "../../../../../documents/Documents"; +import { Col } from "../DocCreatorMenu"; +import { DynamicField } from "./DynamicField"; +import { FieldUtils } from "./FieldUtils"; +import { Field, FieldContentType, FieldDimensions, FieldSettings, ViewType } from "./Field"; + +export class StaticField { + private content: string; + private contentType: FieldContentType | undefined; + private subfields: Field[] = []; + private renderedDocument: Doc; + + private id: number; + private title: string = ''; + + private settings: FieldSettings; + + private parent: Field; + private dimensions: FieldDimensions; + + constructor(settings: FieldSettings, parent: Field, id: number) { + this.settings = settings; + if (settings.title) { this.title = settings.title }; + this.id = id; + this.parent = parent; + this.dimensions = FieldUtils.getLocalDimensions({tl: settings.tl, br: settings.br}, this.parent.getDimensions); + this.content = ''; + this.subfields = this.setupSubfields(); + this.renderedDocument = this.updateRenderedDoc(); + }; + + get getSubfields(): Field[] { return this.subfields ?? []; }; + + get getAllSubfields(): Field[] { + let fields: Field[] = []; + this.subfields?.forEach(field => { + fields.push(field); + fields = fields.concat(field.getAllSubfields); + }); + return fields; + }; + + get getDimensions() { return this.dimensions }; + get getID() { return this.id }; + get getViewType() { return this.settings.viewType }; + + get getDescription(): string { + return this.settings.description ?? ''; + } + + renderedDoc = () => { + return this.renderedDocument; + } + + setContent = (newContent: string, type?: FieldContentType) => { + this.content = newContent; + if (type) this.contentType = type; + this.updateRenderedDoc(this.renderedDocument); + }; + getContent() { return this.content }; + + setTitle = (title: string) => { + this.title = title; + this.renderedDocument.title = title; + this.updateRenderedDoc(this.renderedDocument); + }; + getTitle = () => { return this.title }; + + applyAttributes = (field: Field) => { //!!! can be updated later for more robust clonign; this is all ythat's needed now + field.setTitle(this.title); + field.setContent('', this.contentType); + field.updateRenderedDoc(this.renderedDoc()); + } + + setupSubfields = (): Field[] => { + const fields: Field[] = []; + this.settings.subfields?.forEach((fieldSettings, index) => { + let field: Field; + const type = fieldSettings.viewType; + + const id = Number(String(this.id) + String(index)); + + if (type === ViewType.FREEFORM || type === ViewType.CAROUSEL3D) { + field = new DynamicField(fieldSettings, id, this); + } else { + field = new StaticField(fieldSettings, this, id); + }; + + fields.push(field); + }); + return fields; + }; + + matches = (cols: Col[]): number[] => { + const colMatchesField = (col: Col) => { + const isMatch: boolean = ( + this.settings.sizes?.some(size => col.sizes?.includes(size)) + && this.settings.types?.includes(col.type)) + ?? false; + return isMatch; + } + + const matches: Array<number> = []; + + cols.forEach((col, v) => { + if (colMatchesField(col)) { + matches.push(v); + } + }); + + return matches; + }; + + updateRenderedDoc = (oldDoc?: Doc): Doc => { + const opts = this.settings.opts; + + if (!this.contentType) { this.contentType = FieldContentType.STRING }; + + let doc: Doc; + + switch (this.contentType) { + case FieldContentType.STRING: + doc = Docs.Create.TextDocument(String(this.content), { + title: this.title, + text_fontColor: oldDoc ? String(oldDoc.color) : opts.color, + contentBold: oldDoc ? Boolean(oldDoc.fontBold) : opts.fontBold, + textTransform: oldDoc ? String(oldDoc.fontTransform) : opts.fontTransform, + color: oldDoc ? String(oldDoc.color) : opts.color, + _text_fontSize: `${FieldUtils.calculateFontSize(this.dimensions.width, this.dimensions.height, String(this.content), true)}` + }); + FieldUtils.applyBasicOpts(doc, this.dimensions, this.settings, oldDoc); + break; + case FieldContentType.IMAGE: + doc = Docs.Create.ImageDocument(String(this.content), { + title: this.title, + _layout_fitWidth: false, + }); + FieldUtils.applyBasicOpts(doc, this.dimensions, this.settings, oldDoc); + break; + } + + this.renderedDocument = doc; + + return doc; + }; +}
\ No newline at end of file diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu/Template.tsx b/src/client/views/nodes/DataVizBox/DocCreatorMenu/Template.tsx new file mode 100644 index 000000000..0a5097d4a --- /dev/null +++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu/Template.tsx @@ -0,0 +1,139 @@ +import { Doc, FieldType } from "../../../../../fields/Doc"; +import { Col } from "./DocCreatorMenu"; +import { DynamicField } from "./FieldTypes/DynamicField"; +import { Field, FieldSettings, ViewType } from "./FieldTypes/Field"; +import { } from "./FieldTypes/FieldUtils"; +import { } from "./FieldTypes/StaticField"; + +export class Template { + + mainField: DynamicField; + settings: FieldSettings; + + constructor(templateInfo: FieldSettings) { + this.mainField = this.setupMainField(templateInfo); + this.settings = templateInfo; + } + + get childFields(): Field[] { return this.mainField.getSubfields }; + get allFields(): Field[] { return this.mainField.getAllSubfields }; + get contentFields(): Field[] { return this.allFields.filter(field => field.getViewType === ViewType.STATIC) }; + get doc(){ return this.mainField.renderedDoc(); }; + + cloneBase = () => { + const clone: Template = new Template(this.settings); + clone.allFields.forEach(field => { + const matchingField: Field = this.allFields.filter(f => f.getID === field.getID)[0]; + matchingField.applyAttributes(field); + }) + return clone; + } + + getRenderedDoc = () => { + const doc: Doc = this.mainField.renderedDoc(); + this.contentFields.forEach(field => { + const title: string = field.getTitle(); + const val: FieldType = field.getContent() as FieldType; + if (!title || !val) return; + doc[title] = val; + }); + return doc; + } + + getFieldByID = (id: number): Field => { + return this.allFields.filter(field => field.getID === id)[0]; + } + + getFieldByTitle = (title: string) => { + return this.allFields.filter(field => field.getTitle() === title)[0]; + } + + setupMainField = (templateInfo: FieldSettings) => { + return new DynamicField(templateInfo, 1); + } + + get descriptionSummary(): string { + let summary: string = ''; + this.contentFields.forEach(field => { + summary += `--- Field #${field.getID} (title: ${field.getTitle()}): ${field.getDescription ?? ''} ---`; + }); + return summary; + } + + get compiledContent(): string { + let summary: string = ''; + this.contentFields.forEach(field => { + summary += `--- Field #${field.getID} (title: ${field.getTitle()}): ${field.getContent() ?? ''} ---`; + }); + return summary; + } + + renderUpdates = () => { + this.allFields.forEach(field => { + field.updateRenderedDoc(field.renderedDoc()); + }); + }; + + resetToBase = () => { + this.allFields.forEach(field => { + field.updateRenderedDoc(); + }) + } + + isValidTemplate = (cols: Col[]) => { + const matches: number[][] = this.getMatches(cols); + const maxMatches: number = this.maxMatches(matches); + return maxMatches === this.contentFields.length; + } + + getMatches = (cols: Col[]): number[][] => { + const numFields = this.contentFields.length; + + if (cols.length !== numFields) return []; + + const matches: number[][] = Array(numFields) + .fill([]) + .map(() => []); + + this.contentFields.forEach((field, i) => { + matches[i] = (field.matches(cols)); + }); + + return matches; + } + + maxMatches = (matches: number[][]) => { + if (matches.length === 0) return 0; + + const fieldsCt = this.contentFields.length; + const used: boolean[] = Array(fieldsCt).fill(false); + const mt: number[] = Array(fieldsCt).fill(-1); + + const augmentingPath = (v: number): boolean => { + if (used[v]) return false; + used[v] = true; + + for (const to of matches[v]) { + if (mt[to] === -1 || augmentingPath(mt[to])) { + mt[to] = v; + return true; + } + } + return false; + }; + + for (let v = 0; v < fieldsCt; ++v) { + used.fill(false); + augmentingPath(v); + } + + let count: number = 0; + + for (let i = 0; i < fieldsCt; ++i) { + if (mt[i] !== -1) ++count; + } + + return count; + }; + +}
\ No newline at end of file diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu/TemplateBackend.tsx b/src/client/views/nodes/DataVizBox/DocCreatorMenu/TemplateBackend.tsx new file mode 100644 index 000000000..d3282eda3 --- /dev/null +++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu/TemplateBackend.tsx @@ -0,0 +1,752 @@ +import { FieldSettings, ViewType } from "./FieldTypes/Field"; +import { } from "./FieldTypes/StaticField"; + +export enum TemplateFieldType { + TEXT = 'text', + VISUAL = 'visual', + UNSET = 'unset', +} + +export enum TemplateFieldSize { + TINY = 'tiny', + SMALL = 'small', + MEDIUM = 'medium', + LARGE = 'large', + HUGE = 'huge', +} + +export class TemplateLayouts { + public static get allTemplates(): FieldSettings[] { + return Object.values(TemplateLayouts); + } + + public static FourField001: FieldSettings = { + title: 'fourfield001', + tl: [0, 0], + br: [416, 700], + viewType: ViewType.FREEFORM, + opts: { + backgroundColor: '#C0B887', + cornerRounding: .05, + //borderColor: '#6B461F', + //borderWidth: '12', + }, + subfields: [ + { + viewType: ViewType.STATIC, + tl: [-0.95, -1], + br: [0.95, -0.85], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY], + description: 'A title field for very short text that contextualizes the content.', + opts: { + backgroundColor: 'transparent', + color: '#F1F0E9', + contentXCentering: 'h-center', + fontBold: true, + }, + }, + { + viewType: ViewType.STATIC, + tl: [-0.87, -0.83], + br: [0.87, 0.2], + types: [TemplateFieldType.TEXT, TemplateFieldType.VISUAL], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], + description: 'The main focus of the template; could be an image, long text, etc.', + opts: { + cornerRounding: .05, + borderColor: '#8F5B25', + borderWidth: '6', + backgroundColor: '#CECAB9', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-0.8, 0.2], + br: [0.8, 0.3], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], + description: 'A caption for field #2, very short text.', + opts: { + backgroundColor: 'transparent', + contentXCentering: 'h-center', + color: '#F1F0E9', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-0.87, 0.37], + br: [0.87, 0.96], + types: [TemplateFieldType.TEXT, TemplateFieldType.VISUAL], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], + description: 'A medium-sized field for medium/long text.', + opts: { + cornerRounding: .05, + borderColor: '#8F5B25', + borderWidth: '6', + backgroundColor: '#CECAB9', + }, + }, + ], + }; + + public static FourField002: FieldSettings = { + title: 'fourfield002', + viewType: ViewType.FREEFORM, + tl: [0,0], + br: [425, 778], + opts: { + backgroundColor: '#242425', + }, + subfields: [ + { + viewType: ViewType.STATIC, + tl: [-0.83, -0.95], + br: [0.83, -0.2], + types: [TemplateFieldType.VISUAL, TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE], + description: 'A medium to large-sized field suitable for an image or longer text that should be the main focus.', + opts: { + borderWidth: '8', + borderColor: '#F8E71C', + backgroundColor: '#242425', + color: 'white', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-0.65, -0.2], + br: [0.65, -0.02], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY], + description: 'A tiny field for just a word or two of plain text.', + opts: { + backgroundColor: 'transparent', + color: 'white', + contentXCentering: 'h-center', + fontTransform: 'uppercase', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-0.65, 0], + br: [0.65, 0.18], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY], + description: 'A tiny field for just a word or two of plain text.', + opts: { + backgroundColor: 'transparent', + color: 'white', + contentXCentering: 'h-center', + fontTransform: 'uppercase', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-0.83, 0.2], + br: [0.83, 0.95], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], + description: 'A medium to large-sized field suitable for longer text that should contextualize field 1.', + opts: { + borderWidth: '8', + borderColor: '#F8E71C', + color: 'white', + backgroundColor: '#242425', + }, + }, + { + viewType: ViewType.DEC, + tl: [-0.8, -0.075], + br: [-0.525, 0.075], + opts: { + backgroundColor: '#F8E71C', + rotation: 45, + }, + }, + { + viewType: ViewType.DEC, + tl: [-0.3075, -0.0245], + br: [-0.2175, 0.0245], + opts: { + backgroundColor: '#F8E71C', + rotation: 45, + }, + }, + { + viewType: ViewType.DEC, + tl: [-0.045, -0.0245], + br: [0.045, 0.0245], + opts: { + backgroundColor: '#F8E71C', + rotation: 45, + }, + }, + { + viewType: ViewType.DEC, + tl: [0.2175, -0.0245], + br: [0.3075, 0.0245], + opts: { + backgroundColor: '#F8E71C', + rotation: 45, + }, + }, + { + viewType: ViewType.DEC, + tl: [0.525, -0.075], + br: [0.8, 0.075], + opts: { + backgroundColor: '#F8E71C', + rotation: 45, + }, + }, + ], + }; + + // public static FourField003: TemplateDocInfos = { + // title: 'fourfield3', + // width: 477, + // height: 662, + // opts: { + // backgroundColor: '#9E9C95' + // }, + // fields: [{ + // tl: [-.875, -.9], + // br: [.875, .7], + // types: [TemplateFieldType.VISUAL], + // sizes: [TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], + // description: '', + // opts: { + // borderWidth: '15', + // borderColor: '#E0E0DA', + // } + // }, { + // tl: [-.95, .8], + // br: [-.1, .95], + // types: [TemplateFieldType.TEXT], + // sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], + // description: '', + // opts: { + // backgroundColor: 'transparent', + // color: 'white', + // contentXCentering: 'h-right', + // } + // }, { + // tl: [.1, .8], + // br: [.95, .95], + // types: [TemplateFieldType.TEXT], + // sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], + // description: '', + // opts: { + // backgroundColor: 'transparent', + // color: 'red', + // fontTransform: 'uppercase', + // contentXCentering: 'h-left' + // } + // }, { + // tl: [0, -.9], + // br: [.85, -.66], + // types: [TemplateFieldType.TEXT, TemplateFieldType.VISUAL], + // sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], + // description: '', + // opts: { + // backgroundColor: 'transparent', + // contentXCentering: 'h-right' + // } + // }], + // decorations: [{ + // tl: [-.025, .8], + // br: [.025, .95], + // opts: { + // backgroundColor: '#E0E0DA', + // } + // }] + // }; + + public static FourField004: FieldSettings = { + title: 'fourfield04', + viewType: ViewType.FREEFORM, + tl: [0,0], + br: [414,583], + opts: { + backgroundColor: '#6CCAF0', + //borderColor: '#1088C3', + //borderWidth: '10', + }, + subfields: [ + { + viewType: ViewType.STATIC, + tl: [-0.86, -0.92], + br: [-0.075, -0.77], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY], + description: 'A tiny field for just a word or two of plain text.', + opts: { + backgroundColor: '#E2B4F5', + borderWidth: '9', + borderColor: '#9222F1', + contentXCentering: 'h-center', + }, + }, + { + viewType: ViewType.STATIC, + tl: [0.075, -0.92], + br: [0.86, -0.77], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY], + description: 'A tiny field for just a word or two of plain text.', + opts: { + backgroundColor: '#F5B4DD', + borderWidth: '9', + borderColor: '#E260F3', + contentXCentering: 'h-center', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-0.81, -0.64], + br: [0.81, 0.48], + types: [TemplateFieldType.VISUAL], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], + description: 'A large to huge field for visual content that is the main content of the template.', + opts: { + borderWidth: '16', + borderColor: '#A2BD77', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-0.86, 0.6], + br: [0.86, 0.92], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE], + description: 'A medium to large field for text that describes the visual content above', + opts: { + borderWidth: '9', + borderColor: '#F0D601', + backgroundColor: '#F3F57D', + }, + }, + { + viewType: ViewType.DEC, + tl: [-0.852, -0.67], + br: [0.852, 0.51], + opts: { + backgroundColor: 'transparent', + borderColor: '#007C0C', + borderWidth: '10', + }, + }, + ], + }; + + public static FourField005: FieldSettings = { + title: 'fourfield05', + viewType: ViewType.FREEFORM, + tl: [0,0], + br: [400,550], + opts: { + backgroundColor: '#95A575', + }, + subfields: [ + { + viewType: ViewType.STATIC, + tl: [-0.9, -.925], + br: [-.075, -.775], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], + description: 'A small text field for a title or word(s) that categorize the rest of the content.', + opts: { + borderColor: '#3B4A2C', + borderWidth: '8', + contentXCentering: "h-center", + backgroundColor: '#B8DC90', + }, + }, + { + viewType: ViewType.STATIC, + tl: [.075, -.925], + br: [.9, -.775], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], + description: 'A small text field for a title that categorizes the rest of the content.', + opts: { + borderColor: '#3B4A2C', + borderWidth: '8', + contentXCentering: "h-center", + backgroundColor: '#B8DC90', + }, + }, + { + viewType: ViewType.DEC, + tl: [-.82, -.4], + br: [-.5, -.2], + opts: { + backgroundColor: '#94B058', + borderColor: '#3B4A2C', + borderWidth: '8', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-0.66, -.65], + br: [0.66, .25], + types: [TemplateFieldType.VISUAL], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE], + description: 'A medium to large field in the center of the template, for the main visual content.', + opts: { + borderColor: '#3B4A2C', + borderWidth: '8', + backgroundColor: '#B8DC90', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-.875, .425], + br: [0.875, .925], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE], + description: 'A medium to large field at the bottom of the template, for the main text content.', + opts: { + borderColor: '#3B4A2C', + borderWidth: '8', + contentXCentering: "h-center", + backgroundColor: '#B8DC90', + }, + }, + { + viewType: ViewType.DEC, + tl: [-1.1, -.62], + br: [-.9, -.5], + opts: { + backgroundColor: '#7A9D31', + borderColor: '#3B4A2C', + borderWidth: '8', + }, + }, + { + viewType: ViewType.DEC, + tl: [-1.1, 0], + br: [-.9, .15], + opts: { + backgroundColor: '#94B058', + borderColor: '#3B4A2C', + borderWidth: '8', + }, + }, + { + viewType: ViewType.DEC, + tl: [-.93, -.265], + br: [-.715, -.125], + opts: { + backgroundColor: '#728745', + borderColor: '#3B4A2C', + borderWidth: '8', + }, + }, + { + viewType: ViewType.DEC, + tl: [.7, -.45], + br: [.85, -.3], + opts: { + backgroundColor: '#7A9D31', + borderColor: '#3B4A2C', + borderWidth: '8', + }, + }, + { + viewType: ViewType.DEC, + tl: [.8, .03], + br: [1.2, .33], + opts: { + backgroundColor: '#728745', + borderColor: '#3B4A2C', + borderWidth: '8', + }, + }, + { + viewType: ViewType.DEC, + tl: [.875, -.13], + br: [1.2, .12], + opts: { + backgroundColor: '#94B058', + borderColor: '#3B4A2C', + borderWidth: '8', + }, + }, + ] + } + + public static FourFieldCarousel: FieldSettings = { + title: 'title_fourfieldcarousel', + viewType: ViewType.FREEFORM, + tl:[0,0], + br:[500, 600], + opts: { + backgroundColor: '#DDD3A9', + }, + subfields: [ + { + viewType: ViewType.STATIC, + tl: [-0.8, -.9], + br: [0.8, -.5], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], + description: 'A small text field for a title that categorizes the rest of the content.', + opts: { + borderColor: 'yellow', + borderWidth: '8', + contentXCentering: "h-center", + backgroundColor: 'transparent', + }, + }, + { + viewType: ViewType.CAROUSEL3D, + tl: [-0.9, -.3], + br: [0.9, .9], + opts: { + borderColor: 'yellow', + borderWidth: '8', + backgroundColor: 'transparent', + }, + subfields: [ + { + viewType: ViewType.STATIC, + tl: [-.3, -.6], + br: [.3, .6], + types: [TemplateFieldType.VISUAL, TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], + description: 'A medium to large field for content that will share central focus with other content in the carousel.', + opts: { + borderColor: 'yellow', + borderWidth: '8', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-.3, -.6], + br: [.3, .6], + types: [TemplateFieldType.VISUAL, TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], + description: 'A medium to large field for content that will share central focus with other content in the carousel.', + opts: { + borderColor: 'black', + borderWidth: '8', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-.3, -.6], + br: [.3, .6], + types: [TemplateFieldType.VISUAL, TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], + description: 'A medium to large field for content that will share central focus with other content in the carousel.', + opts: { + borderColor: 'yellow', + borderWidth: '8', + }, + }, + ] + }, + ] + } + + public static ThreeField001: FieldSettings = { + title: 'threefield001', + viewType: ViewType.FREEFORM, + tl: [0,0], + br: [575, 770], + opts: { + backgroundColor: '#DDD3A9', + }, + subfields: [ + { + viewType: ViewType.FREEFORM, + tl: [-0.66, -0.747], + br: [0.66, 0.247], + description: 'A medium to large field for visual content that is the central focus.', + opts: { + borderColor: 'yellow', + borderWidth: '8', + backgroundColor: '#DDD3A9', + rotation: 45, + }, + subfields: [ + { + viewType: ViewType.STATIC, + tl: [-1.25, -1.25], + br: [1.25, 1.25], + types: [TemplateFieldType.VISUAL], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], + description: 'A medium to large field for visual content that is the central focus.', + opts: { + rotation: -45, + }, + }, + ] + }, + { + viewType: ViewType.STATIC, + tl: [-0.7, 0.2], + br: [0.7, 0.46], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], + description: 'A very small text field for one to a few words. A good caption for the image.', + opts: { + backgroundColor: 'transparent', + contentXCentering: 'h-center', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-0.95, 0.5], + br: [0.95, 0.95], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE], + description: 'A medium to large text field for a thorough description of the image. ', + opts: { + backgroundColor: 'transparent', + color: 'white', + }, + }, + { + viewType: ViewType.FREEFORM, + tl: [0.2, -1.32], + br: [1.8, -0.66], + opts: { + backgroundColor: '#CEB155', + rotation: 45, + }, + subfields: [ + { + viewType: ViewType.DEC, + tl: [-1, -.7], + br: [1, -.625], + opts: { + backgroundColor: 'yellow', + }, + }, + ] + }, + { + viewType: ViewType.FREEFORM, + tl: [-1.8, -1.32], + br: [-0.2, -0.66], + opts: { + backgroundColor: '#CEB155', + rotation: 135, + }, + subfields: [ + { + viewType: ViewType.DEC, + tl: [-1, -.7], + br: [1, -.625], + opts: { + backgroundColor: 'yellow', + }, + }, + ] + }, + { + viewType: ViewType.FREEFORM, + tl: [0.33, 0.75], + br: [1.66, 1.25], + opts: { + backgroundColor: '#CEB155', + rotation: 135, + }, + subfields: [ + { + viewType: ViewType.DEC, + tl: [-1, -.7], + br: [1, -.625], + opts: { + backgroundColor: 'yellow', + }, + }, + ] + }, + { + viewType: ViewType.FREEFORM, + tl: [-1.66, 0.75], + br: [-0.33, 1.25], + opts: { + backgroundColor: '#CEB155', + rotation: 45, + }, + subfields: [ + { + viewType: ViewType.DEC, + tl: [-1, -.7], + br: [1, -.625], + opts: { + backgroundColor: 'yellow', + }, + }, + ] + }, + ], + }; + + public static ThreeField002: FieldSettings = { + title: 'threefield002', + viewType: ViewType.FREEFORM, + tl: [0,0], + br: [477, 662], + opts: { + backgroundColor: '#9E9C95', + }, + subfields: [ + { + viewType: ViewType.STATIC, + tl: [-0.875, -0.9], + br: [0.875, 0.7], + types: [TemplateFieldType.VISUAL], + sizes: [TemplateFieldSize.MEDIUM, TemplateFieldSize.LARGE, TemplateFieldSize.HUGE], + description: 'A medium to large visual field for the main content of the template', + opts: { + borderWidth: '15', + borderColor: '#E0E0DA', + }, + }, + { + viewType: ViewType.STATIC, + tl: [0.1, 0.775], + br: [0.95, 0.975], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], + description: 'A very small text field for one to a few words. The content should represent a general categorization of the image.', + opts: { + backgroundColor: 'transparent', + color: '#AF0D0D', + fontTransform: 'uppercase', + fontBold: true, + contentXCentering: 'h-left', + }, + }, + { + viewType: ViewType.STATIC, + tl: [-0.95, 0.775], + br: [-0.1, 0.975], + types: [TemplateFieldType.TEXT], + sizes: [TemplateFieldSize.TINY, TemplateFieldSize.SMALL], + description: 'A very small text field for one to a few words. The content should contextualize field 2.', + opts: { + backgroundColor: 'transparent', + color: 'black', + contentXCentering: 'h-right', + }, + }, + { + viewType: ViewType.DEC, + tl: [-0.025, 0.8], + br: [0.025, 0.95], + opts: { + backgroundColor: '#E0E0DA', + }, + }, + ], + }; +} + + diff --git a/src/client/views/nodes/DataVizBox/DocCreatorMenu/TemplateManager.tsx b/src/client/views/nodes/DataVizBox/DocCreatorMenu/TemplateManager.tsx new file mode 100644 index 000000000..50ae4d72a --- /dev/null +++ b/src/client/views/nodes/DataVizBox/DocCreatorMenu/TemplateManager.tsx @@ -0,0 +1,22 @@ +import { Col } from "./DocCreatorMenu"; +import { FieldSettings } from "./FieldTypes/Field"; +import { Template } from "./Template"; + +export class TemplateManager { + + templates: Template[] = []; + + constructor(templateSettings: FieldSettings[]) { + this.templates = this.initializeTemplates(templateSettings); + } + + initializeTemplates = (templateSettings: FieldSettings[]): Template[] => { + const initializedTemplates: Template[] = []; + templateSettings.forEach(settings => initializedTemplates.push(new Template(settings))); + return initializedTemplates; + } + + getValidTemplates = (cols: Col[]): Template[] => { + return this.templates.filter(template => template.isValidTemplate(cols)); + } +}
\ No newline at end of file diff --git a/src/client/views/nodes/DataVizBox/components/Chart.scss b/src/client/views/nodes/DataVizBox/components/Chart.scss index 0eb27b65b..ff1fa343d 100644 --- a/src/client/views/nodes/DataVizBox/components/Chart.scss +++ b/src/client/views/nodes/DataVizBox/components/Chart.scss @@ -1,4 +1,4 @@ -@import '../../../global/globalCssVariables.module.scss'; +@use '../../../global/globalCssVariables.module.scss' as global; .chart-container { display: flex; flex-direction: column; @@ -108,7 +108,7 @@ } } tr td { - height: $DATA_VIZ_TABLE_ROW_HEIGHT !important; // bcz: hack. you can't set a <tr> height directly, but you can set the height of all of it's <td>s. So this is the height of a tableBox row. + height: global.$DATA_VIZ_TABLE_ROW_HEIGHT !important; // bcz: hack. you can't set a <tr> height directly, but you can set the height of all of it's <td>s. So this is the height of a tableBox row. padding: 0 !important; vertical-align: middle !important; } @@ -135,7 +135,7 @@ } .tableBox-filterPopup { - background: $light-gray; + background: global.$light-gray; position: absolute; min-width: 235px; top: 60px; @@ -152,7 +152,7 @@ .tableBox-filterPopup-selectColumn-each { margin-left: 25px; border-radius: 3px; - background: $light-gray; + background: global.$light-gray; } } .tableBox-filterPopup-setValue { @@ -162,7 +162,7 @@ .tableBox-filterPopup-setValue-each { margin-right: 5px; border-radius: 3px; - background: $light-gray; + background: global.$light-gray; } .tableBox-filterPopup-setValue-input { margin: 5px; diff --git a/src/client/views/nodes/DocumentLinksButton.scss b/src/client/views/nodes/DocumentLinksButton.scss index b32b27e65..e1b83dc59 100644 --- a/src/client/views/nodes/DocumentLinksButton.scss +++ b/src/client/views/nodes/DocumentLinksButton.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .documentLinksButton-wrapper { transform-origin: top left; @@ -29,7 +29,7 @@ pointer-events: auto; display: flex; align-items: center; - background-color: $light-blue; + background-color: global.$light-blue; color: black; } .documentLinksButton, @@ -59,30 +59,30 @@ } } .documentLinksButton { - background-color: $dark-gray; - color: $white; + background-color: global.$dark-gray; + color: global.$white; font-weight: bold; font-size: 100%; font-family: 'Roboto'; transition: 0.2s ease all; &:hover { - background-color: $black; + background-color: global.$black; } } .documentLinksButton.startLink { - background-color: $medium-blue; + background-color: global.$medium-blue; width: 75%; height: 75%; - color: $white; + color: global.$white; font-weight: bold; font-size: 100%; transition: 0.2s ease all; } .documentLinksButton-endLink { - border: $medium-blue 2px dashed; - color: $medium-blue; + border: global.$medium-blue 2px dashed; + color: global.$medium-blue; background-color: none !important; font-size: 100%; transition: 0.2s ease all; diff --git a/src/client/views/nodes/DocumentView.scss b/src/client/views/nodes/DocumentView.scss index 7e5507586..dd5fd0d0c 100644 --- a/src/client/views/nodes/DocumentView.scss +++ b/src/client/views/nodes/DocumentView.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .documentView-effectsWrapper { border-radius: inherit; @@ -28,7 +28,7 @@ // overflow: hidden; // need this so that title will be clipped when borderRadius is set // transition: outline 0.3s linear; - // background: $white; //overflow: hidden; + // background: global.$white; //overflow: hidden; transform-origin: center; &.minimized { @@ -180,7 +180,7 @@ .documentView-titleWrapper, .documentView-titleWrapper-hover { - color: $black; + color: global.$black; transform-origin: top left; top: 0; width: 100%; @@ -291,6 +291,7 @@ justify-items: center; background-color: rgb(223, 223, 223); transform-origin: top left; + background: transparent; .documentView-editorView-resizer { height: 5px; diff --git a/src/client/views/nodes/DocumentView.tsx b/src/client/views/nodes/DocumentView.tsx index 0193fd328..595abc7f8 100644 --- a/src/client/views/nodes/DocumentView.tsx +++ b/src/client/views/nodes/DocumentView.tsx @@ -131,6 +131,7 @@ export class DocumentViewInternal extends DocComponent<FieldViewProps & Document style = (doc: Doc, sprop: StyleProp | string) => this._props.styleProvider?.(doc, this._props, sprop); @computed get opacity() { return this.style(this.layoutDoc, StyleProp.Opacity) as number; } // prettier-ignore @computed get boxShadow() { return this.style(this.layoutDoc, StyleProp.BoxShadow) as string; } // prettier-ignore + @computed get border() { return this.style(this.layoutDoc, StyleProp.Border) as string || ""; } // prettier-ignore @computed get borderRounding() { return this.style(this.layoutDoc, StyleProp.BorderRounding) as string; } // prettier-ignore @computed get widgetDecorations() { return this.style(this.layoutDoc, StyleProp.Decorations) as JSX.Element; } // prettier-ignore @computed get backgroundBoxColor(){ return this.style(this.layoutDoc, StyleProp.BackgroundColor + ':docView') as string; } // prettier-ignore @@ -278,16 +279,17 @@ export class DocumentViewInternal extends DocComponent<FieldViewProps & Document setTimeout(() => this._titleRef.current?.setIsFocused(true)); // use timeout in case title wasn't shown to allow re-render so that titleref will be defined }; onBrowseClick = (e: React.MouseEvent) => { - const browseTransitionTime = 500; + //const browseTransitionTime = 500; DocumentView.DeselectAll(); DocumentView.showDocument(this.Document, { zoomScale: 0.8, willZoomCentered: true }, (focused: boolean) => { - const options: FocusViewOptions = { pointFocus: { X: e.clientX, Y: e.clientY }, zoomTime: browseTransitionTime }; + // const options: FocusViewOptions = { pointFocus: { X: e.clientX, Y: e.clientY }, zoomTime: browseTransitionTime }; if (!focused && this._docView) { - this._docView - .docViewPath() - .reverse() - .forEach(cont => cont.ComponentView?.focus?.(cont.Document, options)); - Doc.linkFollowHighlight(this.Document, false); + DocumentView.showDocument(this.Document, { zoomScale: 0.3, willZoomCentered: true }); + // this._docView + // .docViewPath() + // .reverse() + // .forEach(cont => cont.ComponentView?.focus?.(cont.Document, options)); + // Doc.linkFollowHighlight(this.Document, false); } }); e.stopPropagation(); @@ -684,14 +686,14 @@ export class DocumentViewInternal extends DocComponent<FieldViewProps & Document }; rootSelected = () => this._rootSelected; - panelHeight = () => this._props.PanelHeight() - this.headerMargin; + panelHeight = () => this._props.PanelHeight() - this.headerMargin - 2 * NumCast(this.Document.borderWidth); screenToLocalContent = () => this._props .ScreenToLocalTransform() - .translate(0, -this.headerMargin) + .translate(-NumCast(this.Document.borderWidth), -this.headerMargin - NumCast(this.Document.borderWidth)) .scale(this._props.showAIEditor ? (this._props.PanelHeight() || 1) / this.aiContentsHeight() : 1); onClickFunc = this.disableClickScriptFunc ? undefined : () => this.onClickHdlr; - setHeight = (height: number) => { !this._props.suppressSetHeight && (this.layoutDoc._height = Math.min(NumCast(this.layoutDoc._maxHeight, Number.MAX_SAFE_INTEGER), height)); } // prettier-ignore + setHeight = (height: number) => { !this._props.suppressSetHeight && (this.layoutDoc._height = Math.min(NumCast(this.layoutDoc._maxHeight, Number.MAX_SAFE_INTEGER), height + 2 * NumCast(this.Document.borderWidth))); } // prettier-ignore setContentView = action((view: ViewBoxInterface<FieldViewProps>) => { this._componentView = view; }); // prettier-ignore isContentActive = (): boolean | undefined => this._isContentActive; childFilters = () => [...this._props.childFilters(), ...StrListCast(this.layoutDoc.childFilters)]; @@ -777,9 +779,9 @@ export class DocumentViewInternal extends DocComponent<FieldViewProps & Document style={{ width: `${100 / this.uiBtnScaling}%`, // transform: `scale(${this.uiBtnScaling})`, - bottom: this.maxWidgetSize, + bottom: Number.isNaN(this.maxWidgetSize) ? undefined : this.maxWidgetSize, }}> - {this._props.DocumentView?.() ? <TagsView Views={[this._props.DocumentView?.()]} /> : null} + {this._props.DocumentView?.() && !this._props.docViewPath().slice(-2)[0].ComponentView?.isUnstyledView?.() ? <TagsView Views={[this._props.DocumentView?.()]} /> : null} </div> ) : ( <> @@ -796,6 +798,7 @@ export class DocumentViewInternal extends DocComponent<FieldViewProps & Document <div className="documentView-editorView" style={{ + background: SnappingManager.userVariantColor, width: `${100 / this.uiBtnScaling}%`, // transform: `scale(${this.uiBtnScaling})`, }} @@ -989,15 +992,11 @@ export class DocumentViewInternal extends DocComponent<FieldViewProps & Document highlightStroke: undefined, }; const { clipPath, jsx } = (borderPath as { clipPath: string; jsx: JSX.Element }) ?? { clipPath: undefined, jsx: undefined }; - const boxShadow = !highlighting - ? this.boxShadow - : highlighting && this.borderRounding && highlightStyle !== 'dashed' - ? `0 0 0 ${highlightIndex}px ${highlightColor}` - : this.boxShadow || (this.Document.isTemplateForField ? 'black 0.2vw 0.2vw 0.8vw' : undefined); + const boxShadow = this.boxShadow; const renderDoc = this.renderDoc({ borderRadius: this.borderRounding, - outline: highlighting && !this.borderRounding && !highlightStroke ? `${highlightColor} ${highlightStyle} ${highlightIndex}px` : 'solid 0px', - border: highlighting && this.borderRounding && highlightStyle === 'dashed' ? `${highlightStyle} ${highlightColor} ${highlightIndex}px` : undefined, + outline: highlighting && !highlightStroke ? `${highlightColor} ${highlightStyle} ${highlightIndex}px` : 'solid 0px', + border: this._componentView?.isUnstyledView?.() ? undefined : this.border, boxShadow, clipPath, }); @@ -1013,7 +1012,7 @@ export class DocumentViewInternal extends DocComponent<FieldViewProps & Document onPointerOver={() => (!SnappingManager.IsDragging || SnappingManager.CanEmbed) && Doc.BrushDoc(this.Document)} onPointerLeave={e => !isParentOf(this._contentDiv, document.elementFromPoint(e.nativeEvent.x, e.nativeEvent.y)) && Doc.UnBrushDoc(this.Document)} style={{ - borderRadius: this.borderRounding, + borderRadius: this._componentView?.isUnstyledView?.() ? undefined : this.borderRounding, pointerEvents: this._pointerEvents === 'visiblePainted' ? 'none' : this._pointerEvents, // visible painted means that the underlying doc contents are irregular and will process their own pointer events (otherwise, the contents are expected to fill the entire doc view box so we can handle pointer events here) }}> {this._componentView?.isUnstyledView?.() || this.Document.type === DocumentType.CONFIG || !renderDoc ? renderDoc : DocumentViewInternal.AnimationEffect(renderDoc, this.Document[Animation], this.Document)} @@ -1487,7 +1486,7 @@ export class DocumentView extends DocComponent<DocumentViewProps>() { ShouldNotScale = () => this.shouldNotScale; NativeWidth = () => this.effectiveNativeWidth; NativeHeight = () => this.effectiveNativeHeight; - PanelWidth = () => this.panelWidth; + PanelWidth = () => this.panelWidth - 2 * NumCast(this.Document.borderWidth); PanelHeight = () => this.panelHeight; ReducedPanelWidth = () => this.panelWidth / 2; ReducedPanelHeight = () => this.panelWidth / 2; diff --git a/src/client/views/nodes/EquationBox.scss b/src/client/views/nodes/EquationBox.scss index 55e0f5184..bcbb44e68 100644 --- a/src/client/views/nodes/EquationBox.scss +++ b/src/client/views/nodes/EquationBox.scss @@ -1,5 +1,3 @@ -@import '../global/globalCssVariables.module.scss'; - .equationBox-cont { transform-origin: center; width: fit-content; diff --git a/src/client/views/nodes/FontIconBox/FontIconBox.scss b/src/client/views/nodes/FontIconBox/FontIconBox.scss index 2405889cf..186d24e92 100644 --- a/src/client/views/nodes/FontIconBox/FontIconBox.scss +++ b/src/client/views/nodes/FontIconBox/FontIconBox.scss @@ -1,4 +1,4 @@ -@import '../../global/globalCssVariables.module.scss'; +@use '../../global/globalCssVariables.module.scss' as global; // bcz: something's messed up with the IconButton css. this mostly fixes the fit-all button, the color buttons, the undo +/- expander and the dropdown doc type list (eg 'text') .iconButton-container { @@ -23,7 +23,7 @@ justify-content: center; align-items: center; font-size: 80%; - border-radius: $standard-border-radius; + border-radius: global.$standard-border-radius; transition: 0.15s; .menuButton-wrap { @@ -34,7 +34,7 @@ } .fontIconBox-label { - color: $white; + color: global.$white; bottom: -1; position: absolute; text-align: center; @@ -124,17 +124,17 @@ width: 21px; left: 2px; bottom: 2px; - background-color: $white; + background-color: global.$white; -webkit-transition: 0.4s; transition: 0.4s; } input:checked + .slider { - background-color: $medium-blue; + background-color: global.$medium-blue; } input:focus + .slider { - box-shadow: 0 0 1px $medium-blue; + box-shadow: 0 0 1px global.$medium-blue; } input:checked + .slider:before { @@ -145,11 +145,11 @@ /* Rounded sliders */ .slider.round { - border-radius: $standard-border-radius; + border-radius: global.$standard-border-radius; } .slider.round:before { - border-radius: $standard-border-radius; + border-radius: global.$standard-border-radius; } } @@ -259,12 +259,12 @@ height: fit-content; top: 100%; z-index: 21; - background-color: $white; + background-color: global.$white; box-shadow: 0px 3px 4px rgba(0, 0, 0, 0.3); padding: 1px; .list-item { - color: $black; + color: global.$black; width: 100%; height: 25px; font-weight: 400; @@ -285,7 +285,7 @@ background: transparent; &.slider { - color: $white; + color: global.$white; cursor: pointer; flex-direction: column; background: transparent; @@ -302,7 +302,7 @@ z-index: 21; background-color: #e3e3e3; box-shadow: 0px 3px 4px rgba(0, 0, 0, 0.3); - border-radius: $standard-border-radius; + border-radius: global.$standard-border-radius; .menu-slider { height: 10px; @@ -340,7 +340,7 @@ border: none; text-align: right; width: 100%; - color: $white; + color: global.$white; height: 100%; text-align: center; } @@ -354,7 +354,7 @@ &.list { width: 100%; justify-content: space-around; - border: $standard-border; + border: global.$standard-border; .menuButton-dropdownList { position: absolute; @@ -365,12 +365,12 @@ overflow-y: scroll; top: 100%; z-index: 21; - background-color: $white; + background-color: global.$white; box-shadow: 0px 3px 4px rgba(0, 0, 0, 0.3); padding: 1px; .list-item { - color: $black; + color: global.$black; width: 100%; height: 25px; font-weight: 400; @@ -394,7 +394,7 @@ padding-left: 10px; justify-content: flex-start; color: black; - background-color: $light-gray; + background-color: global.$light-gray; padding: 5px; padding-left: 10px; width: 100%; @@ -417,7 +417,7 @@ top: 100%; background-color: #e3e3e3; box-shadow: 0px 3px 4px rgba(0, 0, 0, 0.3); - border-radius: $standard-border-radius; + border-radius: global.$standard-border-radius; } } diff --git a/src/client/views/nodes/FontIconBox/FontIconBox.tsx b/src/client/views/nodes/FontIconBox/FontIconBox.tsx index f58862028..7e0236b74 100644 --- a/src/client/views/nodes/FontIconBox/FontIconBox.tsx +++ b/src/client/views/nodes/FontIconBox/FontIconBox.tsx @@ -1,11 +1,13 @@ +import { Button, ColorPicker, Dropdown, DropdownType, IconButton, IListItemProps, MultiToggle, NumberDropdown, NumberDropdownType, Popup, Size, Toggle, ToggleType, Type } from '@dash/components'; import { IconProp } from '@fortawesome/fontawesome-svg-core'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; -import { Button, ColorPicker, Dropdown, DropdownType, IconButton, IListItemProps, MultiToggle, NumberDropdown, NumberDropdownType, Popup, Size, Toggle, ToggleType, Type } from '@dash/components'; import { action, computed, makeObservable, observable } from 'mobx'; import { observer } from 'mobx-react'; import * as React from 'react'; import { ClientUtils, DashColor, returnFalse, returnTrue, setupMoveUpEvents } from '../../../../ClientUtils'; import { Doc, DocListCast, StrListCast } from '../../../../fields/Doc'; +import { InkTool } from '../../../../fields/InkField'; +import { ScriptField } from '../../../../fields/ScriptField'; import { BoolCast, DocCast, NumCast, ScriptCast, StrCast } from '../../../../fields/Types'; import { emptyFunction } from '../../../../Utils'; import { Docs } from '../../../documents/Documents'; @@ -21,8 +23,6 @@ import { FieldView, FieldViewProps } from '../FieldView'; import { OpenWhere } from '../OpenWhere'; import './FontIconBox.scss'; import TrailsIcon from './TrailsIcon'; -import { InkTool } from '../../../../fields/InkField'; -import { ScriptField } from '../../../../fields/ScriptField'; export enum ButtonType { TextButton = 'textBtn', @@ -134,6 +134,7 @@ export class FontIconBox extends ViewBoxBaseComponent<ButtonProps>() { min={NumCast(this.dataDoc.numBtnMin, 0)} max={NumCast(this.dataDoc.numBtnMax, 100)} number={checkResult} + size={Size.XSMALL} setNumber={undoable(value => numScript(value), `${this.Document.title} button set from list`)} fillWidth /> diff --git a/src/client/views/nodes/IconTagBox.scss b/src/client/views/nodes/IconTagBox.scss index c79d662f4..202b0c701 100644 --- a/src/client/views/nodes/IconTagBox.scss +++ b/src/client/views/nodes/IconTagBox.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .card-button-container { display: flex; @@ -18,7 +18,7 @@ margin: auto; padding: 0; border-radius: 50%; - background-color: $dark-gray; + background-color: global.$dark-gray; background-color: transparent; } } diff --git a/src/client/views/nodes/ImageBox.scss b/src/client/views/nodes/ImageBox.scss index fe4f0b1a2..3d6942e6f 100644 --- a/src/client/views/nodes/ImageBox.scss +++ b/src/client/views/nodes/ImageBox.scss @@ -40,7 +40,8 @@ max-height: 100%; pointer-events: inherit; background: transparent; - z-index: -10000; + z-index: 0; + // z-index: -10000; // bcz: not sure why this was here. it broke dropping images on the image box alternate bullseye icon. img { height: auto; @@ -103,6 +104,10 @@ margin: 0 auto; display: flex; height: 100%; + img { + object-fit: contain; + height: 100%; + } .imageBox-fadeBlocker, .imageBox-fadeBlocker-hover { @@ -122,6 +127,7 @@ } } } +.imageBox-regenerateDropTarget, .imageBox-alternateDropTarget { position: absolute; color: white; @@ -129,7 +135,19 @@ right: 0; bottom: 0; z-index: 2; + transform-origin: bottom right; cursor: default; + > svg { + width: 100%; + height: 100%; + } +} +.imageBox-regenerateDropTarget { + right: 30; + border-radius: 50%; + svg { + border-radius: 50%; + } } .imageBox-fader img { @@ -182,8 +200,9 @@ flex-direction: row; gap: 5px; width: 100%; + padding: 0 10; .imageBox-aiView-regenerate-createBtn { - max-width: 10%; + max-width: 20%; .button-container { width: 100% !important; justify-content: left !important; @@ -194,7 +213,7 @@ .imageBox-aiView-firefly { overflow: hidden; text-overflow: ellipsis; - max-width: 10%; + max-width: 15%; width: 100%; } .imageBox-aiView-regenerate-send { @@ -205,7 +224,7 @@ text-align: center; align-items: center; display: flex; - max-width: 25%; + max-width: 90%; width: 100%; .imageBox-aiView-similarity { max-width: 65; @@ -223,5 +242,6 @@ text-overflow: ellipsis; max-width: 65%; width: 100%; + color: black; } } diff --git a/src/client/views/nodes/ImageBox.tsx b/src/client/views/nodes/ImageBox.tsx index caefbf542..017ef7191 100644 --- a/src/client/views/nodes/ImageBox.tsx +++ b/src/client/views/nodes/ImageBox.tsx @@ -1,11 +1,12 @@ +import { Button, Colors, Size, Type } from '@dash/components'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Slider, Tooltip } from '@mui/material'; import axios from 'axios'; -import { Colors, Button, Type, Size } from '@dash/components'; import { action, computed, IReactionDisposer, makeObservable, observable, ObservableMap, reaction } from 'mobx'; import { observer } from 'mobx-react'; import { extname } from 'path'; import * as React from 'react'; +import { AiOutlineSend } from 'react-icons/ai'; import ReactLoading from 'react-loading'; import { ClientUtils, DashColor, returnEmptyString, returnFalse, returnOne, returnZero, setupMoveUpEvents, UpdateIcon } from '../../../ClientUtils'; import { Doc, DocListCast, Opt } from '../../../fields/Doc'; @@ -16,12 +17,14 @@ import { ObjectField } from '../../../fields/ObjectField'; import { Cast, DocCast, ImageCast, NumCast, RTFCast, StrCast } from '../../../fields/Types'; import { ImageField } from '../../../fields/URLField'; import { TraceMobx } from '../../../fields/util'; +import { Upload } from '../../../server/SharedMediaTypes'; import { emptyFunction } from '../../../Utils'; import { Docs } from '../../documents/Documents'; import { DocumentType } from '../../documents/DocumentTypes'; import { DocUtils, FollowLinkScript } from '../../documents/DocUtils'; import { Networking } from '../../Network'; import { DragManager } from '../../util/DragManager'; +import { SettingsManager } from '../../util/SettingsManager'; import { SnappingManager } from '../../util/SnappingManager'; import { undoable, undoBatch } from '../../util/UndoManager'; import { CollectionFreeFormView } from '../collections/collectionFreeForm/CollectionFreeFormView'; @@ -32,6 +35,9 @@ import { MarqueeAnnotator } from '../MarqueeAnnotator'; import { OverlayView } from '../OverlayView'; import { AnchorMenu } from '../pdf/AnchorMenu'; import { PinDocView, PinProps } from '../PinFuncs'; +import { DrawingFillHandler } from '../smartdraw/DrawingFillHandler'; +import { FireflyImageData, isFireflyImageData } from '../smartdraw/FireflyConstants'; +import { SmartDrawHandler } from '../smartdraw/SmartDrawHandler'; import { StickerPalette } from '../smartdraw/StickerPalette'; import { StyleProp } from '../StyleProp'; import { DocumentView } from './DocumentView'; @@ -39,12 +45,7 @@ import { FieldView, FieldViewProps } from './FieldView'; import { FocusViewOptions } from './FocusViewOptions'; import './ImageBox.scss'; import { OpenWhere } from './OpenWhere'; -import { Upload } from '../../../server/SharedMediaTypes'; -import { SmartDrawHandler } from '../smartdraw/SmartDrawHandler'; -import { SettingsManager } from '../../util/SettingsManager'; -import { AiOutlineSend } from 'react-icons/ai'; -import { FireflyImageData } from '../smartdraw/FireflyConstants'; -import { DrawingFillHandler } from '../smartdraw/DrawingFillHandler'; +import { RichTextField } from '../../../fields/RichTextField'; export class ImageEditorData { // eslint-disable-next-line no-use-before-define @@ -83,7 +84,8 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { private _disposers: { [name: string]: IReactionDisposer } = {}; private _getAnchor: (savedAnnotations: Opt<ObservableMap<number, HTMLDivElement[]>>, addAsAnnotation: boolean) => Opt<Doc> = () => undefined; private _overlayIconRef = React.createRef<HTMLDivElement>(); - private _mainCont: React.RefObject<HTMLDivElement> = React.createRef(); + private _regenerateIconRef = React.createRef<HTMLDivElement>(); + private _mainCont: HTMLDivElement | null = null; private _annotationLayer: React.RefObject<HTMLDivElement> = React.createRef(); imageRef: HTMLImageElement | null = null; // <video> ref marqueeref = React.createRef<MarqueeAnnotator>(); @@ -108,6 +110,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { } protected createDropTarget = (ele: HTMLDivElement) => { + this._mainCont = ele; this._dropDisposer?.(); ele && (this._dropDisposer = DragManager.MakeDropTarget(ele, this.drop.bind(this), this.Document)); }; @@ -135,11 +138,11 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { this._disposers.sizer = reaction( () => ({ forceFull: this._props.renderDepth < 1 || this.layoutDoc._showFullRes, - scrSize: (this.ScreenToLocalBoxXf().inverse().transformDirection(this.nativeSize.nativeWidth, this.nativeSize.nativeHeight)[0] / this.nativeSize.nativeWidth) * NumCast(this.layoutDoc._freeform_scale, 1), + scrSize: (NumCast(this.layoutDoc._freeform_scale, 1) / (this._props.DocumentView?.().screenToLocalScale() ?? 1)) * this._props.PanelWidth(), selected: this._props.isSelected(), }), ({ forceFull, scrSize, selected }) => { - this._curSuffix = selected ? '_o' : this.fieldKey === 'icon' ? '_m' : forceFull ? '_o' : scrSize < 0.25 ? '_s' : scrSize < 0.5 ? '_m' : scrSize < 0.8 ? '_l' : '_o'; + this._curSuffix = selected ? '_o' : this.fieldKey === 'icon' ? '_m' : forceFull ? '_o' : scrSize < 100 ? '_s' : scrSize < 400 ? '_m' : scrSize < 800 ? '_l' : '_o'; }, { fireImmediately: true, delay: 1000 } ); @@ -147,7 +150,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { this._disposers.path = reaction( () => ({ nativeSize: this.nativeSize, width: NumCast(this.layoutDoc._width) }), ({ nativeSize, width }) => { - if (layoutDoc === this.layoutDoc || !this.layoutDoc._height) { + if ((layoutDoc === this.layoutDoc && !this.layoutDoc._layout_nativeDimEditable) || !this.layoutDoc._height) { this.layoutDoc._height = (width * nativeSize.nativeHeight) / nativeSize.nativeWidth; } }, @@ -157,8 +160,8 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { () => this.layoutDoc.layout_scrollTop, sTop => { this._forcedScroll = true; - !this._ignoreScroll && this._mainCont.current && (this._mainCont.current.scrollTop = NumCast(sTop)); - this._mainCont.current?.scrollTo({ top: NumCast(sTop) }); + !this._ignoreScroll && this._mainCont && (this._mainCont.scrollTop = NumCast(sTop)); + this._mainCont?.scrollTo({ top: NumCast(sTop) }); this._forcedScroll = false; }, { fireImmediately: true } @@ -195,36 +198,47 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { this._searchInput = selection; }; - drop = undoable((e: Event, de: DragManager.DropEvent) => { - if (de.complete.docDragData) { - let added: boolean | undefined; - const targetIsBullseye = (ele: HTMLElement): boolean => { - if (!ele) return false; - if (ele === this._overlayIconRef.current) return true; - return targetIsBullseye(ele.parentElement as HTMLElement); - }; - if (de.metaKey || targetIsBullseye(e.target as HTMLElement)) { - added = de.complete.docDragData.droppedDocuments.reduce((last: boolean, drop: Doc) => { - this.layoutDoc[this.fieldKey + '_usePath'] = 'alternate:hover'; - return last && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_alternates', drop); - }, true); - } else if (de.altKey || !this.dataDoc[this.fieldKey]) { - const layoutDoc = de.complete.docDragData?.draggedDocuments[0]; - const targetField = Doc.LayoutFieldKey(layoutDoc); - const targetDoc = layoutDoc[DocData]; - if (targetDoc[targetField] instanceof ImageField) { - added = true; - this.dataDoc[this.fieldKey] = ObjectField.MakeCopy(targetDoc[targetField] as ImageField); - Doc.SetNativeWidth(this.dataDoc, Doc.NativeWidth(targetDoc), this.fieldKey); - Doc.SetNativeHeight(this.dataDoc, Doc.NativeHeight(targetDoc), this.fieldKey); + drop = undoable( + action((e: Event, de: DragManager.DropEvent) => { + if (de.complete.docDragData) { + let added: boolean | undefined; + const hitDropTarget = (ele: HTMLElement, dropTarget: HTMLDivElement | null): boolean => { + if (!ele) return false; + if (ele === dropTarget) return true; + return hitDropTarget(ele.parentElement as HTMLElement, dropTarget); + }; + if (de.metaKey || hitDropTarget(e.target as HTMLElement, this._overlayIconRef.current)) { + added = de.complete.docDragData.droppedDocuments.reduce((last: boolean, drop: Doc) => { + this.layoutDoc[this.fieldKey + '_usePath'] = 'alternate:hover'; + return last && Doc.AddDocToList(this.dataDoc, this.fieldKey + '_alternates', drop); + }, true); + } else if (hitDropTarget(e.target as HTMLElement, this._regenerateIconRef.current)) { + this._regenerateLoading = true; + const drag = de.complete.docDragData.draggedDocuments.lastElement(); + const dragField = drag[Doc.LayoutFieldKey(drag)]; + const oldPrompt = StrCast(this.Document.ai_firefly_prompt, StrCast(this.Document.title)); + const newPrompt = (text: string) => (oldPrompt ? `${oldPrompt} ~~~ ${text}` : text); + DrawingFillHandler.drawingToImage(this.Document, 100, newPrompt(dragField instanceof RichTextField ? dragField.Text : ''), drag)?.then(action(() => (this._regenerateLoading = false))); + added = false; + } else if (de.altKey || !this.dataDoc[this.fieldKey]) { + const layoutDoc = de.complete.docDragData?.draggedDocuments[0]; + const targetField = Doc.LayoutFieldKey(layoutDoc); + const targetDoc = layoutDoc[DocData]; + if (targetDoc[targetField] instanceof ImageField) { + added = true; + this.dataDoc[this.fieldKey] = ObjectField.MakeCopy(targetDoc[targetField] as ImageField); + Doc.SetNativeWidth(this.dataDoc, Doc.NativeWidth(targetDoc), this.fieldKey); + Doc.SetNativeHeight(this.dataDoc, Doc.NativeHeight(targetDoc), this.fieldKey); + } } + added === false && e.preventDefault(); + added !== undefined && e.stopPropagation(); + return added; } - added === false && e.preventDefault(); - added !== undefined && e.stopPropagation(); - return added; - } - return false; - }, 'image drop'); + return false; + }), + 'image drop' + ); @undoBatch resolution = () => { @@ -315,6 +329,16 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { return cropping; }; + docEditorView = action(() => { + const field = Cast(this.dataDoc[this.fieldKey], ImageField); + if (field) { + ImageEditorData.Open = true; + ImageEditorData.Source = this.choosePath(field.url); + ImageEditorData.AddDoc = this._props.addDocument; + ImageEditorData.RootDoc = this.Document; + } + }); + specificContextMenu = (): void => { const field = Cast(this.dataDoc[this.fieldKey], ImageField); if (field) { @@ -343,7 +367,8 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { const ext = extname(file); return file.replace(ext, (this._error ? '_o' : this._curSuffix) + ext); })(ImageCast(this.Document[Doc.LayoutFieldKey(this.Document)])?.url.href), - }).then((info: Upload.ImageInformation) => { + }).then(res => { + const info = res as Upload.ImageInformation; const img = Docs.Create.ImageDocument(info.accessPaths.agnostic.client, { title: 'expand:' + this.Document.title }); DocUtils.assignImageInfo(info, img); this._props.addDocTab(img, OpenWhere.addRight); @@ -352,21 +377,17 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { icon: 'expand-arrows-alt', }); funcs.push({ description: 'Copy path', event: () => ClientUtils.CopyText(this.choosePath(field.url)), icon: 'copy' }); - funcs.push({ - description: 'Open Image Editor', - event: action(() => { - ImageEditorData.Open = true; - ImageEditorData.Source = this.choosePath(field.url); - ImageEditorData.AddDoc = this._props.addDocument; - ImageEditorData.RootDoc = this.Document; - }), - icon: 'pencil-alt', - }); + funcs.push({ description: 'Open Image Editor', event: this.docEditorView, icon: 'pencil-alt' }); this.layoutDoc.ai && funcs.push({ description: 'Regenerate AI Image', - event: action(e => { - !SmartDrawHandler.Instance.ShowRegenerate ? SmartDrawHandler.Instance.displayRegenerate(e?.x || 0, e?.y || 0) : SmartDrawHandler.Instance.hideRegenerate(); + event: action(() => { + if (!SmartDrawHandler.Instance.ShowRegenerate && this.DocumentView) { + const [x, y] = this.DocumentView().screenToViewTransform().inverse().transformPoint(NumCast(this.Document.width), 0); + this._props.docViewPath().slice(-2)[0]?.ComponentView?.showSmartDraw?.(x, y, true); + } else { + SmartDrawHandler.Instance.hideRegenerate(); + } }), icon: 'pen-to-square', }); @@ -381,7 +402,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { // updateIcon = () => new Promise<void>(res => res()); updateIcon = (usePanelDimensions?: boolean) => { - const contentDiv = this._mainCont.current; + const contentDiv = this._mainCont; return !contentDiv ? new Promise<void>(res => res()) : UpdateIcon( @@ -415,6 +436,11 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { }; getScrollHeight = () => (this._props.fitWidth?.(this.Document) !== false && NumCast(this.layoutDoc._freeform_scale, 1) === NumCast(this.dataDoc._freeform_scaleMin, 1) ? this.nativeSize.nativeHeight : undefined); + @computed get usingAlternate() { + const usePath = StrCast(this.Document[this.fieldKey + '_usePath']); + return 'alternate' === usePath || ('alternate:hover' === usePath && this._isHovering) || (':hover' === usePath && !this._isHovering); + } + @computed get nativeSize() { TraceMobx(); if (this.paths.length && this.paths[0].includes('icon-hi')) return { nativeWidth: NumCast(this.layoutDoc._width), nativeHeight: NumCast(this.layoutDoc._height), nativeOrientation: 0 }; @@ -423,6 +449,20 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { const nativeOrientation = NumCast(this.dataDoc[this.fieldKey + '_nativeOrientation'], 1); return { nativeWidth, nativeHeight, nativeOrientation }; } + private _sideBtnWidth = 35; + /** + * How much the content of the view is being scaled based on its nesting and its fit-to-width settings + */ + @computed get viewScaling() { return this.ScreenToLocalBoxXf().Scale * ( this._props.NativeDimScaling?.() || 1); } // prettier-ignore + /** + * The maximum size a UI widget can be scaled so that it won't be bigger in screen pixels than its normal 35 pixel size. + */ + @computed get maxWidgetSize() { return Math.min(this._sideBtnWidth, 0.5 * Math.min(NumCast(this.Document.width)))* this.viewScaling; } // prettier-ignore + /** + * How much to reactively scale a UI element so that it is as big as it can be (up to its normal 35pixel size) without being too big for the Doc content + */ + @computed get uiBtnScaling() { return Math.min(this.maxWidgetSize / this._sideBtnWidth, 1); } // prettier-ignore + @computed get overlayImageIcon() { const usePath = this.layoutDoc[`_${this.fieldKey}_usePath`]; return ( @@ -436,10 +476,13 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { <span style={{ color: usePath === 'alternate' ? 'black' : undefined }}> <em>alternate, </em> </span> - and show <span style={{ color: usePath === 'alternate:hover' ? 'black' : undefined }}> <em> alternate on hover</em> </span> + and show + <span style={{ color: usePath === ':hover' ? 'black' : undefined }}> + <em> primary on hover</em> + </span> </div> }> <div @@ -447,13 +490,14 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { ref={this._overlayIconRef} onPointerDown={e => setupMoveUpEvents(e.target, e, returnFalse, emptyFunction, () => { - this.layoutDoc[`_${this.fieldKey}_usePath`] = usePath === undefined ? 'alternate' : usePath === 'alternate' ? 'alternate:hover' : undefined; + this.layoutDoc[`_${this.fieldKey}_usePath`] = usePath === undefined ? 'alternate' : usePath === 'alternate' ? 'alternate:hover' : usePath === 'alternate:hover' ? ':hover' : undefined; }) } style={{ - display: (this._props.isContentActive() !== false && SnappingManager.CanEmbed) || this.dataDoc[this.fieldKey + '_alternates'] ? 'block' : 'none', - width: 'min(10%, 25px)', - height: 'min(10%, 25px)', + display: this._props.isContentActive() && (SnappingManager.CanEmbed || this.dataDoc[this.fieldKey + '_alternates']) ? 'block' : 'none', + transform: `scale(${this.uiBtnScaling})`, + width: this._sideBtnWidth, + height: this._sideBtnWidth, background: usePath === undefined ? 'white' : usePath === 'alternate' ? 'black' : 'gray', color: usePath === undefined ? 'black' : 'white', }}> @@ -462,6 +506,24 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { </Tooltip> ); } + @computed get regenerateImageIcon() { + return ( + <div + className="imageBox-regenerateDropTarget" + ref={this._regenerateIconRef} + onClick={() => DocumentView.showDocument(DocCast(this.Document.ai_firefly_generatedDocs), { openLocation: OpenWhere.addRight })} + style={{ + display: (this._props.isContentActive() && (SnappingManager.CanEmbed || this.Document.ai_firefly_generatedDocs)) || this._regenerateLoading ? 'block' : 'none', + transform: `scale(${this.uiBtnScaling})`, + width: this._sideBtnWidth, + height: this._sideBtnWidth, + background: 'transparent', + // color: SettingsManager.userBackgroundColor, + }}> + {this._regenerateLoading ? <ReactLoading type="spin" color={SettingsManager.userVariantColor} width="100%" height="100%" /> : <FontAwesomeIcon icon="portrait" color={SettingsManager.userColor} size="lg" />} + </div> + ); + } @computed get paths() { const field = this.dataDoc[this.fieldKey] instanceof ImageField ? Cast(this.dataDoc[this.fieldKey], ImageField, null) : new ImageField(String(this.dataDoc[this.fieldKey])); // retrieve the primary image URL that is being rendered from the data doc @@ -473,7 +535,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { .filter(url => url) .map(url => this.choosePath(url)) ?? []; // acc ess the primary layout data of the alternate documents const paths = field ? [this.choosePath(field.url), ...altpaths] : altpaths; - return paths.length ? paths : [defaultUrl.href]; + return paths.length ? paths.reverse() : [defaultUrl.href]; } @computed get content() { @@ -498,7 +560,6 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { transformOrigin = 'right top'; transform = `translate(-100%, 0%) rotate(${rotation}deg) scale(${aspect})`; } - const usePath = this.layoutDoc[`_${this.fieldKey}_usePath`]; return ( <div @@ -510,7 +571,6 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { this._isHovering = false; })} key={this.layoutDoc[Id]} - ref={this.createDropTarget} onPointerDown={this.marqueeDown}> <div className="imageBox-fader" style={{ opacity: backAlpha }}> <img @@ -518,7 +578,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { ref={action((r: HTMLImageElement | null) => (this.imageRef = r))} key="paths" src={srcpath} - style={{ transform, transformOrigin, objectFit: 'fill', height: '100%' }} + style={{ transform, transformOrigin }} onError={action(e => { this._error = e.toString(); })} @@ -526,12 +586,11 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { width={nativeWidth} /> {fadepath === srcpath ? null : ( - <div className={`imageBox-fadeBlocker${(this._isHovering && usePath === 'alternate:hover') || usePath === 'alternate' ? '-hover' : ''}`} style={{ transition: StrCast(this.layoutDoc.viewTransition, 'opacity 1000ms') }}> + <div className={`imageBox-fadeBlocker${this.usingAlternate ? '-hover' : ''}`} style={{ transition: StrCast(this.layoutDoc.viewTransition, 'opacity 1000ms') }}> <img alt="" className="imageBox-fadeaway" key="fadeaway" src={fadepath} style={{ transform, transformOrigin }} draggable={false} width={nativeWidth} /> </div> )} </div> - {this.overlayImageIcon} </div> ); } @@ -567,123 +626,72 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { return ( <div className="imageBox-aiView"> <div className="imageBox-aiView-regenerate"> - <span className="imageBox-aiView-firefly">Firefly:</span> + <span className="imageBox-aiView-firefly" style={{ color: SnappingManager.userColor }}> + Firefly: + </span> <input + style={{ color: SnappingManager.userColor, background: SnappingManager.userBackgroundColor }} className="imageBox-aiView-input" aria-label="Edit instructions input" type="text" - value={this._regenInput} + value={this._regenInput || StrCast(this.Document.title)} onChange={action(e => this._canInteract && (this._regenInput = e.target.value))} placeholder={this._regenInput || StrCast(this.Document.title)} /> - <div className="imageBox-aiView-strength"> - <span className="imageBox-aiView-similarity">Similarity</span> - <Slider - className="imageBox-aiView-slider" - sx={{ - '& .MuiSlider-track': { color: SettingsManager.userVariantColor }, - '& .MuiSlider-rail': { color: SettingsManager.userBackgroundColor }, - '& .MuiSlider-thumb': { color: SettingsManager.userVariantColor, '&.Mui-focusVisible, &:hover, &.Mui-active': { boxShadow: `0px 0px 0px 8px${SettingsManager.userColor.slice(0, 7)}10` } }, - }} - min={0} - max={100} - step={1} - size="small" - value={this._fireflyRefStrength} - onChange={action((e, val) => this._canInteract && (this._fireflyRefStrength = val as number))} - valueLabelDisplay="auto" - /> - </div> <div className="imageBox-aiView-regenerate-createBtn"> <Button text="Create" - type={Type.SEC} + type={Type.TERT} + color={SnappingManager.userColor} + background={SnappingManager.userBackgroundColor} // style={{ alignSelf: 'flex-end' }} icon={this._regenerateLoading ? <ReactLoading type="spin" color={SettingsManager.userVariantColor} width={16} height={20} /> : <AiOutlineSend />} iconPlacement="right" onClick={action(async () => { this._regenerateLoading = true; if (this._fireflyRefStrength) { - DrawingFillHandler.drawingToImage(this.props.Document, this._fireflyRefStrength, this._regenInput || StrCast(this.Document.title), this.Document)?.then( - action(() => { - this._regenerateLoading = false; - }) - ); - } else + DrawingFillHandler.drawingToImage(this.props.Document, this._fireflyRefStrength, this._regenInput || StrCast(this.Document.title), this.Document)?.then(action(() => (this._regenerateLoading = false))); + } else { SmartDrawHandler.Instance.regenerate([this.Document], undefined, undefined, this._regenInput || StrCast(this.Document.title), true).then( action(newImgs => { - if (newImgs[0]) { - const url = newImgs[0].pathname; + const firstImg = newImgs[0]; + if (isFireflyImageData(firstImg)) { + const url = firstImg.pathname; const imgField = new ImageField(url); this._prevImgs.length === 0 && this._prevImgs.push({ prompt: StrCast(this.dataDoc.ai_firefly_prompt), seed: this.dataDoc.ai_firefly_seed as number, href: this.paths.lastElement(), pathname: field.url.pathname }); - this._prevImgs.unshift({ prompt: newImgs[0].prompt, seed: newImgs[0].seed, pathname: url }); + this._prevImgs.unshift({ prompt: firstImg.prompt, seed: firstImg.seed, pathname: url }); this.dataDoc.ai_firefly_history = JSON.stringify(this._prevImgs); - this.dataDoc.ai_firefly_prompt = newImgs[0].prompt; + this.dataDoc.ai_firefly_prompt = firstImg.prompt; this.dataDoc[this.fieldKey] = imgField; this._regenerateLoading = false; this._regenInput = ''; } }) ); + } })} /> </div> </div> - <div className="imageBox-aiView-options"> - <span className="imageBox-aiView-subtitle"> More: </span> - <Button - type={Type.TERT} - text="Get Text" - icon={<FontAwesomeIcon icon="font" />} - color={SettingsManager.userBackgroundColor} - iconPlacement="right" - onClick={() => { - Networking.PostToServer('/queryFireflyImageText', { - file: (file => { - const ext = extname(file); - return file.replace(ext, (this._error ? '_o' : this._curSuffix) + ext); - })(ImageCast(this.Document[Doc.LayoutFieldKey(this.Document)])?.url.href), - }).then(text => alert(text)); - }} - /> - <Button - type={Type.TERT} - text="Generative Fill" - icon={<FontAwesomeIcon icon="fill" />} - color={SettingsManager.userBackgroundColor} - iconPlacement="right" - onClick={action(() => { - ImageEditorData.Open = true; - ImageEditorData.Source = (field && this.choosePath(field.url)) || ''; - ImageEditorData.AddDoc = this._props.addDocument; - ImageEditorData.RootDoc = this.Document; - })} - /> - <Button - type={Type.TERT} - text="Expand" - icon={<FontAwesomeIcon icon="expand" />} - color={SettingsManager.userBackgroundColor} - iconPlacement="right" - onClick={() => { - Networking.PostToServer('/expandImage', { - prompt: 'sunny skies', - file: (file => { - const ext = extname(file); - return file.replace(ext, (this._error ? '_o' : this._curSuffix) + ext); - })(ImageCast(this.Document[Doc.LayoutFieldKey(this.Document)])?.url.href), - }).then((info: Upload.ImageInformation) => { - const img = Docs.Create.ImageDocument(info.accessPaths.agnostic.client, { title: 'expand:' + this.Document.title }); - DocUtils.assignImageInfo(info, img); - const genratedDocs = this.Document.generatedDocs - ? DocCast(this.Document.generatedDocs) - : Docs.Create.MasonryDocument([], { _width: 400, _height: 400, x: NumCast(this.Document.x) + NumCast(this.Document.width), y: NumCast(this.Document.y) }); - Doc.AddDocToList(genratedDocs, undefined, img); - this.Document[DocData].generatedDocs = genratedDocs; - if (!DocumentView.getFirstDocumentView(genratedDocs)) this._props.addDocTab(genratedDocs, OpenWhere.addRight); - }); + <div className="imageBox-aiView-strength"> + <span className="imageBox-aiView-similarity" style={{ color: SnappingManager.userColor }}> + Similarity + </span> + <Slider + className="imageBox-aiView-slider" + sx={{ + '& .MuiSlider-track': { color: SettingsManager.userColor }, + '& .MuiSlider-rail': { color: SettingsManager.userBackgroundColor }, + '& .MuiSlider-thumb': { color: SettingsManager.userColor, '&.Mui-focusVisible, &:hover, &.Mui-active': { boxShadow: `0px 0px 0px 8px${SettingsManager.userColor.slice(0, 7)}10` } }, }} + min={0} + max={100} + step={1} + size="small" + value={this._fireflyRefStrength} + onChange={action((e, val) => this._canInteract && (this._fireflyRefStrength = val as number))} + valueLabelDisplay="auto" /> </div> </div> @@ -726,25 +734,27 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { focus = (anchor: Doc, options: FocusViewOptions) => (anchor.type === DocumentType.CONFIG ? undefined : this._ffref.current?.focus(anchor, options)); renderedPixelDimensions = async () => { - const { nativeWidth: width, nativeHeight: height } = await Networking.PostToServer('/inspectImage', { source: this.paths[0] }); + const res = await Networking.PostToServer('/inspectImage', { source: this.paths[0] }); + const { nativeWidth: width, nativeHeight: height } = res as { nativeWidth: number; nativeHeight: number }; return { width, height }; }; savedAnnotations = () => this._savedAnnotations; - render() { TraceMobx(); const borderRad = this._props.styleProvider?.(this.layoutDoc, this._props, StyleProp.BorderRounding) as string; const borderRadius = borderRad?.includes('px') ? `${Number(borderRad.split('px')[0]) / (this._props.NativeDimScaling?.() || 1)}px` : borderRad; + const alts = DocListCast(this.dataDoc[this.fieldKey + '_alternates']); + const doc = this.usingAlternate ? (alts.lastElement() ?? this.Document) : this.Document; return ( <div className="imageBox" onContextMenu={this.specificContextMenu} - ref={this._mainCont} + ref={this.createDropTarget} onScroll={action(() => { if (!this._forcedScroll) { - if (this.layoutDoc._layout_scrollTop || this._mainCont.current?.scrollTop) { + if (this.layoutDoc._layout_scrollTop || this._mainCont?.scrollTop) { this._ignoreScroll = true; - this.layoutDoc._layout_scrollTop = this._mainCont.current?.scrollTop; + this.layoutDoc._layout_scrollTop = this._mainCont?.scrollTop; this._ignoreScroll = false; } } @@ -759,6 +769,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { <CollectionFreeFormView ref={this._ffref} {...this._props} + Document={doc} setContentViewBox={emptyFunction} NativeWidth={returnZero} NativeHeight={returnZero} @@ -786,8 +797,10 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { <ReactLoading type="spin" height={50} width={50} color={'blue'} /> </div> ) : null} + {this.regenerateImageIcon} + {this.overlayImageIcon} {this.annotationLayer} - {!this._mainCont.current || !this.DocumentView || !this._annotationLayer.current ? null : ( + {!this._mainCont || !this.DocumentView || !this._annotationLayer.current ? null : ( <MarqueeAnnotator Document={this.Document} ref={this.marqueeref} @@ -802,7 +815,7 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { savedAnnotations={this.savedAnnotations} selectionText={returnEmptyString} annotationLayer={this._annotationLayer.current} - marqueeContainer={this._mainCont.current} + marqueeContainer={this._mainCont} highlightDragSrcColor="" anchorMenuCrop={this.crop} // anchorMenuFlashcard={() => this.getImageDesc()} @@ -839,5 +852,5 @@ export class ImageBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { Docs.Prototypes.TemplateMap.set(DocumentType.IMG, { layout: { view: ImageBox, dataField: 'data' }, - options: { acl: '', freeform: '', systemIcon: 'BsFileEarmarkImageFill' }, + options: { acl: '', freeform: '', _layout_nativeDimEditable: true, systemIcon: 'BsFileEarmarkImageFill' }, }); diff --git a/src/client/views/nodes/KeyValueBox.scss b/src/client/views/nodes/KeyValueBox.scss index a44f614b2..441fceba4 100644 --- a/src/client/views/nodes/KeyValueBox.scss +++ b/src/client/views/nodes/KeyValueBox.scss @@ -1,11 +1,11 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .keyValueBox-cont { overflow-y: scroll; width: 100%; height: 100%; - background-color: $white; - border: 1px solid $medium-gray; - border-radius: $border-radius; + background-color: global.$white; + border: 1px solid global.$medium-gray; + border-radius: global.$border-radius; box-sizing: border-box; display: inline-block; cursor: default; @@ -56,8 +56,8 @@ $header-height: 30px; width: 100%; position: relative; display: inline-block; - background: $medium-gray; - color: $white; + background: global.$medium-gray; + color: global.$white; text-transform: uppercase; letter-spacing: 2px; font-size: 12px; @@ -66,7 +66,7 @@ $header-height: 30px; th { font-weight: normal; &:first-child { - border-right: 1px solid $white; + border-right: 1px solid global.$white; } } } @@ -76,9 +76,9 @@ $header-height: 30px; display: flex; width: 100%; height: $header-height; - background: $white; + background: global.$white; .formattedTextBox-cont { - background: $white; + background: global.$white; } } .keyValueBox-cont { @@ -116,8 +116,8 @@ $header-height: 30px; display: flex; width: 100%; height: 30px; - background: $light-gray; + background: global.$light-gray; .formattedTextBox-cont { - background: $light-gray; + background: global.$light-gray; } } diff --git a/src/client/views/nodes/KeyValuePair.scss b/src/client/views/nodes/KeyValuePair.scss index 46ea9c18e..913ab641c 100644 --- a/src/client/views/nodes/KeyValuePair.scss +++ b/src/client/views/nodes/KeyValuePair.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .keyValuePair-td-key { display: inline-block; diff --git a/src/client/views/nodes/LinkDescriptionPopup.scss b/src/client/views/nodes/LinkDescriptionPopup.scss index 104301656..b44b69af5 100644 --- a/src/client/views/nodes/LinkDescriptionPopup.scss +++ b/src/client/views/nodes/LinkDescriptionPopup.scss @@ -1,12 +1,12 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .linkDescriptionPopup { display: flex; flex-direction: row; justify-content: center; align-items: center; - border: 2px solid $medium-blue; - background-color: $white; + border: 2px solid global.$medium-blue; + background-color: global.$white; width: auto; position: absolute; @@ -35,7 +35,7 @@ white-space: nowrap; padding: 5px; vertical-align: middle; - background-color: $close-red; + background-color: global.$close-red; border-radius: 3px; color: black; } @@ -46,7 +46,7 @@ white-space: nowrap; padding: 5px; vertical-align: middle; - background-color: $light-blue; + background-color: global.$light-blue; border-radius: 3px; color: black; } diff --git a/src/client/views/nodes/MapBox/AnimationUtility.ts b/src/client/views/nodes/MapBox/AnimationUtility.ts index f4bae66bb..a3ac68b99 100644 --- a/src/client/views/nodes/MapBox/AnimationUtility.ts +++ b/src/client/views/nodes/MapBox/AnimationUtility.ts @@ -1,11 +1,12 @@ import * as turf from '@turf/turf'; -import { Position } from '@turf/turf'; import * as d3 from 'd3'; -import { Feature, GeoJsonProperties, Geometry } from 'geojson'; -import mapboxgl, { MercatorCoordinate } from 'mapbox-gl'; +import { Feature, GeoJsonProperties, Geometry, LineString } from 'geojson'; +import { MercatorCoordinate } from 'mapbox-gl'; import { action, computed, makeObservable, observable, runInAction } from 'mobx'; import { MapRef } from 'react-map-gl'; +export type Position = [number, number]; + export enum AnimationStatus { START = 'start', RESUME = 'resume', @@ -23,7 +24,7 @@ export class AnimationUtility { private ROUTE_COORDINATES: Position[] = []; @observable - private PATH?: turf.helpers.Feature<turf.helpers.LineString, turf.helpers.Properties> = undefined; + private PATH?: Feature<LineString> = undefined; // turf.helpers.Feature<turf.helpers.LineString, turf.helpers.Properties> = undefined; private PATH_DISTANCE: number = 0; private FLY_IN_START_PITCH = 40; @@ -65,7 +66,7 @@ export class AnimationUtility { const coords: mapboxgl.LngLatLike = [this.previousLngLat.lng, this.previousLngLat.lat]; // console.log('MAP REF: ', this.MAP_REF) // console.log("current elevation: ", this.MAP_REF?.queryTerrainElevation(coords)); - let altitude = this.MAP_REF ? this.MAP_REF.queryTerrainElevation(coords) ?? 0 : 0; + let altitude = this.MAP_REF ? (this.MAP_REF.queryTerrainElevation(coords) ?? 0) : 0; if (altitude === 0) { altitude += 50; } @@ -165,7 +166,8 @@ export class AnimationUtility { } @action - public setPath = (path: turf.helpers.Feature<turf.helpers.LineString, turf.helpers.Properties>) => { + public setPath = (path: Feature<LineString>) => { + // turf.helpers.Feature<turf.helpers.LineString, turf.helpers.Properties>) => { this.PATH = path; }; @@ -178,7 +180,7 @@ export class AnimationUtility { this.ROUTE_COORDINATES = routeCoordinates; this.PATH = turf.lineString(routeCoordinates); - this.PATH_DISTANCE = turf.lineDistance(this.PATH); + this.PATH_DISTANCE = turf.length(this.PATH as Feature<LineString>); this.terrainDisplayed = terrainDisplayed; const bearing = this.calculateBearing( @@ -232,7 +234,7 @@ export class AnimationUtility { if (!this.PATH) return; // calculate the distance along the path based on the animationPhase - const alongPath = turf.along(this.PATH, this.PATH_DISTANCE * animationPhase).geometry.coordinates; + const alongPath = turf.along(this.PATH as Feature<LineString>, this.PATH_DISTANCE * animationPhase).geometry.coordinates; const lngLat = { lng: alongPath[0], diff --git a/src/client/views/nodes/MapBox/MapAnchorMenu.tsx b/src/client/views/nodes/MapBox/MapAnchorMenu.tsx index cef202256..8079d96ea 100644 --- a/src/client/views/nodes/MapBox/MapAnchorMenu.tsx +++ b/src/client/views/nodes/MapBox/MapAnchorMenu.tsx @@ -1,9 +1,7 @@ -/* eslint-disable react/button-has-type */ import { IconLookup, faAdd, faArrowDown, faArrowLeft, faArrowsRotate, faBicycle, faCalendarDays, faCar, faDiamondTurnRight, faEdit, faPersonWalking, faRoute } from '@fortawesome/free-solid-svg-icons'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Autocomplete, Checkbox, FormControlLabel, TextField } from '@mui/material'; import { IconButton } from '@dash/components'; -import { Position } from 'geojson'; import { IReactionDisposer, ObservableMap, action, makeObservable, observable, reaction, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import * as React from 'react'; @@ -19,6 +17,8 @@ import { DocumentView } from '../DocumentView'; import './MapAnchorMenu.scss'; import { MapboxApiUtility, TransportationType } from './MapboxApiUtility'; import { MarkerIcons } from './MarkerIcons'; +import { LngLatLike } from 'mapbox-gl'; +import { Position } from './AnimationUtility'; // import { GPTPopup, GPTPopupMode } from './../../GPTPopup/GPTPopup'; type MapAnchorMenuType = 'standard' | 'routeCreation' | 'calendar' | 'customize' | 'route'; @@ -44,10 +44,9 @@ export class MapAnchorMenu extends AntimodeMenu<AntimodeMenuProps> { // public MakeTargetToggle: () => void = unimplementedFunction; // public ShowTargetTrail: () => void = unimplementedFunction; public IsTargetToggler: () => boolean = returnFalse; - - public DisplayRoute: (routeInfoMap: Record<TransportationType, any> | undefined, type: TransportationType) => void = unimplementedFunction; - public AddNewRouteToMap: (coordinates: Position[], origin: string, destination: any, createPinForDestination: boolean) => void = unimplementedFunction; - public CreatePin: (feature: any) => void = unimplementedFunction; + public DisplayRoute: (routeInfoMap: Record<TransportationType, { coordinates: Position[] }> | undefined, type: TransportationType) => void = unimplementedFunction; + public AddNewRouteToMap: (coordinates: Position[], origin: string, destination: { place_name: string; center: number[] }, createPinForDestination: boolean) => void = unimplementedFunction; + public CreatePin: (feature: { place_name: string; center: LngLatLike; properties: { wikiData: unknown } }) => void = unimplementedFunction; public UpdateMarkerColor: (color: string) => void = unimplementedFunction; public UpdateMarkerIcon: (iconKey: string) => void = unimplementedFunction; @@ -212,19 +211,19 @@ export class MapAnchorMenu extends AntimodeMenu<AntimodeMenuProps> { }; @observable - destinationFeatures: any[] = []; + destinationFeatures: { place_name: string; center: number[] }[] = []; @observable destinationSelected: boolean = false; @observable - selectedDestinationFeature: any = undefined; + selectedDestinationFeature?: { place_name: string; center: number[] } = undefined; @observable createPinForDestination: boolean = true; @observable - currentRouteInfoMap: Record<TransportationType, any> | undefined = undefined; + currentRouteInfoMap: Record<TransportationType, { coordinates: Position[]; duration: number; distance: number }> | undefined = undefined; @observable selectedTransportationType: TransportationType = 'driving'; @@ -238,7 +237,7 @@ export class MapAnchorMenu extends AntimodeMenu<AntimodeMenuProps> { }; @action - handleSelectedDestinationFeature = (destinationFeature: any) => { + handleSelectedDestinationFeature = (destinationFeature?: { place_name: string; center: number[] }) => { this.selectedDestinationFeature = destinationFeature; }; @@ -258,7 +257,7 @@ export class MapAnchorMenu extends AntimodeMenu<AntimodeMenuProps> { } }; - getRoutes = async (destinationFeature: any) => { + getRoutes = async (destinationFeature: { center: number[] }) => { const currentPinLong: number = NumCast(this.pinDoc?.longitude); const currentPinLat: number = NumCast(this.pinDoc?.latitude); @@ -280,8 +279,6 @@ export class MapAnchorMenu extends AntimodeMenu<AntimodeMenuProps> { HandleAddRouteClick = () => { if (this.currentRouteInfoMap && this.selectedTransportationType && this.selectedDestinationFeature) { const { coordinates } = this.currentRouteInfoMap[this.selectedTransportationType]; - console.log(coordinates); - console.log(this.selectedDestinationFeature); this.AddNewRouteToMap(coordinates, this.title ?? '', this.selectedDestinationFeature, this.createPinForDestination); } }; @@ -441,27 +438,26 @@ export class MapAnchorMenu extends AntimodeMenu<AntimodeMenuProps> { <Autocomplete fullWidth id="route-destination-searcher" - onInputChange={(e: any, searchText: any) => this.handleDestinationSearchChange(searchText)} - onChange={(e: any, feature: any, reason: any) => { + onInputChange={(e, searchText) => this.handleDestinationSearchChange(searchText)} + onChange={(e, feature: unknown, reason: unknown) => { if (reason === 'clear') { this.handleSelectedDestinationFeature(undefined); } else if (reason === 'selectOption') { - this.handleSelectedDestinationFeature(feature); + this.handleSelectedDestinationFeature(feature as { place_name: string; center: number[] }); } }} options={this.destinationFeatures.filter(feature => feature.place_name).map(feature => feature)} - getOptionLabel={(feature: any) => feature.place_name} - // eslint-disable-next-line react/jsx-props-no-spreading - renderInput={(params: any) => <TextField {...params} placeholder="Enter a destination" />} + getOptionLabel={(feature: unknown) => (feature as { place_name: string }).place_name} + renderInput={params => <TextField {...params} placeholder="Enter a destination" />} /> {!this.selectedDestinationFeature ? null - : !this.allMapPinDocs.some(pinDoc => pinDoc.title === this.selectedDestinationFeature.place_name) && ( + : !this.allMapPinDocs.some(pinDoc => pinDoc.title === this.selectedDestinationFeature?.place_name) && ( <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: '5px' }}> <FormControlLabel label="Create pin for destination?" control={<Checkbox color="success" checked={this.createPinForDestination} onChange={this.toggleCreatePinForDestinationCheckbox} />} /> </div> )} - <button id="get-routes-button" disabled={!this.selectedDestinationFeature} onClick={() => this.getRoutes(this.selectedDestinationFeature)}> + <button id="get-routes-button" disabled={!this.selectedDestinationFeature} onClick={() => this.selectedDestinationFeature && this.getRoutes(this.selectedDestinationFeature)}> Get routes </button> diff --git a/src/client/views/nodes/MapBox/MapBox.scss b/src/client/views/nodes/MapBox/MapBox.scss index 25b4587a5..fdd8a29d7 100644 --- a/src/client/views/nodes/MapBox/MapBox.scss +++ b/src/client/views/nodes/MapBox/MapBox.scss @@ -1,4 +1,6 @@ -@import '../../global/globalCssVariables.module.scss'; +@use 'sass:color'; +@use '../../global/globalCssVariables.module.scss' as global; + .mapBox { width: 100%; height: 100%; @@ -25,14 +27,6 @@ gap: 5px; align-items: center; width: calc(100% - 40px); - - // .editableText-container { - // width: 100%; - // font-size: 16px !important; - // } - // input { - // width: 100%; - // } } .mapbox-settings-panel { @@ -83,7 +77,7 @@ width: 100%; padding: 10px; &:hover { - background-color: lighten(rgb(187, 187, 187), 10%); + background-color: color.adjust(rgb(187, 187, 187), $lightness: 10%); } } } @@ -167,7 +161,7 @@ pointer-events: all; z-index: 1; // so it appears on top of the document's title, if shown - box-shadow: $standard-box-shadow; + box-shadow: global.$standard-box-shadow; transition: 0.2s; &:hover { diff --git a/src/client/views/nodes/MapBox/MapBox.tsx b/src/client/views/nodes/MapBox/MapBox.tsx index c4bb7c47d..541b41bf7 100644 --- a/src/client/views/nodes/MapBox/MapBox.tsx +++ b/src/client/views/nodes/MapBox/MapBox.tsx @@ -4,14 +4,13 @@ import { Checkbox, FormControlLabel, TextField } from '@mui/material'; import * as turf from '@turf/turf'; import { IconButton, Size, Type } from '@dash/components'; import * as d3 from 'd3'; -import { Feature, FeatureCollection, GeoJsonProperties, Geometry, LineString, Position } from 'geojson'; -import mapboxgl, { LngLatBoundsLike, MapLayerMouseEvent } from 'mapbox-gl'; +import { Feature, FeatureCollection, GeoJsonProperties, Geometry, LineString } from 'geojson'; +import { LngLatBoundsLike, LngLatLike, MapLayerMouseEvent } from 'mapbox-gl'; import { IReactionDisposer, ObservableMap, action, autorun, computed, makeObservable, observable, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import * as React from 'react'; import { CirclePicker, ColorResult } from 'react-color'; import { Layer, MapProvider, MapRef, Map as MapboxMap, Marker, Source, ViewState, ViewStateChangeEvent } from 'react-map-gl'; -import { MarkerEvent } from 'react-map-gl/dist/esm/types'; import { ClientUtils, setupMoveUpEvents } from '../../../../ClientUtils'; import { emptyFunction } from '../../../../Utils'; import { Doc, DocListCast, Field, LinkedTo, Opt } from '../../../../fields/Doc'; @@ -30,11 +29,12 @@ import { DocumentView } from '../DocumentView'; import { FieldView, FieldViewProps } from '../FieldView'; import { FocusViewOptions } from '../FocusViewOptions'; import { fastSpeedIcon, mediumSpeedIcon, slowSpeedIcon } from './AnimationSpeedIcons'; -import { AnimationSpeed, AnimationStatus, AnimationUtility } from './AnimationUtility'; +import { AnimationSpeed, AnimationStatus, AnimationUtility, Position } from './AnimationUtility'; import { MapAnchorMenu } from './MapAnchorMenu'; import './MapBox.scss'; import { MapboxApiUtility, TransportationType } from './MapboxApiUtility'; import { MarkerIcons } from './MarkerIcons'; +import { RichTextField } from '../../../../fields/RichTextField'; // import { GeocoderControl } from './GeocoderControl'; // amongus @@ -76,7 +76,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { makeObservable(this); } - @observable _featuresFromGeocodeResults: any[] = []; + @observable _featuresFromGeocodeResults: { place_name: string; center: LngLatLike | undefined }[] = []; @observable _savedAnnotations = new ObservableMap<number, HTMLDivElement[]>(); @observable _selectedPinOrRoute: Doc | undefined = undefined; // The pin that is selected @observable _mapReady = false; @@ -100,7 +100,8 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { geometry: { type: 'LineString', coordinates: [] }, }; - @observable path: turf.helpers.Feature<turf.helpers.LineString, turf.helpers.Properties> = { + @observable path: Feature<LineString> = { + // turf.helpers.Feature<turf.helpers.LineString, turf.helpers.Properties> = { type: 'Feature', geometry: { type: 'LineString', coordinates: [] }, properties: {}, @@ -168,7 +169,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { autorun(() => { const animationUtil = this._animationUtility; const concattedCoordinates = geometry.coordinates.concat(originalCoordinates.slice(endIndex)); - const newFeature: Feature<LineString, turf.Properties> = { + const newFeature: Feature<LineString> = { type: 'Feature', properties: {}, geometry: { @@ -445,7 +446,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { /// this should use SELECTED pushpin for lat/long if there is a selection, otherwise CENTER const anchor = Docs.Create.ConfigDocument({ title: 'MapAnchor:' + this.Document.title, - text: (StrCast(this._selectedPinOrRoute?.map) || StrCast(this.Document.map) || 'map location') as any, + text: (StrCast(this._selectedPinOrRoute?.map) || StrCast(this.Document.map) || 'map location') as unknown as RichTextField, // strings are allowed for text config_latitude: NumCast((existingPin ?? this._selectedPinOrRoute)?.latitude ?? this.dataDoc.latitude), config_longitude: NumCast((existingPin ?? this._selectedPinOrRoute)?.longitude ?? this.dataDoc.longitude), config_map_zoom: NumCast(this.dataDoc.map_zoom), @@ -464,7 +465,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { return this.Document; }; - map_docToPinMap = new Map<Doc, any>(); + map_docToPinMap = new Map<Doc, unknown>(); map_pinHighlighted = new Map<Doc, boolean>(); /* @@ -541,15 +542,17 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { * Creates Pushpin doc and adds it to the list of annotations */ @action - createPushpin = undoable((latitude: number, longitude: number, location?: string, wikiData?: string) => { + createPushpin = undoable((center: LngLatLike, location?: string, wikiData?: string) => { + const lat = 'lat' in center ? center.lat : center[0]; + const lon = 'lng' in center ? center.lng : 'lon' in center ? center.lon : center[1]; // Stores the pushpin as a MapMarkerDocument const pushpin = Docs.Create.PushpinDocument( - NumCast(latitude), - NumCast(longitude), + lat, + lon, false, [], { - title: location ?? `lat=${NumCast(latitude)},lng=${NumCast(longitude)}`, + title: location ?? `lat=${lat},lng=${lon}`, map: location, description: '', wikiData: wikiData, @@ -567,7 +570,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { }, 'createpin'); @action - createMapRoute = undoable((coordinates: Position[], originName: string, destination: any, createPinForDestination: boolean) => { + createMapRoute = undoable((coordinates: Position[], originName: string, destination: { place_name: string; center: number[] }, createPinForDestination: boolean) => { if (originName !== destination.place_name) { const mapRoute = Docs.Create.MapRouteDocument(false, [], { title: `${originName} --> ${destination.place_name}`, routeCoordinates: JSON.stringify(coordinates) }); this.addDocument(mapRoute, this.annotationKey); @@ -586,23 +589,21 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { }, 'createmaproute'); @action - searchbarKeyDown = (e: any) => { + searchbarKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && this._featuresFromGeocodeResults) { - const center = this._featuresFromGeocodeResults[0]?.center; + const center = this._featuresFromGeocodeResults[0]; this._featuresFromGeocodeResults = []; - setTimeout(() => center && this._mapRef.current?.flyTo({ center })); + setTimeout(() => center && this._mapRef.current?.flyTo(center)); } }; @action - addMarkerForFeature = (feature: any) => { + addMarkerForFeature = (feature: { place_name: string; center: LngLatLike | undefined; properties?: { wikiData: unknown } }) => { const location = feature.place_name; if (feature.center) { - const longitude = feature.center[0]; - const latitude = feature.center[1]; const wikiData = feature.properties?.wikiData; - this.createPushpin(latitude, longitude, location, wikiData); + this.createPushpin(feature.center, location, wikiData); if (this._mapRef.current) { this._mapRef.current.flyTo({ @@ -727,7 +728,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { }; @action - handleMarkerClick = (e: MarkerEvent<mapboxgl.Marker, MouseEvent>, pinDoc: Doc) => { + handleMarkerClick = (clientX: number, clientY: number, pinDoc: Doc) => { this._featuresFromGeocodeResults = []; this.deselectPinOrRoute(); // TODO: check this method this._selectedPinOrRoute = pinDoc; @@ -758,7 +759,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { // MapAnchorMenu.Instance.jumpTo(NumCast(pinDoc.longitude), NumCast(pinDoc.latitude)-3, true); - MapAnchorMenu.Instance.jumpTo(e.originalEvent.clientX, e.originalEvent.clientY, true); + MapAnchorMenu.Instance.jumpTo(clientX, clientY, true); document.addEventListener('pointerdown', this.tryHideMapAnchorMenu, true); @@ -768,7 +769,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { }; @action - displayRoute = (routeInfoMap: Record<TransportationType, any> | undefined, type: TransportationType) => { + displayRoute = (routeInfoMap: Record<TransportationType, { coordinates: Position[] }> | undefined, type: TransportationType) => { if (routeInfoMap) { const newTempRouteSource: FeatureCollection = { type: 'FeatureCollection', @@ -1052,7 +1053,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { <div id="divider">|</div> <div style={{ display: 'flex', alignItems: 'center' }}> <div>Select Line Color: </div> - <CirclePicker circleSize={12} circleSpacing={5} width="100%" colors={['#ffff00', '#03a9f4', '#ff0000', '#ff5722', '#000000', '#673ab7']} onChange={(color: any) => this.setAnimationLineColor(color)} /> + <CirclePicker circleSize={12} circleSpacing={5} width="100%" colors={['#ffff00', '#03a9f4', '#ff0000', '#ff5722', '#000000', '#673ab7']} onChange={color => this.setAnimationLineColor(color)} /> </div> </div> </> @@ -1147,7 +1148,6 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { return MarkerIcons.getFontAwesomeIcon(markerType, '2x', markerColor) ?? null; }; - _textRef = React.createRef<any>(); render() { const scale = this._props.NativeDimScaling?.() || 1; const parscale = scale === 1 ? 1 : (this.ScreenToLocalBoxXf().Scale ?? 1); @@ -1161,7 +1161,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { style={{ transformOrigin: 'top left', transform: `scale(${scale})`, width: `calc(100% - ${this.sidebarWidthPercent})`, pointerEvents: this.pointerEvents() }}> {!this._routeToAnimate && ( <div className="mapBox-searchbar" style={{ width: `${100 / scale}%`, zIndex: 1, position: 'relative', background: 'lightGray' }}> - <TextField ref={this._textRef} fullWidth placeholder="Enter a location" onKeyDown={this.searchbarKeyDown} onChange={(e: any) => this.handleSearchChange(e.target.value)} /> + <TextField fullWidth placeholder="Enter a location" onKeyDown={this.searchbarKeyDown} onChange={e => this.handleSearchChange(e.target.value)} /> <IconButton icon={<FontAwesomeIcon icon={faGear as IconLookup} size="1x" />} type={Type.TERT} onClick={() => this.toggleSettings()} /> <div style={{ opacity: 0 }}> <IconButton icon={<FontAwesomeIcon icon={faGear as IconLookup} size="1x" />} type={Type.TERT} onClick={() => this.toggleSettings()} /> @@ -1217,7 +1217,6 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { .filter(feature => feature.place_name) .map((feature, idx) => ( <div - // eslint-disable-next-line react/no-array-index-key key={idx} className="search-result-container" onClick={() => { @@ -1321,8 +1320,7 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { this._animationPhase === 0 && this.allPushpins // .filter(anno => !anno.layout_unrendered) .map((pushpin, idx) => ( - // eslint-disable-next-line react/no-array-index-key - <Marker key={idx} longitude={NumCast(pushpin.longitude)} latitude={NumCast(pushpin.latitude)} anchor="bottom" onClick={(e: MarkerEvent<mapboxgl.Marker, MouseEvent>) => this.handleMarkerClick(e, pushpin)}> + <Marker key={idx} longitude={NumCast(pushpin.longitude)} latitude={NumCast(pushpin.latitude)} anchor="bottom" onClick={e => this.handleMarkerClick(e.originalEvent.clientX, e.originalEvent.clientY, pushpin)}> {this.getMarkerIcon(pushpin)} </Marker> ))} @@ -1336,7 +1334,6 @@ export class MapBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { <div className="mapBox-sidebar" style={{ width: `${this.sidebarWidthPercent}`, backgroundColor: `${this.sidebarColor}` }}> <SidebarAnnos ref={this._sidebarRef} - // eslint-disable-next-line react/jsx-props-no-spreading {...this._props} fieldKey={this.fieldKey} Document={this.Document} diff --git a/src/client/views/nodes/PDFBox.scss b/src/client/views/nodes/PDFBox.scss index f6908d5fd..f2160feb7 100644 --- a/src/client/views/nodes/PDFBox.scss +++ b/src/client/views/nodes/PDFBox.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .pdfBox, .pdfBox-interactive { @@ -22,11 +22,11 @@ // glr: This should really be the same component as text and PDFs .pdfBox-sidebarBtn { - background: $black; + background: global.$black; height: 25px; width: 25px; right: 5px; - color: $white; + color: global.$white; display: flex; position: absolute; align-items: center; @@ -35,7 +35,7 @@ pointer-events: all; z-index: 1; // so it appears on top of the document's title, if shown - box-shadow: $standard-box-shadow; + box-shadow: global.$standard-box-shadow; transition: 0.2s; &:hover { diff --git a/src/client/views/nodes/RecordingBox/RecordingView.tsx b/src/client/views/nodes/RecordingBox/RecordingView.tsx index 37ffca2d6..e7a6193d4 100644 --- a/src/client/views/nodes/RecordingBox/RecordingView.tsx +++ b/src/client/views/nodes/RecordingBox/RecordingView.tsx @@ -1,4 +1,3 @@ -/* eslint-disable react/button-has-type */ import * as React from 'react'; import { useEffect, useRef, useState } from 'react'; import { IconContext } from 'react-icons'; @@ -72,7 +71,7 @@ export function RecordingView(props: IRecordingViewProps) { const serverPaths: string[] = (await Networking.UploadFilesToServer(videoFiles.map(file => ({ file })))).map(res => (res.result instanceof Error ? '' : res.result.accessPaths.agnostic.server)); // concat the segments together using post call - const result: Upload.AccessPathInfo | Error = await Networking.PostToServer('/concatVideos', serverPaths); + const result = (await Networking.PostToServer('/concatVideos', serverPaths)) as Upload.AccessPathInfo | Error; !(result instanceof Error) ? props.setResult(result, concatPres || undefined) : console.error('video conversion failed'); })(); } diff --git a/src/client/views/nodes/VideoBox.scss b/src/client/views/nodes/VideoBox.scss index 460155446..b5405f0fb 100644 --- a/src/client/views/nodes/VideoBox.scss +++ b/src/client/views/nodes/VideoBox.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .mini-viewer { cursor: grab; @@ -22,7 +22,7 @@ height: 100%; border-radius: inherit; opacity: 0.99; // hack! overcomes some kind of Chrome weirdness where buttons (e.g., snapshot) disappear at some point as the video is resized larger - background: $dark-gray; + background: global.$dark-gray; } .inkingCanvas-paths-markers { @@ -93,7 +93,7 @@ align-items: center; justify-content: center; display: flex; - background-color: $dark-gray; + background-color: global.$dark-gray; color: white; border-radius: 100px; height: 40px; @@ -128,13 +128,13 @@ width: 25px; height: 25px; border-radius: 50%; - background: $dark-gray; + background: global.$dark-gray; display: flex; align-items: center; justify-content: center; &:hover { - background: $black; + background: global.$black; } svg { @@ -157,7 +157,7 @@ cursor: pointer; &:hover { - background-color: $medium-gray; + background-color: global.$medium-gray; } } @@ -198,7 +198,7 @@ input[type='range']::-webkit-slider-runnable-track { height: 10px; cursor: pointer; box-shadow: 0; - background: $light-gray; + background: global.$light-gray; border-radius: 10px; } @@ -208,7 +208,7 @@ input[type='range']::-webkit-slider-thumb { height: 12px; width: 12px; border-radius: 10px; - background: $medium-blue; + background: global.$medium-blue; cursor: pointer; -webkit-appearance: none; margin-top: -1px; diff --git a/src/client/views/nodes/WebBox.scss b/src/client/views/nodes/WebBox.scss index a1686adaf..05d5babf9 100644 --- a/src/client/views/nodes/WebBox.scss +++ b/src/client/views/nodes/WebBox.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .webBox { height: 100%; @@ -120,7 +120,7 @@ pointer-events: all; z-index: 1; // so it appears on top of the document's title, if shown - box-shadow: $standard-box-shadow; + box-shadow: global.$standard-box-shadow; transition: 0.2s; &:hover { diff --git a/src/client/views/nodes/WebBox.tsx b/src/client/views/nodes/WebBox.tsx index 6026d9ca7..e7a10cc29 100644 --- a/src/client/views/nodes/WebBox.tsx +++ b/src/client/views/nodes/WebBox.tsx @@ -383,7 +383,7 @@ export class WebBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { this._textAnnotationCreator = () => this.createTextAnnotation(sel, !sel.isCollapsed ? sel.getRangeAt(0) : undefined); AnchorMenu.Instance.jumpTo(e.clientX * scale + mainContBounds.translateX, e.clientY * scale + mainContBounds.translateY - NumCast(this.layoutDoc._layout_scrollTop) * scale); // Changing which document to add the annotation to (the currently selected WebBox) - GPTPopup.Instance.setSidebarId(`${this._props.fieldKey}_${this._urlHash ? this._urlHash + '_' : ''}sidebar`); + GPTPopup.Instance.setSidebarFieldKey(`${this._props.fieldKey}_${this._urlHash ? this._urlHash + '_' : ''}sidebar`); GPTPopup.Instance.addDoc = this.sidebarAddDocument; } } else { @@ -446,7 +446,7 @@ export class WebBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { this._textAnnotationCreator = () => this.createTextAnnotation(sel, selRange); (!sel.isCollapsed || this.marqueeing) && AnchorMenu.Instance.jumpTo(e.clientX, e.clientY); // Changing which document to add the annotation to (the currently selected WebBox) - GPTPopup.Instance.setSidebarId(`${this._props.fieldKey}_${this._urlHash ? this._urlHash + '_' : ''}sidebar`); + GPTPopup.Instance.setSidebarFieldKey(`${this._props.fieldKey}_${this._urlHash ? this._urlHash + '_' : ''}sidebar`); GPTPopup.Instance.addDoc = this.sidebarAddDocument; } }; diff --git a/src/client/views/nodes/calendarBox/CalendarBox.tsx b/src/client/views/nodes/calendarBox/CalendarBox.tsx index d38cb5423..009eb82cd 100644 --- a/src/client/views/nodes/calendarBox/CalendarBox.tsx +++ b/src/client/views/nodes/calendarBox/CalendarBox.tsx @@ -1,4 +1,4 @@ -import { Calendar, EventClickArg, EventSourceInput } from '@fullcalendar/core'; +import { Calendar, EventClickArg, EventDropArg, EventSourceInput } from '@fullcalendar/core'; import dayGridPlugin from '@fullcalendar/daygrid'; import multiMonthPlugin from '@fullcalendar/multimonth'; import timeGrid from '@fullcalendar/timegrid'; @@ -17,6 +17,7 @@ import { DocumentView } from '../DocumentView'; import { OpenWhere } from '../OpenWhere'; import { DragManager } from '../../../util/DragManager'; import { DocData } from '../../../../fields/DocSymbols'; +import { ContextMenu } from '../../ContextMenu'; type CalendarView = 'multiMonth' | 'dayGridMonth' | 'timeGridWeek' | 'timeGridDay'; @@ -104,32 +105,44 @@ export class CalendarBox extends CollectionSubView() { } // TODO: Return a different color based on the event type - eventToColor(event: Doc): string { + eventToColor = (event: Doc): string => { return 'red'; - } + }; - internalDocDrop(e: Event, de: DragManager.DropEvent, docDragData: DragManager.DocumentDragData) { + internalDocDrop = (e: Event, de: DragManager.DropEvent, docDragData: DragManager.DocumentDragData) => { if (!super.onInternalDrop(e, de)) return false; de.complete.docDragData?.droppedDocuments.forEach(doc => { const today = new Date().toISOString(); if (!doc.date_range) doc[DocData].date_range = `${today}|${today}`; }); return true; - } + }; onInternalDrop = (e: Event, de: DragManager.DropEvent): boolean => { if (de.complete.docDragData?.droppedDocuments.length) return this.internalDocDrop(e, de, de.complete.docDragData); return false; }; + handleEventDrop = (arg: EventDropArg) => { + const doc = DocServer.GetCachedRefField(arg.event._def.groupId ?? ''); + doc && arg.event.start && (doc.date_range = arg.event.start?.toString() + '|' + (arg.event.end ?? arg.event.start).toString()); + }; + handleEventClick = (arg: EventClickArg) => { const doc = DocServer.GetCachedRefField(arg.event._def.groupId ?? ''); - DocumentView.DeselectAll(); if (doc) { DocumentView.showDocument(doc, { openLocation: OpenWhere.lightboxAlways }); arg.jsEvent.stopPropagation(); } }; + handleEventContextMenu = (pageX: number, pageY: number, docid: string) => { + const doc = DocServer.GetCachedRefField(docid ?? ''); + if (doc) { + const cm = ContextMenu.Instance; + cm.addItem({ description: 'Show Metadata', event: () => this._props.addDocTab(doc, OpenWhere.addRightKeyvalue), icon: 'table-columns' }); + cm.displayMenu(pageX - 15, pageY - 15, undefined, undefined); + } + }; // https://fullcalendar.io renderCalendar = () => { @@ -157,6 +170,25 @@ export class CalendarBox extends CollectionSubView() { aspectRatio: NumCast(this.Document.width) / NumCast(this.Document.height), events: this.calendarEvents, eventClick: this.handleEventClick, + eventDrop: this.handleEventDrop, + eventDidMount: arg => { + arg.el.addEventListener('pointerdown', ev => { + ev.button && ev.stopPropagation(); + }); + if (navigator.userAgent.includes('Macintosh')) { + arg.el.addEventListener('pointerup', ev => { + ev.button && ev.stopPropagation(); + ev.button && this.handleEventContextMenu(ev.pageX, ev.pageY, arg.event._def.groupId); + }); + } + arg.el.addEventListener('contextmenu', ev => { + if (!navigator.userAgent.includes('Macintosh')) { + this.handleEventContextMenu(ev.pageX, ev.pageY, arg.event._def.groupId); + } + ev.stopPropagation(); + ev.preventDefault(); + }); + }, })); cal?.render(); setTimeout(() => cal?.view.calendar.select(this.dateSelect.start, this.dateSelect.end)); diff --git a/src/client/views/nodes/chatbot/agentsystem/Agent.ts b/src/client/views/nodes/chatbot/agentsystem/Agent.ts index b2b0c9aea..e93fb87db 100644 --- a/src/client/views/nodes/chatbot/agentsystem/Agent.ts +++ b/src/client/views/nodes/chatbot/agentsystem/Agent.ts @@ -22,6 +22,8 @@ import { ChatCompletionMessageParam } from 'openai/resources'; import { Doc } from '../../../../../fields/Doc'; import { parsedDoc } from '../chatboxcomponents/ChatBox'; import { WebsiteInfoScraperTool } from '../tools/WebsiteInfoScraperTool'; +import { Upload } from '../../../../../server/SharedMediaTypes'; +import { RAGTool } from '../tools/RAGTool'; //import { CreateTextDocTool } from '../tools/CreateTextDocumentTool'; dotenv.config(); @@ -61,7 +63,7 @@ export class Agent { history: () => string, csvData: () => { filename: string; id: string; text: string }[], addLinkedUrlDoc: (url: string, id: string) => void, - createImage: (result: any, options: DocumentOptions) => void, + createImage: (result: Upload.FileInformation & Upload.InspectionResults, options: DocumentOptions) => void, addLinkedDoc: (doc: parsedDoc) => Doc | undefined, // eslint-disable-next-line @typescript-eslint/no-unused-vars createCSVInDash: (url: string, title: string, id: string, data: string) => void @@ -76,7 +78,7 @@ export class Agent { // Define available tools for the assistant this.tools = { calculate: new CalculateTool(), - // rag: new RAGTool(this.vectorstore), + rag: new RAGTool(this.vectorstore), dataAnalysis: new DataAnalysisTool(csvData), websiteInfoScraper: new WebsiteInfoScraperTool(addLinkedUrlDoc), searchTool: new SearchTool(addLinkedUrlDoc), diff --git a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.scss b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.scss index 9cf760a12..3d27fa887 100644 --- a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.scss +++ b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.scss @@ -1,3 +1,4 @@ +@use 'sass:color'; @import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600&display=swap'); $primary-color: #3f51b5; @@ -68,7 +69,7 @@ $transition: all 0.2s ease-in-out; &:focus { outline: none; border-color: $primary-color; - box-shadow: 0 0 0 2px rgba($primary-color, 0.2); + box-shadow: 0 0 0 2px color.adjust($primary-color, $alpha: -0.8); } &:disabled { @@ -92,11 +93,11 @@ $transition: all 0.2s ease-in-out; transition: $transition; &:hover { - background-color: darken($primary-color, 10%); + background-color: color.adjust($primary-color, $lightness: -10%); } &:disabled { - background-color: lighten($primary-color, 20%); + background-color: color.adjust($primary-color, $lightness: 20%); cursor: not-allowed; } @@ -178,7 +179,7 @@ $transition: all 0.2s ease-in-out; margin-bottom: 16px; &:hover { - background-color: rgba($primary-color, 0.1); + background-color: color.adjust($primary-color, $alpha: -0.9); } } @@ -220,7 +221,7 @@ $transition: all 0.2s ease-in-out; transition: $transition; &:hover { - background-color: rgba($primary-color, 0.2); + background-color: color.adjust($primary-color, $alpha: -0.8); color: #fff; } } diff --git a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx index 16da360fc..6e9307d37 100644 --- a/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx +++ b/src/client/views/nodes/chatbot/chatboxcomponents/ChatBox.tsx @@ -42,6 +42,7 @@ import './ChatBox.scss'; import MessageComponentBox from './MessageComponent'; import { ProgressBar } from './ProgressBar'; import { OpenWhere } from '../../OpenWhere'; +import { Upload } from '../../../../../server/SharedMediaTypes'; dotenv.config(); @@ -412,7 +413,7 @@ export class ChatBox extends ViewBoxAnnotatableComponent<FieldViewProps>() { }); @action - createImageInDash = async (result: any, options: DocumentOptions) => { + createImageInDash = async (result: Upload.FileInformation & Upload.InspectionResults, options: DocumentOptions) => { const newImgSrc = result.accessPaths.agnostic.client.indexOf('dashblobstore') === -1 // ? ClientUtils.prepend(result.accessPaths.agnostic.client) diff --git a/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts b/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts index ef4bbbc47..754d230c8 100644 --- a/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts +++ b/src/client/views/nodes/chatbot/tools/CreateAnyDocTool.ts @@ -13,63 +13,63 @@ const standardOptions = ['title', 'backgroundColor']; * Description of document options and data field for each type. */ const documentTypesInfo: { [key in supportedDocTypes]: { options: string[]; dataDescription: string } } = { - [supportedDocumentTypes.flashcard]: { + [supportedDocTypes.flashcard]: { options: [...standardOptions, 'fontColor', 'text_align'], dataDescription: 'an array of two strings. the first string contains a question, and the second string contains an answer', }, - [supportedDocumentTypes.text]: { + [supportedDocTypes.text]: { options: [...standardOptions, 'fontColor', 'text_align'], dataDescription: 'The text content of the document.', }, - [supportedDocumentTypes.html]: { + [supportedDocTypes.html]: { options: [], dataDescription: 'The HTML-formatted text content of the document.', }, - [supportedDocumentTypes.equation]: { + [supportedDocTypes.equation]: { options: [...standardOptions, 'fontColor'], dataDescription: 'The equation content as a string.', }, - [supportedDocumentTypes.functionplot]: { + [supportedDocTypes.functionplot]: { options: [...standardOptions, 'function_definition'], dataDescription: 'The function definition(s) for plotting. Provide as a string or array of function definitions.', }, - [supportedDocumentTypes.dataviz]: { + [supportedDocTypes.dataviz]: { options: [...standardOptions, 'chartType'], dataDescription: 'A string of comma-separated values representing the CSV data.', }, - [supportedDocumentTypes.notetaking]: { + [supportedDocTypes.notetaking]: { options: standardOptions, dataDescription: 'The initial content or structure for note-taking.', }, - [supportedDocumentTypes.rtf]: { + [supportedDocTypes.rtf]: { options: standardOptions, dataDescription: 'The rich text content in RTF format.', }, - [supportedDocumentTypes.image]: { + [supportedDocTypes.image]: { options: standardOptions, dataDescription: 'The image content as an image file URL.', }, - [supportedDocumentTypes.pdf]: { + [supportedDocTypes.pdf]: { options: standardOptions, dataDescription: 'the pdf content as a PDF file url.', }, - [supportedDocumentTypes.audio]: { + [supportedDocTypes.audio]: { options: standardOptions, dataDescription: 'The audio content as a file url.', }, - [supportedDocumentTypes.video]: { + [supportedDocTypes.video]: { options: standardOptions, dataDescription: 'The video content as a file url.', }, - [supportedDocumentTypes.message]: { + [supportedDocTypes.message]: { options: standardOptions, dataDescription: 'The message content of the document.', }, - [supportedDocumentTypes.diagram]: { + [supportedDocTypes.diagram]: { options: ['title', 'backgroundColor'], dataDescription: 'diagram content as a text string in Mermaid format.', }, - [supportedDocumentTypes.script]: { + [supportedDocTypes.script]: { options: ['title', 'backgroundColor'], dataDescription: 'The compilable JavaScript code. Use this for creating scripts.', }, diff --git a/src/client/views/nodes/chatbot/tools/CreateCSVTool.ts b/src/client/views/nodes/chatbot/tools/CreateCSVTool.ts index e8ef3fbfe..290c48d6c 100644 --- a/src/client/views/nodes/chatbot/tools/CreateCSVTool.ts +++ b/src/client/views/nodes/chatbot/tools/CreateCSVTool.ts @@ -38,10 +38,10 @@ export class CreateCSVTool extends BaseTool<CreateCSVToolParamsType> { async execute(args: ParametersType<CreateCSVToolParamsType>): Promise<Observation[]> { try { console.log('Creating CSV file:', args.filename, ' with data:', args.csvData); - const { fileUrl, id } = await Networking.PostToServer('/createCSV', { + const { fileUrl, id } = (await Networking.PostToServer('/createCSV', { filename: args.filename, data: args.csvData, - }); + })) as { fileUrl: string; id: string }; this._handleCSVResult(fileUrl, args.filename, id, args.csvData); diff --git a/src/client/views/nodes/chatbot/tools/CreateDocumentTool.ts b/src/client/views/nodes/chatbot/tools/CreateDocumentTool.ts index 6dc36b0d1..284879a4a 100644 --- a/src/client/views/nodes/chatbot/tools/CreateDocumentTool.ts +++ b/src/client/views/nodes/chatbot/tools/CreateDocumentTool.ts @@ -263,79 +263,79 @@ const standardOptions = ['title', 'backgroundColor']; * Description of document options and data field for each type. */ const documentTypesInfo: { [key in supportedDocTypes]: { options: string[]; dataDescription: string } } = { - [supportedDocTypes.comparison]: { + comparison: { options: [...standardOptions, 'fontColor', 'text_align'], dataDescription: 'an array of two documents of any kind that can be compared.', }, - [supportedDocTypes.deck]: { + deck: { options: [...standardOptions, 'fontColor', 'text_align'], dataDescription: 'an array of flashcard docs', }, - [supportedDocTypes.flashcard]: { + flashcard: { options: [...standardOptions, 'fontColor', 'text_align'], dataDescription: 'an array of two strings. the first string contains a question, and the second string contains an answer', }, - [supportedDocTypes.text]: { + text: { options: [...standardOptions, 'fontColor', 'text_align'], dataDescription: 'The text content of the document.', }, - [supportedDocTypes.web]: { + web: { options: [], dataDescription: 'A URL to a webpage. Example: https://en.wikipedia.org/wiki/Brown_University', }, - [supportedDocTypes.html]: { + html: { options: [], dataDescription: 'The HTML-formatted text content of the document.', }, - [supportedDocTypes.equation]: { + equation: { options: [...standardOptions, 'fontColor'], dataDescription: 'The equation content represented as a MathML string.', }, - [supportedDocTypes.functionplot]: { + functionplot: { options: [...standardOptions, 'function_definition'], dataDescription: 'The function definition(s) for plotting. Provide as a string or array of function definitions.', }, - [supportedDocTypes.dataviz]: { + dataviz: { options: [...standardOptions, 'chartType'], dataDescription: 'A string of comma-separated values representing the CSV data.', }, - [supportedDocTypes.notetaking]: { + notetaking: { options: standardOptions, dataDescription: 'An array of related text documents with small amounts of text.', }, - [supportedDocTypes.rtf]: { + rtf: { options: standardOptions, dataDescription: 'The rich text content in RTF format.', }, - [supportedDocTypes.image]: { + image: { options: standardOptions, dataDescription: `A url string that must end with '.png', '.jpeg', '.gif', or '.jpg'`, }, - [supportedDocTypes.pdf]: { + pdf: { options: standardOptions, dataDescription: 'the pdf content as a PDF file url.', }, - [supportedDocTypes.audio]: { + audio: { options: standardOptions, dataDescription: 'The audio content as a file url.', }, - [supportedDocTypes.video]: { + video: { options: standardOptions, dataDescription: 'The video content as a file url.', }, - [supportedDocTypes.message]: { + message: { options: standardOptions, dataDescription: 'The message content of the document.', }, - [supportedDocTypes.diagram]: { + diagram: { options: standardOptions, dataDescription: 'diagram content as a text string in Mermaid format.', }, - [supportedDocTypes.script]: { + script: { options: standardOptions, dataDescription: 'The compilable JavaScript code. Use this for creating scripts.', }, - [supportedDocTypes.collection]: { + collection: { options: [...standardOptions, 'type_collection'], dataDescription: 'A collection of Docs represented as an array.', }, diff --git a/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts b/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts index 177552c5c..37907fd4f 100644 --- a/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts +++ b/src/client/views/nodes/chatbot/tools/ImageCreationTool.ts @@ -1,10 +1,11 @@ -import { v4 as uuidv4 } from 'uuid'; import { RTFCast } from '../../../../../fields/Types'; import { DocumentOptions } from '../../../../documents/Documents'; import { Networking } from '../../../../Network'; import { ParametersType, ToolInfo } from '../types/tool_types'; import { Observation } from '../types/types'; import { BaseTool } from './BaseTool'; +import { Upload } from '../../../../../server/SharedMediaTypes'; +import { List } from '../../../../../fields/List'; const imageCreationToolParams = [ { @@ -25,8 +26,8 @@ const imageCreationToolInfo: ToolInfo<ImageCreationToolParamsType> = { }; export class ImageCreationTool extends BaseTool<ImageCreationToolParamsType> { - private _createImage: (result: any, options: DocumentOptions) => void; - constructor(createImage: (result: any, options: DocumentOptions) => void) { + private _createImage: (result: Upload.FileInformation & Upload.InspectionResults, options: DocumentOptions) => void; + constructor(createImage: (result: Upload.FileInformation & Upload.InspectionResults, options: DocumentOptions) => void) { super(imageCreationToolInfo); this._createImage = createImage; } @@ -37,28 +38,24 @@ export class ImageCreationTool extends BaseTool<ImageCreationToolParamsType> { console.log(`Generating image for prompt: ${image_prompt}`); // Create an array of promises, each one handling a search for a query try { - const { result, url } = await Networking.PostToServer('/generateImage', { + const { result, url } = (await Networking.PostToServer('/generateImage', { image_prompt, - }); + })) as { result: Upload.FileInformation & Upload.InspectionResults; url: string }; console.log('Image generation result:', result); - this._createImage(result, { text: RTFCast(image_prompt) }); - if (url) { - const id = uuidv4(); - - return [ - { - type: 'image_url', - image_url: { url }, - }, - ]; - } else { - return [ - { - type: 'text', - text: `An error occurred while generating image.`, - }, - ]; - } + this._createImage(result, { text: RTFCast(image_prompt), ai: 'dall-e-3', tags: new List<string>(['@ai']) }); + return url + ? [ + { + type: 'image_url', + image_url: { url }, + }, + ] + : [ + { + type: 'text', + text: `An error occurred while generating image.`, + }, + ]; } catch (error) { console.log(error); return [ diff --git a/src/client/views/nodes/chatbot/tools/RAGTool.ts b/src/client/views/nodes/chatbot/tools/RAGTool.ts index 2db61c768..ef374ed22 100644 --- a/src/client/views/nodes/chatbot/tools/RAGTool.ts +++ b/src/client/views/nodes/chatbot/tools/RAGTool.ts @@ -75,7 +75,7 @@ export class RAGTool extends BaseTool<RAGToolParamsType> { async getFormattedChunks(relevantChunks: RAGChunk[]): Promise<Observation[]> { try { - const { formattedChunks } = await Networking.PostToServer('/formatChunks', { relevantChunks }); + const { formattedChunks } = await Networking.PostToServer('/formatChunks', { relevantChunks }) as { formattedChunks: Observation[]} if (!formattedChunks) { throw new Error('Failed to format chunks'); diff --git a/src/client/views/nodes/chatbot/tools/SearchTool.ts b/src/client/views/nodes/chatbot/tools/SearchTool.ts index 5fc6ab768..6a11407a5 100644 --- a/src/client/views/nodes/chatbot/tools/SearchTool.ts +++ b/src/client/views/nodes/chatbot/tools/SearchTool.ts @@ -41,15 +41,15 @@ export class SearchTool extends BaseTool<SearchToolParamsType> { // Create an array of promises, each one handling a search for a query const searchPromises = queries.map(async query => { try { - const { results } = await Networking.PostToServer('/getWebSearchResults', { + const { results } = (await Networking.PostToServer('/getWebSearchResults', { query, max_results: this._max_results, - }); + })) as { results: { url: string; snippet: string }[] }; const data = results.map((result: { url: string; snippet: string }) => { const id = uuidv4(); this._addLinkedUrlDoc(result.url, id); return { - type: 'text', + type: 'text' as const, text: `<chunk chunk_id="${id}" chunk_type="url"><url>${result.url}</url><overview>${result.snippet}</overview></chunk>`, }; }); @@ -58,7 +58,7 @@ export class SearchTool extends BaseTool<SearchToolParamsType> { console.log(error); return [ { - type: 'text', + type: 'text' as const, text: `An error occurred while performing the web search for query: ${query}`, }, ]; diff --git a/src/client/views/nodes/chatbot/types/types.ts b/src/client/views/nodes/chatbot/types/types.ts index 995ac531d..882e74ebb 100644 --- a/src/client/views/nodes/chatbot/types/types.ts +++ b/src/client/views/nodes/chatbot/types/types.ts @@ -1,6 +1,3 @@ -import { indexes } from 'd3'; -import { AnyLayer } from 'react-map-gl'; - export enum ASSISTANT_ROLE { USER = 'user', ASSISTANT = 'assistant', @@ -122,9 +119,8 @@ export interface AI_Document { type: string; } +export type Observation = { type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } }; export interface AgentMessage { role: 'system' | 'user' | 'assistant'; content: string | Observation[]; } - -export type Observation = { type: 'text'; text: string } | { type: 'image_url'; image_url: { url: string } }; diff --git a/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts b/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts index ef24e59bc..afd34f28d 100644 --- a/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts +++ b/src/client/views/nodes/chatbot/vectorstore/Vectorstore.ts @@ -1,13 +1,11 @@ /** * @file Vectorstore.ts - * @description This file defines the Vectorstore class, which integrates with Pinecone for vector-based document indexing and Cohere for text embeddings. + * @description This file defines the Vectorstore class, which integrates with Pinecone for vector-based document indexing and OpenAI text-embedding-3-large for text embeddings. * It manages AI document handling, including adding documents, processing media files, combining document chunks, indexing documents, * and retrieving relevant sections based on user queries. */ import { Index, IndexList, Pinecone, PineconeRecord, QueryResponse, RecordMetadata } from '@pinecone-database/pinecone'; -import { CohereClient } from 'cohere-ai'; -import { EmbedResponse } from 'cohere-ai/api'; import dotenv from 'dotenv'; import path from 'path'; import { v4 as uuidv4 } from 'uuid'; @@ -15,17 +13,20 @@ import { Doc } from '../../../../../fields/Doc'; import { AudioCast, CsvCast, PDFCast, StrCast, VideoCast } from '../../../../../fields/Types'; import { Networking } from '../../../../Network'; import { AI_Document, CHUNK_TYPE, RAGChunk } from '../types/types'; +import OpenAI from 'openai'; +import { Embedding } from 'openai/resources'; +import { PineconeEnvironmentVarsNotSupportedError } from '@pinecone-database/pinecone/dist/errors'; dotenv.config(); /** * The Vectorstore class integrates with Pinecone for vector-based document indexing and retrieval, - * and Cohere for text embedding. It handles AI document management, uploads, and query-based retrieval. + * and OpenAI text-embedding-3-large for text embedding. It handles AI document management, uploads, and query-based retrieval. */ export class Vectorstore { private pinecone: Pinecone; // Pinecone client for managing the vector index. private index!: Index; // The specific Pinecone index used for document chunks. - private cohere: CohereClient; // Cohere client for generating embeddings. + private openai: OpenAI; // OpenAI client for generating embeddings. private indexName: string = 'pdf-chatbot'; // Default name for the index. private _id: string; // Unique ID for the Vectorstore instance. private _doc_ids: () => string[]; // List of document IDs handled by this instance. @@ -33,20 +34,20 @@ export class Vectorstore { documents: AI_Document[] = []; // Store the documents indexed in the vectorstore. /** - * Initializes the Pinecone and Cohere clients, sets up the document ID list, + * Initializes the Pinecone and OpenAI clients, sets up the document ID list, * and initializes the Pinecone index. * @param id The unique identifier for the vectorstore instance. * @param doc_ids A function that returns a list of document IDs. */ constructor(id: string, doc_ids: () => string[]) { - const pineconeApiKey = '51738e9a-bea2-4c11-b6bf-48a825e774dc'; + const pineconeApiKey = process.env.PINECONE_API_KEY; if (!pineconeApiKey) { throw new Error('PINECONE_API_KEY is not defined.'); } - // Initialize Pinecone and Cohere clients with API keys from the environment. + // Initialize Pinecone and OpenAI clients with API keys from the environment. this.pinecone = new Pinecone({ apiKey: pineconeApiKey }); - // this.cohere = new CohereClient({ token: process.env.COHERE_API_KEY }); + this.openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY, dangerouslyAllowBrowser: true }); this._id = id; this._doc_ids = doc_ids; this.initializeIndex(); @@ -63,7 +64,7 @@ export class Vectorstore { if (!indexList.indexes?.some(index => index.name === this.indexName)) { await this.pinecone.createIndex({ name: this.indexName, - dimension: 1024, + dimension: 3072, metric: 'cosine', spec: { serverless: { @@ -119,23 +120,12 @@ export class Vectorstore { const texts = segmentedTranscript.map((chunk: any) => chunk.text); try { - const embeddingsResponse = await this.cohere.v2.embed({ - model: 'embed-english-v3.0', - inputType: 'classification', - embeddingTypes: ['float'], // Specify that embeddings should be floats - texts, // Pass the array of chunk texts + const embeddingsResponse = await this.openai.embeddings.create({ + model: 'text-embedding-3-large', + input: texts, + encoding_format: 'float', }); - if (!embeddingsResponse.embeddings.float || embeddingsResponse.embeddings.float.length !== texts.length) { - throw new Error('Mismatch between embeddings and the number of chunks'); - } - - // Assign embeddings to each chunk - segmentedTranscript.forEach((chunk: any, index: number) => { - if (!embeddingsResponse.embeddings || !embeddingsResponse.embeddings.float) { - throw new Error('Invalid embeddings response'); - } - }); doc.original_segments = JSON.stringify(response.full); doc.ai_type = local_file_path.endsWith('.mp3') ? 'audio' : 'video'; const doc_id = uuidv4(); @@ -149,7 +139,7 @@ export class Vectorstore { summary: '', chunks: segmentedTranscript.map((chunk: any, index: number) => ({ id: uuidv4(), - values: (embeddingsResponse.embeddings.float as number[][])[index], // Assign embedding + values: (embeddingsResponse.data as Embedding[])[index].embedding, // Assign embedding metadata: { indexes: chunk.indexes, original_document: local_file_path, @@ -291,7 +281,7 @@ export class Vectorstore { /** * Retrieves the most relevant document chunks for a given query. - * Uses Cohere for embedding the query and Pinecone for vector similarity matching. + * Uses OpenAI for embedding the query and Pinecone for vector similarity matching. * @param query The search query string. * @param topK The number of top results to return (default is 10). * @returns A list of document chunks that match the query. @@ -299,27 +289,17 @@ export class Vectorstore { async retrieve(query: string, topK: number = 10): Promise<RAGChunk[]> { console.log(`Retrieving chunks for query: ${query}`); try { - // Generate an embedding for the query using Cohere. - const queryEmbeddingResponse: EmbedResponse = await this.cohere.embed({ - texts: [query], - model: 'embed-english-v3.0', - inputType: 'search_query', + // Generate an embedding for the query using OpenAI. + const queryEmbeddingResponse = await this.openai.embeddings.create({ + model: 'text-embedding-3-large', + input: query, + encoding_format: 'float', }); - let queryEmbedding: number[]; + let queryEmbedding = queryEmbeddingResponse.data[0].embedding; // Extract the embedding from the response. - if (Array.isArray(queryEmbeddingResponse.embeddings)) { - queryEmbedding = queryEmbeddingResponse.embeddings[0]; - } else if (queryEmbeddingResponse.embeddings && 'embeddings' in queryEmbeddingResponse.embeddings) { - queryEmbedding = (queryEmbeddingResponse.embeddings as { embeddings: number[][] }).embeddings[0]; - } else { - throw new Error('Invalid embedding response format'); - } - if (!Array.isArray(queryEmbedding)) { - throw new Error('Query embedding is not an array'); - } console.log(this._doc_ids()); // Query the Pinecone index using the embedding and filter by document IDs. const queryResponse: QueryResponse = await this.index.query({ diff --git a/src/client/views/nodes/formattedText/DashFieldView.scss b/src/client/views/nodes/formattedText/DashFieldView.scss index d79df4272..78bbb520e 100644 --- a/src/client/views/nodes/formattedText/DashFieldView.scss +++ b/src/client/views/nodes/formattedText/DashFieldView.scss @@ -1,4 +1,4 @@ -@import '../../global/globalCssVariables.module.scss'; +@use '../../global/globalCssVariables.module.scss' as global; .dashFieldView-active, .dashFieldView { @@ -64,5 +64,5 @@ } .ProseMirror-selectedNode { - outline: solid 1px $light-blue !important; + outline: solid 1px global.$light-blue !important; } diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.scss b/src/client/views/nodes/formattedText/FormattedTextBox.scss index 84859b94d..f9de4ab5a 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBox.scss +++ b/src/client/views/nodes/formattedText/FormattedTextBox.scss @@ -1,4 +1,4 @@ -@import '../../global/globalCssVariables.module.scss'; +@use '../../global/globalCssVariables.module.scss' as global; .ProseMirror { width: 100%; @@ -22,7 +22,7 @@ &.h-left * { display: flex; - justify-content: flex-start; + justify-content: flex-start; } &.h-right * { @@ -32,7 +32,7 @@ &.template * { ::-webkit-scrollbar-track { - background: none; + background: none; } } @@ -64,7 +64,7 @@ audiotag:hover { background: inherit; padding: 0; border-width: 0px; - border-color: $medium-gray; + border-color: global.$medium-gray; box-sizing: border-box; background-color: inherit; border-style: solid; @@ -79,7 +79,6 @@ audiotag:hover { transform-origin: left top; top: 0; left: 0; - } .formattedTextBox-cont { @@ -88,7 +87,7 @@ audiotag:hover { padding: 0; border-width: 0px; border-radius: inherit; - border-color: $medium-gray; + border-color: global.$medium-gray; box-sizing: border-box; background-color: inherit; border-style: solid; @@ -147,13 +146,13 @@ audiotag:hover { font-size: 11px; border-radius: 3px; color: white; - background: $medium-gray; + background: global.$medium-gray; border-radius: 5px; display: flex; justify-content: center; align-items: center; cursor: grabbing; - box-shadow: $standard-box-shadow; + box-shadow: global.$standard-box-shadow; // transition: 0.2s; opacity: 0.3; &:hover { @@ -646,7 +645,7 @@ footnote::before { } @media only screen and (max-width: 1000px) { - @import '../../global/globalCssVariables.module.scss'; + // @import '../../global/globalCssVariables.module.scss'; .ProseMirror { width: 100%; @@ -664,7 +663,7 @@ footnote::before { padding: 0; border-width: 0px; border-radius: inherit; - border-color: $medium-gray; + border-color: global.$medium-gray; box-sizing: border-box; background-color: inherit; border-style: solid; @@ -1074,4 +1073,3 @@ footnote::before { } } } - diff --git a/src/client/views/nodes/formattedText/FormattedTextBox.tsx b/src/client/views/nodes/formattedText/FormattedTextBox.tsx index eb1f9d07b..c2a2caecf 100644 --- a/src/client/views/nodes/formattedText/FormattedTextBox.tsx +++ b/src/client/views/nodes/formattedText/FormattedTextBox.tsx @@ -135,7 +135,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FormattedTextB /** * ApplyingChange - Marks whether an interactive text edit is currently in the process of being written to the database. - * This is needed to distinguish changes to text fields caused by editing vs those caused by changes to + * This is needed to distinguish changes to text fields caused by editing vs those caused by changes to * the prototype or other external edits */ public ApplyingChange: string = ''; @@ -977,7 +977,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FormattedTextB }, icon: 'star', }); - optionItems.push({ description: `Generate Dall-E Image`, event: () => this.generateImage(), icon: 'star' }); + optionItems.push({ description: `Generate Dall-E Image`, event: this.generateImage, icon: 'star' }); // optionItems.push({ description: `Make AI Flashcards`, event: () => this.makeAIFlashcards(), icon: 'lightbulb' }); optionItems.push({ description: `Ask GPT-3`, event: this.askGPT, icon: 'lightbulb' }); this._props.renderDepth && @@ -1043,7 +1043,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FormattedTextB askGPT = action(async () => { try { - GPTPopup.Instance.setSidebarId(this.sidebarKey); + GPTPopup.Instance.setSidebarFieldKey(this.sidebarKey); GPTPopup.Instance.addDoc = this.sidebarAddDocument; const res = await gptAPICall((this.dataDoc.text as RichTextField)?.Text, GPTCallType.COMPLETION); if (!res) { @@ -1061,12 +1061,9 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FormattedTextB } }); - generateImage = async () => { + generateImage = () => { GPTPopup.Instance?.setTextAnchor(this.getAnchor(false)); - GPTPopup.Instance?.setImgTargetDoc(this.Document); - GPTPopup.Instance.addToCollection = this._props.addDocument; - GPTPopup.Instance.setImgDesc((this.dataDoc.text as RichTextField)?.Text); - GPTPopup.Instance.generateImage(); + GPTPopup.Instance.generateImage((this.dataDoc.text as RichTextField)?.Text, this.Document, this._props.addDocument); }; breakupDictation = () => { @@ -1285,14 +1282,14 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FormattedTextB ); this._disposers.componentHeights = reaction( // set the document height when one of the component heights changes and layout_autoHeight is on - () => ({ sidebarHeight: this.sidebarHeight, textHeight: this.textHeight, layoutAutoHeight: this.layout_autoHeight, marginsHeight: this.layout_autoHeightMargins }), - ({ sidebarHeight, textHeight, layoutAutoHeight, marginsHeight }) => { + () => ({ border: this._props.PanelHeight(), sidebarHeight: this.sidebarHeight, textHeight: this.textHeight, layoutAutoHeight: this.layout_autoHeight, marginsHeight: this.layout_autoHeightMargins }), + ({ border, sidebarHeight, textHeight, layoutAutoHeight, marginsHeight }) => { const newHeight = this.contentScaling * (marginsHeight + Math.max(sidebarHeight, textHeight)); if ( (!Array.from(FormattedTextBox._globalHighlights).includes('Bold Text') || this._props.isSelected()) && // layoutAutoHeight && newHeight && - newHeight !== this.layoutDoc.height && + (newHeight !== this.layoutDoc.height || border < NumCast(this.layoutDoc.height)) && !this._props.dontRegisterView ) { this._props.setHeight?.(newHeight); @@ -1660,7 +1657,7 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FormattedTextB } }; onSelectEnd = () => { - GPTPopup.Instance.setSidebarId(this.sidebarKey); + GPTPopup.Instance.setSidebarFieldKey(this.sidebarKey); GPTPopup.Instance.addDoc = this.sidebarAddDocument; document.removeEventListener('pointerup', this.onSelectEnd); }; @@ -1672,7 +1669,19 @@ export class FormattedTextBox extends ViewBoxAnnotatableComponent<FormattedTextB for (let target: HTMLElement | Element | null = clickTarget as HTMLElement; target instanceof HTMLElement && !target.dataset?.targethrefs; target = target.parentElement); while (clickTarget instanceof HTMLElement && !clickTarget.dataset?.targethrefs) clickTarget = clickTarget.parentElement; const dataset = clickTarget instanceof HTMLElement ? clickTarget?.dataset : undefined; - FormattedTextBoxComment.update(this, this.EditorView!, undefined, dataset?.targethrefs, dataset?.linkdoc, dataset?.nopreview === 'true'); + + if (dataset?.targethrefs) + window + .open( + dataset?.targethrefs + ?.trim() + .split(' ') + .filter(h => h) + .lastElement(), + '_blank' + ) + ?.focus(); + else FormattedTextBoxComment.update(this, this.EditorView!, undefined, dataset?.targethrefs, dataset?.linkdoc, dataset?.nopreview === 'true'); } }; @action diff --git a/src/client/views/nodes/formattedText/RichTextMenu.scss b/src/client/views/nodes/formattedText/RichTextMenu.scss index d6ed5ebee..fcc816447 100644 --- a/src/client/views/nodes/formattedText/RichTextMenu.scss +++ b/src/client/views/nodes/formattedText/RichTextMenu.scss @@ -1,4 +1,4 @@ -@import '../../global/globalCssVariables.module.scss'; +@use '../../global/globalCssVariables.module.scss' as global; .button-dropdown-wrapper { position: relative; @@ -25,7 +25,7 @@ top: 35px; left: 0; background-color: #323232; - color: $light-gray; + color: global.$light-gray; border: 1px solid #4d4d4d; border-radius: 0 6px 6px 6px; box-shadow: 3px 3px 3px rgba(0, 0, 0, 0.25); diff --git a/src/client/views/nodes/imageEditor/ImageEditor.tsx b/src/client/views/nodes/imageEditor/ImageEditor.tsx index 6b1d05031..657e689bb 100644 --- a/src/client/views/nodes/imageEditor/ImageEditor.tsx +++ b/src/client/views/nodes/imageEditor/ImageEditor.tsx @@ -90,18 +90,8 @@ const ImageEditor = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc * @param type The new tool type we are changing to */ const changeTool = (type: ImageToolType) => { - switch (type) { - case ImageToolType.GenerativeFill: - setCurrTool(genFillTool); - setCursorData(prev => ({ ...prev, width: genFillTool.sliderDefault as number })); - break; - case ImageToolType.Cut: - setCurrTool(cutTool); - setCursorData(prev => ({ ...prev, width: cutTool.sliderDefault as number })); - break; - default: - break; - } + setCurrToolType(type); + setCursorData(prev => ({ ...prev, width: currTool().sliderDefault as number })); }; // Undo and Redo const handleUndo = () => { @@ -171,9 +161,8 @@ const ImageEditor = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc // handles brushing on pointer movement useEffect(() => { - if (!isBrushing) return undefined; const canvas = canvasRef.current; - if (!canvas) return undefined; + if (!isBrushing || !canvas) return undefined; const ctx = ImageUtility.getCanvasContext(canvasRef); if (!ctx) return undefined; @@ -188,33 +177,29 @@ const ImageEditor = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc }; drawingAreaRef.current?.addEventListener('pointermove', handlePointerMove); - return () => { - drawingAreaRef.current?.removeEventListener('pointermove', handlePointerMove); - }; + return () => drawingAreaRef.current?.removeEventListener('pointermove', handlePointerMove); }, [isBrushing]); // first load useEffect(() => { - const loadInitial = async () => { - if (!imageEditorSource || imageEditorSource === '') return; - const img = new Image(); - const res = await ImageUtility.urlToBase64(imageEditorSource); - if (!res) return; - img.src = `data:image/png;base64,${res}`; - - img.onload = () => { - currImg.current = img; - originalImg.current = img; - const imgWidth = img.naturalWidth; - const imgHeight = img.naturalHeight; - const scale = Math.min(canvasSize / imgWidth, canvasSize / imgHeight); - const width = imgWidth * scale; - const height = imgHeight * scale; - setCanvasDims({ width, height }); - }; - }; - - loadInitial(); + if (imageEditorSource && imageEditorSource) { + ImageUtility.urlToBase64(imageEditorSource).then(res => { + if (res) { + const img = new Image(); + img.src = `data:image/png;base64,${res}`; + img.onload = () => { + currImg.current = img; + originalImg.current = img; + const imgWidth = img.naturalWidth; + const imgHeight = img.naturalHeight; + const scale = Math.min(canvasSize / imgWidth, canvasSize / imgHeight); + const width = imgWidth * scale; + const height = imgHeight * scale; + setCanvasDims({ width, height }); + }; + } + }); + } // cleanup return () => { @@ -300,7 +285,7 @@ const ImageEditor = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc if (!canvasMask) return; const maskBlob = await ImageUtility.canvasToBlob(canvasMask); const imgBlob = await ImageUtility.canvasToBlob(canvasOriginalImg); - const res = await ImageUtility.getEdit(imgBlob, maskBlob, input !== '' ? input + ' in the same style' : 'Fill in the image in the same style', 2); + const res = await ImageUtility.getEdit(imgBlob, maskBlob, input || 'Fill in the image in the same style', 2); // create first image if (!newCollectionRef.current) { @@ -569,11 +554,15 @@ const ImageEditor = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc setIsFirstDoc(true); }; + function currTool() { + return imageEditTools.find(tool => tool.type === currToolType) ?? genFillTool; + } + // defines the tools and sets current tool - const genFillTool: ImageEditTool = { type: ImageToolType.GenerativeFill, name: 'Generative Fill', btnText: 'GET EDITS', icon: 'fill', applyFunc: getEdit, sliderMin: 25, sliderMax: 500, sliderDefault: 150 }; - const cutTool: ImageEditTool = { type: ImageToolType.Cut, name: 'Cut', btnText: 'CUT IMAGE', icon: 'scissors', applyFunc: cutImage, sliderMin: 1, sliderMax: 50, sliderDefault: 5 }; + const genFillTool: ImageEditTool = { type: ImageToolType.GenerativeFill, btnText: 'GET EDITS', icon: 'fill', applyFunc: getEdit, sliderMin: 25, sliderMax: 500, sliderDefault: 150 }; + const cutTool: ImageEditTool = { type: ImageToolType.Cut, btnText: 'CUT IMAGE', icon: 'scissors', applyFunc: cutImage, sliderMin: 1, sliderMax: 50, sliderDefault: 5 }; const imageEditTools: ImageEditTool[] = [genFillTool, cutTool]; - const [currTool, setCurrTool] = useState<ImageEditTool>(genFillTool); + const [currToolType, setCurrToolType] = useState<ImageToolType>(ImageToolType.GenerativeFill); // the top controls for making a new collection, resetting, and applying edits, function renderControls() { @@ -595,7 +584,7 @@ const ImageEditor = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc labelPlacement="end" sx={{ whiteSpace: 'nowrap' }} /> - <ApplyFuncButtons onClick={() => currTool.applyFunc(cutType, cursorData.width, edits, isFirstDoc)} loading={loading} onReset={handleReset} btnText={currTool.btnText} /> + <ApplyFuncButtons onClick={() => currTool().applyFunc(cutType, cursorData.width, edits, isFirstDoc)} loading={loading} onReset={handleReset} btnText={currTool().btnText} /> <IconButton color={activeColor} tooltip="close" icon={<CgClose size="16px" />} onClick={handleViewClose} /> </div> </div> @@ -607,8 +596,8 @@ const ImageEditor = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc return ( <div className="sideControlsContainer" style={{ backgroundColor: bgColor }}> <div className="sideControls"> - <div className="imageToolsContainer">{imageEditTools.map(tool => ImageToolButton(tool, tool.type === currTool.type, changeTool))}</div> - {currTool.type == ImageToolType.Cut && ( + <div className="imageToolsContainer">{imageEditTools.map(tool => ImageToolButton(tool, tool.type === currTool().type, changeTool))}</div> + {currTool().type == ImageToolType.Cut && ( <div className="cutToolsContainer"> <Button style={{ width: '100%' }} text="Keep in" type={Type.TERT} color={cutType == CutMode.IN ? SettingsManager.userColor : bgColor} onClick={() => setCutType(CutMode.IN)} /> <Button style={{ width: '100%' }} text="Keep out" type={Type.TERT} color={cutType == CutMode.OUT ? SettingsManager.userColor : bgColor} onClick={() => setCutType(CutMode.OUT)} /> @@ -617,11 +606,13 @@ const ImageEditor = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc </div> )} <div className="sliderContainer" onPointerDown={e => e.stopPropagation()}> - {currTool.type === ImageToolType.GenerativeFill && ( + {currTool().type === ImageToolType.GenerativeFill && ( <Slider sx={{ '& input[type="range"]': { - WebkitAppearance: 'slider-vertical', + writingMode: 'vertical-lr', + direction: 'rtl', + // WebkitAppearance: 'slider-vertical', }, }} orientation="vertical" @@ -633,11 +624,13 @@ const ImageEditor = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc onChange={(e, val) => setCursorData(prev => ({ ...prev, width: val as number }))} /> )} - {currTool.type === ImageToolType.Cut && ( + {currTool().type === ImageToolType.Cut && ( <Slider sx={{ '& input[type="range"]': { - WebkitAppearance: 'slider-vertical', + writingMode: 'vertical-lr', + direction: 'rtl', + // WebkitAppearance: 'slider-vertical', }, }} orientation="vertical" @@ -780,7 +773,7 @@ const ImageEditor = ({ imageEditorOpen, imageEditorSource, imageRootDoc, addDoc {renderSideIcons()} {renderEditThumbnails()} </div> - {currTool.type === ImageToolType.GenerativeFill && renderPromptBox()} + {currTool().type === ImageToolType.GenerativeFill && renderPromptBox()} </div> ); }; diff --git a/src/client/views/nodes/imageEditor/ImageEditorButtons.tsx b/src/client/views/nodes/imageEditor/ImageEditorButtons.tsx index 985dc914f..3eaa251f2 100644 --- a/src/client/views/nodes/imageEditor/ImageEditorButtons.tsx +++ b/src/client/views/nodes/imageEditor/ImageEditorButtons.tsx @@ -53,10 +53,10 @@ export function ApplyFuncButtons({ loading, onClick: getEdit, onReset, btnText } export function ImageToolButton(tool: ImageEditTool, isActive: boolean, selectTool: (type: ImageToolType) => void) { return ( - <div key={tool.name} className="imageEditorButtonContainer"> + <div key={tool.type} className="imageEditorButtonContainer"> <Button style={{ width: '100%' }} - text={tool.name} + text={tool.type} type={Type.TERT} color={isActive ? SettingsManager.userVariantColor : bgColor} icon={<FontAwesomeIcon icon={tool.icon} />} diff --git a/src/client/views/nodes/imageEditor/imageEditorUtils/ImageHandler.ts b/src/client/views/nodes/imageEditor/imageEditorUtils/ImageHandler.ts index ece0f4d7f..1c6a38a24 100644 --- a/src/client/views/nodes/imageEditor/imageEditorUtils/ImageHandler.ts +++ b/src/client/views/nodes/imageEditor/imageEditorUtils/ImageHandler.ts @@ -87,7 +87,6 @@ export class ImageUtility { body: fd, }); const data = await res.json(); - console.log(data.data); return { status: 'success', urls: (data.data as { b64_json: string }[]).map(urlData => `data:image/png;base64,${urlData.b64_json}`), diff --git a/src/client/views/nodes/imageEditor/imageEditorUtils/imageEditorInterfaces.ts b/src/client/views/nodes/imageEditor/imageEditorUtils/imageEditorInterfaces.ts index a14b55439..02dbc0312 100644 --- a/src/client/views/nodes/imageEditor/imageEditorUtils/imageEditorInterfaces.ts +++ b/src/client/views/nodes/imageEditor/imageEditorUtils/imageEditorInterfaces.ts @@ -13,8 +13,8 @@ export interface Point { } export enum ImageToolType { - GenerativeFill = 'genFill', - Cut = 'cut', + GenerativeFill = 'Generative Fill', + Cut = 'Cut', } export enum CutMode { @@ -26,7 +26,6 @@ export enum CutMode { export interface ImageEditTool { type: ImageToolType; - name: string; btnText: string; icon: IconProp; // this is the function that the image tool applies, so it can be defined depending on the tool diff --git a/src/client/views/nodes/trails/PresBox.scss b/src/client/views/nodes/trails/PresBox.scss index e34e1b380..e24b47bd1 100644 --- a/src/client/views/nodes/trails/PresBox.scss +++ b/src/client/views/nodes/trails/PresBox.scss @@ -1,4 +1,4 @@ -@import '../../global/globalCssVariables.module.scss'; +@use '../../global/globalCssVariables.module.scss' as global; .presBox-gpt-chat { padding: 16px; @@ -203,8 +203,8 @@ align-items: center; height: 30px; width: 100%; - color: $white; - background-color: $dark-gray; + color: global.$white; + background-color: global.$dark-gray; .toolbar-button { cursor: pointer; @@ -218,7 +218,7 @@ } .toolbar-button.active { - color: $light-blue; + color: global.$light-blue; background-color: white; border-radius: 100%; } @@ -266,7 +266,7 @@ } .toolbar-divider { - border-left: solid $medium-gray 0.5px; + border-left: solid global.$medium-gray 0.5px; height: 20px; } } @@ -274,13 +274,13 @@ .dropdown { font-size: 10; margin-left: 5px; - color: $medium-gray; + color: global.$medium-gray; transition: 0.5s ease; } .dropdown.active { transform: rotate(180deg); - color: $light-blue; + color: global.$light-blue; opacity: 0.7; } @@ -340,7 +340,7 @@ .ribbon-colorBox { cursor: pointer; - border: solid 1px $black; + border: solid 1px global.$black; display: flex; margin-left: 5px; margin-top: 5px; @@ -387,7 +387,7 @@ } .ribbon-propertyUpDownItem:hover { - background: $medium-gray; + background: global.$medium-gray; transform: scale(1.05); } } @@ -413,7 +413,7 @@ @media screen and (-webkit-min-device-pixel-ratio: 0) { .multiThumb-slider { display: grid; - background-color: $white; + background-color: global.$white; height: 10px; border-radius: 10px; overflow: hidden; @@ -431,8 +431,8 @@ -webkit-appearance: none; height: 10px; cursor: ew-resize; - background: $medium-blue; - box-shadow: -100vw 0 0 100vw $white; + background: global.$medium-blue; + box-shadow: -100vw 0 0 100vw global.$white; } .toolbar-slider.end::-webkit-slider-thumb { @@ -441,8 +441,8 @@ -webkit-appearance: none; height: 10px; cursor: ew-resize; - background: $medium-blue; - box-shadow: -100vw 0 0 100vw $light-blue; + background: global.$medium-blue; + box-shadow: -100vw 0 0 100vw global.$light-blue; } } @@ -456,7 +456,7 @@ height: 10px; border-radius: 10px; -webkit-appearance: none; - background-color: $white; + background-color: global.$white; } .toolbar-slider:focus { @@ -476,8 +476,8 @@ -webkit-appearance: none; height: 10px; cursor: ew-resize; - background: $medium-blue; - box-shadow: -100vw 0 0 100vw $light-blue; + background: global.$medium-blue; + box-shadow: -100vw 0 0 100vw global.$light-blue; } .presBox-checkbox { @@ -493,7 +493,7 @@ width: 15px; min-width: 15px; cursor: pointer; - background: $white; + background: global.$white; } .presBox-checkbox:focus { @@ -501,11 +501,11 @@ } .presBox-checkbox:hover { - background: $light-gray; + background: global.$light-gray; } .presBox-checkbox:checked { - background: $light-blue; + background: global.$light-blue; } } @@ -554,9 +554,9 @@ text-align: center; font-size: 16; width: 90%; - color: $black; + color: global.$black; transform: translate(5%, 0px); - border-bottom: solid 2px $medium-gray; + border-bottom: solid 2px global.$medium-gray; } .ribbon-textInput { @@ -568,8 +568,8 @@ justify-self: left; margin-top: 5px; padding-left: 10px; - background-color: $white; - border: solid 1px $black; + background-color: global.$white; + border: solid 1px global.$black; min-width: 80px; max-width: 200px; width: 100%; @@ -590,7 +590,7 @@ } .ribbon-frameSelector { - border: $black solid 1px; + border: global.$black solid 1px; width: 60px; height: 20px; margin-top: 5px; @@ -607,12 +607,12 @@ cursor: pointer; position: relative; height: 100%; - background: $white; + background: global.$white; display: flex; align-items: center; justify-content: center; text-align: center; - color: $black; + color: global.$black; } .numKeyframe { @@ -620,7 +620,7 @@ font-size: 10; font-weight: 600; position: relative; - color: $black; + color: global.$black; display: flex; width: 100%; height: 100%; @@ -662,7 +662,7 @@ padding-left: 10; padding-right: 10; border-radius: 10px; - background-color: $medium-gray; + background-color: global.$medium-gray; } .ribbon-final-button:hover { @@ -681,13 +681,13 @@ align-items: center; margin-bottom: 5px; height: 25px; - color: $light-gray; + color: global.$light-gray; width: 100%; max-width: 120; padding-left: 10; padding-right: 10; border-radius: 10px; - background-color: $black; + background-color: global.$black; } .ribbon-final-button-hidden:hover { @@ -698,15 +698,15 @@ .ribbon-frameList { width: calc(100% - 5px); height: 50px; - background-color: $white; - border: 1px solid $medium-gray; + background-color: global.$white; + border: 1px solid global.$medium-gray; grid-template-rows: max-content; .frameList-header { display: grid; width: 100%; height: 20px; - background-color: $medium-gray; + background-color: global.$medium-gray; .frameList-headerButtons { display: flex; @@ -761,7 +761,7 @@ font-size: 10.5; font-weight: 300; height: 20; - background-color: $medium-gray; + background-color: global.$medium-gray; color: white; display: flex; margin-top: 5px; @@ -780,8 +780,8 @@ transition: all 0.4s; font-weight: 400; opacity: 1; - color: $white; - background-color: $black; + color: global.$white; + background-color: global.$black; } .ribbon-toggle { @@ -789,9 +789,9 @@ font-size: 10.5; font-weight: 200; height: 20; - background-color: $white; + background-color: global.$white; display: inline-flex; - color: $black; + color: global.$black; border-radius: 5px; width: max-content; justify-content: center; @@ -831,13 +831,13 @@ position: relative; font-size: 13; padding-bottom: 10px; - border-bottom: solid 1px $dark-gray; + border-bottom: solid 1px global.$dark-gray; .presBox-dropdown:hover { - border: solid 1px $medium-blue; + border: solid 1px global.$medium-blue; .presBox-dropdownIcon { - color: $medium-blue; + color: global.$medium-blue; } } @@ -846,12 +846,12 @@ display: grid; grid-template-columns: auto 20%; position: relative; - border: solid 1px $black; - background-color: $light-gray; + border: solid 1px global.$black; + background-color: global.$light-gray; border-radius: 5px; font-size: 10; height: 25; - color: $black; + color: global.$black; padding-left: 5px; align-items: center; margin-top: 5px; @@ -917,7 +917,7 @@ height: 100px; padding-top: 5px; padding-bottom: 5px; - border: solid 1px $black; + border: solid 1px global.$black; // overflow: auto; ::-webkit-scrollbar { @@ -967,7 +967,7 @@ cursor: pointer; position: relative; text-align: center; - border-left: solid 1px $medium-gray; + border-left: solid 1px global.$medium-gray; width: 20%; height: 100%; display: flex; @@ -998,7 +998,7 @@ box-shadow: 0px 4px 10px rgba(0, 0, 0, 0.8); z-index: 200; background-color: white; - color: $black; + color: global.$black; position: absolute; overflow: hidden; } @@ -1014,12 +1014,12 @@ align-items: center; justify-content: center; transform: translate(0px, -1px); - background-color: $white; + background-color: global.$white; width: 40px; height: 15px; align-self: center; justify-self: center; - border: solid 1px $black; + border: solid 1px global.$black; border-top: 0px; border-bottom-right-radius: 7px; border-bottom-left-radius: 7px; @@ -1028,15 +1028,15 @@ .layout-container { padding: 5px; display: grid; - background-color: $white; + background-color: global.$white; grid-template-columns: repeat(auto-fit, minmax(90px, 100px)); width: 100%; - border: solid 1px $black; + border: solid 1px global.$black; min-width: 100px; overflow: hidden; .layout:hover { - border: solid 2px $medium-blue; + border: solid 2px global.$medium-blue; } .layout { @@ -1051,7 +1051,7 @@ width: 90px; overflow: hidden; background-color: white; - border: solid $medium-gray 1px; + border: solid global.$medium-gray 1px; display: grid; grid-template-rows: auto; align-items: center; @@ -1066,7 +1066,7 @@ height: 13; font-size: 12; display: flex; - background-color: $white; + background-color: global.$white; } .subtitle { @@ -1079,7 +1079,7 @@ height: 13; font-size: 9; display: flex; - background-color: $white; + background-color: global.$white; } .content { @@ -1092,7 +1092,7 @@ height: 13; font-size: 10; display: flex; - background-color: $white; + background-color: global.$white; height: 33; text-align: left; font-size: 8px; @@ -1103,7 +1103,7 @@ .presBox-buttons { position: relative; width: 100%; - background: $medium-gray; + background: global.$medium-gray; min-height: 35px; padding-top: 5px; padding-bottom: 5px; @@ -1137,8 +1137,8 @@ } select { - background: $dark-gray; - color: $white; + background: global.$dark-gray; + color: global.$white; } .presBox-button { @@ -1152,8 +1152,8 @@ text-align: center; letter-spacing: normal; width: inherit; - background: $dark-gray; - color: $white; + background: global.$dark-gray; + color: global.$white; } .presBox-button.active { @@ -1161,7 +1161,7 @@ } .presBox-button.active:hover { - background-color: $medium-blue; + background-color: global.$medium-blue; } .presBox-button.edit { @@ -1238,8 +1238,8 @@ font-size: 100; display: flex; align-items: center; - background: $dark-gray; - color: $white; + background: global.$dark-gray; + color: global.$white; } .presBox-viewPicker { @@ -1273,7 +1273,7 @@ left: 0; opacity: 0.5; transition: all 0.4s; - color: $white; + color: global.$white; width: 100%; height: 100%; } @@ -1283,8 +1283,8 @@ } .presPanelOverlay { - background-color: $dark-gray; - color: $white; + background-color: global.$dark-gray; + color: global.$white; border-radius: 5px; grid-template-rows: 100%; height: 100%; @@ -1316,7 +1316,7 @@ .presPanel-divider { width: 0.5px; height: 80%; - border-right: solid 1px $medium-gray; + border-right: solid 1px global.$medium-gray; } .presPanel-button-frame { @@ -1348,12 +1348,12 @@ } .presPanel-button:hover { - background-color: $medium-gray; + background-color: global.$medium-gray; transform: scale(1.2); } .presPanel-button-text:hover { - background-color: $medium-gray; + background-color: global.$medium-gray; } } diff --git a/src/client/views/nodes/trails/SlideEffect.tsx b/src/client/views/nodes/trails/SlideEffect.tsx index a114c231f..89abdd12d 100644 --- a/src/client/views/nodes/trails/SlideEffect.tsx +++ b/src/client/views/nodes/trails/SlideEffect.tsx @@ -1,4 +1,3 @@ -/* eslint-disable react/require-default-props */ import { animated, to, useInView, useSpring } from '@react-spring/web'; import React, { useEffect } from 'react'; import { Doc } from '../../../../fields/Doc'; diff --git a/src/client/views/pdf/AnchorMenu.tsx b/src/client/views/pdf/AnchorMenu.tsx index 18da01890..9aa8fe649 100644 --- a/src/client/views/pdf/AnchorMenu.tsx +++ b/src/client/views/pdf/AnchorMenu.tsx @@ -1,5 +1,5 @@ -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { ColorPicker, Group, IconButton, Popup, Size, Toggle, ToggleType, Type } from '@dash/components'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { IReactionDisposer, ObservableMap, action, computed, makeObservable, observable, reaction, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import * as React from 'react'; @@ -9,16 +9,16 @@ import { ClientUtils, returnFalse, setupMoveUpEvents } from '../../../ClientUtil import { emptyFunction, unimplementedFunction } from '../../../Utils'; import { Doc, Opt } from '../../../fields/Doc'; import { DocData } from '../../../fields/DocSymbols'; -import { GPTCallType, gptAPICall } from '../../apis/gpt/GPT'; import { SettingsManager } from '../../util/SettingsManager'; import { undoBatch } from '../../util/UndoManager'; import { AntimodeMenu, AntimodeMenuProps } from '../AntimodeMenu'; import { LinkPopup } from '../linking/LinkPopup'; +import { ComparisonBox } from '../nodes/ComparisonBox'; import { DocumentView } from '../nodes/DocumentView'; import { DrawingOptions, SmartDrawHandler } from '../smartdraw/SmartDrawHandler'; import './AnchorMenu.scss'; -import { GPTPopup, GPTPopupMode } from './GPTPopup/GPTPopup'; -import { ComparisonBox } from '../nodes/ComparisonBox'; +import { GPTPopup } from './GPTPopup/GPTPopup'; +import { RichTextMenu } from '../nodes/formattedText/RichTextMenu'; @observer export class AnchorMenu extends AntimodeMenu<AntimodeMenuProps> { @@ -98,15 +98,7 @@ export class AnchorMenu extends AntimodeMenu<AntimodeMenuProps> { * Invokes the API with the selected text and stores it in the summarized text. * @param e pointer down event */ - gptSummarize = () => { - GPTPopup.Instance.setVisible(true); - GPTPopup.Instance.setMode(GPTPopupMode.SUMMARY); - GPTPopup.Instance.setLoading(true); - gptAPICall(this._selectedText, GPTCallType.SUMMARY) - .then(res => GPTPopup.Instance.setText(res || 'Something went wrong.')) - .catch(err => console.error(err)) - .finally(() => GPTPopup.Instance.setLoading(false)); - }; + gptSummarize = () => GPTPopup.Instance.generateSummary(this._selectedText); /* * Transfers the flashcard text generated by GPT on flashcards and creates a collection out them. @@ -148,7 +140,7 @@ export class AnchorMenu extends AntimodeMenu<AntimodeMenuProps> { createDrawingAnnotation = action((drawing: Doc, opts: DrawingOptions, gptRes: string) => { this.AddDrawingAnnotation(drawing); const docData = drawing[DocData]; - docData.title = opts.text.match(/^(.*?)~~~.*$/)?.[1] || opts.text; + docData.title = opts.text?.match(/^(.*?)~~~.*$/)?.[1] || opts.text; docData.ai_drawing_input = opts.text; docData.ai_drawing_complexity = opts.complexity; docData.ai_drawing_colored = opts.autoColor; @@ -250,6 +242,7 @@ export class AnchorMenu extends AntimodeMenu<AntimodeMenuProps> { color={SettingsManager.userColor} /> )} + {this._selectedText && RichTextMenu.Instance?.createLinkButton()} {AnchorMenu.Instance.OnAudio === unimplementedFunction ? null : ( <IconButton tooltip="Click to Record Annotation" // diff --git a/src/client/views/pdf/GPTPopup/GPTPopup.scss b/src/client/views/pdf/GPTPopup/GPTPopup.scss index 0247dc10c..c8903e09f 100644 --- a/src/client/views/pdf/GPTPopup/GPTPopup.scss +++ b/src/client/views/pdf/GPTPopup/GPTPopup.scss @@ -4,19 +4,23 @@ $greyborder: #d3d3d3; $lightgrey: #ececec; $button: #5b97ff; $highlightedText: #82e0ff; +$inputHeight: 60px; +$headingHeight: 32px; -.summary-box { +.gptPopup-summary-box { position: fixed; top: 115px; left: 75px; - width: 250px; - height: 200px; - min-height: 200px; - min-width: 180px; - + width: 100%; + height: 100%; + top: 0; + left: 0; + pointer-events: none; + border-top: solid gray 20px; border-radius: 16px; padding: 16px; padding-bottom: 0; + padding-top: 0px; z-index: 999; display: flex; flex-direction: column; @@ -24,25 +28,20 @@ $highlightedText: #82e0ff; background-color: #ffffff; box-shadow: 0 2px 5px #7474748d; color: $textgrey; - resize: both; /* Allows resizing */ - overflow: auto; - - .resize-handle { - width: 10px; - height: 10px; - background: #ccc; - position: absolute; - right: 0; - bottom: 0; - cursor: se-resize; - } + + .gptPopup-sortBox { + display: flex; + flex-direction: column; + height: calc(100% - $inputHeight - $headingHeight); + pointer-events: all; + } .summary-heading { display: flex; justify-content: space-between; align-items: center; border-bottom: 1px solid $greyborder; - padding-bottom: 5px; + height: $headingHeight; .summary-text { font-size: 12px; @@ -63,95 +62,77 @@ $highlightedText: #82e0ff; cursor: pointer; } - .content-wrapper { + .gptPopup-content-wrapper { padding-top: 10px; min-height: 50px; - // max-height: 150px; - overflow-y: auto; - height: 100% + height: calc(100% - 32px); } - .btns-wrapper-gpt { - height: 100%; + .inputWrapper { display: flex; justify-content: center; align-items: center; - flex-direction: column; + height: $inputHeight; + background-color: white; + width: 100%; + pointer-events: all; - .inputWrapper{ - display: flex; - justify-content: center; - align-items: center; - height: 60px; - position: absolute; - bottom: 0; - width: 100%; - background-color: white; - - - } - - .searchBox-input{ + .searchBox-input { height: 40px; border-radius: 10px; - position: absolute; - bottom: 10px; + position: relative; border-color: #5b97ff; - width: 90% + width: 90%; } + } + .btns-wrapper-gpt { + height: 100%; + display: flex; + justify-content: center; + align-items: center; + flex-direction: column; .chat-wrapper { display: flex; flex-direction: column; width: 100%; - max-height: calc(100vh - 80px); + height: 100%; overflow-y: auto; - padding-bottom: 60px; + padding-right: 5px; } - + .chat-bubbles { margin-top: 20px; display: flex; flex-direction: column; flex-grow: 1; } - + .chat-bubble { padding: 10px; margin-bottom: 10px; border-radius: 10px; max-width: 60%; } - + .user-message { background-color: #283d53; align-self: flex-end; color: whitesmoke; } - + .chat-message { background-color: #367ae7; align-self: flex-start; - color:whitesmoke; + color: whitesmoke; } - - - .summarizing { display: flex; align-items: center; } - - - - - - } - - .text-btn { &:hover { background-color: $button; @@ -198,22 +179,16 @@ $highlightedText: #82e0ff; color: #666; } - - - - @keyframes spin { to { transform: rotate(360deg); } } - - .image-content-wrapper { display: flex; flex-direction: column; - align-items: flex-start; + align-items: center; gap: 8px; padding-bottom: 16px; diff --git a/src/client/views/pdf/GPTPopup/GPTPopup.tsx b/src/client/views/pdf/GPTPopup/GPTPopup.tsx index 2d95ac2eb..4dc45e6a0 100644 --- a/src/client/views/pdf/GPTPopup/GPTPopup.tsx +++ b/src/client/views/pdf/GPTPopup/GPTPopup.tsx @@ -1,324 +1,334 @@ -import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Button, IconButton, Toggle, ToggleType, Type } from '@dash/components'; -import { action, makeObservable, observable, runInAction } from 'mobx'; +import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; +import { action, makeObservable, observable, reaction } from 'mobx'; import { observer } from 'mobx-react'; import * as React from 'react'; -import { CgClose, CgCornerUpLeft } from 'react-icons/cg'; +import { AiOutlineSend } from 'react-icons/ai'; +import { CgCornerUpLeft } from 'react-icons/cg'; import ReactLoading from 'react-loading'; import { TypeAnimation } from 'react-type-animation'; import { ClientUtils } from '../../../../ClientUtils'; import { Doc } from '../../../../fields/Doc'; import { NumCast, StrCast } from '../../../../fields/Types'; import { Networking } from '../../../Network'; -import { GPTCallType, gptAPICall, gptImageCall } from '../../../apis/gpt/GPT'; +import { DescriptionSeperator, DocSeperator, GPTCallType, GPTDocCommand, gptAPICall, gptImageCall } from '../../../apis/gpt/GPT'; import { DocUtils } from '../../../documents/DocUtils'; import { Docs } from '../../../documents/Documents'; import { SettingsManager } from '../../../util/SettingsManager'; import { SnappingManager } from '../../../util/SnappingManager'; +import { undoable } from '../../../util/UndoManager'; +import { DictationButton } from '../../DictationButton'; import { ObservableReactComponent } from '../../ObservableReactComponent'; -import { DocumentView } from '../../nodes/DocumentView'; +import { TagItem } from '../../TagsView'; +import { ChatSortField, docSortings } from '../../collections/CollectionSubView'; +import { DocumentView, DocumentViewInternal } from '../../nodes/DocumentView'; +import { SmartDrawHandler } from '../../smartdraw/SmartDrawHandler'; import { AnchorMenu } from '../AnchorMenu'; import './GPTPopup.scss'; -import { isJSDocProtectedTag } from 'typescript'; +import { FireflyImageDimensions } from '../../smartdraw/FireflyConstants'; +import { Upload } from '../../../../server/SharedMediaTypes'; +import { OpenWhere } from '../../nodes/OpenWhere'; +import { DrawingFillHandler } from '../../smartdraw/DrawingFillHandler'; +import { ImageField } from '../../../../fields/URLField'; +import { List } from '../../../../fields/List'; export enum GPTPopupMode { - SUMMARY, - EDIT, - IMAGE, - FLASHCARD, + SUMMARY, // summary of seleted document text + IMAGE, // generate image from image description DATA, - CARD, - SORT, - QUIZ, -} - -export enum GPTQuizType { - CURRENT = 0, - CHOOSE = 1, - MULTIPLE = 2, + GPT_MENU, // menu for choosing type of prompts user will provide + USER_PROMPT, // user prompts for sorting,filtering and asking about docs + QUIZ_RESPONSE, // user definitions or explanations to be evaluated by GPT + FIREFLY, // firefly image generation } @observer export class GPTPopup extends ObservableReactComponent<object> { // eslint-disable-next-line no-use-before-define static Instance: GPTPopup; - private messagesEndRef: React.RefObject<HTMLDivElement>; - - @observable private chatMode: boolean = false; - private correlatedColumns: string[] = []; + static ChatTag = '#chat'; // tag used by GPT popup to filter docs + private _askDictation: DictationButton | null = null; + private _messagesEndRef: React.RefObject<HTMLDivElement>; + private _correlatedColumns: string[] = []; + private _dataChatPrompt: string | undefined = undefined; + private _imgTargetDoc: Doc | undefined; + private _textAnchor: Doc | undefined; + private _dataJson: string = ''; + private _documentDescriptions: Promise<string> | undefined; // a cache of the descriptions of all docs in the selected collection. makes it more efficient when asking GPT multiple questions about the collection. + private _sidebarFieldKey: string = ''; + private _textToSummarize: string = ''; + private _imageDescription: string = ''; + private _textToDocMap = new Map<string, Doc>(); // when GPT answers with a doc's content, this helps us find the Doc + private _addToCollection: ((doc: Doc | Doc[], annotationKey?: string | undefined) => boolean) | undefined; - @observable public Visible: boolean = false; - @action public setVisible = (vis: boolean) => { - this.Visible = vis; - }; - @observable public loading: boolean = false; - @action public setLoading = (loading: boolean) => { - this.loading = loading; - }; - @observable public text: string = ''; - @action public setText = (text: string) => { - this.text = text; - }; - @observable public selectedText: string = ''; - @action public setSelectedText = (text: string) => { - this.selectedText = text; - }; - @observable public dataJson: string = ''; - public dataChatPrompt: string | undefined = undefined; - @action public setDataJson = (text: string) => { - if (text === '') this.dataChatPrompt = ''; - this.dataJson = text; - }; - - @observable public imgDesc: string = ''; - @action public setImgDesc = (text: string) => { - this.imgDesc = text; - }; - - @observable public imgUrls: string[][] = []; - @action public setImgUrls = (imgs: string[][]) => { - this.imgUrls = imgs; - }; - - @observable public mode: GPTPopupMode = GPTPopupMode.SUMMARY; - @action public setMode = (mode: GPTPopupMode) => { - this.mode = mode; - }; - - @observable public highlightRange: number[] = []; - @action callSummaryApi = () => {}; - - @observable private done: boolean = false; - @action public setDone = (done: boolean) => { - this.done = done; - this.chatMode = false; - }; - - // change what can be a ref into a ref - @observable private sidebarId: string = ''; - @action public setSidebarId = (id: string) => { - this.sidebarId = id; - }; - - @observable private imgTargetDoc: Doc | undefined; - @action public setImgTargetDoc = (anchor: Doc) => { - this.imgTargetDoc = anchor; - }; - - @observable private textAnchor: Doc | undefined; - @action public setTextAnchor = (anchor: Doc) => { - this.textAnchor = anchor; - }; + constructor(props: object) { + super(props); + makeObservable(this); + GPTPopup.Instance = this; + this._messagesEndRef = React.createRef(); + } - @observable public sortDesc: string = ''; - @action public setSortDesc = (t: string) => { - this.sortDesc = t; + public addDoc: ((doc: Doc | Doc[], sidebarKey?: string | undefined) => boolean) | undefined; + public createFilteredDoc: (axes?: string[]) => boolean = () => false; + public setSidebarFieldKey = (id: string) => (this._sidebarFieldKey = id); + public setImgTargetDoc = (anchor: Doc) => (this._imgTargetDoc = anchor); + public setTextAnchor = (anchor: Doc) => (this._textAnchor = anchor); + public setDataJson = (text: string) => { + if (text === '') this._dataChatPrompt = ''; + this._dataJson = text; }; - onSortComplete?: (sortResult: string, questionType: string, tag?: string) => void; - onQuizRandom?: () => void; - - @observable collectionDoc: Doc | undefined = undefined; - @action setCollectionDoc(doc: Doc | undefined) { - this.collectionDoc = doc; + componentDidUpdate() { + this._gptProcessing && this.setStopAnimatingResponse(false); } - - @observable sortRespText: string = ''; - - @action setSortRespText(resp: string) { - this.sortRespText = resp; + componentDidMount(): void { + reaction( + () => ({ selDoc: DocumentView.Selected().lastElement(), visible: SnappingManager.ChatVisible }), + ({ selDoc, visible }) => { + const hasChildDocs = visible && selDoc?.ComponentView?.hasChildDocs; + if (hasChildDocs) { + this._textToDocMap.clear(); + this.setCollectionContext(selDoc.Document); + this.onGptResponse = (sortResult: string, questionType: GPTDocCommand, args?: string) => this.processGptResponse(selDoc, this._textToDocMap, sortResult, questionType, args); + this.onQuizRandom = () => this.randomlyChooseDoc(selDoc.Document, hasChildDocs()); + this._documentDescriptions = Promise.all(hasChildDocs().map(doc => + Doc.getDescription(doc).then(text => this._textToDocMap.set(text.trim(), doc) && `${DescriptionSeperator}${text}${DescriptionSeperator}`) + )).then(docDescriptions => docDescriptions.join()); // prettier-ignore + } + }, + { fireImmediately: true } + ); } - @observable chatSortPrompt: string = ''; + @observable private _conversationArray: string[] = ['Hi! In this pop up, you can ask ChatGPT questions about your documents and filter / sort them. ']; + @observable private _fireflyArray: string[] = ['Hi! In this pop up, you can ask Firefly to create images. ']; + @observable private _chatEnabled: boolean = false; + @action private setChatEnabled = (start: boolean) => (this._chatEnabled = start); + @observable private _gptProcessing: boolean = false; + @action private setGptProcessing = (loading: boolean) => (this._gptProcessing = loading); + @observable private _responseText: string = ''; + @action private setResponseText = (text: string) => (this._responseText = text); + @observable private _imgUrls: string[][] = []; + @action private setImgUrls = (imgs: string[][]) => (this._imgUrls = imgs); + @observable private _collectionContext: Doc | undefined = undefined; + @action setCollectionContext = (doc: Doc | undefined) => (this._collectionContext = doc); + @observable private _userPrompt: string = ''; + @action setUserPrompt = (e: string) => (this._userPrompt = e); + @observable private _quizAnswer: string = ''; + @action setQuizAnswer = (e: string) => (this._quizAnswer = e); + @observable private _stopAnimatingResponse: boolean = false; + @action private setStopAnimatingResponse = (done: boolean) => (this._stopAnimatingResponse = done); + + @observable private _mode: GPTPopupMode = GPTPopupMode.SUMMARY; + @action public setMode = (mode: GPTPopupMode) => (this._mode = mode); - sortPromptChanged = action((e: React.ChangeEvent<HTMLInputElement>) => { - this.chatSortPrompt = e.target.value; - }); - - @observable quizAnswer: string = ''; - - quizAnswerChanged = action((e: React.ChangeEvent<HTMLInputElement>) => { - this.quizAnswer = e.target.value; - }); - - @observable conversationArray: string[] = ['Hi! In this pop up, you can ask ChatGPT questions about your documents and filter / sort them. ']; + onQuizRandom?: () => void; + onGptResponse?: (sortResult: string, questionType: GPTDocCommand, args?: string) => void; + NumberToCommandType = (questionType: string) => +questionType.split(' ')[0][0]; /** - * When the cards are in quiz mode in the card view, allows gpt to determine whether the user's answer was correct - * @returns + * Processes gpt's output depending on the type of question the user asked. Converts gpt's string output to + * usable code + * @param gptOutput + * @param questionType + * @param tag */ - generateQuiz = (selected: Doc) => - (this.regenerateCallback?.() ?? Promise.resolve()).then(() => - this.generateRubric(selected).then(() => - gptAPICall('Question: ' + StrCast(selected.gptInputText) + ' UserAnswer: ' + this.quizAnswer + '. Rubric: ' + StrCast(selected.gptRubric), GPTCallType.QUIZ) - .then(res => { - if (res) { - this.setQuizResp(res); - this.conversationArray.push(res); - this.onQuizRandom?.(); - } else { - console.error('GPT provided no response'); - } - }) - .catch(err => console.error('GPT call failed', err)) - ) - ); + processGptResponse = (docView: DocumentView, textToDocMap: Map<string, Doc>, gptOutput: string, questionType: GPTDocCommand, args?: string) => + undoable(() => { + switch (questionType) { // reset collection based on question typefc + case GPTDocCommand.Sort: + docView.Document[docView.ComponentView?.fieldKey + '_sort'] = docSortings.Chat; + break; + case GPTDocCommand.Filter: + docView.ComponentView?.hasChildDocs?.().forEach(d => TagItem.removeTagFromDoc(d, GPTPopup.ChatTag)); + break; + } // prettier-ignore + + gptOutput.split('======').filter(item => item.trim() !== '') // Split output into individual document contents + .map(docContentRaw => textToDocMap.get(docContentRaw.replace(/\n/g, ' ').trim())) // the find the corresponding Doc using textToDoc map + .filter(doc => doc).map(doc => doc!) // filter out undefined values + .forEach((doc, index) => { + switch (questionType) { + case GPTDocCommand.Sort: + doc[ChatSortField] = index; + break; + case GPTDocCommand.AssignTags: + if (args) { + const hashTag = args.startsWith('#') ? args : '#' + args[0].toLowerCase() + args.slice(1); + const filterTag = Doc.MyFilterHotKeys.map(key => StrCast(key.toolType)).find(key => key.includes(args)) ?? hashTag; + TagItem.addTagToDoc(doc, filterTag); + } + break; + case GPTDocCommand.Filter: + TagItem.addTagToDoc(doc, GPTPopup.ChatTag); + Doc.setDocFilter(docView.Document, 'tags', GPTPopup.ChatTag, 'check'); + break; + } + }); // prettier-ignore + }, '')(); /** - * Generates a rubric by which to compare the user's answer to - * @param inputText user's answer + * When in quiz mode, randomly selects a document + */ + randomlyChooseDoc = (doc: Doc, childDocs: Doc[]) => DocumentView.getDocumentView(childDocs[Math.floor(Math.random() * childDocs.length)])?.select(false); + /** + * Generates a rubric for evaluating the user's description of the document's text * @param doc the doc the user is providing info about - * @returns gpt's response + * @returns gpt's response rubric */ generateRubric = (doc: Doc) => StrCast(doc.gptRubric) ? Promise.resolve(StrCast(doc.gptRubric)) - : gptAPICall(StrCast(doc.gptInputText), GPTCallType.RUBRIC) - .then(res => (doc.gptRubric = res)) - .catch(err => console.error('GPT call failed', err)); - - @observable private regenerateCallback: (() => Promise<void>) | null = null; - - /** - * Callback function that causes the card view to update the childpair string list - * @param callback - */ - @action public setRegenerateCallback(collectionDoc: Doc | undefined, callback: null | (() => Promise<void>)) { - this.setCollectionDoc(collectionDoc); - this.regenerateCallback = callback; - } - - public addDoc: (doc: Doc | Doc[], sidebarKey?: string | undefined) => boolean = () => false; - public createFilteredDoc: (axes?: string[]) => boolean = () => false; - public addToCollection: ((doc: Doc | Doc[], annotationKey?: string | undefined) => boolean) | undefined; - - @observable quizRespText: string = ''; - - @action setQuizResp(resp: string) { - this.quizRespText = resp; - } + : Doc.getDescription(doc).then(desc => + gptAPICall(desc, GPTCallType.MAKERUBRIC) + .then(res => (doc.gptRubric = res)) + .catch(err => console.error('GPT call failed', err)) + ); /** - * Generates a response to the user's question depending on the type of their question + * When the cards are in quiz mode in the card view, allows gpt to determine whether the user's answer was correct + * @param doc the doc the user is providing info about + * @param quizAnswer the user's answer/description for the document + * @returns */ - generateCard = async () => { - this.setLoading(true); - - await this.regenerateCallback?.(); - - try { - const questionType = await gptAPICall(this.chatSortPrompt, GPTCallType.TYPE); - const questionNumber = questionType.split(' ')[0][0]; - const res = await (() => { - switch (questionNumber) { - case '1': - case '2': - case '4': return gptAPICall(this.sortDesc, GPTCallType.SUBSET, this.chatSortPrompt); - case '6': return gptAPICall(this.sortDesc, GPTCallType.SORT, this.chatSortPrompt); - default: return gptAPICall(StrCast(DocumentView.SelectedDocs().lastElement()?.gptInputText), GPTCallType.INFO, this.chatSortPrompt); - }})(); // prettier-ignore - - // Trigger the callback with the result - if (this.onSortComplete) { - this.onSortComplete(res || 'Something went wrong :(', questionNumber, questionType.split(' ').slice(1).join(' ')); - - let explanation = res; - - if (questionType != '5' && questionType != '3') { - // Extract explanation surrounded by ------ at the top or both at the top and bottom - const explanationMatch = res.match(/------\s*([\s\S]*?)\s*(?:------|$)/) || []; - explanation = explanationMatch[1] ? explanationMatch[1].trim() : 'No explanation found'; - } - - // Set the extracted explanation to sortRespText - this.setSortRespText(explanation); - runInAction(() => this.conversationArray.push(this.sortRespText)); - this.scrollToBottom(); - - console.log(res); - } - } catch (err) { - console.error(err); + generateQuizAnswerAnalysis = (doc: Doc, quizAnswer: string) => + this.generateRubric(doc).then(() => + Doc.getDescription(doc).then(desc => + gptAPICall( + `Question: ${desc}; + UserAnswer: ${quizAnswer}; + Rubric: ${StrCast(doc.gptRubric)}`, + GPTCallType.QUIZDOC + ).then(res => { + this._conversationArray.push(res || 'GPT provided no answer'); + this.onQuizRandom?.(); + }) + .catch(err => console.error('GPT call failed', err)) + )) // prettier-ignore + + generateFireflyImage = (imgDesc: string) => { + const selView = DocumentView.Selected().lastElement(); + const selDoc = selView?.Document; + if (selDoc && (selView._props.renderDepth > 1 || selDoc[Doc.LayoutFieldKey(selDoc)] instanceof ImageField)) { + const oldPrompt = StrCast(selDoc.ai_firefly_prompt, StrCast(selDoc.title)); + const newPrompt = oldPrompt ? `${oldPrompt} ~~~ ${imgDesc}` : imgDesc; + return DrawingFillHandler.drawingToImage(selDoc, 100, newPrompt, selDoc) + .then(action(() => (this._userPrompt = ''))) + .catch(e => { + alert(e); + return undefined; + }); } - - this.setLoading(false); + return SmartDrawHandler.CreateWithFirefly(imgDesc, FireflyImageDimensions.Square, 0) + .then( + action(doc => { + doc instanceof Doc && DocumentViewInternal.addDocTabFunc(doc, OpenWhere.addRight); + this._userPrompt = ''; + }) + ) + .catch(e => { + alert(e); + return undefined; + }); }; + /** + * Generates a response to the user's question about the docs in the collection. + * The type of response depends on the chat's analysis of the type of their question + * @param userPrompt the user's input that chat will respond to + */ + generateUserPromptResponse = (userPrompt: string) => + gptAPICall(userPrompt, GPTCallType.COMMANDTYPE, undefined, true).then((commandType, args = commandType.split(' ').slice(1).join(' ')) => + (async () => { + switch (this.NumberToCommandType(commandType)) { + case GPTDocCommand.AssignTags: + case GPTDocCommand.Filter: return this._documentDescriptions?.then(descs => gptAPICall(userPrompt, GPTCallType.SUBSETDOCS, descs)) ?? ""; + case GPTDocCommand.Sort: return this._documentDescriptions?.then(descs => gptAPICall(userPrompt, GPTCallType.SORTDOCS, descs)) ?? ""; + default: return Doc.getDescription(DocumentView.SelectedDocs().lastElement()).then(desc => gptAPICall(userPrompt, GPTCallType.DOCINFO, desc)); + } // prettier-ignore + })().then( + action(res => { + // Trigger the callback with the result + this.onGptResponse?.(res || 'Something went wrong :(', this.NumberToCommandType(commandType), args); + this._conversationArray.push( + this.NumberToCommandType(commandType) === GPTDocCommand.GetInfo ? res: + // Extract explanation surrounded by the DocSeperator string (defined in GPT.ts) at the top or both at the top and bottom + (res.match(new RegExp(`${DocSeperator}\\s*([\\s\\S]*?)\\s*(?:${DocSeperator}|$)`)) ?? [])[1]?.trim() ?? 'No explanation found' + ); + }) + ).catch(err => console.log(err)) + ).catch(err => console.log(err)); // prettier-ignore /** * Generates a Dalle image and uploads it to the server. */ - generateImage = async () => { - if (this.imgDesc === '') return undefined; + generateImage = (imgDesc: string, imgTarget: Doc, addToCollection?: (doc: Doc | Doc[], annotationKey?: string | undefined) => boolean) => { + this._imgTargetDoc = imgTarget; + SnappingManager.SetChatVisible(true); + this.addDoc = addToCollection; this.setImgUrls([]); this.setMode(GPTPopupMode.IMAGE); - this.setVisible(true); - this.setLoading(true); - - try { - const imageUrls = await gptImageCall(this.imgDesc); - if (imageUrls && imageUrls[0]) { - const [result] = await Networking.PostToServer('/uploadRemoteImage', { sources: [imageUrls[0]] }); - const source = ClientUtils.prepend(result.accessPaths.agnostic.client); - this.setImgUrls([[imageUrls[0], source]]); - } - } catch (err) { - console.error(err); - } - this.setLoading(false); - return undefined; + this.setGptProcessing(true); + this._imageDescription = imgDesc; + + return gptImageCall(imgDesc) + .then(imageUrls => + imageUrls?.[0] + ? Networking.PostToServer('/uploadRemoteImage', { sources: [imageUrls[0]] }).then(res => { + const source = ClientUtils.prepend((res as Upload.FileInformation[])[0].accessPaths.agnostic.client); + return this.setImgUrls([[imageUrls[0]!, source]]); + }) + : undefined + ) + .catch(err => console.error(err)) + .finally(() => this.setGptProcessing(false)); }; /** - * Completes an API call to generate a summary of - * this.selectedText in the popup. + * Completes an API call to generate a summary of the specified text + * + * @param text the text to summarizz */ - generateSummary = async () => { - GPTPopup.Instance.setVisible(true); - GPTPopup.Instance.setMode(GPTPopupMode.SUMMARY); - GPTPopup.Instance.setLoading(true); - - try { - const res = await gptAPICall(this.selectedText, GPTCallType.SUMMARY); - GPTPopup.Instance.setText(res || 'Something went wrong.'); - } catch (err) { - console.error(err); - } - GPTPopup.Instance.setLoading(false); + generateSummary = (text: string) => { + SnappingManager.SetChatVisible(true); + this._textToSummarize = text; + this.setMode(GPTPopupMode.SUMMARY); + this.setGptProcessing(true); + return gptAPICall(text, GPTCallType.SUMMARY) + .then(res => this.setResponseText(res || 'Something went wrong.')) + .catch(err => console.error(err)) + .finally(() => this.setGptProcessing(false)); }; /** * Completes an API call to generate an analysis of * this.dataJson in the popup. */ - generateDataAnalysis = async () => { - GPTPopup.Instance.setVisible(true); - GPTPopup.Instance.setLoading(true); - try { - const res = await gptAPICall(this.dataJson, GPTCallType.DATA, this.dataChatPrompt); - const json = JSON.parse(res! as string); - const keys = Object.keys(json); - this.correlatedColumns = []; - this.correlatedColumns.push(json[keys[0]]); - this.correlatedColumns.push(json[keys[1]]); - GPTPopup.Instance.setText(json[keys[2]] || 'Something went wrong.'); - } catch (err) { - console.error(err); - } - GPTPopup.Instance.setLoading(false); + generateDataAnalysis = () => { + this.setGptProcessing(true); + return gptAPICall(this._dataJson, GPTCallType.DATA, this._dataChatPrompt) + .then(res => { + const json = JSON.parse(res! as string); + const keys = Object.keys(json); + this._correlatedColumns = []; + this._correlatedColumns.push(json[keys[0]]); + this._correlatedColumns.push(json[keys[1]]); + this.setResponseText(json[keys[2]] || 'Something went wrong.'); + }) + .catch(err => console.error(err)) + .finally(() => this.setGptProcessing(false)); }; /** * Transfers the summarization text to a sidebar annotation text document. */ private transferToText = () => { - const newDoc = Docs.Create.TextDocument(this.text.trim(), { + const newDoc = Docs.Create.TextDocument(this._responseText.trim(), { _width: 200, _height: 50, _layout_fitWidth: true, _layout_autoHeight: true, }); - this.addDoc(newDoc, this.sidebarId); - // newDoc.data = 'Hello world'; + this.addDoc?.(newDoc, this._sidebarFieldKey); const anchor = AnchorMenu.Instance?.GetAnchor(undefined, false); if (anchor) { DocUtils.MakeLink(newDoc, anchor, { @@ -330,80 +340,44 @@ export class GPTPopup extends ObservableReactComponent<object> { /** * Creates a histogram to show the correlation relationship that was found */ - private createVisualization = () => { - this.createFilteredDoc(this.correlatedColumns); - }; + private createVisualization = () => this.createFilteredDoc(this._correlatedColumns); /** * Transfers the image urls to actual image docs */ private transferToImage = (source: string) => { - const textAnchor = this.textAnchor ?? this.imgTargetDoc; - if (!textAnchor) return; - const newDoc = Docs.Create.ImageDocument(source, { - x: NumCast(textAnchor.x) + NumCast(textAnchor._width) + 10, - y: NumCast(textAnchor.y), - _height: 200, - _width: 200, - data_nativeWidth: 1024, - data_nativeHeight: 1024, - }); - if (Doc.IsInMyOverlay(textAnchor)) { - newDoc.overlayX = textAnchor.x; - newDoc.overlayY = NumCast(textAnchor.y) + NumCast(textAnchor._height); - Doc.AddToMyOverlay(newDoc); - } else { - this.addToCollection?.(newDoc); - } - // Create link between prompt and image - DocUtils.MakeLink(textAnchor, newDoc, { link_relationship: 'Image Prompt' }); - }; - - /** - * Creates a chatbox for analyzing data so that users can ask specific questions. - */ - private chatWithAI = () => { - this.chatMode = true; - }; - dataPromptChanged = action((e: React.ChangeEvent<HTMLInputElement>) => { - this.dataChatPrompt = e.target.value; - }); - - private getPreviewUrl = (source: string) => source.split('.').join('_m.'); - - constructor(props: object) { - super(props); - makeObservable(this); - GPTPopup.Instance = this; - this.messagesEndRef = React.createRef(); - } - - scrollToBottom = () => { - setTimeout(() => { - // Code to execute after 1 second (1000 ms) - if (this.messagesEndRef.current) { - this.messagesEndRef.current.scrollIntoView({ behavior: 'smooth', block: 'end' }); + const textAnchor = this._textAnchor ?? this._imgTargetDoc; + if (textAnchor) { + const newDoc = Docs.Create.ImageDocument(source, { + x: NumCast(textAnchor.x) + NumCast(textAnchor._width) + 10, + y: NumCast(textAnchor.y), + _height: 200, + _width: 200, + ai: 'dall-e', + tags: new List<string>(['@ai']), + data_nativeWidth: 1024, + data_nativeHeight: 1024, + }); + if (Doc.IsInMyOverlay(textAnchor)) { + newDoc.overlayX = textAnchor.x; + newDoc.overlayY = NumCast(textAnchor.y) + NumCast(textAnchor._height); + Doc.AddToMyOverlay(newDoc); + } else { + this.addDoc?.(newDoc); } - }, 50); - }; - - componentDidUpdate = () => { - if (this.loading) { - this.setDone(false); + // Create link between prompt and image + DocUtils.MakeLink(textAnchor, newDoc, { link_relationship: 'Image Prompt' }); } }; - @observable quizMode: GPTQuizType = GPTQuizType.CURRENT; - @action setQuizMode(g: GPTQuizType) { - this.quizMode = g; - } + scrollToBottom = () => setTimeout(() => this._messagesEndRef.current?.scrollIntoView({ behavior: 'smooth', block: 'end' }), 50); - cardMenu = () => ( + gptMenu = () => ( <div className="btns-wrapper-gpt"> <Button - tooltip="Have ChatGPT sort, tag, define, or filter your cards for you!" - text="Modify/Sort Cards!" - onClick={() => this.setMode(GPTPopupMode.SORT)} + tooltip="Ask Firefly to create images" + text="Ask Firefly" + onClick={() => this.setMode(GPTPopupMode.FIREFLY)} color={StrCast(Doc.UserDoc().userVariantColor)} type={Type.TERT} style={{ @@ -416,152 +390,183 @@ export class GPTPopup extends ObservableReactComponent<object> { }} /> <Button - tooltip="Test your knowledge with ChatGPT!" - text="Quiz Cards!" + tooltip="Ask GPT to sort, tag, define, or filter your Docs!" + text="Ask GPT" + onClick={() => this.setMode(GPTPopupMode.USER_PROMPT)} + color={StrCast(Doc.UserDoc().userVariantColor)} + type={Type.TERT} + style={{ + width: '100%', + height: '40%', + textAlign: 'center', + color: '#ffffff', + fontSize: '16px', + marginBottom: '10px', + }} + /> + <Button + tooltip="Test your knowledge by verifying answers with ChatGPT" + text="Take Quiz" onClick={() => { - this.conversationArray = ['Define the selected card!']; - this.setMode(GPTPopupMode.QUIZ); + this._conversationArray = ['Define the selected card!']; + this.setMode(GPTPopupMode.QUIZ_RESPONSE); this.onQuizRandom?.(); }} color={StrCast(Doc.UserDoc().userVariantColor)} type={Type.TERT} style={{ width: '100%', + height: '40%', textAlign: 'center', color: '#ffffff', fontSize: '16px', - height: '40%', }} /> </div> ); + callGpt = action((mode: GPTPopupMode) => { + this.setGptProcessing(true); + switch (mode) { + case GPTPopupMode.FIREFLY: + this._fireflyArray.push(this._userPrompt); + return this.generateFireflyImage(this._userPrompt).then(action(() => (this._userPrompt = ''))); + case GPTPopupMode.USER_PROMPT: + this._conversationArray.push(this._userPrompt); + return this.generateUserPromptResponse(this._userPrompt).then(action(() => (this._userPrompt = ''))); + case GPTPopupMode.QUIZ_RESPONSE: + this._conversationArray.push(this._quizAnswer); + return this.generateQuizAnswerAnalysis(DocumentView.SelectedDocs().lastElement(), this._quizAnswer).then(action(() => (this._quizAnswer = ''))); + } + }); + @action - handleKeyPress = (e: React.KeyboardEvent, isSort: boolean) => { + handleKeyPress = async (e: React.KeyboardEvent, mode: GPTPopupMode) => { + this._askDictation?.stopDictation(); if (e.key === 'Enter') { e.stopPropagation(); - if (isSort) { - this.conversationArray.push(this.chatSortPrompt); - this.generateCard().then( - action(() => { - this.chatSortPrompt = ''; - }) - ); - } else { - this.conversationArray.push(this.quizAnswer); - this.setLoading(true); - this.generateQuiz(DocumentView.SelectedDocs().lastElement()).then( - action(() => { - this.quizAnswer = ''; - this.setLoading(false); - }) - ); - } - - this.scrollToBottom(); + this.callGpt(mode)?.then(() => { + this.setGptProcessing(false); + this.scrollToBottom(); + }); } }; - cardActual = (isSort: boolean) => ( + gptUserInput = () => ( <div className="btns-wrapper-gpt"> <div className="chat-wrapper"> <div className="chat-bubbles"> - {this.conversationArray.map((message, index) => ( + {(this._mode === GPTPopupMode.FIREFLY ? this._fireflyArray : this._conversationArray).map((message, index) => ( <div key={index} className={`chat-bubble ${index % 2 === 1 ? 'user-message' : 'chat-message'}`}> {message} </div> ))} - {this.loading && <div className={`chat-bubble chat-message`}>...</div>} + {this._gptProcessing && <div className="chat-bubble chat-message">...</div>} </div> - <div ref={this.messagesEndRef} style={{ height: '100px' }} /> + <div ref={this._messagesEndRef} style={{ height: '100px' }} /> + </div> + </div> + ); + + promptBox = (heading: string, value: string, onChange: (e: string) => string, placeholder: string) => ( + <> + <div className="gptPopup-sortBox"> + {this.heading(heading)} + {this.gptUserInput()} </div> <div className="inputWrapper"> <input className="searchBox-input" - defaultValue="" - value={isSort ? this.chatSortPrompt : this.quizAnswer} // Controlled input + value={value} // Controlled input autoComplete="off" - onChange={isSort ? this.sortPromptChanged : this.quizAnswerChanged} - onKeyDown={e => { - this.handleKeyPress(e, isSort); - }} + onChange={e => onChange(e.target.value)} + onKeyDown={e => this.handleKeyPress(e, this._mode)} type="text" - placeholder={`${isSort ? 'Have ChatGPT sort, tag, define, or filter your cards for you!' : 'Define the selected card!'}`} + placeholder={placeholder} /> + <Button // + text="Send" + type={Type.TERT} + icon={<AiOutlineSend />} + iconPlacement="right" + color={SnappingManager.userVariantColor} + onClick={() => this.callGpt(this._mode)} + /> + <DictationButton ref={r => (this._askDictation = r)} setInput={onChange} /> </div> - </div> + </> ); - sortBox = (isSort: boolean) => ( - <div className="gptPopup-sortBox" style={{ height: '80%' }}> - {this.heading(isSort ? 'SORTING' : 'QUIZ')} - {this.mode === GPTPopupMode.CARD ? this.cardMenu() : this.cardActual(isSort)} + menuBox = () => ( + <div className="gptPopup-sortBox"> + {this.heading('CHOOSE')} + {this.gptMenu()} </div> ); imageBox = () => ( - <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem' }}> + <div style={{ display: 'flex', flexDirection: 'column', gap: '1rem', overflow: 'auto', height: '100%', pointerEvents: 'all' }}> {this.heading('GENERATED IMAGE')} <div className="image-content-wrapper"> - {this.imgUrls.map((rawSrc, i) => ( - <div key={rawSrc[0] + i} className="img-wrapper"> - <div className="img-container"> - <img key={rawSrc[0]} src={rawSrc[0]} width={150} height={150} alt="dalle generation" /> + {this._imgUrls.map((rawSrc, i) => ( + <> + <div key={rawSrc[0] + i} className="img-wrapper"> + <div className="img-container"> + <img key={rawSrc[0]} src={rawSrc[0]} width={150} height={150} alt="dalle generation" /> + </div> </div> - <div className="btn-container"> + <div key={rawSrc[0] + i + 'btn'} className="btn-container"> <Button text="Save Image" onClick={() => this.transferToImage(rawSrc[1])} color={StrCast(Doc.UserDoc().userColor)} type={Type.TERT} /> </div> - </div> + </> ))} </div> - {!this.loading && <IconButton tooltip="Generate Again" onClick={this.generateImage} icon={<FontAwesomeIcon icon="redo-alt" size="lg" />} color={StrCast(Doc.UserDoc().userVariantColor)} />} + {this._gptProcessing ? null : ( + <IconButton + tooltip="Generate Again" + onClick={() => this._imgTargetDoc && this.generateImage(this._imageDescription, this._imgTargetDoc, this._addToCollection)} + icon={<FontAwesomeIcon icon="redo-alt" size="lg" />} + color={StrCast(Doc.UserDoc().userVariantColor)} + /> + )} </div> ); summaryBox = () => ( <> - <div> + <div style={{ height: 'calc(100% - 60px)', overflow: 'auto' }}> {this.heading('SUMMARY')} - <div className="content-wrapper"> - {!this.loading && - (!this.done ? ( + <div className="gptPopup-content-wrapper"> + {!this._gptProcessing && + (!this._stopAnimatingResponse ? ( <TypeAnimation speed={50} sequence={[ - this.text, + this._responseText, () => { - setTimeout(() => { - this.setDone(true); - }, 500); + setTimeout(() => this.setStopAnimatingResponse(true), 500); }, ]} /> ) : ( - this.text + this._responseText ))} </div> </div> - {!this.loading && ( - <div className="btns-wrapper"> - {this.done ? ( + {!this._gptProcessing && ( + <div className="btns-wrapper" style={{ position: 'absolute', bottom: 0, width: 'calc(100% - 32px)' }}> + {this._stopAnimatingResponse ? ( <> - <IconButton tooltip="Generate Again" onClick={this.generateSummary /* this.callSummaryApi */} icon={<FontAwesomeIcon icon="redo-alt" size="lg" />} color={StrCast(SettingsManager.userVariantColor)} /> + <IconButton tooltip="Generate Again" onClick={() => this.generateSummary(this._textToSummarize + ' ')} icon={<FontAwesomeIcon icon="redo-alt" size="lg" />} color={StrCast(SettingsManager.userVariantColor)} /> <Button tooltip="Transfer to text" text="Transfer To Text" onClick={this.transferToText} color={StrCast(SettingsManager.userVariantColor)} type={Type.TERT} /> </> ) : ( <div className="summarizing"> <span>Summarizing</span> <ReactLoading type="bubbles" color="#bcbcbc" width={20} height={20} /> - <Button - text="Stop Animation" - onClick={() => { - this.setDone(true); - }} - color={StrCast(SettingsManager.userVariantColor)} - type={Type.TERT} - /> + <Button text="Stop Animation" onClick={() => this.setStopAnimatingResponse(true)} color={StrCast(SettingsManager.userVariantColor)} type={Type.TERT} /> </div> )} </div> @@ -573,33 +578,31 @@ export class GPTPopup extends ObservableReactComponent<object> { <> <div> {this.heading('ANALYSIS')} - <div className="content-wrapper"> - {!this.loading && - (!this.done ? ( + <div className="gptPopup-content-wrapper"> + {!this._gptProcessing && + (!this._stopAnimatingResponse ? ( <TypeAnimation speed={50} sequence={[ - this.text, + this._responseText, () => { - setTimeout(() => { - this.setDone(true); - }, 500); + setTimeout(() => this.setStopAnimatingResponse(true), 500); }, ]} /> ) : ( - this.text + this._responseText ))} </div> </div> - {!this.loading && ( + {!this._gptProcessing && ( <div className="btns-wrapper"> - {this.done ? ( - this.chatMode ? ( + {this._stopAnimatingResponse ? ( + this._chatEnabled ? ( <input defaultValue="" autoComplete="off" - onChange={this.dataPromptChanged} + onChange={e => (this._dataChatPrompt = e.target.value)} onKeyDown={e => { e.key === 'Enter' ? this.generateDataAnalysis() : null; e.stopPropagation(); @@ -613,21 +616,14 @@ export class GPTPopup extends ObservableReactComponent<object> { ) : ( <> <Button tooltip="Transfer to text" text="Transfer To Text" onClick={this.transferToText} color={StrCast(SnappingManager.userVariantColor)} type={Type.TERT} /> - <Button tooltip="Chat with AI" text="Chat with AI" onClick={this.chatWithAI} color={StrCast(SnappingManager.userVariantColor)} type={Type.TERT} /> + <Button tooltip="Chat with AI" text="Chat with AI" onClick={() => this.setChatEnabled(true)} color={StrCast(SnappingManager.userVariantColor)} type={Type.TERT} /> </> ) ) : ( <div className="summarizing"> <span>Summarizing</span> <ReactLoading type="bubbles" color="#bcbcbc" width={20} height={20} /> - <Button - text="Stop Animation" - onClick={() => { - this.setDone(true); - }} - color={StrCast(SnappingManager.userVariantColor)} - type={Type.TERT} - /> + <Button text="Stop Animation" onClick={() => this.setStopAnimatingResponse(true)} color={StrCast(SnappingManager.userVariantColor)} type={Type.TERT} /> </div> )} </div> @@ -636,71 +632,53 @@ export class GPTPopup extends ObservableReactComponent<object> { ); aiWarning = () => - this.done ? ( + !this._stopAnimatingResponse ? null : ( <div className="ai-warning"> <FontAwesomeIcon icon="exclamation-circle" size="sm" style={{ paddingRight: '5px' }} /> AI generated responses can contain inaccurate or misleading content. </div> - ) : null; + ); heading = (headingText: string) => ( <div className="summary-heading"> <label className="summary-text">{headingText}</label> - {this.loading ? ( + {this._gptProcessing ? ( <ReactLoading type="spin" color="#bcbcbc" width={14} height={14} /> ) : ( <> - {(this.mode === GPTPopupMode.SORT || this.mode === GPTPopupMode.QUIZ) && ( - <IconButton color={StrCast(SettingsManager.userVariantColor)} tooltip="back" icon={<CgCornerUpLeft size="16px" />} onClick={() => (this.mode = GPTPopupMode.CARD)} style={{ right: '50px', position: 'absolute' }} /> - )} <Toggle tooltip="Clear Chat filter" toggleType={ToggleType.BUTTON} type={Type.PRIM} - toggleStatus={Doc.hasDocFilter(this.collectionDoc, 'tags', '#chat')} - text={Doc.hasDocFilter(this.collectionDoc, 'tags', '#chat') ? 'filtered' : ''} - color="red" - onClick={() => this.collectionDoc && Doc.setDocFilter(this.collectionDoc, 'tags', '#chat', 'remove')} - /> - <IconButton - color={StrCast(SettingsManager.userVariantColor)} - tooltip="close" - icon={<CgClose size="16px" />} - onClick={() => { - this.setVisible(false); - }} + toggleStatus={Doc.hasDocFilter(this._collectionContext, 'tags', GPTPopup.ChatTag)} + text={Doc.hasDocFilter(this._collectionContext, 'tags', GPTPopup.ChatTag) ? 'filtered' : ''} + color={Doc.hasDocFilter(this._collectionContext, 'tags', GPTPopup.ChatTag) ? 'red' : 'transparent'} + onClick={() => this._collectionContext && Doc.setDocFilter(this._collectionContext, 'tags', GPTPopup.ChatTag, 'remove')} /> + {[GPTPopupMode.USER_PROMPT, GPTPopupMode.QUIZ_RESPONSE, GPTPopupMode.FIREFLY].includes(this._mode) && ( + <IconButton color={StrCast(SettingsManager.userVariantColor)} tooltip="back" icon={<CgCornerUpLeft size="16px" />} onClick={() => (this._mode = GPTPopupMode.GPT_MENU)} /> + )} </> )} </div> ); render() { - let content; - - switch (this.mode) { - case GPTPopupMode.SUMMARY: - content = this.summaryBox(); - break; - case GPTPopupMode.DATA: - content = this.dataAnalysisBox(); - break; - case GPTPopupMode.IMAGE: - content = this.imageBox(); - break; - case GPTPopupMode.SORT: - case GPTPopupMode.CARD: - case GPTPopupMode.QUIZ: - content = this.sortBox(this.mode === GPTPopupMode.SORT); - break; - default: - content = null; - } - return ( - <div className="summary-box" style={{ display: this.Visible ? 'flex' : 'none' }}> - {content} - <div className="resize-handle" /> + <div className="gptPopup-summary-box" style={{ display: SnappingManager.ChatVisible ? 'flex' : 'none', overflow: 'auto' }}> + {(() => { + //prettier-ignore + switch (this._mode) { + case GPTPopupMode.USER_PROMPT: return this.promptBox("ASK", this._userPrompt, this.setUserPrompt, 'Ask GPT to sort, tag, define, or filter your documents for you!'); + case GPTPopupMode.FIREFLY: return this.promptBox("CREATE", this._userPrompt, this.setUserPrompt, StrCast(DocumentView.Selected().lastElement()?.Document.ai_firefly_prompt, 'Ask Firefly to generate images')); + case GPTPopupMode.QUIZ_RESPONSE: return this.promptBox("QUIZ", this._quizAnswer, this.setQuizAnswer, 'Describe/answer the selected document!'); + case GPTPopupMode.GPT_MENU: return this.menuBox(); + case GPTPopupMode.SUMMARY: return this.summaryBox(); + case GPTPopupMode.DATA: return this.dataAnalysisBox(); + case GPTPopupMode.IMAGE: return this.imageBox(); + default: return null; + } + })()} </div> ); } diff --git a/src/client/views/pdf/PDFViewer.tsx b/src/client/views/pdf/PDFViewer.tsx index 8728ce99c..167421a4a 100644 --- a/src/client/views/pdf/PDFViewer.tsx +++ b/src/client/views/pdf/PDFViewer.tsx @@ -437,7 +437,7 @@ export class PDFViewer extends ObservableReactComponent<IViewerProps> { AnchorMenu.Instance.jumpTo(e.clientX, e.clientY); } - GPTPopup.Instance.setSidebarId('data_sidebar'); + GPTPopup.Instance.setSidebarFieldKey('data_sidebar'); GPTPopup.Instance.addDoc = this._props.sidebarAddDoc; // allows for creating collection AnchorMenu.Instance.addToCollection = this._props.DocumentView?.()._props.addDocument; diff --git a/src/client/views/search/SearchBox.scss b/src/client/views/search/SearchBox.scss index 94e64b952..030d56f0c 100644 --- a/src/client/views/search/SearchBox.scss +++ b/src/client/views/search/SearchBox.scss @@ -1,4 +1,4 @@ -@import '../global/globalCssVariables.module.scss'; +@use '../global/globalCssVariables.module.scss' as global; .searchBox-container { width: 100%; @@ -22,7 +22,7 @@ top: 0px; position: sticky; overflow-y: scroll; - border-bottom: $standard-border; + border-bottom: global.$standard-border; .searchBox-type { display: block; @@ -48,20 +48,20 @@ .section-header { .section-title { - font-size: $body-text; + font-size: global.$body-text; font-weight: 600; } .section-subtitle { display: flex; - color: $light-gray; + color: global.$light-gray; } padding: 5px 10px; display: flex; flex-direction: column; gap: 3px; - background: $medium-blue; + background: global.$medium-blue; color: white; } diff --git a/src/client/views/smartdraw/DrawingFillHandler.tsx b/src/client/views/smartdraw/DrawingFillHandler.tsx index d0a840883..c672bc718 100644 --- a/src/client/views/smartdraw/DrawingFillHandler.tsx +++ b/src/client/views/smartdraw/DrawingFillHandler.tsx @@ -1,6 +1,7 @@ import { imageUrlToBase64 } from '../../../ClientUtils'; import { Doc, StrListCast } from '../../../fields/Doc'; import { DocData } from '../../../fields/DocSymbols'; +import { List } from '../../../fields/List'; import { DocCast, ImageCast } from '../../../fields/Types'; import { ImageField } from '../../../fields/URLField'; import { Upload } from '../../../server/SharedMediaTypes'; @@ -28,41 +29,43 @@ export class DrawingFillHandler { const hrefParts = ImageCast(styleImg).url.href.split('.'); return `${hrefParts.slice(0, -1).join('.')}_o.${hrefParts.lastElement()}`; }); - DocumentView.GetDocImage(drawing)?.then(imageField => { + return DocumentView.GetDocImage(drawing)?.then(imageField => { if (imageField) { const aspectRatio = (drawing.width as number) / (drawing.height as number); - let dims: { width: number; height: number }; - if (aspectRatio > AspectRatioLimits[FireflyImageDimensions.Widescreen]) { - dims = FireflyDimensionsMap[FireflyImageDimensions.Widescreen]; - } else if (aspectRatio > AspectRatioLimits[FireflyImageDimensions.Landscape]) { - dims = FireflyDimensionsMap[FireflyImageDimensions.Landscape]; - } else if (aspectRatio < AspectRatioLimits[FireflyImageDimensions.Portrait]) { - dims = FireflyDimensionsMap[FireflyImageDimensions.Portrait]; - } else { - dims = FireflyDimensionsMap[FireflyImageDimensions.Square]; - } + const dims = (() => { + if (aspectRatio > AspectRatioLimits[FireflyImageDimensions.Widescreen]) return FireflyDimensionsMap[FireflyImageDimensions.Widescreen]; + if (aspectRatio > AspectRatioLimits[FireflyImageDimensions.Landscape]) return FireflyDimensionsMap[FireflyImageDimensions.Landscape]; + if (aspectRatio < AspectRatioLimits[FireflyImageDimensions.Portrait]) return FireflyDimensionsMap[FireflyImageDimensions.Portrait]; + return FireflyDimensionsMap[FireflyImageDimensions.Square]; + })(); const { href } = ImageCast(imageField).url; const hrefParts = href.split('.'); const structureUrl = `${hrefParts.slice(0, -1).join('.')}_o.${hrefParts.lastElement()}`; return imageUrlToBase64(structureUrl) .then(gptDescribeImage) .then((prompt, newPrompt = user_prompt || prompt) => - Networking.PostToServer('/queryFireflyImageFromStructure', { prompt: `${newPrompt}`, width: dims.width, height: dims.height, structure: structureUrl, strength, presets: styles, styleUrl }) - .then((infos: Upload.ImageInformation[]) => { + Networking.PostToServer('/queryFireflyImageFromStructure', { prompt: `${newPrompt}`, width: dims.width, height: dims.height, structureUrl, strength, presets: styles, styleUrl }) + .then(res => { const genratedDocs = DocCast(drawing.ai_firefly_generatedDocs) ?? Docs.Create.MasonryDocument([], { _width: 400, _height: 400 }); drawing[DocData].ai_firefly_generatedDocs = genratedDocs; - infos.map(info => + (res as Upload.ImageInformation[]).map(info => Doc.AddDocToList( genratedDocs, undefined, Docs.Create.ImageDocument(info.accessPaths.agnostic.client, { ai: 'firefly', + tags: new List<string>(['@ai']), title: newPrompt, + _data_usePath: 'alternate:hover', + data_alternates: new List<Doc>([drawing]), ai_firefly_prompt: newPrompt, _width: 500, data_nativeWidth: info.nativeWidth, data_nativeHeight: info.nativeHeight, - }) + }), + undefined, + undefined, + true ) ); if (!DocumentView.getFirstDocumentView(genratedDocs)) DocumentViewInternal.addDocTabFunc(genratedDocs, OpenWhere.addRight); diff --git a/src/client/views/smartdraw/FireflyConstants.ts b/src/client/views/smartdraw/FireflyConstants.ts index 1f1781617..8cc9e36a5 100644 --- a/src/client/views/smartdraw/FireflyConstants.ts +++ b/src/client/views/smartdraw/FireflyConstants.ts @@ -5,6 +5,11 @@ export interface FireflyImageData { href?: string; } +export function isFireflyImageData(obj: unknown): obj is FireflyImageData { + const tobj = obj as FireflyImageData; + return typeof obj === 'object' && obj !== null && typeof tobj.pathname === 'string' && typeof tobj.prompt === 'string' && typeof tobj.seed === 'number'; +} + export enum FireflyImageDimensions { Square = 'square', Landscape = 'landscape', diff --git a/src/client/views/smartdraw/SmartDrawHandler.tsx b/src/client/views/smartdraw/SmartDrawHandler.tsx index 7db9ef133..1cceabed3 100644 --- a/src/client/views/smartdraw/SmartDrawHandler.tsx +++ b/src/client/views/smartdraw/SmartDrawHandler.tsx @@ -1,19 +1,21 @@ +import { Button, IconButton } from '@dash/components'; import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'; import { Checkbox, FormControlLabel, Radio, RadioGroup, Slider, Switch } from '@mui/material'; -import { Button, IconButton } from '@dash/components'; import { action, makeObservable, observable, runInAction } from 'mobx'; import { observer } from 'mobx-react'; import React from 'react'; import { AiOutlineSend } from 'react-icons/ai'; import ReactLoading from 'react-loading'; import { INode, parse } from 'svgson'; -import { imageUrlToBase64 } from '../../../ClientUtils'; +import { imageUrlToBase64, setupMoveUpEvents } from '../../../ClientUtils'; import { unimplementedFunction } from '../../../Utils'; import { Doc, DocListCast } from '../../../fields/Doc'; import { DocData } from '../../../fields/DocSymbols'; import { InkData, InkField, InkTool } from '../../../fields/InkField'; import { BoolCast, ImageCast, NumCast, StrCast } from '../../../fields/Types'; +import { Networking } from '../../Network'; import { GPTCallType, gptAPICall, gptDrawingColor } from '../../apis/gpt/GPT'; +import { DocumentType } from '../../documents/DocumentTypes'; import { Docs } from '../../documents/Documents'; import { SettingsManager } from '../../util/SettingsManager'; import { undoable } from '../../util/UndoManager'; @@ -21,22 +23,24 @@ import { SVGToBezier, SVGType } from '../../util/bezierFit'; import { InkingStroke } from '../InkingStroke'; import { ObservableReactComponent } from '../ObservableReactComponent'; import { MarqueeView } from '../collections/collectionFreeForm'; -import { ActiveInkArrowEnd, ActiveInkArrowStart, ActiveInkDash, ActiveInkFillColor, ActiveInkBezierApprox, ActiveInkColor, ActiveInkWidth, ActiveIsInkMask, DocumentView, DocumentViewInternal } from '../nodes/DocumentView'; +import { ActiveInkArrowEnd, ActiveInkArrowStart, ActiveInkBezierApprox, ActiveInkColor, ActiveInkDash, ActiveInkFillColor, ActiveInkWidth, ActiveIsInkMask, DocumentView } from '../nodes/DocumentView'; +import { FireflyDimensionsMap, FireflyImageData, FireflyImageDimensions } from './FireflyConstants'; import './SmartDrawHandler.scss'; -import { Networking } from '../../Network'; -import { OpenWhere } from '../nodes/OpenWhere'; -import { FireflyDimensionsMap, FireflyImageDimensions, FireflyImageData } from './FireflyConstants'; -import { DocumentType } from '../../documents/DocumentTypes'; +import { Upload } from '../../../server/SharedMediaTypes'; +import { PointData } from '../../../pen-gestures/GestureTypes'; +import { List } from '../../../fields/List'; export interface DrawingOptions { - text: string; - complexity: number; - size: number; - autoColor: boolean; - x: number; - y: number; + text?: string; + complexity?: number; + size?: number; + autoColor?: boolean; + x?: number; + y?: number; } +type svgparsedData = [PointData[], string, string]; + /** * The SmartDrawHandler allows users to generate drawings with GPT from text input. Users are able to enter * the item to draw, how complex they want the drawing to be, how large the drawing should be, and whether @@ -60,7 +64,6 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { private _lastInput: DrawingOptions = { text: '', complexity: 5, size: 350, autoColor: true, x: 0, y: 0 }; private _lastResponse: string = ''; private _selectedDocs: Doc[] = []; - private _errorOccurredOnce = false; @observable private _display: boolean = false; @observable private _pageX: number = 0; @@ -95,7 +98,7 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { CollectionFreeForm, FormattedTextBox, StickerPalette) to define how a drawing document should be added or removed in their respective locations (to the freeform canvas, to the sticker palette's preview, etc.) */ - public AddDrawing: (doc: Doc, opts: DrawingOptions, gptRes: string) => void = unimplementedFunction; + public AddDrawing: (doc: Doc, opts: DrawingOptions, gptRes: string, x?: number, y?: number) => void = unimplementedFunction; public RemoveDrawing: (useLastContainer: boolean, doc?: Doc) => void = unimplementedFunction; /** * This creates the ink document that represents a drawing, so it goes through the strokes that make up the drawing, @@ -103,7 +106,7 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { * classes to customize the way the drawing docs get created. For example, the freeform canvas has a different way of * defining document bounds, so CreateDrawingDoc is redefined when that class calls gpt draw functions. */ - public CreateDrawingDoc: (strokeList: [InkData, string, string][], opts: DrawingOptions, gptRes: string, containerDoc?: Doc) => Doc | undefined = (strokeList: [InkData, string, string][], opts: DrawingOptions) => { + public static CreateDrawingDoc: (strokeList: [InkData, string, string][], opts: DrawingOptions, gptRes: string, containerDoc?: Doc) => Doc | undefined = (strokeList: [InkData, string, string][], opts: DrawingOptions) => { const drawing: Doc[] = []; strokeList.forEach((stroke: [InkData, string, string]) => { const bounds = InkField.getBounds(stroke[0]); @@ -115,7 +118,7 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { y: bounds.top - inkWidth / 2, _width: bounds.width + inkWidth, _height: bounds.height + inkWidth, - stroke_showLabel: !BoolCast(Doc.UserDoc().activeHideTextLabels)}, // prettier-ignore + stroke_showLabel: false}, // prettier-ignore inkWidth, opts.autoColor ? stroke[1] : ActiveInkColor(), ActiveInkBezierApprox(), @@ -189,9 +192,9 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { /** * This allows users to press the return/enter key to send input. */ - handleKeyPress = (event: React.KeyboardEvent) => { - if (event.key === 'Enter') { - this.handleSendClick(); + handleKeyPress = (e: React.KeyboardEvent) => { + if (e.key === 'Enter') { + this.handleSendClick(this._pageX, this._pageY); } }; @@ -201,41 +204,24 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { * what the user sees. */ @action - handleSendClick = async () => { + handleSendClick = async (X: number, Y: number) => { if ((!this.ShowRegenerate && this._userInput == '') || (!this._generateImage && !this._generateDrawing)) return; this._isLoading = true; this._canInteract = false; if (this.ShowRegenerate) { - await this.regenerate(this._selectedDocs); - runInAction(() => { - this._selectedDocs = []; - this._regenInput = ''; - this._showEditBox = false; - }); + await this.regenerate(this._selectedDocs, undefined, undefined, this._regenInput).then(action(() => (this._showEditBox = false))); } else { - runInAction(() => { - this._showOptions = false; - }); + this._showOptions = false; try { if (this._generateImage) { await this.createImageWithFirefly(this._userInput); } if (this._generateDrawing) { - await this.drawWithGPT({ X: this._pageX, Y: this._pageY }, this._userInput, this._complexity, this._size, this._autoColor); + await this.drawWithGPT({ X, Y }, this._userInput, this._complexity, this._size, this._autoColor); } this.hideSmartDrawHandler(); - - runInAction(() => { - this.ShowRegenerate = true; - }); } catch (err) { - if (this._errorOccurredOnce) { - console.error('GPT call failed', err); - this._errorOccurredOnce = false; - } else { - this._errorOccurredOnce = true; - await this.handleSendClick(); - } + console.error('GPT call failed', err); } } runInAction(() => { @@ -247,16 +233,15 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { /** * Calls GPT API to create a drawing based on user input. */ - drawWithGPT = async (startPt: { X: number; Y: number }, input: string, complexity: number, size: number, autoColor: boolean) => { + drawWithGPT = async (screenPt: { X: number; Y: number }, input: string, complexity: number, size: number, autoColor: boolean) => { if (input) { - this._lastInput = { text: input, complexity: complexity, size: size, autoColor: autoColor, x: startPt.X, y: startPt.Y }; + this._lastInput = { text: input, complexity: complexity, size: size, autoColor: autoColor, x: screenPt.X, y: screenPt.Y }; const res = await gptAPICall(`"${input}", "${complexity}", "${size}"`, GPTCallType.DRAW, undefined, true); if (res) { - const strokeData = await this.parseSvg(res, startPt, false, autoColor); - const drawingDoc = strokeData && this.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); - drawingDoc && this.AddDrawing(drawingDoc, this._lastInput, res); + const strokeData = await this.parseSvg(res, { X: 0, Y: 0 }, false, autoColor); + const drawingDoc = strokeData && SmartDrawHandler.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); + drawingDoc && this.AddDrawing(drawingDoc, this._lastInput, res, screenPt.X, screenPt.Y); drawingDoc && this._selectedDocs.push(drawingDoc); - this._errorOccurredOnce = false; return strokeData; } else { console.error('GPT call failed'); @@ -268,28 +253,64 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { /** * Calls Firefly API to create an image based on user input */ - createImageWithFirefly = (input: string, seed?: number, changeInPlace?: boolean): Promise<FireflyImageData> => { + createImageWithFirefly = (input: string, seed?: number): Promise<FireflyImageData | Doc | undefined> => { this._lastInput.text = input; - const dims = FireflyDimensionsMap[this._imgDims]; + return SmartDrawHandler.CreateWithFirefly(input, this._imgDims, seed).then(doc => { + doc instanceof Doc && this.AddDrawing(doc, this._lastInput, input, this._pageX, this._pageY); + return doc; + }); + }; /** + * Calls Firefly API to create an image based on user input + */ + recreateImageWithFirefly = (input: string, seed?: number): Promise<FireflyImageData | Doc | undefined> => { + this._lastInput.text = input; + return SmartDrawHandler.ReCreateWithFirefly(input, this._imgDims, seed); + }; + public static ReCreateWithFirefly(input: string, imgDims: FireflyImageDimensions, seed?: number): Promise<FireflyImageData | Doc | undefined> { + const dims = FireflyDimensionsMap[imgDims]; return Networking.PostToServer('/queryFireflyImage', { prompt: input, width: dims.width, height: dims.height, seed }) - .then(img => { - const newseed = img.accessPaths.agnostic.client.match(/\/(\d+)upload/)[1]; - if (!changeInPlace) { - const imgDoc: Doc = Docs.Create.ImageDocument(img.accessPaths.agnostic.client, { - title: input.match(/^(.*?)~~~.*$/)?.[1] || input, - nativeWidth: dims.width, - nativeHeight: dims.height, - ai: 'firefly', - ai_firefly_seed: newseed, - ai_firefly_prompt: input, - }); - DocumentViewInternal.addDocTabFunc(imgDoc, OpenWhere.addRight); - this._selectedDocs.push(imgDoc); + .then(res => { + const img = res as Upload.FileInformation; + const error = res as { error: string }; + if ('error' in error) { + alert('recreate image failed: ' + error.error); + return undefined; } return { prompt: input, seed, pathname: img.accessPaths.agnostic.client }; }) - .catch(e => alert('create image failed: ' + e.toString())); - }; + .catch(e => { + alert('recreate image failed: ' + e.toString()); + return undefined; + }); + } + public static CreateWithFirefly(input: string, imgDims: FireflyImageDimensions, seed?: number): Promise<FireflyImageData | Doc | undefined> { + const dims = FireflyDimensionsMap[imgDims]; + return Networking.PostToServer('/queryFireflyImage', { prompt: input, width: dims.width, height: dims.height, seed }) + .then(res => { + const img = res as Upload.FileInformation; + const error = res as { error: string }; + if ('error' in error) { + alert('create image failed: ' + error.error); + return undefined; + } + const newseed = img.accessPaths.agnostic.client.match(/\/(\d+)upload/)?.[1]; + return Docs.Create.ImageDocument(img.accessPaths.agnostic.client, { + title: input, + nativeWidth: dims.width, + nativeHeight: dims.height, + tags: new List<string>(['@ai']), + _width: Math.min(400, dims.width), + _height: (Math.min(400, dims.width) * dims.height) / dims.width, + ai: 'firefly', + ai_firefly_seed: +(newseed ?? 0), + ai_firefly_prompt: input, + }); + }) + .catch(e => { + alert('create image failed: ' + e.toString()); + return undefined; + }); + } /** * Regenerates drawings with the option to add a specific regenerate prompt/request. @@ -303,28 +324,25 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { return Promise.all( drawingDocs.map(async doc => { switch (doc.type) { - case DocumentType.IMG: - if (this._regenInput) { - // if (this._selectedDoc) { - const newPrompt = doc.ai_firefly_prompt ? `${doc.ai_firefly_prompt} ~~~ ${this._regenInput}` : this._regenInput; - return this.createImageWithFirefly(newPrompt, NumCast(doc?.ai_firefly_seed), changeInPlace); - // } - } - return this.createImageWithFirefly(this._lastInput.text || StrCast(doc.ai_firefly_prompt), undefined, changeInPlace); + case DocumentType.IMG: { + const func = changeInPlace ? this.recreateImageWithFirefly : this.createImageWithFirefly; + const newPrompt = doc.ai_firefly_prompt ? `${doc.ai_firefly_prompt} ~~~ ${this._regenInput}` : this._regenInput; + return this._regenInput ? func(newPrompt, NumCast(doc?.ai_firefly_seed)) : func(this._lastInput.text || StrCast(doc.ai_firefly_prompt)); + } case DocumentType.COL: { try { - let res; - if (this._regenInput) { - const prompt = `This is your previously generated svg code: ${this._lastResponse} for the user input "${this._lastInput.text}". Please regenerate it with the provided specifications.`; - res = await gptAPICall(`"${this._regenInput}"`, GPTCallType.DRAW, prompt, true); - this._lastInput.text = `${this._lastInput.text} ~~~ ${this._regenInput}`; - } else { - res = await gptAPICall(`"${this._lastInput.text}", "${this._lastInput.complexity}", "${this._lastInput.size}"`, GPTCallType.DRAW, undefined, true); - } + const res = await (async () => { + if (this._regenInput) { + const prompt = `This is your previously generated svg code: ${this._lastResponse} for the user input "${this._lastInput.text}". Please regenerate it with the provided specifications.`; + this._lastInput.text = `${this._lastInput.text} ~~~ ${this._regenInput}`; + return gptAPICall(`"${this._regenInput}"`, GPTCallType.DRAW, prompt, true); + } + return gptAPICall(`"${this._lastInput.text}", "${this._lastInput.complexity}", "${this._lastInput.size}"`, GPTCallType.DRAW, undefined, true); + })(); if (res) { - const strokeData = await this.parseSvg(res, { X: this._lastInput.x, Y: this._lastInput.y }, true, lastInput?.autoColor || this._autoColor); + const strokeData = await this.parseSvg(res, { X: this._lastInput.x ?? 0, Y: this._lastInput.y ?? 0 }, true, lastInput?.autoColor || this._autoColor); this.RemoveDrawing !== unimplementedFunction && this.RemoveDrawing(true, doc); - const drawingDoc = strokeData && this.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); + const drawingDoc = strokeData && SmartDrawHandler.CreateDrawingDoc(strokeData.data, strokeData.lastInput, strokeData.lastRes); drawingDoc && this.AddDrawing(drawingDoc, this._lastInput, res); } else { console.error('GPT call failed'); @@ -344,20 +362,35 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { */ parseSvg = async (res: string, startPoint: { X: number; Y: number }, regenerate: boolean, autoColor: boolean) => { const svg = res.match(/<svg[^>]*>([\s\S]*?)<\/svg>/g); + if (svg) { this._lastResponse = svg[0]; const svgObject = await parse(svg[0]); + console.log(res, svgObject); const svgStrokes: INode[] = svgObject.children; const strokeData: [InkData, string, string][] = []; + + const tl = { X: Number.MAX_SAFE_INTEGER, Y: Number.MAX_SAFE_INTEGER }; + let last: PointData = { X: 0, Y: 0 }; svgStrokes.forEach(child => { - const convertedBezier: InkData = SVGToBezier(child.name as SVGType, child.attributes); + const convertedBezier: InkData = SVGToBezier(child.name as SVGType, child.attributes, last); + last = convertedBezier.lastElement(); strokeData.push([ - convertedBezier.map(point => ({ X: startPoint.X + (point.X - startPoint.X) * this._scale, Y: startPoint.Y + (point.Y - startPoint.Y) * this._scale })), + convertedBezier.map(point => { + if (point.X < tl.X) tl.X = point.X; + if (point.Y < tl.Y) tl.Y = point.Y; + return { X: point.X, Y: point.Y }; + }), (regenerate ? this._lastInput.autoColor : autoColor) ? child.attributes.stroke : '', (regenerate ? this._lastInput.autoColor : autoColor) ? child.attributes.fill : '', ]); }); - return { data: strokeData, lastInput: this._lastInput, lastRes: svg[0] }; + const mapStroke = (pd: PointData): PointData => ({ X: startPoint.X + (pd.X - tl.X) * this._scale, Y: startPoint.Y + (pd.Y - tl.Y) * this._scale }); + return { + data: strokeData.map(sdata => [sdata[0].map(mapStroke), sdata[1], sdata[2]] as svgparsedData), + lastInput: this._lastInput, + lastRes: svg[0], + }; } }; @@ -427,7 +460,7 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { }, }} checked={this._generateImage} - onChange={() => this._canInteract && (this._generateImage = !this._generateImage)} + onChange={action(() => this._canInteract && (this._generateImage = !this._generateImage))} /> </div> </div> @@ -507,6 +540,19 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { return ( <div className="smart-draw-handler" + onPointerDown={e => + setupMoveUpEvents( + this, + e, + action(me => { + this._pageX = this._pageX + me.movementX; + this._pageY = this._pageY + me.movementY; + return false; + }), + () => {}, + () => {} + ) + } style={{ display: this._display ? '' : 'none', left: this._pageX, @@ -525,6 +571,7 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { color={SettingsManager.userColor} /> <input + style={{ color: SettingsManager.userColor, background: SettingsManager.userBackgroundColor }} aria-label="Smart Draw Input" className="smartdraw-input" type="text" @@ -541,7 +588,7 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { icon={this._isLoading ? <ReactLoading type="spin" color={SettingsManager.userVariantColor} width={16} height={20} /> : <AiOutlineSend />} iconPlacement="right" color={SettingsManager.userColor} - onClick={this.handleSendClick} + onClick={() => this.handleSendClick(this._pageX, this._pageY)} /> </div> {this._showOptions && ( @@ -565,6 +612,7 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { onChange={action(e => this._canInteract && (this._regenInput = e.target.value))} onKeyDown={this.handleKeyPress} placeholder="Edit instructions" + onPointerDown={e => e.stopPropagation()} /> <Button style={{ alignSelf: 'flex-end' }} @@ -572,15 +620,42 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { icon={this._isLoading && this._regenInput !== '' ? <ReactLoading type="spin" color={SettingsManager.userVariantColor} width={16} height={20} /> : <AiOutlineSend />} iconPlacement="right" color={SettingsManager.userColor} - onClick={this.handleSendClick} + onClick={() => this.handleSendClick(this._pageX, this._pageY)} /> </div> ); + startDragging = (e: PointerEvent) => { + setupMoveUpEvents( + this, + e, + action(me => { + this._pageX = this._pageX + me.movementX; + this._pageY = this._pageY + me.movementY; + return false; + }), + () => {}, + () => {} + ); + }; renderRegenerate = () => ( <div className="smart-draw-handler" + onPointerDown={e => + setupMoveUpEvents( + this, + e, + action(me => { + this._pageX = this._pageX + me.movementX; + this._pageY = this._pageY + me.movementY; + return false; + }), + () => {}, + () => {} + ) + } style={{ + padding: 10, left: this._pageX, ...(this._yRelativeToTop ? { top: Math.max(0, this._pageY) } : { bottom: this._pageY }), background: SettingsManager.userBackgroundColor, @@ -591,7 +666,7 @@ export class SmartDrawHandler extends ObservableReactComponent<object> { tooltip="Regenerate" icon={this._isLoading && this._regenInput === '' ? <ReactLoading type="spin" color={SettingsManager.userVariantColor} width={16} height={20} /> : <FontAwesomeIcon icon={'rotate'} />} color={SettingsManager.userColor} - onClick={this.handleSendClick} + onClick={() => this.handleSendClick(this._pageX, this._pageY)} /> <IconButton tooltip="Edit with GPT" icon={<FontAwesomeIcon icon="pen-to-square" />} color={SettingsManager.userColor} onClick={action(() => (this._showEditBox = !this._showEditBox))} /> {this._showEditBox ? this.renderRegenerateEditBox() : null} diff --git a/src/client/views/topbar/TopBar.scss b/src/client/views/topbar/TopBar.scss index 20245104e..35a3da312 100644 --- a/src/client/views/topbar/TopBar.scss +++ b/src/client/views/topbar/TopBar.scss @@ -1,4 +1,5 @@ -@import '../global/globalCssVariables.module.scss'; +@use 'sass:color'; +@use '../global/globalCssVariables.module.scss' as global; .topbar-container { flex-direction: column; @@ -6,13 +7,13 @@ line-height: 1; overflow-y: auto; overflow-x: visible; - background: $dark-gray; + background: global.$dark-gray; overflow: visible; z-index: 1000; align-items: center; - height: $topbar-height; - background-color: $dark-gray; - border-bottom: $standard-border; + height: global.$topbar-height; + background-color: global.$dark-gray; + border-bottom: global.$standard-border; padding: 0px 10px; cursor: default; display: flex; @@ -34,7 +35,7 @@ } .topbar-button-text { - color: $white; + color: global.$white; padding: 10px; size: 15; @@ -54,16 +55,16 @@ align-self: center; padding: 5px; transition: linear 0.2s; - color: $white; + color: global.$white; &:hover { - background-color: darken($color: $light-gray, $amount: 20); + background-color: color.adjust(global.$light-gray, $lightness: -20%); font-weight: 500; } } .topbar-title { - color: $white; + color: global.$white; font-size: 17; font-weight: 500; } @@ -119,7 +120,7 @@ } .topBar-icon:hover { - background-color: $close-red; + background-color: global.$close-red; } .topbar-lozenge-user, @@ -180,7 +181,7 @@ &.topbar-input { margin: 5px; border-radius: 20px; - border: $dark-gray; + border: global.$dark-gray; display: block; width: 130px; -webkit-transition: width 0.4s; @@ -212,8 +213,8 @@ } &.topbar-close { - color: $white; - max-height: $topbar-height; + color: global.$white; + max-height: global.$topbar-height; } } } @@ -229,7 +230,7 @@ .no-result { width: 500px; - background: $light-gray; + background: global.$light-gray; padding: 10px; height: 50px; text-transform: uppercase; diff --git a/src/fields/Doc.ts b/src/fields/Doc.ts index e62ca4bb8..bdd41b0bb 100644 --- a/src/fields/Doc.ts +++ b/src/fields/Doc.ts @@ -7,7 +7,7 @@ import { CollectionViewType, DocumentType } from '../client/documents/DocumentTy import { scriptingGlobal, ScriptingGlobals } from '../client/util/ScriptingGlobals'; import { afterDocDeserialize, autoObject, Deserializable, SerializationHelper } from '../client/util/SerializationHelper'; import { undoable, UndoManager } from '../client/util/UndoManager'; -import { ClientUtils, incrementTitleCopy } from '../ClientUtils'; +import { ClientUtils, imageUrlToBase64, incrementTitleCopy } from '../ClientUtils'; import { AclAdmin, AclAugment, AclEdit, AclPrivate, AclReadonly, Animation, AudioPlay, Brushed, CachedUpdates, DirectLinks, DocAcl, DocCss, DocData, DocLayout, DocViews, FieldKeys, FieldTuples, ForceServerWrite, Height, Highlight, @@ -22,8 +22,9 @@ import { FieldId, RefField } from './RefField'; import { RichTextField } from './RichTextField'; import { listSpec } from './Schema'; import { ComputedField, ScriptField } from './ScriptField'; -import { BoolCast, Cast, DocCast, FieldValue, NumCast, StrCast, ToConstructor, toList } from './Types'; +import { BoolCast, Cast, DocCast, FieldValue, ImageCastWithSuffix, NumCast, RTFCast, StrCast, ToConstructor, toList } from './Types'; import { containedFieldChangedHandler, deleteProperty, GetEffectiveAcl, getField, getter, makeEditable, makeReadOnly, setter, SharingPermissions } from './util'; +import { gptImageLabel } from '../client/apis/gpt/GPT'; export let ObjGetRefField: (id: string, force?: boolean) => Promise<Doc | undefined>; export let ObjGetRefFields: (ids: string[]) => Promise<Map<string, Doc | undefined>>; @@ -1467,6 +1468,25 @@ export namespace Doc { }); } + /** + * text description of a Doc. RTF documents will have just their text and pdf documents will have the first 50 words. + * Image documents are converted to bse64 and gpt generates a description for them. all other documents use their title. + * @param doc + * @returns + */ + export function getDescription(doc: Doc) { + const curDescription = StrCast(doc[DocData][Doc.LayoutFieldKey(doc) + '_description']); + const docText = (async (tdoc:Doc) => { + switch (tdoc.type) { + case DocumentType.PDF: return curDescription || StrCast(tdoc.text).split(/\s+/).slice(0, 50).join(' '); // first 50 words of pdf text + case DocumentType.IMG: return curDescription || imageUrlToBase64(ImageCastWithSuffix(Doc.LayoutField(tdoc), '_o') ?? '') + .then(hrefBase64 => gptImageLabel(hrefBase64, 'Give three to five labels to describe this image.')); + case DocumentType.RTF: return RTFCast(tdoc[Doc.LayoutFieldKey(tdoc)]).Text; + default: return StrCast(tdoc.title).startsWith("Untitled") ? "" : StrCast(tdoc.title); + }}); // prettier-ignore + return docText(doc).then(text => (doc[DocData][Doc.LayoutFieldKey(doc) + '_description'] = text)); + } + // prettier-ignore export function toIcon(doc?: Doc, isOpen?: Opt<boolean>) { if (isOpen) return doc?.isFolder ? 'chevron-down' : 'folder-open'; diff --git a/src/fields/RichTextUtils.ts b/src/fields/RichTextUtils.ts index 8c073c87b..42dd0d432 100644 --- a/src/fields/RichTextUtils.ts +++ b/src/fields/RichTextUtils.ts @@ -1,7 +1,7 @@ /* eslint-disable no-await-in-loop */ /* eslint-disable no-use-before-define */ import { AssertionError } from 'assert'; -import * as Color from 'color'; +import Color from 'color'; import { docs_v1 as docsV1 } from 'googleapis'; import { Fragment, Mark, Node, Schema } from 'prosemirror-model'; import { sinkListItem } from 'prosemirror-schema-list'; diff --git a/src/fields/Types.ts b/src/fields/Types.ts index e19673665..474882959 100644 --- a/src/fields/Types.ts +++ b/src/fields/Types.ts @@ -134,6 +134,10 @@ export function PDFCast(field: FieldResult, defaultVal: PdfField | null = null) export function ImageCast(field: FieldResult, defaultVal: ImageField | null = null) { return Cast(field, ImageField, defaultVal); } +export function ImageCastWithSuffix(field: FieldResult, suffix: string, defaultVal: ImageField | null = null) { + const href = ImageCast(field, defaultVal)?.url.href; + return href ? `${href.split('.')[0]}${suffix}.${href.split('.')[1]}` : null; +} export function FieldValue<T extends FieldType, U extends WithoutList<T>>(field: FieldResult<T>, defaultValue: U): WithoutList<T>; // eslint-disable-next-line no-redeclare diff --git a/src/server/ApiManagers/AssistantManager.ts b/src/server/ApiManagers/AssistantManager.ts index e859e5c5f..af25722a4 100644 --- a/src/server/ApiManagers/AssistantManager.ts +++ b/src/server/ApiManagers/AssistantManager.ts @@ -539,7 +539,7 @@ export default class AssistantManager extends ApiManager { // Spawn the Python process and track its progress/output // eslint-disable-next-line no-use-before-define - spawnPythonProcess(jobId, file_name, public_path); + spawnPythonProcess(jobId, public_path); // Send the job ID back to the client for tracking res.send({ jobId }); @@ -696,7 +696,7 @@ export default class AssistantManager extends ApiManager { * @param file_name The name of the file to process. * @param file_path The filepath of the file to process. */ -function spawnPythonProcess(jobId: string, file_name: string, file_path: string) { +function spawnPythonProcess(jobId: string, file_path: string) { const venvPath = path.join(__dirname, '../chunker/venv'); const requirementsPath = path.join(__dirname, '../chunker/requirements.txt'); const pythonScriptPath = path.join(__dirname, '../chunker/pdf_chunker.py'); diff --git a/src/server/ApiManagers/FireflyManager.ts b/src/server/ApiManagers/FireflyManager.ts index 160a94d40..e75ede9df 100644 --- a/src/server/ApiManagers/FireflyManager.ts +++ b/src/server/ApiManagers/FireflyManager.ts @@ -132,7 +132,8 @@ export default class FireflyManager extends ApiManager { ], body: body, }) - .then(response2 => response2.json().then(json => ({ seed: json.outputs?.[0]?.seed, url: json.outputs?.[0]?.image?.url }))) + .then(response2 => response2.json()) + .then(json => (json.error_code ? json : { seed: json.outputs?.[0]?.seed, url: json.outputs?.[0]?.image?.url })) .catch(error => { console.error('Error:', error); return undefined; @@ -297,13 +298,13 @@ export default class FireflyManager extends ApiManager { _invalid(res, styleUrl.message); throw new Error('Error uploading images to dropbox'); } - this.uploadImageToDropbox(req.body.structure, req.user as DashUserModel) - .then(structureUrl => { - if (structureUrl instanceof Error) { - _invalid(res, structureUrl.message); + this.uploadImageToDropbox(req.body.structureUrl, req.user as DashUserModel) + .then(dropboxStructureUrl => { + if (dropboxStructureUrl instanceof Error) { + _invalid(res, dropboxStructureUrl.message); throw new Error('Error uploading images to dropbox'); } - return { styleUrl, structureUrl }; + return { styleUrl, structureUrl: dropboxStructureUrl }; }) .then(uploads => this.generateImageFromStructure(req.body.prompt, req.body.width, req.body.height, uploads.structureUrl, req.body.strength, req.body.presets, uploads.styleUrl) @@ -332,10 +333,12 @@ export default class FireflyManager extends ApiManager { subscription: '/queryFireflyImage', secureHandler: ({ req, res }) => this.generateImage(req.body.prompt, req.body.width, req.body.height, req.body.seed).then(img => - DashUploadUtils.UploadImage(img?.url ?? '', undefined, img?.seed).then(info => { - if (info instanceof Error) _invalid(res, info.message); - else _success(res, info); - }) + img.error_code + ? _invalid(res, img.message) + : DashUploadUtils.UploadImage(img?.url ?? '', undefined, img?.seed).then(info => { + if (info instanceof Error) _invalid(res, info.message); + else _success(res, info); + }) ), }); diff --git a/src/server/DashUploadUtils.ts b/src/server/DashUploadUtils.ts index 2177c5d97..a2747257a 100644 --- a/src/server/DashUploadUtils.ts +++ b/src/server/DashUploadUtils.ts @@ -23,6 +23,7 @@ import { AcceptableMedia, Upload } from './SharedMediaTypes'; import { Directory, clientPathToFile, filesDirectory, pathToDirectory, publicDirectory, serverPathToFile } from './SocketData'; import { resolvedServerUrl } from './server_Initialization'; import { Worker, isMainThread, parentPort } from 'worker_threads'; +import requestImageSize from '../client/util/request-image-size'; // Create an array to store worker threads enum workertasks { @@ -62,9 +63,6 @@ if (isMainThread) { } } -// eslint-disable-next-line @typescript-eslint/no-require-imports -const requestImageSize = require('../client/util/request-image-size'); - export enum SizeSuffix { Small = '_s', Medium = '_m', @@ -349,14 +347,14 @@ export namespace DashUploadUtils { imgReadStream.push(null); await Promise.all( sizes.map(({ suffix }) => - new Promise<unknown>(res => + new Promise<void>(res => imgReadStream.pipe(createWriteStream(writtenFiles[suffix] = InjectSize(outputPath, suffix))).on('close', res) ) )); // prettier-ignore } else { await Promise.all( sizes.map(({ suffix }) => - new Promise<unknown>(res => + new Promise<void>(res => request.get(imgSourcePath).pipe(createWriteStream(writtenFiles[suffix] = InjectSize(outputPath, suffix))).on('close', res) ) )); // prettier-ignore diff --git a/src/server/apis/google/GoogleApiServerUtils.ts b/src/server/apis/google/GoogleApiServerUtils.ts index 21c405bee..7373df473 100644 --- a/src/server/apis/google/GoogleApiServerUtils.ts +++ b/src/server/apis/google/GoogleApiServerUtils.ts @@ -1,7 +1,7 @@ +/* eslint-disable no-use-before-define */ import { GaxiosResponse } from 'gaxios'; import { Credentials, OAuth2Client, OAuth2ClientOptions } from 'google-auth-library'; import { google } from 'googleapis'; -import * as qs from 'query-string'; import * as request from 'request-promise'; import { Opt } from '../../../fields/Doc'; import { Database } from '../../database'; @@ -21,7 +21,6 @@ const scope = ['documents.readonly', 'documents', 'presentations', 'presentation * This namespace manages server side authentication for Google API queries, either * from the standard v1 APIs or the Google Photos REST API. */ - export namespace GoogleApiServerUtils { /** * As we expand out to more Google APIs that are accessible from @@ -71,29 +70,29 @@ export namespace GoogleApiServerUtils { /** * A briefer format for the response from a 'googleapis' API request */ - export type ApiResponse = Promise<GaxiosResponse>; + export type ApiResponse = Promise<GaxiosResponse<unknown>>; /** * A generic form for a handler that executes some request on the endpoint */ - export type ApiRouter = (endpoint: Endpoint, parameters: any) => ApiResponse; + export type ApiRouter = (endpoint: Endpoint, parameters: Record<string, unknown>) => ApiResponse; /** * A generic form for the asynchronous function that actually submits the - * request to the API and returns the corresporing response. Helpful when + * request to the API and returns the corresponding response. Helpful when * making an extensible endpoint definition. */ - export type ApiHandler = (parameters: any, methodOptions?: any) => ApiResponse; + export type ApiHandler = (parameters: Record<string, unknown>, methodOptions?: Record<string, unknown>) => ApiResponse; /** * A literal union type indicating the valid actions for these 'googleapis' - * requestions + * requests */ export type Action = 'create' | 'retrieve' | 'update'; /** * An interface defining any entity on which one can invoke - * anuy of the following handlers. All 'googleapis' wrappers + * any of the following handlers. All 'googleapis' wrappers * such as google.docs().documents and google.slides().presentations * satisfy this interface. */ @@ -109,7 +108,7 @@ export namespace GoogleApiServerUtils { * of needless duplicate clients that would arise from * making one new client instance per request. */ - const authenticationClients = new Map<String, OAuth2Client>(); + const authenticationClients = new Map<string, OAuth2Client>(); /** * This function receives the target sector ("which G-Suite app's API am I interested in?") @@ -120,23 +119,21 @@ export namespace GoogleApiServerUtils { * @returns the relevant 'googleapis' wrapper, if any */ export async function GetEndpoint(sector: string, userId: string): Promise<Endpoint | void> { - return new Promise(async resolve => { - const auth = await retrieveOAuthClient(userId); - if (!auth) { - return resolve(); - } - let routed: Opt<Endpoint>; - const parameters: any = { auth, version: 'v1' }; - switch (sector) { - case Service.Documents: - routed = google.docs(parameters).documents; - break; - case Service.Slides: - routed = google.slides(parameters).presentations; - break; - } - resolve(routed); - }); + const auth = await retrieveOAuthClient(userId); + if (!auth) { + return; + } + let routed: Opt<Endpoint>; + const parameters: { version: 'v1' } = { /* auth, */ version: 'v1' }; ///* auth: OAuth2Client;*/ + switch (sector) { + case Service.Documents: + routed = google.docs(parameters).documents; + break; + case Service.Slides: + routed = google.slides(parameters).presentations; + break; + } + return routed; } /** @@ -149,19 +146,17 @@ export namespace GoogleApiServerUtils { * security. */ export async function retrieveOAuthClient(userId: string): Promise<OAuth2Client | void> { - return new Promise(async resolve => { - const { credentials, refreshed } = await retrieveCredentials(userId); - if (!credentials) { - return resolve(); - } - let client = authenticationClients.get(userId); - if (!client) { - authenticationClients.set(userId, (client = generateClient(credentials))); - } else if (refreshed) { - client.setCredentials(credentials); - } - resolve(client); - }); + const { credentials, refreshed } = await retrieveCredentials(userId); + if (!credentials) { + return; + } + let client = authenticationClients.get(userId); + if (!client) { + authenticationClients.set(userId, (client = generateClient(credentials))); + } else if (refreshed) { + client.setCredentials(credentials); + } + return client; } /** @@ -173,7 +168,9 @@ export namespace GoogleApiServerUtils { */ function generateClient(credentials?: Credentials): OAuth2Client { const client = new google.auth.OAuth2(oAuthOptions); - credentials && client.setCredentials(credentials); + if (credentials) { + client.setCredentials(credentials); + } return client; } @@ -206,7 +203,7 @@ export namespace GoogleApiServerUtils { */ export async function processNewUser(userId: string, authenticationCode: string): Promise<EnrichedCredentials> { const credentials = await new Promise<Credentials>((resolve, reject) => { - worker.getToken(authenticationCode, async (err, credentials) => { + worker.getToken(authenticationCode, (err, credentials) => { if (err || !credentials) { reject(err); return; @@ -221,7 +218,7 @@ export namespace GoogleApiServerUtils { /** * This type represents the union of the full set of OAuth2 credentials - * and all of a Google user's publically available information. This is the strucure + * and all of a Google user's publicly available information. This is the structure * of the JSON object we ultimately store in the googleAuthentication table of the database. */ export type EnrichedCredentials = Credentials & { userInfo: UserInfo }; @@ -297,15 +294,15 @@ export namespace GoogleApiServerUtils { async function refreshAccessToken(credentials: Credentials, userId: string): Promise<Credentials> { const headerParameters = { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }; const { client_id, client_secret } = GoogleCredentialsLoader.ProjectCredentials; - const url = `https://oauth2.googleapis.com/token?${qs.stringify({ - refreshToken: credentials.refresh_token, + const params = new URLSearchParams({ + refresh_token: credentials.refresh_token!, client_id, client_secret, grant_type: 'refresh_token', - })}`; - const { access_token, expires_in } = await new Promise<any>(async resolve => { - const response = await request.post(url, headerParameters); - resolve(JSON.parse(response)); + }); + const url = `https://oauth2.googleapis.com/token?${params.toString()}`; + const { access_token, expires_in } = await new Promise<{ access_token: string; expires_in: number }>(resolve => { + request.post(url, headerParameters).then(response => resolve(JSON.parse(response))); }); // expires_in is in seconds, but we're building the new expiry date in milliseconds const expiry_date = new Date().getTime() + expires_in * 1000; diff --git a/src/server/chunker/pdf_chunker.py b/src/server/chunker/pdf_chunker.py index a9dbcbb0c..697550f2e 100644 --- a/src/server/chunker/pdf_chunker.py +++ b/src/server/chunker/pdf_chunker.py @@ -21,7 +21,7 @@ import json import os import uuid # For generating unique IDs from enum import Enum # Enums for types like document type and purpose -import cohere # Embedding client +import openai import numpy as np from PyPDF2 import PdfReader # PDF text extraction from openai import OpenAI # OpenAI client for text completion @@ -35,8 +35,8 @@ warnings.filterwarnings('ignore', message="torch.load") dotenv.load_dotenv() # Load environment variables # Fix for newer versions of PIL -if parse(PIL.__version__) >= parse('10.0.0'): - Image.LINEAR = Image.BILINEAR +# if parse(PIL.__version__) >= parse('10.0.0'): +# Image.LINEAR = Image.BILINEAR # Global dictionary to track progress of document processing jobs current_progress = {} @@ -727,19 +727,19 @@ class Document: """ Embed the text chunks using the Cohere API. """ - co = cohere.Client(os.getenv("COHERE_API_KEY")) # Initialize Cohere client with API key + openai = OpenAI() # Initialize Cohere client with API key batch_size = 90 # Batch size for embedding chunks_len = len(self.chunks) # Total number of chunks to embed for i in tqdm(range(0, chunks_len, batch_size), desc="Embedding Chunks"): batch = self.chunks[i: min(i + batch_size, chunks_len)] # Get batch of chunks texts = [chunk['metadata']['text'] for chunk in batch] # Extract text from each chunk - chunk_embs_batch = co.embed( - texts=texts, - model="embed-english-v3.0", # Use Cohere's embedding model - input_type="search_document" # Specify input type + chunk_embs_batch = openai.embeddings.create( + model="text-embedding-3-large", + input=texts, + encoding_format="float" ) - for j, emb in enumerate(chunk_embs_batch.embeddings): - self.chunks[i + j]['values'] = emb # Store the embeddings in the corresponding chunks + for j, data_val in enumerate(chunk_embs_batch.data): + self.chunks[i + j]['values'] = data_val.embedding # Store the embeddings in the corresponding chunks def _generate_summary(self) -> str: """ diff --git a/src/typings/index.d.ts b/src/typings/index.d.ts index bee79a38d..dbfabed51 100644 --- a/src/typings/index.d.ts +++ b/src/typings/index.d.ts @@ -13,6 +13,7 @@ declare module 'iink-js'; declare module 'pdfjs-dist/web/pdf_viewer'; declare module 'react-jsx-parser'; declare module 'type_decls.d'; +declare module 'standard-http-error'; declare module '@react-pdf/renderer' { import * as React from 'react'; |