跳转到内容

MediaWiki:Gadget-CommentsinLocalTime.js

维基百科,自由的百科全书
注意:保存之后,你必须清除浏览器缓存才能看到做出的更改。Google Chrome、Firefox、Microsoft Edge及Safari:按住⇧ Shift键并单击工具栏的“刷新”按钮。参阅Help:绕过浏览器缓存以获取更多帮助。
// 「以本地時區顯示簽名時間」(原版 & ConvenientDiscussions兼容版)
// 更新记录:
// 2009-05-28: Gary King, "User:Gary King/comments in local time.js," Wikipedia, The Free Encyclopedia, http://en.wikipedia.org/w/index.php?title=User:Gary_King/comments_in_local_time.js&oldid=281324481 (accessed May 28, 2009).
// 2026-07-30:Sekidoki(原臺灣杉),修正与ConvenientDiscussions兼容性,参见User:Sekidoki/cd-comments-in-local-time.js
// 2026-08-18:逆襲のあまのじゃく(逆襲的天邪鬼),Gadget化以便部署
// 2026-08-20:逆襲のあまのじゃく(逆襲的天邪鬼),修正讨论最开头“最新留言”未显示“X日前”问题;当CD也设置为显示相对时间时,本小工具停止工作,以免界面重复出现“X日前”

