add scripts
This commit is contained in:
411
scripts/excelJS_helper.js
Normal file
411
scripts/excelJS_helper.js
Normal file
@@ -0,0 +1,411 @@
|
||||
/**
|
||||
* 需要 ExcelJS 套件
|
||||
* 提供一些 function,可以把呼叫 ExcelJS 的方法,把 html 的 table 轉成 excel
|
||||
*/
|
||||
|
||||
// let namespace = window.exhelper;
|
||||
|
||||
(function (ns) {
|
||||
'use strict';
|
||||
|
||||
// create a self-reference
|
||||
var _self = ns;
|
||||
|
||||
/**
|
||||
* 以 0 為起始的行、列座標
|
||||
* @param {Number} col 行座標
|
||||
* @param {Number} row 列座標
|
||||
*/
|
||||
_self.CellCoordinate = function (col, row) {
|
||||
this.col = col || 0;
|
||||
this.row = row || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 每格的資料
|
||||
* @param {String} addr 位址 (A1, A2...)
|
||||
* @param {Any} val 值
|
||||
* @param {Object} style 格式
|
||||
* @param {Number} type 型別 (預設 3 string)
|
||||
*/
|
||||
_self.CellData = function(addr, val, style, type){
|
||||
this.address = addr || "";
|
||||
this.value = val || "";
|
||||
this.style = style || {};
|
||||
this.type = type || 3;
|
||||
}
|
||||
|
||||
/**
|
||||
* 合併欄位的資料
|
||||
* @param {Number} top
|
||||
* @param {Number} left
|
||||
* @param {Number} bottom
|
||||
* @param {Number} right
|
||||
*/
|
||||
_self.MergedRange = function(top, left, bottom, right){
|
||||
this.top = top || 0;
|
||||
this.left = left || 0;
|
||||
this.bottom = bottom || 0;
|
||||
this.right = right || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 傳入 CellCoordinate { col: 0, row: 0 } 回傳 A1
|
||||
* @param {CellCoordinate} coordinate
|
||||
* @return {String} 格位標記
|
||||
*/
|
||||
_self.parseCelltoTag = function (coordinate) {
|
||||
if (parseInt(coordinate.col) < 0) {
|
||||
console.log("傳入參數有誤,Coordinate 的 col 要大於 0");
|
||||
return;
|
||||
}
|
||||
|
||||
return _self.getAlphabetByInt(parseInt(coordinate.col)) + (parseInt(coordinate.row) + 1);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 傳入數字,回傳對應的字母 ( 0=>A, 1=>B...)
|
||||
* @param {Number} idx 要對應的數字
|
||||
* @param {Number} alphabetBase 要用幾個字母去對應,預設 26,最大 26
|
||||
*/
|
||||
_self.getAlphabetByInt = function (idx, alphabetBase) {
|
||||
|
||||
if (!alphabetBase)
|
||||
alphabetBase = 26;
|
||||
|
||||
let alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
// 在 base 內,一個字母就可以處理
|
||||
if (idx < alphabetBase) {
|
||||
return alphabets.charAt(idx);
|
||||
}
|
||||
|
||||
let result = "";
|
||||
|
||||
let quotient = idx;
|
||||
|
||||
while (quotient >= alphabetBase) {
|
||||
|
||||
let mod = quotient % alphabetBase;
|
||||
|
||||
quotient = Math.floor(idx / alphabetBase);
|
||||
|
||||
result = alphabets.charAt(mod) + result;
|
||||
|
||||
}
|
||||
|
||||
// 最後一碼
|
||||
result = alphabets.charAt(quotient - 1) + result;
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 傳入字母,回傳對應的數值 ( A=>0, B=>2...)
|
||||
* @param {String} a 要對應的字串
|
||||
* @param {Number} alphabetBase 要用幾個字母去對應,預設 26,最大 26
|
||||
*/
|
||||
_self.getIdxByAlphbet = function (a, alphabetBase) {
|
||||
if (!alphabetBase)
|
||||
alphabetBase = 26;
|
||||
|
||||
let alphabets = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
||||
|
||||
// 全部轉大寫
|
||||
a = a.toUpperCase();
|
||||
|
||||
let result = 0;
|
||||
|
||||
for (let i = 0; i < a.length; i++) {
|
||||
// 如果是第二碼以上,就要加 1 再去乘
|
||||
let modifier = (i == 0) ? 0 : 1;
|
||||
result += (alphabets.indexOf(a.charAt(a.length - (i + 1))) + modifier) * Math.pow(alphabetBase, i);
|
||||
}
|
||||
|
||||
return result;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 傳入格位代碼,回傳以 0 起始的座標物件
|
||||
* @param {String} tag 格位代碼 (A1, A2...)
|
||||
* @return {CellCoordinate} { col: 0, row: 0}
|
||||
*/
|
||||
_self.parseCelltoCoordinate = function (tag) {
|
||||
|
||||
let re = /(\w+)(\d+)/;
|
||||
let match = tag.match(re);
|
||||
|
||||
return new _self.CellCoordinate(_self.getIdxByAlphbet(match[1]), parseInt(match[2]) - 1);
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 儲存 Blob 資料至下載檔案
|
||||
* @param {String} fileName 檔案名稱(含副檔名)
|
||||
* @param {object} byte 檔案內容 byte 陣列
|
||||
*/
|
||||
_self.saveBlob = function (fileName, byte) {
|
||||
var blob = new Blob([byte], {
|
||||
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
});
|
||||
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
|
||||
// for IE
|
||||
window.navigator.msSaveOrOpenBlob(blob, fileName);
|
||||
} else {
|
||||
// for other browsers
|
||||
var url = window.URL.createObjectURL(blob, {
|
||||
type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
});
|
||||
/*
|
||||
var a = $("<a style='display: none;'/>");
|
||||
a.attr("href", url);
|
||||
a.attr("download", fileName);
|
||||
$("body").append(a);
|
||||
a[0].click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
a.remove();
|
||||
*/
|
||||
|
||||
var a = document.createElement("a");
|
||||
a.style.display = "none";
|
||||
a.setAttribute("href", url);
|
||||
a.setAttribute("download", fileName);
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
window.URL.revokeObjectURL(url);
|
||||
a.remove();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 將 ExcelJS.Workbook 物件存成 excel 檔案,並開始下載
|
||||
* @param {String} filename 檔案名稱含副檔名
|
||||
* @param {object} Workbook 物件
|
||||
*/
|
||||
_self.saveXlsx = function (filename, wb) {
|
||||
wb.xlsx.writeBuffer().then(
|
||||
function (result) {
|
||||
_self.saveBlob(filename, result);
|
||||
},
|
||||
function (err) {
|
||||
console.log("error: ", err);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 傳入 table 物件,回傳 ExcelJS.Workbook 物件
|
||||
* @param {object} elt table 物件
|
||||
* @param {object} opt 屬性設定 => { sheet: "sheet 名稱 預設 Sheet1" }
|
||||
* @return {object} ExcelJS.Workbook 物件
|
||||
*/
|
||||
_self.tableToBook = function (elt, opt) {
|
||||
|
||||
if (!opt)
|
||||
opt = {};
|
||||
|
||||
// 沒有這個方法 => 可能是 jquery 物件,要轉成原始的 html 物件
|
||||
if (!elt.getElementsByTagName)
|
||||
elt = elt.get(0);
|
||||
|
||||
var wb = new ExcelJS.Workbook();
|
||||
|
||||
wb.creator = "gamapay";
|
||||
wb.lastModifiedBy = "gamapay";
|
||||
wb.created = new Date();
|
||||
wb.modified = new Date();
|
||||
|
||||
let sheetName = opt.sheet || "Sheet1";
|
||||
|
||||
// Set workbook dates to 1904 date system
|
||||
wb.properties.date1904 = true;
|
||||
|
||||
var ws = wb.addWorksheet(sheetName);
|
||||
|
||||
var rows = elt.getElementsByTagName("tr");
|
||||
|
||||
var mergedCells = new Array(rows.length);
|
||||
|
||||
for (let i = 0; i < rows.length; i++) {
|
||||
// 取得格位資料
|
||||
var cols = rows[i].querySelectorAll("th,td");
|
||||
|
||||
// 計算要右移幾格 (因為合併)
|
||||
let shiftCell = 0;
|
||||
|
||||
for (let j = 0; j < cols.length; j++) {
|
||||
let colElem = cols[j];
|
||||
let colspan = colElem.getAttribute("colspan");
|
||||
let rowspan = colElem.getAttribute("rowspan");
|
||||
|
||||
let colValue = colElem.innerHTML;
|
||||
// 如果有值,就進行移除所有的 html tag 運算
|
||||
if (colValue) {
|
||||
colValue = colValue.replace(/<\/?[^>]+(>|$)/g, "");
|
||||
}
|
||||
|
||||
// 初始化本列的合併格位陣列 (如果是合併列的話,可能已經有初始化了)
|
||||
if (!mergedCells[i])
|
||||
mergedCells[i] = [];
|
||||
|
||||
// 檢查目前的格位有沒有在合併欄位中,有的話就右移一格
|
||||
while (mergedCells[i].indexOf(j + shiftCell) >= 0) {
|
||||
shiftCell++;
|
||||
}
|
||||
|
||||
// 目前的格位 (位移後)
|
||||
let currCell = new _self.CellCoordinate(j + shiftCell, i);
|
||||
|
||||
// 轉成 tag
|
||||
let currTag = _self.parseCelltoTag(currCell);
|
||||
|
||||
// 設定本格的值
|
||||
ws.getCell(currTag).value = colValue;
|
||||
|
||||
// 是否有合併欄位
|
||||
let hasMerge = false;
|
||||
|
||||
// 要合併欄位
|
||||
let toCell = new _self.CellCoordinate(j + shiftCell, i);
|
||||
|
||||
if (colspan && colspan != 1) {
|
||||
hasMerge = true;
|
||||
toCell.col += parseInt(colspan) - 1;
|
||||
}
|
||||
|
||||
if (rowspan && rowspan != 1) {
|
||||
hasMerge = true;
|
||||
toCell.row += parseInt(rowspan) - 1;
|
||||
}
|
||||
|
||||
|
||||
if (hasMerge) {
|
||||
// 把合併的欄位加到陣列中
|
||||
for (let idr = currCell.row; idr <= toCell.row; idr++) {
|
||||
// 如果是列之間的合併格位,會遇到還沒有初始化,所以在這要初始化
|
||||
if (!mergedCells[idr])
|
||||
mergedCells[idr] = [];
|
||||
for (let idx = currCell.col; idx <= toCell.col; idx++) {
|
||||
// 將合併的欄位加到陣列中
|
||||
mergedCells[idr].push(idx);
|
||||
}
|
||||
}
|
||||
|
||||
// 將要合併的欄位轉成 tag
|
||||
let toTag = _self.parseCelltoTag(toCell);
|
||||
// 進行合併
|
||||
ws.mergeCells(currTag + ":" + toTag);
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return wb;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在指定位置插入指定行數的空行
|
||||
* @param {Object} sheet Worksheet object
|
||||
* @param {Number} pos 要插入的位置
|
||||
* @param {Number} cnt 要插入幾行
|
||||
*/
|
||||
_self.insertRows = function (sheet, pos, cnt){
|
||||
|
||||
// 建立要合併的欄位
|
||||
var merged = [];
|
||||
|
||||
// 每個合併的欄位向下一行
|
||||
for(let cell in sheet._merges){
|
||||
let model = sheet._merges[cell].model;
|
||||
|
||||
let range = new _self.MergedRange(model.top, model.left, model.bottom, model.right);
|
||||
|
||||
merged.push(range);
|
||||
|
||||
// 清除 merge 資訊
|
||||
sheet.unMergeCells(cell);
|
||||
}
|
||||
|
||||
|
||||
// 紀錄所有格位資料
|
||||
let cells = [];
|
||||
sheet.eachRow(function(row, rowNumber) {
|
||||
row.eachCell(function(cell, colNumber){
|
||||
let model = cell._value.model;
|
||||
let cellData = new _self.CellData(model.address, model.value, model. style, model.type);
|
||||
cells.push(cellData);
|
||||
});
|
||||
});
|
||||
|
||||
// 清空所有資料
|
||||
sheet._rows = [];
|
||||
sheet._columns = [];
|
||||
|
||||
for(let i = 0; i < cells.length; i++){
|
||||
let cell = cells[i];
|
||||
|
||||
let cellCoordinate = _self.parseCelltoCoordinate(cell.address);
|
||||
|
||||
// col 原則上不會變
|
||||
let newCol = cellCoordinate.col + 1;
|
||||
let newRow = cellCoordinate.row + 1;
|
||||
|
||||
console.log(cell.value, newRow, pos);
|
||||
// row 依插入幾行而變
|
||||
if(newRow >= pos){
|
||||
newRow = newRow + cnt;
|
||||
}
|
||||
|
||||
// 將原本的值寫入
|
||||
sheet.getRow(newRow).getCell(newCol).value = cell.value;
|
||||
|
||||
}
|
||||
|
||||
// 重新 merge
|
||||
for(let i = 0; i < merged.length; i++){
|
||||
let range = merged[i];
|
||||
|
||||
// 如果插入的行在merge行的中間,那就不進行merge
|
||||
if(range.top > pos && range.bottom <= pos)
|
||||
continue;
|
||||
|
||||
// 原本合併的行在插入行之下,下移指定行數
|
||||
// ,在插入行之上,維持不變
|
||||
if(range.top >= pos){
|
||||
range.top += cnt;
|
||||
range.bottom += cnt;
|
||||
}
|
||||
|
||||
// 進行合併
|
||||
sheet.mergeCells(range.top, range.left, range.bottom, range.right);
|
||||
}
|
||||
}
|
||||
/**
|
||||
* 為 worksheet 物件增加表頭
|
||||
* @param {object} sheet ExcelJS.Worksheet 物件
|
||||
* @param {String} title 表頭
|
||||
*/
|
||||
_self.addTitle = function (sheet, title) {
|
||||
|
||||
_self.insertRows(sheet, 1, 1);
|
||||
|
||||
// 插入表頭
|
||||
sheet.mergeCells(1, 1, 1, sheet.columnCount);
|
||||
let titleCell = sheet.getRow(1).getCell(1);
|
||||
titleCell.value = title;
|
||||
titleCell.alignment = { vertical: 'middle', horizontal: 'center' };
|
||||
titleCell.font = { bold: true };
|
||||
}
|
||||
|
||||
|
||||
// reasign everything just incase
|
||||
_self = ns;
|
||||
|
||||
|
||||
})(window.exhelper = window.exhelper || {});
|
||||
2
scripts/jquery-3.5.1.min.js
vendored
Normal file
2
scripts/jquery-3.5.1.min.js
vendored
Normal file
File diff suppressed because one or more lines are too long
10872
scripts/jquery.js
vendored
Normal file
10872
scripts/jquery.js
vendored
Normal file
File diff suppressed because it is too large
Load Diff
14
scripts/myjs.js
Normal file
14
scripts/myjs.js
Normal file
@@ -0,0 +1,14 @@
|
||||
requirejs([
|
||||
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.promise.min.js",
|
||||
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.string.includes.min.js",
|
||||
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.object.assign.min.js",
|
||||
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.object.keys.min.js",
|
||||
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.symbol.min.js",
|
||||
"https://cdn.jsdelivr.net/npm/core-js@3.6.5/modules/es.symbol.async-iterator.min.js",
|
||||
"https://cdn.jsdelivr.net/npm/regenerator-runtime@0.13.7/runtime.min.js",
|
||||
"https://cdnjs.cloudflare.com/ajax/libs/exceljs/4.1.1/exceljs.js"
|
||||
], function(es1, es2, es3, es4, es5, es6, es7, exceljs){
|
||||
$(function(){
|
||||
console.log("test");
|
||||
});
|
||||
})
|
||||
7087
scripts/polyfill.js
Normal file
7087
scripts/polyfill.js
Normal file
File diff suppressed because it is too large
Load Diff
2145
scripts/require.js
Normal file
2145
scripts/require.js
Normal file
File diff suppressed because it is too large
Load Diff
397
scripts/rewrite-pattern.js
Normal file
397
scripts/rewrite-pattern.js
Normal file
@@ -0,0 +1,397 @@
|
||||
'use strict';
|
||||
|
||||
function _createForOfIteratorHelper(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; var F = function F() {}; return { s: F, n: function n() { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }, e: function e(_e) { throw _e; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var normalCompletion = true, didErr = false, err; return { s: function s() { it = o[Symbol.iterator](); }, n: function n() { var step = it.next(); normalCompletion = step.done; return step; }, e: function e(_e2) { didErr = true; err = _e2; }, f: function f() { try { if (!normalCompletion && it.return != null) it.return(); } finally { if (didErr) throw err; } } }; }
|
||||
|
||||
function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }
|
||||
|
||||
function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }
|
||||
|
||||
var generate = require('regjsgen').generate;
|
||||
|
||||
var parse = require('regjsparser').parse;
|
||||
|
||||
var regenerate = require('regenerate');
|
||||
|
||||
var unicodeMatchProperty = require('unicode-match-property-ecmascript');
|
||||
|
||||
var unicodeMatchPropertyValue = require('unicode-match-property-value-ecmascript');
|
||||
|
||||
var iuMappings = require('./data/iu-mappings.js');
|
||||
|
||||
var ESCAPE_SETS = require('./data/character-class-escape-sets.js'); // Prepare a Regenerate set containing all code points, used for negative
|
||||
// character classes (if any).
|
||||
|
||||
|
||||
var UNICODE_SET = regenerate().addRange(0x0, 0x10FFFF); // Without the `u` flag, the range stops at 0xFFFF.
|
||||
// https://mths.be/es6#sec-pattern-semantics
|
||||
|
||||
var BMP_SET = regenerate().addRange(0x0, 0xFFFF); // Prepare a Regenerate set containing all code points that are supposed to be
|
||||
// matched by `/./u`. https://mths.be/es6#sec-atom
|
||||
|
||||
var DOT_SET_UNICODE = UNICODE_SET.clone() // all Unicode code points
|
||||
.remove( // minus `LineTerminator`s (https://mths.be/es6#sec-line-terminators):
|
||||
0x000A, // Line Feed <LF>
|
||||
0x000D, // Carriage Return <CR>
|
||||
0x2028, // Line Separator <LS>
|
||||
0x2029 // Paragraph Separator <PS>
|
||||
);
|
||||
|
||||
var getCharacterClassEscapeSet = function getCharacterClassEscapeSet(character, unicode, ignoreCase) {
|
||||
if (unicode) {
|
||||
if (ignoreCase) {
|
||||
return ESCAPE_SETS.UNICODE_IGNORE_CASE.get(character);
|
||||
}
|
||||
|
||||
return ESCAPE_SETS.UNICODE.get(character);
|
||||
}
|
||||
|
||||
return ESCAPE_SETS.REGULAR.get(character);
|
||||
};
|
||||
|
||||
var getUnicodeDotSet = function getUnicodeDotSet(dotAll) {
|
||||
return dotAll ? UNICODE_SET : DOT_SET_UNICODE;
|
||||
};
|
||||
|
||||
var getUnicodePropertyValueSet = function getUnicodePropertyValueSet(property, value) {
|
||||
var path = value ? "".concat(property, "/").concat(value) : "Binary_Property/".concat(property);
|
||||
|
||||
try {
|
||||
return require("regenerate-unicode-properties/".concat(path, ".js"));
|
||||
} catch (exception) {
|
||||
throw new Error("Failed to recognize value `".concat(value, "` for property ") + "`".concat(property, "`."));
|
||||
}
|
||||
};
|
||||
|
||||
var handleLoneUnicodePropertyNameOrValue = function handleLoneUnicodePropertyNameOrValue(value) {
|
||||
// It could be a `General_Category` value or a binary property.
|
||||
// Note: `unicodeMatchPropertyValue` throws on invalid values.
|
||||
try {
|
||||
var _property = 'General_Category';
|
||||
var category = unicodeMatchPropertyValue(_property, value);
|
||||
return getUnicodePropertyValueSet(_property, category);
|
||||
} catch (exception) {} // It’s not a `General_Category` value, so check if it’s a binary
|
||||
// property. Note: `unicodeMatchProperty` throws on invalid properties.
|
||||
|
||||
|
||||
var property = unicodeMatchProperty(value);
|
||||
return getUnicodePropertyValueSet(property);
|
||||
};
|
||||
|
||||
var getUnicodePropertyEscapeSet = function getUnicodePropertyEscapeSet(value, isNegative) {
|
||||
var parts = value.split('=');
|
||||
var firstPart = parts[0];
|
||||
var set;
|
||||
|
||||
if (parts.length == 1) {
|
||||
set = handleLoneUnicodePropertyNameOrValue(firstPart);
|
||||
} else {
|
||||
// The pattern consists of two parts, i.e. `Property=Value`.
|
||||
var property = unicodeMatchProperty(firstPart);
|
||||
|
||||
var _value = unicodeMatchPropertyValue(property, parts[1]);
|
||||
|
||||
set = getUnicodePropertyValueSet(property, _value);
|
||||
}
|
||||
|
||||
if (isNegative) {
|
||||
return UNICODE_SET.clone().remove(set);
|
||||
}
|
||||
|
||||
return set.clone();
|
||||
}; // Given a range of code points, add any case-folded code points in that range
|
||||
// to a set.
|
||||
|
||||
|
||||
regenerate.prototype.iuAddRange = function (min, max) {
|
||||
var $this = this;
|
||||
|
||||
do {
|
||||
var folded = caseFold(min);
|
||||
|
||||
if (folded) {
|
||||
$this.add(folded);
|
||||
}
|
||||
} while (++min <= max);
|
||||
|
||||
return $this;
|
||||
};
|
||||
|
||||
var update = function update(item, pattern) {
|
||||
var tree = parse(pattern, config.useUnicodeFlag ? 'u' : '');
|
||||
|
||||
switch (tree.type) {
|
||||
case 'characterClass':
|
||||
case 'group':
|
||||
case 'value':
|
||||
// No wrapping needed.
|
||||
break;
|
||||
|
||||
default:
|
||||
// Wrap the pattern in a non-capturing group.
|
||||
tree = wrap(tree, pattern);
|
||||
}
|
||||
|
||||
Object.assign(item, tree);
|
||||
};
|
||||
|
||||
var wrap = function wrap(tree, pattern) {
|
||||
// Wrap the pattern in a non-capturing group.
|
||||
return {
|
||||
'type': 'group',
|
||||
'behavior': 'ignore',
|
||||
'body': [tree],
|
||||
'raw': "(?:".concat(pattern, ")")
|
||||
};
|
||||
};
|
||||
|
||||
var caseFold = function caseFold(codePoint) {
|
||||
return iuMappings.get(codePoint) || false;
|
||||
};
|
||||
|
||||
var processCharacterClass = function processCharacterClass(characterClassItem, regenerateOptions) {
|
||||
var set = regenerate();
|
||||
|
||||
var _iterator = _createForOfIteratorHelper(characterClassItem.body),
|
||||
_step;
|
||||
|
||||
try {
|
||||
for (_iterator.s(); !(_step = _iterator.n()).done;) {
|
||||
var item = _step.value;
|
||||
|
||||
switch (item.type) {
|
||||
case 'value':
|
||||
set.add(item.codePoint);
|
||||
|
||||
if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) {
|
||||
var folded = caseFold(item.codePoint);
|
||||
|
||||
if (folded) {
|
||||
set.add(folded);
|
||||
}
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'characterClassRange':
|
||||
var min = item.min.codePoint;
|
||||
var max = item.max.codePoint;
|
||||
set.addRange(min, max);
|
||||
|
||||
if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) {
|
||||
set.iuAddRange(min, max);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'characterClassEscape':
|
||||
set.add(getCharacterClassEscapeSet(item.value, config.unicode, config.ignoreCase));
|
||||
break;
|
||||
|
||||
case 'unicodePropertyEscape':
|
||||
set.add(getUnicodePropertyEscapeSet(item.value, item.negative));
|
||||
break;
|
||||
// The `default` clause is only here as a safeguard; it should never be
|
||||
// reached. Code coverage tools should ignore it.
|
||||
|
||||
/* istanbul ignore next */
|
||||
|
||||
default:
|
||||
throw new Error("Unknown term type: ".concat(item.type));
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
_iterator.e(err);
|
||||
} finally {
|
||||
_iterator.f();
|
||||
}
|
||||
|
||||
if (characterClassItem.negative) {
|
||||
update(characterClassItem, "(?!".concat(set.toString(regenerateOptions), ")[\\s\\S]"));
|
||||
} else {
|
||||
update(characterClassItem, set.toString(regenerateOptions));
|
||||
}
|
||||
|
||||
return characterClassItem;
|
||||
};
|
||||
|
||||
var updateNamedReference = function updateNamedReference(item, index) {
|
||||
delete item.name;
|
||||
item.matchIndex = index;
|
||||
};
|
||||
|
||||
var assertNoUnmatchedReferences = function assertNoUnmatchedReferences(groups) {
|
||||
var unmatchedReferencesNames = Object.keys(groups.unmatchedReferences);
|
||||
|
||||
if (unmatchedReferencesNames.length > 0) {
|
||||
throw new Error("Unknown group names: ".concat(unmatchedReferencesNames));
|
||||
}
|
||||
};
|
||||
|
||||
var processTerm = function processTerm(item, regenerateOptions, groups) {
|
||||
switch (item.type) {
|
||||
case 'dot':
|
||||
if (config.useDotAllFlag) {
|
||||
break;
|
||||
} else if (config.unicode) {
|
||||
update(item, getUnicodeDotSet(config.dotAll).toString(regenerateOptions));
|
||||
} else if (config.dotAll) {
|
||||
// TODO: consider changing this at the regenerate level.
|
||||
update(item, '[\\s\\S]');
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'characterClass':
|
||||
item = processCharacterClass(item, regenerateOptions);
|
||||
break;
|
||||
|
||||
case 'unicodePropertyEscape':
|
||||
if (config.unicodePropertyEscape) {
|
||||
update(item, getUnicodePropertyEscapeSet(item.value, item.negative).toString(regenerateOptions));
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'characterClassEscape':
|
||||
update(item, getCharacterClassEscapeSet(item.value, config.unicode, config.ignoreCase).toString(regenerateOptions));
|
||||
break;
|
||||
|
||||
case 'group':
|
||||
if (item.behavior == 'normal') {
|
||||
groups.lastIndex++;
|
||||
}
|
||||
|
||||
if (item.name && config.namedGroup) {
|
||||
var name = item.name.value;
|
||||
|
||||
if (groups.names[name]) {
|
||||
throw new Error("Multiple groups with the same name (".concat(name, ") are not allowed."));
|
||||
}
|
||||
|
||||
var index = groups.lastIndex;
|
||||
delete item.name;
|
||||
groups.names[name] = index;
|
||||
|
||||
if (groups.onNamedGroup) {
|
||||
groups.onNamedGroup.call(null, name, index);
|
||||
}
|
||||
|
||||
if (groups.unmatchedReferences[name]) {
|
||||
groups.unmatchedReferences[name].forEach(function (reference) {
|
||||
updateNamedReference(reference, index);
|
||||
});
|
||||
delete groups.unmatchedReferences[name];
|
||||
}
|
||||
}
|
||||
|
||||
/* falls through */
|
||||
|
||||
case 'alternative':
|
||||
case 'disjunction':
|
||||
case 'quantifier':
|
||||
item.body = item.body.map(function (term) {
|
||||
return processTerm(term, regenerateOptions, groups);
|
||||
});
|
||||
break;
|
||||
|
||||
case 'value':
|
||||
var codePoint = item.codePoint;
|
||||
var set = regenerate(codePoint);
|
||||
|
||||
if (config.ignoreCase && config.unicode && !config.useUnicodeFlag) {
|
||||
var folded = caseFold(codePoint);
|
||||
|
||||
if (folded) {
|
||||
set.add(folded);
|
||||
}
|
||||
}
|
||||
|
||||
update(item, set.toString(regenerateOptions));
|
||||
break;
|
||||
|
||||
case 'reference':
|
||||
if (item.name) {
|
||||
var _name = item.name.value;
|
||||
var _index = groups.names[_name];
|
||||
|
||||
if (_index) {
|
||||
updateNamedReference(item, _index);
|
||||
break;
|
||||
}
|
||||
|
||||
if (!groups.unmatchedReferences[_name]) {
|
||||
groups.unmatchedReferences[_name] = [];
|
||||
} // Keep track of references used before the corresponding group.
|
||||
|
||||
|
||||
groups.unmatchedReferences[_name].push(item);
|
||||
}
|
||||
|
||||
break;
|
||||
|
||||
case 'anchor':
|
||||
case 'empty':
|
||||
case 'group':
|
||||
// Nothing to do here.
|
||||
break;
|
||||
// The `default` clause is only here as a safeguard; it should never be
|
||||
// reached. Code coverage tools should ignore it.
|
||||
|
||||
/* istanbul ignore next */
|
||||
|
||||
default:
|
||||
throw new Error("Unknown term type: ".concat(item.type));
|
||||
}
|
||||
|
||||
return item;
|
||||
};
|
||||
|
||||
var config = {
|
||||
'ignoreCase': false,
|
||||
'unicode': false,
|
||||
'dotAll': false,
|
||||
'useDotAllFlag': false,
|
||||
'useUnicodeFlag': false,
|
||||
'unicodePropertyEscape': false,
|
||||
'namedGroup': false
|
||||
};
|
||||
|
||||
var rewritePattern = function rewritePattern(pattern, flags, options) {
|
||||
config.unicode = flags && flags.includes('u');
|
||||
var regjsparserFeatures = {
|
||||
'unicodePropertyEscape': config.unicode,
|
||||
'namedGroups': true,
|
||||
'lookbehind': options && options.lookbehind
|
||||
};
|
||||
config.ignoreCase = flags && flags.includes('i');
|
||||
var supportDotAllFlag = options && options.dotAllFlag;
|
||||
config.dotAll = supportDotAllFlag && flags && flags.includes('s');
|
||||
config.namedGroup = options && options.namedGroup;
|
||||
config.useDotAllFlag = options && options.useDotAllFlag;
|
||||
config.useUnicodeFlag = options && options.useUnicodeFlag;
|
||||
config.unicodePropertyEscape = options && options.unicodePropertyEscape;
|
||||
|
||||
if (supportDotAllFlag && config.useDotAllFlag) {
|
||||
throw new Error('`useDotAllFlag` and `dotAllFlag` cannot both be true!');
|
||||
}
|
||||
|
||||
var regenerateOptions = {
|
||||
'hasUnicodeFlag': config.useUnicodeFlag,
|
||||
'bmpOnly': !config.unicode
|
||||
};
|
||||
var groups = {
|
||||
'onNamedGroup': options && options.onNamedGroup,
|
||||
'lastIndex': 0,
|
||||
'names': Object.create(null),
|
||||
// { [name]: index }
|
||||
'unmatchedReferences': Object.create(null) // { [name]: Array<reference> }
|
||||
|
||||
};
|
||||
var tree = parse(pattern, flags, regjsparserFeatures); // Note: `processTerm` mutates `tree` and `groups`.
|
||||
|
||||
processTerm(tree, regenerateOptions, groups);
|
||||
assertNoUnmatchedReferences(groups);
|
||||
return generate(tree);
|
||||
};
|
||||
|
||||
module.exports = rewritePattern;
|
||||
Reference in New Issue
Block a user