dayjs.extend(window.dayjs_plugin_relativeTime)
let currentMemoLock = ''
function msg(key) {
if (typeof window.t === 'function') return window.t(key)
return chrome.i18n.getMessage(key) || ''
}
function applyDayjsLocaleByUiLanguage(uiLang) {
const lang = String(uiLang || 'auto')
if (lang === 'zh_CN') {
dayjs.locale('zh-cn')
return
}
if (lang === 'ja') {
dayjs.locale('ja')
return
}
if (lang === 'ko') {
dayjs.locale('ko')
return
}
if (lang === 'en') {
dayjs.locale('en')
return
}
// auto: best-effort infer from browser UI language
const ui = String(chrome.i18n.getUILanguage ? chrome.i18n.getUILanguage() : '').toLowerCase()
if (ui.startsWith('zh')) {
dayjs.locale('zh-cn')
return
}
if (ui.startsWith('ja')) {
dayjs.locale('ja')
return
}
if (ui.startsWith('ko')) {
dayjs.locale('ko')
return
}
dayjs.locale('en')
}
function updateLockNowText(lockType) {
if (lockType === 'PUBLIC') {
$('#lock-now').text(msg('lockPublic'))
} else if (lockType === 'PRIVATE') {
$('#lock-now').text(msg('lockPrivate'))
} else if (lockType === 'PROTECTED') {
$('#lock-now').text(msg('lockProtected'))
}
}
applyDayjsLocaleByUiLanguage(typeof window.getUiLanguage === 'function' ? window.getUiLanguage() : 'auto')
window.addEventListener('i18n:changed', (ev) => {
applyDayjsLocaleByUiLanguage(ev && ev.detail ? ev.detail.lang : 'auto')
updateLockNowText(currentMemoLock)
renderUploadList(relistNow)
})
let relistNow = []
function get_info(callback) {
chrome.storage.sync.get(
{
apiUrl: '',
apiTokens: '',
hidetag: '',
showtag: '',
memo_lock: '',
open_action: '',
open_content: '',
userid: '',
memoUiPath: 'memos',
resourceIdList: []
},
function (items) {
var flag = false
var returnObject = {}
if (items.apiUrl === '' || items.apiTokens === '') {
flag = false
} else {
flag = true
}
returnObject.status = flag
returnObject.apiUrl = items.apiUrl
returnObject.apiTokens = items.apiTokens
returnObject.hidetag = items.hidetag
returnObject.showtag = items.showtag
returnObject.memo_lock = items.memo_lock
returnObject.open_content = items.open_content
returnObject.open_action = items.open_action
returnObject.userid = items.userid
returnObject.memoUiPath = items.memoUiPath
returnObject.resourceIdList = items.resourceIdList
if (callback) callback(returnObject)
}
)
}
get_info(function (info) {
if (info.status) {
//已经有绑定信息了,折叠
$('#blog_info').hide()
}
var memoNow = info.memo_lock
if (memoNow == '') {
chrome.storage.sync.set(
{ memo_lock: 'PUBLIC' }
)
memoNow = 'PUBLIC'
}
currentMemoLock = memoNow
updateLockNowText(memoNow)
$('#apiUrl').val(info.apiUrl)
$('#apiTokens').val(info.apiTokens)
$('#hideInput').val(info.hidetag)
$('#showInput').val(info.showtag)
if (info.open_action === 'upload_image') {
//打开的时候就是上传图片
uploadImage(info.open_content)
} else {
$("textarea[name=text]").val(info.open_content)
}
relistNow = Array.isArray(info.resourceIdList) ? info.resourceIdList : []
renderUploadList(relistNow)
//从localstorage 里面读取数据
setTimeout(get_info, 1)
})
chrome.storage.onChanged.addListener(function (changes, areaName) {
if (areaName !== 'sync') return
if (!changes.resourceIdList) return
relistNow = Array.isArray(changes.resourceIdList.newValue)
? changes.resourceIdList.newValue
: []
renderUploadList(relistNow)
})
$("textarea[name=text]").focus()
//监听输入结束,保存未发送内容到本地
$("textarea[name=text]").blur(function () {
chrome.storage.sync.set(
{ open_action: 'save_text', open_content: $("textarea[name=text]").val() }
)
})
$("textarea[name=text]").on('keydown', function (ev) {
if (ev.code === 'Enter' && (ev.ctrlKey || ev.metaKey)) {
$('#content_submit_text').click()
}
})
//监听拖拽事件,实现拖拽到窗口上传图片
initDrag()
//监听复制粘贴事件,实现粘贴上传图片
document.addEventListener('paste', function (e) {
let photo = null
if (e.clipboardData.files[0]) {
photo = e.clipboardData.files[0]
} else if (e.clipboardData.items[0] && e.clipboardData.items[0].getAsFile()) {
photo = e.clipboardData.items[0].getAsFile()
}
if (photo != null) {
uploadImage(photo)
}
})
function initDrag() {
var file = null
var obj = $("textarea[name=text]")[0]
obj.ondragenter = function (ev) {
if (ev.target.className === 'common-editor-inputer') {
$.message({
message: msg('picDrag'),
autoClose: false
})
$('body').css('opacity', 0.3)
}
ev.dataTransfer.dropEffect = 'copy'
}
obj.ondragover = function (ev) {
ev.preventDefault()
ev.dataTransfer.dropEffect = 'copy'
}
obj.ondrop = function (ev) {
$('body').css('opacity', 1)
ev.preventDefault()
var files = ev.dataTransfer.files || ev.target.files
for (var i = 0; i < files.length; i++) {
file = files[i]
}
uploadImage(file)
}
obj.ondragleave = function (ev) {
ev.preventDefault()
if (ev.target.className === 'common-editor-inputer') {
$.message({
message: msg('picCancelDrag')
})
$('body').css('opacity', 1)
}
}
}
function escapeHtml(input) {
return String(input)
.replace(/&/g, '&')
.replace(//g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''')
}
function renderUploadList(list) {
const $wrapper = $('.upload-list-wrapper')
const $list = $('#uploadlist')
if ($list.length === 0) return
const items = Array.isArray(list) ? list : []
if (items.length === 0) {
if ($wrapper.length) $wrapper.hide()
$list.html('')
return
}
if ($wrapper.length) $wrapper.show()
const tipReorder = escapeHtml(msg('tipReorder'))
const tipDelete = escapeHtml(msg('tipDeleteAttachment'))
let html = ''
for (let i = 0; i < items.length; i++) {
const att = items[i] || {}
const name = att.name || ''
const filename = att.filename || name
html +=
'
' +
'
' +
'≡' +
'' +
escapeHtml(filename) +
'' +
'
' +
'
' +
'
'
}
$list.html(html)
}
function saveUploadList(nextList, callback) {
relistNow = Array.isArray(nextList) ? nextList : []
chrome.storage.sync.set({ resourceIdList: relistNow }, callback)
}
let uploadDragIndex = null
$(document).on('dragstart', '.upload-item', function (e) {
uploadDragIndex = Number($(this).data('index'))
const dt = e.originalEvent && e.originalEvent.dataTransfer
if (dt) {
dt.effectAllowed = 'move'
dt.setData('text/plain', String(uploadDragIndex))
}
})
$(document).on('dragover', '.upload-item', function (e) {
e.preventDefault()
$(this).addClass('drag-over')
const dt = e.originalEvent && e.originalEvent.dataTransfer
if (dt) dt.dropEffect = 'move'
})
$(document).on('dragleave', '.upload-item', function () {
$(this).removeClass('drag-over')
})
$(document).on('drop', '.upload-item', function (e) {
e.preventDefault()
$('.upload-item.drag-over').removeClass('drag-over')
const fromIndex =
uploadDragIndex != null
? uploadDragIndex
: Number(
(e.originalEvent && e.originalEvent.dataTransfer
? e.originalEvent.dataTransfer.getData('text/plain')
: '') || -1
)
const toIndex = Number($(this).data('index'))
uploadDragIndex = null
if (!Number.isFinite(fromIndex) || !Number.isFinite(toIndex)) return
if (fromIndex < 0 || toIndex < 0) return
if (fromIndex === toIndex) return
const next = (Array.isArray(relistNow) ? relistNow : []).slice()
if (fromIndex >= next.length || toIndex >= next.length) return
const moved = next.splice(fromIndex, 1)[0]
next.splice(toIndex, 0, moved)
saveUploadList(next, function () {
renderUploadList(relistNow)
})
})
$(document).on('click', '.upload-del', function () {
const name = $(this).data('name')
if (!name) return
get_info(function (info) {
if (!info.status) {
$.message({ message: msg('placeApiUrl') })
return
}
$.ajax({
url: info.apiUrl + 'api/v1/' + name,
type: 'DELETE',
headers: { Authorization: 'Bearer ' + info.apiTokens },
success: function () {
const next = (Array.isArray(relistNow) ? relistNow : []).filter(function (x) {
return x && x.name !== name
})
saveUploadList(next, function () {
$.message({ message: msg('attachmentDeleteSuccess') })
renderUploadList(relistNow)
})
},
error: function () {
$.message({ message: msg('attachmentDeleteFailed') })
}
})
})
})
function uploadImage(file) {
$.message({
message: msg('picUploading'),
autoClose: false
});
const reader = new FileReader();
reader.onload = function(e) {
const base64String = e.target.result.split(',')[1];
uploadImageNow(base64String, file);
};
reader.onerror = function(error) {
console.error('Error reading file:', error);
};
reader.readAsDataURL(file);
};
function uploadImageNow(base64String, file) {
get_info(function(info) {
if (info.status) {
let old_name = file.name.split('.');
let file_ext = file.name.split('.').pop();
let now = dayjs().format('YYYYMMDDHHmmss');
let new_name = old_name[0] + '_' + now + '.' + file_ext;
var hideTag = info.hidetag
var showTag = info.showtag
var nowTag = $("textarea[name=text]").val().match(/(#[^\s#]+)/)
var sendvisi = info.memo_lock || ''
if(nowTag){
if(nowTag[1] == showTag){
sendvisi = 'PUBLIC'
}else if(nowTag[1] == hideTag){
sendvisi = 'PRIVATE'
}
}
const data = {
content: base64String,
visibility: sendvisi,
filename: new_name,
type: file.type
};
window.MemosApi.uploadAttachmentOrResource(
info,
data,
function (resp, kind) {
if (resp && resp.name) {
relistNow.push({
name: resp.name,
filename: resp.filename || new_name,
createTime: resp.createTime,
type: resp.type
})
chrome.storage.sync.set(
{
open_action: '',
open_content: '',
resourceIdList: relistNow
},
function () {
$.message({ message: msg('picSuccess') })
}
)
} else {
chrome.storage.sync.set(
{
open_action: '',
open_content: '',
resourceIdList: []
},
function () {
$.message({ message: msg('picFailed') })
}
)
}
},
function () {
$.message({ message: msg('picFailed') })
}
)
}else {
$.message({
message: msg('placeApiUrl')
})
}
});
}
$('#saveKey').click(function () {
var apiUrl = $('#apiUrl').val()
if (apiUrl.length > 0 && !apiUrl.endsWith('/')) {
apiUrl += '/';
}
var apiTokens = $('#apiTokens').val()
window.MemosApi.authWithFallback(apiUrl, apiTokens, function (auth) {
if (!auth || auth.userId == null) {
$.message({ message: msg('invalidToken') })
return
}
chrome.storage.sync.set(
{
apiUrl: apiUrl,
apiTokens: apiTokens,
userid: auth.userId,
memoUiPath: auth.uiPath || 'memos'
},
function () {
$.message({ message: msg('saveSuccess') })
$('#blog_info').hide()
}
)
})
});
$('#opensite').click(function () {
get_info(function (info) {
chrome.tabs.create({url:info.apiUrl})
})
})
// 0.23.1版本 GET api/v1/{parent}/tags 接口已移除,参考 https://github.com/usememos/memos/issues/4161
$('#tags').click(function () {
get_info(function (info) {
if (info.apiUrl) {
var parent = `users/${info.userid}`;
// 从最近的1000条memo中获取tags,因此不保证获取能全部的
var tagDom = "";
window.MemosApi.fetchMemosWithFallback(
info,
'?pageSize=1000',
function (data) {
const memos = window.MemosApi.extractMemosListFromResponse(data)
const allTags = memos.flatMap(function (memo) {
if (!memo) return []
if (Array.isArray(memo.tags)) return memo.tags
if (Array.isArray(memo.tagList)) return memo.tagList
return []
})
const uniTags = [...new Set(allTags.filter(Boolean))]
$.each(uniTags, function (_, tag) {
tagDom += '#' + tag + '';
});
tagDom += ''
$("#taglist").html(tagDom).slideToggle(500)
},
function () {
$.message({ message: msg('placeApiUrl') })
}
)
} else {
$.message({
message: msg('placeApiUrl')
})
}
})
})
$(document).on("click","#hideTag",function () {
$('#taghide').slideToggle(500)
})
$('#saveTag').click(function () {
// 保存数据
chrome.storage.sync.set(
{
hidetag: $('#hideInput').val(),
showtag: $('#showInput').val()
},
function () {
$.message({
message: msg('saveSuccess')
})
$('#taghide').hide()
}
)
})
$('#lock').click(function () {
$("#lock-wrapper").toggleClass( "!hidden", 1000 );
})
$(document).on("click",".item-lock",function () {
$("#lock-wrapper").toggleClass( "!hidden", 1000 );
$("#lock-now").text($(this).text())
_this = $(this)[0].dataset.type;
currentMemoLock = _this
chrome.storage.sync.set(
{memo_lock: _this}
)
})
$('#search').click(function () {
get_info(function (info) {
const pattern = $("textarea[name=text]").val()
var parent = `users/${info.userid}`;
var filter = "?filter=" + encodeURIComponent(`visibility in ["PUBLIC","PROTECTED"] && content.contains("${pattern}")`);
if (info.status) {
$("#randomlist").html('').hide()
var searchDom = ""
if(pattern){
window.MemosApi.fetchMemosWithFallback(
info,
filter,
function (data) {
let searchData = window.MemosApi.extractMemosListFromResponse(data)
if(searchData.length == 0){
$.message({
message: msg('searchNone')
})
}else{
for(var i=0;i < searchData.length;i++){
var memosID = searchData[i].name.split('/').pop();
var memoTime = searchData[i].createTime || searchData[i].createdTs || searchData[i].createdAt
searchDom += ''+(memoTime ? dayjs(memoTime).fromNow() : '')+'
'+(searchData[i].content || '').replace(/!\[.*?\]\((.*?)\)/g,'

').replace(/\[(.*?)\]\((.*?)\)/g,'
$1 ')+'
'
var resources = (searchData[i].attachments && searchData[i].attachments.length > 0) ? searchData[i].attachments : (searchData[i].resources || []);
if(resources && resources.length > 0){
for(var j=0;j < resources.length;j++){
var restype = (resources[j].type || '').slice(0,5);
var resexlink = resources[j].externalLink
var resLink = '',fileId=''
if(resexlink){
resLink = resexlink
}else{
fileId = resources[j].publicId || resources[j].filename
resLink = info.apiUrl+'file/'+resources[j].name+'/'+fileId
}
if(restype == 'image'){
searchDom += '

'
}
if(restype !== 'image'){
searchDom += '
'+resources[j].filename+''
}
}
}
searchDom += '
'
}
window.ViewImage && ViewImage.init('.random-image')
$("#randomlist").html(searchDom).slideDown(500);
}
},
function () {
$.message({ message: msg('searchNone') })
}
)
}else{
$.message({
message: msg('searchNow')
})
}
} else {
$.message({
message: msg('placeApiUrl')
})
}
})
})
$('#random').click(function () {
get_info(function (info) {
var parent = `users/${info.userid}`;
var filter = "?filter=" + encodeURIComponent(`visibility in ["PUBLIC","PROTECTED"]`);
if (info.status) {
$("#randomlist").html('').hide()
window.MemosApi.fetchMemosWithFallback(
info,
filter,
function (data) {
const memos = window.MemosApi.extractMemosListFromResponse(data)
let randomNum = Math.floor(Math.random() * (memos.length));
var randomData = memos[randomNum]
randDom(randomData)
},
function () {
$.message({ message: msg('placeApiUrl') })
}
)
} else {
$.message({
message: msg('placeApiUrl')
})
}
})
})
function randDom(randomData){
get_info(function (info) {
var memosID = randomData.name.split('/').pop();
var randomDom = ''+dayjs(randomData.createTime).fromNow()+'
'+randomData.content.replace(/!\[.*?\]\((.*?)\)/g,'

').replace(/\[(.*?)\]\((.*?)\)/g,'
$1 ')+'
'
var resources = (randomData.attachments && randomData.attachments.length > 0) ? randomData.attachments : (randomData.resources || []);
if(resources && resources.length > 0){
for(var j=0;j < resources.length;j++){
var restype = resources[j].type.slice(0,5);
var resexlink = resources[j].externalLink
var resLink = '',fileId=''
if(resexlink){
resLink = resexlink
}else{
fileId = resources[j].publicId || resources[j].filename
resLink = info.apiUrl+'file/'+resources[j].name+'/'+fileId
}
if(restype == 'image'){
randomDom += '

'
}
if(restype !== 'image'){
randomDom += '
'+resources[j].filename+''
}
}
}
randomDom += '
'
window.ViewImage && ViewImage.init('.random-image')
$("#randomlist").html(randomDom).slideDown(500);
})
}
$(document).on("click","#random-link",function () {
var memoUid = $("#random-link").data('uid');
get_info(function (info) {
const path = (info.memoUiPath || 'memos').replace(/^\/+|\/+$/g, '')
chrome.tabs.create({url:info.apiUrl + path + "/" + memoUid})
})
})
$(document).on("click","#random-delete",function () {
get_info(function (info) {
// var memoUid = $("#random-delete").data('uid');
var memosName = $("#random-delete").data('name');
var deleteUrl = info.apiUrl+'api/v1/'+memosName
$.ajax({
url:deleteUrl,
type:"PATCH",
data:JSON.stringify({
// 'uid': memoUid,
'state': "ARCHIVED"
}),
contentType:"application/json",
dataType:"json",
headers : {'Authorization':'Bearer ' + info.apiTokens},
success: function(result){
$("#randomlist").html('').hide()
$.message({
message: msg('archiveSuccess')
})
},error:function(err){//清空open_action(打开时候进行的操作),同时清空open_content
$.message({
message: msg('archiveFailed')
})
}
})
})
})
$(document).on("click",".item-container",function () {
var tagHtml = $(this).text()+" "
add(tagHtml);
})
$('#newtodo').click(function () {
var tagHtml = "\n- [ ] "
add(tagHtml);
})
$('#getlink').click(function () {
chrome.tabs.query({ active: true, currentWindow: true }, ([tab]) => {
var linkHtml = " ["+tab.title+"]("+tab.url+") "
if(tab.url){
add(linkHtml);
}else{
$.message({
message: msg('getTabFailed')
})
}
})
})
$('#upres').click(async function () {
$('#inFile').click()
})
$('#inFile').on('change', function(data){
var fileVal = $('#inFile').val();
var file = null
if(fileVal == '') {
return;
}
file= this.files[0];
uploadImage(file)
});
function add(str) {
var tc = document.getElementById("content");
var tclen = tc.value.length;
tc.focus();
if(typeof document.selection != "undefined"){
document.selection.createRange().text = str;
}else{
tc.value =
tc.value.substr(0, tc.selectionStart) +
str +
tc.value.substring(tc.selectionStart, tclen);
}
}
$('#blog_info_edit').click(function () {
$('#blog_info').slideToggle()
})
$('#content_submit_text').click(function () {
var contentVal = $("textarea[name=text]").val()
if(contentVal){
sendText()
}else{
$.message({
message: msg('placeContent')
})
}
})
function getOne(memosId){
get_info(function (info) {
if (info.apiUrl) {
$("#randomlist").html('').hide()
var getUrl = info.apiUrl+'api/v1/'+memosId
$.ajax({
url:getUrl,
type:"GET",
contentType:"application/json",
dataType:"json",
headers : {'Authorization':'Bearer ' + info.apiTokens},
success: function(data){
randDom(data)
}
})
} else {
$.message({
message: msg('placeApiUrl')
})
}
})
}
function sendText() {
get_info(function (info) {
if (info.status) {
$.message({
message: msg('memoUploading')
})
//$("#content_submit_text").attr('disabled','disabled');
let content = $("textarea[name=text]").val()
var hideTag = info.hidetag
var showTag = info.showtag
var nowTag = $("textarea[name=text]").val().match(/(#[^\s#]+)/)
var sendvisi = info.memo_lock || ''
if(nowTag){
if(nowTag[1] == showTag){
sendvisi = 'PUBLIC'
}else if(nowTag[1] == hideTag){
sendvisi = 'PRIVATE'
}
}
$.ajax({
url:info.apiUrl+'api/v1/memos',
type:"POST",
data:JSON.stringify({
'content': content,
'visibility': sendvisi
}),
contentType:"application/json",
dataType:"json",
headers : {'Authorization':'Bearer ' + info.apiTokens},
success: function(data){
if(info.resourceIdList.length > 0 ){
//匹配图片
window.MemosApi.patchMemoWithAttachmentsOrResources(
info,
data.name,
info.resourceIdList,
function () {
getOne(data.name)
},
function () {
getOne(data.name)
}
)
}else{
getOne(data.name)
}
chrome.storage.sync.set(
{ open_action: '', open_content: '',resourceIdList:[]},
function () {
$.message({
message: msg('memoSuccess')
})
//$("#content_submit_text").removeAttr('disabled');
$("textarea[name=text]").val('')
relistNow = []
renderUploadList(relistNow)
}
)
},error:function(err){//清空open_action(打开时候进行的操作),同时清空open_content
chrome.storage.sync.set(
{ open_action: '', open_content: '',resourceIdList:[] },
function () {
$.message({
message: msg('memoFailed')
})
}
)},
})
} else {
$.message({
message: msg('placeApiUrl')
})
}
})
}