Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ページ解析系スクリプトをcontentスクリプトから分離してモジュール化したい #27

Merged
merged 3 commits into from
Jan 26, 2020
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
1,821 changes: 932 additions & 889 deletions novels-reader-crx/background.js

Large diffs are not rendered by default.

23,356 changes: 11,961 additions & 11,395 deletions novels-reader-crx/content.js

Large diffs are not rendered by default.

23,040 changes: 11,714 additions & 11,326 deletions novels-reader-crx/options.js

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@
"webpack": ">=3.0.0"
},
"dependencies": {
"jquery": "^3.4.0",
"jquery": "^3.4.1",
"roudokuka": "^0.1.2"
}
}
139 changes: 23 additions & 116 deletions src/js/content.js
Original file line number Diff line number Diff line change
@@ -1,66 +1,19 @@
import _find from 'lodash/find'
import _orderBy from 'lodash/orderBy'
import Roudokuka from 'roudokuka'
import pageAnalyzer from 'pageAnalyzer'
import initializeHead from 'initializer/head'

// global variables
let options = undefined
let dictionaries = undefined
let rubies = []
let lineIndex = 0

const getDictionaryText = (rubies) => {
let dictionaryText = ''
rubies.forEach((ruby) => {
dictionaryText += `${ruby.rb}::${ruby.rt}\n`
})
return dictionaryText.trim()
}

const checkIncludeRuby = (text) => {
return /<ruby><rb>/gi.test(text)
}

const checkIgnoreRubiesTest = (ruby) => {
return dictionaries.ignoreRubies && dictionaries.ignoreRubies.raw && RegExp(dictionaries.ignoreRubies.raw, 'gi').test(ruby.rt)
}

const setRubyData = ($lineElement) => {
if(checkIncludeRuby($lineElement.html())) {
$lineElement.addClass('include-ruby')

const divider = '__|novels|reader|ruby|tag|divider|__'
const splitRubyTagTexts = $lineElement.html().replace(/<ruby><rb>/gi, `${divider}<ruby><rb>`).replace(/<\/rp><\/ruby>/gi, `</rp></ruby>${divider}`).split(divider)
const readText = splitRubyTagTexts.map((splitRubyTagText) => {
if(checkIncludeRuby(splitRubyTagText)) {
const ruby = {rb: $(splitRubyTagText).find('rb').text(), rt: $(splitRubyTagText).find('rt').text()}
if(!_find(rubies, ruby) && !checkIgnoreRubiesTest(ruby)) {
rubies.push(ruby)
}
return checkIgnoreRubiesTest(ruby)
? ruby.rb
: ruby.rt
} else {
return splitRubyTagText
}
}).join('')
$lineElement.data({readText: readText})
}
}

const setPlayButtonElementsAndSetRubyData = (lineElements) => {
lineElements.each((index, lineElement) => {
let $lineElement = $(lineElement)
setRubyData($lineElement)
$lineElement.prepend($(`<div class='controll-button play' data-index='${lineIndex++}'><i class='fa fa-play-circle' aria-hidden='true'></div>`))
})
}
let analyzer = new pageAnalyzer(window.location.hostname)