mw.loader.using(['ext.gadget.HanAssist']).then(function (require) {
	'use strict';
	const langConv = require('ext.gadget.HanAssist').conv;

	/* ==========================================================================
	   0. 公共函数
	   ========================================================================== */
	/**
	 * 获取本地偏移小时数
	 */
	function getLocalUtcOffset() {
		var LocalComments = window.LocalComments || {};
		if (typeof LocalComments.utcOffset === 'number') {
			return LocalComments.utcOffset;
		}
		return -1 * new Date().getTimezoneOffset() / 60;
	}
	/**
	 * 计算目标时间与基准时间(默认当前时间)的相对差值
	 * @param {Date} targetDate 目标时间
	 * @param {Date} [baseDate] 基准时间(默认为当前本地时间)
	 * @returns {Object} 包含结构化差值与预设描述文本的对象
	 */
	function calculateDateDifference(targetLocalDate, baseDate) {
		var base = baseDate || new Date();
		var todayZero = new Date(base.getFullYear(), base.getMonth(), base.getDate());
		var targetZero = new Date(targetLocalDate.getFullYear(), targetLocalDate.getMonth(), targetLocalDate.getDate());

		var diffMs = todayZero.getTime() - targetZero.getTime();
		var daysAgo = Math.round(diffMs / 86400000);

		// 判定相对日期
		var relativeDay = '';
		if (daysAgo === 0) {
			relativeDay = '今天';
		} else if (daysAgo === 1) {
			relativeDay = '昨天';
		} else if (daysAgo === -1) {
			relativeDay = '明天';
		}

		var isPast = diffMs >= 0;
		var absDiffMs = Math.abs(diffMs);
		var diffObj = new Date(absDiffMs);

		// 使用 UTC 方法读取 Date(ms) 解析值,避免本地时区偏移干扰
		var diffYears = diffObj.getUTCFullYear() - 1970;
		var diffMonths = diffObj.getUTCMonth();
		var diffDays = diffObj.getUTCDate() - 1;

		var directionWord = isPast ? '前' : langConv({ hans: '后', hant: '後' });

		var parts = [];
		if (diffYears > 0) parts.push(diffYears + '年');
		if (diffMonths > 0) parts.push(diffMonths + langConv({ hans: '个月', hant: '個月' }));
		if (diffDays > 0) parts.push(diffDays + '日');

		var descriptiveDiff = parts.length > 0 ? (parts.join('') + directionWord) : '';
		var descriptiveDiffBracket = descriptiveDiff ? ' (' + descriptiveDiff + ')' : '';

		return {
			daysAgo: daysAgo,
			relativeDay: relativeDay,
			isPast: isPast,
			directionWord: directionWord,
			diffYears: diffYears,
			diffMonths: diffMonths,
			diffDays: diffDays,
			descriptiveDiff: descriptiveDiff,
			descriptiveDiffBracket: descriptiveDiffBracket
		};
	}

	function add_leading_zero(number) {
		return number < 10 ? '0' + number : '' + number;
	}
	
	/* ==========================================================================
	   1. 原CommentsInLocalTime小工具(未开启ConvenientDiscussions)
	   ========================================================================== */
	var CommentsInLocalTime = function() {
		// mw.config.get('wgCanonicalNamespace') = unsafeWindow.mw.config.get('wgCanonicalNamespace')

		/*
		Settings
		 */
		var LocalComments = window.LocalComments || {};

		if (typeof(LocalComments.dateFormat) === 'undefined') {
			// Deprecated: LocalizeConfig
			if (typeof(window.LocalizeConfig) !== 'undefined' && typeof(window.LocalizeConfig.dateFormat) !== 'undefined' && window.LocalizeConfig.dateFormat !== '') {
				LocalComments.dateFormat = window.LocalizeConfig.dateFormat;
			} else {
				LocalComments.dateFormat = 'ymd';
			}
		}

		if (typeof(LocalComments.timeFirst) === 'undefined') LocalComments.timeFirst = false;
		if (typeof(LocalComments.dateDifference) === 'undefined') LocalComments.dateDifference = true;
		if (typeof(LocalComments.twentyFourHours) === 'undefined') LocalComments.twentyFourHours = false;
		if (typeof(LocalComments.dayOfWeek) === 'undefined') LocalComments.dayOfWeek = true;
		if (typeof(LocalComments.utcOffset) !== 'number') LocalComments.utcOffset = getLocalUtcOffset();
		if (typeof(LocalComments.disablePages) !== 'function') {
			LocalComments.disablePages = function() {
				return false;
			};
		}
		/*
		End Settings
		 */

		if (mw.config.get('wgCanonicalNamespace') === '' || mw.config.get('wgCanonicalNamespace') === 'MediaWiki' || mw.config.get('wgCanonicalNamespace') === 'Special' || LocalComments.disablePages()) return;

		var disabled_urls = new Array('action=history'),
			unique_url = false,
			wikiPreview = new Array('action=edit', 'action=submit');
		for (var i = 0; i < disabled_urls.length; i++) {
			if (document.location.href.indexOf(disabled_urls[i]) !== -1) return;
		}
		for (var i = 0; i < wikiPreview.length; i++) {
			if (document.location.href.indexOf(wikiPreview[i]) != -1) unique_url = 'wikiPreview';
		}

		var element_class = unique_url ? unique_url : '.mw-body-content .mw-parser-output[dir]';
		replace_text(document.querySelector(element_class), /(\d{4})年(\d{1,2})月(\d{1,2})日 \([一二三四五六日]\) (\d\d):(\d\d) \(UTC\)/g, adjust_time);

		function adjust_time(original_timestamp, old_year, old_month, old_day, old_hour, old_minute, offset) {
			// set the date entered
			var time = new Date();
			time.setFullYear(old_year, old_month - 1, old_day);
			time.setHours(old_hour);
			time.setMinutes(old_minute);

			// determine the time offset
			var utc_offset = LocalComments.utcOffset;
			if (utc_offset >= 0) {
				utc_offset = '+' + utc_offset;
			} else {
				utc_offset = '−' + Math.abs(utc_offset);
			}
			
			time = new Date( +time + LocalComments.utcOffset * 36e5 );

			// set the date bits to output
			var year = time.getFullYear(),
				month = add_leading_zero(time.getMonth() + 1);
			var day = time.getDate();
			var hour = parseInt(time.getHours()),
				minute = add_leading_zero(time.getMinutes());

			// output am or pm depending on the date and user config settings
			var ampm = '';
			if (!LocalComments.twentyFourHours) {
				ampm = hour <= 11 ? ' am' : ' pm';
				if (hour > 12) {
					hour -= 12;
				} else if (hour === 0) {
					hour = 12;
				}
			}

			var diffInfo = calculateDateDifference(time);

			var date = '';
			if (diffInfo.relativeDay) {
				date = diffInfo.relativeDay;
			} else {
				var day_names = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
				var day_of_the_week = day_names[time.getDay()];
				var descriptive_difference = LocalComments.dateDifference ? diffInfo.descriptiveDiffBracket : '';

				var formatted_date = '',
					month_name = convert_number_to_month(time.getMonth()),
					raw_month = time.getMonth() + 1;

				switch (LocalComments.dateFormat.toLowerCase()) {
				case 'ymd':
					formatted_date = year + '年' + raw_month + '月' + day + '日';
					break;
				case 'ymd0':
					formatted_date = year + '年' + add_leading_zero(raw_month) + '月' + add_leading_zero(day) + '日';
					break;
				case 'dmy':
					formatted_date = day + ' ' + month_name + ' ' + year;
					break;
				case 'mdy':
					formatted_date = month_name + ' ' + day + ', ' + year;
					break;
				default:
					formatted_date = year + '-' + add_leading_zero(raw_month) + '-' + add_leading_zero(day);
				}

				if (LocalComments.dayOfWeek) {
					date = formatted_date + ', ' + day_of_the_week + descriptive_difference;
				} else {
					date = formatted_date + ', ' + descriptive_difference;
				}
			}

			var formatted_time = add_leading_zero(hour) + ':' + minute + ' ' + ampm;
			var return_date;
			if (LocalComments.timeFirst) {
				return_date = formatted_time + ', ' + date + ' (UTC' + utc_offset + ')';
			} else {
				return_date = date + ', ' + formatted_time + ' (UTC' + utc_offset + ')';
			}
			return return_date;
		}

		function convert_month_to_number(month) {
			var output = new Date(month + ' 1, 2001');
			return output.getMonth();
		}

		function convert_number_to_month(number) {
			var month = new Array('一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月');
			return month[number];
		}

		function replace_text(node, search, replace) {
			if (!node) {
				return;
			} else if (node.nodeType == 3) {
				var value = node.nodeValue;
				var matches = value.match(search);

				if (matches != null) {
					var node_parent_node = node.parentNode;
					var old_node = node;
					// old_node_list = node.parentNode.childNodes;

					var new_node = document.createDocumentFragment();

					var after_match = value;

					for (var match = 0; match < matches.length; match++) {
						var position = after_match.search(search);
						var length = matches[match].toString().length;
						var before_match = after_match.substring(0, position);
						after_match = after_match.substring(position + length);

						var first_span = document.createElement('span');
						first_span.setAttribute('style', 'font-size: 85%;');

						var second_span = document.createElement('span');
						second_span.setAttribute('class', 'localcomments');
						second_span.setAttribute('title', matches[match]);
						second_span.appendChild(document.createTextNode(matches[match].toString().replace(search, replace)));

						first_span.appendChild(second_span);

						new_node.appendChild(document.createTextNode(before_match));
						new_node.appendChild(first_span);

						// new_node_list = new_node.childNodes;
						// old_node_list = new_node_list;
					}

					new_node.appendChild(document.createTextNode(after_match));
					node_parent_node.replaceChild(new_node, old_node);
				}
			} else {
				var children = [];
				var child = node.firstChild;
				while (child) {
					children[children.length] = child;
					child = child.nextSibling;
				}

				for (var i = 0; i < children.length; i++)
					replace_text(children[i], search, replace);
			}
		}
	};

	/* ==========================================================================
	   2. ConvenientDiscussions专用处理
	   ========================================================================== */
	function getRelativeDiffText(targetLocalDate) {
		var diffInfo = calculateDateDifference(targetLocalDate);
		if (diffInfo.relativeDay) {
			return '(' + diffInfo.relativeDay + ')';
		}
		return diffInfo.descriptiveDiffBracket;
	}

	function formatToLocalBrowserTime(utcMs, settings) {
		var localOffsetHours = (typeof settings.utcOffset === 'number')
			? settings.utcOffset
			: getLocalUtcOffset();

		// 用真实时间戳换算目标时区的真实时刻
		var localTime = new Date(utcMs + localOffsetHours * 3600000);
		var year = localTime.getUTCFullYear();
		var month = localTime.getUTCMonth() + 1;
		var day = localTime.getUTCDate();
		var hour = localTime.getUTCHours();
		var minute = add_leading_zero(localTime.getUTCMinutes());
		var dayNames = ['星期日', '星期一', '星期二', '星期三', '星期四', '星期五', '星期六'];
		var dayOfWeek = dayNames[localTime.getUTCDay()];

		var ampm = '';
		if (!settings.twentyFourHours) {
			ampm = hour <= 11 ? ' am' : ' pm';
			if (hour > 12) hour -= 12;
			else if (hour === 0) hour = 12;
		}

		var formattedDate = '';
		switch ((settings.dateFormat || 'ymd').toLowerCase()) {
			case 'ymd':
				formattedDate = year + '年' + month + '月' + day + '日';
				break;
			case 'ymd0':
				formattedDate = year + '年' + add_leading_zero(month) + '月' + add_leading_zero(day) + '日';
				break;
			default:
				formattedDate = year + '-' + add_leading_zero(month) + '-' + add_leading_zero(day);
		}

		if (settings.dayOfWeek !== false) {
			formattedDate += ' (' + dayOfWeek.replace('星期', '') + ')';
		}

		var offsetStr = localOffsetHours >= 0 ? '+' + localOffsetHours : '−' + Math.abs(localOffsetHours);
		var timeStr = add_leading_zero(hour) + ':' + minute + ampm;

		return formattedDate + ' ' + timeStr + ' (UTC' + offsetStr + ')';
	}

	function processCDComments() {
		// 如果在CD中选择了“相对时间”,该小工具就不再做重复的事情
		var cdSettings = mw.user.options.get('userjs-convenientDiscussions-settings')
		if (cdSettings) {
			if (JSON.parse(cdSettings).timestampFormat === 'relative') {
				return;
			}
		}
		
		var LocalComments = window.LocalComments || {};
		var timeCorrection = mw.user.options.get('timecorrection');
		var needsTimezoneShift = (timeCorrection === 'System|0');
		var localOffsetHours = (typeof LocalComments.utcOffset === 'number') ? LocalComments.utcOffset : getLocalUtcOffset();
		
		// 移除标题上的时间,以便重新设置
		var oldTitleNodes = document.querySelectorAll('.cd-section-bar > .cd-section-metadata > .cd-section-bar-item:last-child > .cd-localcomments-diff');
		oldTitleNodes.forEach(function (item) {
			item.remove();
		});

		var timestampNodes = document.querySelectorAll('a.cd-comment-timestamp:not(.cd-localcomments-processed),.cd-section-metadata > .cd-section-bar-item:last-child > a.cd-clickHandled');
		timestampNodes.forEach(function (tsLink) {
			tsLink.classList.add('cd-localcomments-processed');

			var rawTitle = tsLink.getAttribute('title') || tsLink.textContent || '';
			var match = rawTitle.match(/(\d{4})年(\d{1,2})月(\d{1,2})日.*?(\d{1,2}):(\d{2})/);
			if (!match) return;

			var year = parseInt(match[1], 10);
			var month = parseInt(match[2], 10) - 1;
			var day = parseInt(match[3], 10);
			var hour = parseInt(match[4], 10);
			var minute = parseInt(match[5], 10);

			var utcMs = Date.UTC(year, month, day, hour, minute);

			// 1. 如果是系统时区 System|0,将链接文本转换为浏览器时区
			if (needsTimezoneShift) {
				tsLink.textContent = formatToLocalBrowserTime(utcMs, LocalComments);
			}

			// 2. 相对时间差(不论是否为系统时区,均提供相对时间展示)
			if (LocalComments.dateDifference !== false) {
				// 获取目标时间在本地时区下的等效时间对象
				var targetLocalDate = new Date(utcMs + localOffsetHours * 3600000);
				var normalizedLocalDate = new Date(
					targetLocalDate.getUTCFullYear(),
					targetLocalDate.getUTCMonth(),
					targetLocalDate.getUTCDate(),
					targetLocalDate.getUTCHours(),
					targetLocalDate.getUTCMinutes()
				);

				var diffText = getRelativeDiffText(normalizedLocalDate);
				if (diffText) {
					var diffSpan = document.createElement('span');
					diffSpan.className = 'cd-localcomments-diff localcomments';
					diffSpan.style.fontSize = '85%';
					diffSpan.style.opacity = '0.85';
					diffSpan.textContent = ' ' + diffText;
					tsLink.parentNode.insertBefore(diffSpan, tsLink.nextSibling);
				}
			}
		});
	}
	
	/* ==========================================================================
	   3. 系统加载
	   ========================================================================== */
	var isCDMode = false;
	window.CommentsinLocalTime = CommentsInLocalTime;
	$(function() {
		if (window.location.href.indexOf('&disable=loco') !== -1) {
			return;
		}
		
		mw.hook('convenientDiscussions.commentsReady').add(function () {
			isCDMode = true;
			processCDComments();
		});
	
		mw.hook('convenientDiscussions.pageReady').add(function () {
			isCDMode = true;
			processCDComments();
		});
		
		// 未启用CD时加载原插件
		mw.hook('wikipage.content').add(function($item) {
			if ($item.attr('id') === 'mw-content-text') {
				setTimeout(function () {
					if (!window.convenientDiscussions && !isCDMode) {
						CommentsInLocalTime();
					}
				}, 100);
			}
		});
	});
});