@@ -106,22 +106,38 @@ function setupBlock(pre, run) {
106106 }
107107
108108 let output
109+ let outputTextNode
109110 const ensureOutput = ( ) => {
110111 if ( ! output ) {
111112 output = document . createElement ( 'pre' )
112113 output . className = 'highlight__run-output'
113114 output . setAttribute ( 'aria-live' , 'polite' )
115+ // COPY ボタン(先頭)を残したまま本文を書き換えられるように、
116+ // 出力テキストは専用のテキストノードに持つ
117+ outputTextNode = document . createTextNode ( '' )
118+ output . appendChild ( outputTextNode )
114119 pre . after ( output )
120+ // 実行結果もコピーできるようにする(script.js の公開フック)。
121+ // 出力は実行のたびに変わるので、クリック時のテキストを渡す
122+ if ( window . ruremaAddCopyButton ) {
123+ window . ruremaAddCopyButton ( output , ( ) => outputTextNode . data )
124+ }
115125 }
116126 return output
117127 }
128+ const setOutputText = ( text ) => {
129+ outputTextNode . data = text
130+ }
118131
119132 // After the first run the sample becomes editable (like a scratchpad);
120- // Ctrl+Enter (or Cmd+Enter) re-runs the edited code. Editing gradually
121- // loses the syntax-highlight spans; the COPY button keeps copying the
122- // original text.
133+ // Ctrl+Enter (or Cmd+Enter) re-runs the edited code. The COPY button
134+ // keeps copying the original text.
123135 const enableEditing = ( ) => {
124136 if ( code . isContentEditable ) return
137+ // 編集でハイライトの span に文字が食い込むと、貼り付けた文字が
138+ // その場の色を引き継いで中途半端に崩れるため、編集可能にする
139+ // 時点でプレーンテキスト化して色を消す
140+ code . textContent = code . textContent
125141 code . contentEditable = 'true'
126142 code . spellcheck = false
127143 pre . dataset . editing = 'true'
@@ -140,22 +156,22 @@ function setupBlock(pre, run) {
140156 button . textContent = 'LOADING...'
141157 const out = ensureOutput ( )
142158 out . classList . remove ( 'highlight__run-output--error' )
143- out . textContent = ''
159+ setOutputText ( '' )
144160 let label = 'RUN'
145161 try {
146162 const result = await run ( code . textContent , ( ) => {
147163 button . textContent = 'RUNNING...'
148164 } )
149165 if ( result ) {
150- out . textContent = result . error
166+ setOutputText ( result . error
151167 ? ( result . output === '' ? result . error : result . output + '\n' + result . error )
152- : result . output
168+ : result . output )
153169 if ( result . error ) out . classList . add ( 'highlight__run-output--error' )
154170 enableEditing ( )
155171 }
156172 } catch ( e ) {
157173 out . classList . add ( 'highlight__run-output--error' )
158- out . textContent = formatRunError ( e )
174+ setOutputText ( formatRunError ( e ) )
159175 label = 'RETRY'
160176 } finally {
161177 button . textContent = label
0 commit comments