Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changeset/plain-forks-serve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
'@better-comments-for-github/extension': patch
'@better-comments-for-github/core': patch
---

Reply is not resetted on discussion page after submit
18 changes: 18 additions & 0 deletions extension/src/entrypoints/editor-content.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/

import { mountEditor } from '@better-comments-for-github/core/render'
import { log } from '@better-comments-for-github/core/editor/utils/logger'
import {
createGitHubEditorInstance,
createGitHubPageInstance,
Expand Down Expand Up @@ -76,6 +77,16 @@ export default defineUnlistedScript(() => {
textarea,
dispose,
)

log(
`Create editor instance`,
{
editorInstance,
textarea,
},
{ id: editorInstance.id },
)

const editorInjector = new GitHubEditorInjector()
editorInstance.setInjector(editorInjector)
registerGitHubEditorInstance(this, textarea, editorInstance)
Expand Down Expand Up @@ -103,6 +114,10 @@ export default defineUnlistedScript(() => {
// Old comment component of GitHub, This is still present in pull requests
const jsCommentField = nativeTextareaHandler.findTextarea()
if (jsCommentField) {
log(`GitHub textarea is native/rails`, {
id: editorInstance.id,
})

type = 'native'
setTextareaRef(jsCommentField)

Expand Down Expand Up @@ -147,6 +162,7 @@ export default defineUnlistedScript(() => {
nativeTextareaHandler.getMountEditorFn()
} else {
type = 'react'
log(`${editorInstance.id} - GitHub textarea is react-based`)

reactTextareaHandler.loadSuggestionDataAsync(element, {
onSuggestionDataChange: (data) => setSuggestionData(data),
Expand Down Expand Up @@ -174,6 +190,7 @@ export default defineUnlistedScript(() => {
// TODO: potential perforamnce issue
const observer = new MutationObserver((entry) => {
const ref = textareaRef()

if (!ref || !ref.isConnected) {
// This is needed to trigger a re-execution of the
// effect that will check if the textarea is still connected
Expand Down Expand Up @@ -201,6 +218,7 @@ export default defineUnlistedScript(() => {

editorElement.setDisposer(
mountEditor(root, {
id: editorInstance.id,
currentUsername,
suggestionData,
open: showOldEditor,
Expand Down
19 changes: 1 addition & 18 deletions extension/src/entrypoints/iframe-worker.html
Original file line number Diff line number Diff line change
Expand Up @@ -22,24 +22,7 @@
<title>MDN Example - Embedded worker</title>
</head>
<body>
<!-- dev only -->
<!--<script>-->
<!-- import * as Comlink from 'comlink';-->
<!-- addEventListener('message', message => {-->
<!-- const url = message.data;-->
<!-- const worker = new Worker(url);-->
<!-- console.warn("Registering worker", worker);-->

<!-- const wrappedWorker = Comlink.wrap(worker);-->

<!-- Comlink.expose(-->
<!-- wrappedWorker,-->
<!-- Comlink.windowEndpoint(self.parent)-->
<!-- )-->
<!-- }, {once: true});-->
<!--</script>-->
<!-- build only -->
<script src="/iframe-worker-connector.js">
<script src="/iframe-worker-connector.js" type="module">
</script>
</body>
</html>
5 changes: 0 additions & 5 deletions extension/src/entrypoints/main.module.css
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,5 @@
*/

.injectedEditorContent {
/*position: absolute;*/
width: 100%;
/*height: 100%;*/
/*left: 0;*/
/*top: 0;*/
/*margin-bottom: var(--base-size-12);*/
}
Empty file.
21 changes: 11 additions & 10 deletions extension/src/utils/gitHubNativeTextareaHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ import {
tryGetReferences,
} from '@better-comments-for-github/core/github/data'
import { GitHubUploaderNativeHandler } from '@better-comments-for-github/core/core/custom/image/github-file-uploader'
import { log } from '@better-comments-for-github/core/editor/utils/logger'
import type { AttachmentHandlerElement } from '@better-comments-for-github/core/core/custom/image/github-file-uploader'
import type { SuggestionData } from '@better-comments-for-github/core/editor/utils/loadSuggestionData'

Expand Down Expand Up @@ -91,11 +92,11 @@ export class GitHubNativeTextareaHandler {
// If we are in a new comment form, we can directly inject
// the footer into the bottom action bar
if (newCommentForm) {
return () => {
const commentFooter = newCommentForm.querySelector(
'#partial-new-comment-form-actions',
)
if (commentFooter) {
const commentFooter = newCommentForm.querySelector(
'#partial-new-comment-form-actions',
)
if (commentFooter) {
return () => {
const actionsWrapper = commentFooter.firstElementChild
if (actionsWrapper) {
const switchRoot = document.createElement('div')
Expand Down Expand Up @@ -205,9 +206,9 @@ export class GitHubNativeTextareaHandler {

return () => {
// Just a noop
console.warn(
'[github-better-comments] No mount point found for the switch button',
)
log('No mount point found for the switch button', {
id: this.instance.id,
})
}
}

Expand Down Expand Up @@ -269,8 +270,8 @@ export class GitHubNativeTextareaHandler {
effect(() => {
const show = this.instance.showOldEditor()
show
? tabContainer.style.setProperty('display', 'none')
: tabContainer.style.removeProperty('display')
? tabContainer.classList.add('sr-only')
: tabContainer.classList.remove('sr-only')
})
node.classList.add(...this.classList)
node.style.width = 'auto'
Expand Down
4 changes: 2 additions & 2 deletions extension/src/utils/gitHubReactTextareaHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ export class GitHubReactTextareaHandler {
)
if (wrapper) {
show
? wrapper.style.setProperty('display', 'none')
: wrapper.style.removeProperty('display')
? wrapper.classList.add('sr-only')
: wrapper.classList.remove('sr-only')
}
})

Expand Down
15 changes: 14 additions & 1 deletion extension/src/utils/githubPageDetector.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@
* limitations under the License.
*/

import { createComponent } from 'solid-js'
import { createComponent, createUniqueId } from 'solid-js'
import { log } from '@better-comments-for-github/core/editor/utils/logger'
import { SwitchButton } from '../../../src/render'
import type { Accessor, ComponentProps, Setter } from 'solid-js'
import type { GitHubUrlParsedResult } from './githubUrlParser'
Expand All @@ -36,6 +37,7 @@ export interface GitHubPageInstanceOptions {
}

export interface GitHubEditorInstance {
id: string
rootElement: HTMLElement
suggestionData: Accessor<SuggestionData>
setInjector: (injector: GitHubEditorInjector) => void
Expand Down Expand Up @@ -159,6 +161,7 @@ export function createGitHubEditorInstance(
}

return {
id: createUniqueId(),
unmount,
rootElement: el,
showOldEditor,
Expand Down Expand Up @@ -240,11 +243,21 @@ export function createGitHubPageInstance(
setHovercardSubjectTag(content ?? null)
}

document.addEventListener('turbo:visit', console.log)

// Will fire after the first page load, and immediately after turbo:visit
document.addEventListener('turbo:load', (event) => {
loadUsername()
loadParsedUrl()
loadHovercardSubjectTag()

log('Load page', {
event,
username: currentUsername(),
url: parsedUrl,
hovercardSubjectTag: hovercardSubjectTag(),
})

options.onReady?.call(result, event)
})

Expand Down
Binary file not shown.
5 changes: 2 additions & 3 deletions extension/stories/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,13 +50,12 @@ export function App(props: AppProps) {
currentUsername: () => 'riccardoperra',
owner: () => 'riccardoperra',
repository: () => 'test-repository',
hovercardSubjectTag: () => '1',
uploadHandler: mockUploader,
get initialValue() {
return textareaRef().value
},
get textarea() {
return textareaRef()
},
textarea: textareaRef,
get type() {
return 'native' as const
},
Expand Down
58 changes: 34 additions & 24 deletions src/editor/editor.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -44,10 +44,11 @@ import { forceGithubTextAreaSync } from './utils/forceGithubTextAreaSync'
import { DebugNode } from './DebugNode'
import { unistNodeFromMarkdown } from './utils/unistNodeFromMarkdown'
import { patchJsNativeTextareaValue } from './utils/jsNativeTextareaValuePatch'
import type { Root } from 'mdast'
import type { GitHubUploaderHandler } from '../core/custom/image/github-file-uploader'
import type { SuggestionData } from './utils/loadSuggestionData'
import { log } from './utils/logger'
import type { Schema } from 'prosemirror-model'
import type { SuggestionData } from './utils/loadSuggestionData'
import type { GitHubUploaderHandler } from '../core/custom/image/github-file-uploader'
import type { Root } from 'mdast'

export interface EditorProps {
suggestions: SuggestionData
Expand All @@ -56,8 +57,9 @@ export interface EditorProps {

export type EditorType = 'native' | 'react'
export type EditorRootContextProps = {
id: string
data: Accessor<SuggestionData>
textarea: HTMLTextAreaElement
textarea: Accessor<HTMLTextAreaElement>
initialValue: string
uploadHandler: GitHubUploaderHandler
type: EditorType
Expand Down Expand Up @@ -109,45 +111,61 @@ export function Editor(props: EditorProps) {

createEffect(() => {
const abortController = new AbortController()
const textarea = context.textarea()

const observer = new ResizeObserver(([{ target }], observer) => {
if (!target.isConnected) {
observer.disconnect()
}
const observer = new MutationObserver((entries) => {
console.log('mutation observer of entries', entries)
})

observer.observe(context.textarea)
observer.observe(textarea, {
attributes: true,
subtree: true,
childList: true,
characterData: true,
})

// TODO: should we always enable auto-focus?
editor.focus()

if (props.type === 'native') {
const unpatchSetValueEvent = patchJsNativeTextareaValue(context.textarea)
context.textarea.addEventListener(
const unpatchSetValueEvent = patchJsNativeTextareaValue(textarea)
textarea.addEventListener(
'gh-better-comments-textarea-set-value',
(e) => {
const pmNode = textAreaValueToPmNode(e.detail, context, editor.schema)
editor.setContent(pmNode)
},
{ signal: abortController.signal },
)

// This is needed for the native textarea in discussion. I don't know why
// the change event is not always triggered consistently.
const associatedForm = textarea.closest('form')
if (associatedForm) {
associatedForm.addEventListener('reset', (event) => {
log('Reset form event', { event }, { id: context.id })
editor.setContent('')
})
}

onCleanup(() => {
unpatchSetValueEvent()
})
}

onCleanup(() => {
log('Destroy editor', { id: context.id })
abortController.abort('I hope a new reference of textarea')
editor.setContent('')
observer.disconnect()
})

context.textarea.addEventListener(
textarea.addEventListener(
'input',
(event) => {
if (!(event as { fromEditor?: boolean }).fromEditor) {
const pmNode = textAreaValueToPmNode(
context.textarea.value,
textarea.value,
context,
editor.schema,
)
Expand All @@ -157,22 +175,14 @@ export function Editor(props: EditorProps) {
{ signal: abortController.signal },
)

context.textarea.addEventListener(
'manual-reset',
() => {
editor.setContent('')
},
{ signal: abortController.signal },
)

// Old text area change event (e.g. PR)
context.textarea.addEventListener(
textarea.addEventListener(
'change',
(event) => {
if ((event as any)['fromEditor']) return
if (event.isTrusted) return false
const pmNode = textAreaValueToPmNode(
context.textarea.value,
textarea.value,
context,
editor.schema,
)
Expand Down Expand Up @@ -217,7 +227,7 @@ export function Editor(props: EditorProps) {
setTimeout(() => {
const markdown = toMarkdown()
editorStore.set('markdown', markdown)
forceGithubTextAreaSync(context.textarea, markdown, {
forceGithubTextAreaSync(context.textarea(), markdown, {
behavior: props.type,
})
}, 150)
Expand Down
34 changes: 34 additions & 0 deletions src/editor/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/*
* Copyright 2025 Riccardo Perra
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

export const logEnabled = import.meta.env.DEV

export const log = (...args: Array<any>) => {
if (logEnabled) {
const lastArg = args[args.length - 1]
let id: string | undefined = ''
if (typeof lastArg === 'object' && 'id' in lastArg) {
id = lastArg.id
args.length = args.length - 1
}

console.debug(
`%cgithub-better-comments${id ? `:${id}` : ''}`,
'background-color: #0089d9; color: white; border-radius: 4px; padding: 2px 4px;',
...args,
)
}
}
Loading