const getLinesInfo = ($lineElements) => {
let linesInfo = []
$lineElements.each((index, lineElement) => {
let $lineElement = $(lineElement)
linesInfo.push({
text: checkIncludeRuby($lineElement.html()) ? $lineElement.data().readText : $lineElement.text(),
text: analyzer.checkIncludeRuby($lineElement.html()) ? $lineElement.data().readText : $lineElement.text(),
element: $lineElement
})
})
Expand All @@ -72,90 +25,50 @@ const lineHighlight = (lineElement) => {
}

const lineUnHighlight = () => {
$('.novel_subtitle, #novel_p p, #novel_honbun p, #novel_a p').removeClass('highlight')
analyzer.module.highlightElements.removeClass('highlight')
}

if($('#novel_honbun').length) {
const novelId = $('.contents1 .margin_r20').attr('href').replace(/\//g, '')
if(analyzer.module.readElements.body.length) {
chrome.runtime.sendMessage({method: 'getOptions', key: 'options'}, (responseOptions) => {
chrome.runtime.sendMessage({method: 'saveDictionary', dictionary: {
id: novelId,
name: $('.contents1 .margin_r20').text()
id: analyzer.module.novelId,
name: analyzer.module.novelName
}}, (responseDictionaries) => {

// 2 nested -------- start
// start main --------

options = responseOptions
dictionaries = responseDictionaries

$('head').append(`<link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' rel='stylesheet' integrity='sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN' crossorigin='anonymous'>`)
$('head').append(`<style id='novels-reader-style'>
.highlight {
color: ${options.textColor == undefined ? '#fff' : options.textColor};
background-color: ${options.backgroundColor == undefined ? '#498fd9' : options.backgroundColor};
}

.controll-button {
color: ${$('#novel_color').css('color')};
position: absolute;
cursor: pointer;
}
.controll-button:hover {
color: #18b7cd;
}

.controll-button .fa {
line-height: inherit;
font-size: 120%;
}

p.include-ruby .controll-button .fa {
margin-top: ${$('ruby rt').height()}px;
line-height: ${$('ruby rb').height()}px;
}
initializeHead(options)

.controll-button.play {
margin-left: -25px;
}
.controll-button.stop {
position: fixed;
top: ${$('#novel_header').height() + 15}px;
left: 15px;
font-size: 30px;
}
</style>`)

let lineElements = {}
let linesInfo = []

const targetElements = {
title: $('.novel_subtitle'),
foreword: $('#novel_p p'),
body: $('#novel_honbun p'),
afterword: $('#novel_a p')
}
for(let key in targetElements) {
if(options[key] == 'on' && targetElements[key].length) {
let filteredElements = targetElements[key].filter((index, element) => {
for(let key in analyzer.module.readElements) {
if(options[key] == 'on' && analyzer.module.readElements[key].length) {
let filteredElements = analyzer.module.readElements[key].filter((index, element) => {
return /\S/gi.test($(element).text())
})
setPlayButtonElementsAndSetRubyData(filteredElements)
analyzer.setPlayButtonElementsAndSetRubyData(filteredElements, dictionaries)
linesInfo = linesInfo.concat(getLinesInfo(filteredElements))
}
}
// 2 nested -------- end

chrome.runtime.sendMessage({method: 'saveDictionary', dictionary: {
id: novelId,
raw: options.autoSaveDictionary == 'on' ? getDictionaryText(rubies) : ''
id: analyzer.module.novelId,
raw: options.autoSaveDictionary == 'on' ? analyzer.getDictionaryText() : ''
}}, (savedDictionary) => {

// 3 nested -------- start
dictionaries = savedDictionary

let userRubies = dictionaries.user ? _orderBy(dictionaries.user.rubies, [function(r) { return r.rb.length; }], ['desc']) : false
let novelRubies = dictionaries.novel.rubies.length ? _orderBy(dictionaries.novel.rubies, [function(r) { return r.rb.length; }], ['desc']) : false
if(userRubies) {
linesInfo.forEach((lineInfo) => {
userRubies.forEach((ruby) => {
if(!checkIgnoreRubiesTest(ruby)) {
if(!analyzer.checkIgnoreRubiesTest(ruby, dictionaries)) {
lineInfo.text = lineInfo.text.trim().replace(RegExp(ruby.rb, 'gi'), ruby.rt)
}
})
Expand All @@ -164,7 +77,7 @@ if(userRubies) {
if(novelRubies) {
linesInfo.forEach((lineInfo) => {
novelRubies.forEach((ruby) => {
if(!checkIgnoreRubiesTest(ruby)) {
if(!analyzer.checkIgnoreRubiesTest(ruby, dictionaries)) {
lineInfo.text = lineInfo.text.trim().replace(RegExp(ruby.rb, 'gi'), ruby.rt)
}
})
Expand All @@ -189,7 +102,6 @@ if(options.rate != undefined) {
if(options.pitch != undefined) {
roudokukaOptions.pitch = Number(options.pitch)
}
console.log(options)
if(options.volume != undefined) {
roudokukaOptions.volume = Number(options.volume)
}
Expand All @@ -205,12 +117,7 @@ roudokukaOptions.onend = (e, lineInfo) => {
}
roudokukaOptions.onLibrettoEnd = () => {
if(options.autoMoveNext == 'on') {
$($('.novel_bn')[0]).children().each((index, element) => {
element = $(element)
if(/>>/.test(element.text())) {
window.location.href = element.prop('href')
}
})
analyzer.module.goToNext()
}
}
window.roudokuka = new Roudokuka(linesInfo, roudokukaOptions)
Expand All @@ -221,7 +128,7 @@ window.roudokuka.onReady().then(() => {
window.roudokuka.start()
}
})

// 3 nested -------- end
})
// end main --------

Expand Down
38 changes: 38 additions & 0 deletions src/js/initializer/head.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
export default function headInitializer(options) {
$('head').append(`<link href='https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css' rel='stylesheet' integrity='sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN' crossorigin='anonymous'>`)
$('head').append(`<style id='novels-reader-style'>
.highlight {
color: ${options.textColor == undefined ? '#fff' : options.textColor};
background-color: ${options.backgroundColor == undefined ? '#498fd9' : options.backgroundColor};
}

.controll-button {
color: ${$('#novel_color').css('color')};
position: absolute;
cursor: pointer;
}
.controll-button:hover {
color: #18b7cd;
}

.controll-button .fa {
line-height: inherit;
font-size: 120%;
}

p.include-ruby .controll-button .fa {
margin-top: ${$('ruby rt').height()}px;
line-height: ${$('ruby rb').height()}px;
}

.controll-button.play {
margin-left: -25px;
}
.controll-button.stop {
position: fixed;
top: ${$('#novel_header').height() + 15}px;
left: 15px;
font-size: 30px;
}
</style>`)
}
69 changes: 69 additions & 0 deletions src/js/pageAnalyzer/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
import _assign from 'lodash/assign'
import _find from 'lodash/find'
import narou from 'pageAnalyzer/narou'

export default class PageAnalyzer {
constructor(hostname) {
this.modules = [new narou]
this.module = this.getTargetModule(hostname)
this.lineIndex = 0
this.rubies = []
}

getDictionaryText() {
let dictionaryText = ''
this.rubies.forEach((ruby) => {
dictionaryText += `${ruby.rb}::${ruby.rt}\n`
})
return dictionaryText.trim()
}

getTargetModule(hostname) {
let targetModule = null
this.modules.forEach(module => {
if(hostname === module.targetHostname) {
targetModule = module
}
})
return targetModule
}

checkIncludeRuby(text) {
return /<ruby><rb>/gi.test(text)
}

checkIgnoreRubiesTest(ruby, dictionaries) {
return dictionaries.ignoreRubies && dictionaries.ignoreRubies.raw && RegExp(dictionaries.ignoreRubies.raw, 'gi').test(ruby.rt)
}

setRubyData($lineElement, dictionaries) {
if(this.checkIncludeRuby($lineElement.html())) {
$lineElement.addClass('include-ruby')

const divider = '__|novels|reader|ruby|tag|divider|__'
const splitRubyTagTexts = $lineElement.html().replace(/<ruby><rb>/gi, `${divider}<ruby><rb>`).replace(/<\/rp><\/ruby>/gi, `</rp></ruby>${divider}`).split(divider)
const readText = splitRubyTagTexts.map((splitRubyTagText) => {
if(this.checkIncludeRuby(splitRubyTagText)) {
const ruby = {rb: $(splitRubyTagText).find('rb').text(), rt: $(splitRubyTagText).find('rt').text()}
if(!_find(this.rubies, ruby) && !this.checkIgnoreRubiesTest(ruby, dictionaries)) {
this.rubies.push(ruby)
}
return this.checkIgnoreRubiesTest(ruby, dictionaries)
? ruby.rb
: ruby.rt
} else {
return splitRubyTagText
}
}, this).join('')
$lineElement.data({readText: readText})
}
}

setPlayButtonElementsAndSetRubyData(lineElements, dictionaries) {
lineElements.each((index, lineElement) => {
let $lineElement = $(lineElement)
this.setRubyData($lineElement, dictionaries)
$lineElement.prepend($(`<div class='controll-button play' data-index='${this.lineIndex++}'><i class='fa fa-play-circle' aria-hidden='true'></div>`))
})
}
}
25 changes: 25 additions & 0 deletions src/js/pageAnalyzer/narou.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
export default class Narou {
constructor() {
this.targetHostname = 'ncode.syosetu.com'
this.novelId = $('.contents1 .margin_r20').attr('href').replace(/\//g, '')
this.novelName = $('.contents1 .margin_r20').text()

const elementArray = ['.novel_subtitle', '#novel_p p', '#novel_honbun p', '#novel_a p']
this.readElements = {
title: $(elementArray[0]),
foreword: $(elementArray[1]),
body: $(elementArray[2]),
afterword: $(elementArray[3])
}
this.highlightElements = $(elementArray.join(', '))

this.goToNext = () => {
$($('.novel_bn')[0]).children().each((index, element) => {
element = $(element)
if(/>>/.test(element.text())) {
window.location.href = element.prop('href')
}
})
}
}
}
7 changes: 4 additions & 3 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2688,9 +2688,10 @@ isstream@~0.1.2:
version "0.1.2"
resolved "https://registry.yarnpkg.com/isstream/-/isstream-0.1.2.tgz#47e63f7af55afa6f92e1500e690eb8b8529c099a"

jquery@^3.4.0:
version "3.4.0"
resolved "https://registry.yarnpkg.com/jquery/-/jquery-3.4.0.tgz#8de513fa0fa4b2c7d2e48a530e26f0596936efdf"
jquery@^3.4.1:
version "3.4.1"
resolved "https://registry.yarnpkg.com/jquery/-/jquery-3.4.1.tgz#714f1f8d9dde4bdfa55764ba37ef214630d80ef2"
integrity sha512-36+AdBzCL+y6qjw5Tx7HgzeGCzC81MDDgaUP8ld2zhx58HdqXGoBd+tHdrBMiyjGQs0Hxs/MLZTu/eHNJJuWPw==

js-stringify@^1.0.1:
version "1.0.2"
Expand Down