repo_name string | dataset string | owner string | lang string | func_name string | code string | docstring string | url string | sha string |
|---|---|---|---|---|---|---|---|---|
wordflow | github_2023 | poloclub | typescript | WordflowPanelLocal.showSearchBarCancelButtonClicked | showSearchBarCancelButtonClicked() {
if (this.shadowRoot === null) {
throw Error('shadowRoot is null.');
}
const inputElement = this.shadowRoot.querySelector(
'#search-bar-input'
) as HTMLInputElement;
inputElement.value = '';
this.showSearchBarCancelButton = false;
if (this.searchBarDebounceTimer !== null) {
clearTimeout(this.searchBarDebounceTimer);
this.searchBarDebounceTimer = null;
}
this.searchBarDebounceTimer = setTimeout(() => {
this.promptManager.searchPrompt('');
this.searchBarDebounceTimer = null;
}, 150);
} | /**
* Handler for the search bar cancel click event
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L437-L457 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPanelLocal.render | render() {
// Compose the prompt cards
let promptCards = html``;
for (const [i, promptData] of this.localPrompts
.slice(0, Math.min(this.maxPromptCount, this.localPrompts.length))
.entries()) {
promptCards = html`${promptCards}
<div
class="prompt-card-container"
@mouseenter=${(e: MouseEvent) => {
this.promptCardMouseEntered(e, i);
}}
@mouseleave=${(e: MouseEvent) => {
this.promptCardMouseLeft(e);
}}
>
<div
class="prompt-card-menu"
?is-hidden="${this.hoveringPromptCardIndex !== i}"
>
<button
class="edit-button"
@mouseenter=${(e: MouseEvent) =>
this.menuIconMouseEntered(e, 'edit')}
@mouseleave=${() => this.menuIconMouseLeft()}
@click=${() => {
this.promptCardClicked(promptData);
}}
>
<span class="svg-icon">${unsafeHTML(editIcon)}</span>
</button>
<button
class="delete-button"
@mouseenter=${(e: MouseEvent) =>
this.menuIconMouseEntered(e, 'delete')}
@mouseleave=${() => this.menuIconMouseLeft()}
@click=${() => {
this.menuDeleteClicked(promptData);
}}
>
<span class="svg-icon">${unsafeHTML(deleteIcon)}</span>
</button>
</div>
<wordflow-prompt-card
draggable="true"
.promptData=${promptData}
.isLocalPrompt=${true}
@click=${() => {
this.promptCardClicked(promptData);
}}
@dragstart=${(e: DragEvent) => {
this.promptCardDragStarted(e);
}}
@dragend=${(e: DragEvent) => {
this.promptCardDragEnded(e);
}}
></wordflow-prompt-card>
</div>`;
}
// Compose the fav prompts
let favPrompts = html``;
for (const [i, favPrompt] of this.favPrompts.entries()) {
favPrompts = html`${favPrompts}
<div
class="fav-prompt-slot"
@dragenter=${(e: DragEvent) => {
this.favPromptSlotDragEntered(e);
}}
@dragleave=${(e: DragEvent) => {
this.favPromptSlotDragLeft(e);
}}
@dragover=${(e: DragEvent) => {
e.preventDefault();
}}
@drop=${(e: DragEvent) => {
this.favPromptSlotDropped(e, i);
}}
@mouseenter=${() => {
this.hoveringFavPromptCardIndex = i;
}}
@mouseleave=${() => {
this.hoveringFavPromptCardIndex = null;
}}
>
<div
class="prompt-card-menu"
?is-hidden="${this.hoveringFavPromptCardIndex !== i ||
favPrompt === null}"
>
<button
class="edit-button"
@mouseenter=${(e: MouseEvent) =>
this.menuIconMouseEntered(e, 'edit')}
@mouseleave=${() => this.menuIconMouseLeft()}
@click=${() => {
this.promptCardClicked(favPrompt!);
}}
>
<span class="svg-icon">${unsafeHTML(editIcon)}</span>
</button>
<button
class="remove-button"
@mouseenter=${(e: MouseEvent) =>
this.menuIconMouseEntered(e, 'remove')}
@mouseleave=${() => this.menuIconMouseLeft()}
@click=${() => {
this.promptManager.setFavPrompt(i, null);
}}
>
<span class="svg-icon">${unsafeHTML(crossSmallIcon)}</span>
</button>
</div>
<div class="prompt-mini-card" ?is-empty=${favPrompt === null}>
<span class="icon">${favPrompt ? favPrompt.icon : ''}</span>
<span class="title"
>${favPrompt ? favPrompt.title : 'Drag a prompt here'}</span
>
</div>
</div>`;
}
// Compose the prompt count label
let promptCountLabel = html`${this.promptManager.localPromptCount} Private
Prompts`;
if (this.showSearchBarCancelButton) {
promptCountLabel = html`${this.promptManager.localPromptBroadcastCount} /
${this.promptManager.localPromptCount} Private Prompts`;
}
return html`
<div class="panel-local" ?is-dragging=${this.isDraggingPromptCard}>
<div class="prompt-panel">
<div class="search-panel">
<div class="search-group">
<div class="result">${promptCountLabel}</div>
<button
class="create-button"
@click=${() => this.creteButtonClicked()}
>
<span class="svg-icon">${unsafeHTML(addIcon)}</span>New Prompt
</button>
</div>
<div class="search-group">
<div class="search-bar">
<span class="icon-container">
<span class="svg-icon">${unsafeHTML(searchIcon)}</span>
</span>
<input
id="search-bar-input"
type="text"
name="search-bar-input"
@input=${(e: InputEvent) => this.searchBarEntered(e)}
placeholder="Search my prompts"
/>
<span
class="icon-container"
@click=${() => this.showSearchBarCancelButtonClicked()}
?is-hidden=${!this.showSearchBarCancelButton}
>
<span class="svg-icon cross">${unsafeHTML(crossIcon)}</span>
</span>
</div>
<div class="sort-button">
<span class="svg-icon">${unsafeHTML(sortIcon)}</span>
<select
class="sort-selection"
@input=${(e: InputEvent) => this.sortOptionChanged(e)}
>
<option value="created">Recency</option>
<option value="name">Name</option>
<option value="runCount">Run Count</option>
</select>
</div>
</div>
</div>
<div class="prompt-content">
<div
class="prompt-container"
@scroll=${() => {
this.promptContainerScrolled();
}}
>
${promptCards}
<div class="prompt-loader hidden">
<div class="loader-container">
<div class="circle-loader"></div>
</div>
</div>
</div>
<div class="fav-panel">
<div class="header">
<span class="title">Favorite Prompts</span>
<span class="description"
>Drag prompts here to customize the toolbar</span
>
</div>
<div class="fav-prompts">${favPrompts}</div>
</div>
<div class="prompt-modal hidden">
<wordflow-prompt-editor
.promptData=${this.selectedPrompt
? this.selectedPrompt
: getEmptyPromptDataLocal()}
.isNewPrompt=${this.shouldCreateNewPrompt}
.promptManager=${this.promptManager}
@close-clicked=${() => this.modalCloseClickHandler()}
></wordflow-prompt-editor>
</div>
</div>
</div>
<nightjar-confirm-dialog></nightjar-confirm-dialog>
<div
id="popper-tooltip-local"
class="popper-tooltip hidden"
role="tooltip"
>
<span class="popper-content"></span>
<div class="popper-arrow"></div>
</div>
</div>
`;
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-local/panel-local.ts#L466-L705 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPanelSetting.constructor | constructor() {
super();
this.selectedModel = SupportedRemoteModel['gpt-3.5-free'];
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-setting/panel-setting.ts#L134-L137 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPanelSetting.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {
if (changedProperties.has('userConfig')) {
if (this.selectedModel !== this.userConfig.preferredLLM) {
this.selectedModel = this.userConfig.preferredLLM;
// Need to manually update the select element
const selectElement = this.shadowRoot!.querySelector(
'.model-mode-select'
) as HTMLSelectElement;
selectElement.value = supportedModelReverseLookup[this.selectedModel];
this._updateSelectedLocalModelInCache().then(() => {
// Case 1: If the user has set preferred model to a local model in the
// previous session and the model is in cache => activate it
if (this.selectedModelFamily === ModelFamily.local) {
if (this.selectedLocalModelInCache) {
// Request the worker to start loading the model
const message: TextGenLocalWorkerMessage = {
command: 'startLoadModel',
payload: {
temperature: 0.2,
model: this.selectedModel as SupportedLocalModel
}
};
this.textGenLocalWorker.postMessage(message);
} else {
// Case 2: If the user has set preferred model to a local model in the
// previous session but the model is not longer in cache => revert to gpt 3.5 (free)
this.selectedModel = SupportedRemoteModel['gpt-3.5-free'];
selectElement.value =
supportedModelReverseLookup[this.selectedModel];
this.userConfigManager.setPreferredLLM(this.selectedModel);
}
}
});
}
}
} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-setting/panel-setting.ts#L143-L180 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPanelSetting.initData | async initData() {} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-setting/panel-setting.ts#L222-L222 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPanelSetting.textGenMessageHandler | textGenMessageHandler = (
model: SupportedRemoteModel,
apiKey: string,
message: TextGenMessage
) => {
switch (message.command) {
case 'finishTextGen': {
// If the textGen is initialized in the auth function, add the api key
// to the local storage
if (message.payload.requestID.includes('auth')) {
const modelFamily = modelFamilyMap[model];
// Add the api key to the storage
this.userConfigManager.setAPIKey(modelFamily, apiKey);
// Also use set this model as preferred model
if (this.selectedModel === model) {
this.userConfigManager.setPreferredLLM(model);
}
this.toastMessage = 'Successfully added an API key';
this.toastType = 'success';
this.toastComponent?.show();
}
break;
}
case 'error': {
if (message.payload.originalCommand === 'startTextGen') {
console.error(message);
this.toastMessage = 'Invalid API key. Try a different key.';
this.toastType = 'error';
this.toastComponent?.show();
}
break;
}
default: {
console.error('TextGen message handler: unknown message');
break;
}
}
} | // ===== Event Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-setting/panel-setting.ts | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPanelSetting.textGenLocalWorkerMessageHandler | textGenLocalWorkerMessageHandler(e: MessageEvent<TextGenLocalWorkerMessage>) {
switch (e.data.command) {
case 'finishTextGen': {
break;
}
case 'progressLoadModel': {
this.progressBarComponent?.updateProgress(e.data.payload.progress);
break;
}
case 'finishLoadModel': {
// Show the default message
this.localModelMessage = LOCAL_MODEL_MESSAGES.default;
this.showLocalModelProgressBar = false;
// Case 1: The user is using other models when the model finishes loading.
// Do nothing, wait for the users to switch to this model again.
if (e.data.payload.model !== this.selectedModel) {
// Pass
} else {
// Case 2: The user is actively waiting for this model to finish loading.
// Switch preferred model this model
this.userConfigManager.setPreferredLLM(this.selectedModel);
}
break;
}
case 'error': {
break;
}
default: {
console.error('Worker: unknown message', e.data.command);
break;
}
}
} | /**
* Event handler for the text gen local worker
* @param e Text gen message
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-setting/panel-setting.ts#L277-L315 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPanelSetting.infoIconMouseEntered | infoIconMouseEntered(
e: MouseEvent,
field: 'model' | 'api-key' | 'local-llm'
) {
let message = '';
switch (field) {
case 'model': {
message = 'Preferred LLM model to run the prompts';
break;
}
case 'api-key': {
message = 'Enter the API key to call the LLM model';
break;
}
case 'local-llm': {
message =
'Install open-source LLM models to run them directly in your browser';
break;
}
default: {
console.error(`Unknown type ${field}`);
}
}
const target = (e.currentTarget as HTMLElement).querySelector(
'.info-icon'
) as HTMLElement;
tooltipMouseEnter(e, message, 'top', this.tooltipConfig, 200, target, 10);
} | /**
* Event handler for mouse entering the info icon in each filed
* @param e Mouse event
* @param field Field type
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-setting/panel-setting.ts#L449-L481 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPanelSetting.infoIconMouseLeft | infoIconMouseLeft() {
tooltipMouseLeave(this.tooltipConfig);
} | /**
* Event handler for mouse leaving the info icon in each filed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-setting/panel-setting.ts#L486-L488 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPanelSetting._updateSelectedLocalModelInCache | async _updateSelectedLocalModelInCache() {
if (this.selectedModelFamily !== ModelFamily.local) {
this.selectedLocalModelInCache = false;
} else {
this.selectedLocalModelInCache = await hasLocalModelInCache(
this.selectedModel as SupportedLocalModel
);
}
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-setting/panel-setting.ts#L493-L501 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPanelSetting.render | render() {
// Compose the model select options
let remoteModelSelectOptions = html``;
let localModelSelectOptions = html``;
// Remote models
for (const [name, label] of Object.entries(SupportedRemoteModel)) {
remoteModelSelectOptions = html`${remoteModelSelectOptions}
<option value=${name}>${label}</option> `;
}
// Local models
for (const [name, label] of Object.entries(SupportedLocalModel)) {
localModelSelectOptions = html`${localModelSelectOptions}
<option value=${name}>${label}</option> `;
}
return html`
<div class="panel-setting">
<div class="toast-container">
<nightjar-toast
message=${this.toastMessage}
type=${this.toastType}
></nightjar-toast>
</div>
<div class="header">
<span class="name">Settings</span>
</div>
<form class="setting-form">
<div class="two-section-container">
<section class="content-block content-block-title">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) => {
this.infoIconMouseEntered(e, 'model');
}}
@mouseleave=${() => {
this.infoIconMouseLeft();
}}
>
<div class="name">Preferred Model</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
</div>
<span class="model-button">
<span class="model-mode-text">${this.selectedModel}</span>
<select
class="model-mode-select"
value="${supportedModelReverseLookup[this.selectedModel]}"
@change=${(e: InputEvent) => this.modelSelectChanged(e)}
>
<optgroup label="Remote LLMs">
${remoteModelSelectOptions}
</optgroup>
<optgroup label="Local LLMs">
${localModelSelectOptions}
</optgroup>
</select>
</span>
</section>
<section
class="content-block content-block-api"
?no-show=${this.selectedModel ===
SupportedRemoteModel['gpt-3.5-free'] ||
this.selectedModelFamily === ModelFamily.local}
>
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) => {
this.infoIconMouseEntered(e, 'api-key');
}}
@mouseleave=${() => {
this.infoIconMouseLeft();
}}
>
<div class="name">
${apiKeyMap[this.selectedModel as SupportedRemoteModel]} API
Key
</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info"
>${apiKeyDescriptionMap[this.selectedModelFamily]}</span
>
</div>
<div class="length-input-container">
<div class="input-container">
<input
type="text"
class="content-text api-input"
id="text-input-api"
value="${this.userConfig.llmAPIKeys[
this.selectedModelFamily
]}"
placeholder=""
@input=${(e: InputEvent) => {
const element = e.currentTarget as HTMLInputElement;
this.apiInputValue = element.value;
}}
/>
<div class="right-loader">
<div
class="prompt-loader"
?is-hidden=${!this.showModelLoader}
>
<div class="loader-container">
<div class="circle-loader"></div>
</div>
</div>
</div>
</div>
<button
class="add-button"
?has-set=${this.userConfig.llmAPIKeys[
this.selectedModelFamily
] === this.apiInputValue || this.apiInputValue === ''}
@click=${(e: MouseEvent) => this.addButtonClicked(e)}
>
${this.userConfig.llmAPIKeys[this.selectedModelFamily] === ''
? 'Add'
: 'Update'}
</button>
</div>
</section>
<section
class="content-block content-block-local"
?no-show=${this.selectedModelFamily !== ModelFamily.local}
>
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) => {
this.infoIconMouseEntered(e, 'local-llm');
}}
@mouseleave=${() => {
this.infoIconMouseLeft();
}}
>
<div class="name">Local LLM</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info">${this.localModelMessage}</span>
</div>
<div class="download-info-container">
<button
class="add-button"
@mouseenter=${(e: MouseEvent) => {
const element = e.currentTarget as HTMLElement;
tooltipMouseEnter(
e,
'Installing local LLMs for the first time can take several minutes. Once installed, activating them would be much faster.',
'top',
this.tooltipConfig,
200,
element,
10
);
}}
@mouseleave=${() => {
this.infoIconMouseLeft();
}}
?has-set=${this.userConfig.preferredLLM ===
this.selectedModel}
?is-disabled=${!this.curDeviceSupportsLocalModel}
@click=${(e: MouseEvent) => this.localModelButtonClicked(e)}
>
${this.userConfig.preferredLLM === this.selectedModel
? 'Activated'
: this.selectedLocalModelInCache
? 'Activate'
: 'Install'}
(${localModelSizeMap[
this.selectedModel as SupportedLocalModel
]})
</button>
<nightjar-progress-bar
?is-shown=${this.showLocalModelProgressBar}
></nightjar-progress-bar>
</div>
</section>
</div>
</form>
<div
id="popper-tooltip-setting"
class="popper-tooltip hidden"
role="tooltip"
>
<span class="popper-content"></span>
<div class="popper-arrow"></div>
</div>
</div>
`;
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/panel-setting/panel-setting.ts#L506-L716 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PrivacyDialogSimple.constructor | constructor() {
super();
this.confirmAction = () => {};
} | // ===== Lifecycle Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/privacy-dialog/privacy-dialog-simple.ts#L29-L32 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PrivacyDialogSimple.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/privacy-dialog/privacy-dialog-simple.ts#L42-L42 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PrivacyDialogSimple.initData | initData = async () => {} | // ===== Custom Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/privacy-dialog/privacy-dialog-simple.ts | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PrivacyDialogSimple.dialogClicked | dialogClicked(e: MouseEvent) {
if (e.target === this.dialogElement) {
this.dialogElement.close();
}
} | // ===== Event Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/privacy-dialog/privacy-dialog-simple.ts#L56-L60 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PrivacyDialogSimple.render | render() {
return html`
<dialog
class="confirm-dialog"
@click=${(e: MouseEvent) => this.dialogClicked(e)}
>
<div class="header">
<div class="header-name">Wordflow Privacy</div>
</div>
<div class="content">
<div class="message">
<p>
We <strong><u>DO NOT</u></strong> store your input text or any
sensitive data (e.g., name, email address, IP address, and
location). We only store community-shared prompts and the number
of times a prompt is run.
</p>
</div>
</div>
<div class="button-block">
<button
class="cancel-button"
@click=${(e: MouseEvent) => this.cancelClicked(e)}
>
Okay
</button>
</div>
</dialog>
`;
} | // ===== Templates and Styles ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/privacy-dialog/privacy-dialog-simple.ts#L70-L101 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PrivacyDialog.constructor | constructor() {
super();
this.confirmAction = () => {};
} | // ===== Lifecycle Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/privacy-dialog/privacy-dialog.ts#L29-L32 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PrivacyDialog.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/privacy-dialog/privacy-dialog.ts#L42-L42 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PrivacyDialog.initData | initData = async () => {} | // ===== Custom Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/privacy-dialog/privacy-dialog.ts | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PrivacyDialog.dialogClicked | dialogClicked(e: MouseEvent) {
if (e.target === this.dialogElement) {
this.dialogElement.close();
}
} | // ===== Event Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/privacy-dialog/privacy-dialog.ts#L56-L60 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | PrivacyDialog.render | render() {
return html`
<dialog
class="confirm-dialog"
@click=${(e: MouseEvent) => this.dialogClicked(e)}
>
<div class="header">
<div class="header-name">Usage Data Collection Acknowledgement</div>
</div>
<div class="content">
<div class="message">
<p>
You are being asked to be a volunteer in a research study. The
purpose of this study is to understand user interaction patterns
and preferences when using large language models.
</p>
<p>
<strong
>When you use this web app to run or share a prompt, the prompt
prefix, timestamp, and AI model configurations (e.g.,
temperature) will be collected. We <u>DO NOT</u> collect your
input text or any sensitive data (e.g., username, email address,
IP address, location). Please do not include personal
information in the prompt prefix.</strong
>
</p>
<p>
The risks involved are no greater than those involved in daily
activities. You will not benefit or be compensated for joining
this study. We will comply with any applicable laws and
regulations regarding confidentiality. To make sure that this
research is being carried out in the proper way, the Georgia
Institute of Technology IRB may review study records. The Office
of Human Research Protections may also look at study records. If
you have any questions about the study, you may contact the PI at
email polo@gatech.edu. If you have any questions about your rights
as a research subject, you may contact Georgia Institute of
Technology Office of Research Integrity Assurance at
IRB@gatech.edu. Thank you for participating in this study! By
proceeding to use this web app, you indicate your consent to be in
the study.
</p>
</div>
<div class="accordion-container" ?hide-content=${!this.showGDPR}>
<div
class="accordion-header"
@click=${() => {
this.showGDPR = !this.showGDPR;
if (this.showGDPR) {
this.showPRC = false;
}
}}
>
<div class="name">
General Data Protection Regulation (GDPR) Consent
</div>
<span class="svg-icon arrow-icon">${unsafeHTML(arrowIcon)}</span>
</div>
<div class="accordion-content">${gdprContent}</div>
</div>
<div class="accordion-container" ?hide-content=${!this.showPRC}>
<div
class="accordion-header"
@click=${() => {
this.showPRC = !this.showPRC;
if (this.showPRC) {
this.showGDPR = false;
}
}}
>
<div class="name">
Republic of China (PRC) Personal Information Protection Law
Consent
</div>
<span class="svg-icon arrow-icon">${unsafeHTML(arrowIcon)}</span>
</div>
<div class="accordion-content">${prcConsent}</div>
</div>
</div>
<div class="button-block">
<button
class="cancel-button"
@click=${(e: MouseEvent) => this.cancelClicked(e)}
>
Cancel
</button>
<button
class="confirm-button"
@click=${(e: MouseEvent) => this.confirmClicked(e)}
>
Agree
</button>
</div>
</dialog>
`;
} | // ===== Templates and Styles ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/privacy-dialog/privacy-dialog.ts#L80-L181 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarProgressBar.constructor | constructor() {
super();
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/progress-bar/progress-bar.ts#L36-L38 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarProgressBar.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {
if (changedProperties.has('progress')) {
this.updateProgress(this.progress);
}
} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/progress-bar/progress-bar.ts#L66-L70 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarProgressBar.initData | async initData() {} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/progress-bar/progress-bar.ts#L75-L75 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarProgressBar.updateProgress | updateProgress(progress: number) {
this._progress = Math.min(1, Math.max(0, progress));
this.curProgressWidth = this.totalWidth * this._progress;
this.alignProgressLabel();
} | /**
* Update the current progress
* @param progress Progress form 0 to 1
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/progress-bar/progress-bar.ts#L103-L107 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarProgressBar.render | render() {
return html`
<div class="progress-bar">
<div
class="current-progress"
?is-done=${this._progress >= 1}
style="width: ${this.curProgressWidth}px;"
>
<span class="progress-label" ?align-left=${this.labelAlign === 'left'}
>${Math.floor(this._progress * 100)}%</span
>
</div>
</div>
`;
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/progress-bar/progress-bar.ts#L120-L134 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptCard.constructor | constructor() {
super();
this.promptData = getEmptyPromptDataRemote();
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-card/prompt-card.ts#L39-L42 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptCard.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-card/prompt-card.ts#L48-L48 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptCard.initData | async initData() {} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-card/prompt-card.ts#L53-L53 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptCard.tagClicked | tagClicked(e: MouseEvent, tag: string) {
e.preventDefault();
e.stopPropagation();
// Notify the parent
const event = new CustomEvent('tag-clicked', {
detail: tag,
bubbles: true,
composed: true
});
this.dispatchEvent(event);
} | /**
* Tag clicked event handler
* @param tag Clicked tag name
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-card/prompt-card.ts#L62-L73 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptCard.render | render() {
// Compose the tag list
let tagList = html``;
if (this.promptData.tags !== undefined) {
if (!this.isLocalPrompt) {
for (const tag of this.promptData.tags) {
tagList = html`${tagList}
<span
class="tag"
?is-selected=${this.curSelectedTag === tag}
@click=${(e: MouseEvent) => this.tagClicked(e, tag)}
>${tag}</span
>`;
}
}
}
// Compose the share info
const numFormatter = d3.format(',');
let dateFormatter = d3.timeFormat('%b %d, %Y');
const fullTimeFormatter = d3.timeFormat('%b %d, %Y %H:%M');
const date = d3.isoParse(this.promptData.created)!;
const curDate = new Date();
// Ignore the year if it is the same year as today
if (date.getFullYear == curDate.getFullYear) {
dateFormatter = d3.timeFormat('%b %d');
}
const user =
this.promptData.userName === '' ? 'Anonymous' : this.promptData.userName;
let userTemplate = html``;
if (!this.isLocalPrompt) {
userTemplate = html`
<span class="name" title=${user ? user : ''}>${user}</span>
<span class="separator"></span>
`;
}
return html`
<div class="prompt-card" ?is-local=${this.isLocalPrompt}>
<div class="header">
<span class="icon"><span>${this.promptData.icon}</span></span>
<span class="name-wrapper">
<span class="name" title=${this.promptData.title}
>${this.promptData.title}</span
>
</span>
</div>
<div class="prompt">${this.promptData.prompt}</div>
<div class="tag-list">${tagList}</div>
<div class="footer">
<span class="run-count"
>${numFormatter(this.promptData.promptRunCount)} runs</span
>
<span class="share-info">
${userTemplate}
<span class="date" title=${fullTimeFormatter(date)}
>${dateFormatter(date)}</span
>
</span>
</div>
</div>
`;
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-card/prompt-card.ts#L82-L149 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.constructor | constructor() {
super();
this.promptData = getEmptyPromptDataLocal();
this.availableModels = structuredClone(ALL_MODELS);
this.placeholderEmoji =
EMOJI_CANDIDATES[Math.floor(Math.random() * EMOJI_CANDIDATES.length)];
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L225-L232 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {
if (changedProperties.has('promptData')) {
this.injectionMode = this.promptData.injectionMode;
this.temperature = this.promptData.temperature;
}
} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L249-L254 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.initData | async initData() {} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L259-L259 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.parseForm | parseForm() {
if (this.shadowRoot === null) {
throw Error('Shadow root is null.');
}
const newPromptData = getEmptyPromptDataLocal();
// Add the information that is not included in the input fields
// `forkFrom`, `key`, `promptRunCount`
// We will use a new `created` for the new data
newPromptData.forkFrom = this.promptData.forkFrom;
newPromptData.key = this.promptData.key;
newPromptData.promptRunCount = this.promptData.promptRunCount;
// Parse the title
const title = (
this.shadowRoot.querySelector('#text-input-title') as HTMLInputElement
).value;
newPromptData.title = title.slice(0, MAX_TITLE_LENGTH);
// Parse the icon
const icon = (
this.shadowRoot.querySelector('#text-input-icon') as HTMLInputElement
).value;
const match = icon.match(EMOJI_REGEX);
let iconChar = icon.slice(0, 1);
if (match) {
iconChar = match[0];
}
newPromptData.icon = iconChar;
// If the user doesn't set an icon, use the placeholder instead
if (newPromptData.icon === '') {
newPromptData.icon = this.placeholderEmoji;
}
// Parse the prompt
const prompt = (
this.shadowRoot.querySelector('#text-input-prompt') as HTMLInputElement
).value;
newPromptData.prompt = prompt.slice(0, MAX_PROMPT_LENGTH);
// Parse the temperature
newPromptData.temperature = this.temperature;
// Parse output parsing - pattern
const outputParsingPattern = (
this.shadowRoot.querySelector(
'#text-input-output-parsing-pattern'
) as HTMLInputElement
).value;
newPromptData.outputParsingPattern = outputParsingPattern.slice(
0,
MAX_OUTPUT_PARSING_LENGTH
);
// Parse output parsing - replacement
const outputParsingReplacement = (
this.shadowRoot.querySelector(
'#text-input-output-parsing-replacement'
) as HTMLInputElement
).value;
newPromptData.outputParsingReplacement = outputParsingReplacement.slice(
0,
MAX_OUTPUT_PARSING_LENGTH
);
// Parse injection mode
newPromptData.injectionMode = this.injectionMode;
// Parse the prompt description
const description = (
this.shadowRoot.querySelector(
'#text-input-description'
) as HTMLInputElement
).value;
newPromptData.description = description.slice(0, MAX_DESCRIPTION_LENGTH);
// Parse the tags
const tags = (
this.shadowRoot.querySelector('#text-input-tags') as HTMLInputElement
).value;
if (tags.length > 0) {
const tagsArray = tags.split(/\s*,\s*/);
const formattedTags = tagsArray.map(tag =>
tag.replace(/\s+/g, '-').toLowerCase()
);
newPromptData.tags = formattedTags.slice(0, MAX_TAGS_COUNT);
}
// Parse the user name
const userName = (
this.shadowRoot.querySelector('#text-input-user-name') as HTMLInputElement
).value;
newPromptData.userName = userName.slice(0, MAX_USER_NAME_LENGTH);
// Parse the recommended models
const modelCheckboxes =
this.shadowRoot.querySelectorAll<HTMLInputElement>('.model-checkbox');
const recommendedModels: string[] = [];
for (const checkbox of modelCheckboxes) {
if (checkbox.checked) {
recommendedModels.push(checkbox.name);
}
}
newPromptData.recommendedModels = recommendedModels;
return newPromptData;
} | /**
* Create a prompt object by parsing the current form. This function does not
* validate the user's inputs.
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L265-L377 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.savePrompt | savePrompt() {
if (this.toastComponent === undefined) {
throw Error('toastComponent is undefined.');
}
// Parse the input fields
const newPromptData = this.parseForm();
// Validate the data
if (newPromptData.title.length === 0) {
this.toastMessage = "Title can't be empty.";
this.toastType = 'error';
this.toastComponent.show();
return;
}
if (newPromptData.icon.length === 0) {
this.toastMessage = "Icon can't be empty.";
this.toastType = 'error';
this.toastComponent.show();
return;
}
if (newPromptData.prompt.length === 0) {
this.toastMessage = "Prompt can't be empty.";
this.toastType = 'error';
this.toastComponent.show();
return;
}
if (this.isNewPrompt) {
// Add the new prompt
this.promptManager.addPrompt(newPromptData);
} else {
// Update the old prompt
newPromptData.forkFrom = this.promptData.forkFrom;
this.promptManager.setPrompt(newPromptData);
}
this.toastComponent.hide();
this.closeButtonClicked();
} | /**
* Save the user's input as a prompt. It creates a new prompt or updates an
* existing prompt.
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L383-L424 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.sharePrompt | sharePrompt() {
if (this.toastComponent === undefined) {
throw Error('toastComponent is undefined.');
}
if (this.shadowRoot === null) {
throw Error('Shadow root is null');
}
if (this.confirmDialogComponent === undefined) {
throw Error('confirmDialogComponent is undefined');
}
// Parse the input fields
const newPromptData = this.parseForm();
// Validate the data
if (newPromptData.title.length === 0) {
this.toastMessage = "Title can't be empty.";
this.toastType = 'error';
this.toastComponent.show();
return;
}
if (newPromptData.icon.length === 0) {
this.toastMessage = "Icon can't be empty.";
this.toastType = 'error';
this.toastComponent.show();
return;
}
if (newPromptData.prompt.length === 0) {
this.toastMessage = "Prompt can't be empty.";
this.toastType = 'error';
this.toastComponent.show();
return;
}
if (newPromptData.description.length === 0) {
this.toastMessage =
"Description (under Sharing Settings) can't be empty.";
this.toastType = 'error';
this.toastComponent.show();
return;
}
if (newPromptData.tags.length === 0) {
this.toastMessage = "Tags (under Sharing Settings) can't be empty.";
this.toastType = 'error';
this.toastComponent.show();
return;
}
if (newPromptData.tags.length > MAX_TAGS_COUNT) {
this.toastMessage = `You can only enter at most ${MAX_TAGS_COUNT} tags.`;
this.toastType = 'error';
this.toastComponent.show();
return;
}
for (const tag of newPromptData.tags) {
if (tag.length < 2) {
this.toastMessage = 'Each tag should have least 2 characters.';
this.toastType = 'error';
this.toastComponent.show();
return;
}
if (tag.length > 20) {
this.toastMessage = 'Each tag should have at most 20 characters.';
this.toastType = 'error';
this.toastComponent.show();
return;
}
}
// Try to share the prompt first
if (this.isNewPrompt) {
// Add the new prompt
this.promptManager.addPrompt(newPromptData);
} else {
// Update the old prompt
newPromptData.forkFrom = this.promptData.forkFrom;
this.promptManager.setPrompt(newPromptData);
}
// Show the loader
const contentElement = this.shadowRoot.querySelector(
'.content'
) as HTMLElement;
const loaderElement = this.shadowRoot.querySelector(
'.prompt-loader'
) as HTMLElement;
const toastComponent = this.toastComponent;
loaderElement.style.setProperty('top', `${contentElement.scrollTop}px`);
contentElement.classList.add('no-scroll');
loaderElement.classList.remove('hidden');
const stopLoader = (status: number) => {
contentElement.classList.remove('no-scroll');
loaderElement.style.setProperty('top', '0px');
loaderElement.classList.add('hidden');
// If the status code is 515, the prompt already exists. We should the toast
if (status === 515) {
this.toastMessage =
'The same prompt has been shared by a user. Try a different prompt.';
this.toastType = 'error';
toastComponent.show();
} else if (status === 201) {
this.toastMessage = 'This prompt is shared.';
this.toastType = 'success';
toastComponent.show();
} else if (status > 400 && status < 600) {
this.toastMessage = 'Failed to share this prompt. Try again later.';
this.toastType = 'error';
toastComponent.show();
}
};
const dialogInfo: DialogInfo = {
header: 'Share Prompt',
message:
'Are you sure you want to share this prompt? You cannot unshare it. The shared content will be using a CC0 license.',
yesButtonText: 'Share',
actionKey: 'share-prompt-local'
};
const confirmAction = () => {
const event = new CustomEvent<SharePromptMessage>('share-clicked', {
bubbles: true,
composed: true,
detail: { data: newPromptData, stopLoader }
});
this.dispatchEvent(event);
};
const cancelAction = () => {
stopLoader(204);
};
this.confirmDialogComponent.show(dialogInfo, confirmAction, cancelAction);
} | /**
* Share the current prompt.
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L429-L572 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.deletePrompt | deletePrompt() {
if (this.confirmDialogComponent === undefined) {
throw Error('confirmDialogComponent is undefined');
}
const dialogInfo: DialogInfo = {
header: 'Delete Prompt',
message:
'Are you sure you want to delete this prompt? This action cannot be undone.',
yesButtonText: 'Delete',
actionKey: 'delete-prompt'
};
this.confirmDialogComponent.show(dialogInfo, () => {
this.promptManager.deletePrompt(this.promptData);
this.closeButtonClicked();
});
} | /**
* Delete the current prompt.
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L577-L594 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.accordionHeaderClicked | async accordionHeaderClicked(e: MouseEvent, type: 'advanced' | 'sharing') {
e.preventDefault();
if (type === 'advanced') {
if (!this.sliderComponent) {
throw Error('sliderComponent is not initialized');
}
this.showAdvancedOptions = !this.showAdvancedOptions;
// Need to force the slider to sync thumb, because its first time would fail
// as all elements inside the accordion are not rendered yet.
await this.updateComplete;
this.sliderComponent.syncThumb();
} else if (type === 'sharing') {
this.showSharingOptions = !this.showSharingOptions;
}
} | /**
* Event handler for clicking the accordion header
* @param e Event
* @param type Accordion type
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L604-L619 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.closeButtonClicked | closeButtonClicked() {
if (this.shadowRoot === null) {
throw Error('shadowRoot is null');
}
// Notify the parent
const event = new Event('close-clicked', {
bubbles: true,
composed: true
});
this.dispatchEvent(event);
// Clean up the input
const formElement = this.shadowRoot.querySelector(
'form.content'
) as HTMLFormElement;
formElement.reset();
// Collapse all accordions
this.showAdvancedOptions = false;
this.showSharingOptions = false;
// Hide toast
this.toastComponent?.hide();
} | /**
* Event handler for clicking the close button
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L624-L648 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.infoIconMouseEntered | infoIconMouseEntered(e: MouseEvent, field: Field) {
const target = (e.currentTarget as HTMLElement).querySelector(
'.info-icon'
) as HTMLElement;
tooltipMouseEnter(
e,
FIELD_INFO[field].tooltip,
'top',
this.tooltipConfig,
200,
target,
10
);
} | /**
* Event handler for mouse entering the info icon in each filed
* @param e Mouse event
* @param field Field type
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L655-L668 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.infoIconMouseLeft | infoIconMouseLeft() {
tooltipMouseLeave(this.tooltipConfig);
} | /**
* Event handler for mouse leaving the info icon in each filed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L673-L675 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.iconInput | iconInput(e: InputEvent) {
const iconElement = e.currentTarget as HTMLInputElement;
// Check if the delete key is pressed
if (e.inputType === 'deleteContentBackward') {
iconElement.value = ''; // Empty the input field
} else {
// Check if there is an emoji in the icon element
const match = iconElement.value.match(EMOJI_REGEX);
if (match === null) {
// Use the first character
iconElement.value = iconElement.value.slice(0, 1);
} else {
// Use the first emoji
iconElement.value = match[0];
}
}
} | /**
* Only allow users to enter one character or one emoji in the icon input
* @param e Input event
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L681-L699 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.promptEditorBackgroundClicked | promptEditorBackgroundClicked(e: MouseEvent) {
const target = e.target as HTMLElement;
if (target.classList.contains('prompt-editor')) {
this.closeButtonClicked();
}
} | /**
* Close the modal if the user clicks the background
* @param e Mouse event
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L705-L710 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptEditor.render | render() {
// Compose the model checkbox lists
let modelCheckboxes = html``;
for (const model of this.availableModels) {
// Check if the model is included in the recommended model list
modelCheckboxes = html`${modelCheckboxes}
<div class="checkbox-group">
<input
type="checkbox"
name="${model.name}"
class="model-checkbox"
id="model-checkbox-${model.name}"
?checked=${this.promptData.recommendedModels.includes(model.name)}
/>
<label for="model-checkbox-${model.name}">${model.label}</label>
</div> `;
}
return html`
<div
class="prompt-editor"
@mousedown=${(e: MouseEvent) => this.promptEditorBackgroundClicked(e)}
>
<div class="prompt-window">
<div class="toast-container">
<nightjar-toast
message=${this.toastMessage}
type=${this.toastType}
></nightjar-toast>
</div>
<div class="header">
<div class="title-bar">
<span class="name"
>${this.isNewPrompt
? 'New Private Prompt'
: 'Edit Prompt'}</span
>
<span class="svg-icon" @click=${() => this.closeButtonClicked()}
>${unsafeHTML(crossIcon)}</span
>
</div>
</div>
<form class="content">
<div class="prompt-loader hidden">
<div class="loader-container">
<span class="label">Sharing Prompt</span>
<div class="circle-loader"></div>
</div>
</div>
<div class="two-section-container">
<section class="content-block content-block-title">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) =>
this.infoIconMouseEntered(e, Field.title)}
@mouseleave=${() => this.infoIconMouseLeft()}
>
<div class="name required-name">${Field.title}</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info"
>${FIELD_INFO[Field.title].description}</span
>
</div>
<div class="length-input-container">
<input
type="text"
class="content-text title-input"
id="text-input-title"
value="${this.promptData.title}"
maxlength="${MAX_TITLE_LENGTH}"
placeholder=${FIELD_INFO[Field.title].placeholder}
@input=${(e: InputEvent) => {
const inputElement = e.currentTarget as HTMLInputElement;
this.titleLengthRemain =
MAX_TITLE_LENGTH - inputElement.value.length;
}}
/>
<span class="length-counter title-length-counter"
>${this.titleLengthRemain}</span
>
</div>
</section>
<section class="content-block content-block-icon">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) =>
this.infoIconMouseEntered(e, Field.icon)}
@mouseleave=${() => this.infoIconMouseLeft()}
>
<div class="name required-name">${Field.icon}</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
</div>
<div class="content-icon-wrapper">
<input
type="text"
class="content-text"
id="text-input-icon"
value="${this.promptData.icon}"
@input=${(e: InputEvent) => this.iconInput(e)}
placeholder="${this.placeholderEmoji}"
maxlength="20"
/>
</div>
</section>
</div>
<section class="content-block content-block-prompt">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) =>
this.infoIconMouseEntered(e, Field.prompt)}
@mouseleave=${() => this.infoIconMouseLeft()}
>
<div class="name required-name">${Field.prompt}</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info"
>${FIELD_INFO[Field.prompt].description}</span
>
</div>
<textarea
type="text"
class="content-text prompt-input"
id="text-input-prompt"
maxlength="${MAX_PROMPT_LENGTH}"
placeholder="${FIELD_INFO[Field.prompt].placeholder}"
>
${this.promptData.prompt}</textarea
>
</section>
<div
class="accordion-container"
?hide-content=${!this.showAdvancedOptions}
>
<div
class="accordion-header"
@click=${(e: MouseEvent) => {
this.accordionHeaderClicked(e, 'advanced');
}}
>
<div class="name">Advanced Settings</div>
<span class="svg-icon arrow-icon"
>${unsafeHTML(arrowIcon)}</span
>
</div>
<div class="accordion-content">
<section class="content-block">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) =>
this.infoIconMouseEntered(e, Field.temperature)}
@mouseleave=${() => this.infoIconMouseLeft()}
>
<div class="name">${Field.temperature}</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info"
>${FIELD_INFO[Field.temperature].description}</span
>
</div>
<div class="slider-container">
<nightjar-slider
min=${0}
max=${1}
curValue=${this.temperature}
.styleConfig=${{
foregroundColor: 'var(--gray-500)',
backgroundColor: 'var(--gray-300)'
}}
@valueChanged=${(e: CustomEvent<ValueChangedMessage>) => {
this.temperature = e.detail.value;
}}
></nightjar-slider>
<input
type="text"
class="content-text"
id="text-input-temperature"
value="${round(this.temperature, 2)}"
maxlength="${MAX_OUTPUT_PARSING_LENGTH}"
placeholder=${this.temperature}
@change=${(e: InputEvent) => {
const target = e.currentTarget as HTMLInputElement;
const value = parseFloat(target.value);
this.temperature = Math.min(1, Math.max(0, value));
target.value = `${round(this.temperature, 2)}`;
}}
/>
</div>
</section>
<section class="content-block">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) =>
this.infoIconMouseEntered(
e,
Field.outputParsingPattern
)}
@mouseleave=${() => this.infoIconMouseLeft()}
>
<div class="name">${Field.outputParsingPattern}</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info"
>${FIELD_INFO[Field.outputParsingPattern]
.description}</span
>
</div>
<input
type="text"
class="content-text"
id="text-input-output-parsing-pattern"
value="${this.promptData.outputParsingPattern || ''}"
maxlength="${MAX_OUTPUT_PARSING_LENGTH}"
placeholder=${FIELD_INFO[Field.outputParsingPattern]
.placeholder}
/>
</section>
<section class="content-block">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) =>
this.infoIconMouseEntered(
e,
Field.outputParsingReplacement
)}
@mouseleave=${() => this.infoIconMouseLeft()}
>
<div class="name">${Field.outputParsingReplacement}</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info"
>${FIELD_INFO[Field.outputParsingReplacement]
.description}</span
>
</div>
<input
type="text"
class="content-text"
id="text-input-output-parsing-replacement"
value="${this.promptData.outputParsingReplacement || ''}"
maxlength="${MAX_OUTPUT_PARSING_LENGTH}"
placeholder=${FIELD_INFO[Field.outputParsingReplacement]
.placeholder}
/>
</section>
<section class="content-block">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) =>
this.infoIconMouseEntered(e, Field.injectionMode)}
@mouseleave=${() => this.infoIconMouseLeft()}
>
<div class="name">${Field.injectionMode}</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info"
>${FIELD_INFO[Field.injectionMode].description}</span
>
</div>
<span class="injection-button">
<span class="injection-mode-text"
>${INJECTION_MODE_MAP[this.injectionMode]}</span
>
<select
class="injection-mode-select"
value="${this.injectionMode}"
@change=${(e: InputEvent) => {
const select = e.currentTarget as HTMLSelectElement;
if (select.value === 'replace') {
this.injectionMode = 'replace';
} else {
this.injectionMode = 'append';
}
}}
>
<option value="replace">
${INJECTION_MODE_MAP.replace}
</option>
<option value="append">
${INJECTION_MODE_MAP.append}
</option>
</select>
</span>
</section>
</div>
</div>
<div
class="accordion-container"
?hide-content=${!this.showSharingOptions}
>
<div
class="accordion-header"
@click=${(e: MouseEvent) => {
this.accordionHeaderClicked(e, 'sharing');
}}
>
<div class="name">Sharing Settings</div>
<span class="svg-icon arrow-icon"
>${unsafeHTML(arrowIcon)}</span
>
</div>
<div class="accordion-content">
<section class="content-block">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) =>
this.infoIconMouseEntered(e, Field.description)}
@mouseleave=${() => this.infoIconMouseLeft()}
>
<div class="name required-name share">
${Field.description}
</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info"
>${FIELD_INFO[Field.description].description}</span
>
</div>
<textarea
type="text"
class="content-text prompt-description"
id="text-input-description"
maxlength="${MAX_DESCRIPTION_LENGTH}"
placeholder=${FIELD_INFO[Field.description].placeholder}
>
${this.promptData.description || ''}</textarea
>
</section>
<section class="content-block">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) =>
this.infoIconMouseEntered(e, Field.tags)}
@mouseleave=${() => this.infoIconMouseLeft()}
>
<div class="name required-name share">${Field.tags}</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info"
>${FIELD_INFO[Field.tags].description}</span
>
</div>
<input
type="text"
class="content-text"
id="text-input-tags"
value="${this.promptData.tags !== undefined
? this.promptData.tags.join(', ')
: ''}"
maxlength="${MAX_TAGS_LENGTH}"
placeholder=${FIELD_INFO[Field.tags].placeholder}
/>
</section>
<section class="content-block">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) =>
this.infoIconMouseEntered(e, Field.userName)}
@mouseleave=${() => this.infoIconMouseLeft()}
>
<div class="name">${Field.userName}</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info"
>${FIELD_INFO[Field.userName].description}</span
>
</div>
<input
type="text"
class="content-text"
id="text-input-user-name"
value="${this.promptData.userName || ''}"
maxlength="${MAX_USER_NAME_LENGTH}"
/>
</section>
<section class="content-block">
<div class="name-row">
<div
class="name-container"
@mouseenter=${(e: MouseEvent) =>
this.infoIconMouseEntered(e, Field.recommendedModels)}
@mouseleave=${() => this.infoIconMouseLeft()}
>
<div class="name">${Field.recommendedModels}</div>
<span class="svg-icon info-icon"
>${unsafeHTML(infoIcon)}</span
>
</div>
<span class="name-info"
>${FIELD_INFO[Field.recommendedModels].description}</span
>
</div>
<div
class="model-checkbox-container"
id="form-recommended-models"
>
${modelCheckboxes}
</div>
</section>
</div>
</div>
</form>
<div class="footer">
<div class="button-container">
<button
?no-display=${this.isNewPrompt}
class="footer-button"
@click=${() => this.deletePrompt()}
>
<span class="svg-icon">${unsafeHTML(deleteIcon)}</span>Delete
</button>
</div>
<div class="button-container">
<button class="footer-button" @click=${() => this.sharePrompt()}>
<span class="svg-icon">${unsafeHTML(shareIcon)}</span>Share
</button>
<button class="footer-button" @click=${() => this.savePrompt()}>
<span class="svg-icon">${unsafeHTML(saveIcon)}</span>Save
</button>
</div>
</div>
</div>
</div>
<div
id="popper-tooltip-editor"
class="popper-tooltip hidden"
role="tooltip"
>
<span class="popper-content"></span>
<div class="popper-arrow"></div>
</div>
<nightjar-confirm-dialog></nightjar-confirm-dialog>
`;
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-editor/prompt-editor.ts#L719-L1202 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptViewer.constructor | constructor() {
super();
this.promptData = getEmptyPromptDataRemote();
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-viewer/prompt-viewer.ts#L43-L46 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptViewer.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-viewer/prompt-viewer.ts#L52-L52 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptViewer.initData | async initData() {} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-viewer/prompt-viewer.ts#L57-L57 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptViewer.tagClicked | tagClicked(e: MouseEvent, tag: string) {
e.preventDefault();
e.stopPropagation();
} | /**
* Tag clicked event handler
* @param tag Clicked tag name
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-viewer/prompt-viewer.ts#L66-L69 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptViewer.closeButtonClicked | closeButtonClicked() {
if (this.shadowRoot === null) {
throw Error('shadowRoot is null');
}
// Notify the parent
const event = new Event('close-clicked', {
bubbles: true,
composed: true
});
this.dispatchEvent(event);
} | /**
* Event handler for clicking the close button
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-viewer/prompt-viewer.ts#L74-L85 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptViewer.promptEditorBackgroundClicked | promptEditorBackgroundClicked(e: MouseEvent) {
const target = e.target as HTMLElement;
if (target.classList.contains('prompt-viewer')) {
this.closeButtonClicked();
}
} | /**
* Close the modal if the user clicks the background
* @param e Mouse event
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-viewer/prompt-viewer.ts#L91-L96 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptViewer.shareButtonClicked | shareButtonClicked() {
const promptID = this.promptData.forkFrom.replace('prompt#', '');
const shareData: ShareData = {
title: 'Wordflow',
text: this.promptData.title,
url: `https://poloclub.github.io/wordflow?prompt=${promptID}`
};
navigator.share(shareData);
} | /**
* Use web share api to share this prompt
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-viewer/prompt-viewer.ts#L111-L119 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptViewer.getInfoPairs | getInfoPairs() {
const infos: InfoPair[] = [];
infos.push({ key: 'Injection mode', value: this.promptData.injectionMode });
if (this.promptData.recommendedModels.length > 0) {
const models = this.promptData.recommendedModels.join(', ');
infos.push({ key: 'Models', value: models });
}
if (this.promptData.outputParsingPattern !== '') {
infos.push({
key: 'Output pattern',
value: this.promptData.outputParsingPattern
});
}
if (this.promptData.outputParsingReplacement !== '') {
infos.push({
key: 'Output replacement',
value: this.promptData.outputParsingReplacement
});
}
return infos;
} | /**
* Create info as key-value pairs
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-viewer/prompt-viewer.ts#L128-L151 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowPromptViewer.render | render() {
// Compose the share info
const numFormatter = d3.format(',');
// d3.timeFormat('%m/%d/%Y');
let dateFormatter = d3.timeFormat('%b %d, %Y');
const fullTimeFormatter = d3.timeFormat('%b %d, %Y %H:%M');
const date = d3.isoParse(this.promptData.created)!;
const curDate = new Date();
// Ignore the year if it is the same year as today
if (date.getFullYear == curDate.getFullYear) {
dateFormatter = d3.timeFormat('%b %d');
}
const user =
this.promptData.userName === '' ? 'Anonymous' : this.promptData.userName;
// Compose the tag list
let tagList = html``;
for (const tag of this.promptData.tags) {
tagList = html`${tagList}
<span
class="tag"
?is-selected=${this.curSelectedTag === tag}
@click=${(e: MouseEvent) => this.tagClicked(e, tag)}
>${tag}</span
>`;
}
// Compose the info table
const infoPairs = this.getInfoPairs();
let infoContent = html``;
for (const pair of infoPairs) {
infoContent = html`${infoContent}
<span class="key">${pair.key}</span>
<span></span>
<span class="value">${pair.value}</span> `;
}
// Add a report row
infoContent = html`${infoContent}
<span class="key">Report</span>
<span></span>
<span class="value"
><a href="mailto:jayw@gatech.edu">Report a concern</a></span
> `;
// Add a sharing row
infoContent = html`${infoContent}
<span class="key">Share</span>
<span></span>
<span class="value"
><span class="text-button" @click=${() => this.shareButtonClicked()}
>Share with a friend</span
></span
> `;
return html`
<div
class="prompt-viewer"
@click=${(e: MouseEvent) => this.promptEditorBackgroundClicked(e)}
>
<div class="prompt-window">
<div class="header">
<div class="title-bar">
<span class="icon"><span>${this.promptData.icon}</span></span>
<span class="name">${this.promptData.title}</span>
<button
class="svg-icon"
@click=${() => this.closeButtonClicked()}
>
${unsafeHTML(crossIcon)}
</button>
</div>
<div class="info-bar">
<span class="user-name-wrapper">
<span class="user-name" title=${user}>${user}</span>
</span>
<div class="separator"></div>
<span class="date" title=${fullTimeFormatter(date)}
>${dateFormatter(date)}</span
>
<div class="separator"></div>
<span class="run-info"
>${numFormatter(this.promptData.promptRunCount)} runs</span
>
<button
class="add-button"
@click=${() => {
this.addButtonClicked();
}}
>
Add
</button>
</div>
</div>
<div class="content">
<section class="content-block">
<div class="name">Description</div>
<div class="content-text">${this.promptData.description}</div>
</section>
<section class="content-block">
<div class="name">Prompt</div>
<div class="content-text">${this.promptData.prompt}</div>
</section>
<section class="content-block">
<div class="name">Tags</div>
<div class="tag-list">${tagList}</div>
</section>
<section class="content-block">
<div class="name">More Info</div>
<div class="info-table">${infoContent}</div>
</section>
</div>
</div>
</div>
`;
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/prompt-viewer/prompt-viewer.ts#L156-L280 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSettingWindow.constructor | constructor() {
super();
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/setting-window/setting-window.ts#L103-L105 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSettingWindow.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/setting-window/setting-window.ts#L111-L111 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSettingWindow.initData | async initData() {} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/setting-window/setting-window.ts#L124-L124 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSettingWindow.showCommunityPrompt | showCommunityPrompt(prompt: PromptDataRemote) {
this.activeMenuItemIndex = 1;
this.communityPanelComponent.then(panel => {
panel.promptCardClicked(prompt);
});
} | /**
* Show a community prompt without clicking
* @param prompt remote prompt data
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/setting-window/setting-window.ts#L130-L135 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSettingWindow.menuItemClicked | menuItemClicked(index: number) {
this.activeMenuItemIndex = index;
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/setting-window/setting-window.ts#L140-L142 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSettingWindow.promptViewerAddClickHandler | promptViewerAddClickHandler(e: CustomEvent<PromptDataRemote>) {
if (!this.toastComponent) {
throw Error('Toast is undefined.');
}
const remotePrompt = e.detail;
const newLocalPrompt: PromptDataLocal = { ...remotePrompt, key: uuidv4() };
let curUserID = localStorage.getItem('user-id');
if (curUserID === null) {
console.warn('userID is not set.');
curUserID = uuidv4();
localStorage.setItem('user-id', curUserID);
}
// Clean up some fields
newLocalPrompt.created = new Date().toISOString();
newLocalPrompt.userName = '';
newLocalPrompt.userID = curUserID;
newLocalPrompt.promptRunCount = 0;
this.promptManager.addPrompt(newLocalPrompt);
// Show a toaster and switch the tab
this.toastMessage = 'Added the prompt to My Prompts.';
this.toastType = 'success';
this.toastComponent.show();
this.activeMenuItemIndex = 0;
} | /**
* Fork a remote prompt into the local library
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/setting-window/setting-window.ts#L147-L175 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSettingWindow.backgroundClicked | backgroundClicked(e: MouseEvent) {
const target = e.target as HTMLElement;
if (target.classList.contains('setting-window')) {
this.closeButtonClicked();
}
} | /**
* Close the modal if the user clicks the background
* @param e Mouse event
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/setting-window/setting-window.ts#L189-L194 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSettingWindow.render | render() {
const menuItems: MenuItem[] = [
{
name: 'My Prompts',
component: html`<wordflow-panel-local
class="setting-panel"
?is-shown=${this.activeMenuItemIndex === 0}
.promptManager=${this.promptManager}
.localPrompts=${this.localPrompts}
.favPrompts=${this.favPrompts}
></wordflow-panel-local>`
},
{
name: 'Community',
component: html`<wordflow-panel-community
class="setting-panel"
?is-shown=${this.activeMenuItemIndex === 1}
.remotePromptManager=${this.remotePromptManager}
.remotePrompts=${this.remotePrompts}
.popularTags=${this.popularTags}
@add-clicked=${(e: CustomEvent<PromptDataRemote>) =>
this.promptViewerAddClickHandler(e)}
></wordflow-panel-community>`
},
{
name: 'Settings',
component: html`<wordflow-panel-setting
class="setting-panel"
.userConfigManager=${this.userConfigManager}
.userConfig=${this.userConfig}
.textGenLocalWorker=${this.textGenLocalWorker}
?is-shown=${this.activeMenuItemIndex === 2}
></wordflow-panel-setting>`
}
];
// Compose the menu items
let menuItemsTemplate = html``;
for (const [i, item] of menuItems.entries()) {
menuItemsTemplate = html`${menuItemsTemplate}
<div
class="menu-item"
data-text="${item.name}"
?selected=${this.activeMenuItemIndex === i}
@click=${() => this.menuItemClicked(i)}
>
${item.name}
</div> `;
}
// Compose the panels
let panelTemplate = html``;
for (const item of menuItems) {
panelTemplate = html`${panelTemplate} ${item.component} `;
}
return html`
<div
class="setting-window"
@click=${(e: MouseEvent) => this.backgroundClicked(e)}
>
<div class="window">
<div class="toast-container">
<nightjar-toast
id="setting-toast"
message=${this.toastMessage}
type=${this.toastType}
></nightjar-toast>
</div>
<div class="header">
<div class="name">Prompt Manager</div>
<div
class="svg-icon close-button"
@click=${() => this.closeButtonClicked()}
>
${unsafeHTML(crossIcon)}
</div>
</div>
<div class="content">
<div class="menu">${menuItemsTemplate}</div>
<div class="panel">${panelTemplate}</div>
</div>
</div>
</div>
`;
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/setting-window/setting-window.ts#L203-L289 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSidebarMenu.constructor | constructor() {
super();
this.modeColorMap = {
add: {
backgroundColor: config.customColors.addedColor,
circleColor: config.colors['green-200']
},
replace: {
backgroundColor: config.customColors.replacedColor,
circleColor: config.colors['orange-200']
},
delete: {
backgroundColor: config.customColors.deletedColor,
circleColor: config.colors['pink-200']
},
summary: {
backgroundColor: 'inherit',
circleColor: config.colors['gray-300']
}
};
this.headerTextMap = {
add: 'Adding Text',
replace: 'Replacing Text',
delete: 'Removing Text',
summary: 'Editing Text'
};
this.counterNameMap = {
add: 'addition',
replace: 'replacement',
delete: 'deletion'
};
} | // ===== Lifecycle Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/sidebar-menu/sidebar-menu.ts#L63-L97 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSidebarMenu.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/sidebar-menu/sidebar-menu.ts#L103-L103 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSidebarMenu.initData | async initData() {} | // ===== Custom Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/sidebar-menu/sidebar-menu.ts#L117-L117 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSidebarMenu.footerButtonClicked | footerButtonClicked(e: MouseEvent) {
const target = e.target as HTMLElement;
if (target.tagName !== 'BUTTON') {
return;
}
// Event delegation based on the button that the user clicks
const buttonName = target.getAttribute('button-key');
if (buttonName === null) {
console.error('Clicking a button without button-key.');
return;
}
// Dispatch the event above shadow dom
const event = new CustomEvent<string>('footer-button-clicked', {
detail: buttonName,
bubbles: true,
composed: true
});
this.dispatchEvent(event);
} | // ===== Event Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/sidebar-menu/sidebar-menu.ts#L120-L141 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSidebarMenu.buttonMouseEntered | buttonMouseEntered(e: MouseEvent, message: string) {
const target = e.currentTarget as HTMLElement;
tooltipMouseEnter(e, message, 'top', this.tooltipConfig, 200, target, 10);
} | /**
* Event handler for mouse entering the info icon in each filed
* @param e Mouse event
* @param field Field type
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/sidebar-menu/sidebar-menu.ts#L148-L151 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSidebarMenu.buttonMouseLeft | buttonMouseLeft() {
tooltipMouseLeave(this.tooltipConfig);
} | /**
* Event handler for mouse leaving the info icon in each filed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/sidebar-menu/sidebar-menu.ts#L156-L158 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowSidebarMenu.render | render() {
// Compose the summary text
let summaryText = html``;
if (this.summaryCounter) {
for (const key of Object.keys(this.summaryCounter)) {
const k = key as keyof SidebarSummaryCounter;
const count = this.summaryCounter[k];
if (count > 0) {
summaryText = html`${summaryText}
<div
class="summary-row"
style="background-color: ${this.modeColorMap[k].backgroundColor};"
>
${count} ${this.counterNameMap[k]}${count > 1 ? 's' : ''}
</div>`;
}
}
}
return html`
<div
class="sidebar-menu"
?is-on-left=${this.isOnLeft}
?is-hidden=${this.isHidden}
>
<div
id="popper-tooltip-sidebar"
class="popper-tooltip hidden"
role="tooltip"
>
<span class="popper-content"></span>
<div class="popper-arrow"></div>
</div>
<div class="header-row">
<span
class="header-circle"
style="background-color: ${this.modeColorMap[this.mode]
.circleColor};"
></span>
<span class="header-name">${this.headerTextMap[this.mode]}</span>
</div>
<div class="content-row">
<div
class="text-block old-text"
?is-hidden=${this.mode === 'add' || this.mode === 'summary'}
style="background-color: ${this.mode === 'delete'
? this.modeColorMap[this.mode].backgroundColor
: 'inherent'};"
>
${this.oldText}
</div>
<div class="arrow" ?is-hidden=${this.mode !== 'replace'}></div>
<div
class="text-block new-text"
?is-hidden=${this.mode === 'delete' || this.mode === 'summary'}
style="background-color: ${this.modeColorMap[this.mode]
.backgroundColor};"
>
${this.newText}
</div>
<div
class="text-block summary-text"
?is-hidden=${this.mode !== 'summary'}
style="background-color: ${this.modeColorMap[this.mode]
.backgroundColor};"
>
${summaryText}
</div>
</div>
<div
class="footer-row"
@click=${(e: MouseEvent) => this.footerButtonClicked(e)}
>
<div class="group">
<button
class="button"
button-key=${this.mode === 'summary' ? 'accept-all' : 'accept'}
@mouseenter=${(e: MouseEvent) =>
this.buttonMouseEntered(
e,
this.mode === 'summary' ? 'Accept all' : 'Accept'
)}
@mouseleave=${() => this.buttonMouseLeft()}
>
<span class="svg-icon">${unsafeHTML(checkIcon)}</span>
</button>
<button
class="button"
button-key=${this.mode === 'summary' ? 'reject-all' : 'reject'}
@mouseenter=${(e: MouseEvent) =>
this.buttonMouseEntered(
e,
this.mode === 'summary' ? 'Reject all' : 'Reject'
)}
@mouseleave=${() => this.buttonMouseLeft()}
>
<span class="svg-icon">${unsafeHTML(crossIcon)}</span>
</button>
</div>
</div>
</div>
`;
} | // ===== Templates and Styles ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/sidebar-menu/sidebar-menu.ts#L161-L270 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarSlider.constructor | constructor() {
super();
} | // ===== Lifecycle Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/slider/slider.ts#L46-L48 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarSlider.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {
if (changedProperties.has('curValue') && this.curValue !== null) {
this.syncThumb();
}
} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/slider/slider.ts#L61-L65 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarSlider.initData | initData = async () => {} | // ===== Custom Methods ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/slider/slider.ts | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarSlider.syncThumb | syncThumb() {
if (this.curValue !== null) {
// Update the thumb to reflect the cur value
const track = this.backgroundTrackElement;
const thumb = this.middleThumbElement;
const rangeTrack = this.rangeTrackElement;
if (track && thumb && rangeTrack) {
const thumbBBox = thumb.getBoundingClientRect();
const trackBBox = track.getBoundingClientRect();
// Update the thumb and the range track
const progress = this.curValue / (this.max - this.min);
const xPos = progress * trackBBox.width - thumbBBox.width / 2;
thumb.style.left = `${xPos}px`;
rangeTrack.style.width = `${Math.max(0, xPos)}px`;
}
}
} | /**
* Sync thumb position to this.curValue
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/slider/slider.ts#L73-L91 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarSlider.thumbMouseDownHandler | thumbMouseDownHandler(e: MouseEvent) {
e.preventDefault();
e.stopPropagation();
const thumb = e.target! as HTMLElement;
if (!thumb.id.includes('thumb')) {
console.error('Thumb event target is not thumb itself.');
}
// const eventBlocker = this.component.querySelector('.grab-blocker')!;
const track = thumb.parentElement!;
const rangeTrack = track.querySelector('.range-track') as HTMLElement;
const thumbBBox = thumb.getBoundingClientRect();
const trackBBox = track.getBoundingClientRect();
const trackWidth = trackBBox.width;
// Need to use focus instead of active because FireFox doesn't treat dragging
// as active
thumb.focus();
const mouseMoveHandler = (e: MouseEvent) => {
e.preventDefault();
e.stopPropagation();
// Block the mouse event outside the slider
// eventBlocker.classList.add('activated');
const deltaX = e.pageX - trackBBox.x;
const progress = Math.min(1, Math.max(0, deltaX / trackWidth));
// Move the thumb
thumb.setAttribute('data-curValue', String(progress));
// Compute the position to move the thumb to
const xPos = progress * trackBBox.width - thumbBBox.width / 2;
thumb.style.left = `${xPos}px`;
rangeTrack.style.width = `${Math.max(0, xPos)}px`;
// Notify the parent about the change
const curValue = this.min + (this.max - this.min) * progress;
const event = new CustomEvent<ValueChangedMessage>('valueChanged', {
detail: {
value: curValue
}
});
this.dispatchEvent(event);
// Update the tooltip thumb
// this.moveTimeSliderThumb(progress);
};
const mouseUpHandler = () => {
document.removeEventListener('mousemove', mouseMoveHandler);
document.removeEventListener('mouseup', mouseUpHandler);
// eventBlocker.classList.remove('activated');
thumb.blur();
};
// Listen to mouse move on the whole page (users can drag outside of the
// thumb, track, or even WizMap!)
document.addEventListener('mousemove', mouseMoveHandler);
document.addEventListener('mouseup', mouseUpHandler);
} | /**
* Event handler for the thumb mousedown
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/slider/slider.ts#L97-L160 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarSlider.render | render() {
const cssVariables = {
'--foreground-color':
this.styleConfig?.foregroundColor || 'hsl(174, 41.28%, 78.63%)',
'--background-color':
this.styleConfig?.backgroundColor || 'hsl(174, 100%, 29.41%)'
};
return html`
<div class="slider" style=${styleMap(cssVariables)}>
<div class="slider-track background-track"></div>
<div class="slider-track range-track"></div>
<div
class="middle-thumb"
id="slider-middle-thumb"
tabindex="-1"
@mousedown=${(e: MouseEvent) => this.thumbMouseDownHandler(e)}
>
<div class="thumb-label thumb-label-middle">
<span class="thumb-label-span"></span>
</div>
</div>
</div>
`;
} | // ===== Templates and Styles ====== | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/slider/slider.ts#L163-L187 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | updateFloatingMenuPosition | const updateFloatingMenuPosition = async (
options: EventHandlerProps,
editor: Editor,
view: EditorView
) => {
const floatingMenuBox = await options.floatingMenuBox;
const $from = view.state.selection.$from;
const cursorCoordinate = view.coordsAtPos($from.pos);
// Need to bound the box inside the view
const floatingMenuBoxBBox = floatingMenuBox.getBoundingClientRect();
const windowHeight = window.innerHeight;
const invisibleHeight = window.scrollY;
// Get the line height in the editor element
const lineHeight = parseInt(
window.getComputedStyle(editor.options.element).lineHeight
);
const PADDING_OFFSET = 5;
const minTop =
invisibleHeight + floatingMenuBoxBBox.height / 2 + PADDING_OFFSET;
const maxTop =
windowHeight +
invisibleHeight -
floatingMenuBoxBBox.height / 2 -
PADDING_OFFSET;
const idealTop = cursorCoordinate.top + invisibleHeight + lineHeight / 2;
const boundedTop = Math.min(maxTop, Math.max(minTop, idealTop));
floatingMenuBox.style.marginTop = `${boundedTop}px`;
}; | /**
* Update the position of the floating menu
* @param options Props
* @param editor Editor
* @param view Editor view
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/event-handler.ts#L33-L64 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | diff_linesToCharsMunge_ | const diff_linesToCharsMunge_ = (text: string) => {
let chars = '';
// Walk the text, pulling out a substring for each line.
// text.split('\n') would would temporarily double our memory footprint.
// Modifying text would create many large strings to garbage collect.
let lineStart = 0;
let lineEnd = -1;
// Keeping our own length variable is faster than looking it up.
let lineArrayLength = lineArray.length;
while (lineEnd < text.length - 1) {
// eslint-disable-next-line no-useless-escape
lineEnd = text.replace(/[\n,\.;:]/g, ' ').indexOf(' ', lineStart);
if (lineEnd == -1) {
lineEnd = text.length - 1;
}
let line = text.substring(lineStart, lineEnd + 1);
if (
lineHash.hasOwnProperty
? // eslint-disable-next-line no-prototype-builtins
lineHash.hasOwnProperty(line)
: lineHash[line] !== undefined
) {
chars += String.fromCharCode(lineHash[line]);
} else {
if (lineArrayLength == maxLines) {
// Bail out at 65535 because
// String.fromCharCode(65536) == String.fromCharCode(0)
line = text.substring(lineStart);
lineEnd = text.length;
}
chars += String.fromCharCode(lineArrayLength);
lineHash[line] = lineArrayLength;
lineArray[lineArrayLength++] = line;
}
lineStart = lineEnd + 1;
}
return chars;
}; | /**
* Split a text into an array of strings. Reduce the texts to a string of
* hashes where each Unicode character represents one line.
* Modifies linearray and linehash through being a closure.
* @param {string} text String to encode.
* @return {string} Encoded string.
* @private
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-diff.ts#L37-L75 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.constructor | constructor() {
super();
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L124-L126 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L285-L285 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.initData | async initData() {} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L290-L290 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.isEmptySelection | isEmptySelection() {
if (this.editor === null) {
console.error('Editor is not initialized yet.');
return;
}
const { $from, $to } = this.editor.view.state.selection;
let hasSelection = $from.pos !== $to.pos;
// If the user select the collapse node, the selection range is also 1
if (Math.abs($from.pos - $to.pos) === 1) {
const node = $from.nodeAfter;
if (node && node.type.name === 'collapse') {
hasSelection = false;
}
}
return hasSelection;
} | /**
* Detection if the users has not selected anything
* @returns True if there is empty selection
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L407-L422 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.acceptChange | acceptChange() {
if (this.editor === null) {
throw Error('Editor is not fully initialized');
}
const view = this.editor.view;
const state = view.state;
const selection = state.selection;
const { $from } = selection;
const isActive = this._isEditActive();
if (!isActive) {
return;
}
// To accept the change, we only need to remove the mark or the node
if (this.editor.isActive('edit-highlight')) {
this.editor
.chain()
.focus()
.unsetMark('edit-highlight', { extendEmptyMarkRange: true })
.run();
} else if (this.editor.isActive('collapse')) {
// Move the cursor
const newSelection = TextSelection.create(state.doc, $from.pos);
const tr = state.tr;
tr.setSelection(newSelection);
// Remove the node
tr.delete($from.pos, $from.pos + 1);
view.dispatch(tr);
view.focus();
}
} | /**
* Accept the current active edit (replace, add, or delete)
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L427-L459 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.rejectChange | rejectChange() {
if (this.editor === null) {
throw Error('Editor is not fully initialized');
}
const view = this.editor.view;
const state = view.state;
const { selection, schema } = state;
const { $from } = selection;
const isActive = this._isEditActive();
if (!isActive) {
return;
}
// To reject a change, we need to replace the new content with old text
if (this.editor.isActive('edit-highlight')) {
const mark = $from.marks()[0];
const markAttribute = mark.attrs as EditHighlightAttributes;
// Find the range of the mark
let from = -1;
let to = -1;
state.doc.content.descendants((node, pos) => {
if (
node.marks.some(
m => (m.attrs as EditHighlightAttributes).id === markAttribute.id
)
) {
from = pos;
to = pos + node.nodeSize;
return false;
}
});
// Replace the text content in the highlight with the old text
const tr = state.tr;
if (markAttribute.oldText.length > 0) {
// Reject replacement
const newText = schema.text(markAttribute.oldText);
const newSelection = TextSelection.create(
state.doc,
from + newText.nodeSize
);
// Need to set the selection before replacing the text
tr.setSelection(newSelection);
tr.replaceWith(from, to, newText);
} else {
// Reject addition
tr.delete(from, to);
}
view.dispatch(tr);
view.focus();
} else if (this.editor.isActive('collapse')) {
// Remove the node
const node = $from.nodeAfter!;
const nodeAttrs = node.attrs as CollapseAttributes;
// Move the cursor
const newSelection = TextSelection.create(state.doc, $from.pos);
const tr = state.tr;
tr.setSelection(newSelection);
// Remove the node
tr.delete($from.pos, $from.pos + 1);
// Add new text node
const newText = schema.text(nodeAttrs['deleted-text']);
tr.insert($from.pos, newText);
view.dispatch(tr);
view.focus();
}
} | /**
* Reject the current active edit (replace, add, or delete)
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L464-L536 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.acceptAllChanges | acceptAllChanges() {
if (this.editor === null) {
throw Error('Editor is not fully initialized');
}
const view = this.editor.view;
const state = view.state;
const selection = state.selection;
const { $from, $to } = selection;
const tr = state.tr;
// Remove all the marks
const markType = state.schema.marks['edit-highlight'];
tr.removeMark($from.pos, $to.pos, markType);
// Remove all the collapse nodes
let positions: number[] = [];
state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
if (node.type.name === 'collapse') {
positions.push(pos);
}
});
// Delete from the end to not mess up the pos index
positions = positions.reverse();
for (const pos of positions) {
const node = state.doc.nodeAt(pos);
if (node) {
tr.delete(pos, pos + node.nodeSize);
}
}
view.dispatch(tr);
view.focus();
} | /**
* Accept all edits in the selection (replace, add, or delete)
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L541-L576 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.rejectAllChanges | rejectAllChanges() {
if (this.editor === null) {
throw Error('Editor is not fully initialized');
}
const view = this.editor.view;
const state = view.state;
const { selection, schema } = state;
const { $from, $to } = selection;
const tr = state.tr;
// To reject a change, we need to replace the new content with old text
let posOffset = 0;
state.doc.nodesBetween($from.pos, $to.pos, (node, pos) => {
// Reject adds and replacement
for (const mark of node.marks) {
const markAttribute = mark.attrs as EditHighlightAttributes;
if (mark.type.name === 'edit-highlight') {
const markFrom = pos + posOffset;
const markTo = pos + node.nodeSize + posOffset;
if (markAttribute.oldText.length === 0) {
// If the old text is empty, delete this mark node
tr.delete(markFrom, markTo);
posOffset -= node.nodeSize;
} else {
const newText = schema.text(markAttribute.oldText);
tr.replaceWith(markFrom, markTo, newText);
posOffset = posOffset - node.nodeSize + newText.nodeSize;
}
}
}
// Reject deletions
if (node.type.name === 'collapse') {
const nodeAttrs = node.attrs as CollapseAttributes;
const newText = schema.text(nodeAttrs['deleted-text']);
const nodeFrom = pos + posOffset;
const nodeTo = pos + node.nodeSize + posOffset;
tr.replaceWith(nodeFrom, nodeTo, newText);
posOffset = posOffset - node.nodeSize + newText.nodeSize;
}
});
view.dispatch(tr);
view.focus();
} | /**
* Reject all edits in the selection (replace, add, or delete)
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L581-L629 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.textGenLocalWorkerMessageHandler | textGenLocalWorkerMessageHandler(e: MessageEvent<TextGenLocalWorkerMessage>) {
switch (e.data.command) {
case 'finishTextGen': {
const message: TextGenMessage = {
command: 'finishTextGen',
payload: e.data.payload
};
this.textGenLocalWorkerResolve(message);
break;
}
case 'progressLoadModel': {
break;
}
case 'finishLoadModel': {
break;
}
case 'error': {
const message: TextGenMessage = {
command: 'error',
payload: e.data.payload
};
this.textGenLocalWorkerResolve(message);
break;
}
default: {
console.error('Worker: unknown message', e.data.command);
break;
}
}
} | /**
* Event handler for the text gen local worker
* @param e Text gen message
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L638-L671 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.floatingMenuToolsMouseEnterHandler | floatingMenuToolsMouseEnterHandler() {
if (this.editor === null) {
console.error('Editor is not initialized yet.');
return;
}
this.isHoveringFloatingMenu = true;
const { $from, $to } = this.editor.view.state.selection;
const hasSelection = this.isEmptySelection();
// Highlight the paragraph
if (!hasSelection) {
const node = $from.node();
if (node.content.size > 0) {
this._setParagraphAttribute($from, 'is-highlighted', 'true');
}
}
} | /**
* Highlight the currently effective selection. It is the user's selected
* text or the current paragraph (if there is no selection).
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L705-L721 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.floatingMenuToolsMouseLeaveHandler | floatingMenuToolsMouseLeaveHandler() {
if (this.editor === null) {
console.error('Editor is not initialized yet.');
return;
}
this.isHoveringFloatingMenu = false;
const { $from, $to } = this.editor.view.state.selection;
const hasSelection = this.isEmptySelection();
// Highlight the paragraph
if (!hasSelection) {
this._setParagraphAttribute($from, 'is-highlighted', null);
}
} | /**
* Cancel any highlighting set from mouseenter
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L726-L739 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.floatingMenuToolButtonClickHandler | floatingMenuToolButtonClickHandler(promptData: PromptDataLocal) {
if (this.editor === null) {
console.error('Editor is not initialized yet.');
return;
}
const { state } = this.editor.view;
const { $from, $to } = state.selection;
const hasSelection = this.isEmptySelection();
// Paragraph mode
if (!hasSelection) {
// Change the highlight style
this._setParagraphAttribute($from, 'is-highlighted', null);
if ($from.node().content.size > 0) {
this._setParagraphAttribute($from, 'is-loading', 'true');
}
// Find the paragraph node of the cursor's region
const paragraphNode = $from.node(1);
const paragraphPos = $from.before(1);
const oldText = paragraphNode.textContent;
const runRequest = this._runPrompt(promptData, oldText);
runRequest.then(message => {
// Cancel the loading style
this._setParagraphAttribute($from, 'is-loading', null);
this._dispatchLoadingFinishedEvent();
switch (message.command) {
case 'finishTextGen': {
// Success
if (this.editor === null) {
console.error('Editor is not initialized');
return;
}
if (DEV_MODE) {
console.info(
`Finished running prompt with [${this.userConfig.preferredLLM}]`
);
console.info(message.payload.result);
}
// If the users uses their own API key, record the run with only the
// prompt prefix
if (
this.userConfig.preferredLLM !==
SupportedRemoteModel['gpt-3.5-free']
) {
textGenWordflow(
'text-gen',
promptData.prompt,
'',
promptData.temperature,
promptData.userID,
supportedModelReverseLookup[this.userConfig.preferredLLM],
USE_CACHE
);
}
let newText = this._parseOutput(promptData, message.payload.result);
// Append the output to the end of the input text if the prompt
// uses append mode
if (promptData.injectionMode === 'append') {
if (oldText !== '') {
newText = oldText + '\n' + newText;
}
}
let diffText = this.diffParagraph(oldText, newText);
diffText = `<p>${diffText}</p>`;
this.editor
.chain()
.focus()
.insertContentAt(
{
from: paragraphPos,
to: paragraphPos + paragraphNode.nodeSize
},
diffText,
{ updateSelection: true }
)
.run();
this._updateAfterSuccessfulPromptRun(promptData);
break;
}
case 'error': {
this._handleError(message.payload.message);
}
}
});
} else {
// Selection mode
// Set the highlight
this.editor
.chain()
.focus()
.setMeta('addToHistory', false)
.setMark('loading-highlight')
.run();
// Generate new text
const oldText = state.doc.textBetween($from.pos, $to.pos);
const runRequest = this._runPrompt(promptData, oldText);
runRequest.then(message => {
if (this.editor === null) {
console.error('Editor is not initialized yet.');
return;
}
this._dispatchLoadingFinishedEvent();
// Remove the highlight
this.editor
.chain()
.focus()
.setMeta('addToHistory', false)
.unsetMark('loading-highlight', { extendEmptyMarkRange: true })
.run();
switch (message.command) {
case 'finishTextGen': {
if (this.editor === null) {
console.error('Editor is not initialized');
return;
}
if (DEV_MODE) {
console.info(message.payload.result);
}
// If the users uses their own API key, record the run with only the
// prompt prefix
if (
this.userConfig.preferredLLM !==
SupportedRemoteModel['gpt-3.5-free']
) {
textGenWordflow(
'text-gen',
promptData.prompt,
'',
promptData.temperature,
promptData.userID,
supportedModelReverseLookup[this.userConfig.preferredLLM],
USE_CACHE
);
}
let newText = this._parseOutput(promptData, message.payload.result);
// Append the output to the end of the input text if the prompt
// uses append mode
if (promptData.injectionMode === 'append') {
newText = oldText + ' ' + newText;
}
let diffText = this.diffParagraph(oldText, newText);
diffText = `${diffText}`;
const diffTextChunks = diffText.split('\n\n');
if (diffTextChunks.length > 1) {
let newDiffText = '';
for (const [i, chunk] of diffTextChunks.entries()) {
if (i === 0) {
// First chunk
newDiffText += `${chunk}<p></p>`;
} else if (i === diffTextChunks.length - 1) {
// Last chunk
newDiffText += `${chunk}`;
} else {
newDiffText += `<p>${chunk}</p><p></p>`;
}
}
diffText = newDiffText;
}
this.editor
.chain()
.focus()
.insertContentAt(
{
from: $from.pos,
to: $to.pos
},
diffText,
{ updateSelection: true }
)
.joinBackward()
.run();
this._updateAfterSuccessfulPromptRun(promptData);
break;
}
case 'error': {
this._handleError(message.payload.message);
}
}
});
}
} | /**
* Execute the prompt on the selected text
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L744-L950 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor._runPrompt | _runPrompt(promptData: PromptDataLocal, inputText: string) {
const curPrompt = this._formatPrompt(
promptData.prompt,
inputText,
INPUT_TEXT_PLACEHOLDER
);
let runRequest: Promise<TextGenMessage>;
switch (this.userConfig.preferredLLM) {
case SupportedRemoteModel['gpt-3.5']: {
runRequest = textGenGpt(
this.userConfig.llmAPIKeys[ModelFamily.openAI],
'text-gen',
curPrompt,
promptData.temperature,
'gpt-3.5-turbo',
USE_CACHE
);
break;
}
case SupportedRemoteModel['gpt-4']: {
runRequest = textGenGpt(
this.userConfig.llmAPIKeys[ModelFamily.openAI],
'text-gen',
curPrompt,
promptData.temperature,
'gpt-4-1106-preview',
USE_CACHE
);
break;
}
case SupportedRemoteModel['gemini-pro']: {
runRequest = textGenGemini(
this.userConfig.llmAPIKeys[ModelFamily.google],
'text-gen',
curPrompt,
promptData.temperature,
USE_CACHE
);
break;
}
// case SupportedLocalModel['mistral-7b-v0.2']:
case SupportedLocalModel['gemma-2b']:
case SupportedLocalModel['phi-2']:
case SupportedLocalModel['llama-2-7b']:
case SupportedLocalModel['tinyllama-1.1b']: {
runRequest = new Promise<TextGenMessage>(resolve => {
this.textGenLocalWorkerResolve = resolve;
});
const message: TextGenLocalWorkerMessage = {
command: 'startTextGen',
payload: {
apiKey: '',
prompt: curPrompt,
requestID: '',
temperature: promptData.temperature
}
};
this.textGenLocalWorker.postMessage(message);
break;
}
case SupportedRemoteModel['gpt-3.5-free']: {
runRequest = textGenWordflow(
'text-gen',
promptData.prompt,
inputText,
promptData.temperature,
promptData.userID,
'gpt-3.5-free',
USE_CACHE
);
break;
}
default: {
console.error('Unknown case ', this.userConfig.preferredLLM);
runRequest = textGenWordflow(
'text-gen',
promptData.prompt,
inputText,
promptData.temperature,
promptData.userID,
'gpt-3.5-free',
USE_CACHE
);
}
}
return runRequest;
} | /**
* Run the given prompt using the preferred model
* @returns A promise of the prompt inference
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L960-L1053 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor._handleError | _handleError(errorMessage: string) {
console.error('Failed to generate text', errorMessage);
let message = 'Failed to run this prompt. Try again later.';
if (errorMessage === 'time out') {
message = 'Fail to run this prompt (OpenAI API timed out!)';
}
if (errorMessage === 'Rate limit exceeded.') {
message = 'You have run too many prompts. Try again later.';
}
// Show a toast
const event = new CustomEvent<ToastMessage>('show-toast', {
bubbles: true,
composed: true,
detail: {
message,
type: 'error'
}
});
this.dispatchEvent(event);
} | /**
* Show a toast when the API call is timed out
* @param errorMessage Error message
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L1059-L1081 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor._updateAfterSuccessfulPromptRun | _updateAfterSuccessfulPromptRun(promptData: PromptDataLocal) {
if (this.editor === null) {
console.error('Editor is not initialized yet.');
return;
}
const newPrompt = structuredClone(promptData);
newPrompt.promptRunCount += 1;
this.promptManager.setPrompt(newPrompt);
// Also update the local storage
localStorage.setItem('has-run-a-prompt', 'true');
// Save the editor's content to local storage
const content = this.editor.getJSON();
localStorage.setItem('last-editor-content', JSON.stringify(content));
} | /**
* Increase the prompt run count by 1
* @param promptData Prompt data
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L1087-L1103 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor._formatPrompt | _formatPrompt(prompt: string, inputText: string, placeholder: string) {
let curPrompt = '';
if (prompt.includes(placeholder)) {
curPrompt = prompt.replace(placeholder, inputText);
} else {
curPrompt = prompt + '\n' + inputText;
}
return curPrompt;
} | /**
* Combine prompt prefix and the input text
* @param prompt Prompt prefix
* @param inputText Input text
* @param placeholder Placeholder string
* @returns Formatted prompt
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L1112-L1120 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor._parseOutput | _parseOutput(prompt: PromptDataLocal, output: string) {
if (prompt.outputParsingPattern === '') {
return output;
}
const pattern = new RegExp(prompt.outputParsingPattern);
let replacement = prompt.outputParsingReplacement;
if (replacement === '') {
replacement = '$1';
}
const outputText = output.replace(pattern, replacement);
return outputText;
} | /**
* Parse an LLM output using rules defined in a prompt
* @param prompt Prompt data
* @param output LLM output
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L1127-L1140 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor._isEditActive | _isEditActive() {
if (this.editor === null) {
throw Error('Editor is not fully initialized');
}
const view = this.editor.view;
const selection = view.state.selection;
const { $from } = selection;
let isActive = false;
if (this.editor.isActive('edit-highlight')) {
if ($from.marks().length > 0) {
isActive = true;
}
} else if (this.editor.isActive('collapse')) {
if ($from.nodeAfter !== null) {
isActive = true;
}
}
return isActive;
} | /**
* Helper method to check if the user has selected an edit
* @returns True if an edit is actively selected
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L1146-L1167 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor._setParagraphAttribute | _setParagraphAttribute(
$from: ResolvedPos,
attribute: string,
value: string | null
) {
if (this.editor === null) {
console.error('Editor is not initialized yet.');
return;
}
// Find the paragraph node of the cursor's region
const paragraphNode = $from.node(1);
const paragraphPos = $from.before(1);
// Update the node's attributes to include the highlighted class
const updatedAttrs = {
...paragraphNode.attrs
};
updatedAttrs[attribute] = value;
const tr = this.editor.view.state.tr;
tr.setNodeMarkup(paragraphPos, null, updatedAttrs);
tr.setMeta('addToHistory', false);
this.editor.view.dispatch(tr);
} | /**
* Set the attribute of the current paragraph node
* @param $from From position of the selection
* @param attribute Attribute name
* @param value Attribute value
* @returns void
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L1176-L1200 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor._dispatchLoadingFinishedEvent | _dispatchLoadingFinishedEvent() {
const event = new Event('loading-finished', {
bubbles: true,
composed: true
});
this.dispatchEvent(event);
} | /**
* Notify the parent that the loading is finished.
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L1205-L1211 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | WordflowTextEditor.render | render() {
return html` <div class="text-editor-container">
<div
class="text-editor"
?is-hovering-floating-menu=${this.isHoveringFloatingMenu}
></div>
</div>`;
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/text-editor/text-editor.ts#L1216-L1223 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarToast.constructor | constructor() {
super();
} | //==========================================================================|| | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/toast/toast.ts#L109-L111 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
wordflow | github_2023 | poloclub | typescript | NightjarToast.willUpdate | willUpdate(changedProperties: PropertyValues<this>) {} | /**
* This method is called before new DOM is updated and rendered
* @param changedProperties Property that has been changed
*/ | https://github.com/poloclub/wordflow/blob/09840c4b7b4434152c83b55c5d47ab85d367e772/src/components/toast/toast.ts#L117-L117 | 09840c4b7b4434152c83b55c5d47ab85d367e772 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.